forked from isamert/scli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscli
executable file
·6135 lines (5223 loc) · 226 KB
/
scli
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 python3
import argparse
import atexit
import base64
import bisect
import collections
import errno
import hashlib
import importlib
import json
import logging
import os
import pprint
import re
import resource
import shlex
import shutil
import signal as signal_ipc
import subprocess
import sys
import tempfile
import textwrap
from abc import ABC, abstractmethod
from contextlib import contextmanager, suppress
from datetime import datetime, timezone
import urwid
try:
from urwid_readline import ReadlineEdit
Edit = ReadlineEdit
except ImportError:
Edit = urwid.Edit
# #############################################################################
# constants
# #############################################################################
DATA_FOLDER = os.getenv('XDG_DATA_HOME', os.path.expanduser('~/.local/share'))
CFG_FOLDER = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
SIGNALCLI_LEGACY_FOLDER = os.path.join(CFG_FOLDER, 'signal')
SIGNALCLI_LEGACY_DATA_FOLDER = os.path.join(SIGNALCLI_LEGACY_FOLDER, 'data')
SIGNALCLI_LEGACY_ATTACHMENT_FOLDER = os.path.join(SIGNALCLI_LEGACY_FOLDER, 'attachments')
SIGNALCLI_FOLDER = os.path.join(DATA_FOLDER, 'signal-cli')
SIGNALCLI_DATA_FOLDER = os.path.join(SIGNALCLI_FOLDER, 'data')
SIGNALCLI_ATTACHMENT_FOLDER = os.path.join(SIGNALCLI_FOLDER, 'attachments')
SIGNALCLI_AVATARS_FOLDER = os.path.join(SIGNALCLI_FOLDER, 'avatars')
SIGNALCLI_STICKERS_FOLDER = os.path.join(SIGNALCLI_FOLDER, 'stickers')
SCLI_DATA_FOLDER = os.path.join(DATA_FOLDER, 'scli')
SCLI_ATTACHMENT_FOLDER = os.path.join(SCLI_DATA_FOLDER, 'attachments')
SCLI_HISTORY_FILE = os.path.join(SCLI_DATA_FOLDER, 'history')
SCLI_CFG_FILE = os.path.join(CFG_FOLDER, 'sclirc')
SCLI_LOG_FILE = os.path.join(SCLI_DATA_FOLDER, 'log')
SCLI_EXEC_FOLDER = os.path.dirname(os.path.realpath(__file__))
SCLI_README_FILE = os.path.join(SCLI_EXEC_FOLDER, 'README.md')
# #############################################################################
# utility
# #############################################################################
def noop(*_args, **_kwargs):
pass
def get_nested(dct, *keys, default=None):
for key in keys:
try:
dct = dct[key]
except (KeyError, TypeError, IndexError):
return default
return dct
def get_urls(txt):
return re.findall(r'(https?://[^\s]+)', txt)
def callf(cmd, rmap=None, background=False, **subprocess_kwargs):
if rmap:
optionals = rmap.pop("_optionals", ())
for key, val in rmap.items():
if key not in cmd and key not in optionals:
raise ValueError(f'Command string `{cmd}` should contain a replacement placeholder `{key}` (e.g. `some-cmd "{key}"`). See `--help`.')
cmd = cmd.replace(key, val)
if not subprocess_kwargs.get('shell'):
cmd = shlex.split(cmd)
logger.debug('callf: `%s`', cmd)
if background:
for arg in ('stdin', 'stdout', 'stderr'):
subprocess_kwargs.setdefault(arg, subprocess.DEVNULL)
proc = subprocess.Popen(cmd, **subprocess_kwargs)
return proc
subprocess_kwargs.setdefault('text', True)
proc = subprocess.run(cmd, **subprocess_kwargs)
if proc.returncode != 0:
logger.error(
'callf: %s: exit code: %d, stderr: %s',
proc.args,
proc.returncode,
proc.stderr
)
elif proc.stdout:
logger.debug('callf: %s', proc.stdout)
return proc
def get_prog_dir():
return os.path.dirname(os.path.realpath(__file__))
def get_version():
"""Get this program's version.
Based on either `git describe`, or, if not available (e.g. for a release downloaded without the `.git` dir), use VERSION file populated during the creation of the release.
Does not output the leading `v` if it's present in git tag's name.
"""
prog_dir = get_prog_dir()
git_dir = os.path.join(prog_dir, '.git')
git_cmd = ['git', '--git-dir', git_dir, 'describe']
with suppress(FileNotFoundError, subprocess.CalledProcessError):
proc = subprocess.run(git_cmd, capture_output=True, check=True, text=True)
return proc.stdout.strip('v\n')
version_file_path = os.path.join(prog_dir, 'VERSION')
try:
with open(version_file_path, encoding='utf-8') as f:
version_str = f.readline()
except OSError:
return git_hash_file(__file__)[:8] # Short SHA
if not version_str.startswith('v'):
# '$Format:...' - not a `git archive` (e.g. a manually dl'ed blob)
# '%(..)' - `git archive` if git < 2.32
return git_hash_file(__file__)[:8] # Short SHA
return version_str[1:] # `git-describe`-like string
def get_python_version():
# Equivalent of platform.python_version()
return '.'.join(str(d) for d in sys.version_info[:3])
def git_hash_file(path, block_size=2**16):
"""git-hash-object for a file.
Method description in <https://git-scm.com/book/en/v2/Git-Internals-Git-Objects#_object_storage>.
To find commits referencing an object's hash, use `git log --find-object=<hash>` (<https://stackoverflow.com/a/48590251>).
"""
size = os.stat(path).st_size
header = f"blob {size}\0".encode()
hash_obj = hashlib.sha1()
hash_obj.update(header)
with open(path, 'rb') as fo:
# In Python 3.11, can use hashlib.file_digest()
# In Python 3.8, can use `while block := fo.read(…)`
for block in iter(lambda: fo.read(block_size), b''):
hash_obj.update(block)
return hash_obj.hexdigest()
def prog_version_str():
return f"scli {get_version()}"
def get_default_editor():
for env_var in ('VISUAL', 'EDITOR'):
ret = os.getenv(env_var)
if ret is not None:
return ret
for exe in ('sensible-editor', 'editor', 'nano', 'emacs', 'vi'):
ret = shutil.which(exe)
if ret is not None:
return ret
return ret
def get_default_pager():
with suppress(KeyError):
return os.environ['PAGER']
for exe in ('pager', 'less', 'more'):
ret = shutil.which(exe)
if ret is not None:
return ret
return None
PHONE_NUM_REGEX = re.compile('^\\+[1-9][0-9]{6,14}$')
# https://github.com/signalapp/libsignal-service-java/blob/master/java/src/main/java/org/whispersystems/signalservice/api/util/PhoneNumberFormatter.java
def is_number(number):
return bool(PHONE_NUM_REGEX.match(number))
def is_path(path):
return path.startswith(("/", "~/", "./"))
PATH_RE = re.compile(
r"""
# Matches a path-like string, with whitespaces escaped or with the whole path in quotes.
(
(
\\\ | # escaped whitespace OR ..
[^'" ] # .. not a quote or space
)+
) # Path with escaped whitespace ..
| # .. OR ..
( # .. path in quotes.
(?P<quote>['"]) # a quote char; name the capture
.+? # anything, non-greedily
(?P=quote) # matching quote
)
""",
re.VERBOSE,
)
def split_path(string):
string = string.strip()
if not string:
return ['', '']
re_match = PATH_RE.match(string)
if not re_match:
return ['', string]
path = re_match.group()
if re_match.group(1): # unquoted path
path = path.replace(r'\ ', ' ')
else: # path in quotes
path = path.strip('\'"')
rest = string[re_match.end() :].strip()
return [path, rest] if rest else [path]
def get_current_timestamp_ms():
return int(datetime.now().timestamp() * 1000)
def utc2local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
def strftimestamp(timestamp, strformat='%H:%M:%S (%Y-%m-%d)'):
try:
date = datetime.utcfromtimestamp(timestamp)
except ValueError:
date = datetime.utcfromtimestamp(timestamp / 1000)
return utc2local(date).strftime(strformat)
def strip_non_printable_chars(string):
if string.isprintable():
return string
return ''.join((c for c in string if c.isprintable()))
# #############################################################################
# signal utility
# #############################################################################
def get_contact_id(contact_dict):
return contact_dict.get('number') or contact_dict.get('groupId')
def is_contact_group(contact_dict):
return 'groupId' in contact_dict
def is_group_v2(group_dict):
gid = group_dict['groupId']
return len(gid) == 44
def get_envelope_data_val(envelope, *keys, default=None, return_tuple=False):
data_message_ret = get_nested(envelope, 'dataMessage', *keys, default=default)
sync_message_ret = get_nested(envelope, 'syncMessage', 'sentMessage', *keys, default=default)
if return_tuple:
return (data_message_ret, sync_message_ret)
else:
return data_message_ret or sync_message_ret
def is_envelope_outgoing(envelope):
return (
'target' in envelope
or get_nested(envelope, 'syncMessage', 'sentMessage') is not None
or get_nested(envelope, 'callMessage', 'answerMessage') is not None
)
def is_envelope_group_message(envelope):
return (
get_envelope_data_val(envelope, 'groupInfo') is not None
or ('target' in envelope and not is_number(envelope['target']))
or get_nested(envelope, 'typingMessage', 'groupId') is not None
)
def get_envelope_msg(envelope):
# If the `message` field is absent from the envelope: return None. If it is present but contains no text (since signal-cli v0.6.8, this is represented as `'message': null`): return ''. Otherwise: return the `message` field's value.
for msg in get_envelope_data_val(envelope, 'message', default=0, return_tuple=True):
if msg is None:
return ''
elif msg != 0:
return msg
return None
def get_envelope_time(envelope):
return (
envelope['timestamp']
or get_envelope_data_val(envelope, 'timestamp')
)
def get_envelope_contact_id(envelope):
return (
envelope.get('target')
or get_envelope_data_val(envelope, 'groupInfo', 'groupId')
or get_nested(envelope, 'syncMessage', 'sentMessage', 'destination')
or get_nested(envelope, 'typingMessage', 'groupId')
or envelope.get('sourceNumber')
or envelope['source']
)
def get_envelope_sender_id(envelope):
return envelope['source']
def get_envelope_quote(envelope):
return get_envelope_data_val(envelope, 'quote')
def get_envelope_reaction(envelope):
return get_envelope_data_val(envelope, 'reaction')
def get_envelope_mentions(envelope):
return get_envelope_data_val(envelope, 'mentions')
def get_envelope_remote_delete(envelope):
return get_envelope_data_val(envelope, 'remoteDelete')
def get_envelope_sticker(envelope):
return get_envelope_data_val(envelope, 'sticker')
def get_envelope_attachments(envelope):
return get_envelope_data_val(envelope, 'attachments')
def get_attachment_name(attachment):
if isinstance(attachment, dict):
filename = attachment['filename']
return filename if filename else attachment['contentType']
else:
return os.path.basename(attachment)
def get_attachment_path(attachment):
try:
aid = attachment['id']
except TypeError:
return attachment
received_attachment = os.path.join(SIGNALCLI_ATTACHMENT_FOLDER, aid)
if not os.path.exists(received_attachment):
received_attachment = os.path.join(SIGNALCLI_LEGACY_ATTACHMENT_FOLDER, aid)
return received_attachment
def get_sticker_file_path(sticker):
dir_name = sticker['packId']
file_name = str(sticker['stickerId'])
return os.path.join(SIGNALCLI_STICKERS_FOLDER, dir_name, file_name)
def b64_to_bytearray(group_id):
return ','.join(str(i) for i in base64.b64decode(group_id.encode()))
def b64_to_hex_str(group_id):
return base64.b64decode(group_id.encode()).hex()
def hex_str_to_b64(hex_str):
return base64.b64encode(bytes.fromhex(hex_str)).decode()
# #############################################################################
# clipboard
# #############################################################################
TEMPFILE_PREFIX = '_scli-tmp.'
class ClipBase(ABC):
mime_order = ['image/png', 'image/jpeg', 'image/jpg', 'text/uri-list']
@staticmethod
def get_installed_clipb_manager():
for executable in ('wl-paste', 'xclip'):
if shutil.which(executable) is not None:
return executable
return None
_get_types_arg = None
_get_files_arg = None
_put_cmd = None
@abstractmethod
def _run_cmd(self, args):
pass
@abstractmethod
def _get_args(self, mime):
pass
def _run(self, args):
try:
proc = subprocess.run(
self._run_cmd(args),
capture_output=True,
check=True,
)
except (OSError, subprocess.CalledProcessError):
return None
return proc.stdout
def _get(self, mime):
return self._run(self._get_args(mime))
def _run_lines(self, args):
out = self._run(args)
if out:
return out.decode('utf-8').splitlines()
return None
def _get_types(self):
return self._run_lines(self._get_types_arg)
def _get_files(self):
return [f for f in self._run_lines(self._get_files_arg) if f]
def _clip_files(self):
out = self._get_types()
if out is None:
return out
for otype in out:
for mtype in self.mime_order:
if mtype == otype:
if mtype.startswith('image/'):
content = self._get(mtype)
suffix = '.' + mtype.split('/')[1]
if cfg.save_history:
clip_file_path = os.path.join(
SCLI_ATTACHMENT_FOLDER,
f"clipboard_{datetime.now().strftime('%Y-%m-%d-%H-%M-%S')}{suffix}"
)
clip_file = open(clip_file_path, 'w+b')
else:
clip_file = tempfile.NamedTemporaryFile(
mode='w+b',
prefix=TEMPFILE_PREFIX,
suffix=suffix,
delete=False,
)
with clip_file:
clip_file.write(content)
return [clip_file.name]
elif mtype == 'text/uri-list':
content = self._get_files()
return [x.replace('file://', '') for x in content]
return None
def files(self):
cmd = cfg.clipboard_get_command
if cmd is None:
return self._clip_files()
return callf(cmd, capture_output=True).stdout.splitlines()
def _put(self, txt):
if not txt:
return
try:
proc = subprocess.Popen(
self._put_cmd,
stdin=subprocess.PIPE,
text=True,
)
except OSError:
return
else:
with proc:
proc.stdin.write(txt)
def put(self, txt):
cmd = cfg.clipboard_put_command
if cmd is None:
return self._put(txt)
return callf(cmd, {'%s': txt})
class Xclip(ClipBase):
_get_types_arg = 'TARGETS'
_get_files_arg = 'text/uri-list'
_put_cmd = ['xclip', '-selection', 'clipboard']
def _run_cmd(self, args):
return ['xclip', '-selection', 'clipboard', '-t', args, '-o']
def _get_args(self, mime):
return mime
class WLclip(ClipBase):
_get_types_arg = ['-l']
_get_files_arg = ['-t', 'text/uri-list']
_put_cmd = ['wl-copy']
def _run_cmd(self, args):
return ['wl-paste', *args]
def _get_args(self, mime):
return ['-t', mime]
# #############################################################################
# AsyncProc & Daemon
# #############################################################################
class AsyncProc:
def __init__(self, main_loop):
# The `main_loop` is an object like `urwid.MainLoop`, that implements `watch_pipe()` and `set_alarm_in()` methods.
self.main_loop = main_loop
def _on_proc_started(self, proc): pass
def _on_proc_done(self, proc): pass
def run(self, args, shell, callback, callback_args, callback_kwargs):
""" Run the command composed of `args` in the background (asynchronously); run the `callback` function when it finishes """
def watchpipe_handler(line):
# This function is run when the shell process returns (finishes execution).
# The `line` printed to watch pipe is of the form "b'<PID> <RETURN_CODE>\n'"
_proc_pid, return_code = [int(i) for i in line.decode().split()]
proc.wait() # reap the child process, to prevent zombies
proc.returncode = return_code # overwrite the 'wrapper' command return code (always 0) with the actual command return code
proc.output = proc.stderr.read().rstrip('\n') # stderr stream is not seekable, so can be read only once
proc.stderr.close()
if return_code != 0:
logger.error(
'proc: cmd:`%s`; return_code:%d; output:"%s"',
proc.args,
return_code,
proc.output,
)
if callback is not None:
callback(proc, *callback_args, **callback_kwargs)
self._on_proc_done(proc)
os.close(watchpipe_fd) # Close the write end of watch pipe.
return False # Close the read end of watch pipe and remove the watch from event_loop.
watchpipe_fd = self.main_loop.watch_pipe(watchpipe_handler)
# If the command is run with Popen(.., shell=True), shlex.quote is needed to escape special chars in args.
sh_command = " ".join(
[shlex.quote(arg) for arg in args] if not shell else ['{', args, ';', '}']
)
# Redirect all the process's output to stderr, and write the process PID and exit status to the watch pipe.
sh_command += " 1>&2; echo $$ $?"
proc = subprocess.Popen(
sh_command,
shell=True,
stdout=watchpipe_fd,
stderr=subprocess.PIPE,
universal_newlines=True,
)
atexit.register(proc.kill) # prevent orphaned processes surviving after the main program is stopped
self._on_proc_started(proc)
return proc
class AsyncQueued(AsyncProc):
_MAX_BACKGROUND_PROCS_DEFAULT = 64
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._curr_running = set()
self._run_queue = collections.deque()
try:
self._max_background_procs = self._background_procs_resource(self._MAX_BACKGROUND_PROCS_DEFAULT)
except OSError:
self._max_background_procs = self._MAX_BACKGROUND_PROCS_DEFAULT
@staticmethod
def _background_procs_resource(default):
nprocs = min(
default,
resource.getrlimit(resource.RLIMIT_NPROC)[0],
)
try:
n_curr_fds = len(os.listdir('/proc/self/fd')) * 3 # x3 to account for signal-cli's added FDs after it starts
except OSError:
n_curr_fds = 32
fd_limits = [nprocs*3+n_curr_fds] # each proc opens 3 FDs
for res in (resource.RLIMIT_NOFILE, resource.RLIMIT_OFILE):
with suppress(OSError, ValueError):
fd_limits.append(resource.getrlimit(res)[0])
return (min(fd_limits) - n_curr_fds) // 3
@property
def _max_procs_reached(self):
return len(self._curr_running) == self._max_background_procs
def _add_run_to_queue(self, run_args):
self._run_queue.append(run_args)
def run(self, args, callback=None, *callback_args, shell=False, **callback_kwargs):
run_args = {k: v for k, v in locals().items() if k not in ('self', '__class__')}
if not self._max_procs_reached:
return super().run(**run_args)
else:
return self._add_run_to_queue(run_args)
def _on_proc_started(self, proc):
super()._on_proc_started(proc)
self._curr_running.add(proc)
def _pop_run(self, proc):
self._curr_running.remove(proc)
try:
return self._run_queue.popleft()
except IndexError:
return None
def _on_proc_done(self, proc):
super()._on_proc_done(proc)
run_args_next = self._pop_run(proc)
if run_args_next is not None:
started_proc = super().run(**run_args_next)
else:
started_proc = None
return (run_args_next, started_proc)
class AsyncContext(AsyncQueued):
class ContextItem:
__slots__ = (
'procs',
'callback',
'callback_kwargs',
'proc_callback',
'proc_callback_kwargs',
'buffered_runs',
)
def __init__(self, callback, callback_kwargs, proc_callback, proc_callback_kwargs):
self.procs = set()
self.callback = callback
self.callback_kwargs = callback_kwargs
self.proc_callback = proc_callback
self.proc_callback_kwargs = proc_callback_kwargs
self.buffered_runs = set()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._context_items = collections.deque()
self._accepting_new_procs_for_item = False
def _new_item(self, callback, callback_kwargs, proc_callback, proc_callback_kwargs):
if callback is None and proc_callback is None:
return
self._context_items.append(
self.ContextItem(callback, callback_kwargs, proc_callback, proc_callback_kwargs)
)
self._accepting_new_procs_for_item = True
@property
def _curr_item(self):
return self._context_items[-1]
def _on_proc_started(self, proc):
super()._on_proc_started(proc)
if not self._accepting_new_procs_for_item:
return
self._curr_item.procs.add(proc)
def _finalize_item(self):
self._accepting_new_procs_for_item = False
if not self._context_items:
return
curr_item = self._curr_item
if not (curr_item.procs or curr_item.buffered_runs):
# No background procs have been started
self._pop_callback()
def _pop_callback(self, item=None):
if item is None:
item = self._context_items.pop()
else:
self._context_items.remove(item)
if item.callback is not None:
item.callback(**item.callback_kwargs)
@contextmanager
def callback_finally(
self,
callback=None,
proc_callback=None,
proc_callback_kwargs=None,
**callback_kwargs
):
"""Execute callback function after all background processes started inside this context have finished.
Optionally, run `proc_callback` after every background processes that exits.
"""
proc_callback_kwargs = proc_callback_kwargs or {}
try:
yield self._new_item(
callback,
callback_kwargs,
proc_callback,
proc_callback_kwargs,
)
finally:
self._finalize_item()
@staticmethod
def _run_id(run_params):
return id(run_params)
def _add_buffered_run(self, run_params):
if not self._accepting_new_procs_for_item:
return
self._curr_item.buffered_runs.add(self._run_id(run_params))
def _add_run_to_queue(self, run_args):
super()._add_run_to_queue(run_args)
self._add_buffered_run(run_args)
def _remove_buffered_run(self, run_params, started_proc):
if run_params is None:
return
run_id = self._run_id(run_params)
for item in self._context_items:
try:
item.buffered_runs.remove(run_id)
except KeyError:
continue
else:
item.procs.add(started_proc)
# There should be no race condition if the proc has already finished: the python code is executed in a single thread, and this is always run before the proc's return is processed.
return
def _on_proc_done(self, proc):
self._remove_buffered_run(*super()._on_proc_done(proc))
for item in self._context_items:
try:
item.procs.remove(proc)
except KeyError:
continue
if item.proc_callback is not None:
item.proc_callback(proc, **item.proc_callback_kwargs)
if not (item.procs or item.buffered_runs or self._accepting_new_procs_for_item):
self._pop_callback(item)
return
class Daemon(AsyncContext):
def __init__(self, main_loop, username):
super().__init__(main_loop)
self._username = username
self._buffer = ''
self.logger = logging.getLogger(f"{self.__class__.__name__}")
self._logger_level_re = re.compile(r"^(2.*? \[.*\] )?(?P<lev_name>[A-Z]+) .*$")
self._msg_processing_paused = True
# Paused initially, to prevent a race condition betw registering the dbus service and getting a message on stdout (e.g. while polling in _run_when_dbus_service_started)
self.callbacks = {
cb_name: noop for cb_name in [
'daemon_started',
'daemon_log',
'receive_message',
'receive_sync_message',
'receive_receipt',
'receive_reaction',
'receive_sticker',
'sending_message',
'sending_reaction',
'sending_done',
'sending_reaction_done',
'contact_typing',
'call_message',
'contacts_sync',
'remote_delete',
'sending_remote_delete_done',
'untrusted_identity_err',
'user_unregistered_err',
]
}
def start(self):
stdout_fd = self.main_loop.watch_pipe(self._daemon_stdout_handler)
stderr_fd = self.main_loop.watch_pipe(self._daemon_stderr_handler)
try:
proc = callf(
cfg.daemon_command,
{'%u': self._username, '_optionals': ['%u']},
background=True,
stdout=stdout_fd,
stderr=stderr_fd,
#text=True, # urwid returns bytes-objects anyway; see comment in _daemon_stdout_handler
)
except FileNotFoundError:
sys.exit(
f"ERROR: could not find `{cfg.daemon_command.split()[0]}` executable. "
"Make sure it is on system path."
)
return proc
def _daemon_stdout_handler(self, output):
output = self._buffer + output.decode()
# The `output` (supplied by urwid) is a `bytes` object, even when the `subprocess` is launched with `text=True`.
if self._msg_processing_paused:
self._buffer = output
return True
lines = output.split('\n') # Different from splitlines(): adds a final '' element after '\n'
self._buffer = lines.pop()
for line in lines:
if not line or line.isspace():
continue
try:
json_data = json.loads(line)
envelope = json_data['envelope']
except (json.JSONDecodeError, KeyError) as err:
logger.error('Could not parse daemon output: %s', line)
logger.exception(err)
return True
logger.debug("Daemon: json_data = \n%s", pprint.pformat(json_data))
error_data = None
for error_key in ('error', 'exception'):
try:
error_data = json_data[error_key]
except KeyError:
continue
self._error_data_handler(error_data, envelope)
if error_data is None:
self._envelope_handler(envelope)
return True
def _daemon_stderr_handler(self, output):
lines = output.decode().strip()
if not lines:
return True
if self._msg_processing_paused and any(s in lines for s in (
# `_msg_processing_paused` as a proxy for `daemon_started` / `is_dbus_service_running`
#"Exported dbus object: /org/asamk/Signal", # signal-cli v0.9.2 or earlier
"DBus daemon running", # signal-cli v0.12.8 or earlier
"Started DBus server",
)):
self._run_when_dbus_service_started(
self.callbacks['daemon_started']
)
for line in lines.splitlines():
log_lev = getattr(
logging,
self._daemon_output_log_level(line) or "INFO",
logging.INFO,
)
self.logger.log(log_lev, line)
self.callbacks['daemon_log'](line)
return True
def _envelope_handler(self, envelope):
envelope['_received_timestamp'] = get_current_timestamp_ms()
if get_envelope_msg(envelope) or get_envelope_attachments(envelope):
if get_nested(envelope, 'syncMessage', 'sentMessage') is not None:
self.callbacks['receive_sync_message'](envelope)
else:
self.callbacks['receive_message'](envelope)
elif envelope.get('receiptMessage') is not None:
# In signal-cli >=0.7.3, above check can be replaced with just
# 'receiptMessage' in envelope
# Keeping `is not None` for compatiability with envelopes in history from older signal-cli versions.
self.callbacks['receive_receipt'](envelope)
elif 'typingMessage' in envelope:
self.callbacks['contact_typing'](envelope)
elif get_envelope_reaction(envelope):
self.callbacks['receive_reaction'](envelope)
elif envelope.get('callMessage') is not None:
self.callbacks['call_message'](envelope)
elif get_nested(envelope, 'syncMessage', 'type') in ('CONTACTS_SYNC', 'GROUPS_SYNC'):
self.callbacks['contacts_sync']()
elif get_envelope_data_val(envelope, 'groupInfo', 'type') == 'UPDATE':
self.callbacks['contacts_sync']()
elif get_envelope_remote_delete(envelope):
self.callbacks['remote_delete'](envelope)
elif get_envelope_sticker(envelope):
self.callbacks['receive_sticker'](envelope)
else:
logger.info('No action for received envelope: %s', pprint.pformat(envelope))
def _error_data_handler(self, error_data, envelope):
logger.error("Daemon: error = \n%s", pprint.pformat(error_data))
if error_data.get('type') == 'UntrustedIdentityException':
self.callbacks['untrusted_identity_err'](envelope)
def _daemon_output_log_level(self, line):
match = self._logger_level_re.match(line)
return match.group("lev_name") if match else None
def pause_message_processing(self):
self._msg_processing_paused = True
def unpause_message_processing(self):
self._msg_processing_paused = False
self._daemon_stdout_handler(b'')
def _dbus_send(self, args, *proc_args, async_proc=True, **proc_kwargs):
args = [
'dbus-send',
'--session',
'--type=method_call',
'--print-reply=literal',
*args
]
if async_proc:
proc = self.run(args, *proc_args, **proc_kwargs)
else:
proc = subprocess.run(args, *proc_args, **proc_kwargs)
return proc
def _dbus_send_signal_cli(self, args, *proc_args, **proc_kwargs):
""" Send a command to signal-cli daemon through dbus """
args = [
'--dest=org.asamk.Signal',
'/org/asamk/Signal',
*args
]
return self._dbus_send(args, *proc_args, **proc_kwargs)
def _send_message_dbus_cmd(self, message, attachments, recipient, is_group=False, *proc_args, **proc_kwargs):
args = [
('org.asamk.Signal.sendMessage'
if not is_group else
'org.asamk.Signal.sendGroupMessage'),
'string:' + message,
'array:string:' + ','.join(attachments),
('string:' + recipient
if not is_group else
'array:byte:' + b64_to_bytearray(recipient))
]
self._dbus_send_signal_cli(args, *proc_args, **proc_kwargs)
def _send_reaction_dbus_cmd(self, emoji, remove, target_author, target_sent_timestamp, recipient, is_group=False, *proc_args, **proc_kwargs):
dbus_args = [
('org.asamk.Signal.sendMessageReaction'
if not is_group else
'org.asamk.Signal.sendGroupMessageReaction'),
"string:" + emoji,
"boolean:" + str(remove).lower(),
"string:" + target_author,
"int64:" + str(target_sent_timestamp),
('string:' + recipient
if not is_group else
'array:byte:' + b64_to_bytearray(recipient))
]
self._dbus_send_signal_cli(dbus_args, *proc_args, **proc_kwargs)
def _send_remote_delete_dbus_cmd(self, target_sent_timestamp, recipient, is_group=False, *proc_args, **proc_kwargs):
dbus_args = [
('org.asamk.Signal.sendRemoteDeleteMessage'
if not is_group else
'org.asamk.Signal.sendGroupRemoteDeleteMessage'),
"int64:" + str(target_sent_timestamp),
('string:' + recipient
if not is_group else
'array:byte:' + b64_to_bytearray(recipient))
]