From afc8e5bee07dbd488b34df9d7d853df89c1a4e15 Mon Sep 17 00:00:00 2001 From: Schuyler Cebulskie Date: Mon, 19 Sep 2016 16:52:46 -0400 Subject: [PATCH] Add message sweeping --- src/client/Client.js | 20 ++++++++++++++++++++ src/util/Constants.js | 6 ++++++ 2 files changed, 26 insertions(+) diff --git a/src/client/Client.js b/src/client/Client.js index bea30e389..2349b9300 100644 --- a/src/client/Client.js +++ b/src/client/Client.js @@ -126,6 +126,10 @@ class Client extends EventEmitter { this._timeouts = new Set(); this._intervals = new Set(); + + if (this.options.message_sweep_interval > 0) { + this.setInterval(this.sweepMessages.bind(this), this.options.message_sweep_interval * 1000); + } } /** @@ -243,6 +247,22 @@ class Client extends EventEmitter { return this.rest.methods.getInvite(code); } + /** + * Sweeps all channels' messages and removes the ones older than the max message lifetime. + * If the message has been edited, the time of the edit is used rather than the time of the original message. + */ + sweepMessages() { + if (this.options.max_message_lifetime <= 0) return; + const now = Date.now(); + const lifetime = this.options.max_message_lifetime * 1000; + for (const channel of this.channels.values()) { + if (!channel.messages) continue; + for (const message of channel.messages.values()) { + if (now - (message._editedTimestamp || message._timestamp) > lifetime) channel.messages.delete(message.id); + } + } + } + setTimeout(fn, ...params) { const timeout = setTimeout(() => { fn(); diff --git a/src/util/Constants.js b/src/util/Constants.js index 9d15cd528..d330dce71 100644 --- a/src/util/Constants.js +++ b/src/util/Constants.js @@ -6,6 +6,10 @@ * @property {number} [shard_id=0] The ID of this shard * @property {number} [shard_count=0] The number of shards * @property {number} [max_message_cache=200] Number of messages to cache per channel + * @property {number} [max_message_lifetime=0] How long until a message should be uncached by the message sweeping + * (in seconds, 0 for forever) + * @property {number} [message_sweep_interval=0] How frequently to remove messages from the cache that are older than + * the max message lifetime (in seconds, 0 for never) * @property {boolean} [fetch_all_members=false] Whether to cache all guild members and users upon startup * @property {boolean} [disable_everyone=false] Default value for MessageOptions.disable_everyone * @property {number} [rest_ws_bridge_timeout=5000] Maximum time permitted between REST responses and their @@ -17,6 +21,8 @@ exports.DefaultOptions = { shard_id: 0, shard_count: 0, max_message_cache: 200, + max_message_lifetime: 0, + message_sweep_interval: 0, fetch_all_members: false, disable_everyone: false, rest_ws_bridge_timeout: 5000,