Repository navigation
Expand file tree
/
Copy pathmessage-sync-service.js
More file actions
5283 lines (4861 loc) · 179 KB
/
Copy pathmessage-sync-service.js
File metadata and controls
5283 lines (4861 loc) · 179 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 Database from 'better-sqlite3';
import path from 'path';
import fs from 'fs';
import { setTimeout as delay } from 'timers/promises';
import { Message, MtArgumentError, MtPeerNotFoundError, PeersIndex, _messageMediaFromTl, getMarkedPeerId } from '@mtcute/core';
import { isChatGone, normalizeChannelId, summarizeMedia } from './telegram-client.js';
import { resolveStoreDir, resolveStorePaths } from './core/store.js';
import { parseRequiredWaitSeconds } from './core/send-utils.js';
import { chatIdSql, isChatId } from './core/chat-key.js';
const DEFAULT_DB_PATH = resolveStorePaths(resolveStoreDir()).dbPath;
const DEFAULT_TARGET_MESSAGES = 1000;
const SEARCH_INDEX_VERSION = 2;
const MEDIA_INDEX_VERSION = 1;
const METADATA_TTL_MS = 7 * 24 * 60 * 60 * 1000;
const JOB_STATUS = {
PENDING: 'pending',
IN_PROGRESS: 'in_progress',
IDLE: 'idle',
ERROR: 'error',
};
// A repair Telegram refuses for good, such as in a chat the account has left.
const REPAIR_STATUS = { ...JOB_STATUS, SKIPPED: 'skipped' };
// A job or repair with work ahead of it: an error is retried when the server starts.
const UNFINISHED_STATUSES = new Set([JOB_STATUS.PENDING, JOB_STATUS.IN_PROGRESS, JOB_STATUS.ERROR]);
// Tables mergeChatKey moves by rules of their own rather than as plain copies.
const MERGED_APART = new Set(['messages', 'message_links', 'message_media', 'jobs', 'archive_repairs']);
// Out of reach for this long, Telegram's catch-up is no longer trusted to be complete.
const LONG_OUTAGE_MS = 5 * 60 * 1000;
const PERIODIC_CHECK_INTERVAL_MS = 30 * 1000;
// How long after a message was named deleted or skipped to read it again.
const RECHECK_AFTER_MS = [60 * 1000, 10 * 60 * 1000, 60 * 60 * 1000];
// A message Telegram hides is a fresh one, so ids further than this from the cursor or
// from the next message, and those next to older messages, are not checked.
const RECHECK_MAX_ID_DISTANCE = 100;
const RECHECK_RECENT_MS = 10 * 60 * 1000;
// A read that keeps failing for this long, on a running server, is not going to work.
const RECHECK_GIVE_UP_MS = 24 * 60 * 60 * 1000;
const PERIODIC_RECONCILE_MS = 60 * 60 * 1000;
// A chat missing from the dialog list but still joined is asked about again this often.
const MEMBERSHIP_RECHECK_MS = 24 * 60 * 60 * 1000;
const CONNECTION_CHECK_TIMEOUT_MS = 20 * 1000;
const RETRY_BASE_MS = 60 * 1000;
// A repair walks history one page per queue step, so jobs and gap fills never wait
// behind it for long.
const REPAIR_PAGE_SIZE = 100;
const REPAIR_PAGE_DELAY_MS = 1000;
const RETRY_MAX_MS = 60 * 60 * 1000;
// A username Telegram did not find is asked about again after this long.
const USERNAME_RECHECK_MS = 24 * 60 * 60 * 1000;
// Marked channel ids are below this. A text prefix would also match some basic groups.
const MAX_MARKED_CHANNEL_ID = -1000000000000;
const URL_PATTERN = /https?:\/\/[^\s<>"')]+/giu;
const FILE_NAME_PATTERN = /\b[\w.\-]+\.[a-z0-9]{2,7}\b/iu;
const MAX_FILENAME_SCAN_DEPTH = 5;
const MEDIA_COLUMNS = `
message_media.media_type,
message_media.file_id,
message_media.unique_file_id,
message_media.file_name,
message_media.mime_type,
message_media.file_size,
message_media.width,
message_media.height,
message_media.duration,
message_media.extra_json
`;
const MEDIA_JOIN = `
LEFT JOIN message_media
ON message_media.channel_id = messages.channel_id
AND message_media.message_id = messages.message_id
`;
const TAG_RULES = [
{
tag: 'ai',
patterns: [
/\bai\b/iu,
/\bartificial intelligence\b/iu,
/\bmachine learning\b/iu,
/\bml\b/iu,
/\bgpt\b/iu,
/\bllm\b/iu,
/нейросет/iu,
/искусственн/iu,
/машинн(ое|ого) обучен/iu,
],
},
{
tag: 'memes',
patterns: [
/\bmeme(s)?\b/iu,
/мем/iu,
/юмор/iu,
/шутк/iu,
/\blol\b/iu,
/\bkek\b/iu,
],
},
{
tag: 'news',
patterns: [
/\bnews\b/iu,
/новост/iu,
/сводк/iu,
/дайджест/iu,
/\bbreaking\b/iu,
],
},
{
tag: 'crypto',
patterns: [
/\bcrypto\b/iu,
/\bbitcoin\b/iu,
/\bbtc\b/iu,
/\beth\b/iu,
/\bblockchain\b/iu,
/крипт/iu,
/блокчейн/iu,
],
},
{
tag: 'jobs',
patterns: [
/\bjob(s)?\b/iu,
/ваканс/iu,
/работа/iu,
/\bhiring\b/iu,
/\bcareer\b/iu,
],
},
{
tag: 'events',
patterns: [
/\bevent(s)?\b/iu,
/мероприяти/iu,
/встреч/iu,
/митап/iu,
/конференц/iu,
],
},
{
tag: 'travel',
patterns: [
/\btravel\b/iu,
/\btrip\b/iu,
/путешеств/iu,
/туризм/iu,
],
},
{
tag: 'finance',
patterns: [
/\bfinance\b/iu,
/финанс/iu,
/инвест/iu,
/\bstock(s)?\b/iu,
/акци/iu,
],
},
{
tag: 'real_estate',
patterns: [
/\breal estate\b/iu,
/недвижим/iu,
/аренд/iu,
/\brent\b/iu,
/квартир/iu,
],
},
{
tag: 'education',
patterns: [
/\bcourse(s)?\b/iu,
/курс/iu,
/обучен/iu,
/учеб/iu,
],
},
{
tag: 'tech',
patterns: [
/\btech\b/iu,
/технол/iu,
/\bsoftware\b/iu,
/разработк/iu,
/\bdev\b/iu,
],
},
{
tag: 'marketing',
patterns: [
/\bmarketing\b/iu,
/маркетинг/iu,
/\bsmm\b/iu,
/реклам/iu,
],
},
{
tag: 'gaming',
patterns: [
/\bgam(e|ing|es)\b/iu,
/игр/iu,
/стрим/iu,
],
},
{
tag: 'sports',
patterns: [
/\bsport(s)?\b/iu,
/спорт/iu,
/футбол/iu,
/\bnba\b/iu,
],
},
{
tag: 'health',
patterns: [
/\bhealth\b/iu,
/здоров/iu,
/медиц/iu,
/fitness/iu,
/фитнес/iu,
],
},
];
function normalizeChannelKey(channelId) {
return String(normalizeChannelId(channelId));
}
// A username gets here only through resolveChatKey, which turns it into the id.
function chatIdForWrite(channelId) {
const key = normalizeChannelKey(channelId);
if (!isChatId(key)) {
throw new Error(`Chat ${key} has to be resolved to its Telegram id before it is archived.`);
}
return key;
}
const USERNAME_NOT_FOUND_ERRORS = new Set(['USERNAME_INVALID', 'USERNAME_NOT_OCCUPIED']);
function isChatNotFound(error) {
// mtcute says the same of a chat it found but cannot reach yet, which passes.
if (error instanceof MtPeerNotFoundError && /no access hash/.test(error.message ?? '')) {
return false;
}
return error instanceof MtArgumentError || USERNAME_NOT_FOUND_ERRORS.has(error?.text) || isChatGone(error);
}
function chatNotFound(key, cause) {
const error = new Error(`Telegram has no chat ${key}.`, { cause });
error.code = 'CHAT_NOT_FOUND';
return error;
}
// Whether Telegram's answer for a username is the chat that has it now. mtcute answers
// from its own cache first, which can still name the account that had it before.
function peerHasUsername(peer, key) {
const wanted = key.replace(/^@/, '').toLowerCase();
if (wanted === 'me' || wanted === 'self') {
return true;
}
const names = (peer?.usernames ?? []).map((entry) => entry.username?.toLowerCase());
return names.includes(wanted) || peer?.username?.toLowerCase() === wanted;
}
// Only in channels and supergroups, private chats and basic groups share them.
function hasSequentialIds(channelId) {
return Number(channelId) <= MAX_MARKED_CHANNEL_ID;
}
// Telegram refusing this chat will not change soon, unlike a dropped connection, an
// expired session (401) or a failure of its own (5xx), which say nothing about the message.
function isRefusedRead(error) {
const code = error?.code;
return (code >= 400 && code < 500 && code !== 401) || error instanceof MtPeerNotFoundError;
}
// mtcute builds the message of an updateShortSentMessage from the response alone,
// which has no reply header and no link preview. Telegram answers that way only to
// text sent outside channels, so any such send may need a full copy afterwards.
function mayLackFullContent(message) {
return message.raw?.peerId?._ !== 'peerChannel' && !message.raw?.media;
}
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 parseIsoDate(value) {
if (!value) return null;
const date = value instanceof Date ? value : new Date(value);
const ts = date.getTime();
if (Number.isNaN(ts)) {
throw new Error('minDate must be a valid ISO-8601 string');
}
return Math.floor(ts / 1000);
}
function toIsoString(dateSeconds) {
if (!dateSeconds) return null;
return new Date(dateSeconds * 1000).toISOString();
}
function formatMediaRow(row) {
if (!row) {
return null;
}
const hasMedia = row.media_type || row.file_id || row.unique_file_id || row.file_name;
if (!hasMedia) {
return null;
}
const extras = safeParseJson(row.extra_json);
return {
type: row.media_type ?? null,
fileId: row.file_id ?? null,
uniqueFileId: row.unique_file_id ?? null,
fileName: row.file_name ?? null,
mimeType: row.mime_type ?? null,
fileSize: typeof row.file_size === 'number' ? row.file_size : row.file_size ?? null,
width: typeof row.width === 'number' ? row.width : row.width ?? null,
height: typeof row.height === 'number' ? row.height : row.height ?? null,
duration: typeof row.duration === 'number' ? row.duration : row.duration ?? null,
extras: extras ?? null,
};
}
function formatArchivedRow(row) {
const isBot = row.from_is_bot;
return {
channelId: row.channel_id,
peerTitle: row.peer_title ?? null,
username: row.username ?? null,
messageId: row.message_id,
date: row.date ? new Date(row.date * 1000).toISOString() : null,
fromId: row.from_id ?? null,
fromUsername: row.from_username ?? null,
fromDisplayName: row.from_display_name ?? null,
fromPeerType: row.from_peer_type ?? null,
fromIsBot: typeof isBot === 'number' ? Boolean(isBot) : isBot ?? null,
text: row.text ?? '',
media: formatMediaRow(row),
topicId: row.topic_id ?? null,
};
}
function normalizeTagsList(raw) {
if (!raw) {
return [];
}
if (Array.isArray(raw)) {
return raw.filter(Boolean);
}
if (typeof raw === 'string') {
return raw
.split(',')
.map((tag) => tag.trim())
.filter(Boolean);
}
return [];
}
function formatContactRow(row) {
if (!row) {
return null;
}
const isBot = row.is_bot;
const isContact = row.is_contact;
const tags = normalizeTagsList(row.tags);
return {
userId: row.user_id,
peerType: row.peer_type ?? null,
username: row.username ?? null,
displayName: row.display_name ?? null,
phone: row.phone ?? null,
isContact: typeof isContact === 'number' ? Boolean(isContact) : isContact ?? null,
isBot: typeof isBot === 'number' ? Boolean(isBot) : isBot ?? null,
alias: row.alias ?? null,
notes: row.notes ?? null,
tags,
};
}
function extractLinksFromText(text) {
if (!text || typeof text !== 'string') {
return [];
}
const matches = text.match(URL_PATTERN) ?? [];
const results = new Set();
for (const raw of matches) {
const cleaned = raw.replace(/[),.!?;:]+$/g, '');
if (cleaned) {
results.add(cleaned);
}
}
return [...results];
}
function extractFileNamesFromText(text) {
if (!text || typeof text !== 'string') {
return [];
}
const matches = text.match(new RegExp(FILE_NAME_PATTERN.source, 'giu')) ?? [];
return matches;
}
function collectFileNames(value, results, depth = 0) {
if (!value || depth > MAX_FILENAME_SCAN_DEPTH) {
return;
}
if (Array.isArray(value)) {
for (const entry of value) {
collectFileNames(entry, results, depth + 1);
}
return;
}
if (typeof value !== 'object') {
return;
}
for (const [key, entry] of Object.entries(value)) {
if ((key === 'fileName' || key === 'file_name') && typeof entry === 'string') {
results.add(entry);
continue;
}
if (key === 'name' && typeof entry === 'string' && FILE_NAME_PATTERN.test(entry)) {
results.add(entry);
continue;
}
collectFileNames(entry, results, depth + 1);
}
}
function extractFileNames(message) {
const results = new Set();
const textFiles = extractFileNamesFromText(message?.text ?? message?.message ?? null);
for (const entry of textFiles) {
results.add(entry);
}
if (message?.raw) {
collectFileNames(message.raw, results);
}
return [...results];
}
function buildSenderText(message) {
const parts = [];
if (message?.from_username) {
parts.push(String(message.from_username));
}
if (message?.from_display_name) {
parts.push(String(message.from_display_name));
}
if (message?.from_id) {
parts.push(String(message.from_id));
}
return parts.length ? parts.join(' ') : null;
}
function buildTopicText(message) {
if (!message) {
return null;
}
if (typeof message.topic_title === 'string' && message.topic_title.trim()) {
return message.topic_title.trim();
}
if (message.topic_id !== null && message.topic_id !== undefined) {
return String(message.topic_id);
}
return null;
}
function buildLinkEntries(links) {
const entries = [];
for (const url of links) {
let domain = null;
try {
domain = new URL(url).hostname || null;
} catch (error) {
domain = null;
}
entries.push({ url, domain });
}
return entries;
}
function buildSearchFields(message) {
const links = extractLinksFromText(message?.text ?? message?.message ?? null);
const files = extractFileNames(message);
const sender = buildSenderText(message);
const topic = buildTopicText(message);
return {
linksText: links.length ? links.join(' ') : null,
filesText: files.length ? files.join(' ') : null,
senderText: sender,
topicText: topic,
linkEntries: buildLinkEntries(links),
};
}
function safeParseJson(value) {
if (!value || typeof value !== 'string') {
return null;
}
try {
return JSON.parse(value);
} catch (error) {
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 buildMediaRecord(summary) {
if (!summary || typeof summary !== 'object') {
return null;
}
const mediaType = normalizeMediaText(summary.type ?? summary.media_type);
if (!mediaType) {
return null;
}
let extraJson = null;
if (summary.extras && typeof summary.extras === 'object') {
try {
extraJson = JSON.stringify(summary.extras);
} catch (error) {
extraJson = null;
}
} else if (typeof summary.extra_json === 'string') {
extraJson = summary.extra_json;
}
return {
media_type: mediaType,
file_id: normalizeMediaText(summary.fileId ?? summary.file_id),
unique_file_id: normalizeMediaText(summary.uniqueFileId ?? summary.unique_file_id),
file_name: normalizeMediaText(summary.fileName ?? summary.file_name),
mime_type: normalizeMediaText(summary.mimeType ?? summary.mime_type),
file_size: normalizeMediaNumber(summary.fileSize ?? summary.file_size),
width: normalizeMediaNumber(summary.width),
height: normalizeMediaNumber(summary.height),
duration: normalizeMediaNumber(summary.duration),
extra_json: extraJson,
};
}
function extractMediaSummary(message) {
if (!message || typeof message !== 'object') {
return null;
}
if (message.media) {
const summary = summarizeMedia(message.media);
if (summary) {
return summary;
}
}
const rawMedia = message.raw?.media;
if (!rawMedia || typeof rawMedia !== 'object') {
return null;
}
try {
const parsed = _messageMediaFromTl(null, rawMedia);
return summarizeMedia(parsed);
} catch (error) {
return null;
}
}
function normalizeTag(tag) {
if (!tag) return null;
const normalized = String(tag).trim().toLowerCase();
return normalized.replace(/\s+/g, ' ');
}
function buildTagText({ peerTitle, username, about }) {
return [peerTitle, username, about].filter(Boolean).join(' ').trim();
}
function classifyTags(text) {
if (!text) return [];
const results = [];
for (const rule of TAG_RULES) {
let hits = 0;
for (const pattern of rule.patterns) {
if (pattern.test(text)) {
hits += 1;
}
}
if (hits > 0) {
const confidence = Math.min(1, hits / 3);
results.push({ tag: rule.tag, confidence });
}
}
return results;
}
export default class MessageSyncService {
constructor(telegramClient, options = {}) {
this.telegramClient = telegramClient;
this.dbPath = path.resolve(options.dbPath || DEFAULT_DB_PATH);
this.batchSize = options.batchSize || 100;
this.interJobDelayMs = options.interJobDelayMs || 3000;
this.interBatchDelayMs = options.interBatchDelayMs || 1000;
this.repairPageDelayMs = options.repairPageDelayMs ?? REPAIR_PAGE_DELAY_MS;
// ServerStats of the running server; see core/server-stats.js.
this.stats = options.stats ?? null;
this.processing = false;
this.stopRequested = false;
this.recheckingMessages = false;
this.realtimeActive = false;
this.realtimeHandlers = null;
this.unsubscribeChannelTooLong = null;
this.unsubscribeClientReplaced = null;
// Channels whose gap failed, as { attempts, retryAt }. The gap stays recorded, and
// the queue gets on with other work instead of spinning on it.
this.gapRetries = new Map();
this.gapRetryTimer = null;
// Until the next comparison with the dialog list, and from the first sign of a lost
// connection until Telegram answers again, updates leave last_message_id where it is.
this.reconcileNeeded = false;
this.reconcilePromise = null;
this.reconcileAgain = false;
this.disconnectedAt = null;
this.disconnectCount = 0;
this.confirmingConnection = false;
this.lastCheckAt = Date.now();
this.lastErroredJobsRetryAt = Date.now();
this.lastReconcileAt = Date.now();
this.periodicCheckTimer = null;
// Id of the job this instance set to `in_progress` while running the queue.
// Only the queue worker owns its in-flight job; `shutdown()` requeues just
// this one so it resumes next run, without touching jobs other processes own.
this.ownedInProgressJobId = null;
// The run of migrateUsernameKeys under way, which the queue waits for, and the
// queue's step in flight, which the migration waits for.
this.usernameKeyMigration = null;
this.queueStep = null;
// Peers resolveChatKey found by username, by id, until a write describes the chat.
this.resolvedPeers = new Map();
this._initDatabase();
}
_initDatabase() {
const dir = path.dirname(this.dbPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
this.db = new Database(this.dbPath);
this.db.pragma('journal_mode = WAL');
const newArchive = !this.db.prepare(`
SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages'
`).get();
this.db.exec(`
CREATE TABLE IF NOT EXISTS channels (
channel_id TEXT PRIMARY KEY,
peer_title TEXT,
peer_type TEXT,
chat_type TEXT,
is_forum INTEGER,
username TEXT,
sync_enabled INTEGER NOT NULL DEFAULT 1,
last_message_id INTEGER DEFAULT 0,
last_message_date TEXT,
oldest_message_id INTEGER,
oldest_message_date TEXT,
gap_after_message_id INTEGER,
newer_sync_pending INTEGER NOT NULL DEFAULT 0,
in_dialogs INTEGER,
sync_off_reason TEXT,
membership TEXT,
membership_checked_at INTEGER,
sync_by_user INTEGER,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS channel_metadata (
channel_id TEXT PRIMARY KEY,
about TEXT,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS channel_metadata_updated_idx
ON channel_metadata (updated_at);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS channel_tags (
channel_id TEXT NOT NULL,
tag TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'manual',
confidence REAL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (channel_id, tag, source)
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS channel_tags_tag_idx
ON channel_tags (tag);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT '${JOB_STATUS.PENDING}',
target_message_count INTEGER DEFAULT ${DEFAULT_TARGET_MESSAGES},
message_count INTEGER DEFAULT 0,
cursor_message_id INTEGER,
cursor_message_date TEXT,
backfill_min_date TEXT,
last_synced_at TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
error TEXT
);
`);
this._ensureChannelColumn('chat_type', 'TEXT');
this._ensureChannelColumn('is_forum', 'INTEGER');
this._ensureChannelColumn('gap_after_message_id', 'INTEGER');
// 1 when the last full dialog list had the chat, 0 when it did not, NULL before any.
this._ensureChannelColumn('in_dialogs', 'INTEGER');
// 'left' when the server turned sync off because Telegram said the account left.
this._ensureChannelColumn('sync_off_reason', 'TEXT');
// What Telegram last said about a chat missing from the dialog list ('member', 'left',
// 'gone' or 'unknown'), and when (ms).
this._ensureChannelColumn('membership', 'TEXT');
this._ensureChannelColumn('membership_checked_at', 'INTEGER');
// 1 when the user asked for the chat (channels watch, backfill --chat): a public
// channel can be archived without joining it, and Telegram calls that left.
this._ensureChannelColumn('sync_by_user', 'INTEGER');
if (this._ensureChannelColumn('newer_sync_pending', 'INTEGER NOT NULL DEFAULT 0')) {
// Jobs queued before this column existed still have their newer sync ahead of them.
this.db.prepare(`
UPDATE channels
SET newer_sync_pending = 1
WHERE channel_id IN (SELECT channel_id FROM jobs WHERE status != ?)
`).run(JOB_STATUS.IDLE);
}
this._ensureJobColumn('target_message_count', `INTEGER DEFAULT ${DEFAULT_TARGET_MESSAGES}`);
this._ensureJobColumn('message_count', 'INTEGER DEFAULT 0');
this._ensureJobColumn('cursor_message_id', 'INTEGER');
this._ensureJobColumn('cursor_message_date', 'TEXT');
this._ensureJobColumn('backfill_min_date', 'TEXT');
this._ensureJobColumn('started_at', 'TEXT');
this.db.exec(`
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY,
peer_type TEXT,
username TEXT,
display_name TEXT,
phone TEXT,
is_contact INTEGER,
is_bot INTEGER,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`);
this._ensureUserColumn('phone', 'TEXT');
this._ensureUserColumn('is_contact', 'INTEGER');
this.db.exec(`
CREATE INDEX IF NOT EXISTS users_username_idx
ON users (username);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS users_phone_idx
ON users (phone);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS contacts (
user_id TEXT PRIMARY KEY,
alias TEXT,
notes TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS contact_tags (
user_id TEXT NOT NULL,
tag TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, tag)
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS contact_tags_tag_idx
ON contact_tags (tag);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS contact_tags_user_idx
ON contact_tags (user_id);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id TEXT NOT NULL,
message_id INTEGER NOT NULL,
topic_id INTEGER,
date INTEGER,
from_id TEXT,
text TEXT,
links TEXT,
files TEXT,
sender TEXT,
topic TEXT,
raw_json TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(channel_id, message_id)
);
`);
this._ensureMessageColumn('topic_id', 'INTEGER');
this._ensureMessageColumn('links', 'TEXT');
this._ensureMessageColumn('files', 'TEXT');
this._ensureMessageColumn('sender', 'TEXT');
this._ensureMessageColumn('topic', 'TEXT');
this.db.exec(`
CREATE TABLE IF NOT EXISTS sent_messages_to_refetch (
channel_id TEXT NOT NULL,
message_id INTEGER NOT NULL,
PRIMARY KEY (channel_id, message_id)
);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS messages_to_recheck (
channel_id TEXT NOT NULL,
message_id INTEGER NOT NULL,
queued_at INTEGER NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (channel_id, message_id)
);
`);
// One repair per chat: a walk of its history from the newest message down to a
// bound, writing back what the archive lacks. cursor_message_id is where the
// next page starts, so a restarted server carries on. A dry run writes nothing and
// counts in added_count what it would have added.
this.db.exec(`
CREATE TABLE IF NOT EXISTS archive_repairs (
channel_id TEXT PRIMARY KEY,
status TEXT NOT NULL,
after_message_id INTEGER NOT NULL DEFAULT 0,
since_date INTEGER,
cursor_message_id INTEGER,
checked_count INTEGER NOT NULL DEFAULT 0,
added_count INTEGER NOT NULL DEFAULT 0,
error TEXT,
generation INTEGER NOT NULL DEFAULT 0,
dry_run INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`);
if (!this.db.prepare('PRAGMA table_info(archive_repairs)').all().some((col) => col.name === 'dry_run')) {
this.db.exec('ALTER TABLE archive_repairs ADD COLUMN dry_run INTEGER NOT NULL DEFAULT 0');
}
// Chats still stored under a username that the last try could not move to their
// Telegram id, and why: Telegram did not find it, the try failed, or the messages
// under it name another chat than the one Telegram gave.
this.db.exec(`
CREATE TABLE IF NOT EXISTS username_key_checks (
chat_key TEXT PRIMARY KEY,
outcome TEXT NOT NULL,
detail TEXT,
checked_at INTEGER NOT NULL
);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS message_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
channel_id TEXT NOT NULL,
message_id INTEGER NOT NULL,
url TEXT NOT NULL,
domain TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(channel_id, message_id, url)
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS message_links_url_idx
ON message_links (url);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS message_links_domain_idx
ON message_links (domain);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS message_media (
channel_id TEXT NOT NULL,
message_id INTEGER NOT NULL,
media_type TEXT,
file_id TEXT,
unique_file_id TEXT,
file_name TEXT,
mime_type TEXT,
file_size INTEGER,
width INTEGER,
height INTEGER,
duration INTEGER,
extra_json TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (channel_id, message_id)
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS message_media_type_idx
ON message_media (media_type);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS message_media_mime_idx
ON message_media (mime_type);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS message_media_name_idx
ON message_media (file_name);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS topics (
channel_id TEXT NOT NULL,
topic_id INTEGER NOT NULL,
title TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (channel_id, topic_id)
);
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS topics_title_idx
ON topics (title);
`);
this.db.exec(`
CREATE TABLE IF NOT EXISTS search_meta (
key TEXT PRIMARY KEY,
value TEXT
);
`);
if (newArchive) {
this._setRepairNotNeeded('archive started with the fixes');
}