2023-12-11 06:15:31 +03:00
|
|
|
import Long from 'long'
|
2024-08-13 04:53:07 +03:00
|
|
|
import type { mtp } from '@mtcute/tl'
|
2024-09-05 22:06:01 +03:00
|
|
|
import { timers } from '@fuman/utils'
|
2024-08-21 11:05:07 +03:00
|
|
|
|
2023-12-11 23:59:08 +03:00
|
|
|
export class ServerSaltManager {
|
2023-12-11 06:15:31 +03:00
|
|
|
private _futureSalts: mtp.RawMt_future_salt[] = []
|
|
|
|
|
2024-08-18 09:31:23 +03:00
|
|
|
currentSalt: Long = Long.ZERO
|
2023-12-11 06:15:31 +03:00
|
|
|
|
|
|
|
isFetching = false
|
|
|
|
|
|
|
|
shouldFetchSalts(): boolean {
|
|
|
|
return !this.isFetching && !this.currentSalt.isZero() && this._futureSalts.length < 2
|
|
|
|
}
|
|
|
|
|
|
|
|
setFutureSalts(salts: mtp.RawMt_future_salt[]): void {
|
|
|
|
this._futureSalts = salts
|
|
|
|
|
2023-12-11 23:59:08 +03:00
|
|
|
const now = Date.now() / 1000
|
|
|
|
|
|
|
|
while (salts.length > 0 && now > salts[0].validSince) {
|
2023-12-11 06:15:31 +03:00
|
|
|
this.currentSalt = salts[0].salt
|
|
|
|
this._futureSalts.shift()
|
|
|
|
}
|
|
|
|
|
2023-12-11 23:59:08 +03:00
|
|
|
if (!this._futureSalts.length) this.currentSalt = Long.ZERO
|
|
|
|
else this._scheduleNext()
|
2023-12-11 06:15:31 +03:00
|
|
|
}
|
|
|
|
|
2024-08-21 11:05:07 +03:00
|
|
|
private _timer?: timers.Timer
|
2023-12-11 06:15:31 +03:00
|
|
|
|
|
|
|
private _scheduleNext(): void {
|
2024-08-21 11:05:07 +03:00
|
|
|
if (this._timer) timers.clearTimeout(this._timer)
|
2023-12-11 06:15:31 +03:00
|
|
|
if (this._futureSalts.length === 0) return
|
|
|
|
|
|
|
|
const next = this._futureSalts.shift()!
|
|
|
|
|
2024-08-21 11:05:07 +03:00
|
|
|
this._timer = timers.setTimeout(
|
2023-12-11 06:15:31 +03:00
|
|
|
() => {
|
|
|
|
this.currentSalt = next.salt
|
|
|
|
this._scheduleNext()
|
|
|
|
},
|
|
|
|
next.validSince * 1000 - Date.now(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
destroy(): void {
|
2024-08-21 11:05:07 +03:00
|
|
|
timers.clearTimeout(this._timer)
|
2023-12-11 06:15:31 +03:00
|
|
|
}
|
|
|
|
}
|