mtcute/packages/core/src/network/server-salt.ts

52 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-12-11 06:15:31 +03:00
import Long from 'long'
import type { mtp } from '@mtcute/tl'
2023-12-11 06:15:31 +03:00
2024-08-25 23:22:20 +03:00
import { timers } from '../utils/index.js'
2024-08-21 11:05:07 +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
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()
}
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
}
}