forked from yguy2/PyBitmessage-CLI
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbitmessagecli.py
More file actions
1837 lines (1661 loc) · 88.9 KB
/
bitmessagecli.py
File metadata and controls
1837 lines (1661 loc) · 88.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2.7
# Originally created by Adam Melton (Dokument)
# Modified by Scott King (Lvl4Sword)
# Distributed under the MIT/X11 software license
# See http://www.opensource.org/licenses/mit-license.php
# https://bitmessage.org/wiki/API_Reference for API documentation
import base64
import ConfigParser
import datetime
import imghdr
import json
import os
import random
import signal
import socket
import subprocess
import sys
# Because without it we'll be warned about not being connected to the API
import time
import xml
import xmlrpclib
import string
APPNAME = 'PyBitmessage'
CHARACTERS = string.digits + string.ascii_letters
SECURE_RANDOM = random.SystemRandom()
CONFIG = ConfigParser.RawConfigParser()
PROXY_TYPE_DICT = {'none': 'none', 'socks4a': 'SOCKS4a', 'socks5': 'SOCKS5'}
class Bitmessage(object):
def __init__(self):
# What we'll use to actually connect to Bitmessage ( main() )
self.api = ''
# Works even if you're in the same directory as the cli
# and bitmessagemain, which os.path.dirname(__file__) didn't
self.program_dir = os.path.dirname(os.path.realpath(__file__))
self.keys_path = self.program_dir
self.keys_file = os.path.join(self.keys_path, 'keys.dat')
self.bm_active = False
# This is for the subprocess call ( run_bitmessage() )
self.enable_bm = 0
self.api_import = False
# Used for the self.api call and initial running of bitmessage
self.first_run = True
self.commands = {'addinfo': self.add_info,
'apitest': self.api_test,
'bmsettings': self.bm_settings,
'listaddresses': self.list_add,
'generateaddress': self.generate_an_address,
'getaddress': self.get_address,
'deleteaddress': self.delete_address,
'listaddressbook': self.list_address_book,
'addaddressbook': self.add_address_book,
'deleteaddressbook': self.delete_address_book,
'listsubscriptions': self.list_subscriptions,
'status': self.client_status,
'subscribe': self.subscribe,
'unsubscribe': self.unsubscribe,
'inbox': [self.inbox, False],
'unread': [self.inbox, True],
'create': self.create_chan,
'join': self.join_chan,
'leave': self.leave_chan,
'outbox': self.outbox,
'send': self.send_something,
'read': self.read_something,
'save': self.save_message,
'delete': self.delete_message,
'markallmessagesunread': self.mark_all_messages_unread,
'markallmessagesread': self.mark_all_messages_read}
self.settings_options = {'daemon': 'boolean',
'timeformat': '',
'blackwhitelist': 'boolean',
'socksproxytype': ['none', 'SOCKS4a', 'SOCKS5'],
'sockshostname': '',
'socksport': '',
'socksauthentication': 'boolean',
'socksusername': '',
'sockspassword': '',
'sockslisten': 'boolean',
'digestalg': ['sha256', 'sha1'],
'keysencrypted': 'boolean',
'messagesencrypted': 'boolean',
'defaultnoncetrialsperbyte': '',
'defaultpayloadlengthextrabytes': '',
'maxacceptablenoncetrialsperbyte': '',
'maxacceptablepayloadlengthextrabytes': '',
'userlocale': '',
'replybelow': '',
'maxdownloadrate': '',
'maxuploadrate': '',
'maxoutboundconnections': '',
'ttl': '',
'stopresendingafterxdays': '',
'stopresendingafterxmonths': '',
'namecoinrpctype': '',
'namecoinrpchost': '',
'namecoinrpcuser': '',
'namecoinrpcpassword': '',
'namecoinrpcport': '',
'sendoutgoingconnections': '',
'onionhostname': '',
'onionbindip': '',
'hidetrayconnectionnotifications': '',
'trayonclose': '',
'willinglysendtomobile': '',
'opencl': 'boolean'}
# Checks input for exit or quit, strips all input,
# and catches keyboard exits
def user_input(self, message):
try:
print('\n{0}'.format(message))
the_input = raw_input('> ').strip()
except(EOFError, KeyboardInterrupt):
self.kill_program()
else:
if the_input.lower() in ['exit', 'x']:
self.main()
elif the_input.lower() in ['quit', 'q']:
self.kill_program()
elif the_input.lower() in ['help', 'h', '?']:
self.view_help()
self.main()
else:
try:
if self.enable_bm.poll() is not None:
self.preparations()
time.sleep(2.5)
except AttributeError:
pass
return the_input
def kill_program(self):
try:
print('Shutting down..')
self.api.shutdown()
sys.exit(0)
except(AttributeError, OSError, socket.error):
sys.exit(1)
# This isn't currently used, but best to keep it in as it may be used later.
def lookup_appdata_folder(self):
if sys.platform.startswith('darwin'):
if 'HOME' in os.environ:
self.keys_path = os.path.join(os.environ['HOME'],
'Library/Application support/',
APPNAME)
else:
print('Could not find your home folder.')
print('Please report this message and your OS X version at:')
print('https://github.com/Bitmessage/PyBitmessage/issues/')
self.kill_program()
elif sys.platform.startswith('win'):
self.keys_path = os.path.join(os.environ['APPDATA'], APPNAME)
else:
self.keys_path = os.path.join(os.path.expanduser('~'), '.config', APPNAME)
def return_api(self):
try:
CONFIG.read(self.keys_file)
api_username = CONFIG.get('bitmessagesettings', 'apiusername')
api_password = CONFIG.get('bitmessagesettings', 'apipassword')
api_interface = CONFIG.get('bitmessagesettings', 'apiinterface')
api_port = CONFIG.getint('bitmessagesettings', 'apiport')
except ConfigParser.MissingSectionHeaderError:
print("'bitmessagesettings' header is missing.")
self.config_init()
except ConfigParser.NoOptionError as e:
print("{0} and possibly others are missing.".format(str(e).split("'")[1]))
self.config_init()
except socket.error as e:
self.api_import = False
else:
if self.first_run:
# For whatever reason, the API doesn't connect right away unless
# we pause for 1 second or more.
# Not sure if it's a xmlrpclib or BM issue, but it's annoying.
time.sleep(2.5)
self.first_run = False
# Build the api credentials
self.api_import = True
return 'http://{0}:{1}@{2}:{3}/'.format(api_username,
api_password,
api_interface,
api_port)
def config_init(self):
print("I'm going to ask you a series of questions..")
try:
CONFIG.add_section('bitmessagesettings')
except ConfigParser.DuplicateSectionError:
pass
CONFIG.set('bitmessagesettings', 'port', '8444')
CONFIG.set('bitmessagesettings', 'settingsversion', '10')
# 17600 - 17650 is set for OnionShare in the Tails OS.
# If this is randomized, it won't work.
# Thus, won't connect using xmlrpclib.
CONFIG.set('bitmessagesettings', 'apiport', '17650')
CONFIG.set('bitmessagesettings', 'apiinterface', '127.0.0.1')
CONFIG.set('bitmessagesettings', 'apiusername',
''.join([SECURE_RANDOM.choice(CHARACTERS) for x in range(0,64)]))
CONFIG.set('bitmessagesettings', 'apipassword',
''.join([SECURE_RANDOM.choice(CHARACTERS) for x in range(0,64)]))
CONFIG.set('bitmessagesettings', 'daemon', True)
CONFIG.set('bitmessagesettings', 'timeformat', '%%c')
CONFIG.set('bitmessagesettings', 'blackwhitelist', 'black')
CONFIG.set('bitmessagesettings', 'startonlogon', 'False')
CONFIG.set('bitmessagesettings', 'minimizetotray', 'False')
CONFIG.set('bitmessagesettings', 'showtraynotifications', 'True')
CONFIG.set('bitmessagesettings', 'startintray', 'False')
CONFIG.set('bitmessagesettings', 'socksproxytype', 'none')
CONFIG.set('bitmessagesettings', 'sockshostname', 'localhost')
CONFIG.set('bitmessagesettings', 'socksport', '9050')
CONFIG.set('bitmessagesettings', 'socksauthentication', 'False')
CONFIG.set('bitmessagesettings', 'sockslisten', 'False')
CONFIG.set('bitmessagesettings', 'socksusername', '')
CONFIG.set('bitmessagesettings', 'sockspassword', '')
# https://www.reddit.com/r/bitmessage/comments/5vt3la/sha1_and_bitmessage/deev8je/
CONFIG.set('bitmessagesettings', 'digestalg', 'sha256')
CONFIG.set('bitmessagesettings', 'keysencrypted', 'False')
CONFIG.set('bitmessagesettings', 'messagesencrypted', 'False')
CONFIG.set('bitmessagesettings', 'defaultnoncetrialsperbyte', '1000')
CONFIG.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', '1000')
CONFIG.set('bitmessagesettings', 'minimizeonclose', 'False')
CONFIG.set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', '20000000000')
CONFIG.set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', '20000000000')
CONFIG.set('bitmessagesettings', 'userlocale', 'system')
CONFIG.set('bitmessagesettings', 'useidenticons', 'False')
CONFIG.set('bitmessagesettings', 'identiconsuffix', '')
CONFIG.set('bitmessagesettings', 'replybelow', 'False')
CONFIG.set('bitmessagesettings', 'maxdownloadrate', '0')
CONFIG.set('bitmessagesettings', 'maxuploadrate', '0')
CONFIG.set('bitmessagesettings', 'maxoutboundconnections', '8')
CONFIG.set('bitmessagesettings', 'ttl', '367200')
CONFIG.set('bitmessagesettings', 'stopresendingafterxdays', '')
CONFIG.set('bitmessagesettings', 'stopresendingafterxmonths', '')
CONFIG.set('bitmessagesettings', 'namecoinrpctype', 'namecoind')
CONFIG.set('bitmessagesettings', 'namecoinrpchost', 'localhost')
CONFIG.set('bitmessagesettings', 'namecoinrpcuser', '')
CONFIG.set('bitmessagesettings', 'namecoinrpcpassword', '')
CONFIG.set('bitmessagesettings', 'namecoinrpcport', '8336')
CONFIG.set('bitmessagesettings', 'sendoutgoingconnections', 'True')
CONFIG.set('bitmessagesettings', 'onionhostname', '')
CONFIG.set('bitmessagesettings', 'onionbindip', '127.0.0.1')
CONFIG.set('bitmessagesettings', 'hidetrayconnectionnotifications', 'False')
CONFIG.set('bitmessagesettings', 'trayonclose', 'False')
CONFIG.set('bitmessagesettings', 'willinglysendtomobile', 'False')
CONFIG.set('bitmessagesettings', 'opencl', 'None')
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
enable_proxy = self.user_input('Enable proxy (Y/n)?').lower()
if enable_proxy in ['yes', 'y']:
print('Proxy settings are:')
print('Type: {0}'.format(CONFIG.get('bitmessagesettings', 'socksproxytype')))
print('Port: {0}'.format(CONFIG.getint('bitmessagesettings', 'socksport')))
print('Host: {0}'.format(CONFIG.get('bitmessagesettings', 'sockshostname')))
double_check_proxy = self.user_input('Do these need to be changed? (Y/n)').lower()
if double_check_proxy in ['yes', 'y']:
while True:
invalid_input = False
setting_input = self.user_input('What setting would you like to modify? (enter to exit)').lower()
if setting_input == 'type':
setting_input = self.user_input('Possibilities: \'none\', \'SOCKS4a\', \'SOCKS5\'').lower()
if setting_input in PROXY_TYPE_DICT.keys():
CONFIG.set('bitmessagesettings', 'socksproxytype', PROXY_TYPE_DICT[setting_input])
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
else:
print('socksproxytype was not changed')
invalidInput = True
elif setting_input == 'port':
try:
setting_input = int(self.user_input('Please input proxy port'))
if 1 <= setting_input <= 65535:
CONFIG.set('bitmessagesettings', 'socksport', setting_input)
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
else:
print('That\'s an invalid port number')
except ValueError:
print('How were you expecting that to work?')
invalidInput = True
elif setting_input == 'host':
setting_input = int(self.user_input('Please input proxy hostname'))
CONFIG.set('bitmessagesettings', 'sockshostname', setting_input)
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
elif setting_input == '':
break
else:
print('That\'s not an option.')
invalid_input = True
if not invalid_input:
print('Proxy settings are:')
print('Type: {0}'.format(CONFIG.get('bitmessagesettings', 'socksproxytype')))
print('Port: {0}'.format(CONFIG.getint('bitmessagesettings', 'socksport')))
print('Host: {0}'.format(CONFIG.get('bitmessagesettings', 'sockshostname')))
exit_verification = self.user_input('Would you like to change anything else? (Y/n)')
if exit_verification in ['yes', 'y']:
pass
else:
break
else:
CONFIG.set('bitmessagesettings', 'socksproxytype', 'none')
# Prevents Exit or Quit from overriding the proxy question
CONFIG.set('bitmessagesettings', 'apienabled', 'True')
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
def api_data(self):
try:
CONFIG.read(self.keys_file)
CONFIG.getint('bitmessagesettings', 'port')
CONFIG.getboolean('bitmessagesettings', 'apienabled')
CONFIG.getint('bitmessagesettings', 'settingsversion')
CONFIG.getint('bitmessagesettings', 'apiport')
CONFIG.get('bitmessagesettings', 'apiinterface')
CONFIG.get('bitmessagesettings', 'apiusername')
CONFIG.get('bitmessagesettings', 'apipassword')
CONFIG.getboolean('bitmessagesettings', 'daemon')
CONFIG.get('bitmessagesettings', 'timeformat')
CONFIG.get('bitmessagesettings', 'blackwhitelist')
CONFIG.getboolean('bitmessagesettings', 'startonlogon')
CONFIG.getboolean('bitmessagesettings', 'minimizetotray')
CONFIG.getboolean('bitmessagesettings', 'showtraynotifications')
CONFIG.getboolean('bitmessagesettings', 'startintray')
CONFIG.get('bitmessagesettings', 'sockshostname')
CONFIG.getint('bitmessagesettings', 'socksport')
CONFIG.getboolean('bitmessagesettings', 'socksauthentication')
CONFIG.getboolean('bitmessagesettings', 'sockslisten')
CONFIG.get('bitmessagesettings', 'socksusername')
CONFIG.get('bitmessagesettings', 'digestalg')
CONFIG.get('bitmessagesettings', 'sockspassword')
CONFIG.get('bitmessagesettings', 'socksproxytype')
CONFIG.getboolean('bitmessagesettings', 'keysencrypted')
CONFIG.getboolean('bitmessagesettings', 'messagesencrypted')
CONFIG.getint('bitmessagesettings', 'defaultnoncetrialsperbyte')
CONFIG.getint('bitmessagesettings', 'defaultpayloadlengthextrabytes')
CONFIG.getboolean('bitmessagesettings', 'minimizeonclose')
CONFIG.getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte')
CONFIG.getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')
CONFIG.get('bitmessagesettings', 'userlocale')
CONFIG.getboolean('bitmessagesettings', 'useidenticons')
CONFIG.get('bitmessagesettings', 'identiconsuffix')
CONFIG.getboolean('bitmessagesettings', 'replybelow')
CONFIG.getint('bitmessagesettings', 'maxdownloadrate')
CONFIG.getint('bitmessagesettings', 'maxuploadrate')
CONFIG.getint('bitmessagesettings', 'maxoutboundconnections')
CONFIG.getint('bitmessagesettings', 'ttl')
CONFIG.get('bitmessagesettings', 'stopresendingafterxdays')
CONFIG.get('bitmessagesettings', 'stopresendingafterxmonths')
CONFIG.get('bitmessagesettings', 'namecoinrpctype')
CONFIG.get('bitmessagesettings', 'namecoinrpchost')
CONFIG.get('bitmessagesettings', 'namecoinrpcuser')
CONFIG.get('bitmessagesettings', 'namecoinrpcpassword')
CONFIG.getint('bitmessagesettings', 'namecoinrpcport')
CONFIG.getboolean('bitmessagesettings', 'sendoutgoingconnections')
CONFIG.get('bitmessagesettings', 'onionhostname')
CONFIG.get('bitmessagesettings', 'onionbindip')
CONFIG.getboolean('bitmessagesettings', 'hidetrayconnectionnotifications')
CONFIG.getboolean('bitmessagesettings', 'trayonclose')
CONFIG.getboolean('bitmessagesettings', 'willinglysendtomobile')
CONFIG.get('bitmessagesettings', 'opencl')
CONFIG.set('bitmessagesettings', 'daemon', True)
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
except ConfigParser.NoOptionError as e:
print("{0} and possibly others are missing.".format(str(e).split("'")[1]))
self.config_init()
except ConfigParser.NoSectionError:
print("No section 'bitmessagesettings'")
self.config_init()
def api_test(self):
try:
if self.api_check():
print('API connection test has: PASSED')
else:
print('API connection test has: FAILED')
except socket.error:
self.api_import = False
return False
# Tests the API connection to bitmessage.
# Returns True if it is connected.
def api_check(self):
try:
result = self.api.add(2,3)
except socket.error:
self.api_import = False
return False
else:
if result == 5:
return True
else:
return False
# Allows the viewing and modification of keys.dat settings.
def bm_settings(self):
# Read the keys.dat
self.current_settings()
while True:
modify_settings = self.user_input('Would you like to modify any of these settings, (Y)/(n)').lower()
if modify_settings:
break
if modify_settings in ['yes', 'y']:
# loops if they mistype the setting name, they can exit the loop with 'exit')
while True:
invalid_input = True
which_modify = self.user_input('What setting would you like to modify?').lower()
if which_modify in self.settings_options.keys():
how_modify = self.user_input('What would you like to set {0} to?'.format(which_modify)).lower()
if how_modify in self.settings_options[which_modify]:
CONFIG.set('bitmessagesettings', which_modify, how_modify)
invalid_input = False
elif self.settings_options[which_modify] == 'boolean':
if how_modify in ['true', 'false']:
CONFIG.set('bitmessagesettings', which_modify, how_modify)
invalid_input = False
elif self.settings_options[which_modify] == ['none', 'SOCKS4a', 'SOCKS5']:
CONFIG.set('bitmessagesettings', which_modify, PROXY_TYPE_DICT[how_modify])
invalid_input = False
elif self.settings_options[which_modify] in ['sha256', 'sha1']:
CONFIG.set('bitmessagesettings', which_modify, how_modify)
invalid_input = False
elif self.settings_options[which_modify] == '':
CONFIG.set('bitmessagesettings', which_modify, how_modify)
invalid_input = False
else:
print("The way you were trying to modify {0} is invalid.".format(which_modify))
print("Your input was: {0}".format(how_modify))
invalid_input = True
else:
print("What you wanted to modify isn't an option")
print("Your input was: {0}".format(which_modify))
invalid_input = True
# don't prompt if they made a mistake
if not invalid_input:
with open(self.keys_file, 'w') as configfile:
CONFIG.write(configfile)
print('Changes made')
self.current_settings()
change_another = self.user_input('Would you like to change another setting, (Y)/(n)').lower()
if change_another not in ['yes', 'y']:
break
def valid_address(self, address):
try:
address_information = json.loads(self.api.decodeAddress(address))
except AttributeError:
return False
except socket.error:
self.api_import = False
return False
else:
if address_information.get('status') == 'success':
return True
else:
return False
def get_address(self, passphrase, version_number, stream_number):
try:
# passphrase must be encoded
passphrase = self.user_input('Enter the address passphrase.')
passphrase = base64.b64encode(passphrase)
version_number = 4
# TODO - This shouldn't be hardcoded, but it's all we have right now.
stream_number = 1
print('Address: {0}'.format(self.api.getDeterministicAddress(passphrase, version_number, stream_number)))
except socket.error:
self.api_import = False
print('Address couldn\'t be generated due to an API connection issue')
def subscribe(self):
try:
while True:
address = self.user_input('Address you would like to subscribe to:')
if self.valid_address(address):
break
else:
print('Not a valid address, please try again.')
while True:
label = self.user_input('Enter a label for this address:')
label = base64.b64encode(label)
subscription_check = self.api.addSubscription(address, label)
break
except socket.error:
self.api_import = False
print('Couldn\'t subscribe to channel due to an API connection issue')
else:
if subscription_check == 'Added subscription.':
print('You are now subscribed to: {0}'.format(address))
else:
print(subscription_check)
def unsubscribe(self):
try:
while True:
address = self.user_input('Enter the address to unsubscribe from:')
if self.valid_address(address):
break
while True:
unsubscribe_verify = self.user_input('Are you sure, (Y)/(n)').lower()
if unsubscribe_verify in ['yes', 'y']:
a = self.api.deleteSubscription(address)
print('You are now unsubscribed from: {0}'.format(address))
else:
print("You weren't unsubscribed from anything.")
break
except socket.error:
self.api_import = False
print('Couldn\'t unsubscribe from channel due to an API connection issue')
def list_subscriptions(self):
try:
total_subscriptions = json.loads(self.api.listSubscriptions())
print('-------------------------------------')
for each in total_subscriptions['subscriptions']:
print('Label: {0}'.format(base64.b64decode(each['label'])))
print('Address: {0}'.format(each['address']))
print('Enabled: {0}'.format(each['enabled']))
print('-------------------------------------')
except socket.error:
self.api_import = False
print('Couldn\'t list subscriptions due to an API connection issue')
def create_chan(self):
try:
password = self.user_input('Enter channel name:')
password = base64.b64encode(password)
print('Channel password: ' + self.api.createChan(password))
except socket.error:
self.api_import = False
print('Couldn\'t create channel due to an API connection issue')
def join_chan(self):
try:
while True:
address = self.user_input('Enter Channel Address:')
if self.valid_address(address):
break
while True:
password = self.user_input('Enter Channel Name:')
if password:
break
password = base64.b64encode(password)
joining_channel = self.api.joinChan(password, address)
if joining_channel == 'success':
print('Successfully joined {0}'.format(address))
# TODO - This should probably be done better
elif joining_channel.endswith('list index out of range'):
print("You're already in that channel")
except socket.error:
self.api_import = False
print('Couldn\'t join channel due to an API connection issue')
def leave_chan(self):
try:
while True:
address = self.user_input('Enter Channel Address or Label:')
if self.valid_address(address):
break
else:
json_addresses = json.loads(self.api.listAddresses())
# Number of addresses
number_of_addresses = len(json_addresses['addresses'])
# processes all of the addresses and lists them out
for each in range (0, number_of_addresses):
label = json_addresses['addresses'][each]['label']
single_address = json_addresses['addresses'][each]['address']
if '[chan] {0}'.format(address) == label:
address = single_address
found = True
break
if found:
break
leaving_channel = self.api.leaveChan(address)
if leaving_channel == 'success':
print('Successfully left {0}'.format(address))
else:
print('Couldn\'t leave channel. Expected response of \'success\', got: {0}'.format(leaving_channel))
except socket.error:
self.api_import = False
print('Couldn\'t leave channel due to an API connection issue')
# Lists all of the addresses and their info
def list_add(self):
try:
json_load_addresses = json.loads(self.api.listAddresses())
json_addresses = json_load_addresses['addresses']
if not json_addresses:
print('You have no addresses!')
else:
print('-------------------------------------')
for each in json_addresses:
print('Label: {0}'.format(each['label']))
print('Address: {0}'.format(each['address']))
print('Stream: {0}'.format(each['stream']))
print('Enabled: {0}'.format(each['enabled']))
print('-------------------------------------')
except socket.error:
self.api_import = False
print('Couldn\'t list addresses due to an API connection issue')
# Generate address
def generate_address(self, label, deterministic, passphrase, number_of_addresses,
address_version_number, stream_number, ripe):
try:
# Generates a new address with the user defined label, non-deterministic
if deterministic is False:
address_label = base64.b64encode(label)
return self.api.createRandomAddress(address_label)
# Generates a new deterministic address with the user inputs
elif deterministic is True:
passphrase = base64.b64encode(passphrase)
return self.api.createDeterministicAddresses(passphrase, number_of_addresses, address_version_number, stream_number, ripe)
except socket.error:
self.api_import = False
print('Couldn\'t generate address(es) due to an API connection issue')
return False
def delete_address(self):
try:
json_load_addresses = json.loads(self.api.listAddresses())
json_addresses = json_load_addresses['addresses']
number_of_addresses = len(json_addresses['addresses'])
if not json_addresses:
print('You have no addresses!')
else:
while True:
address = self.user_input('Enter Address or Label you wish to delete:')
if self.valid_address(address):
break
else:
# processes all of the addresses and lists them out
for each in range (0, number_of_addresses):
label = json_addresses['addresses'][each]['label']
json_address = json_addresses['addresses'][each]['address']
if '{0}'.format(address) == label:
address = json_address
found = True
break
if found:
delete_this = self.api.deleteAddress(address)
if delete_this == 'success':
print('{0} has been deleted!'.format(address))
break
else:
print('Couldn\'t delete address. Expected response of \'success\', got: {0}'.format(leaving_channel))
except socket.error:
self.api_import = False
print('Couldn\'t delete address due to an API connection issue')
# Allows attachments and messages/broadcats to be saved
def save_file(self, file_name, file_data):
# This section finds all invalid characters and replaces them with ~
filename_replacements = ["/", "\\", ":", "*", "?", "'", "<", ">", "|"]
for each in filename_replacements:
file_name = file_name.replace(each, '~')
while True:
directory = self.user_input('Where would you like to save the attachment?: ')
if not os.path.isdir(directory):
print("That directory doesn't exist.")
else:
if sys.platform.startswith('win'):
if not directory.endswith('\\'):
directory = directory + '\\'
else:
if not directory.endswith('/'):
directory = directory + '/'
file_path = directory + file_name
# Begin saving to file
try:
with open(file_path, 'w') as outfile:
outfile.write(base64.b64decode(file_data))
except IOError:
print("Failed to save the attachment. Choose another directory")
else:
print('Successfully saved {0}'.format(file_path))
break
# Allows users to attach a file to their message or broadcast
def attachment(self):
while True:
is_image = False
the_attachment = ''
file_path = self.user_input('Please enter the path to the attachment')
if os.path.isfile(file_path):
break
else:
print('{0} was not found on your filesystem or can not be opened.'.format(file_path))
while True:
# Get filesize and Converts to kilobytes
attachment_size = os.path.getsize(file_path) / 1024.0
# Rounds to two decimal places
round(attachment_size, 2)
# If over 200KB
if attachment_size > 200.0:
print('WARNING: The maximum message size including attachments, body, and headers is 256KB.')
print("If you reach over this limit, your message won't send.")
print("Your current attachment is {0}".format(attachment_size))
verify_attachment_200kb_warning = self.user_input('Are you sure you still want to attach it, (Y)/(n)').lower()
if verify_attachment_200kb_warning not in ['yes', 'y']:
print('Attachment discarded.')
return ''
# If larger than 256KB, discard
if attachment_size > 256.0:
print('Attachment too big, maximum allowed message size is 256KB')
return ''
break
# reads the filename
file_name = os.path.basename(file_path)
# Tests if it is an image file
file_type = imghdr.what(file_path)
if file_type is not None:
print('------------------------------------------')
print(' Attachment detected as an Image.')
print('<img> tags will be automatically included.')
print('------------------------------------------\n')
is_image = True
print('Reading file...')
with open(filePath, 'rb') as f:
# Reads files up to 256KB
file_data = f.read(262144)
file_data = base64.b64encode(file_data)
# Alert the user that the encoding process may take some time
print('Encoding attachment, please wait ...')
# Begin the actual encoding
# If it is an image, include image tags in the message
if isImage:
the_attachment = '<!-- Note: Base64 encoded image attachment below. -->\n\n'
the_attachment += 'Filename:{0}\n'.format(file_name)
the_attachment += 'Filesize:{0}KB\n'.format(attachment_size)
the_attachment += 'Encoding:base64\n\n'
the_attachment += '<center>\n'
the_attachment += "<img alt = \"{0}\" src='data:image/{0};base64, {1}' />\n".format(file_name, file_data)
the_attachment += '</center>'
# Else it is not an image so do not include the embedded image code.
else:
the_attachment = '<!-- Note: Base64 encoded file attachment below. -->\n\n'
the_attachment += 'Filename:{0}\n'.format(file_name)
the_attachment += 'Filesize:{0}KB\n'.format(attachment_size)
the_attachment += 'Encoding:base64\n\n'
the_attachment += '<center>\n'
the_attachment += "<attachment alt = \"{0}\" src='data:file/{0};base64, {1}' />\n".format(file_name, data)
the_attachment += '</center>'
return the_attachment
# With no arguments sent, send_message fills in the blanks
# subject and message must be encoded before they are passed
def send_message(self, to_address, from_address, subject, message):
try:
# TODO - Was using .encode('UTF-8'), not needed?
json_addresses = json.loads(self.api.listAddresses())
# Number of addresses
number_of_addresses = len(json_addresses['addresses'])
if not self.valid_address(to_address):
found = False
while True:
to_address = self.user_input('What is the To Address?')
if self.valid_address(to_address):
break
else:
for each in range (0, number_of_addresses):
label = json_addresses['addresses'][each]['label']
address = json_addresses['addresses'][each]['address']
if label.startswith('[chan] '):
label = label.split('[chan] ')[1]
# address entered was a label and is found
elif to_address == label:
found = True
to_address = address
break
if not found:
print('Invalid Address. Please try again.')
else:
break
if not self.valid_address(from_address):
# Ask what address to send from if multiple addresses
if number_of_addresses > 1:
found = False
while True:
from_address = self.user_input('Enter an Address or Address Label to send from')
if not self.valid_address(from_address):
# processes all of the addresses
for each in range (0, number_of_addresses):
label = jsonAddresses['addresses'][each]['label']
address = jsonAddresses['addresses'][each]['address']
if label.startswith('[chan] '):
label = label.split('[chan] ')[1]
# address entered was a label and is found
if fromAddress == label:
found = True
fromAddress = address
break
if not found:
print('Invalid Address. Please try again.')
else:
for each in range (0, number_of_addresses):
address = json_addresses['addresses'][each]['address']
# address entered was found in our address book
if from_address == address:
found = True
break
if not found:
print('The address entered is not one of yours. Please try again.')
else:
break
if found:
break
else:
try:
from_address = json_addresses['addresses'][0]['address']
# No address in the address book
except IndexError:
print('You don\'t have any addresses generated!')
print('Please use the \'generateaddress\' command')
self.main()
else:
# Only one address in address book
print('Using the only address in the addressbook to send from.')
if subject == '':
subject = self.user_input('Enter your subject')
subject = base64.b64encode(subject)
if message == '':
message = self.user_input('Enter your message.')
add_attachment = self.user_input('Would you like to add an attachment, (Y)/(n)').lower()
if add_attachment in ['yes', 'y']:
message = '{0}\n\n{1}'.format(message, self.attachment())
message = base64.b64encode(message)
ack_data = self.api.sendMessage(to_address, from_address, subject, message)
sending_message = self.api.getStatus(ack_data)
# TODO - There are more statuses that should be paid attention to
if sending_message == 'doingmsgpow':
print('Doing POW, will send soon.')
else:
print(sending_message)
except socket.error:
self.api_import = False
print('Couldn\'t send message due to an API connection issue')
def send_broadcast(self, from_address, subject, message):
try:
if from_address == '':
# TODO - Was using .encode('UTF-8'), not needed?
json_addresses = json.loads(self.api.listAddresses())
# Number of addresses
number_of_addresses = len(json_addresses['addresses'])
# Ask what address to send from if multiple addresses
if number_of_addresses > 1:
found = False
while True:
from_address = self.user_input('Enter an Address or Address Label to send from')
if not self.valid_address(from_address):
# processes all of the addresses
for each in range (0, number_of_addresses):
label = json_addresses['addresses'][each]['label']
address = json_addresses['addresses'][each]['address']
if label.startswith('[chan] '):
label = label.split('[chan] ')[1]
# address entered was a label and is found
if from_address == label:
found = True
from_address = address
break
if not found:
print('Invalid Address. Please try again.')
else:
for each in range (0, number_of_addresses):
address = json_addresses['addresses'][each]['address']
# address entered was found in our address book
if from_address == address:
found = True
break
if not found:
print('The address entered is not one of yours. Please try again.')
else:
# Address was found
break
if found:
break
else:
try:
from_address = json_addresses['addresses'][0]['address']
# No address in the address book!
except IndexError:
print('You don\'t have any addresses generated!')
print('Please use the \'generateaddress\' command')
self.main()
else:
# Only one address in address book
print('Using the only address in the addressbook to send from.')
if subject == '':
subject = self.user_input('Enter your Subject.')
subject = base64.b64encode(subject)
if message == '':
message = self.user_input('Enter your Message.')
add_attachment = self.user_input('Would you like to add an attachment, (Y)/(n)').lower()
if add_attachment in ['yes', 'y']:
message = message + '\n\n' + self.attachment()
message = base64.b64encode(message)
ack_data = self.api.sendBroadcast(from_address, subject, message)
sending_message = self.api.getStatus(ack_data)
# TODO - There are more statuses that should be paid attention to
if sending_message == 'broadcastqueued':
print('Broadcast is now in the queue')
else:
print(sending_message)
except socket.error:
self.api_import = False
print('Couldn\'t send message due to an API connection issue')
# Lists the messages by: Message Number, To Address Label,
# From Address Label, Subject, Received Time
def inbox(self, unread_only):
try:
inbox_messages = json.loads(self.api.getAllInboxMessages())
except socket.error:
self.api_import = False
print('Couldn\'t access inbox due to an API connection issue')
else:
total_messages = len(inbox_messages['inboxMessages'])
messages_printed = 0
messages_unread = 0
# processes all of the messages in the inbox
for each in range (0, total_messages):
message = inbox_messages['inboxMessages'][each]
# if we are displaying all messages or
# if this message is unread then display it
if not unread_only or not message['read']:
print('-----------------------------------')
# Message Number
print('Message Number: {0}'.format(each))
# Get the to address
print('To: {0}'.format(message['toAddress']))
# Get the from address
print('From: {0}'.format(message['fromAddress']))
# Get the subject
print('Subject: {0}'.format(base64.b64decode(message['subject'])))
print('Received: {0}'.format(datetime.datetime.fromtimestamp(float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S')))
messages_printed += 1
if not message['read']:
messages_unread += 1
print('-----------------------------------')
print('There are {0:d} unread messages of {1:d} in the inbox.'.format(messages_unread, total_messages))
print('-----------------------------------')
def outbox(self):
try:
outbox_messages = json.loads(self.api.getAllSentMessages())
json_outbox = outbox_messages['sentMessages']