-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·3445 lines (3207 loc) · 113 KB
/
cli.js
File metadata and controls
executable file
·3445 lines (3207 loc) · 113 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
#!/usr/bin/env node
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawn, spawnSync } from 'child_process';
import { setTimeout as delay } from 'timers/promises';
import { fileURLToPath } from 'url';
import readline from 'readline';
import { Command } from 'commander';
import { acquireStoreLock, acquireReadLock, readStoreLock } from './store-lock.js';
import { loadConfig, normalizeConfig, saveConfig, validateConfig } from './core/config.js';
import { createServices } from './core/services.js';
import { resolveStoreDir } from './core/store.js';
const CLI_PATH = fileURLToPath(import.meta.url);
const SERVICE_STATE_FILE = 'service-state.json';
const LAUNCHD_LABEL = 'com.kfastov.tgcli';
const SYSTEMD_SERVICE_NAME = 'tgcli';
const CONFIG_SPECS = [
{ key: 'apiId', path: ['apiId'], type: 'number' },
{ key: 'apiHash', path: ['apiHash'], type: 'string', secret: true },
{ key: 'phoneNumber', path: ['phoneNumber'], type: 'string' },
{ key: 'mcp.enabled', path: ['mcp', 'enabled'], type: 'boolean' },
{ key: 'mcp.host', path: ['mcp', 'host'], type: 'string' },
{ key: 'mcp.port', path: ['mcp', 'port'], type: 'number' },
];
const CLI_PROGRAM = buildProgram();
function buildProgram() {
const program = new Command();
program
.name('tgcli')
.description('Telegram CLI + MCP server')
.usage('[options] <command>')
.option('--json', 'Machine-readable output')
.option('--timeout <duration>', 'Wall-clock timeout (e.g. 30s, 5m)')
.version(readVersion(), '--version', 'Print version and exit')
.showHelpAfterError(true);
const auth = program.command('auth').description('Authentication and session setup');
auth
.option('--follow', 'Continue syncing after login')
.action(withGlobalOptions((globalFlags, options) =>
runAuthLogin(globalFlags, options),
));
auth
.command('status')
.description('Show auth status')
.action(withGlobalOptions((globalFlags) => runAuthStatus(globalFlags)));
auth
.command('logout')
.description('Log out of Telegram')
.action(withGlobalOptions((globalFlags) => runAuthLogout(globalFlags)));
const config = program.command('config').description('View and edit config');
config
.command('list')
.description('List config values')
.action(withGlobalOptions((globalFlags) => runConfigList(globalFlags)));
config
.command('get')
.description('Get a config value')
.argument('<key>', 'Config key')
.action(withGlobalOptions((globalFlags, key) => runConfigGet(globalFlags, key)));
config
.command('set')
.description('Set a config value')
.argument('<key>', 'Config key')
.argument('<value>', 'Config value')
.action(withGlobalOptions((globalFlags, key, value) => runConfigSet(globalFlags, key, value)));
config
.command('unset')
.description('Unset a config value')
.argument('<key>', 'Config key')
.action(withGlobalOptions((globalFlags, key) => runConfigUnset(globalFlags, key)));
const sync = program.command('sync').description('Archive backfill and realtime sync');
sync
.option('--once', 'Run once and exit')
.option('--follow', 'Keep syncing realtime updates')
.option('--idle-exit <duration>', 'Exit after idle period')
.action(withGlobalOptions((globalFlags, options) => runSync(globalFlags, options)));
sync
.command('status')
.description('Show sync status')
.action(withGlobalOptions((globalFlags) => runSyncStatus(globalFlags)));
const syncJobs = sync.command('jobs').description('Manage sync jobs');
syncJobs
.command('list')
.description('List sync jobs')
.option('--status <status>', 'Filter by status (pending|in_progress|idle|error)')
.option('--limit <n>', 'Limit results')
.option('--channel <id|username>', 'Filter by channel')
.action(withGlobalOptions((globalFlags, options) => runSyncJobsList(globalFlags, options)));
syncJobs
.command('add')
.description('Add a sync job')
.option('--chat <id|username>', 'Channel identifier')
.option('--depth <n>', 'Maximum messages to backfill')
.option('--min-date <iso>', 'Earliest date to backfill')
.action(withGlobalOptions((globalFlags, options) => runSyncJobsAdd(globalFlags, options)));
syncJobs
.command('retry')
.description('Retry failed jobs')
.option('--job-id <n>', 'Retry by job id')
.option('--channel <id|username>', 'Retry by channel')
.option('--all-errors', 'Retry all error jobs')
.action(withGlobalOptions((globalFlags, options) => runSyncJobsRetry(globalFlags, options)));
syncJobs
.command('cancel')
.description('Cancel jobs')
.option('--job-id <n>', 'Cancel by job id')
.option('--channel <id|username>', 'Cancel by channel')
.action(withGlobalOptions((globalFlags, options) => runSyncJobsCancel(globalFlags, options)));
program
.command('server')
.description('Run background sync service (MCP optional)')
.action(withGlobalOptions((globalFlags) => runServer(globalFlags)));
const service = program.command('service').description('Manage background service');
service
.command('install')
.description('Install service definition')
.action(withGlobalOptions((globalFlags) => runServiceInstall(globalFlags)));
service
.command('start')
.description('Start service')
.action(withGlobalOptions((globalFlags) => runServiceStart(globalFlags)));
service
.command('stop')
.description('Stop service')
.action(withGlobalOptions((globalFlags) => runServiceStop(globalFlags)));
service
.command('status')
.description('Show service status')
.action(withGlobalOptions((globalFlags) => runServiceStatus(globalFlags)));
service
.command('logs')
.description('Show service logs')
.action(withGlobalOptions((globalFlags) => runServiceLogs(globalFlags)));
program
.command('doctor')
.description('Diagnostics and sanity checks')
.option('--connect', 'Connect to Telegram for live checks')
.action(withGlobalOptions((globalFlags, options) => runDoctor(globalFlags, options)));
const channels = program.command('channels').description('Channel discovery and settings');
channels
.command('list')
.description('List channels')
.option('--query <text>', 'Search by title or username')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, options) => runChannelsList(globalFlags, options)));
channels
.command('show')
.description('Show channel info')
.option('--chat <id|username>', 'Channel identifier')
.action(withGlobalOptions((globalFlags, options) => runChannelsShow(globalFlags, options)));
channels
.command('sync')
.description('Enable or disable sync')
.option('--chat <id|username>', 'Channel identifier')
.option('--enable', 'Enable sync')
.option('--disable', 'Disable sync')
.action(withGlobalOptions((globalFlags, options) => runChannelsSync(globalFlags, options)));
const messages = program.command('messages').description('List and search messages');
messages
.command('list')
.description('List messages')
.option('--chat <id|username>', 'Channel identifier', collectList)
.option('--topic <id>', 'Forum topic id')
.option('--source <source>', 'archive|live|both')
.option('--after <iso>', 'Filter messages after date')
.option('--before <iso>', 'Filter messages before date')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, options) => runMessagesList(globalFlags, options)));
messages
.command('search')
.description('Search messages')
.argument('[query...]')
.option('--query <text>', 'Search query')
.option('--chat <id|username>', 'Channel identifier', collectList)
.option('--topic <id>', 'Forum topic id')
.option('--source <source>', 'archive|live|both')
.option('--after <iso>', 'Filter messages after date')
.option('--before <iso>', 'Filter messages before date')
.option('--limit <n>', 'Limit results')
.option('--regex <pattern>', 'Regex pattern')
.option('--tag <tag>', 'Filter by tag', collectList)
.option('--tags <tags>', 'Comma-separated tags')
.option('--case-sensitive', 'Disable case-insensitive search')
.action(withGlobalOptions((globalFlags, queryParts, options) =>
runMessagesSearch(globalFlags, queryParts, options),
));
messages
.command('show')
.description('Show a message')
.option('--chat <id|username>', 'Channel identifier')
.option('--id <msgId>', 'Message id')
.option('--source <source>', 'archive|live|both')
.action(withGlobalOptions((globalFlags, options) => runMessagesShow(globalFlags, options)));
messages
.command('context')
.description('Show message context')
.option('--chat <id|username>', 'Channel identifier')
.option('--id <msgId>', 'Message id')
.option('--source <source>', 'archive|live|both')
.option('--before <n>', 'Messages before')
.option('--after <n>', 'Messages after')
.action(withGlobalOptions((globalFlags, options) => runMessagesContext(globalFlags, options)));
const send = program.command('send').description('Send text or files');
send
.command('text')
.description('Send a text message')
.option('--to <id|username>', 'Recipient id or username')
.option('--message <text>', 'Message text')
.option('--topic <id>', 'Forum topic id')
.action(withGlobalOptions((globalFlags, options) => runSendText(globalFlags, options)));
send
.command('file')
.description('Send a file')
.option('--to <id|username>', 'Recipient id or username')
.option('--file <path>', 'File path')
.option('--caption <text>', 'Optional caption')
.option('--filename <name>', 'Override filename')
.option('--topic <id>', 'Forum topic id')
.action(withGlobalOptions((globalFlags, options) => runSendFile(globalFlags, options)));
const media = program.command('media').description('Download media');
media
.command('download')
.description('Download message media')
.option('--chat <id|username>', 'Channel identifier')
.option('--id <msgId>', 'Message id')
.option('--output <path>', 'Output file path')
.action(withGlobalOptions((globalFlags, options) => runMediaDownload(globalFlags, options)));
const topics = program.command('topics').description('Forum topics');
topics
.command('list')
.description('List topics')
.option('--chat <id|username>', 'Channel identifier')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, options) => runTopicsList(globalFlags, options)));
topics
.command('search')
.description('Search topics')
.option('--chat <id|username>', 'Channel identifier')
.option('--query <text>', 'Search query')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, options) => runTopicsSearch(globalFlags, options)));
const tags = program.command('tags').description('Channel tags');
tags
.command('set')
.description('Set channel tags')
.option('--chat <id|username>', 'Channel identifier')
.option('--tags <tags>', 'Comma-separated tags')
.option('--tag <tag>', 'Tag', collectList)
.option('--source <source>', 'Tag source')
.action(withGlobalOptions((globalFlags, options) => runTagsSet(globalFlags, options)));
tags
.command('list')
.description('List channel tags')
.option('--chat <id|username>', 'Channel identifier')
.option('--source <source>', 'Tag source')
.action(withGlobalOptions((globalFlags, options) => runTagsList(globalFlags, options)));
tags
.command('search')
.description('Search channels by tag')
.option('--tag <tag>', 'Tag to search')
.option('--source <source>', 'Tag source')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, options) => runTagsSearch(globalFlags, options)));
tags
.command('auto')
.description('Auto-tag channels')
.option('--chat <id|username>', 'Channel identifier', collectList)
.option('--limit <n>', 'Limit channels')
.option('--source <source>', 'Tag source')
.option('--no-refresh-metadata', 'Skip metadata refresh')
.action(withGlobalOptions((globalFlags, options) => runTagsAuto(globalFlags, options)));
const metadata = program.command('metadata').description('Channel metadata cache');
metadata
.command('get')
.description('Show cached metadata')
.option('--chat <id|username>', 'Channel identifier')
.action(withGlobalOptions((globalFlags, options) => runMetadataGet(globalFlags, options)));
metadata
.command('refresh')
.description('Refresh cached metadata')
.option('--chat <id|username>', 'Channel identifier', collectList)
.option('--limit <n>', 'Limit channels')
.option('--force', 'Force refresh')
.option('--only-missing', 'Only refresh missing metadata')
.action(withGlobalOptions((globalFlags, options) => runMetadataRefresh(globalFlags, options)));
const contacts = program.command('contacts').description('Contacts and people');
contacts
.command('search')
.description('Search contacts')
.argument('<query...>')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, queryParts, options) =>
runContactsSearch(globalFlags, queryParts, options),
));
contacts
.command('show')
.description('Show contact profile')
.option('--user <id>', 'User id')
.action(withGlobalOptions((globalFlags, options) => runContactsShow(globalFlags, options)));
const contactAlias = contacts.command('alias').description('Manage contact aliases');
contactAlias
.command('set')
.description('Set contact alias')
.option('--user <id>', 'User id')
.option('--alias <name>', 'Alias')
.action(withGlobalOptions((globalFlags, options) => runContactsAliasSet(globalFlags, options)));
contactAlias
.command('rm')
.description('Remove contact alias')
.option('--user <id>', 'User id')
.action(withGlobalOptions((globalFlags, options) => runContactsAliasRm(globalFlags, options)));
const contactTags = contacts.command('tags').description('Manage contact tags');
contactTags
.command('add')
.description('Add contact tags')
.option('--user <id>', 'User id')
.option('--tag <tag>', 'Tag', collectList)
.action(withGlobalOptions((globalFlags, options) => runContactsTagsAdd(globalFlags, options)));
contactTags
.command('rm')
.description('Remove contact tags')
.option('--user <id>', 'User id')
.option('--tag <tag>', 'Tag', collectList)
.action(withGlobalOptions((globalFlags, options) => runContactsTagsRm(globalFlags, options)));
const contactNotes = contacts.command('notes').description('Manage contact notes');
contactNotes
.command('set')
.description('Set contact notes')
.option('--user <id>', 'User id')
.option('--notes <text>', 'Notes')
.action(withGlobalOptions((globalFlags, options) => runContactsNotesSet(globalFlags, options)));
const groups = program.command('groups').description('Group management');
groups
.command('list')
.description('List groups')
.option('--query <text>', 'Search by title')
.option('--limit <n>', 'Limit results')
.action(withGlobalOptions((globalFlags, options) => runGroupsList(globalFlags, options)));
groups
.command('info')
.description('Show group info')
.option('--chat <id|username>', 'Group identifier')
.action(withGlobalOptions((globalFlags, options) => runGroupsInfo(globalFlags, options)));
groups
.command('rename')
.description('Rename group')
.option('--chat <id|username>', 'Group identifier')
.option('--name <text>', 'New name')
.action(withGlobalOptions((globalFlags, options) => runGroupsRename(globalFlags, options)));
const groupMembers = groups.command('members').description('Manage group members');
groupMembers
.command('add')
.description('Add members')
.option('--chat <id|username>', 'Group identifier')
.option('--user <id>', 'User id', collectList)
.action(withGlobalOptions((globalFlags, options) => runGroupMembersAdd(globalFlags, options)));
groupMembers
.command('remove')
.description('Remove members')
.option('--chat <id|username>', 'Group identifier')
.option('--user <id>', 'User id', collectList)
.action(withGlobalOptions((globalFlags, options) => runGroupMembersRemove(globalFlags, options)));
const groupInvite = groups.command('invite').description('Manage invite links');
groupInvite
.command('get')
.description('Get invite link')
.option('--chat <id|username>', 'Group identifier')
.action(withGlobalOptions((globalFlags, options) => runGroupInviteLinkGet(globalFlags, options)));
groupInvite
.command('revoke')
.description('Revoke invite link')
.option('--chat <id|username>', 'Group identifier')
.action(withGlobalOptions((globalFlags, options) => runGroupInviteLinkRevoke(globalFlags, options)));
groups
.command('join')
.description('Join via invite code')
.option('--code <invite-code>', 'Invite code')
.action(withGlobalOptions((globalFlags, options) => runGroupsJoin(globalFlags, options)));
groups
.command('leave')
.description('Leave group')
.option('--chat <id|username>', 'Group identifier')
.action(withGlobalOptions((globalFlags, options) => runGroupsLeave(globalFlags, options)));
disableHelpCommand(program);
program.addHelpText('after', '\nUse "tgcli [command] --help" for more information about a command.');
program.action(() => {
program.help();
});
return program;
}
function disableHelpCommand(command) {
command.addHelpCommand(false);
for (const subcommand of command.commands) {
disableHelpCommand(subcommand);
}
}
function getGlobalFlags(command) {
const options = command.optsWithGlobals();
const timeoutMs = options.timeout ? parseDuration(options.timeout) : null;
return {
json: Boolean(options.json),
timeout: options.timeout ?? null,
timeoutMs,
};
}
function withGlobalOptions(handler) {
return async (...args) => {
let globalFlags;
try {
const command = args[args.length - 1];
globalFlags = getGlobalFlags(command);
await handler(globalFlags, ...args);
} catch (error) {
writeError(error, globalFlags?.json ?? process.argv.includes('--json'));
process.exitCode = 1;
}
};
}
function writeJson(payload) {
process.stdout.write(`${JSON.stringify(payload, null, 2)}\n`);
}
function writeError(error, asJson) {
const message = error?.message ?? String(error);
if (asJson) {
process.stderr.write(`${JSON.stringify({ ok: false, error: message })}\n`);
} else {
process.stderr.write(`${message}\n`);
}
}
function supportsColorOutput() {
if (process.env.NO_COLOR) {
return false;
}
return Boolean(process.stdout.isTTY);
}
function colorizeNote(message) {
if (!supportsColorOutput()) {
return message;
}
return `\x1b[33m${message}\x1b[0m`;
}
function printArchiveFallbackNote(channelIds) {
if (!channelIds?.length) {
return;
}
const prefix = 'Note:';
if (channelIds.length === 1) {
const id = channelIds[0];
const message = `${prefix} no archived messages for ${id}. Showing live results. ` +
`To archive: tgcli channels sync --chat ${id} --enable; ` +
`tgcli sync jobs add --chat ${id}; ` +
'tgcli sync --once (or --follow).';
console.log(colorizeNote(message));
return;
}
const message = `${prefix} no archived messages for chats: ${channelIds.join(', ')}. ` +
'Showing live results. To archive: tgcli channels sync --chat <id> --enable; ' +
'tgcli sync jobs add --chat <id>; tgcli sync --once (or --follow).';
console.log(colorizeNote(message));
}
function parseDuration(value) {
if (typeof value !== 'string' || !value.trim()) {
return null;
}
const raw = value.trim();
const match = raw.match(/^(\d+)(ms|s|m|h)?$/i);
if (!match) {
throw new Error(`Invalid duration: ${value}`);
}
const amount = Number(match[1]);
const unit = (match[2] || 's').toLowerCase();
if (unit === 'ms') return amount;
if (unit === 's') return amount * 1000;
if (unit === 'm') return amount * 60 * 1000;
if (unit === 'h') return amount * 60 * 60 * 1000;
return amount * 1000;
}
function resolveConfigSpec(key) {
if (typeof key !== 'string' || !key.trim()) {
throw new Error('Config key is required.');
}
const normalized = key.trim().toLowerCase();
const spec = CONFIG_SPECS.find((entry) => entry.key.toLowerCase() === normalized);
if (!spec) {
const allowed = CONFIG_SPECS.map((entry) => entry.key).join(', ');
throw new Error(`Unknown config key "${key}". Supported keys: ${allowed}.`);
}
return spec;
}
function normalizeOutputValue(value) {
if (value === undefined || value === null) {
return null;
}
if (typeof value === 'string' && !value.trim()) {
return null;
}
return value;
}
function maskSecret(value) {
if (value === null || value === undefined) {
return null;
}
const str = String(value);
if (str.length <= 4) {
return '****';
}
return `${'*'.repeat(str.length - 4)}${str.slice(-4)}`;
}
function formatConfigValue(value) {
if (value === null || value === undefined) {
return 'unset';
}
if (typeof value === 'boolean') {
return value ? 'true' : 'false';
}
return String(value);
}
function getValueAtPath(target, pathParts) {
let current = target;
for (const part of pathParts) {
if (!current || typeof current !== 'object' || !(part in current)) {
return undefined;
}
current = current[part];
}
return current;
}
function setValueAtPath(target, pathParts, value) {
let current = target;
for (let index = 0; index < pathParts.length - 1; index += 1) {
const part = pathParts[index];
if (!current[part] || typeof current[part] !== 'object') {
current[part] = {};
}
current = current[part];
}
current[pathParts[pathParts.length - 1]] = value;
}
function deleteValueAtPath(target, pathParts) {
let current = target;
for (let index = 0; index < pathParts.length - 1; index += 1) {
const part = pathParts[index];
if (!current || typeof current !== 'object') {
return;
}
current = current[part];
}
if (current && typeof current === 'object') {
delete current[pathParts[pathParts.length - 1]];
}
}
function parseBooleanValue(value) {
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value !== 0;
}
if (typeof value === 'string') {
const normalized = value.trim().toLowerCase();
if (['true', '1', 'yes', 'y', 'on'].includes(normalized)) {
return true;
}
if (['false', '0', 'no', 'n', 'off'].includes(normalized)) {
return false;
}
}
throw new Error('Value must be boolean (true/false).');
}
function parseNumberValue(value, label) {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(`${label} must be a positive number.`);
}
return parsed;
}
function parseStringValue(value, label) {
if (value === undefined || value === null) {
throw new Error(`${label} is required.`);
}
const trimmed = String(value).trim();
if (!trimmed) {
throw new Error(`${label} must not be empty.`);
}
return trimmed;
}
function parseConfigValue(spec, rawValue) {
if (spec.type === 'boolean') {
return parseBooleanValue(rawValue);
}
if (spec.type === 'number') {
return parseNumberValue(rawValue, spec.key);
}
return parseStringValue(rawValue, spec.key);
}
function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, {
encoding: 'utf8',
...options,
});
return {
status: result.status ?? 1,
stdout: result.stdout ?? '',
stderr: result.stderr ?? '',
error: result.error ?? null,
};
}
function getServiceStatePath(storeDir) {
return path.join(storeDir, SERVICE_STATE_FILE);
}
function readServiceState(storeDir) {
try {
const raw = fs.readFileSync(getServiceStatePath(storeDir), 'utf8');
return JSON.parse(raw);
} catch (error) {
return null;
}
}
function getLaunchdPaths() {
const baseDir = path.join(os.homedir(), 'Library', 'LaunchAgents');
return {
plistPath: path.join(baseDir, `${LAUNCHD_LABEL}.plist`),
logPath: path.join(os.homedir(), 'Library', 'Logs', 'tgcli.log'),
errorLogPath: path.join(os.homedir(), 'Library', 'Logs', 'tgcli.error.log'),
};
}
function getSystemdPath() {
return path.join(os.homedir(), '.config', 'systemd', 'user', `${SYSTEMD_SERVICE_NAME}.service`);
}
function xmlEscape(value) {
return String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function buildLaunchdPlist({ nodePath, cliPath, envVars, logPath, errorLogPath }) {
const envEntries = Object.entries(envVars || {})
.map(([key, value]) => ` <key>${xmlEscape(key)}</key>\n <string>${xmlEscape(value)}</string>`)
.join('\n');
const envBlock = envEntries
? ` <key>EnvironmentVariables</key>\n <dict>\n${envEntries}\n </dict>\n`
: '';
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
'<plist version="1.0">',
'<dict>',
` <key>Label</key>`,
` <string>${LAUNCHD_LABEL}</string>`,
' <key>ProgramArguments</key>',
' <array>',
` <string>${xmlEscape(nodePath)}</string>`,
` <string>${xmlEscape(cliPath)}</string>`,
' <string>server</string>',
' </array>',
envBlock.trimEnd(),
' <key>RunAtLoad</key>',
' <true/>',
' <key>KeepAlive</key>',
' <true/>',
` <key>StandardOutPath</key>`,
` <string>${xmlEscape(logPath)}</string>`,
` <key>StandardErrorPath</key>`,
` <string>${xmlEscape(errorLogPath)}</string>`,
'</dict>',
'</plist>',
'',
]
.filter((line) => line !== '')
.join('\n');
}
function buildSystemdService({ nodePath, cliPath, envVars }) {
const envLines = Object.entries(envVars || {}).map(
([key, value]) => `Environment=${key}=${JSON.stringify(String(value))}`,
);
return [
'[Unit]',
'Description=tgcli background service',
'After=network-online.target',
'',
'[Service]',
`ExecStart=${nodePath} ${cliPath} server`,
'Restart=on-failure',
...envLines,
'',
'[Install]',
'WantedBy=default.target',
'',
].join('\n');
}
function parseBrewServicesList(output) {
const lines = output.split('\n').slice(1);
for (const line of lines) {
if (!line.trim()) continue;
const [name, status] = line.trim().split(/\s+/);
if (name === 'tgcli') {
return { status };
}
}
return null;
}
function detectBrewService() {
const brewCheck = runCommand('brew', ['--version']);
if (brewCheck.status !== 0) {
return { available: false };
}
const list = runCommand('brew', ['list', '--formula', 'tgcli']);
if (list.status !== 0) {
return { available: true, installed: false };
}
const prefixResult = runCommand('brew', ['--prefix', 'tgcli']);
const brewPrefix = prefixResult.status === 0 ? prefixResult.stdout.trim() : null;
const cliPath = fs.realpathSync(CLI_PATH);
const brewCliMatch = brewPrefix ? cliPath.startsWith(path.join(brewPrefix, 'libexec')) : false;
const servicesResult = runCommand('brew', ['services', 'list']);
const serviceEntry = servicesResult.status === 0 ? parseBrewServicesList(servicesResult.stdout) : null;
const serviceAvailable = Boolean(serviceEntry);
return {
available: true,
installed: true,
brewPrefix,
brewCliMatch,
serviceAvailable,
serviceStatus: serviceEntry?.status ?? null,
};
}
function resolveServiceManager() {
const brewInfo = detectBrewService();
if (brewInfo.available && brewInfo.installed && brewInfo.serviceAvailable) {
return { manager: 'brew', brewInfo };
}
if (process.platform === 'darwin') {
return { manager: 'launchd', brewInfo };
}
if (process.platform === 'linux') {
const systemctlCheck = runCommand('systemctl', ['--user', '--version']);
if (systemctlCheck.status !== 0) {
return { manager: 'unsupported', brewInfo };
}
return { manager: 'systemd', brewInfo };
}
return { manager: 'unsupported', brewInfo };
}
function runWithTimeout(task, timeoutMs, onTimeout) {
if (!timeoutMs) {
return task();
}
let timeoutId;
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(async () => {
try {
if (onTimeout) {
await onTimeout();
}
} finally {
reject(new Error('Timeout'));
}
}, timeoutMs);
});
return Promise.race([task(), timeoutPromise]).finally(() => {
if (timeoutId) {
clearTimeout(timeoutId);
}
});
}
function readVersion() {
try {
const pkgPath = new URL('./package.json', import.meta.url);
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
return pkg.version || '0.0.0';
} catch (error) {
return '0.0.0';
}
}
function promptInput(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise(resolve => {
rl.question(question, answer => {
rl.close();
resolve(answer.trim());
});
});
}
function getStoreConfig(storeDir) {
const { config } = loadConfig(storeDir);
const normalized = normalizeConfig(config ?? {});
const missing = validateConfig(normalized);
return { config: normalized, missing };
}
async function ensureStoreConfig(storeDir) {
const { config, missing } = getStoreConfig(storeDir);
if (missing.length === 0) {
return config;
}
const updated = { ...config };
if (!updated.apiId) {
updated.apiId = await promptInput('Telegram API ID: ');
}
if (!updated.apiHash) {
updated.apiHash = await promptInput('Telegram API hash: ');
}
if (!updated.phoneNumber) {
updated.phoneNumber = await promptInput('Telegram phone number (+...): ');
}
const normalized = normalizeConfig(updated);
const remaining = validateConfig(normalized);
if (remaining.length > 0) {
throw new Error('Missing tgcli configuration. Run "tgcli auth" to set credentials.');
}
saveConfig(storeDir, normalized);
return normalized;
}
function parsePositiveInt(value, label) {
if (value === undefined || value === null || value === '') {
return null;
}
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed <= 0) {
throw new Error(`${label} must be a positive number`);
}
return parsed;
}
function parseNonNegativeInt(value, label) {
if (value === undefined || value === null || value === '') {
return null;
}
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
throw new Error(`${label} must be a non-negative number`);
}
return parsed;
}
function collectList(value, previous) {
const list = previous ?? [];
list.push(value);
return list;
}
function parseListValues(value) {
const raw = Array.isArray(value) ? value : (value ? [value] : []);
return raw
.flatMap((entry) => String(entry).split(','))
.map((entry) => entry.trim())
.filter(Boolean);
}
function resolveSource(source) {
const resolved = source ? String(source).toLowerCase() : 'archive';
if (!['archive', 'live', 'both'].includes(resolved)) {
throw new Error(`Invalid source: ${source}`);
}
return resolved;
}
function parseDateMs(value, label) {
if (!value) {
return null;
}
const ts = Date.parse(value);
if (Number.isNaN(ts)) {
throw new Error(`Invalid ${label}: ${value}`);
}
return ts;
}
function filterLiveMessagesByDate(messages, fromDate, toDate) {
const fromMs = parseDateMs(fromDate, 'after');
const toMs = parseDateMs(toDate, 'before');
if (!fromMs && !toMs) {
return messages;
}
return messages.filter((message) => {
const ts = typeof message.date === 'number' ? message.date * 1000 : null;
if (!ts) {
return false;
}
if (fromMs && ts < fromMs) {
return false;
}
if (toMs && ts > toMs) {
return false;
}
return true;
});
}
function formatLiveMessage(message, context) {
const dateIso = message.date ? new Date(message.date * 1000).toISOString() : null;
return {
channelId: context.channelId ?? message.peer_id ?? null,
peerTitle: context.peerTitle ?? null,
username: context.username ?? null,
messageId: message.id,
date: dateIso,
fromId: message.from_id ?? null,
fromUsername: message.from_username ?? null,
fromDisplayName: message.from_display_name ?? null,
fromPeerType: message.from_peer_type ?? null,
fromIsBot: typeof message.from_is_bot === 'boolean' ? message.from_is_bot : null,
text: message.text ?? message.message ?? '',
urls: message.urls ?? null,
media: message.media ?? null,
topicId: message.topic_id ?? null,
};
}
function getMessageSenderLabel(message) {
return message.fromDisplayName || message.fromUsername || message.fromId || null;
}
function groupMessagesByChannel(messages) {
const groups = new Map();
for (const message of messages) {
const channelId = message.channelId ?? 'unknown';
const key = String(channelId);
let group = groups.get(key);
if (!group) {
group = {
channelId: key,
peerTitle: message.peerTitle ?? null,
username: message.username ?? null,
messages: [],
};
groups.set(key, group);
} else {
if (!group.peerTitle && message.peerTitle) {
group.peerTitle = message.peerTitle;
}
if (!group.username && message.username) {
group.username = message.username;