@mi-gpt/next
Version:
让小爱音箱「听你的」,解锁无限可能。
114 lines (110 loc) • 3.4 kB
JavaScript
'use strict';
var chunk4NFIC7L2_cjs = require('./chunk-4NFIC7L2.cjs');
var crypto = require('crypto');
var utils = require('@mi-gpt/utils');
var _MiMessage = class {
_lastQueryMsg;
_tempQueryMsgs = [];
async fetchNextMessage() {
if (!this._lastQueryMsg) {
return this._fetchFirstMessage();
}
return this._fetchNextMessage();
}
async _fetchFirstMessage() {
const msgs = await this._fetchHistoryMsgs({
limit: 1,
filterAnswer: false
});
this._lastQueryMsg = msgs[0];
return void 0;
}
async _fetchNextMessage() {
if (this._tempQueryMsgs.length > 0) {
return this._fetchNextTempMessage();
}
const nextMsg = await this._fetchNext2Messages();
if (nextMsg !== "continue") {
return nextMsg;
}
return this._fetchNextRemainingMessages();
}
/**
* 拉取最新的 2 条消息,用于和上一条消息比对是否连续
*/
async _fetchNext2Messages() {
const msgs = await this._fetchHistoryMsgs({ limit: 2 });
if (msgs.length < 1 || utils.firstOf(msgs).timestamp <= this._lastQueryMsg.timestamp) {
return;
}
if (utils.firstOf(msgs).timestamp > this._lastQueryMsg.timestamp && (msgs.length === 1 || utils.lastOf(msgs).timestamp <= this._lastQueryMsg.timestamp)) {
this._lastQueryMsg = utils.firstOf(msgs);
return this._lastQueryMsg;
}
for (const msg of msgs) {
if (msg.timestamp > this._lastQueryMsg.timestamp) {
this._tempQueryMsgs.push(msg);
}
}
return "continue";
}
/**
* 继续向上拉取其他新消息
*/
async _fetchNextRemainingMessages(options) {
let currentPage = 0;
const { maxPage = 3, pageSize = 10 } = options ?? {};
while (true) {
currentPage++;
if (currentPage > maxPage) {
return this._fetchNextTempMessage();
}
const nextTimestamp = utils.lastOf(this._tempQueryMsgs).timestamp;
const msgs = await this._fetchHistoryMsgs({
limit: pageSize,
timestamp: nextTimestamp
});
for (const msg of msgs) {
if (msg.timestamp >= nextTimestamp) ; else if (msg.timestamp > this._lastQueryMsg.timestamp) {
this._tempQueryMsgs.push(msg);
} else {
return this._fetchNextTempMessage();
}
}
}
}
/**
* 读取暂存的消息
*/
_fetchNextTempMessage() {
const nextMsg = this._tempQueryMsgs.pop();
this._lastQueryMsg = nextMsg;
return nextMsg;
}
async _fetchHistoryMsgs(options) {
var _a;
const filterAnswer = (options == null ? void 0 : options.filterAnswer) ?? true;
const conversation = await ((_a = chunk4NFIC7L2_cjs.MiService.MiNA) == null ? void 0 : _a.getConversations(options));
let records = (conversation == null ? void 0 : conversation.records) ?? [];
if (filterAnswer) {
records = records.filter(
(e) => {
var _a2;
return ["TTS", "LLM"].includes(((_a2 = e.answers[0]) == null ? void 0 : _a2.type) ?? "") && // 过滤 TTS 和 LLM 消息
e.answers.length === 1;
}
// 播放音乐时会有 TTS、Audio 两个 Answer
);
}
return records.map((e) => {
return {
id: crypto.randomUUID(),
sender: "user",
text: e.query,
timestamp: e.time
};
});
}
};
var MiMessage = new _MiMessage();
exports.MiMessage = MiMessage;