-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmessage-sync-service.js
More file actions
3545 lines (3216 loc) · 102 KB
/
message-sync-service.js
File metadata and controls
3545 lines (3216 loc) · 102 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, PeersIndex, _messageMediaFromTl } from '@mtcute/core';
import { normalizeChannelId, summarizeMedia } from './telegram-client.js';
import { resolveStoreDir, resolveStorePaths } from './core/store.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',
};
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));
}
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.processing = false;
this.stopRequested = false;
this.realtimeActive = false;
this.realtimeHandlers = null;
this.unsubscribeChannelTooLong = null;
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');
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,
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._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.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 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
);
`);
const searchSchema = this.db.prepare(`
SELECT sql FROM sqlite_master
WHERE type = 'table' AND name = 'message_search'
`).get();
const storedVersion = this.db.prepare(`
SELECT value FROM search_meta WHERE key = 'search_index_version'
`).get()?.value;
const storedMediaVersion = this.db.prepare(`
SELECT value FROM search_meta WHERE key = 'media_index_version'
`).get()?.value;
const needsVersionRebuild = Number(storedVersion ?? 0) !== SEARCH_INDEX_VERSION;
const needsMediaRebuild = Number(storedMediaVersion ?? 0) !== MEDIA_INDEX_VERSION;
const needsSearchRecreate = !searchSchema?.sql
|| !searchSchema.sql.includes("tokenize='unicode61'")
|| !searchSchema.sql.includes('links')
|| needsVersionRebuild;
const shouldRebuildSearch = needsSearchRecreate;
if (needsSearchRecreate) {
this.db.exec(`
DROP TRIGGER IF EXISTS messages_ai;
DROP TRIGGER IF EXISTS messages_ad;
DROP TRIGGER IF EXISTS messages_au;
DROP TABLE IF EXISTS message_search;
`);
}
if (needsVersionRebuild || needsMediaRebuild) {
this._backfillSearchFields({ rebuildMedia: needsMediaRebuild });
}
this.db.exec(`
CREATE VIRTUAL TABLE IF NOT EXISTS message_search USING fts5(
text,
links,
files,
sender,
topic,
content='messages',
content_rowid='id',
tokenize='unicode61'
);
`);
this.db.exec(`
CREATE TRIGGER IF NOT EXISTS messages_ai
AFTER INSERT ON messages BEGIN
INSERT INTO message_search(rowid, text, links, files, sender, topic)
VALUES (
new.id,
COALESCE(new.text, ''),
COALESCE(new.links, ''),
COALESCE(new.files, ''),
COALESCE(new.sender, ''),
COALESCE(new.topic, '')
);
END;
`);
this.db.exec(`
CREATE TRIGGER IF NOT EXISTS messages_ad
AFTER DELETE ON messages BEGIN
INSERT INTO message_search(message_search, rowid, text, links, files, sender, topic)
VALUES (
'delete',
old.id,
COALESCE(old.text, ''),
COALESCE(old.links, ''),
COALESCE(old.files, ''),
COALESCE(old.sender, ''),
COALESCE(old.topic, '')
);
END;
`);
this.db.exec(`
CREATE TRIGGER IF NOT EXISTS messages_au
AFTER UPDATE ON messages BEGIN
INSERT INTO message_search(message_search, rowid, text, links, files, sender, topic)
VALUES (
'delete',
old.id,
COALESCE(old.text, ''),
COALESCE(old.links, ''),
COALESCE(old.files, ''),
COALESCE(old.sender, ''),
COALESCE(old.topic, '')
);
INSERT INTO message_search(rowid, text, links, files, sender, topic)
VALUES (
new.id,
COALESCE(new.text, ''),
COALESCE(new.links, ''),
COALESCE(new.files, ''),
COALESCE(new.sender, ''),
COALESCE(new.topic, '')
);
END;
`);
this.db.exec(`
CREATE INDEX IF NOT EXISTS messages_channel_topic_idx
ON messages (channel_id, topic_id, message_id);
`);
this.db.exec(`
INSERT OR IGNORE INTO channels (channel_id, sync_enabled)
SELECT channel_id, 1
FROM jobs
WHERE channel_id IS NOT NULL;
`);
this.upsertChannelStmt = this.db.prepare(`
INSERT INTO channels (channel_id, peer_title, peer_type, chat_type, is_forum, username, updated_at)
VALUES (@channel_id, @peer_title, @peer_type, @chat_type, @is_forum, @username, CURRENT_TIMESTAMP)
ON CONFLICT(channel_id) DO UPDATE SET
peer_title = excluded.peer_title,
peer_type = COALESCE(excluded.peer_type, channels.peer_type),
chat_type = COALESCE(excluded.chat_type, channels.chat_type),
is_forum = COALESCE(excluded.is_forum, channels.is_forum),
username = COALESCE(excluded.username, channels.username),
updated_at = CURRENT_TIMESTAMP
RETURNING channel_id, sync_enabled;
`);
this.upsertChannelMetadataStmt = this.db.prepare(`
INSERT INTO channel_metadata (channel_id, about, updated_at)
VALUES (@channel_id, @about, CURRENT_TIMESTAMP)
ON CONFLICT(channel_id) DO UPDATE SET
about = excluded.about,
updated_at = CURRENT_TIMESTAMP
`);
this.insertChannelTagStmt = this.db.prepare(`
INSERT INTO channel_tags (channel_id, tag, source, confidence, updated_at)
VALUES (@channel_id, @tag, @source, @confidence, CURRENT_TIMESTAMP)
ON CONFLICT(channel_id, tag, source) DO UPDATE SET
confidence = excluded.confidence,
updated_at = CURRENT_TIMESTAMP
`);
this.deleteChannelTagsStmt = this.db.prepare(`
DELETE FROM channel_tags
WHERE channel_id = ? AND source = ?
`);
this.upsertUserStmt = this.db.prepare(`
INSERT INTO users (
user_id,
peer_type,
username,
display_name,
phone,
is_contact,
is_bot,
updated_at
)
VALUES (
@user_id,
@peer_type,
@username,
@display_name,
@phone,
@is_contact,
@is_bot,
CURRENT_TIMESTAMP
)
ON CONFLICT(user_id) DO UPDATE SET
peer_type = COALESCE(excluded.peer_type, users.peer_type),
username = COALESCE(excluded.username, users.username),
display_name = COALESCE(excluded.display_name, users.display_name),
phone = COALESCE(excluded.phone, users.phone),
is_contact = COALESCE(excluded.is_contact, users.is_contact),
is_bot = COALESCE(excluded.is_bot, users.is_bot),
updated_at = CURRENT_TIMESTAMP
`);
this.ensureUserStmt = this.db.prepare(`
INSERT OR IGNORE INTO users (user_id, peer_type, updated_at)
VALUES (?, 'user', CURRENT_TIMESTAMP)
`);
this.upsertContactAliasStmt = this.db.prepare(`
INSERT INTO contacts (user_id, alias, updated_at)
VALUES (@user_id, @alias, CURRENT_TIMESTAMP)
ON CONFLICT(user_id) DO UPDATE SET
alias = excluded.alias,
updated_at = CURRENT_TIMESTAMP
`);
this.upsertContactNotesStmt = this.db.prepare(`
INSERT INTO contacts (user_id, notes, updated_at)
VALUES (@user_id, @notes, CURRENT_TIMESTAMP)
ON CONFLICT(user_id) DO UPDATE SET
notes = excluded.notes,
updated_at = CURRENT_TIMESTAMP
`);
this.insertContactTagStmt = this.db.prepare(`
INSERT OR IGNORE INTO contact_tags (user_id, tag, updated_at)
VALUES (@user_id, @tag, CURRENT_TIMESTAMP)
`);
this.deleteContactTagStmt = this.db.prepare(`
DELETE FROM contact_tags
WHERE user_id = ? AND tag = ?