Move chat history operations into Client
This commit is contained in:
@@ -39,6 +39,7 @@ export default class Client extends EventTarget {
|
||||
batches = new Map();
|
||||
autoReconnect = true;
|
||||
reconnectTimeoutID = null;
|
||||
pendingHistory = Promise.resolve(null);
|
||||
|
||||
constructor(params) {
|
||||
super();
|
||||
@@ -359,4 +360,55 @@ export default class Client extends EventTarget {
|
||||
this.send(msg);
|
||||
});
|
||||
}
|
||||
|
||||
roundtripChatHistory(params) {
|
||||
// Don't send multiple CHATHISTORY commands in parallel, we can't
|
||||
// properly handle batches and errors.
|
||||
this.pendingHistory = this.pendingHistory.catch(() => {}).then(() => {
|
||||
var msg = {
|
||||
command: "CHATHISTORY",
|
||||
params,
|
||||
};
|
||||
return this.roundtrip(msg, (event) => {
|
||||
var msg = event.detail.message;
|
||||
|
||||
switch (msg.command) {
|
||||
case "BATCH":
|
||||
var enter = msg.params[0].startsWith("+");
|
||||
var name = msg.params[0].slice(1);
|
||||
if (enter) {
|
||||
break;
|
||||
}
|
||||
var batch = this.batches.get(name);
|
||||
if (batch.type == "chathistory") {
|
||||
return batch;
|
||||
}
|
||||
break;
|
||||
case "FAIL":
|
||||
if (msg.params[0] == "CHATHISTORY") {
|
||||
throw msg;
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
});
|
||||
return this.pendingHistory;
|
||||
}
|
||||
|
||||
/* Fetch history in ascending order. */
|
||||
fetchHistoryBetween(target, after, before, limit) {
|
||||
var max = Math.min(limit, CHATHISTORY_PAGE_SIZE);
|
||||
var params = ["AFTER", target, "timestamp=" + after.time, max];
|
||||
return this.roundtripChatHistory(params).then((batch) => {
|
||||
limit -= batch.messages.length;
|
||||
if (limit <= 0) {
|
||||
throw new Error("Cannot fetch all chat history: too many messages");
|
||||
}
|
||||
if (batch.messages.length == max) {
|
||||
// There are still more messages to fetch
|
||||
after.time = batch.messages[batch.messages.length - 1].tags.time;
|
||||
return this.fetchHistoryBetween(target, after, before, limit);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user