/
bitchan.py
1786 lines (1598 loc) · 80.6 KB
/
bitchan.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
import base64
import json
import logging
import random
import socket
import sqlite3
import subprocess
import time
import xmlrpc.client
from collections import OrderedDict
from operator import getitem
from threading import Thread
import gnupg
import ntplib
from sqlalchemy import and_
from stem import Signal
from stem.control import Controller
import config
from chan_objects import ChanBoard
from chan_objects import ChanPost
from database.models import AddressBook
from database.models import Chan
from database.models import DeletedMessages
from database.models import GlobalSettings
from database.models import Identity
from database.models import Messages
from database.models import PostMessages
from database.models import Threads
from database.models import UploadProgress
from database.utils import db_return
from database.utils import session_scope
from utils.files import LF
from utils.files import delete_message_files
from utils.gateway import get_access
from utils.gateway import get_bitmessage_endpoint
from utils.gateway import get_msg_address_from
from utils.general import get_random_alphanumeric_string
from utils.general import process_passphrase
from utils.message_admin_command import send_commands
from utils.message_processing import process_message
from utils.replacements import replace_lt_gt
from utils.shared import get_msg_expires_time
DB_PATH = 'sqlite:///' + config.DATABASE_BITCHAN
logger = logging.getLogger('bitchan.bm_gateway')
class BitChan(Thread):
def __init__(self):
super(BitChan, self).__init__()
self._non_bitchan_message_ids = []
self._posts_by_id = {}
self._all_chans = {}
self._board_by_chan = {}
self._list_by_chan = {}
self._address_book_dict = {}
self._identity_dict = {}
self._chan_list_dict = {}
self._chan_board_dict = {}
self._subscription_dict = {}
self._refresh = True
self._refresh_identities = False
self._refresh_address_book = True
self._api = xmlrpc.client.ServerProxy(get_bitmessage_endpoint())
socket.setdefaulttimeout(config.API_TIMEOUT)
self.list_start_download = []
self.message_threads = {}
self.max_threads = 8
self.utc_offset = None
self.time_last = 0
self.is_restarting_bitmessage = False
self.list_stats = []
self.first_run = True
self.update_ntp = False
# Bitmessage sync check
self.bm_connected = False
self.bm_connected_timer = None
self.bm_sync_complete = False
self.bm_pending_download = True
self.bm_pending_download_timer = None
# Timers
self.timer_check_bm_alive = time.time()
self.timer_time_server = time.time()
self.timer_sync = time.time()
self.timer_bm_update = time.time()
self.timer_clear_inventory = time.time()
self.timer_message_threads = time.time()
self.timer_clear_uploads = time.time()
self.timer_unread_mail = time.time()
self.timer_non_bitchan_message_ids = time.time()
self.timer_safe_send = time.time()
self.timer_new_tor_identity = time.time() + random.randint(1200, 7200)
self.timer_delete_identity_msgs = time.time() + (60 * 10) # 10 minutes
self.timer_get_msg_expires_time = time.time() + (60 * 10) # 10 minutes
self.timer_remove_deleted_msgs = time.time() + (60 * 10) # 10 minutes
self.timer_send_lists = time.time() + (60 * 5) # 5 minutes
self.timer_send_commands = time.time() + (60 * 5) # 5 minutes
# Net disable settings
self.allow_net_file_size_check = False
self.allow_net_ntp = False
self.refresh_settings()
bm_monitor = Thread(target=self.bitmessage_monitor)
bm_monitor.daemon = True
bm_monitor.start()
def refresh_settings(self):
with session_scope(DB_PATH) as new_session:
settings = new_session.query(GlobalSettings).first()
try:
self._non_bitchan_message_ids = json.loads(settings.discard_message_ids)
except:
self._non_bitchan_message_ids = "[]"
self.allow_net_file_size_check = settings.allow_net_file_size_check
self.allow_net_ntp = settings.allow_net_ntp
def run(self):
while True:
lf = LF()
if (not self.is_restarting_bitmessage and
lf.lock_acquire(config.LOCKFILE_MSG_PROC, to=120)):
try:
self.run_periodic()
finally:
lf.lock_release(config.LOCKFILE_MSG_PROC)
time.sleep(1)
def run_periodic(self):
now = time.time()
#
# Update the time
#
if self.allow_net_ntp:
self.update_ntp = False
if abs(self.time_last - now) > 600:
logger.info("Time changed? Update NTP.")
self.update_ntp = True
self.time_last = now
if self.timer_time_server < now or self.update_ntp:
while self.timer_time_server < now:
self.timer_time_server += (60 * 6 * random.randint(40, 70))
ntp = Thread(target=self.update_utc_offset)
ntp.daemon = True
ntp.start()
#
# Check if sync complete
#
if self.timer_sync < now or self.update_ntp:
while self.timer_sync < now:
self.timer_sync += config.BM_SYNC_CHECK_PERIOD
try:
self.check_sync()
except:
logger.exception("Could not complete check_sync()")
#
# New tor Identity
#
if self.timer_new_tor_identity < now:
while self.timer_new_tor_identity < now:
self.timer_new_tor_identity += random.randint(1200, 7200)
try:
self.new_tor_identity()
except:
logger.exception("Could not complete check_sync()")
#
# Update addresses and messages periodically
#
if self.timer_bm_update < now or self._refresh:
while self.timer_bm_update < now:
self.timer_bm_update += config.BM_REFRESH_PERIOD
self._refresh = False
try:
# logger.info("Updating bitmessage info")
timer = time.time()
self._update_identities()
# self.update_subscriptions() # Currently not used
self.update_address_book()
self.update_chans()
self.queue_new_messages()
list_stats = [
len(self._posts_by_id),
len(self._chan_board_dict),
len(self._chan_list_dict),
len(self._identity_dict),
len(self._address_book_dict)
]
if self.list_stats != list_stats:
msg = str(len(self._posts_by_id))
msg += " post, " if len(self._posts_by_id) == 1 else " posts, "
msg += str(len(self._chan_board_dict))
msg += " board, " if len(self._chan_board_dict) == 1 else " boards, "
msg += str(len(self._chan_list_dict))
msg += " list, " if len(self._chan_list_dict) == 1 else " lists, "
msg += str(len(self._identity_dict))
msg += " identity, " if len(self._identity_dict) == 1 else " identities, "
msg += str(len(self._address_book_dict))
msg += " address book entry" if len(self._address_book_dict) == 1 else " address book entries"
logger.info(msg)
# logger.info("updated in {:.1f} sec".format(time.time() - timer))
self.list_stats = list_stats
except Exception:
logger.exception("Updating bitchan")
#
# Update message thread queue
#
if self.timer_message_threads < now:
while self.timer_message_threads < now:
self.timer_message_threads += 1
try:
self.check_message_threads()
except:
logger.exception("Could not complete check_message_threads()")
#
# Clear upload progress table
#
if self.timer_clear_uploads < now:
while self.timer_clear_uploads < now:
self.timer_clear_uploads += 600
with session_scope(DB_PATH) as new_session:
if self.first_run:
upl = new_session.query(UploadProgress).all()
else:
upl = new_session.query(UploadProgress).filter(and_(
UploadProgress.progress_percent == 100,
UploadProgress.uploading == False
)).all()
for each_upl in upl:
new_session.delete(each_upl)
#
# Clear inventory 10 minutes after last board/list join
#
if self.timer_clear_inventory < now:
with session_scope(DB_PATH) as new_session:
settings = new_session.query(GlobalSettings).first()
if settings and settings.clear_inventory:
self.is_pow_sending()
if self.timer_safe_send < now: # Ensure we don't restart BM while sending
settings.clear_inventory = False
new_session.commit()
try:
self.clear_bm_inventory()
except:
logger.exception("Could not complete clear_bm_inventory()")
#
# Get message expires time if not currently set
#
if self.timer_get_msg_expires_time < now:
while self.timer_get_msg_expires_time < now:
self.timer_get_msg_expires_time += (60 * 10) # 10 minutes
try:
self.get_message_expires_times()
except:
logger.exception("Could not complete get_message_expires_times()")
#
# Delete non-composed identity messages from sent box
#
if self.timer_delete_identity_msgs < now:
while self.timer_delete_identity_msgs < now:
self.timer_delete_identity_msgs += (60 * 10) # 10 minutes
try:
self.delete_identity_msgs()
except:
logger.exception("Could not complete delete_identity_msgs()")
#
# Delete entries in deleted message database 1 day after they expire
#
if self.timer_remove_deleted_msgs < now:
while self.timer_remove_deleted_msgs < now:
self.timer_remove_deleted_msgs += (60 * 60 * 24) # 1 day
try:
logger.info("Checking for expired message entries")
with session_scope(DB_PATH) as new_session:
expired = time.time() - (24 * 60 * 60) # 1 day in the past (expired yesterday)
for each_msg in new_session.query(DeletedMessages).all():
if each_msg.expires_time and expired and each_msg.expires_time < expired:
logger.info("DeletedMessages table: delete: {}, {}".format(
each_msg.expires_time, each_msg.message_id))
new_session.delete(each_msg)
new_session.commit()
except:
logger.exception("remove_deleted_msgs")
#
# Check lists that may be expiring and resend
#
if self.timer_send_lists < now and self.bm_sync_complete:
logger.info("Running send_lists()")
while self.timer_send_lists < now:
self.timer_send_lists += (60 * 60 * 6) # 6 hours
try:
self.send_lists()
except:
logger.exception("Could not complete send_lists()")
#
# Check commands that may be expiring and resend
#
if self.timer_send_commands < now and self.bm_sync_complete:
while self.timer_send_commands < now:
self.timer_send_commands += (60 * 60 * 6) # 6 hours
try:
send_commands()
except:
logger.exception("Could not complete send_commands()")
#
# Get unread mail counts
#
if self.timer_unread_mail < now:
while self.timer_unread_mail < now:
self.timer_unread_mail += config.BM_UNREAD_CHECK_PERIOD
try:
self.check_unread_mail()
except:
logger.exception("Could not complete check_unread_mail()")
#
# Rule: Automatically Wipe Board/List
#
with session_scope(DB_PATH) as new_session:
for each_chan in new_session.query(Chan).all():
if each_chan.rules:
try:
rules = json.loads(each_chan.rules)
if ("automatic_wipe" in rules and
rules["automatic_wipe"]["wipe_epoch"] < now):
self.clear_list_board_contents(each_chan.address)
while rules["automatic_wipe"]["wipe_epoch"] < now:
rules["automatic_wipe"]["wipe_epoch"] += rules["automatic_wipe"]["interval_seconds"]
each_chan.rules = json.dumps(rules)
new_session.commit()
except Exception as err:
logger.error("Error clearing board/list: {}".format(err))
continue
self.first_run = False
def check_sync(self):
"""Determine if a Bitmessage sync has completed"""
lf = LF()
if lf.lock_acquire("/var/lock/bm_sync_check.lock", to=60):
try:
self.check_sync_locked()
except Exception as err:
logger.error("Error: {}".format(err))
finally:
lf.lock_release("/var/lock/bm_sync_check.lock")
def check_sync_locked(self):
"""Determine if a Bitmessage sync has completed"""
bm_status = {}
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
bm_status = self._api.clientStatus()
except Exception as err:
logger.error("Error: {}".format(err))
finally:
lf.lock_release(config.LOCKFILE_API)
if "networkStatus" in bm_status:
if bm_status["networkStatus"] != "notConnected":
if not self.bm_connected_timer:
# upon becoming connected, wait 90 sec until checking if synced
self.bm_connected_timer = time.time() + 90
self.bm_connected = True
else:
self.bm_connected = False
self.bm_connected_timer = None
self.bm_pending_download_timer = None
if "pendingDownload" in bm_status:
if bm_status["pendingDownload"] == 0:
self.bm_pending_download = False
else:
self.bm_pending_download = True
self.bm_sync_complete = False
if self.bm_connected:
if bm_status["pendingDownload"] < 50:
if not self.bm_pending_download_timer:
self.bm_pending_download_timer = time.time() + 60
else:
self.bm_pending_download_timer = None
self.bm_sync_complete = False
# indicate sync is complete if:
# 1) connected and no pending downloads for past 60 seconds.
# or
# 2) connected and only a few pending downloads remain and
# have not increased over 50 in the past 60 seconds.
if (self.bm_connected and
(self.bm_connected_timer and time.time() > self.bm_connected_timer) and
(
not self.bm_pending_download or
(self.bm_pending_download_timer and
time.time() > self.bm_pending_download_timer)
)):
self.bm_connected_timer = None
self.bm_pending_download_timer = None
self.bm_sync_complete = True
# logger.info("con {}, pend {} {}, synced {}".format(
# self.bm_connected,
# bm_status["pendingDownload"],
# self.bm_pending_download,
# self.bm_sync_complete))
def send_lists(self):
for list_address in self.get_list_chans():
from_address = None
run_id = get_random_alphanumeric_string(
6, with_punctuation=False, with_spaces=False)
try:
list_chan = db_return(Chan).filter(and_(
Chan.type == "list",
Chan.address == list_address)).first()
if not list_chan:
continue
logger.info("{}: Checking list {} ({})".format(
run_id, list_chan.address, list_chan.label))
list_access = get_access(list_address)
errors, dict_chan_info = process_passphrase(list_chan.passphrase)
if not dict_chan_info or errors:
logger.error("{}: Error(s) sending list message to {}".format(
run_id, list_chan.address))
for err in errors:
logger.error(err)
break
from_primary_secondary = self.find_senders(
list_address, ["primary_addresses", "secondary_addresses"])
from_tertiary = self.find_senders(
list_address, ["tertiary_addresses"])
try:
rules = json.loads(list_chan.rules)
except:
rules = {}
from_non_self = []
requires_identity = False
if (dict_chan_info["access"] == "public" and
"require_identity_to_post" in rules and
rules["require_identity_to_post"]):
requires_identity = True
for each_add in self.get_all_chans():
if each_add != list_address and each_add not in list_access["restricted_addresses"]:
from_non_self.append(each_add)
for each_add in self.get_identities():
if each_add != list_address and each_add not in list_access["restricted_addresses"]:
from_non_self.append(each_add)
if list_chan.list_send:
logger.info("{}: List instructed to send.".format(run_id))
with session_scope(DB_PATH) as new_session:
list_mod = new_session.query(Chan).filter(
Chan.address == list_address).first()
list_mod.list_send = False
new_session.commit()
allowed_addresses = []
if from_primary_secondary:
allowed_addresses += from_primary_secondary
if from_tertiary:
allowed_addresses += from_tertiary
if (dict_chan_info["access"] == "public" and
requires_identity and
from_non_self):
allowed_addresses += from_non_self
if dict_chan_info["access"] == "public":
allowed_addresses.append(list_address)
if allowed_addresses and list_chan.default_from_address in allowed_addresses:
from_address = list_chan.default_from_address
elif allowed_addresses:
from_address = allowed_addresses[0]
else:
from_address = None
elif from_primary_secondary and list_chan.list_message_expires_time_owner:
if self.expiring_from_expires_time(run_id, list_chan.list_message_expires_time_owner):
logger.info("{}: List expiring for owner with expires_time.".format(run_id))
from_address = from_primary_secondary[0]
else:
continue
elif from_tertiary and list_chan.list_message_expires_time_user:
if self.expiring_from_expires_time(run_id, list_chan.list_message_expires_time_user):
logger.info("{}: List expiring for user with expires_time.".format(run_id))
from_address = from_tertiary[0]
else:
continue
elif (dict_chan_info["access"] == "public" and
requires_identity and
from_non_self and
list_chan.list_message_expires_time_user):
if self.expiring_from_expires_time(run_id, list_chan.list_message_expires_time_user):
logger.info("{}: List expiring for user with expires_time and is public "
"with rule requires_identity_to_post.".format(run_id))
from_address = from_non_self[0]
else:
continue
elif dict_chan_info["access"] == "public" and list_chan.list_message_expires_time_user:
if self.expiring_from_expires_time(run_id, list_chan.list_message_expires_time_user):
logger.info("{}: List expiring for user with expires_time and is public.".format(run_id))
from_address = list_address
else:
continue
elif from_primary_secondary and list_chan.list_message_timestamp_utc_owner:
if self.expiring_from_timestamp(run_id, list_chan.list_message_timestamp_utc_owner):
logger.info("{}: List expiring for owner with timestamp.".format(run_id))
from_address = from_primary_secondary[0]
else:
continue
elif from_tertiary and list_chan.list_message_timestamp_utc_user:
if self.expiring_from_timestamp(run_id, list_chan.list_message_timestamp_utc_user):
logger.info("{}: List expiring for user with timestamp.".format(run_id))
from_address = from_tertiary[0]
else:
continue
elif (dict_chan_info["access"] == "public" and
requires_identity and
from_non_self and
list_chan.list_message_timestamp_utc_user):
if self.expiring_from_timestamp(run_id, list_chan.list_message_timestamp_utc_user):
logger.info("{}: List expiring for user with timestamp and is public "
"with rule requires_identity_to_post.".format(run_id))
from_address = from_non_self[0]
else:
continue
elif dict_chan_info["access"] == "public" and list_chan.list_message_timestamp_utc_user:
if self.expiring_from_timestamp(run_id, list_chan.list_message_timestamp_utc_user):
logger.info("{}: List expiring for user with timestamp and is public.".format(run_id))
from_address = list_address
else:
continue
else:
logger.info("{}: List not expiring or you don't have an address authorized to send.".format(run_id))
continue
if not from_address:
continue
send_msg_dict = {
"version": config.VERSION_BITCHAN,
"timestamp_utc": self.get_utc(),
"message_type": "list",
"access": list_chan.access,
"list": json.loads(list_chan.list)
}
pgp_passphrase_msg = config.PGP_PASSPHRASE_MSG
if list_chan.pgp_passphrase_msg:
pgp_passphrase_msg = list_chan.pgp_passphrase_msg
gpg = gnupg.GPG()
message_encrypted = gpg.encrypt(
json.dumps(send_msg_dict),
symmetric="AES256",
passphrase=pgp_passphrase_msg,
recipients=None)
message_send = base64.b64encode(message_encrypted.data).decode()
# Don't send empty public list
if dict_chan_info["access"] == "public" and len(send_msg_dict["list"]) == 0:
continue
logger.info("{}: Sending {} list message with {} entries from {} to {}".format(
run_id,
dict_chan_info["access"],
len(send_msg_dict["list"]),
from_address,
list_address))
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
return_str = self._api.sendMessage(
list_address,
from_address,
"",
message_send,
2,
config.BM_TTL)
if return_str:
self.post_delete_queue(from_address, return_str)
time.sleep(0.1)
except Exception:
pass
finally:
lf.lock_release(config.LOCKFILE_API)
except Exception:
logger.exception("send_lists()")
def get_message_expires_times(self):
try:
with session_scope(DB_PATH) as new_session:
msg_inbox = new_session.query(Messages).filter(
Messages.expires_time == None).all()
for each_msg in msg_inbox:
expires = get_msg_expires_time(each_msg.message_id)
if expires:
logger.info("{}: Messages: Set expire time to {}".format(
each_msg.message_id[-config.ID_LENGTH:].upper(), expires))
each_msg.expires_time = expires
else:
logger.info("{}: Messages: No inventory entry.".format(
each_msg.message_id[-config.ID_LENGTH:].upper()))
msg_deleted = new_session.query(DeletedMessages).filter(
DeletedMessages.expires_time == None).all()
for each_msg in msg_deleted:
expires = get_msg_expires_time(each_msg.message_id)
if expires:
logger.info("{}: DeletedMessages: Set expire time to {}".format(
each_msg.message_id[-config.ID_LENGTH:].upper(), expires))
each_msg.expires_time = expires
# Update list expires time for owner messages
chan_list = new_session.query(Chan).filter(and_(
Chan.type == "list",
Chan.list_message_id_owner == each_msg.message_id,
Chan.list_message_expires_time_owner == None
)).first()
if chan_list:
chan_list.list_message_expires_time_owner = expires
if expires > self.get_utc():
days = (expires - self.get_utc()) / 60 / 60 / 24
logger.info("{}: Setting empty owner list expire time to {} ({:.1f} days from now)".format(
each_msg.message_id[-config.ID_LENGTH:].upper(), expires, days))
# Update list expires time for user messages
chan_list = new_session.query(Chan).filter(and_(
Chan.type == "list",
Chan.list_message_id_user == each_msg.message_id,
Chan.list_message_expires_time_user == None
)).first()
if chan_list:
chan_list.list_message_expires_time_user = expires
if expires > self.get_utc():
days = (expires - self.get_utc()) / 60 / 60 / 24
logger.info(
"{}: Setting empty user list expire time to {} ({:.1f} days from now)".format(
each_msg.message_id[-config.ID_LENGTH:].upper(), expires, days))
else:
logger.info("{}: DeletedMessages. No inventory entry.".format(
each_msg.message_id[-config.ID_LENGTH:].upper()))
new_session.commit()
except:
logger.exception("get_msg_expires_time")
def get_unread_mail_count(self, address):
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
messages = self._api.getInboxMessagesByReceiver(address)
if "inboxMessages" in messages:
unread_count = 0
for each_msg in messages["inboxMessages"]:
if not each_msg["read"]:
unread_count += 1
return unread_count
except Exception as err:
logger.error("Error: {}".format(err))
finally:
lf.lock_release(config.LOCKFILE_API)
def set_unread_mail_count(self, address):
with session_scope(DB_PATH) as new_session:
ident = new_session.query(Identity).filter(
Identity.address == address).first()
ident.unread_messages = self.get_unread_mail_count(address)
new_session.commit()
def check_unread_mail(self):
"""Save number of unread messages for each Identity"""
with session_scope(DB_PATH) as new_session:
for identity in new_session.query(Identity).all():
self.set_unread_mail_count(identity.address)
def _update_identities(self):
new_identities = {}
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
dict_return = self._api.listAddresses()
time.sleep(0.1)
except Exception as err:
logger.error("Exception getting identities: {}".format(err))
return
finally:
lf.lock_release(config.LOCKFILE_API)
else:
return
for address in dict_return['addresses']:
if not address['chan']:
new_identities[address['address']] = {
"label": address['label'],
"enabled": address['enabled']
}
if len(address['label']) > config.LABEL_LENGTH:
new_identities[address['address']]["label_short"] = address['label'][:config.LABEL_LENGTH]
else:
new_identities[address['address']]["label_short"] = address['label']
if self._identity_dict.keys() != new_identities.keys() or self._refresh_identities:
self._refresh_identities = False
logger.info("Adding/Updating Identities")
with session_scope(DB_PATH) as new_session:
for address, each_ident in new_identities.items():
identity = new_session.query(
Identity).filter(Identity.address == address).first()
if not identity:
new_ident = Identity()
new_ident.address = address
new_ident.label = each_ident["label"]
new_session.add(new_ident)
new_session.commit()
else:
new_identities[address]["label"] = identity.label
if len(new_identities[address]["label"]) > config.LABEL_LENGTH:
new_identities[address]["label_short"] = new_identities[address]["label"][:config.LABEL_LENGTH]
else:
new_identities[address]["label_short"] = new_identities[address]["label"]
self._identity_dict = new_identities
def update_subscriptions(self):
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
dict_return = self._api.listSubscriptions()
time.sleep(0.1)
except Exception as err:
logger.error("Exception getting subscriptions: {}".format(err))
return
finally:
lf.lock_release(config.LOCKFILE_API)
else:
return
for address in dict_return['subscriptions']:
dict_subscription = {
"label": address['label'],
"enabled": address['enabled']
}
if (address['address'] not in self._subscription_dict or
self._subscription_dict[address['address']] != dict_subscription):
logger.info("Adding/Updating Identity {}".format(address['address']))
self._subscription_dict[address['address']] = dict_subscription
def update_address_book(self):
new_addresses = {}
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
dict_return = self._api.listAddressBookEntries()
time.sleep(0.1)
except Exception as err:
logger.error("Exception getting address book entries: {}".format(err))
return
finally:
lf.lock_release(config.LOCKFILE_API)
else:
return
for address in dict_return["addresses"]:
label = base64.b64decode(address["label"]).decode()
new_addresses[address["address"]] = {"label": label}
with session_scope(DB_PATH) as new_session:
for address in new_session.query(AddressBook).all():
if address.address not in new_addresses:
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
self._api.addAddressBookEntry(address.address, address.label)
new_addresses[address.address] = {"label": address.label}
time.sleep(0.1)
except Exception as err:
logger.error("Exception adding address book entry: {}".format(err))
finally:
lf.lock_release(config.LOCKFILE_API)
for address in new_addresses:
label = new_addresses[address]["label"]
if len(label) > config.LABEL_LENGTH:
new_addresses[address]["label_short"] = label[:config.LABEL_LENGTH]
else:
new_addresses[address]["label_short"] = label
if self._address_book_dict.keys() != new_addresses.keys() or self._refresh_address_book:
self._refresh_address_book = False
logger.info("Adding/Updating Address Book")
with session_scope(DB_PATH) as new_session:
for address, each_add in new_addresses.items():
address_book = new_session.query(
AddressBook).filter(AddressBook.address == address).first()
if not address_book:
new_add_book = AddressBook()
new_add_book.address = address
new_add_book.label = each_add["label"]
new_session.add(new_add_book)
new_session.commit()
else:
new_addresses[address]["label"] = address_book.label
if len(new_addresses[address]["label"]) > config.LABEL_LENGTH:
new_addresses[address]["label_short"] = new_addresses[address]["label"][:config.LABEL_LENGTH]
else:
new_addresses[address]["label_short"] = new_addresses[address]["label"]
self._address_book_dict = new_addresses
def update_chans(self):
chans_labels = {}
chans_addresses = {}
all_chans = {}
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
dict_return = self._api.listAddresses()
time.sleep(0.1)
except Exception as err:
logger.error("Exception getting chans: {}".format(err))
return
finally:
lf.lock_release(config.LOCKFILE_API)
else:
return
for address in dict_return['addresses']:
# logger.info("Chan: {}".format(address))
if address['chan']:
all_chans[address['address']] = {
"label": address['label'],
"enabled": address['enabled']
}
with session_scope(DB_PATH) as new_session:
# Only scan chans from the bitchan database
# Leave other chans alone
chan = new_session.query(
Chan).filter(Chan.address == address['address']).first()
if chan and address['chan'] and address['enabled']:
chans_labels[address['label']] = address['address']
chans_addresses[address['address']] = address['label']
if address['chan']:
if chan:
all_chans[address['address']]["label"] = chan.label
label = all_chans[address['address']]["label"]
if len(all_chans[address['address']]["label"]) > config.LABEL_LENGTH:
all_chans[address['address']]["label_short"] = label[:config.LABEL_LENGTH]
else:
all_chans[address['address']]["label_short"] = label
if self._all_chans != all_chans:
self._all_chans = all_chans
with session_scope(DB_PATH) as new_session:
# Join board chan if found in database and not found in Bitmessage
board_chans = new_session.query(Chan).filter(Chan.type == "board").all()
for each_board in board_chans:
if not each_board.is_setup:
logger.info("Found board chan in database that needs to be joined. Joining.")
address = self.join_chan(each_board.passphrase, clear_inventory=False)
time.sleep(1)
if address and "Chan address is already present" in address:
logger.info("Board already present in Bitmessage. Updating database.")
for each_address in self._all_chans:
if each_board.passphrase in self._all_chans[each_address]["label"]:
each_board.address = each_address
break
each_board.is_setup = True
new_session.commit()
elif address and address.startswith("BM-") and not each_board.address:
each_board.address = address
each_board.is_setup = True
new_session.commit()
else:
logger.info("Could not join board. Joining might be queued. Trying again later.")
if (each_board.address not in self._chan_board_dict and
each_board.address in chans_addresses):
self._chan_board_dict[each_board.address] = chans_addresses[each_board.address]
# Join list chans if in database and not added to Bitmessage
chans_list = new_session.query(Chan).filter(Chan.type == "list").all()
for each_list in chans_list:
if not each_list.is_setup:
# Chan in bitmessage not in database. Add to database, generate and send list message.
logger.info("Found list chan in database that needs to be joined. Joining.")
# Join default list chan
address = self.join_chan(each_list.passphrase, clear_inventory=False)
time.sleep(1)
if address and "Chan address is already present" in address:
logger.info("List already present in bitmessage. Updating database.")
for each_address in self._all_chans:
if each_list.passphrase in self._all_chans[each_address]["label"]:
each_list.address = each_address
break
each_list.is_setup = True
new_session.commit()
elif address and address.startswith("BM-") and not each_list.address:
each_list.address = address
each_list.is_setup = True
new_session.commit()
else:
logger.info("Could not join list. Joining might be queued. Trying again later.")
if (each_list.address not in self._chan_list_dict and
each_list.address in chans_addresses):
self._chan_list_dict[each_list.address] = chans_addresses[each_list.address]
def queue_new_messages(self):
"""Add new messages to processing queue"""
messages = []
for each_address in self.get_all_chans():
lf = LF()
if lf.lock_acquire(config.LOCKFILE_API, to=60):
try:
messages_api = self._api.getInboxMessagesByReceiver(each_address)
if "inboxMessages" in messages_api and messages_api['inboxMessages']:
messages.extend(messages_api['inboxMessages'])
time.sleep(0.1)
except Exception as err:
logger.error("Exception getting all message IDs: {}".format(err))
return
finally:
lf.lock_release(config.LOCKFILE_API)
else:
return
with session_scope(DB_PATH) as new_session:
for message in messages:
if new_session.query(DeletedMessages).filter(
DeletedMessages.message_id == message["msgid"]).count():
logger.info("{}: Message labeled as deleted. Deleting.".format(
message["msgid"][-config.ID_LENGTH:].upper()))
self.trash_message(message["msgid"])
continue
if message["msgid"] in self._non_bitchan_message_ids:
continue
if (message["msgid"] in self._posts_by_id and
message["msgid"] not in self.list_start_download):
logger.debug("{}: Message already processed. return.".format(
message["msgid"][-config.ID_LENGTH:].upper()))
continue
message_db = new_session.query(Messages).filter(
Messages.message_id == message["msgid"]).first()
if message_db:
if (message["msgid"] in self.list_start_download and
not message_db.file_currently_downloading):
# Download instructed to start by user. Only initiate
# download once, and skip further processing attempts
# unless download has failed. Use thread to allow new
# messages to continue to be processed while
# downloading.
message_db.file_progress = "Download starting"
message_db.file_currently_downloading = True
new_session.commit()
thread_download = Thread(target=self._posts_by_id[message["msgid"]].allow_download)
thread_download.daemon = True
thread_download.start()
continue
# If the server restarted while a download was underway,