-
Notifications
You must be signed in to change notification settings - Fork 577
/
bitmessagecli.py
1887 lines (1492 loc) · 68.5 KB
/
bitmessagecli.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
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
# pylint: disable=too-many-lines,global-statement,too-many-branches,too-many-statements,inconsistent-return-statements
# pylint: disable=too-many-nested-blocks,too-many-locals,protected-access,too-many-arguments,too-many-function-args
# pylint: disable=no-member
"""
Created by Adam Melton (.dok) referenceing https://bitmessage.org/wiki/API_Reference for API documentation
Distributed under the MIT/X11 software license. See http://www.opensource.org/licenses/mit-license.php.
This is an example of a daemon client for PyBitmessage 0.6.2, by .dok (Version 0.3.1) , modified
TODO: fix the following (currently ignored) violations:
"""
import datetime
import imghdr
import json
import ntpath
import os
import socket
import sys
import time
import xmlrpclib
from bmconfigparser import config
api = ''
keysName = 'keys.dat'
keysPath = 'keys.dat'
usrPrompt = 0 # 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up
knownAddresses = dict()
def userInput(message):
"""Checks input for exit or quit. Also formats for input, etc"""
global usrPrompt
print('\n' + message)
uInput = raw_input('> ')
if uInput.lower() == 'exit': # Returns the user to the main menu
usrPrompt = 1
main()
elif uInput.lower() == 'quit': # Quits the program
print('\n Bye\n')
sys.exit(0)
else:
return uInput
def restartBmNotify():
"""Prompt the user to restart Bitmessage"""
print('\n *******************************************************************')
print(' WARNING: If Bitmessage is running locally, you must restart it now.')
print(' *******************************************************************\n')
# Begin keys.dat interactions
def lookupAppdataFolder():
"""gets the appropriate folders for the .dat files depending on the OS. Taken from bitmessagemain.py"""
APPNAME = "PyBitmessage"
if sys.platform == 'darwin':
if "HOME" in os.environ:
dataFolder = os.path.join(os.environ["HOME"], "Library/Application support/", APPNAME) + '/'
else:
print(
' Could not find home folder, please report '
'this message and your OS X version to the Daemon Github.')
sys.exit(1)
elif 'win32' in sys.platform or 'win64' in sys.platform:
dataFolder = os.path.join(os.environ['APPDATA'], APPNAME) + '\\'
else:
dataFolder = os.path.expanduser(os.path.join("~", ".config/" + APPNAME + "/"))
return dataFolder
def configInit():
"""Initialised the configuration"""
config.add_section('bitmessagesettings')
# Sets the bitmessage port to stop the warning about the api not properly
# being setup. This is in the event that the keys.dat is in a different
# directory or is created locally to connect to a machine remotely.
config.set('bitmessagesettings', 'port', '8444')
config.set('bitmessagesettings', 'apienabled', 'true') # Sets apienabled to true in keys.dat
with open(keysName, 'wb') as configfile:
config.write(configfile)
print('\n ' + str(keysName) + ' Initalized in the same directory as daemon.py')
print(' You will now need to configure the ' + str(keysName) + ' file.\n')
def apiInit(apiEnabled):
"""Initialise the API"""
global usrPrompt
config.read(keysPath)
if apiEnabled is False: # API information there but the api is disabled.
uInput = userInput("The API is not enabled. Would you like to do that now, (Y)es or (N)o?").lower()
if uInput == "y":
config.set('bitmessagesettings', 'apienabled', 'true') # Sets apienabled to true in keys.dat
with open(keysPath, 'wb') as configfile:
config.write(configfile)
print('Done')
restartBmNotify()
return True
elif uInput == "n":
print(' \n************************************************************')
print(' Daemon will not work when the API is disabled. ')
print(' Please refer to the Bitmessage Wiki on how to setup the API.')
print(' ************************************************************\n')
usrPrompt = 1
main()
else:
print('\n Invalid Entry\n')
usrPrompt = 1
main()
elif apiEnabled: # API correctly setup
# Everything is as it should be
return True
else: # API information was not present.
print('\n ' + str(keysPath) + ' not properly configured!\n')
uInput = userInput("Would you like to do this now, (Y)es or (N)o?").lower()
if uInput == "y": # User said yes, initalize the api by writing these values to the keys.dat file
print(' ')
apiUsr = userInput("API Username")
apiPwd = userInput("API Password")
apiPort = userInput("API Port")
apiEnabled = userInput("API Enabled? (True) or (False)").lower()
daemon = userInput("Daemon mode Enabled? (True) or (False)").lower()
if (daemon != 'true' and daemon != 'false'):
print('\n Invalid Entry for Daemon.\n')
uInput = 1
main()
print(' -----------------------------------\n')
# sets the bitmessage port to stop the warning about the api not properly
# being setup. This is in the event that the keys.dat is in a different
# directory or is created locally to connect to a machine remotely.
config.set('bitmessagesettings', 'port', '8444')
config.set('bitmessagesettings', 'apienabled', 'true')
config.set('bitmessagesettings', 'apiport', apiPort)
config.set('bitmessagesettings', 'apiinterface', '127.0.0.1')
config.set('bitmessagesettings', 'apiusername', apiUsr)
config.set('bitmessagesettings', 'apipassword', apiPwd)
config.set('bitmessagesettings', 'daemon', daemon)
with open(keysPath, 'wb') as configfile:
config.write(configfile)
print('\n Finished configuring the keys.dat file with API information.\n')
restartBmNotify()
return True
elif uInput == "n":
print('\n ***********************************************************')
print(' Please refer to the Bitmessage Wiki on how to setup the API.')
print(' ***********************************************************\n')
usrPrompt = 1
main()
else:
print(' \nInvalid entry\n')
usrPrompt = 1
main()
def apiData():
"""TBC"""
global keysName
global keysPath
global usrPrompt
config.read(keysPath) # First try to load the config file (the keys.dat file) from the program directory
try:
config.get('bitmessagesettings', 'port')
appDataFolder = ''
except: # noqa:E722
# Could not load the keys.dat file in the program directory. Perhaps it is in the appdata directory.
appDataFolder = lookupAppdataFolder()
keysPath = appDataFolder + keysPath
config.read(keysPath)
try:
config.get('bitmessagesettings', 'port')
except: # noqa:E722
# keys.dat was not there either, something is wrong.
print('\n ******************************************************************')
print(' There was a problem trying to access the Bitmessage keys.dat file')
print(' or keys.dat is not set up correctly')
print(' Make sure that daemon is in the same directory as Bitmessage. ')
print(' ******************************************************************\n')
uInput = userInput("Would you like to create a keys.dat in the local directory, (Y)es or (N)o?").lower()
if uInput in ("y", "yes"):
configInit()
keysPath = keysName
usrPrompt = 0
main()
elif uInput in ("n", "no"):
print('\n Trying Again.\n')
usrPrompt = 0
main()
else:
print('\n Invalid Input.\n')
usrPrompt = 1
main()
try: # checks to make sure that everyting is configured correctly. Excluding apiEnabled, it is checked after
config.get('bitmessagesettings', 'apiport')
config.get('bitmessagesettings', 'apiinterface')
config.get('bitmessagesettings', 'apiusername')
config.get('bitmessagesettings', 'apipassword')
except: # noqa:E722
apiInit("") # Initalize the keys.dat file with API information
# keys.dat file was found or appropriately configured, allow information retrieval
# apiEnabled =
# apiInit(config.safeGetBoolean('bitmessagesettings','apienabled'))
# #if false it will prompt the user, if true it will return true
config.read(keysPath) # read again since changes have been made
apiPort = int(config.get('bitmessagesettings', 'apiport'))
apiInterface = config.get('bitmessagesettings', 'apiinterface')
apiUsername = config.get('bitmessagesettings', 'apiusername')
apiPassword = config.get('bitmessagesettings', 'apipassword')
print('\n API data successfully imported.\n')
# Build the api credentials
return "http://" + apiUsername + ":" + apiPassword + "@" + apiInterface + ":" + str(apiPort) + "/"
# End keys.dat interactions
def apiTest():
"""Tests the API connection to bitmessage. Returns true if it is connected."""
try:
result = api.add(2, 3)
except: # noqa:E722
return False
return result == 5
def bmSettings():
"""Allows the viewing and modification of keys.dat settings."""
global keysPath
global usrPrompt
keysPath = 'keys.dat'
config.read(keysPath) # Read the keys.dat
try:
port = config.get('bitmessagesettings', 'port')
except: # noqa:E722
print('\n File not found.\n')
usrPrompt = 0
main()
startonlogon = config.safeGetBoolean('bitmessagesettings', 'startonlogon')
minimizetotray = config.safeGetBoolean('bitmessagesettings', 'minimizetotray')
showtraynotifications = config.safeGetBoolean('bitmessagesettings', 'showtraynotifications')
startintray = config.safeGetBoolean('bitmessagesettings', 'startintray')
defaultnoncetrialsperbyte = config.get('bitmessagesettings', 'defaultnoncetrialsperbyte')
defaultpayloadlengthextrabytes = config.get('bitmessagesettings', 'defaultpayloadlengthextrabytes')
daemon = config.safeGetBoolean('bitmessagesettings', 'daemon')
socksproxytype = config.get('bitmessagesettings', 'socksproxytype')
sockshostname = config.get('bitmessagesettings', 'sockshostname')
socksport = config.get('bitmessagesettings', 'socksport')
socksauthentication = config.safeGetBoolean('bitmessagesettings', 'socksauthentication')
socksusername = config.get('bitmessagesettings', 'socksusername')
sockspassword = config.get('bitmessagesettings', 'sockspassword')
print('\n -----------------------------------')
print(' | Current Bitmessage Settings |')
print(' -----------------------------------')
print(' port = ' + port)
print(' startonlogon = ' + str(startonlogon))
print(' minimizetotray = ' + str(minimizetotray))
print(' showtraynotifications = ' + str(showtraynotifications))
print(' startintray = ' + str(startintray))
print(' defaultnoncetrialsperbyte = ' + defaultnoncetrialsperbyte)
print(' defaultpayloadlengthextrabytes = ' + defaultpayloadlengthextrabytes)
print(' daemon = ' + str(daemon))
print('\n ------------------------------------')
print(' | Current Connection Settings |')
print(' -----------------------------------')
print(' socksproxytype = ' + socksproxytype)
print(' sockshostname = ' + sockshostname)
print(' socksport = ' + socksport)
print(' socksauthentication = ' + str(socksauthentication))
print(' socksusername = ' + socksusername)
print(' sockspassword = ' + sockspassword)
print(' ')
uInput = userInput("Would you like to modify any of these settings, (Y)es or (N)o?").lower()
if uInput == "y":
while True: # loops if they mistype the setting name, they can exit the loop with 'exit'
invalidInput = False
uInput = userInput("What setting would you like to modify?").lower()
print(' ')
if uInput == "port":
print(' Current port number: ' + port)
uInput = userInput("Enter the new port number.")
config.set('bitmessagesettings', 'port', str(uInput))
elif uInput == "startonlogon":
print(' Current status: ' + str(startonlogon))
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'startonlogon', str(uInput))
elif uInput == "minimizetotray":
print(' Current status: ' + str(minimizetotray))
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'minimizetotray', str(uInput))
elif uInput == "showtraynotifications":
print(' Current status: ' + str(showtraynotifications))
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'showtraynotifications', str(uInput))
elif uInput == "startintray":
print(' Current status: ' + str(startintray))
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'startintray', str(uInput))
elif uInput == "defaultnoncetrialsperbyte":
print(' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte)
uInput = userInput("Enter the new defaultnoncetrialsperbyte.")
config.set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput))
elif uInput == "defaultpayloadlengthextrabytes":
print(' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes)
uInput = userInput("Enter the new defaultpayloadlengthextrabytes.")
config.set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput))
elif uInput == "daemon":
print(' Current status: ' + str(daemon))
uInput = userInput("Enter the new status.").lower()
config.set('bitmessagesettings', 'daemon', str(uInput))
elif uInput == "socksproxytype":
print(' Current socks proxy type: ' + socksproxytype)
print("Possibilities: 'none', 'SOCKS4a', 'SOCKS5'.")
uInput = userInput("Enter the new socksproxytype.")
config.set('bitmessagesettings', 'socksproxytype', str(uInput))
elif uInput == "sockshostname":
print(' Current socks host name: ' + sockshostname)
uInput = userInput("Enter the new sockshostname.")
config.set('bitmessagesettings', 'sockshostname', str(uInput))
elif uInput == "socksport":
print(' Current socks port number: ' + socksport)
uInput = userInput("Enter the new socksport.")
config.set('bitmessagesettings', 'socksport', str(uInput))
elif uInput == "socksauthentication":
print(' Current status: ' + str(socksauthentication))
uInput = userInput("Enter the new status.")
config.set('bitmessagesettings', 'socksauthentication', str(uInput))
elif uInput == "socksusername":
print(' Current socks username: ' + socksusername)
uInput = userInput("Enter the new socksusername.")
config.set('bitmessagesettings', 'socksusername', str(uInput))
elif uInput == "sockspassword":
print(' Current socks password: ' + sockspassword)
uInput = userInput("Enter the new password.")
config.set('bitmessagesettings', 'sockspassword', str(uInput))
else:
print("\n Invalid input. Please try again.\n")
invalidInput = True
if invalidInput is not True: # don't prompt if they made a mistake.
uInput = userInput("Would you like to change another setting, (Y)es or (N)o?").lower()
if uInput != "y":
print('\n Changes Made.\n')
with open(keysPath, 'wb') as configfile:
config.write(configfile)
restartBmNotify()
break
elif uInput == "n":
usrPrompt = 1
main()
else:
print("Invalid input.")
usrPrompt = 1
main()
def validAddress(address):
"""Predicate to test address validity"""
address_information = json.loads(api.decodeAddress(address))
return 'success' in str(address_information['status']).lower()
def getAddress(passphrase, vNumber, sNumber):
"""Get a deterministic address"""
passphrase = passphrase.encode('base64') # passphrase must be encoded
return api.getDeterministicAddress(passphrase, vNumber, sNumber)
def subscribe():
"""Subscribe to an address"""
global usrPrompt
while True:
address = userInput("What address would you like to subscribe to?")
if address == "c":
usrPrompt = 1
print(' ')
main()
elif validAddress(address) is False:
print('\n Invalid. "c" to cancel. Please try again.\n')
else:
break
label = userInput("Enter a label for this address.")
label = label.encode('base64')
api.addSubscription(address, label)
print('\n You are now subscribed to: ' + address + '\n')
def unsubscribe():
"""Unsusbcribe from an address"""
global usrPrompt
while True:
address = userInput("What address would you like to unsubscribe from?")
if address == "c":
usrPrompt = 1
print(' ')
main()
elif validAddress(address) is False:
print('\n Invalid. "c" to cancel. Please try again.\n')
else:
break
userInput("Are you sure, (Y)es or (N)o?").lower() # uInput =
api.deleteSubscription(address)
print('\n You are now unsubscribed from: ' + address + '\n')
def listSubscriptions():
"""List subscriptions"""
global usrPrompt
print('\nLabel, Address, Enabled\n')
try:
print(api.listSubscriptions())
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
print(' ')
def createChan():
"""Create a channel"""
global usrPrompt
password = userInput("Enter channel name")
password = password.encode('base64')
try:
print(api.createChan(password))
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
def joinChan():
"""Join a channel"""
global usrPrompt
while True:
address = userInput("Enter channel address")
if address == "c":
usrPrompt = 1
print(' ')
main()
elif validAddress(address) is False:
print('\n Invalid. "c" to cancel. Please try again.\n')
else:
break
password = userInput("Enter channel name")
password = password.encode('base64')
try:
print(api.joinChan(password, address))
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
def leaveChan():
"""Leave a channel"""
global usrPrompt
while True:
address = userInput("Enter channel address")
if address == "c":
usrPrompt = 1
print(' ')
main()
elif validAddress(address) is False:
print('\n Invalid. "c" to cancel. Please try again.\n')
else:
break
try:
print(api.leaveChan(address))
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
def listAdd():
"""List all of the addresses and their info"""
global usrPrompt
try:
jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
# print('\nAddress Number,Label,Address,Stream,Enabled\n')
print('\n --------------------------------------------------------------------------')
print(' | # | Label | Address |S#|Enabled|')
print(' |---|-------------------|-------------------------------------|--|-------|')
for addNum in range(0, numAddresses): # processes all of the addresses and lists them out
label = (jsonAddresses['addresses'][addNum]['label']).encode(
'utf') # may still misdiplay in some consoles
address = str(jsonAddresses['addresses'][addNum]['address'])
stream = str(jsonAddresses['addresses'][addNum]['stream'])
enabled = str(jsonAddresses['addresses'][addNum]['enabled'])
if len(label) > 19:
label = label[:16] + '...'
print(''.join([
' |',
str(addNum).ljust(3),
'|',
label.ljust(19),
'|',
address.ljust(37),
'|',
stream.ljust(1),
'|',
enabled.ljust(7),
'|',
]))
print(''.join([
' ',
74 * '-',
'\n',
]))
def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
"""Generate address"""
global usrPrompt
if deterministic is False: # Generates a new address with the user defined label. non-deterministic
addressLabel = lbl.encode('base64')
try:
generatedAddress = api.createRandomAddress(addressLabel)
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
return generatedAddress
elif deterministic: # Generates a new deterministic address with the user inputs.
passphrase = passphrase.encode('base64')
try:
generatedAddress = api.createDeterministicAddresses(passphrase, numOfAdd, addVNum, streamNum, ripe)
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
return generatedAddress
return 'Entry Error'
def saveFile(fileName, fileData):
"""Allows attachments and messages/broadcats to be saved"""
# This section finds all invalid characters and replaces them with ~
fileName = fileName.replace(" ", "")
fileName = fileName.replace("/", "~")
# fileName = fileName.replace("\\", "~") How do I get this to work...?
fileName = fileName.replace(":", "~")
fileName = fileName.replace("*", "~")
fileName = fileName.replace("?", "~")
fileName = fileName.replace('"', "~")
fileName = fileName.replace("<", "~")
fileName = fileName.replace(">", "~")
fileName = fileName.replace("|", "~")
directory = os.path.abspath('attachments')
if not os.path.exists(directory):
os.makedirs(directory)
filePath = os.path.join(directory, fileName)
with open(filePath, 'wb+') as path_to_file:
path_to_file.write(fileData.decode("base64"))
print('\n Successfully saved ' + filePath + '\n')
def attachment():
"""Allows users to attach a file to their message or broadcast"""
theAttachmentS = ''
while True:
isImage = False
theAttachment = ''
while True: # loops until valid path is entered
filePath = userInput(
'\nPlease enter the path to the attachment or just the attachment name if in this folder.')
try:
with open(filePath):
break
except IOError:
print('\n %s was not found on your filesystem or can not be opened.\n' % filePath)
# print(filesize, and encoding estimate with confirmation if file is over X size(1mb?))
invSize = os.path.getsize(filePath)
invSize = (invSize / 1024) # Converts to kilobytes
round(invSize, 2) # Rounds to two decimal places
if invSize > 500.0: # If over 500KB
print(''.join([
'\n WARNING:The file that you are trying to attach is ',
invSize,
'KB and will take considerable time to send.\n'
]))
uInput = userInput('Are you sure you still want to attach it, (Y)es or (N)o?').lower()
if uInput != "y":
print('\n Attachment discarded.\n')
return ''
elif invSize > 184320.0: # If larger than 180MB, discard.
print('\n Attachment too big, maximum allowed size:180MB\n')
main()
pathLen = len(str(ntpath.basename(filePath))) # Gets the length of the filepath excluding the filename
fileName = filePath[(len(str(filePath)) - pathLen):] # reads the filename
filetype = imghdr.what(filePath) # Tests if it is an image file
if filetype is not None:
print('\n ---------------------------------------------------')
print(' Attachment detected as an Image.')
print(' <img> tags will automatically be included,')
print(' allowing the recipient to view the image')
print(' using the "View HTML code..." option in Bitmessage.')
print(' ---------------------------------------------------\n')
isImage = True
time.sleep(2)
# Alert the user that the encoding process may take some time.
print('\n Encoding Attachment, Please Wait ...\n')
with open(filePath, 'rb') as f: # Begin the actual encoding
data = f.read(188743680) # Reads files up to 180MB, the maximum size for Bitmessage.
data = data.encode("base64")
if isImage: # If it is an image, include image tags in the message
theAttachment = """
<!-- Note: Image attachment below. Please use the right click "View HTML code ..." option to view it. -->
<!-- Sent using Bitmessage Daemon. https://github.com/Dokument/PyBitmessage-Daemon -->
Filename:%s
Filesize:%sKB
Encoding:base64
<center>
<div id="image">
<img alt = "%s" src='data:image/%s;base64, %s' />
</div>
</center>""" % (fileName, invSize, fileName, filetype, data)
else: # Else it is not an image so do not include the embedded image code.
theAttachment = """
<!-- Note: File attachment below. Please use a base64 decoder, or Daemon, to save it. -->
<!-- Sent using Bitmessage Daemon. https://github.com/Dokument/PyBitmessage-Daemon -->
Filename:%s
Filesize:%sKB
Encoding:base64
<attachment alt = "%s" src='data:file/%s;base64, %s' />""" % (fileName, invSize, fileName, fileName, data)
uInput = userInput('Would you like to add another attachment, (Y)es or (N)o?').lower()
if uInput in ('y', 'yes'): # Allows multiple attachments to be added to one message
theAttachmentS = str(theAttachmentS) + str(theAttachment) + '\n\n'
elif uInput in ('n', 'no'):
break
theAttachmentS = theAttachmentS + theAttachment
return theAttachmentS
def sendMsg(toAddress, fromAddress, subject, message):
"""
With no arguments sent, sendMsg fills in the blanks.
subject and message must be encoded before they are passed.
"""
global usrPrompt
if validAddress(toAddress) is False:
while True:
toAddress = userInput("What is the To Address?")
if toAddress == "c":
usrPrompt = 1
print(' ')
main()
elif validAddress(toAddress) is False:
print('\n Invalid Address. "c" to cancel. Please try again.\n')
else:
break
if validAddress(fromAddress) is False:
try:
jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
if numAddresses > 1: # Ask what address to send from if multiple addresses
found = False
while True:
print(' ')
fromAddress = userInput("Enter an Address or Address Label to send from.")
if fromAddress == "exit":
usrPrompt = 1
main()
for addNum in range(0, numAddresses): # processes all of the addresses
label = jsonAddresses['addresses'][addNum]['label']
address = jsonAddresses['addresses'][addNum]['address']
if fromAddress == label: # address entered was a label and is found
fromAddress = address
found = True
break
if found is False:
if validAddress(fromAddress) is False:
print('\n Invalid Address. Please try again.\n')
else:
for addNum in range(0, numAddresses): # processes all of the addresses
address = jsonAddresses['addresses'][addNum]['address']
if fromAddress == address: # address entered was a found in our addressbook.
found = True
break
if found is False:
print('\n The address entered is not one of yours. Please try again.\n')
if found:
break # Address was found
else: # Only one address in address book
print('\n Using the only address in the addressbook to send from.\n')
fromAddress = jsonAddresses['addresses'][0]['address']
if not subject:
subject = userInput("Enter your Subject.")
subject = subject.encode('base64')
if not message:
message = userInput("Enter your Message.")
uInput = userInput('Would you like to add an attachment, (Y)es or (N)o?').lower()
if uInput == "y":
message = message + '\n\n' + attachment()
message = message.encode('base64')
try:
ackData = api.sendMessage(toAddress, fromAddress, subject, message)
print('\n Message Status:', api.getStatus(ackData), '\n')
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
def sendBrd(fromAddress, subject, message):
"""Send a broadcast"""
global usrPrompt
if not fromAddress:
try:
jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
if numAddresses > 1: # Ask what address to send from if multiple addresses
found = False
while True:
fromAddress = userInput("\nEnter an Address or Address Label to send from.")
if fromAddress == "exit":
usrPrompt = 1
main()
for addNum in range(0, numAddresses): # processes all of the addresses
label = jsonAddresses['addresses'][addNum]['label']
address = jsonAddresses['addresses'][addNum]['address']
if fromAddress == label: # address entered was a label and is found
fromAddress = address
found = True
break
if found is False:
if validAddress(fromAddress) is False:
print('\n Invalid Address. Please try again.\n')
else:
for addNum in range(0, numAddresses): # processes all of the addresses
address = jsonAddresses['addresses'][addNum]['address']
if fromAddress == address: # address entered was a found in our addressbook.
found = True
break
if found is False:
print('\n The address entered is not one of yours. Please try again.\n')
if found:
break # Address was found
else: # Only one address in address book
print('\n Using the only address in the addressbook to send from.\n')
fromAddress = jsonAddresses['addresses'][0]['address']
if not subject:
subject = userInput("Enter your Subject.")
subject = subject.encode('base64')
if not message:
message = userInput("Enter your Message.")
uInput = userInput('Would you like to add an attachment, (Y)es or (N)o?').lower()
if uInput == "y":
message = message + '\n\n' + attachment()
message = message.encode('base64')
try:
ackData = api.sendBroadcast(fromAddress, subject, message)
print('\n Message Status:', api.getStatus(ackData), '\n')
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
def inbox(unreadOnly=False):
"""Lists the messages by: Message Number, To Address Label, From Address Label, Subject, Received Time)"""
global usrPrompt
try:
inboxMessages = json.loads(api.getAllInboxMessages())
numMessages = len(inboxMessages['inboxMessages'])
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
messagesPrinted = 0
messagesUnread = 0
for msgNum in range(0, numMessages): # processes all of the messages in the inbox
message = inboxMessages['inboxMessages'][msgNum]
# if we are displaying all messages or if this message is unread then display it
if not unreadOnly or not message['read']:
print(' -----------------------------------\n')
print(' Message Number:', msgNum) # Message Number)
print(' To:', getLabelForAddress(message['toAddress'])) # Get the to address)
print(' From:', getLabelForAddress(message['fromAddress'])) # Get the from address)
print(' Subject:', message['subject'].decode('base64')) # Get the subject)
print(''.join([
' Received:',
datetime.datetime.fromtimestamp(
float(message['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'),
]))
messagesPrinted += 1
if not message['read']:
messagesUnread += 1
if messagesPrinted % 20 == 0 and messagesPrinted != 0:
userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput =
print('\n -----------------------------------')
print(' There are %d unread messages of %d messages in the inbox.' % (messagesUnread, numMessages))
print(' -----------------------------------\n')
def outbox():
"""TBC"""
global usrPrompt
try:
outboxMessages = json.loads(api.getAllSentMessages())
numMessages = len(outboxMessages['sentMessages'])
except: # noqa:E722
print('\n Connection Error\n')
usrPrompt = 0
main()
for msgNum in range(0, numMessages): # processes all of the messages in the outbox
print('\n -----------------------------------\n')
print(' Message Number:', msgNum) # Message Number)
# print(' Message ID:', outboxMessages['sentMessages'][msgNum]['msgid'])
print(' To:', getLabelForAddress(
outboxMessages['sentMessages'][msgNum]['toAddress']
)) # Get the to address)
# Get the from address
print(' From:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['fromAddress']))
print(' Subject:', outboxMessages['sentMessages'][msgNum]['subject'].decode('base64')) # Get the subject)
print(' Status:', outboxMessages['sentMessages'][msgNum]['status']) # Get the subject)
# print(''.join([
# ' Last Action Time:',
# datetime.datetime.fromtimestamp(
# float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'),
# ]))
print(''.join([
' Last Action Time:',
datetime.datetime.fromtimestamp(
float(outboxMessages['sentMessages'][msgNum]['lastActionTime'])).strftime('%Y-%m-%d %H:%M:%S'),
]))
if msgNum % 20 == 0 and msgNum != 0:
userInput('(Press Enter to continue or type (Exit) to return to the main menu.)').lower() # uInput =
print('\n -----------------------------------')
print(' There are ', numMessages, ' messages in the outbox.')
print(' -----------------------------------\n')
def readSentMsg(msgNum):
"""Opens a sent message for reading"""
global usrPrompt
try:
outboxMessages = json.loads(api.getAllSentMessages())
numMessages = len(outboxMessages['sentMessages'])