From ee5ccf9b2fdabff072c83b71c71da751cd9b690e Mon Sep 17 00:00:00 2001 From: Andrew Ferrazzutti Date: Wed, 16 Jun 2021 02:27:27 -0400 Subject: [PATCH] Attempt to wait for chat messages to appear When opening a chat (like during a sync or in response to a new message notification), the message list loads lazily, so not waiting for all items to load can cause messages to be missed. However, there doesn't seem to be any indicator for when a message list has been fully loaded... As a best effort attempt, simply wait until no new updates to the message list have been seen for a while. --- puppet/src/contentscript.js | 43 +++++++++++++++++++++++++++++++++++++ puppet/src/puppet.js | 3 +++ 2 files changed, 46 insertions(+) diff --git a/puppet/src/contentscript.js b/puppet/src/contentscript.js index 32cfdf7..2276d38 100644 --- a/puppet/src/contentscript.js +++ b/puppet/src/contentscript.js @@ -674,6 +674,49 @@ class MautrixController { return promise } + /** + * Wait for updates to the active chat's message list to settle down. + * Wait an additional bit of time every time an update is observed. + * TODO Look (harder) for an explicit signal of when a chat is fully updated... + * + * @returns Promise + */ + waitForMessageListStability() { + // Increase this if messages get missed on sync / chat change. + // Decrease it if response times are too slow. + const delayMillis = 2000 + + let myResolve + const promise = new Promise(resolve => {myResolve = resolve}) + + let observer + const onTimeout = () => { + console.log("Message list looks stable, continue") + console.debug(`timeoutID = ${timeoutID}`) + observer.disconnect() + myResolve() + } + + let timeoutID + const startTimer = () => { + timeoutID = setTimeout(onTimeout, delayMillis) + } + + observer = new MutationObserver(changes => { + clearTimeout(timeoutID) + console.log("CHANGE to message list detected! Wait a bit longer...") + console.debug(`timeoutID = ${timeoutID}`) + console.debug(changes) + startTimer() + }) + observer.observe( + document.querySelector("#_chat_message_area"), + {childList: true, attributes: true, subtree: true}) + startTimer() + + return promise + } + /** * @param {[MutationRecord]} mutations - The mutation records that occurred * @private diff --git a/puppet/src/puppet.js b/puppet/src/puppet.js index 974c3dd..c7dd429 100644 --- a/puppet/src/puppet.js +++ b/puppet/src/puppet.js @@ -525,6 +525,9 @@ export default class MessagesPuppeteer { this.log("Waiting for detail area") await this.page.waitForSelector("#_chat_detail_area > .mdRGT02Info") + this.log("Waiting for chat to stabilize") + await this.page.evaluate(() => window.__mautrixController.waitForMessageListStability()) + if (hadMsgListObserver) { this.log("Restoring msg list observer") await this.page.evaluate(