121 lines
7.1 KiB
TypeScript
121 lines
7.1 KiB
TypeScript
import { Api, type TelegramClient } from 'teleproto';
|
|
import { getPeerId, getInputPeer, getDisplayName } from 'teleproto/Utils.js';
|
|
import bigInt from 'big-integer';
|
|
import { randomUUID } from 'node:crypto';
|
|
import { TgError } from '../../lib/errors.js';
|
|
|
|
// In-memory state on the existing daemon/session. Never serialize input peers,
|
|
// access hashes, message bodies or session data into a continuation token.
|
|
interface Scan {
|
|
token: string; created: number; touched: number; rows: any[]; seen: Set<string>;
|
|
offsetId: number; offsetDate: number; offsetPeer: Api.TypeInputPeer;
|
|
excludePinned: boolean; complete: boolean; busy: boolean;
|
|
pages: number; skipped: number; lastOffset?: string;
|
|
}
|
|
interface Owner { scans: Map<string, Scan>; current?: string; retryAt: number }
|
|
const owners = new WeakMap<object, Map<string, Owner>>();
|
|
const TTL = 30 * 60_000;
|
|
|
|
function owner(client: TelegramClient, account: string): Owner {
|
|
const key = client.session ?? client;
|
|
let accounts = owners.get(key);
|
|
if (!accounts) owners.set(key, accounts = new Map());
|
|
let value = accounts.get(account);
|
|
if (!value) accounts.set(account, value = { scans: new Map(), retryAt: 0 });
|
|
return value;
|
|
}
|
|
|
|
export function floodSeconds(error: unknown): number | undefined {
|
|
const e = error as any;
|
|
const name = `${e?.errorMessage ?? ''} ${e?.message ?? ''} ${e?.code ?? ''}`;
|
|
if (!/FLOOD(?:_PREMIUM)?_WAIT/i.test(name)) return;
|
|
const seconds = Number(e?.seconds ?? name.match(/FLOOD(?:_PREMIUM)?_WAIT_?(\d+)/i)?.[1]);
|
|
return Number.isFinite(seconds) && seconds >= 0 ? Math.max(1, Math.ceil(seconds)) : undefined;
|
|
}
|
|
|
|
export function recordReadFlood(client: TelegramClient, account: string, error: unknown) {
|
|
const seconds = floodSeconds(error);
|
|
if (seconds === undefined) throw error;
|
|
const o = owner(client, account);
|
|
o.retryAt = Math.max(o.retryAt, Date.now() + seconds * 1000);
|
|
return { retry_after_seconds: Math.ceil((o.retryAt - Date.now()) / 1000), retry_at: new Date(o.retryAt).toISOString() };
|
|
}
|
|
|
|
/** At most five server pages per call. FloodWait preserves the last committed
|
|
* cursor and returns a deadline; the caller resumes, never replays a write. */
|
|
export async function scanDialogs(client: TelegramClient, account: string, target: number,
|
|
cursor?: string, refresh = false) {
|
|
if (cursor && refresh) throw new TgError('Use cursor to resume OR refresh to restart', 'INVALID_OPTIONS');
|
|
const o = owner(client, account), now = Date.now();
|
|
for (const [key, s] of o.scans) if (!s.busy && now - s.touched > TTL) o.scans.delete(key);
|
|
let s = o.scans.get(cursor ?? (refresh ? '' : o.current ?? ''));
|
|
if (cursor && !s) throw new TgError('Dialog cursor expired or belongs to another session/account; restart explicitly', 'CURSOR_EXPIRED');
|
|
if (!s) {
|
|
if (o.scans.size >= 4) throw new TgError('Too many active dialog snapshots; reuse a cursor or wait for expiry', 'SCAN_LIMIT');
|
|
s = { token: randomUUID(), created: now, touched: now, rows: [], seen: new Set(),
|
|
offsetId: 0, offsetDate: 0, offsetPeer: new Api.InputPeerEmpty(), excludePinned: false,
|
|
complete: false, busy: false, pages: 0, skipped: 0 };
|
|
o.scans.set(s.token, s); o.current = s.token;
|
|
}
|
|
if (s.busy) throw new TgError('Dialog snapshot is in use; resume sequentially', 'SCAN_BUSY');
|
|
s.busy = true; s.touched = now;
|
|
try {
|
|
for (let page = 0; page < 5 && !s.complete && s.rows.length < target; page++) {
|
|
if (Date.now() < o.retryAt) break;
|
|
let r: any;
|
|
try {
|
|
r = await client.invoke(new Api.messages.GetDialogs({ offsetId: s.offsetId,
|
|
offsetDate: s.offsetDate, offsetPeer: s.offsetPeer, excludePinned: s.excludePinned,
|
|
limit: 100, hash: bigInt.zero }));
|
|
} catch (e) {
|
|
const seconds = floodSeconds(e);
|
|
if (seconds === undefined) throw e;
|
|
o.retryAt = Date.now() + seconds * 1000;
|
|
break;
|
|
}
|
|
if (!(r instanceof Api.messages.Dialogs || r instanceof Api.messages.DialogsSlice))
|
|
throw new TgError('Unexpected dialog response; cursor preserved', 'DIALOG_RESPONSE');
|
|
const entities = new Map<string, any>();
|
|
for (const e of [...r.users, ...r.chats]) entities.set(getPeerId(e), e);
|
|
const messages = new Map<string, any>();
|
|
for (const m of r.messages) if (m.peerId) messages.set(`${getPeerId(m.peerId)}:${m.id}`, m);
|
|
const unsupported = r.dialogs.filter((d: any) => !(d instanceof Api.Dialog) && !(d instanceof Api.DialogFolder)).length;
|
|
const dialogs = r.dialogs.filter((d: any) => d instanceof Api.Dialog);
|
|
const last = dialogs.at(-1);
|
|
let next: { id: number; date: number; peer: Api.TypeInputPeer; key: string } | undefined;
|
|
const end = r instanceof Api.messages.Dialogs || r.dialogs.length < 100;
|
|
if (!end && last) {
|
|
const id = getPeerId(last.peer), entity = entities.get(id);
|
|
if (!entity) throw new TgError('Missing cursor entity; snapshot incomplete', 'DIALOG_ENTITY');
|
|
next = { id: last.topMessage, date: messages.get(`${id}:${last.topMessage}`)?.date ?? 0,
|
|
peer: getInputPeer(entity), key: `${id}:${last.topMessage}` };
|
|
if (next.key === s.lastOffset) throw new TgError('Dialog cursor did not advance; snapshot incomplete', 'CURSOR_STALLED');
|
|
} else if (!end && !last) throw new TgError('No usable dialog cursor; snapshot incomplete', 'CURSOR_STALLED');
|
|
// Commit only after cursor validation. Discard all message bodies here.
|
|
for (const d of dialogs) {
|
|
const id = getPeerId(d.peer), e = entities.get(id);
|
|
if (s.seen.has(id)) continue;
|
|
if (!e || e instanceof Api.UserEmpty || e instanceof Api.ChatEmpty) { s.skipped++; continue; }
|
|
const m = messages.get(`${id}:${d.topMessage}`), mute = d.notifySettings?.muteUntil;
|
|
s.rows.push({ id, title: getDisplayName(e), username: e.username ?? null,
|
|
type: e.bot ? 'bot' : e instanceof Api.User ? 'user' : e.broadcast ? 'channel' : 'group',
|
|
contact: !!e.contact, self: !!e.self, archived: d.folderId === 1, pinned: !!d.pinned,
|
|
unread_count: d.unreadCount, unread_mentions: d.unreadMentionsCount, unread_mark: !!d.unreadMark,
|
|
mute_until: mute ?? null, muted: mute == null ? null : mute > Date.now() / 1000,
|
|
notifications_inherited: mute == null, last_message_id: d.topMessage,
|
|
last_message_at: m?.date ? new Date(m.date * 1000).toISOString() : null,
|
|
has_draft: !!(d.draft instanceof Api.DraftMessage && d.draft.message) });
|
|
s.seen.add(id);
|
|
}
|
|
s.skipped += unsupported; s.pages++; s.complete = end;
|
|
if (next) { s.offsetId = next.id; s.offsetDate = next.date; s.offsetPeer = next.peer;
|
|
s.lastOffset = next.key; s.excludePinned = true; }
|
|
}
|
|
s.touched = Date.now();
|
|
return { rows: s.rows, cursor: s.token, complete: s.complete && s.skipped === 0,
|
|
exhausted: s.complete, scanned: s.rows.length, skipped: s.skipped, pages_fetched: s.pages,
|
|
snapshot_started_at: new Date(s.created).toISOString(),
|
|
retry_after_seconds: Math.max(0, Math.ceil((o.retryAt - Date.now()) / 1000)),
|
|
retry_at: o.retryAt > Date.now() ? new Date(o.retryAt).toISOString() : null };
|
|
} finally { s.busy = false; }
|
|
}
|