forked from jwoglom/signal-curses
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1085 lines (893 loc) · 35.1 KB
/
main.py
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
"""
signal-curses: Curses-backed terminal interface for Signal using signal-cli and npyscreen.
Copyright (C) 2018 James Woglom
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import npyscreen
import curses
import subprocess
import threading
import re
import pathlib
import json
import os
import time
import argparse
import pydbus
import base64
import pyqrcode
import socket
from gi.repository import GLib
from signal import signal as py_signal
from signal import SIGINT, SIGTERM
from queue import Queue
from datetime import datetime
CURSES_OTHER_ENTER = 10
log_file = open('sc.log', 'w')
log_file_lock = threading.Lock()
out_file = open('daemon.log', 'a')
out_file_lock = threading.Lock()
def log(*args):
log_file_lock.acquire()
log_file.write(str(datetime.now())[:19]+' ')
log_file.write(' '.join([str(i) for i in args]))
log_file.write('\n')
log_file.flush()
log_file_lock.release()
def execute_popen(cmd):
return subprocess.Popen(cmd, stdout=subprocess.PIPE,
universal_newlines=True)
def execute(popen):
for stdout_line in iter(popen.stdout.readline, ""):
yield stdout_line
popen.stdout.close()
return_code = popen.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, None)
def exception_waitloop(fn, ex, sec, name=None):
try:
ret = fn()
except ex as er:
try:
if name:
print('Waiting for '+str(name), end='')
for _ in range(sec):
try:
ret = fn()
except ex:
if name:
print('.', end='')
sys.stdout.flush()
time.sleep(1)
continue
else:
break
else:
if name:
print('Giving up!')
return False
except KeyboardInterrupt:
if name:
print('')
sys.exit(1)
return ret
class MainForm(npyscreen.Popup):
def create(self):
self.to = self.add(npyscreen.TitleSelectOne, max_height=3,
name='To:',
values=['Bob Smith', 'John Doe', 'Jane Doe', 'Todd Smith'],
scroll_exit=True)
self.msg = self.add(npyscreen.TitleText, name='Message:')
def afterEditing(self):
print('after editing', self.to.value, self.msg.value)
self.parentApp.setNextForm('DONE')
class MessagesLine(npyscreen.MultiLine):
_size = 15
_size_max = 30
_date_size = 20
_real_values = []
_saved_lines = {}
def __init__(self, *args, **kwargs):
#kwargs['columns'] = 6
#kwargs['column_width'] = 20
super(MessagesLine, self).__init__(*args, **kwargs)
def update(self, *args, **kwargs):
if self._real_values:
self._gen_size()
self._gen_values()
super(MessagesLine, self).update(*args, **kwargs)
def _gen_size(self):
self._size = min(max([len(i[1]) for i in self._real_values]), self._size_max)
def display_value(self, val):
return val
def _gen_line_max(self, val, size_max):
if len(val) < size_max:
return val
c = '…'
return val[:size_max-len(c)]+c
def _gen_lines(self, val):
return self._gen_lines_full(val, self._size, self._size_max, self._date_size)
def _gen_lines_full(self, val, size, size_max, date_size):
# (date, from, message, suffix)
beg_fmt = '{:<'+str(date_size)+'}{:>'+str(size)+'}'
if len(val) > 2:
beg_fmt += ' | '
first_beg = beg_fmt.format(val[0], self._gen_line_max(val[1], size_max))
cont_beg = beg_fmt.format(val[0], '')
ret = []
if len(val) < 3:
return [first_beg]
text = val[2]
ln = first_beg + str(text[:self.width])
if len(val) >= 4:
#log('adding suffix:', val[3])
if (len(ln) + len(val[3])) <= (self.width + len(cont_beg)):
ln += (' ' * (self.width - len(ln) - len(val[3]) - 1)) + val[3]
else:
# force a new line
ln += (' ' * (self.width - len(ln) - 1))
ret.append(ln)
text = text[self.width:]
while len(text) > 0:
ln = cont_beg + str(text[:self.width])
text = text[self.width:]
if len(val) >= 4:
#log('adding suffix:', val[3])
if (len(ln) + len(val[3])) <= (self.width + len(cont_beg)):
ln += (' ' * (self.width - len(ln) - len(val[3]) - 1)) + val[3]
else:
# force a new line
ln += (' ' * (self.width - len(ln) - 1))
ret.append(ln)
#log('lines:', '\n'.join(ret))
return ret
def _gen_values(self):
self.values = []
for v in self._real_values:
[self.values.append(i) for i in self._gen_lines(v)]
def _time_now(self):
return str(datetime.now())[:19]
def addValues(self, values):
for val in values:
comb = [self._time_now()] + list(val)
self._real_values += [comb]
def clearValues(self):
self._real_values = []
self.values = []
def addDatedValues(self, values):
numRegex = re.compile(".* \(([\+0-9]*)\)")
log('values is', values)
for entry in values:
log('adding dated value to saved_lines ', entry)
source = numRegex.match(entry[1]).group(1)
# need to add dated values under source if from other
# under other end if from self
log('logging as:', source)
if (source not in self._saved_lines.keys()):
self._saved_lines[source] = []
self._saved_lines[source].append(entry)
self._real_values += values
self.update()
def _mark_value_as(self, value, txt):
log('mark: ', value, 'as: ', txt)
return (value[0], value[1], value[2], txt)
def _mark_value_eq(self, a, b):
return (a[:3] == b[:3])
def markAs(self, value, suffix):
for i in range(len(self._real_values)):
if self._mark_value_eq(self._real_values[i], value):
log('markAs success:', value)
self._real_values[i] = self._mark_value_as(value, suffix)
class CurrentSend(object):
timestamp = None
value = None
def __init__(self, timestamp, value):
self.timestamp = timestamp
self.value = value
class AppMessageBox(npyscreen.TitleText):
currentSend = None
def __init__(self, *args, **kwargs):
super(AppMessageBox, self).__init__(*args, **kwargs)
self.entry_widget.add_handlers({
'^A': self._handleEnter,
curses.KEY_ENTER: self._handleEnter,
CURSES_OTHER_ENTER: self._handleEnter
})
def _getSelfName(self):
return '{}'.format(self.parent.parentApp.state.phone)
def _handleEnter(self, inp):
now = int(time.time() * 1000)
val = self.entry_widget.value
log('handleEnter', inp, val, now)
self.entry_widget.value = ''
self.entry_widget.clear()
self.currentSend = CurrentSend(now, val)
self.parent.parentApp.handleSelfEnvelope(now, self._getSelfName(), val)
self.parent.parentApp.queue_event(npyscreen.Event("SEND"))
self.parent.parentApp.queue_event(npyscreen.Event("RELOAD"))
class AppForm(npyscreen.FormMuttActiveTraditionalWithMenus):
COMMAND_WIDGET_CLASS = AppMessageBox
COMMAND_WIDGET_NAME = 'Send: '
COMMAND_WIDGET_BEGIN_ENTRY_AT = 1
MAIN_WIDGET_CLASS = MessagesLine
def create(self):
self.m1 = self.add_menu(name="Main Menu", shortcut="^X")
self.m1.addItemsFromList([
("Switch", self.whenSwitch, None, None, ("blah",)),
("Exit", self.whenExit, "e"),
])
self.add_event_hander("RELOAD", self.reloadHandler)
self.add_event_hander("SEND", self.sendHandler)
super(AppForm, self).create()
def reloadHandler(self, event):
#log('reloadHandler')
self.wMain.update()
def sendHandler(self, event):
cur = self.wCommand.currentSend
log('sendHandler', cur.value, cur.timestamp)
self.parentApp.message_queue.put({
'state': self.parentApp.state,
'currentSend': cur
})
def whenSwitch(self, arg):
self.parentApp.setNextForm('MAIN')
self.parentApp.state.clear()
self.parentApp.switchFormNow()
def whenExit(self):
self.parentApp.setNextForm(None)
self.editing = False
self.parentApp.handleExit()
self.parentApp.switchFormNow()
exit(0)
def beforeEditing(self):
self.wMain.always_show_cursor = False
self.wMain.addValues([
# ('*', 'Connecting...',),
])
self.wMain.display()
def _updateTitle(self, name, numbers):
self.wStatus1.value = 'Signal: {} '.format(name if name else ', '.join(numbers))
self.wStatus2.value = '{} ({}) '.format(name, ', '.join(numbers)) if name else ', '.join(numbers)+' '
self.wStatus1.display()
self.wStatus2.display()
def updateState(self):
self._updateTitle(self.parentApp.state.toName, self.parentApp.state.numbers)
class SelectFormTree(npyscreen.MLTree):
pass
class SelectForm(npyscreen.Form):
tree = None
def create(self):
super(SelectForm, self).create()
self.tree = self.add(SelectFormTree)
td = npyscreen.TreeData(content='Select one:', selectable=False, ignore_root=False)
cobj = td.new_child(content='Contacts:', selectable=False)
contacts = self.parentApp.configData.contacts
for c in contacts:
cobj.new_child(content='{} ({})'.format(c['name'], c['number']))
gobj = td.new_child(content='Groups:', selectable=True)
groups = self.parentApp.configData.groups
for g in groups:
gobj.new_child(content='{} ({})'.format(g['name'], ', '.join(g['members'])))
self.tree.values = td
def getFromId(self, tree_id):
contacts = self.parentApp.configData.contacts
groups = self.parentApp.configData.groups
obj = [None, None] + contacts + [None] + groups
is_group = (tree_id > len(contacts) + 2)
return (obj[tree_id], is_group)
def afterEditing(self):
log(self.tree.value)
selected, is_group = self.getFromId(self.tree.value)
log(selected)
if not selected:
npyscreen.notify_confirm('Invalid entry', title='Select User/Group')
return
self.parentApp.app.wMain.clearValues()
self.parentApp.app.wMain.update()
self.parentApp.updateState(selected, is_group)
self.parentApp.setNextForm('APP')
class AppState(object):
startup_time = None
convType = None
USER = 'user'
GROUP = 'group'
user = None
group = None
configDir = None
phone = None
bus = None
def __init__(self):
self.startup_time = time.time()
def __str__(self):
return 'state type: {} name: {} numbers: {}'.format(self.convType, self.toName, ', '.join(self.numbers))
@property
def is_user(self):
return self.convType == self.USER
@property
def is_group(self):
return self.convType == self.GROUP
@property
def toNumber(self):
return self.user['number'] if self.is_user else None
@property
def toNumbers(self):
return self.group['members'] if self.is_group else None
@property
def numbers(self):
return [self.toNumber] if self.is_user else self.toNumbers if self.is_group else []
@property
def toName(self):
return self.user['name'] if self.is_user else (
self.group['name'] if self.is_group else None)
@property
def groupId(self):
return self.group['groupId'] if self.is_group else None
def load(self, selected, is_group):
if is_group:
self.convType = self.GROUP
self.group = selected
else:
self.convType = self.USER
self.user = selected
def clear(self):
self.convType = None
self.user = None
self.group = None
def loadArgs(self, args):
self.phone = args.phone
self.configDir = args.configDir
self.bus = args.bus
def shouldDisplayEnvelope(self, env):
return env.should_display(self.toNumber, self.phone)
def shouldNotifyEnvelope(self, env):
return env.should_notify(self.toNumber, self.phone)
class SignalApp(npyscreen.StandardApp):
app = None
daemonThread = None
daemonPopen = None
messageThread = None
message_queue = Queue()
raw_lines = []
messageLines = []
state = None
stateNumber = None
isShuttingDown = False
lines = []
envelopes = []
configData = None
def __init__(self, options=None, *args, **kwargs):
super(SignalApp, self).__init__(*args, **kwargs)
self.state = AppState()
self.state.loadArgs(options)
self.configData = SignalConfigData(self.state)
self.initDaemon()
def onStart(self):
log('contacts: ', len(self.configData.contacts))
self.addForm('MAIN', SelectForm, name='Select User/Group')
self.addForm('APP', AppForm, name='Application')
log('start forms', self._Forms)
self.app = self.getForm('APP')
def updateState(self, selected, is_group):
self.state.load(selected, is_group)
log('new state:', self.state, "selected:", selected)
self.stateNumber = selected['number']
self.lines = []
try:
self.loadDisplayLines()
except Exception as e:
log('error loading lines', e)
# add number of state to switch to
self.app.updateState()
def loadDisplayLines(self):
log('disaplaying lines', self.lines)
#self.app.wMain.addDatedValues(self.lines)
log('_key', self.stateNumber)
log('_savedlineskeys:',self.app.wMain._saved_lines.keys())
# load previous lines
try:
# self.app.wMain.addDatedValues(self.app.wMain._saved_lines[self.stateNumber])
log('trying to load prev lines')
for line in self.app.wMain._saved_lines[self.stateNumber]:
log('loaded line:', line)
if (line):
self.lines.append(line)
log('added to lines', self.lines)
log('erasing lines: ', self.app.wMain._saved_lines[self.stateNumber])
self.app.wMain._saved_lines[self.stateNumber] = []
except Exception as e:
log('broken', e)
self.app.wMain.addDatedValues(self.lines)
# for line in self.lines:
# if self.state.shouldDisplayLine(line):
# self.addLine(line)
def addHiddenEnvelope(self, env):
log('adding hidden envelope', env)
log('source:', env.source)
if (env.source not in self.app.wMain._saved_lines.keys()):
self.app.wMain._saved_lines[env.source] = []
self.app.wMain._saved_lines[env.source].append(env.gen_line())
def addEnvelope(self, env):
log('adding envelope', env)
gen_line = env.gen_line()
self.app.wMain.addDatedValues([
gen_line
])
def markAsEnvelope(self, env, suffix):
log('markAsEnvelope:', env, suffix)
gen_line = env.gen_line()
self.app.wMain.markAs(gen_line, suffix)
self.app.wMain.update()
def onInMainLoop(self):
log('mloop forms', self._Forms)
def initDaemon(self):
log('main', self.app)
self.daemonThread = SignalDaemonThread(self)
self.daemonThread.start()
self.messageThread = SignalMessageThread(self, self.message_queue)
self.messageThread.start()
def killMessageThread(self):
self.message_queue.put({
'exit': 1
})
def killDaemon(self):
try:
self.daemonPopen.send_signal(SIGINT)
except Exception as e:
log('couldnt kill daemon')
def handleExit(self):
self.isShuttingDown = True
self.killDaemon()
self.killMessageThread()
def sigint_handler(self, sig, frame):
log('SIGINT')
self.handleExit()
exit(0)
def sigterm_handler(self, sig, frame):
log('SIGTERM')
self.handleExit()
exit(0)
def generateSelfEnvelope(self, now, name, msg):
return Envelope.load({"envelope": {
"timestamp": now,
"source": self.state.phone,
"dataMessage": {
"timestamp": now,
"message": msg
}
}}, self, Envelope.SELF)
def handleSelfEnvelope(self, now, name, msg):
env = self.generateSelfEnvelope(now, name, msg)
self.handleEnvelope(env)
self.markAsEnvelope(env, '(sending)')
#self.parent.wMain.addValues([
# (self._getSelfName(), val)])
def handleDbusLine(self, data):
log('handling dbus line')
try:
env = Envelope.load(data, self, Envelope.NETWORK)
except Exception as e:
log("error", e)
self.handleEnvelope(env)
def handleDaemonLine(self, line):
self.raw_lines.append(line)
log('handleDaemonLine', line)
data = json.loads(line)
env = Envelope.load(data, self, Envelope.NETWORK)
self.handleEnvelope(env)
def handleEnvelope(self, env):
self.envelopes.append(env)
if env.timestamp and (time.time() - env.epoch_ts) >= 60:
log('ignoring envelope due to time difference of', str((time.time() - env.epoch_ts)))
return
if env.dataMessage.is_message():
if self.state.shouldDisplayEnvelope(env):
self.addEnvelope(env)
elif self.state.shouldNotifyEnvelope(env):
log('adding hidden line')
self.addHiddenEnvelope(env)
log('notifying line')
gen_line = env.gen_line()
txt = '{}:\n\n{}'.format(gen_line[0], gen_line[2])
if env.group:
txt = 'Group: {}\n'.format(json.dumps(env.group)) + txt
npyscreen.notify_wait(txt, title='New Message from {}'.format(gen_line[1]))
else:
log('not displaying or notifying dataMessage')
if env.syncMessage.is_read_message():
for e in self.envelopes[:-1]:
if env.syncMessage.sync_read_matches(e):
log('mark_read', e)
self.markAsEnvelope(e, '(read)')
if env.callMessage.is_offer():
self.app.wMain.addValues([
('*', 'You are receiving an inbound call from {}'.format(env.source))
])
npyscreen.notify_wait('You are receiving an inbound call', title='Call from {}'.format(env.source))
if env.callMessage.is_busy():
log('ismessage busy')
self.app.wMain.addValues([
('*', 'The caller {} is busy'.format(env.source))
])
npyscreen.notify_wait('The caller is busy', title='Call from {}'.format(env.source))
if env.callMessage.is_hangup():
log('hangup')
self.app.wMain.addValues([
('*', 'The caller {} hung up'.format(env.source))
])
npyscreen.notify_wait('The caller hung up', title='Call from {}'.format(env.source))
def handleMessageLine(self, line):
self.messageLines.append(line)
class Envelope(object):
app = None
origin = None
NETWORK = 'NETWORK'
SELF = 'SELF'
_data = None
source = None
sourceDevice = None
relay = None
timestamp = None
isReceipt = None
dataMessage = None
syncMessage = None
callMessage = None
@staticmethod
def load(data, app, origin):
self = Envelope()
self.app = app
self._data = data
self.origin = origin
e = data['envelope']
self.source = e.get('source')
self.sourceDevice = e.get('sourceDevice')
self.relay = e.get('relay')
self.timestamp = e.get('timestamp')
self.isReceipt = e.get('isReceipt')
self.dataMessage = DataMessage.load(e.get('dataMessage'))
self.syncMessage = SyncMessage.load(e.get('syncMessage'))
self.callMessage = CallMessage.load(e.get('callMessage'))
return self
def should_display(self, toNumber, phone):
return ((self.source == toNumber) or (self.source == phone)) and self.dataMessage.should_display()
def should_notify(self, toNumber, phone):
# fromNumber != phone
return (self.source != toNumber) and (self.source != phone) and self.dataMessage.should_notify()
def lookup_number(self, number):
contacts = self.app.configData.contacts
return next(i for i in contacts if i['number'] == number)
@property
def sourceName(self):
if self.source == self.app.state.phone:
return 'You'
contact = self.lookup_number(self.source)
return contact['name'] if contact else None
@property
def group(self):
return self.dataMessage.groupInfo
@property
def epoch_ts(self):
return int(self.timestamp)/1000
def format_ts(self):
return str(datetime.fromtimestamp(self.epoch_ts))[:19]
def gen_line(self):
if self.sourceName:
return (self.format_ts(), '{} ({})'.format(self.sourceName, self.source), self.dataMessage.gen_line())
return (self.format_ts(), '{}'.format(self.source), self.dataMessage.gen_line())
def __str__(self):
return json.dumps(self._data)
class DataMessage(object):
timestamp = None
message = None
expiresInSeconds = None
attachments = None
groupInfo = None
@staticmethod
def load(data):
self = DataMessage()
if data:
self.timestamp = data.get('timestamp')
self.message = data.get('message')
self.expiresInSeconds = data.get('expiresInSeconds')
self.attachments = data.get('attachments')
self.groupInfo = data.get('groupInfo')
return self
def is_message(self):
return self.timestamp and self.message
def should_display(self):
return self.is_message()
def should_notify(self):
return self.is_message()
def gen_line(self):
return self.message
class SyncMessage(object):
_data = None
sentMessage = None
blockedNumbers = None
readMessages = None
@staticmethod
def load(data):
self = SyncMessage()
self._data = data
if data:
self.sentMessage = data.get('sentMessage')
self.blockedNumbers = data.get('blockedNumbers')
self.readMessages = data.get('readMessages')
return self
def is_read_message(self):
return self.readMessages and len(self.readMessages) > 0
def _compare_ts(self, envTs, msgTs):
return abs(envTs - msgTs) < 1000
def sync_read_matches(self, env):
ret = False
for msg in self.readMessages:
if env and env.dataMessage.is_message():
log('dm: ts=', env.dataMessage.timestamp, 'source=', env.source)
log('msg: ts=', msg.get('timestamp'), 'sender=', msg.get('sender'))
ret = ret or ((env.source == msg.get('sender')) and
self._compare_ts(env.dataMessage.timestamp, msg.get('timestamp')))
return ret
def __str__(self):
return json.dumps(self._data)
class CallMessage(object):
_data = None
offerMessage = None
busyMessage = None
hangupMessage = None
iceUpdateMessages = None
@staticmethod
def load(data):
self = CallMessage()
self._data = data
if data:
self.offerMessage = data.get('offerMessage')
self.busyMessage = data.get('busyMessage')
self.hangupMessage = data.get('hangupMessage')
self.iceUpdateMessages = data.get('iceUpdateMessages')
return self
def is_offer(self):
return self.offerMessage
def is_busy(self):
return self.busyMessage
def is_hangup(self):
return self.hangupMessage
class SignalDaemonThread(threading.Thread):
daemon = False
app = None
signal = None
bus = None
def __init__(self, app):
super(SignalDaemonThread, self).__init__()
self.app = app
def get_message_bus(self):
return self.bus.get('org.asamk.Signal')
def msgRcv(self, timestamp, source, groupID, message, attachments):
log ('dbus recvd', timestamp, source, message, groupID, message)
data = {"envelope":{ "timestamp" : timestamp,
"source" : source,
"dataMessage": {
"timestamp": timestamp,
"message": message
}
}}
self.app.handleDbusLine(data)
def run(self):
log('daemon thread')
state = self.app.state
if self.app.state.bus == 'system':
self.bus = pydbus.SystemBus()
else:
self.bus = pydbus.SessionBus()
log('daemon waiting for ({}) dbus...'.format(self.app.state.bus))
self.signal = exception_waitloop(self.get_message_bus, GLib.Error, 60)
if not self.signal:
log('dbus err')
npyscreen.notify_wait('Unable to get signal {} bus. Messaging functionality will not function.'.format(self.app.state.bus), title='Error in SignalDaemonThread')
exit(1)
log('got daemon dbus')
msgRcv = lambda timestamp, source, groupID, message, attachments : self.msgRcv(timestamp, source, groupID, message, attachments)
loop = GLib.MainLoop()
self.signal.onMessageReceived = msgRcv
log('daemon starting loop')
loop.run()
class SignalMessageThread(threading.Thread):
app = None
daemon = False
queue = None
signal = None
bus = None
def __init__(self, app, queue):
super(SignalMessageThread, self).__init__()
self.app = app
self.queue = queue
def get_message_bus(self):
return self.bus.get('org.asamk.Signal')
def run(self):
log('message thread')
if self.app.state.bus == 'system':
self.bus = pydbus.SystemBus()
else:
self.bus = pydbus.SessionBus()
log('message waiting for ({}) dbus...'.format(self.app.state.bus))
self.signal = exception_waitloop(self.get_message_bus, GLib.Error, 60)
if not self.signal:
log('dbus err')
npyscreen.notify_wait('Unable to get signal {} bus. Messaging functionality will not function.'.format(self.app.state.bus), title='Error in SignalMessageThread')
exit(1)
log('got message dbus')
while True:
item = self.queue.get()
log('queue item', item)
if 'exit' in item:
break
self.do_action(**item)
self.queue.task_done()
log('message thread exit')
def do_action(self, state=None, currentSend=None):
self.send_message(state, currentSend)
def send_message(self, state, currentSend):
message = currentSend.value
script = []
if state.is_user:
log('send_message user', state.toNumber, message)
self.signal.sendMessage(message, [], [str(state.toNumber)])
elif state.is_group:
log('send_message group', state.groupId, message)
b64 = base64.b64encode(state.groupId.encode())
log('group id:', state.groupId, ' b64:', b64)
self.signal.sendGroupMessage(message, [], b64)
else:
log('ERR: send_message inconsistent state')
return
env = self.app.generateSelfEnvelope(currentSend.timestamp, self.app.state.phone, message)
log('send_message env:', env)
self.app.markAsEnvelope(env, '(sent)')
log('send_message done')
class Setup(object):
token = None
tokenQR = None
showingToken = False
response = None
class SetupLinkDaemonThread(threading.Thread):
daemon = False
app = None
def __init__(self, app):
super(SetupLinkDaemonThread, self).__init__()
self.app = app
def run(self):
log('link daemon thread')
state = self.app.state
script = ['signal-cli', 'link', '-n{} on {}'.format('signal-curses', socket.gethostname())]
try:
popen = execute_popen(script)
self.app.daemonPopen = popen
log('link daemon popen')
for line in execute(popen):
#log('queue event')
"""out_file_lock.acquire()
out_file.write(line)
out_file.flush()
out_file_lock.release()"""
log('link line:', line)
if len(line) > 0:
self.app.sendLinkLine(line)
except subprocess.CalledProcessError as e:
if not self.app.isShuttingDown:
log('EXCEPTION in daemon', e)
log('daemon exit')
class SetupLinkPromptForm(npyscreen.Form):
def create(self):
self.prompt()
def prompt(self):
state = self.parentApp.state
self.parentApp.setNextForm('LINK')
npyscreen.notify_confirm("Couldn't open your signal config file for:\nPhone: {}\nConfig dir: {}".format(state.phone, state.configDir) +
"\nDo you want to link a new device right now? Hit Tab-Enter to continue, or Ctrl+C", title="No signal-cli config")
class SetupLinkForm(npyscreen.Form):
def create(self):
self.parentApp.startLinkDaemon()
self.showQR()
def getQR(self):
if not self.parentApp.setup.showingToken:
return
while self.parentApp.setup.token is None:
npyscreen.notify_wait("Waiting for token...", title="Setup")
time.sleep(1)
return pyqrcode.create(self.parentApp.setup.token).terminal(quiet_zone=1)
def getResponse(self):
while self.parentApp.setup.response is None:
time.sleep(1)
return self.parentApp.setup.response
def showQR(self):
state = self.parentApp.state
self.parentApp.setup.showingToken = True
self.parentApp.tokenQR = self.getQR()
self.parentApp.setup.showingToken = False
npyscreen.blank_terminal()
print("QR Code:")
for line in self.parentApp.tokenQR.splitlines():
print(line)
print("\r", end='')
print("")
print("In the Signal app, scan this QR code in Settings > Linked Devices.\r")
npyscreen.notify_confirm(self.getResponse(), title="Restart signal-curses to begin chatting")
exit(0)
class SetupApp(npyscreen.NPSAppManaged):