Repository navigation
Expand file tree
/
Copy pathtelegram-client.js
More file actions
2041 lines (1858 loc) · 69.3 KB
/
Copy pathtelegram-client.js
File metadata and controls
2041 lines (1858 loc) · 69.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { TelegramClient as MtCuteClient } from '@mtcute/node';
import { InputMedia, Message, MtPeerNotFoundError, PeersIndex, networkMiddlewares } from '@mtcute/core';
import { randomLong, toggleChannelIdMark } from '@mtcute/core/utils.js';
import { html } from '@mtcute/html-parser';
import { md } from '@mtcute/markdown-parser';
import QRCode from 'qrcode';
import EventEmitter from 'events';
import fs from 'fs';
import { stat } from 'fs/promises';
import os from 'os';
import path from 'path';
import readline from 'readline';
import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
import { nodeReadableToFuman } from '@fuman/node';
import { resolveStoreDir, resolveStorePaths } from './core/store.js';
// How long a session Telegram confirmed is taken as logged in without asking again.
const AUTH_CHECK_TTL_MS = 5 * 60 * 1000;
const timeoutPatchKey = Symbol.for('tgcli.timeoutPatch');
if (!globalThis[timeoutPatchKey]) {
const originalSetTimeout = globalThis.setTimeout;
if (typeof originalSetTimeout === 'function') {
const wrapped = (handler, delay, ...args) => {
const safeDelay = Number.isFinite(delay) ? Math.max(0, delay) : 0;
return originalSetTimeout(handler, safeDelay, ...args);
};
globalThis.setTimeout = wrapped;
}
globalThis[timeoutPatchKey] = true;
}
const DEFAULT_STORE_DIR = resolveStoreDir();
const { sessionPath: DEFAULT_SESSION_PATH } = resolveStorePaths(DEFAULT_STORE_DIR);
const DEFAULT_DOWNLOAD_DIR = path.join(DEFAULT_STORE_DIR, 'downloads');
const MIME_EXTENSION_MAP = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
'image/gif': '.gif',
'video/mp4': '.mp4',
'video/quicktime': '.mov',
'audio/mpeg': '.mp3',
'audio/mp4': '.m4a',
'audio/ogg': '.ogg',
'audio/opus': '.opus',
'audio/wav': '.wav',
'application/pdf': '.pdf',
'application/zip': '.zip',
};
const IS_TTY = typeof process === 'object' && Boolean(process.stdout?.isTTY);
const LOG_BASE_FORMAT = IS_TTY ? '%s [%s] [%s%s\x1B[0m] ' : '%s [%s] [%s] ';
const LOG_LEVEL_NAMES = IS_TTY
? [
'',
'\x1B[31mERR\x1B[0m',
'\x1B[33mWRN\x1B[0m',
'\x1B[34mINF\x1B[0m',
'\x1B[36mDBG\x1B[0m',
'\x1B[35mVRB\x1B[0m',
]
: ['', 'ERR', 'WRN', 'INF', 'DBG', 'VRB'];
const LOG_TAG_COLORS = [6, 2, 3, 4, 5, 1].map((i) => `\x1B[3${i};1m`);
const LOG_HANDLER = IS_TTY
? (color, level, tag, fmt, args) => {
console.log(
LOG_BASE_FORMAT + fmt,
new Date().toISOString(),
LOG_LEVEL_NAMES[level],
LOG_TAG_COLORS[color],
tag,
...args,
);
}
: (color, level, tag, fmt, args) => {
console.log(
LOG_BASE_FORMAT + fmt,
new Date().toISOString(),
LOG_LEVEL_NAMES[level],
tag,
...args,
);
};
async function normalizeUploadFile(file) {
if (typeof file === 'string') {
file = fs.createReadStream(file);
}
if (file instanceof fs.ReadStream) {
const filePath = file.path.toString();
const fileName = path.basename(filePath);
const fileSize = await stat(filePath).then((stats) => stats.size);
return {
file: nodeReadableToFuman(file),
fileName,
fileSize,
};
}
if (file instanceof Readable) {
return {
file: nodeReadableToFuman(file),
};
}
return null;
}
function createPlatform() {
return {
beforeExit: (callback) => {
if (typeof process === 'undefined') {
return () => {};
}
const handler = () => {
callback();
};
process.on('exit', handler);
return () => {
process.off('exit', handler);
};
},
log: LOG_HANDLER,
getDefaultLogLevel: () => {
const envLogLevel = Number.parseInt(process.env.MTCUTE_LOG_LEVEL ?? '', 10);
if (!Number.isNaN(envLogLevel)) {
return envLogLevel;
}
return null;
},
getDeviceModel: () => `Node.js/${process.version} (${os.type()} ${os.arch()})`,
normalizeFile: normalizeUploadFile,
};
}
function sanitizeString(value) {
return typeof value === 'string' ? value : '';
}
function normalizeParseMode(value) {
if (value === undefined || value === null || value === '') return null;
const normalized = String(value).trim().toLowerCase();
if (!['markdown', 'html', 'none'].includes(normalized)) {
throw new Error('Invalid parse mode. Allowed values: markdown, html, none');
}
return normalized;
}
function applyParseMode(text, parseMode) {
if (parseMode === 'markdown') return md(text);
if (parseMode === 'html') return html(text);
return text;
}
function resolveScheduleDate(options) {
if (options.scheduleDate !== undefined && options.scheduleDate !== null) return options.scheduleDate;
if (options.schedule) {
const date = new Date(options.schedule);
if (Number.isNaN(date.getTime())) {
throw new Error('Invalid schedule date: must be a valid ISO 8601 datetime');
}
return Math.floor(date.getTime() / 1000);
}
return undefined;
}
function resolveReplyTo(options = {}) {
if (Number.isFinite(options.replyToMessageId)) return options.replyToMessageId;
if (Number.isFinite(options.topicId)) return options.topicId;
return undefined;
}
function buildTextSendParams(options = {}) {
const params = {};
const replyTo = resolveReplyTo(options);
if (replyTo) params.replyTo = replyTo;
if (options.noPreview) params.disableWebPreview = true;
if (options.silent) params.silent = true;
if (options.noForwards || options.noforwards) params.forbidForwards = true;
const scheduleDate = resolveScheduleDate(options);
if (scheduleDate) params.schedule = new Date(scheduleDate * 1000);
return Object.keys(params).length ? params : undefined;
}
function buildMediaSendParams(options = {}) {
const params = {};
const replyTo = resolveReplyTo(options);
if (replyTo) params.replyTo = replyTo;
if (options.silent) params.silent = true;
if (options.noForwards || options.noforwards) params.forbidForwards = true;
const scheduleDate = resolveScheduleDate(options);
if (scheduleDate) params.schedule = new Date(scheduleDate * 1000);
if (options.captionAbove) params.invert = true;
return Object.keys(params).length ? params : undefined;
}
function resolveUploadPath(filePath) {
if (!filePath || typeof filePath !== 'string') {
throw new Error('filePath must be a string.');
}
const resolved = path.resolve(filePath);
if (!fs.existsSync(resolved)) {
throw new Error(`File not found: ${resolved}`);
}
return `file:${resolved}`;
}
// mtcute writes a min peer over the complete one it already has, access hash included
// (still so in 0.32.7). A min row counts as having no hash, so from then on the chat
// cannot be looked up, and an update that hits a pts gap is lost: getChannelDifference
// finds no peer, or is refused with CHANNEL_INVALID. A min copy adds nothing worth that.
function keepCompletePeersOverMinCopies(client) {
const { peers, refMsgs } = client.storage;
const store = peers.store.bind(peers);
peers.store = async (peer) => {
const isChannel = peer._ === 'channel' || peer._ === 'channelForbidden';
const id = isChannel ? toggleChannelIdMark(peer.id) : peer.id;
if (peer.min) {
const existing = await peers.getCompleteById(id);
if (existing && !existing.min) {
await refMsgs.deleteByPeer(id);
return;
}
}
await store(peer);
// store() caches a channel under its bare id while lookups go by the marked one, so
// a lookup that cached the min row would go on answering with its hash. Overwritten,
// not deleted, since LruMap.delete unlinks everything older than the entry.
if (isChannel && !peer.min && peers._cache.get(id)) {
peers._cache.set(id, peers._cache.get(peer.id));
}
};
}
function resolveOptionalCaption(caption) {
if (typeof caption !== 'string') return undefined;
const trimmed = caption.trim();
return trimmed ? trimmed : undefined;
}
function buildSendMessageResult(sent, { method, defaultMediaType } = {}) {
const result = { messageId: sent?.id ?? null };
if (sent?.isScheduled) result.scheduled = true;
if (method) result.method = method;
const media = summarizeMedia(sent?.media) ?? (defaultMediaType ? { type: defaultMediaType } : null);
if (media) result.media = media;
return result;
}
function buildLowLevelReplyTo(options = {}) {
const replyTo = resolveReplyTo(options);
if (!replyTo) return undefined;
return { _: 'inputReplyToMessage', replyToMsgId: replyTo };
}
function splitInputText(value) {
if (!value) return { message: '', entities: undefined };
if (typeof value === 'string') return { message: value, entities: undefined };
if (typeof value === 'object' && typeof value.text === 'string') {
return {
message: value.text,
entities: Array.isArray(value.entities) && value.entities.length > 0 ? value.entities : undefined,
};
}
return { message: String(value), entities: undefined };
}
function randomIdsEqual(left, right) {
if (left?.eq && typeof left.eq === 'function') return left.eq(right);
return String(left) === String(right);
}
const SENT_MESSAGE_UPDATES = new Set(['updateNewMessage', 'updateNewChannelMessage', 'updateNewScheduledMessage']);
// What a send response says about the message it sent: its id and, when the
// response carries the message itself, the update holding it.
function readSendResponse(response, randomId) {
const updates = Array.isArray(response?.updates) ? response.updates : [];
const assignedId = updates.find(
(update) => update?._ === 'updateMessageID' && randomIdsEqual(update.randomId, randomId),
)?.id;
const messageUpdates = updates.filter((update) => SENT_MESSAGE_UPDATES.has(update?._));
const messageUpdate = assignedId === undefined
? messageUpdates[0]
: messageUpdates.find((update) => update.message?.id === assignedId);
return { messageId: assignedId ?? messageUpdate?.message?.id ?? null, messageUpdate };
}
// The send has already gone through at this point, so a response that cannot be
// parsed must not fail it.
function parseSentMessage(messageUpdate, response, peerRef) {
try {
return new Message(messageUpdate.message, PeersIndex.from(response), messageUpdate._ === 'updateNewScheduledMessage');
} catch (error) {
console.error(`[sendPhoto] Failed to parse sent message ${messageUpdate.message?.id} for peer ${peerRef}: ${error.message}`);
return null;
}
}
function coerceApiId(value) {
if (typeof value === 'number') {
return value;
}
if (typeof value === 'string') {
const parsed = parseInt(value, 10);
if (!Number.isNaN(parsed)) {
return parsed;
}
}
throw new Error('TELEGRAM_API_ID must be a number');
}
function normalizePeerType(peer) {
if (!peer) return 'chat';
if (peer.type === 'user' || peer.type === 'bot') return 'user';
if (peer.type === 'channel') return 'channel';
if (peer.type === 'chat' && peer.chatType && peer.chatType !== 'group') return 'channel';
return 'chat';
}
function isGroupPeer(peer) {
if (!peer) return false;
if (typeof peer.isGroup === 'boolean') {
return peer.isGroup;
}
if (peer.type === 'chat') {
return true;
}
if (peer.type === 'channel' && typeof peer.chatType === 'string') {
return peer.chatType !== 'channel';
}
return false;
}
function extractTopicId(message) {
if (!message) return null;
if (typeof message.replyToMessage?.threadId === 'number') {
return message.replyToMessage.threadId;
}
if (message.action?.type === 'topic_created' && typeof message.id === 'number') {
return message.id;
}
const raw = message.raw ?? message;
const replyTo = raw?.replyTo;
if (replyTo?.replyToTopId) {
return replyTo.replyToTopId;
}
return null;
}
function normalizeMediaText(value) {
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
if (typeof value === 'number' || typeof value === 'bigint') {
return String(value);
}
return null;
}
function normalizeMediaNumber(value) {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
function readMediaProperty(media, prop) {
if (!media) {
return null;
}
try {
return media[prop];
} catch (error) {
return null;
}
}
function buildWebpageExtras(media) {
if (!media || media.type !== 'webpage' || !media.preview) {
return null;
}
const preview = media.preview;
const previewData = {
url: preview.url ?? null,
displayUrl: preview.displayUrl ?? null,
siteName: preview.siteName ?? null,
title: preview.title ?? null,
description: preview.description ?? null,
author: preview.author ?? null,
previewType: preview.previewType ?? null,
};
const hasPreview = Object.values(previewData).some((value) => value);
const extras = {};
if (hasPreview) {
extras.preview = previewData;
}
if (typeof media.displaySize === 'string') {
extras.displaySize = media.displaySize;
}
if (typeof media.manual === 'boolean') {
extras.manual = media.manual;
}
return Object.keys(extras).length ? extras : null;
}
export function summarizeMedia(media) {
if (!media || typeof media !== 'object') {
return null;
}
const type = normalizeMediaText(media.type);
if (!type) {
return null;
}
const summary = {
type,
fileId: normalizeMediaText(readMediaProperty(media, 'fileId') ?? media.file_id),
uniqueFileId: normalizeMediaText(readMediaProperty(media, 'uniqueFileId') ?? media.unique_file_id),
fileName: normalizeMediaText(readMediaProperty(media, 'fileName') ?? media.file_name),
mimeType: normalizeMediaText(readMediaProperty(media, 'mimeType') ?? media.mime_type),
fileSize: normalizeMediaNumber(readMediaProperty(media, 'fileSize') ?? media.file_size),
width: normalizeMediaNumber(readMediaProperty(media, 'width') ?? media.width),
height: normalizeMediaNumber(readMediaProperty(media, 'height') ?? media.height),
duration: normalizeMediaNumber(readMediaProperty(media, 'duration') ?? media.duration),
extras: null,
};
if (!summary.mimeType && type === 'photo') {
summary.mimeType = 'image/jpeg';
}
if (media.extras && typeof media.extras === 'object') {
summary.extras = media.extras;
} else {
summary.extras = buildWebpageExtras(media);
}
if (type === 'webpage' && media.preview) {
const previewMedia = media.preview.document ?? media.preview.photo ?? null;
if (previewMedia) {
const previewSummary = summarizeMedia(previewMedia);
if (previewSummary) {
summary.fileId = summary.fileId ?? previewSummary.fileId;
summary.uniqueFileId = summary.uniqueFileId ?? previewSummary.uniqueFileId;
summary.fileName = summary.fileName ?? previewSummary.fileName;
summary.mimeType = summary.mimeType ?? previewSummary.mimeType;
summary.fileSize = summary.fileSize ?? previewSummary.fileSize;
summary.width = summary.width ?? previewSummary.width;
summary.height = summary.height ?? previewSummary.height;
summary.duration = summary.duration ?? previewSummary.duration;
}
}
}
return summary;
}
function extensionFromMime(mimeType) {
if (!mimeType || typeof mimeType !== 'string') {
return null;
}
return MIME_EXTENSION_MAP[mimeType.toLowerCase()] ?? null;
}
function buildDownloadFileName(summary, messageId) {
const rawName = normalizeMediaText(summary?.fileName);
if (rawName) {
return path.basename(rawName);
}
const ext = extensionFromMime(summary?.mimeType) ?? '';
const baseType = normalizeMediaText(summary?.type) ?? 'media';
return `${baseType}-${messageId}${ext}`;
}
function resolveDownloadPath(outputPath, { channelId, messageId, summary }) {
const fileName = buildDownloadFileName(summary, messageId);
if (!outputPath) {
return path.resolve(DEFAULT_DOWNLOAD_DIR, String(channelId), fileName);
}
const resolved = path.resolve(outputPath);
if (fs.existsSync(resolved)) {
const stat = fs.statSync(resolved);
if (stat.isDirectory()) {
return path.join(resolved, fileName);
}
} else if (/[\\/]$/.test(outputPath)) {
return path.join(resolved, fileName);
}
return resolved;
}
function resolveDownloadLocation(media) {
if (!media || typeof media !== 'object') {
return null;
}
if (media.type === 'webpage' && media.preview) {
return media.preview.document ?? media.preview.photo ?? null;
}
if (media.location && typeof media.location === 'object') {
return media;
}
return null;
}
// Errors about a chat itself: the account has left it or was removed, it is gone, or
// Telegram does not know it. Anything else, such as a broken session, says nothing
// about the chat.
const CHAT_GONE_ERRORS = new Set([
'CHANNEL_INVALID',
'CHANNEL_PRIVATE',
'CHAT_FORBIDDEN',
'CHAT_ID_INVALID',
'PEER_ID_INVALID',
'USER_BANNED_IN_CHANNEL',
]);
export function isChatGone(error) {
return error instanceof MtPeerNotFoundError || CHAT_GONE_ERRORS.has(error?.text);
}
// What Telegram says about the account in a channel or group: 'member', 'left' (left, or
// never joined), 'gone' (removed, banned, the chat deleted or migrated) or 'unknown'.
// Only a chat Telegram returns decides: an error may mean a bad access hash, not a left chat.
function membershipOf(chat) {
switch (chat?._) {
case 'channel':
return chat.left ? 'left' : 'member';
case 'chat':
if (chat.deactivated || chat.migratedTo) {
return 'gone';
}
return chat.left ? 'left' : 'member';
case 'channelForbidden':
case 'chatForbidden':
case 'chatEmpty':
return 'gone';
default:
return null;
}
}
export function normalizeChannelId(channelId) {
if (typeof channelId === 'number') {
return channelId;
}
if (typeof channelId === 'bigint') {
return Number(channelId);
}
if (typeof channelId === 'string') {
const trimmed = channelId.trim();
if (/^-?\d+$/.test(trimmed)) {
const numeric = Number(trimmed);
if (!Number.isNaN(numeric)) {
return numeric;
}
}
return trimmed;
}
throw new Error('Invalid channel ID provided');
}
function normalizePositiveMessageId(value) {
const numeric = Number(value);
return Number.isFinite(numeric) && numeric > 0 ? numeric : 0;
}
function filterSerializedMessagesById(messages, options = {}) {
const beforeId = normalizePositiveMessageId(options.beforeId);
const afterId = normalizePositiveMessageId(options.afterId);
if (!beforeId && !afterId) {
return messages;
}
return messages.filter((message) => {
const messageId = normalizePositiveMessageId(message?.id);
if (!messageId) {
return false;
}
if (beforeId && messageId >= beforeId) {
return false;
}
if (afterId && messageId <= afterId) {
return false;
}
return true;
});
}
class TelegramClient {
constructor(apiId, apiHash, phoneNumber, sessionPath = DEFAULT_SESSION_PATH, options = {}) {
this.apiId = coerceApiId(apiId);
this.apiHash = sanitizeString(apiHash);
this.phoneNumber = sanitizeString(phoneNumber);
this.sessionPath = path.resolve(sessionPath);
this.options = options;
const dataDir = path.dirname(this.sessionPath);
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
this.updateEmitter = new EventEmitter();
this.updatesRunning = false;
this.rawUpdateHandler = null;
const userUpdates = options.updates ?? {};
const updatesConfig = {
...userUpdates,
catchUp: userUpdates.catchUp ?? true,
onChannelTooLong: (channelId, diff) => {
if (typeof userUpdates.onChannelTooLong === 'function') {
userUpdates.onChannelTooLong(channelId, diff);
}
this.updateEmitter.emit('channelTooLong', { channelId, diff });
},
};
this.updatesConfig = updatesConfig;
this.client = this._createClient();
}
_createClient() {
const clientOptions = {
apiId: this.apiId,
apiHash: this.apiHash,
storage: this.sessionPath,
// A delayed write of a min copy can land after the complete row that replaced it.
storageOptions: { peers: { updatesWriteInterval: 0 } },
platform: createPlatform(),
};
if (this.options.stats) {
clientOptions.network = { middlewares: this.options.stats.networkMiddlewares(networkMiddlewares.basic()) };
}
if (this.options.disableUpdates) {
clientOptions.disableUpdates = true;
} else {
clientOptions.updates = this.updatesConfig;
}
const client = new MtCuteClient(clientOptions);
keepCompletePeersOverMinCopies(client);
return client;
}
_isAuthKeyUnregisteredError(error) {
if (!error) return false;
const code = error.code || error.status || error.errorCode;
const message = (error.errorMessage || error.text || error.message || '').toUpperCase();
return code === 401 && message.includes('AUTH_KEY_UNREGISTERED');
}
_isSessionResetError(error) {
if (!error) return false;
const message = (error.errorMessage || error.text || error.message || '').toUpperCase();
return message.includes('SESSION IS RESET');
}
async _recreateClient() {
try {
await this.client.destroy();
} catch (error) {
console.warn('[warning] failed to destroy MTProto client during reset:', error?.message || error);
}
this.client = this._createClient();
this.authorizedUntil = 0;
this.updatesRunning = false;
this.rawUpdateHandler = null;
this.updateEmitter.emit('clientReplaced');
}
async _resetSessionAndClient() {
const sessionFiles = [this.sessionPath, `${this.sessionPath}-wal`, `${this.sessionPath}-shm`];
for (const filePath of sessionFiles) {
try {
fs.unlinkSync(filePath);
} catch (error) {
if (error?.code !== 'ENOENT') {
throw error;
}
}
}
await this._recreateClient();
}
_isUnauthorizedError(error) {
if (!error) return false;
const code = error.code || error.status || error.errorCode;
if (code === 401) {
return true;
}
const message = (error.errorMessage || error.message || '').toUpperCase();
return message.includes('AUTH_KEY') || message.includes('AUTHORIZATION') || message.includes('SESSION_PASSWORD_NEEDED');
}
// getMe is a request to Telegram, and ensureLogin runs before every page of history and
// every recheck, so a yes stands for AUTH_CHECK_TTL_MS: asking each time doubled the
// requests of a backfill or a repair. A revoked session still fails the request itself.
// fresh asks Telegram regardless, for login and for commands that report the state.
async _isAuthorized({ fresh = false } = {}) {
if (!fresh && Date.now() < (this.authorizedUntil ?? 0)) {
return true;
}
try {
await this.client.getMe();
this.authorizedUntil = Date.now() + AUTH_CHECK_TTL_MS;
return true;
} catch (error) {
this.authorizedUntil = 0;
if (this._isUnauthorizedError(error)) {
return false;
}
throw error;
}
}
async isAuthorized() {
return this._isAuthorized({ fresh: true });
}
async getCurrentUser() {
try {
return await this.client.getMe();
} catch (error) {
if (this._isUnauthorizedError(error)) {
return null;
}
throw error;
}
}
async _askQuestion(prompt) {
const ask = () => {
if (process.stdin.isPaused()) {
process.stdin.resume();
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => {
rl.question(prompt, answer => {
rl.close();
resolve(answer.trim());
});
});
};
let answer = await ask();
if (!answer) {
answer = await ask();
}
return answer;
}
async _askHiddenQuestion(prompt) {
if (!process.stdin.isTTY) {
return this._askQuestion(prompt);
}
if (process.stdin.isPaused()) {
process.stdin.resume();
}
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: true,
});
rl.stdoutMuted = false;
const writeOutput = rl._writeToOutput.bind(rl);
rl._writeToOutput = (stringToWrite) => {
if (!rl.stdoutMuted) {
writeOutput(stringToWrite);
}
};
return new Promise(resolve => {
rl.question(prompt, answer => {
rl.output.write('\n');
rl.close();
resolve(answer.trim());
});
rl.stdoutMuted = true;
});
}
_buildStartParams() {
const startParams = {
password: async () => {
const value = await this._askHiddenQuestion('Enter your 2FA password (leave empty if not enabled): ');
return value.length ? value : undefined;
},
};
if (this.options.useQr) {
startParams.qrCodeHandler = async (url, expiresAt) => {
const expiresLabel = expiresAt instanceof Date && !Number.isNaN(expiresAt.getTime())
? expiresAt.toISOString()
: 'unknown';
let qrFile = null;
if (this.options.qrFilePath) {
qrFile = this.options.qrFilePath;
await QRCode.toFile(qrFile, url, { type: 'png', width: 300 });
}
if (this.options.json) {
process.stderr.write(`${JSON.stringify({
event: 'qr',
url,
expiresAt: expiresLabel,
qrFile,
})}\n`);
return;
}
console.log('\nScan this QR code in Telegram: Settings -> Devices -> Link Desktop Device');
const terminalQr = await QRCode.toString(url, { type: 'terminal', small: true });
console.log(terminalQr);
console.log(`QR expires at: ${expiresLabel}`);
if (qrFile) {
console.log(`QR saved to: ${qrFile}`);
}
};
} else {
startParams.phone = this.phoneNumber;
startParams.code = async () => await this._askQuestion('Enter the code you received: ');
startParams.codeSentCallback = async (sentCode) => {
if (this.options.forceSms && (sentCode.type === 'app' || sentCode.type === 'email')) {
try {
await this.client.resendCode({ phone: this.phoneNumber, phoneCodeHash: sentCode.phoneCodeHash });
console.log('Code re-sent via SMS.');
} catch (error) {
const message = (error.text || error.message || '').toUpperCase();
if (message.includes('SEND_CODE_UNAVAILABLE')) {
console.log('SMS unavailable for this number. Please use the code sent via app.');
} else {
console.log(`Could not request SMS (${error.text || error.message}). Using code sent via ${sentCode.type}.`);
}
}
} else {
console.log(`The confirmation code has been sent via ${sentCode.type}.`);
}
};
}
return startParams;
}
async login(retriedAfterReset = false, retriedAfterSessionReset = false) {
try {
const hasExistingSession = await this._isAuthorized({ fresh: true });
if (!hasExistingSession && !this.options.useQr && !this.phoneNumber) {
throw new Error('TELEGRAM_PHONE_NUMBER is not configured.');
}
await this.client.start(this._buildStartParams());
console.log(hasExistingSession ? 'Existing session is valid.' : 'Logged in successfully!');
return true;
} catch (error) {
if (!retriedAfterReset && this._isAuthKeyUnregisteredError(error)) {
console.log('Detected AUTH_KEY_UNREGISTERED. Resetting local session and retrying login once...');
try {
await this._resetSessionAndClient();
return await this.login(true, retriedAfterSessionReset);
} catch (resetError) {
console.error('Failed to recover from AUTH_KEY_UNREGISTERED:', resetError);
return false;
}
}
if (!retriedAfterSessionReset && this._isSessionResetError(error)) {
console.log('Detected session reset during login. Recreating MTProto client and retrying once...');
try {
await this._recreateClient();
return await this.login(retriedAfterReset, true);
} catch (resetError) {
console.error('Failed to recover from session reset:', resetError);
return false;
}
}
console.error('Error during login:', error);
return false;
}
}
async ensureLogin() {
if (!(await this._isAuthorized())) {
throw new Error('Not logged in to Telegram. Please restart the server.');
}
return true;
}
async initializeDialogCache() {
console.log('Initializing dialog list...');
const loginSuccess = await this.login();
if (!loginSuccess) {
throw new Error('Failed to login to Telegram. Cannot proceed.');
}
await this.startUpdates();
console.log('Dialogs ready.');
return true;
}
// Asks Telegram about the account's membership in channels and groups, given marked
// ids, with one request per 100 of each kind. Returns a Map of id to 'member', 'left',
// 'gone' or 'unknown'; private chats have no membership and are left out.
async getChatMembership(chatIds) {
await this.ensureLogin();
const result = new Map();
const channels = [];
const groups = [];
for (const id of chatIds) {
let peer;
try {
peer = await this.client.resolvePeer(Number(id));
} catch {
// Not in the peer cache, or not an id mtcute can parse: nothing to ask with.
result.set(String(id), 'unknown');
continue;
}
if (peer._ === 'inputPeerChannel') {
channels.push({ id: String(id), input: { _: 'inputChannel', channelId: peer.channelId, accessHash: peer.accessHash } });
} else if (peer._ === 'inputPeerChat') {
groups.push({ id: String(id), input: peer.chatId });
}
}
const ask = async (items, request, markedId) => {
for (let start = 0; start < items.length; start += 100) {
const batch = items.slice(start, start + 100);
let chats;
try {
({ chats } = await this.client.call(request(batch.map((item) => item.input))));
} catch (error) {
if (!isChatGone(error)) {
throw error;
}
if (batch.length === 1) {
// A stale or min access hash is refused the same way: no answer about the chat.
result.set(batch[0].id, 'unknown');
continue;
}
// One refused chat fails the whole batch, so ask about each on its own.
for (const item of batch) {
await ask([item], request, markedId);
}
continue;
}
const byId = new Map(chats.map((chat) => [markedId(chat.id), membershipOf(chat)]));
for (const item of batch) {
result.set(item.id, byId.get(item.id) ?? 'unknown');
}
}
};
await ask(channels, (id) => ({ _: 'channels.getChannels', id }), (rawId) => String(toggleChannelIdMark(rawId)));
await ask(groups, (id) => ({ _: 'messages.getChats', id }), (rawId) => String(-rawId));
return result;
}
async listDialogs(limit = 50, { includeArchived = false, retriedAfterSessionReset = false } = {}) {
try {
await this.ensureLogin();
const effectiveLimit = limit && limit > 0 ? limit : Infinity;
const results = [];
for await (const dialog of this.client.iterDialogs({ archived: includeArchived ? 'keep' : 'exclude' })) {
const peer = dialog.peer;
if (!peer) continue;
const id = peer.id.toString();
const username = 'username' in peer ? peer.username ?? null : null;
const chatType = typeof peer.chatType === 'string' ? peer.chatType : null;
const isForum = typeof peer.isForum === 'boolean' ? peer.isForum : null;
const isGroup = typeof peer.isGroup === 'boolean' ? peer.isGroup : null;
results.push({
id,
type: normalizePeerType(peer),
title: peer.displayName || 'Unknown',
username,
chatType,
isForum,
isGroup,
unreadCount: typeof dialog.unreadCount === 'number' ? dialog.unreadCount : 0,
unreadMentionsCount: typeof dialog.unreadMentionsCount === 'number' ? dialog.unreadMentionsCount : 0,
topMessageId: dialog.raw.topMessage,
});
if (results.length >= effectiveLimit) {
break;
}
}
return results;