|
| 1 | +import { StateStore } from './store'; |
| 2 | +import type { ChannelResponse, LocalMessage } from './types'; |
| 3 | +import { WithSubscriptions } from './utils/WithSubscriptions'; |
| 4 | +import type { Channel } from './channel'; |
| 5 | + |
| 6 | +export type CooldownTimerState = { |
| 7 | + /** |
| 8 | + * Slow mode cooldown interval in seconds. Change reported via channel.updated WS event. |
| 9 | + */ |
| 10 | + cooldownConfigSeconds: number; |
| 11 | + /** |
| 12 | + * Whether the current user can skip slow mode. Change is not reported via WS. |
| 13 | + */ |
| 14 | + canSkipCooldown: boolean; |
| 15 | + /** |
| 16 | + * Latest message creation date authored by the current user in this channel. Change reported via message.new WS event. |
| 17 | + */ |
| 18 | + ownLatestMessageDate?: Date; |
| 19 | + /** |
| 20 | + * Remaining cooldown in whole seconds (rounded). |
| 21 | + */ |
| 22 | + cooldownRemaining: number; |
| 23 | +}; |
| 24 | + |
| 25 | +const toDateOrUndefined = (value: unknown): Date | undefined => { |
| 26 | + if (value instanceof Date) return value; |
| 27 | + if (typeof value === 'string' || typeof value === 'number') { |
| 28 | + const parsed = new Date(value); |
| 29 | + if (!Number.isNaN(parsed.getTime())) return parsed; |
| 30 | + } |
| 31 | + return undefined; |
| 32 | +}; |
| 33 | + |
| 34 | +export class CooldownTimer extends WithSubscriptions { |
| 35 | + public readonly state: StateStore<CooldownTimerState>; |
| 36 | + private timeout: ReturnType<typeof setTimeout> | null = null; |
| 37 | + private channel: Channel; |
| 38 | + |
| 39 | + constructor({ channel }: { channel: Channel }) { |
| 40 | + super(); |
| 41 | + this.channel = channel; |
| 42 | + this.state = new StateStore<CooldownTimerState>({ |
| 43 | + cooldownConfigSeconds: 0, |
| 44 | + cooldownRemaining: 0, |
| 45 | + ownLatestMessageDate: undefined, |
| 46 | + canSkipCooldown: false, |
| 47 | + }); |
| 48 | + this.refresh(); |
| 49 | + } |
| 50 | + |
| 51 | + get cooldownConfigSeconds() { |
| 52 | + return this.state.getLatestValue().cooldownConfigSeconds; |
| 53 | + } |
| 54 | + |
| 55 | + get cooldownRemaining() { |
| 56 | + return this.state.getLatestValue().cooldownRemaining; |
| 57 | + } |
| 58 | + |
| 59 | + get canSkipCooldown() { |
| 60 | + return this.state.getLatestValue().canSkipCooldown; |
| 61 | + } |
| 62 | + |
| 63 | + get ownLatestMessageDate() { |
| 64 | + return this.state.getLatestValue().ownLatestMessageDate; |
| 65 | + } |
| 66 | + |
| 67 | + public registerSubscriptions = () => { |
| 68 | + this.incrementRefCount(); |
| 69 | + if (this.hasSubscriptions) return; |
| 70 | + |
| 71 | + this.addUnsubscribeFunction( |
| 72 | + this.channel.on('message.new', (event) => { |
| 73 | + const isOwnMessage = |
| 74 | + event.message?.user?.id && event.message.user.id === this.getOwnUserId(); |
| 75 | + if (!isOwnMessage) return; |
| 76 | + this.setOwnLatestMessageDate(toDateOrUndefined(event.message?.created_at)); |
| 77 | + }).unsubscribe, |
| 78 | + ); |
| 79 | + |
| 80 | + this.addUnsubscribeFunction( |
| 81 | + this.channel.on('channel.updated', (event) => { |
| 82 | + const cooldownChanged = event.channel?.cooldown !== this.cooldownConfigSeconds; |
| 83 | + if (!cooldownChanged) return; |
| 84 | + this.refresh(); |
| 85 | + }).unsubscribe, |
| 86 | + ); |
| 87 | + }; |
| 88 | + |
| 89 | + public setCooldownRemaining = (cooldownRemaining: number) => { |
| 90 | + this.state.partialNext({ cooldownRemaining }); |
| 91 | + }; |
| 92 | + |
| 93 | + public clearTimeout = () => { |
| 94 | + if (!this.timeout) return; |
| 95 | + clearTimeout(this.timeout); |
| 96 | + this.timeout = null; |
| 97 | + }; |
| 98 | + |
| 99 | + public refresh = () => { |
| 100 | + const { cooldown: cooldownConfigSeconds = 0, own_capabilities } = (this.channel |
| 101 | + .data ?? {}) as Partial<ChannelResponse>; |
| 102 | + const canSkipCooldown = (own_capabilities ?? []).includes('skip-slow-mode'); |
| 103 | + |
| 104 | + const ownLatestMessageDate = this.findOwnLatestMessageDate({ |
| 105 | + messages: this.channel.state.latestMessages, |
| 106 | + }); |
| 107 | + |
| 108 | + if ( |
| 109 | + cooldownConfigSeconds !== this.cooldownConfigSeconds || |
| 110 | + ownLatestMessageDate?.getTime() !== this.ownLatestMessageDate?.getTime() || |
| 111 | + canSkipCooldown !== this.canSkipCooldown |
| 112 | + ) { |
| 113 | + this.state.partialNext({ |
| 114 | + cooldownConfigSeconds, |
| 115 | + ownLatestMessageDate, |
| 116 | + canSkipCooldown, |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + if (this.canSkipCooldown || this.cooldownConfigSeconds === 0) { |
| 121 | + this.clearTimeout(); |
| 122 | + if (this.cooldownRemaining !== 0) { |
| 123 | + this.setCooldownRemaining(0); |
| 124 | + } |
| 125 | + return; |
| 126 | + } |
| 127 | + |
| 128 | + this.recalculate(); |
| 129 | + }; |
| 130 | + |
| 131 | + /** |
| 132 | + * Updates the known latest own message date and recomputes remaining time. |
| 133 | + * Prefer calling this when you already know the message date (e.g. from an event). |
| 134 | + */ |
| 135 | + public setOwnLatestMessageDate = (date: Date | undefined) => { |
| 136 | + this.state.partialNext({ ownLatestMessageDate: date }); |
| 137 | + this.recalculate(); |
| 138 | + }; |
| 139 | + |
| 140 | + private getOwnUserId() { |
| 141 | + const client = this.channel.getClient(); |
| 142 | + return client.userID ?? client.user?.id; |
| 143 | + } |
| 144 | + |
| 145 | + private findOwnLatestMessageDate({ |
| 146 | + messages, |
| 147 | + }: { |
| 148 | + messages: LocalMessage[]; |
| 149 | + }): Date | undefined { |
| 150 | + const ownUserId = this.getOwnUserId(); |
| 151 | + if (!ownUserId) return undefined; |
| 152 | + |
| 153 | + let latest: Date | undefined; |
| 154 | + for (let i = messages.length - 1; i >= 0; i -= 1) { |
| 155 | + const message = messages[i]; |
| 156 | + if (message.user?.id !== ownUserId) continue; |
| 157 | + const createdAt = toDateOrUndefined(message.created_at); |
| 158 | + if (!createdAt) continue; |
| 159 | + if (!latest || createdAt.getTime() > latest.getTime()) { |
| 160 | + latest = createdAt; |
| 161 | + } |
| 162 | + if (latest.getTime() > createdAt.getTime()) break; |
| 163 | + } |
| 164 | + return latest; |
| 165 | + } |
| 166 | + |
| 167 | + private recalculate = () => { |
| 168 | + this.clearTimeout(); |
| 169 | + |
| 170 | + const { cooldownConfigSeconds, ownLatestMessageDate, canSkipCooldown } = |
| 171 | + this.state.getLatestValue(); |
| 172 | + |
| 173 | + const timeSinceOwnLastMessage = |
| 174 | + ownLatestMessageDate != null |
| 175 | + ? // prevent negative values |
| 176 | + Math.max(0, (Date.now() - ownLatestMessageDate.getTime()) / 1000) |
| 177 | + : undefined; |
| 178 | + |
| 179 | + const remaining = |
| 180 | + !canSkipCooldown && |
| 181 | + typeof timeSinceOwnLastMessage !== 'undefined' && |
| 182 | + cooldownConfigSeconds > timeSinceOwnLastMessage |
| 183 | + ? Math.round(cooldownConfigSeconds - timeSinceOwnLastMessage) |
| 184 | + : 0; |
| 185 | + |
| 186 | + if (remaining !== this.cooldownRemaining) { |
| 187 | + this.setCooldownRemaining(remaining); |
| 188 | + } |
| 189 | + |
| 190 | + if (remaining <= 0) return; |
| 191 | + |
| 192 | + this.timeout = setTimeout(() => { |
| 193 | + this.recalculate(); |
| 194 | + }, 1000); |
| 195 | + }; |
| 196 | +} |
0 commit comments