Updated origin and solved conflicts

This commit is contained in:
jai.s 2020-01-08 17:05:29 +05:30
commit fdbc175769
No known key found for this signature in database
GPG Key ID: 360CFA25EFC67D12
60 changed files with 927 additions and 850 deletions

View File

@ -2,7 +2,6 @@
Operations with addresses
"""
# pylint: disable=redefined-outer-name,inconsistent-return-statements
import hashlib
from binascii import hexlify, unhexlify
from struct import pack, unpack
@ -46,7 +45,8 @@ def decodeBase58(string, alphabet=ALPHABET):
for char in string:
num *= base
num += alphabet.index(char)
except: # ValueError
# ValueError
except:
# character not found (like a space character or a 0)
return 0
return num
@ -85,13 +85,13 @@ def decodeVarint(data):
the minimum amount of data possible or else it is malformed.
Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes)
"""
if not data:
return (0, 0)
firstByte, = unpack('>B', data[0:1])
if firstByte < 253:
# encodes 0 to 252
return (firstByte, 1) # the 1 is the length of the varint
# the 1 is the length of the varint
return (firstByte, 1)
if firstByte == 253:
# encodes 253 to 65535
if len(data) < 3:
@ -180,7 +180,8 @@ def decodeAddress(address):
returns (status, address version number, stream number,
data (almost certainly a ripe hash))
"""
# pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches
# pylint: disable=too-many-return-statements,too-many-statements
# pylint: disable=too-many-branches
address = str(address).strip()
if address[:3] == 'BM-':
@ -237,7 +238,8 @@ def decodeAddress(address):
status = 'success'
if addressVersionNumber == 1:
return status, addressVersionNumber, streamNumber, data[-24:-4]
elif addressVersionNumber == 2 or addressVersionNumber == 3:
# elif addressVersionNumber == 2 or addressVersionNumber == 3:
elif addressVersionNumber in (2, 3):
embeddedRipeData = \
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
if len(embeddedRipeData) == 19:

View File

@ -1,15 +1,12 @@
# pylint: disable=too-many-locals,too-many-lines,no-self-use,too-many-public-methods,too-many-branches
# pylint: disable=too-many-statements
# Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2020 The Bitmessage developers
"""
This is not what you run to run the Bitmessage API. Instead, enable the API
( https://bitmessage.org/wiki/API ) and optionally enable daemon mode
( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py.
"""
# pylint: disable=too-many-locals,too-many-lines,no-self-use,unused-argument
# pylint: disable=too-many-statements,too-many-public-methods,too-many-branches
# Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2019 The Bitmessage developers
import base64
import errno
import hashlib
@ -33,6 +30,7 @@ import queues
import shared
import shutdown
import state
from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError
from bmconfigparser import BMConfigParser
from debug import logger
@ -40,6 +38,7 @@ from helper_ackPayload import genAckPayload
from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
from inventory import Inventory
from network.threads import StoppableThread
# pylint: disable=unused-variable
str_chan = '[chan]'
@ -58,6 +57,7 @@ class APIError(Exception):
class StoppableXMLRPCServer(SimpleXMLRPCServer):
"""A SimpleXMLRPCServer that honours state.shutdown"""
# pylint:disable=too-few-public-methods
allow_reuse_address = True
def serve_forever(self):
@ -150,7 +150,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
Note: this method is the same as in SimpleXMLRPCRequestHandler,
just hacked to handle cookies
"""
# Check that the path is legal
if not self.is_rpc_path_valid():
self.report_404()
@ -175,10 +174,12 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# check to see if a subclass implements _dispatch and dispatch
# using that method if present.
response = self.server._marshaled_dispatch( # pylint: disable=protected-access
# pylint: disable=protected-access
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None)
)
except BaseException: # This should only happen if the module is buggy
# This should only happen if the module is buggy
except BaseException:
# internal error, report as HTTP server error
self.send_response(500)
self.end_headers()
@ -251,7 +252,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if status == 'invalidcharacters':
raise APIError(9, 'Invalid characters in address: ' + address)
if status == 'versiontoohigh':
raise APIError(10, 'Address version number too high (or zero) in address: ' + address)
raise APIError(
10, 'Address version number too high (or zero) in address: ' + address)
if status == 'varintmalformed':
raise APIError(26, 'Malformed varint in address: ' + address)
raise APIError(7, 'Could not decode address: %s : %s' % (address, status))
@ -275,7 +277,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"addresses":['
for addressInKeysFile in BMConfigParser().addresses():
status, addressVersionNumber, streamNumber, hash01 = decodeAddress( # pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
addressInKeysFile)
if len(data) > 20:
data += ','
@ -485,7 +487,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# 0 means "just use the proper addressVersionNumber"
if addressVersionNumber == 0:
addressVersionNumber = 4
if addressVersionNumber != 3 and addressVersionNumber != 4:
# if addressVersionNumber != 3 and addressVersionNumber != 4:
if addressVersionNumber not in (3, 4):
raise APIError(
2, 'The address version number currently must be 3, 4, or 0'
' (which means auto-select). %i isn\'t supported.' %
@ -536,7 +539,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if not passphrase:
raise APIError(1, 'The specified passphrase is blank.')
passphrase = self._decode(passphrase, "base64")
if addressVersionNumber != 3 and addressVersionNumber != 4:
# if addressVersionNumber != 3 and addressVersionNumber != 4:
if addressVersionNumber not in (3, 4):
raise APIError(
2, 'The address version number currently must be 3 or 4. %i'
' isn\'t supported.' % addressVersionNumber)
@ -606,8 +610,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
label = str_chan + ' ' + passphrase
except BaseException:
label = str_chan + ' ' + repr(passphrase)
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( # pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(
suppliedAddress)
suppliedAddress = addBMIfNotPresent(suppliedAddress)
queues.apiAddressGeneratorReturnQueue.queue.clear()
@ -631,8 +634,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.')
elif len(params) == 1:
address, = params
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(address)
address = addBMIfNotPresent(address)
if not BMConfigParser().has_section(address):
raise APIError(
@ -653,8 +656,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.')
elif len(params) == 1:
address, = params
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(address)
address = addBMIfNotPresent(address)
if not BMConfigParser().has_section(address):
raise APIError(
@ -666,7 +669,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
shared.reloadMyAddressHashes()
return 'success'
def HandleGetAllInboxMessages(self, params): # pylint: disable=unused-argument
def HandleGetAllInboxMessages(self, params):
"""Handle a request to get all inbox messages"""
queryreturn = sqlQuery(
@ -694,7 +697,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}'
return data
def HandleGetAllInboxMessageIds(self, params): # pylint: disable=unused-argument
def HandleGetAllInboxMessageIds(self, params):
"""Handle a request to get all inbox message IDs"""
queryreturn = sqlQuery(
@ -753,7 +756,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}'
return data
def HandleGetAllSentMessages(self, params): # pylint: disable=unused-argument
def HandleGetAllSentMessages(self, params):
"""Handle a request to get all sent messages"""
queryreturn = sqlQuery(
@ -782,7 +785,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}'
return data
def HandleGetAllSentMessageIds(self, params): # pylint: disable=unused-argument
def HandleGetAllSentMessageIds(self, params):
"""Handle a request to get all sent message IDs"""
queryreturn = sqlQuery(
@ -873,7 +876,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"sentMessages":['
for row in queryreturn:
msgid, toAddress, fromAddress, subject, lastactiontime, message, \
encodingtype, status, ackdata = row # pylint: disable=unused-variable
encodingtype, status, ackdata = row
subject = shared.fixPotentiallyInvalidUTF8Data(subject)
message = shared.fixPotentiallyInvalidUTF8Data(message)
if len(data) > 25:
@ -983,7 +986,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
TTL = 28 * 24 * 60 * 60
toAddress = addBMIfNotPresent(toAddress)
fromAddress = addBMIfNotPresent(fromAddress)
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(toAddress)
self._verifyAddress(fromAddress)
@ -1157,10 +1159,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
queues.UISignalQueue.put(('rerenderSubscriptions', ''))
return 'Deleted subscription if it existed.'
def ListSubscriptions(self, params): # pylint: disable=unused-argument
def ListSubscriptions(self, params):
"""Handle a request to list susbcriptions"""
# pylint: disable=unused-variable
queryreturn = sqlQuery(
"SELECT label, address, enabled FROM subscriptions")
data = {'subscriptions': []}
@ -1206,7 +1207,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
initialHash = hashlib.sha512(encryptedPayload).digest()
trialValue, nonce = proofofwork.run(target, initialHash)
with shared.printLock:
print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce
print('(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce)
try:
print(
'POW took', int(time.time() - powStartTime), 'seconds.',
@ -1224,7 +1225,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
int(time.time()) + TTL, ''
)
with shared.printLock:
print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash)
print('Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash))
queues.invQueue.put((toStreamNumber, inventoryHash))
def HandleTrashSentMessageByAckDAta(self, params):
@ -1237,7 +1238,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata)
return 'Trashed sent message (assuming message existed).'
def HandleDissimatePubKey(self, params): # pylint: disable=unused-argument
def HandleDissimatePubKey(self, params):
"""Handle a request to disseminate a public key"""
# The device issuing this command to PyBitmessage supplies a pubkey
@ -1254,10 +1255,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
target = 2 ** 64 / ((
len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
print '(For pubkey message via API) Doing proof of work...'
print('(For pubkey message via API) Doing proof of work...')
initialHash = hashlib.sha512(payload).digest()
trialValue, nonce = proofofwork.run(target, initialHash)
print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce
print('(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce)
payload = pack('>Q', nonce) + payload
pubkeyReadPosition = 8 # bypass the nonce
@ -1266,7 +1267,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
pubkeyReadPosition += 8
else:
pubkeyReadPosition += 4
# pylint: disable=unused-variable
addressVersion, addressVersionLength = decodeVarint(
payload[pubkeyReadPosition:pubkeyReadPosition + 10])
pubkeyReadPosition += addressVersionLength
@ -1279,7 +1279,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, ''
)
with shared.printLock:
print 'broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash)
print('broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash))
queues.invQueue.put((pubkeyStreamNumber, inventoryHash))
def HandleGetMessageDataByDestinationHash(self, params):
@ -1325,7 +1325,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}'
return data
def HandleClientStatus(self, params): # pylint: disable=unused-argument
def HandleClientStatus(self, params):
"""Handle a request to get the status of the client"""
connections_num = len(network.stats.connectedHostsList())

View File

@ -29,7 +29,8 @@ from bmconfigparser import BMConfigParser
api = ''
keysName = 'keys.dat'
keysPath = 'keys.dat'
usrPrompt = 0 # 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up
# 0 = First Start, 1 = prompt, 2 = no prompt if the program is starting up
usrPrompt = 0
knownAddresses = dict()
@ -38,7 +39,7 @@ def userInput(message):
global usrPrompt
print '\n' + message
print('\n' + message)
uInput = raw_input('> ')
if uInput.lower() == 'exit': # Returns the user to the main menu
@ -46,7 +47,7 @@ def userInput(message):
main()
elif uInput.lower() == 'quit': # Quits the program
print '\n Bye\n'
print('\n Bye\n')
sys.exit(0)
else:
@ -55,9 +56,9 @@ def userInput(message):
def restartBmNotify():
"""Prompt the user to restart Bitmessage"""
print '\n *******************************************************************'
print ' WARNING: If Bitmessage is running locally, you must restart it now.'
print ' *******************************************************************\n'
print('\n *******************************************************************')
print(' WARNING: If Bitmessage is running locally, you must restart it now.')
print(' *******************************************************************\n')
# Begin keys.dat interactions
@ -96,8 +97,8 @@ def configInit():
with open(keysName, 'wb') as configfile:
BMConfigParser().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'
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):
@ -114,20 +115,20 @@ def apiInit(apiEnabled):
with open(keysPath, 'wb') as configfile:
BMConfigParser().write(configfile)
print 'Done'
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'
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'
print('\n Invalid Entry\n')
usrPrompt = 1
main()
@ -136,11 +137,11 @@ def apiInit(apiEnabled):
return True
else: # API information was not present.
print '\n ' + str(keysPath) + ' not properly configured!\n'
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 ' '
print(' ')
apiUsr = userInput("API Username")
apiPwd = userInput("API Password")
@ -149,11 +150,11 @@ def apiInit(apiEnabled):
daemon = userInput("Daemon mode Enabled? (True) or (False)").lower()
if (daemon != 'true' and daemon != 'false'):
print '\n Invalid Entry for Daemon.\n'
print('\n Invalid Entry for Daemon.\n')
uInput = 1
main()
print ' -----------------------------------\n'
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
@ -168,18 +169,18 @@ def apiInit(apiEnabled):
with open(keysPath, 'wb') as configfile:
BMConfigParser().write(configfile)
print '\n Finished configuring the keys.dat file with API information.\n'
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'
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'
print(' \nInvalid entry\n')
usrPrompt = 1
main()
@ -206,11 +207,11 @@ def apiData():
BMConfigParser().get('bitmessagesettings', 'port')
except:
# 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'
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()
@ -220,11 +221,11 @@ def apiData():
usrPrompt = 0
main()
elif (uInput == "n" or uInput == "no"):
print '\n Trying Again.\n'
print('\n Trying Again.\n')
usrPrompt = 0
main()
else:
print '\n Invalid Input.\n'
print('\n Invalid Input.\n')
usrPrompt = 1
main()
@ -249,7 +250,7 @@ def apiData():
apiUsername = BMConfigParser().get('bitmessagesettings', 'apiusername')
apiPassword = BMConfigParser().get('bitmessagesettings', 'apipassword')
print '\n API data successfully imported.\n'
print('\n API data successfully imported.\n')
# Build the api credentials
return "http://" + apiUsername + ":" + apiPassword + "@" + apiInterface + ":" + str(apiPort) + "/"
@ -281,7 +282,7 @@ def bmSettings():
try:
port = BMConfigParser().get('bitmessagesettings', 'port')
except:
print '\n File not found.\n'
print('\n File not found.\n')
usrPrompt = 0
main()
@ -300,27 +301,27 @@ def bmSettings():
socksusername = BMConfigParser().get('bitmessagesettings', 'socksusername')
sockspassword = BMConfigParser().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 ' '
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()
@ -328,74 +329,74 @@ def bmSettings():
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 ' '
print(' ')
if uInput == "port":
print ' Current port number: ' + port
print(' Current port number: ' + port)
uInput = userInput("Enter the new port number.")
BMConfigParser().set('bitmessagesettings', 'port', str(uInput))
elif uInput == "startonlogon":
print ' Current status: ' + str(startonlogon)
print(' Current status: ' + str(startonlogon))
uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'startonlogon', str(uInput))
elif uInput == "minimizetotray":
print ' Current status: ' + str(minimizetotray)
print(' Current status: ' + str(minimizetotray))
uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'minimizetotray', str(uInput))
elif uInput == "showtraynotifications":
print ' Current status: ' + str(showtraynotifications)
print(' Current status: ' + str(showtraynotifications))
uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'showtraynotifications', str(uInput))
elif uInput == "startintray":
print ' Current status: ' + str(startintray)
print(' Current status: ' + str(startintray))
uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'startintray', str(uInput))
elif uInput == "defaultnoncetrialsperbyte":
print ' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte
print(' Current default nonce trials per byte: ' + defaultnoncetrialsperbyte)
uInput = userInput("Enter the new defaultnoncetrialsperbyte.")
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(uInput))
elif uInput == "defaultpayloadlengthextrabytes":
print ' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes
print(' Current default payload length extra bytes: ' + defaultpayloadlengthextrabytes)
uInput = userInput("Enter the new defaultpayloadlengthextrabytes.")
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(uInput))
elif uInput == "daemon":
print ' Current status: ' + str(daemon)
print(' Current status: ' + str(daemon))
uInput = userInput("Enter the new status.").lower()
BMConfigParser().set('bitmessagesettings', 'daemon', str(uInput))
elif uInput == "socksproxytype":
print ' Current socks proxy type: ' + socksproxytype
print "Possibilities: 'none', 'SOCKS4a', 'SOCKS5'."
print(' Current socks proxy type: ' + socksproxytype)
print("Possibilities: 'none', 'SOCKS4a', 'SOCKS5'.")
uInput = userInput("Enter the new socksproxytype.")
BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(uInput))
elif uInput == "sockshostname":
print ' Current socks host name: ' + sockshostname
print(' Current socks host name: ' + sockshostname)
uInput = userInput("Enter the new sockshostname.")
BMConfigParser().set('bitmessagesettings', 'sockshostname', str(uInput))
elif uInput == "socksport":
print ' Current socks port number: ' + socksport
print(' Current socks port number: ' + socksport)
uInput = userInput("Enter the new socksport.")
BMConfigParser().set('bitmessagesettings', 'socksport', str(uInput))
elif uInput == "socksauthentication":
print ' Current status: ' + str(socksauthentication)
print(' Current status: ' + str(socksauthentication))
uInput = userInput("Enter the new status.")
BMConfigParser().set('bitmessagesettings', 'socksauthentication', str(uInput))
elif uInput == "socksusername":
print ' Current socks username: ' + socksusername
print(' Current socks username: ' + socksusername)
uInput = userInput("Enter the new socksusername.")
BMConfigParser().set('bitmessagesettings', 'socksusername', str(uInput))
elif uInput == "sockspassword":
print ' Current socks password: ' + sockspassword
print(' Current socks password: ' + sockspassword)
uInput = userInput("Enter the new password.")
BMConfigParser().set('bitmessagesettings', 'sockspassword', str(uInput))
else:
print "\n Invalid input. Please try again.\n"
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'
print('\n Changes Made.\n')
with open(keysPath, 'wb') as configfile:
BMConfigParser().write(configfile)
restartBmNotify()
@ -405,7 +406,7 @@ def bmSettings():
usrPrompt = 1
main()
else:
print "Invalid input."
print("Invalid input.")
usrPrompt = 1
main()
@ -433,10 +434,10 @@ def subscribe():
if address == "c":
usrPrompt = 1
print ' '
print(' ')
main()
elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n'
print('\n Invalid. "c" to cancel. Please try again.\n')
else:
break
@ -444,7 +445,7 @@ def subscribe():
label = label.encode('base64')
api.addSubscription(address, label)
print '\n You are now subscribed to: ' + address + '\n'
print('\n You are now subscribed to: ' + address + '\n')
def unsubscribe():
@ -456,31 +457,31 @@ def unsubscribe():
if address == "c":
usrPrompt = 1
print ' '
print(' ')
main()
elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n'
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'
print('\n You are now unsubscribed from: ' + address + '\n')
def listSubscriptions():
"""List subscriptions"""
global usrPrompt
print '\nLabel, Address, Enabled\n'
print('\nLabel, Address, Enabled\n')
try:
print api.listSubscriptions()
print(api.listSubscriptions())
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
print ' '
print(' ')
def createChan():
@ -490,9 +491,9 @@ def createChan():
password = userInput("Enter channel name")
password = password.encode('base64')
try:
print api.createChan(password)
print(api.createChan(password))
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -506,19 +507,19 @@ def joinChan():
if address == "c":
usrPrompt = 1
print ' '
print(' ')
main()
elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n'
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)
print(api.joinChan(password, address))
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -532,17 +533,17 @@ def leaveChan():
if address == "c":
usrPrompt = 1
print ' '
print(' ')
main()
elif validAddress(address) is False:
print '\n Invalid. "c" to cancel. Please try again.\n'
print('\n Invalid. "c" to cancel. Please try again.\n')
else:
break
try:
print api.leaveChan(address)
print(api.leaveChan(address))
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -554,14 +555,14 @@ def listAdd():
jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
# print '\nAddress Number,Label,Address,Stream,Enabled\n'
print '\n --------------------------------------------------------------------------'
print ' | # | Label | Address |S#|Enabled|'
print ' |---|-------------------|-------------------------------------|--|-------|'
# 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
@ -572,7 +573,7 @@ def listAdd():
if len(label) > 19:
label = label[:16] + '...'
print ''.join([
print(''.join([
' |',
str(addNum).ljust(3),
'|',
@ -584,13 +585,13 @@ def listAdd():
'|',
enabled.ljust(7),
'|',
])
]))
print ''.join([
print(''.join([
' ',
74 * '-',
'\n',
])
]))
def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
@ -603,7 +604,7 @@ def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
try:
generatedAddress = api.createRandomAddress(addressLabel)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -614,7 +615,7 @@ def genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe):
try:
generatedAddress = api.createDeterministicAddresses(passphrase, numOfAdd, addVNum, streamNum, ripe)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
return generatedAddress
@ -646,7 +647,7 @@ def saveFile(fileName, fileData):
with open(filePath, 'wb+') as path_to_file:
path_to_file.write(fileData.decode("base64"))
print '\n Successfully saved ' + filePath + '\n'
print('\n Successfully saved ' + filePath + '\n')
def attachment():
@ -667,26 +668,26 @@ def attachment():
with open(filePath):
break
except IOError:
print '\n %s was not found on your filesystem or can not be opened.\n' % filePath
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?)
# 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([
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'
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'
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
@ -694,17 +695,17 @@ def attachment():
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'
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'
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.
@ -759,10 +760,10 @@ def sendMsg(toAddress, fromAddress, subject, message):
if toAddress == "c":
usrPrompt = 1
print ' '
print(' ')
main()
elif validAddress(toAddress) is False:
print '\n Invalid Address. "c" to cancel. Please try again.\n'
print('\n Invalid Address. "c" to cancel. Please try again.\n')
else:
break
@ -771,14 +772,14 @@ def sendMsg(toAddress, fromAddress, subject, message):
jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except:
print '\n Connection Error\n'
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 ' '
print(' ')
fromAddress = userInput("Enter an Address or Address Label to send from.")
if fromAddress == "exit":
@ -795,7 +796,7 @@ def sendMsg(toAddress, fromAddress, subject, message):
if found is False:
if validAddress(fromAddress) is False:
print '\n Invalid Address. Please try again.\n'
print('\n Invalid Address. Please try again.\n')
else:
for addNum in range(0, numAddresses): # processes all of the addresses
@ -805,13 +806,13 @@ def sendMsg(toAddress, fromAddress, subject, message):
break
if found is False:
print '\n The address entered is not one of yours. Please try again.\n'
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'
print('\n Using the only address in the addressbook to send from.\n')
fromAddress = jsonAddresses['addresses'][0]['address']
if subject == '':
@ -828,9 +829,9 @@ def sendMsg(toAddress, fromAddress, subject, message):
try:
ackData = api.sendMessage(toAddress, fromAddress, subject, message)
print '\n Message Status:', api.getStatus(ackData), '\n'
print('\n Message Status:', api.getStatus(ackData), '\n')
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -845,7 +846,7 @@ def sendBrd(fromAddress, subject, message):
jsonAddresses = json.loads(api.listAddresses())
numAddresses = len(jsonAddresses['addresses']) # Number of addresses
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -868,7 +869,7 @@ def sendBrd(fromAddress, subject, message):
if found is False:
if validAddress(fromAddress) is False:
print '\n Invalid Address. Please try again.\n'
print('\n Invalid Address. Please try again.\n')
else:
for addNum in range(0, numAddresses): # processes all of the addresses
@ -878,13 +879,13 @@ def sendBrd(fromAddress, subject, message):
break
if found is False:
print '\n The address entered is not one of yours. Please try again.\n'
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'
print('\n Using the only address in the addressbook to send from.\n')
fromAddress = jsonAddresses['addresses'][0]['address']
if subject == '':
@ -901,9 +902,9 @@ def sendBrd(fromAddress, subject, message):
try:
ackData = api.sendBroadcast(fromAddress, subject, message)
print '\n Message Status:', api.getStatus(ackData), '\n'
print('\n Message Status:', api.getStatus(ackData), '\n')
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -916,7 +917,7 @@ def inbox(unreadOnly=False):
inboxMessages = json.loads(api.getAllInboxMessages())
numMessages = len(inboxMessages['inboxMessages'])
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -926,16 +927,16 @@ def inbox(unreadOnly=False):
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([
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
@ -943,9 +944,9 @@ def inbox(unreadOnly=False):
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'
print('\n -----------------------------------')
print(' There are %d unread messages of %d messages in the inbox.' % (messagesUnread, numMessages))
print(' -----------------------------------\n')
def outbox():
@ -956,32 +957,32 @@ def outbox():
outboxMessages = json.loads(api.getAllSentMessages())
numMessages = len(outboxMessages['sentMessages'])
except:
print '\n Connection Error\n'
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
print('\n -----------------------------------\n')
print(' Message Number:', msgNum) # Message Number
# print(' Message ID:', outboxMessages['sentMessages'][msgNum]['msgid'])
# Get the to address
print(' To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']))
# 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([
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'),
])
]))
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'
print('\n -----------------------------------')
print(' There are ', numMessages, ' messages in the outbox.')
print(' -----------------------------------\n')
def readSentMsg(msgNum):
@ -992,14 +993,14 @@ def readSentMsg(msgNum):
outboxMessages = json.loads(api.getAllSentMessages())
numMessages = len(outboxMessages['sentMessages'])
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
print ' '
print(' ')
if msgNum >= numMessages:
print '\n Invalid Message Number.\n'
print('\n Invalid Message Number.\n')
main()
# Begin attachment detection
@ -1035,19 +1036,19 @@ def readSentMsg(msgNum):
# End attachment Detection
print '\n To:', getLabelForAddress(outboxMessages['sentMessages'][msgNum]['toAddress']) # Get the to address
print('\n 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([
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 ' Message:\n'
print message # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64')
print ' '
]))
print(' Message:\n')
print(message) # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64')
print(' ')
def readMsg(msgNum):
@ -1057,12 +1058,12 @@ def readMsg(msgNum):
inboxMessages = json.loads(api.getAllInboxMessages())
numMessages = len(inboxMessages['inboxMessages'])
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
if msgNum >= numMessages:
print '\n Invalid Message Number.\n'
print('\n Invalid Message Number.\n')
main()
# Begin attachment detection
@ -1097,17 +1098,17 @@ def readMsg(msgNum):
break
# End attachment Detection
print '\n To:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['toAddress']) # Get the to address
print('\n To:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['toAddress'])) # Get the to address
# Get the from address
print ' From:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['fromAddress'])
print ' Subject:', inboxMessages['inboxMessages'][msgNum]['subject'].decode('base64') # Get the subject
print ''.join([
print(' From:', getLabelForAddress(inboxMessages['inboxMessages'][msgNum]['fromAddress']))
print(' Subject:', inboxMessages['inboxMessages'][msgNum]['subject'].decode('base64')) # Get the subject
print(''.join([
' Received:', datetime.datetime.fromtimestamp(
float(inboxMessages['inboxMessages'][msgNum]['receivedTime'])).strftime('%Y-%m-%d %H:%M:%S'),
])
print ' Message:\n'
print message # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64')
print ' '
]))
print(' Message:\n')
print(message) # inboxMessages['inboxMessages'][msgNum]['message'].decode('base64')
print(' ')
return inboxMessages['inboxMessages'][msgNum]['msgid']
@ -1119,7 +1120,7 @@ def replyMsg(msgNum, forwardORreply):
try:
inboxMessages = json.loads(api.getAllInboxMessages())
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1141,14 +1142,14 @@ def replyMsg(msgNum, forwardORreply):
if toAdd == "c":
usrPrompt = 1
print ' '
print(' ')
main()
elif validAddress(toAdd) is False:
print '\n Invalid Address. "c" to cancel. Please try again.\n'
print('\n Invalid Address. "c" to cancel. Please try again.\n')
else:
break
else:
print '\n Invalid Selection. Reply or Forward only'
print('\n Invalid Selection. Reply or Forward only')
usrPrompt = 0
main()
@ -1180,7 +1181,7 @@ def delMsg(msgNum):
msgAck = api.trashMessage(msgId)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1197,7 +1198,7 @@ def delSentMsg(msgNum):
msgId = outboxMessages['sentMessages'][int(msgNum)]['msgid']
msgAck = api.trashSentMessage(msgId)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1233,7 +1234,7 @@ def buildKnownAddresses():
if entry['address'] not in knownAddresses:
knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address'])
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1248,7 +1249,7 @@ def buildKnownAddresses():
if entry['address'] not in knownAddresses:
knownAddresses[entry['address']] = "%s (%s)" % (entry['label'].decode('base64'), entry['address'])
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1263,21 +1264,20 @@ def listAddressBookEntries():
if "API Error" in response:
return getAPIErrorCode(response)
addressBook = json.loads(response)
print
print ' --------------------------------------------------------------'
print ' | Label | Address |'
print ' |--------------------|---------------------------------------|'
print()
print(' --------------------------------------------------------------')
print(' | Label | Address |')
print(' |--------------------|---------------------------------------|')
for entry in addressBook['addresses']:
label = entry['label'].decode('base64')
address = entry['address']
if len(label) > 19:
label = label[:16] + '...'
print ' | ' + label.ljust(19) + '| ' + address.ljust(37) + ' |'
print ' --------------------------------------------------------------'
print
print(' | ' + label.ljust(19) + '| ' + address.ljust(37) + ' |')
print(' --------------------------------------------------------------')
print()
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1292,7 +1292,7 @@ def addAddressToAddressBook(address, label):
if "API Error" in response:
return getAPIErrorCode(response)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1307,7 +1307,7 @@ def deleteAddressFromAddressBook(address):
if "API Error" in response:
return getAPIErrorCode(response)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1331,7 +1331,7 @@ def markMessageRead(messageID):
if "API Error" in response:
return getAPIErrorCode(response)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1346,7 +1346,7 @@ def markMessageUnread(messageID):
if "API Error" in response:
return getAPIErrorCode(response)
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
@ -1359,7 +1359,7 @@ def markAllMessagesRead():
try:
inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages']
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
for message in inboxMessages:
@ -1375,7 +1375,7 @@ def markAllMessagesUnread():
try:
inboxMessages = json.loads(api.getAllInboxMessages())['inboxMessages']
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
for message in inboxMessages:
@ -1391,15 +1391,15 @@ def clientStatus():
try:
client_status = json.loads(api.clientStatus())
except:
print '\n Connection Error\n'
print('\n Connection Error\n')
usrPrompt = 0
main()
print "\nnetworkStatus: " + client_status['networkStatus'] + "\n"
print "\nnetworkConnections: " + str(client_status['networkConnections']) + "\n"
print "\nnumberOfPubkeysProcessed: " + str(client_status['numberOfPubkeysProcessed']) + "\n"
print "\nnumberOfMessagesProcessed: " + str(client_status['numberOfMessagesProcessed']) + "\n"
print "\nnumberOfBroadcastsProcessed: " + str(client_status['numberOfBroadcastsProcessed']) + "\n"
print("\nnetworkStatus: " + client_status['networkStatus'] + "\n")
print("\nnetworkConnections: " + str(client_status['networkConnections']) + "\n")
print("\nnumberOfPubkeysProcessed: " + str(client_status['numberOfPubkeysProcessed']) + "\n")
print("\nnumberOfMessagesProcessed: " + str(client_status['numberOfMessagesProcessed']) + "\n")
print("\nnumberOfBroadcastsProcessed: " + str(client_status['numberOfBroadcastsProcessed']) + "\n")
def shutdown():
@ -1409,7 +1409,7 @@ def shutdown():
api.shutdown()
except socket.error:
pass
print "\nShutdown command relayed\n"
print("\nShutdown command relayed\n")
def UI(usrInput):
@ -1418,75 +1418,75 @@ def UI(usrInput):
global usrPrompt
if usrInput == "help" or usrInput == "h" or usrInput == "?":
print ' '
print ' -------------------------------------------------------------------------'
print ' | https://github.com/Dokument/PyBitmessage-Daemon |'
print ' |-----------------------------------------------------------------------|'
print ' | Command | Description |'
print ' |------------------------|----------------------------------------------|'
print ' | help | This help file. |'
print ' | apiTest | Tests the API |'
print ' | addInfo | Returns address information (If valid) |'
print ' | bmSettings | BitMessage settings |'
print ' | exit | Use anytime to return to main menu |'
print ' | quit | Quits the program |'
print ' |------------------------|----------------------------------------------|'
print ' | listAddresses | Lists all of the users addresses |'
print ' | generateAddress | Generates a new address |'
print ' | getAddress | Get determinist address from passphrase |'
print ' |------------------------|----------------------------------------------|'
print ' | listAddressBookEntries | Lists entries from the Address Book |'
print ' | addAddressBookEntry | Add address to the Address Book |'
print ' | deleteAddressBookEntry | Deletes address from the Address Book |'
print ' |------------------------|----------------------------------------------|'
print ' | subscribe | Subscribes to an address |'
print ' | unsubscribe | Unsubscribes from an address |'
print ' |------------------------|----------------------------------------------|'
print ' | create | Creates a channel |'
print ' | join | Joins a channel |'
print ' | leave | Leaves a channel |'
print ' |------------------------|----------------------------------------------|'
print ' | inbox | Lists the message information for the inbox |'
print ' | outbox | Lists the message information for the outbox |'
print ' | send | Send a new message or broadcast |'
print ' | unread | Lists all unread inbox messages |'
print ' | read | Reads a message from the inbox or outbox |'
print ' | save | Saves message to text file |'
print ' | delete | Deletes a message or all messages |'
print ' -------------------------------------------------------------------------'
print ' '
print(' ')
print(' -------------------------------------------------------------------------')
print(' | https://github.com/Dokument/PyBitmessage-Daemon |')
print(' |-----------------------------------------------------------------------|')
print(' | Command | Description |')
print(' |------------------------|----------------------------------------------|')
print(' | help | This help file. |')
print(' | apiTest | Tests the API |')
print(' | addInfo | Returns address information (If valid) |')
print(' | bmSettings | BitMessage settings |')
print(' | exit | Use anytime to return to main menu |')
print(' | quit | Quits the program |')
print(' |------------------------|----------------------------------------------|')
print(' | listAddresses | Lists all of the users addresses |')
print(' | generateAddress | Generates a new address |')
print(' | getAddress | Get determinist address from passphrase |')
print(' |------------------------|----------------------------------------------|')
print(' | listAddressBookEntries | Lists entries from the Address Book |')
print(' | addAddressBookEntry | Add address to the Address Book |')
print(' | deleteAddressBookEntry | Deletes address from the Address Book |')
print(' |------------------------|----------------------------------------------|')
print(' | subscribe | Subscribes to an address |')
print(' | unsubscribe | Unsubscribes from an address |')
print(' |------------------------|----------------------------------------------|')
print(' | create | Creates a channel |')
print(' | join | Joins a channel |')
print(' | leave | Leaves a channel |')
print(' |------------------------|----------------------------------------------|')
print(' | inbox | Lists the message information for the inbox |')
print(' | outbox | Lists the message information for the outbox |')
print(' | send | Send a new message or broadcast |')
print(' | unread | Lists all unread inbox messages |')
print(' | read | Reads a message from the inbox or outbox |')
print(' | save | Saves message to text file |')
print(' | delete | Deletes a message or all messages |')
print(' -------------------------------------------------------------------------')
print(' ')
main()
elif usrInput == "apitest": # tests the API Connection.
if apiTest():
print '\n API connection test has: PASSED\n'
print('\n API connection test has: PASSED\n')
else:
print '\n API connection test has: FAILED\n'
print('\n API connection test has: FAILED\n')
main()
elif usrInput == "addinfo":
tmp_address = userInput('\nEnter the Bitmessage Address.')
address_information = json.loads(api.decodeAddress(tmp_address))
print '\n------------------------------'
print('\n------------------------------')
if 'success' in str(address_information['status']).lower():
print ' Valid Address'
print ' Address Version: %s' % str(address_information['addressVersion'])
print ' Stream Number: %s' % str(address_information['streamNumber'])
print(' Valid Address')
print(' Address Version: %s' % str(address_information['addressVersion']))
print(' Stream Number: %s' % str(address_information['streamNumber']))
else:
print ' Invalid Address !'
print(' Invalid Address !')
print '------------------------------\n'
print('------------------------------\n')
main()
elif usrInput == "bmsettings": # tests the API Connection.
bmSettings()
print ' '
print(' ')
main()
elif usrInput == "quit": # Quits the application
print '\n Bye\n'
print('\n Bye\n')
sys.exit(0)
elif usrInput == "listaddresses": # Lists all of the identities in the addressbook
@ -1508,17 +1508,17 @@ def UI(usrInput):
if isRipe == "y":
ripe = True
print genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe)
print(genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe))
main()
elif isRipe == "n":
ripe = False
print genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe)
print(genAdd(lbl, deterministic, passphrase, numOfAdd, addVNum, streamNum, ripe))
main()
elif isRipe == "exit":
usrPrompt = 1
main()
else:
print '\n Invalid input\n'
print('\n Invalid input\n')
main()
elif uInput == "r" or uInput == "random": # Creates a random address with user-defined label
@ -1526,18 +1526,18 @@ def UI(usrInput):
null = ''
lbl = userInput('Enter the label for the new address.')
print genAdd(lbl, deterministic, null, null, null, null, null)
print(genAdd(lbl, deterministic, null, null, null, null, null))
main()
else:
print '\n Invalid input\n'
print('\n Invalid input\n')
main()
elif usrInput == "getaddress": # Gets the address for/from a passphrase
phrase = userInput("Enter the address passphrase.")
print '\n Working...\n'
print('\n Working...\n')
address = getAddress(phrase, 4, 1) # ,vNumber,sNumber)
print '\n Address: ' + address + '\n'
print('\n Address: ' + address + '\n')
usrPrompt = 1
main()
@ -1572,17 +1572,17 @@ def UI(usrInput):
main()
elif usrInput == "inbox":
print '\n Loading...\n'
print('\n Loading...\n')
inbox()
main()
elif usrInput == "unread":
print '\n Loading...\n'
print('\n Loading...\n')
inbox(True)
main()
elif usrInput == "outbox":
print '\n Loading...\n'
print('\n Loading...\n')
outbox()
main()
@ -1603,14 +1603,14 @@ def UI(usrInput):
uInput = userInput("Would you like to read a message from the (I)nbox or (O)utbox?").lower()
if (uInput != 'i' and uInput != 'inbox' and uInput != 'o' and uInput != 'outbox'):
print '\n Invalid Input.\n'
print('\n Invalid Input.\n')
usrPrompt = 1
main()
msgNum = int(userInput("What is the number of the message you wish to open?"))
if (uInput == 'i' or uInput == 'inbox'):
print '\n Loading...\n'
print('\n Loading...\n')
messageID = readMsg(msgNum)
uInput = userInput("\nWould you like to keep this message unread, (Y)es or (N)o?").lower()
@ -1622,14 +1622,14 @@ def UI(usrInput):
uInput = userInput("\nWould you like to (D)elete, (F)orward, (R)eply to, or (Exit) this message?").lower()
if uInput in ['r', 'reply']:
print '\n Loading...\n'
print ' '
print('\n Loading...\n')
print(' ')
replyMsg(msgNum, 'reply')
usrPrompt = 1
elif uInput == 'f' or uInput == 'forward':
print '\n Loading...\n'
print ' '
print('\n Loading...\n')
print(' ')
replyMsg(msgNum, 'forward')
usrPrompt = 1
@ -1638,12 +1638,12 @@ def UI(usrInput):
if uInput == "y":
delMsg(msgNum)
print '\n Message Deleted.\n'
print('\n Message Deleted.\n')
usrPrompt = 1
else:
usrPrompt = 1
else:
print '\n Invalid entry\n'
print('\n Invalid entry\n')
usrPrompt = 1
elif (uInput == 'o' or uInput == 'outbox'):
@ -1657,12 +1657,12 @@ def UI(usrInput):
if uInput == "y":
delSentMsg(msgNum)
print '\n Message Deleted.\n'
print('\n Message Deleted.\n')
usrPrompt = 1
else:
usrPrompt = 1
else:
print '\n Invalid Entry\n'
print('\n Invalid Entry\n')
usrPrompt = 1
main()
@ -1672,7 +1672,7 @@ def UI(usrInput):
uInput = userInput("Would you like to save a message from the (I)nbox or (O)utbox?").lower()
if uInput not in ['i', 'inbox', 'o', 'outbox']:
print '\n Invalid Input.\n'
print('\n Invalid Input.\n')
usrPrompt = 1
main()
@ -1684,7 +1684,7 @@ def UI(usrInput):
msgNum = int(userInput("What is the number of the message you wish to save?"))
if msgNum >= numMessages:
print '\n Invalid Message Number.\n'
print('\n Invalid Message Number.\n')
else:
break
@ -1700,7 +1700,7 @@ def UI(usrInput):
msgNum = int(userInput("What is the number of the message you wish to save?"))
if msgNum >= numMessages:
print '\n Invalid Message Number.\n'
print('\n Invalid Message Number.\n')
else:
break
@ -1729,7 +1729,7 @@ def UI(usrInput):
if msgNum == 'a' or msgNum == 'all':
break
elif int(msgNum) >= numMessages:
print '\n Invalid Message Number.\n'
print('\n Invalid Message Number.\n')
else:
break
@ -1737,17 +1737,17 @@ def UI(usrInput):
if uInput == "y":
if msgNum in ['a', 'all']:
print ' '
print(' ')
for msgNum in range(0, numMessages): # processes all of the messages in the inbox
print ' Deleting message ', msgNum + 1, ' of ', numMessages
print(' Deleting message ', msgNum + 1, ' of ', numMessages)
delMsg(0)
print '\n Inbox is empty.'
print('\n Inbox is empty.')
usrPrompt = 1
else:
delMsg(int(msgNum))
print '\n Notice: Message numbers may have changed.\n'
print('\n Notice: Message numbers may have changed.\n')
main()
else:
usrPrompt = 1
@ -1763,7 +1763,7 @@ def UI(usrInput):
if msgNum in ['a', 'all']:
break
elif int(msgNum) >= numMessages:
print '\n Invalid Message Number.\n'
print('\n Invalid Message Number.\n')
else:
break
@ -1771,33 +1771,33 @@ def UI(usrInput):
if uInput == "y":
if msgNum in ['a', 'all']:
print ' '
print(' ')
for msgNum in range(0, numMessages): # processes all of the messages in the outbox
print ' Deleting message ', msgNum + 1, ' of ', numMessages
print(' Deleting message ', msgNum + 1, ' of ', numMessages)
delSentMsg(0)
print '\n Outbox is empty.'
print('\n Outbox is empty.')
usrPrompt = 1
else:
delSentMsg(int(msgNum))
print '\n Notice: Message numbers may have changed.\n'
print('\n Notice: Message numbers may have changed.\n')
main()
else:
usrPrompt = 1
else:
print '\n Invalid Entry.\n'
print('\n Invalid Entry.\n')
usrPrompt = 1
main()
elif usrInput == "exit":
print '\n You are already at the main menu. Use "quit" to quit.\n'
print('\n You are already at the main menu. Use "quit" to quit.\n')
usrPrompt = 1
main()
elif usrInput == "listaddressbookentries":
res = listAddressBookEntries()
if res == 20:
print '\n Error: API function not supported.\n'
print('\n Error: API function not supported.\n')
usrPrompt = 1
main()
@ -1806,9 +1806,9 @@ def UI(usrInput):
label = userInput('Enter label')
res = addAddressToAddressBook(address, label)
if res == 16:
print '\n Error: Address already exists in Address Book.\n'
print('\n Error: Address already exists in Address Book.\n')
if res == 20:
print '\n Error: API function not supported.\n'
print('\n Error: API function not supported.\n')
usrPrompt = 1
main()
@ -1816,7 +1816,7 @@ def UI(usrInput):
address = userInput('Enter address')
res = deleteAddressFromAddressBook(address)
if res == 20:
print '\n Error: API function not supported.\n'
print('\n Error: API function not supported.\n')
usrPrompt = 1
main()
@ -1841,7 +1841,7 @@ def UI(usrInput):
main()
else:
print '\n "', usrInput, '" is not a command.\n'
print('\n "', usrInput, '" is not a command.\n')
usrPrompt = 1
main()
@ -1853,24 +1853,24 @@ def main():
global usrPrompt
if usrPrompt == 0:
print '\n ------------------------------'
print ' | Bitmessage Daemon by .dok |'
print ' | Version 0.3.1 for BM 0.6.2 |'
print ' ------------------------------'
print('\n ------------------------------')
print(' | Bitmessage Daemon by .dok |')
print(' | Version 0.3.1 for BM 0.6.2 |')
print(' ------------------------------')
api = xmlrpclib.ServerProxy(apiData()) # Connect to BitMessage using these api credentials
if apiTest() is False:
print '\n ****************************************************************'
print ' WARNING: You are not connected to the Bitmessage client.'
print ' Either Bitmessage is not running or your settings are incorrect.'
print ' Use the command "apiTest" or "bmSettings" to resolve this issue.'
print ' ****************************************************************\n'
print('\n ****************************************************************')
print(' WARNING: You are not connected to the Bitmessage client.')
print(' Either Bitmessage is not running or your settings are incorrect.')
print(' Use the command "apiTest" or "bmSettings" to resolve this issue.')
print(' ****************************************************************\n')
print 'Type (H)elp for a list of commands.' # Startup message
print('Type (H)elp for a list of commands.') # Startup message
usrPrompt = 2
elif usrPrompt == 1:
print '\nType (H)elp for a list of commands.' # Startup message
print('\nType (H)elp for a list of commands.') # Startup message
usrPrompt = 2
try:

View File

@ -1010,7 +1010,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
def loadInbox():
"""Load the list of messages"""
sys.stdout = sys.__stdout__
print "Loading inbox messages..."
print("Loading inbox messages...")
sys.stdout = printlog
where = "toaddress || fromaddress || subject || message"
@ -1062,7 +1062,7 @@ def loadInbox():
def loadSent():
"""Load the messages that sent"""
sys.stdout = sys.__stdout__
print "Loading sent messages..."
print("Loading sent messages...")
sys.stdout = printlog
where = "toaddress || fromaddress || subject || message"
@ -1148,7 +1148,7 @@ def loadSent():
def loadAddrBook():
"""Load address book"""
sys.stdout = sys.__stdout__
print "Loading address book..."
print("Loading address book...")
sys.stdout = printlog
ret = sqlQuery("SELECT label, address FROM addressbook")
@ -1254,7 +1254,7 @@ def run(stdscr):
def doShutdown():
"""Shutting the app down"""
sys.stdout = sys.__stdout__
print "Shutting down..."
print("Shutting down...")
sys.stdout = printlog
shutdown.doCleanShutdown()
sys.stdout = sys.__stdout__

View File

@ -2,7 +2,6 @@
Core classes for loading images and converting them to a Texture.
The raw image data can be keep in memory for further access
"""
import hashlib
from io import BytesIO
@ -26,7 +25,6 @@ def generate(Generate_string=None):
image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR)
image = generate_image(image, color, hash_string)
image = image.resize(RESOLUTION, 0)
data = BytesIO()
image.save(data, format='png')
data.seek(0)
@ -46,10 +44,8 @@ def generate_hash(string):
string = str.lower(string)
hash_object = hashlib.md5(str.encode(string))
print(hash_object.hexdigest())
# returned object is a hex string
return hash_object.hexdigest()
except IndexError:
print("Error: Please enter a string as an argument.")
@ -59,29 +55,24 @@ def random_color(hash_string):
# remove first three digits from hex string
split = 6
rgb = hash_string[:split]
split = 2
r = rgb[:split]
g = rgb[split:2 * split]
b = rgb[2 * split:3 * split]
color = (int(r, 16), int(g, 16),
int(b, 16), 0xFF)
return color
def generate_image(image, color, hash_string):
"""Generating images"""
hash_string = hash_string[6:]
lower_x = 1
lower_y = 1
upper_x = int(V_RESOLUTION[0] / 2) + 1
upper_y = V_RESOLUTION[1] - 1
limit_x = V_RESOLUTION[0] - 1
index = 0
for x in range(lower_x, upper_x):
for y in range(lower_y, upper_y):
if int(hash_string[index], 16) % 2 == 0:
@ -89,5 +80,4 @@ def generate_image(image, color, hash_string):
image.putpixel((limit_x - x, y), color)
index = index + 1
return image

View File

@ -4,25 +4,25 @@ Sql queries for bitmessagekivy
from helper_sql import sqlQuery
def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False, start_indx=0, end_indx=20):
def search_sql(
xAddress="toaddress", account=None, folder="inbox", where=None,
what=None, unreadOnly=False, start_indx=0, end_indx=20):
"""Method helping for searching mails"""
# pylint: disable=too-many-arguments, too-many-branches
if what is not None and what != "":
what = "%" + what + "%"
else:
what = None
if folder == "sent" or folder == "draft":
sqlStatementBase = (
'''SELECT toaddress, fromaddress, subject, message, status, ackdata,'''
''' lastactiontime FROM sent ''')
'''SELECT toaddress, fromaddress, subject, message, status,'''
''' ackdata, lastactiontime FROM sent ''')
elif folder == "addressbook":
sqlStatementBase = '''SELECT label, address From addressbook '''
else:
sqlStatementBase = (
'''SELECT folder, msgid, toaddress, message, fromaddress, subject,'''
''' received, read FROM inbox ''')
'''SELECT folder, msgid, toaddress, message, fromaddress,'''
''' subject, received, read FROM inbox ''')
sqlStatementParts = []
sqlArguments = []
if account is not None:
@ -58,10 +58,15 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w
sqlStatementParts.append("read = 0")
if sqlStatementParts:
sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts)
# if folder in ("sent", "draft"):
if folder == "sent" or folder == "draft":
sqlStatementBase += " ORDER BY lastactiontime DESC limit {0}, {1}".format(start_indx, end_indx)
sqlStatementBase += \
"ORDER BY lastactiontime DESC limit {0}, {1}".format(
start_indx, end_indx)
elif folder == "inbox":
sqlStatementBase += " ORDER BY received DESC limit {0}, {1}".format(start_indx, end_indx)
sqlStatementBase += \
"ORDER BY received DESC limit {0}, {1}".format(
start_indx, end_indx)
# elif folder == "addressbook":
# sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx)
return sqlQuery(sqlStatementBase, sqlArguments)

View File

@ -25,7 +25,8 @@
#:set color_font (0.957, 0.890, 0.843, 1) # off white
<MyNavigationDrawerIconButton@NavigationDrawerIconButton>:
icon: 'checkbox-blank-circle'
font_style: 'Body1'
theme_text_color: 'Secondary'
<MySpinnerOption@SpinnerOption>:
font_size: '12.5sp'
@ -39,7 +40,7 @@
height: dp(7)
NavigationDrawerSubheader:
text: "Accounts"
NavigationDrawerIconButton:
AddressDropdown:
CustomSpinner:
id: btn
pos_hint:{"x":0,"y":.25}
@ -57,47 +58,48 @@
y: self.parent.y + self.parent.height/4
size: self.parent.height/2, self.parent.height/2
ArrowImg:
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
id: inbox_cnt
icon: 'email-open'
text: "Inbox"
on_release: app.root.ids.scr_mngr.current = 'inbox'
badge_text: "0"
on_press: app.load_screen(self)
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
id: send_cnt
icon: 'send'
text: "Sent"
#use_active: False
on_release: app.root.ids.scr_mngr.current = 'sent'
badge_text: "0"
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
id: draft_cnt
icon: 'message-draw'
text: "Draft"
on_release: app.root.ids.scr_mngr.current = 'draft'
badge_text: "0"
#NavigationDrawerIconButton:
#MyNavigationDrawerIconButton:
#text: "Starred"
#icon:'star'
#on_release: app.root.ids.scr_mngr.current = 'starred'
#badge_text: "0"
#NavigationDrawerIconButton:
#MyNavigationDrawerIconButton:
#icon: 'archive'
#text: "Archieve"
#on_release: app.root.ids.scr_mngr.current = 'archieve'
#badge_text: "0"
#NavigationDrawerIconButton:
#MyNavigationDrawerIconButton:
#icon: 'email-open-outline'
#text: "Spam"
#on_release: app.root.ids.scr_mngr.current = 'spam'
#badge_text: "0"
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
id: trash_cnt
icon: 'delete'
text: "Trash"
on_release: app.root.ids.scr_mngr.current = 'trash'
badge_text: "0"
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
id: allmail_cnt
text: "All Mails"
icon:'contact-mail'
@ -107,31 +109,31 @@
NavigationDrawerDivider:
NavigationDrawerSubheader:
text: "All labels"
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "Address Book"
icon:'book-multiple'
on_release: app.root.ids.scr_mngr.current = 'addressbook'
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "Settings"
icon:'settings'
on_release: app.root.ids.scr_mngr.current = 'set'
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "Subscriptions/Payment"
icon:'bell'
on_release: app.root.ids.scr_mngr.current = 'payment'
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "Credits"
icon:'wallet'
on_release: app.root.ids.scr_mngr.current = 'credits'
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "new address"
icon:'account-plus'
on_release: app.root.ids.scr_mngr.current = 'login'
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "Network Status"
icon:'server-network'
on_release: app.root.ids.scr_mngr.current = 'networkstat'
NavigationDrawerIconButton:
MyNavigationDrawerIconButton:
text: "My Addresses"
icon:'account-multiple'
on_release: app.root.ids.scr_mngr.current = 'myaddress'
@ -206,8 +208,17 @@ NavigationLayout:
transition: NoTransition()
BoxLayout:
orientation: 'vertical'
spacing: dp(10)
spacing: dp(5)
SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
#FloatLayout:
# MDScrollViewRefreshLayout:
# id: refresh_layout
@ -229,7 +240,17 @@ NavigationLayout:
name: 'sent'
BoxLayout:
orientation: 'vertical'
spacing: dp(5)
SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
@ -242,6 +263,21 @@ NavigationLayout:
<Trash>:
name: 'trash'
BoxLayout:
orientation: 'vertical'
spacing: dp(5)
GridLayout:
id: identi_tag
padding: [20, 20, 0, 5]
spacing: dp(5)
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
id: scroll_y
do_scroll_x: False
@ -252,6 +288,20 @@ NavigationLayout:
<Draft>:
name: 'draft'
BoxLayout:
orientation: 'vertical'
spacing: dp(5)
GridLayout:
id: identi_tag
padding: [20, 20, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
id: scroll_y
do_scroll_x: False
@ -292,6 +342,19 @@ NavigationLayout:
# root_layout: root.set_root_layout()
# MDList:
# id: ml
BoxLayout:
orientation: 'vertical'
spacing: dp(5)
GridLayout:
id: identi_tag
padding: [20, 20, 0, 5]
spacing: dp(5)
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
@ -545,12 +608,6 @@ NavigationLayout:
color: (1,1,1,1)
halign: 'center'
<AddressSuccessful>:
name: 'add_sucess'
Label:
text: 'Successfully created a new bit address'
color: 0,0,0,1
<Setting>:
name: 'set'
ScrollView:
@ -624,7 +681,17 @@ NavigationLayout:
name: 'myaddress'
BoxLayout:
orientation: 'vertical'
spacing: dp(5)
SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: 'My Addresses'
font_style: 'Subtitle2'
FloatLayout:
MDScrollViewRefreshLayout:
id: refresh_layout
@ -639,7 +706,17 @@ NavigationLayout:
name: 'addressbook'
BoxLayout:
orientation: 'vertical'
spacing: dp(5)
SearchBar:
GridLayout:
id: identi_tag
padding: [20, 0, 0, 5]
cols: 1
size_hint_y: None
height: self.minimum_height
MDLabel:
text: ''
font_style: 'Subtitle2'
BoxLayout:
orientation:'vertical'
ScrollView:
@ -800,7 +877,7 @@ NavigationLayout:
id: popup
size_hint : (None,None)
height: 2*(label.height + address.height) + 10
width :app.window_size[0] - app.window_size[0]/10
width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4)
title: 'add contact\'s'
background: './images/popup.jpeg'
title_size: sp(20)
@ -1031,7 +1108,7 @@ NavigationLayout:
id: myadd_popup
size_hint : (None,None)
height: 4.5*(myaddr_label.height+ my_add_btn.children[0].height)
width :app.window_size[0] - app.window_size[0]/10
width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4)
background: './images/popup.jpeg'
auto_dismiss: False
separator_height: 0
@ -1111,7 +1188,7 @@ NavigationLayout:
id: addbook_popup
size_hint : (None,None)
height: 4*(add_label.height)
width :app.window_size[0] - app.window_size[0]/10
width :app.window_size[0] - (app.window_size[0]/10 if app.app_platform == 'android' else app.window_size[0]/4)
background: './images/popup.jpeg'
separator_height: 0
auto_dismiss: False

View File

@ -1,8 +1,9 @@
"""
Bitmessage android(mobile) interface
src/bitmessagekivy/mpybit.py
=================================
"""
# pylint: disable=relative-import, import-error, no-name-in-module
# pylint: disable=too-few-public-methods, too-many-lines, unused-argument
# pylint: disable=import-error, no-name-in-module, too-many-lines
# pylint: disable=too-few-public-methods, unused-argument, too-many-ancestors
import os
import time
from bmconfigparser import BMConfigParser
@ -36,8 +37,6 @@ from kivy.uix.screenmanager import Screen
from kivy.uix.spinner import Spinner
from kivy.uix.textinput import TextInput
from kivy.utils import platform
from bitmessagekivy import kivy_helper_search
from kivymd.uix.button import MDIconButton
from kivymd.uix.dialog import MDDialog
@ -48,7 +47,7 @@ from kivymd.uix.list import (
IRightBodyTouch,
TwoLineAvatarIconListItem,
TwoLineListItem,
OneLineIconListItem
OneLineIconListItem,
)
from kivymd.uix.navigationdrawer import (
MDNavigationDrawer,
@ -60,35 +59,36 @@ import queues
from semaphores import kivyuisignaler
import state
from bitmessagekivy.uikivysignaler import UIkivySignaler
from bitmessagekivy.uikivysignaler import UIkivySignaler
from bitmessagekivy import identiconGeneration
from addresses import addBMIfNotPresent, decodeAddress
from addresses import addBMIfNotPresent, decodeAddress, encodeVarint
# pylint: disable=unused-argument, too-few-public-methods
def toast(text):
"""Function displays toast message"""
# pylint: disable=redefined-outer-name
from kivymd.toast.kivytoast import toast
"""Method will display the toast message"""
from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name
toast(text)
return
class Navigatorss(MDNavigationDrawer):
"""Navigator class (image, title and logo)"""
"""Navigators class contains image, title and logo"""
image_source = StringProperty('images/qidenticon_two.png')
title = StringProperty('Navigation')
drawer_logo = StringProperty()
class Inbox(Screen):
"""Inbox Screen uses screen to show widgets of screens."""
"""Inbox Screen uses screen to show widgets of screens"""
queryreturn = ListProperty()
has_refreshed = True
account = StringProperty()
def __init__(self, *args, **kwargs):
"""Method Parsing the address."""
"""Method Parsing the address"""
super(Inbox, self).__init__(*args, **kwargs)
Clock.schedule_once(self.init_ui, 0)
@ -100,11 +100,11 @@ class Inbox(Screen):
state.association = BMConfigParser().addresses()[0]
def init_ui(self, dt=0):
"""Clock schdule for method inbox accounts."""
"""Clock schdule for method inbox accounts"""
self.loadMessagelist()
def loadMessagelist(self, where="", what=""):
"""Load Inbox list for Inbox messages."""
"""Load Inbox list for Inbox messages"""
# pylint: disable=too-many-locals
self.set_defaultAddress()
self.account = state.association
@ -260,6 +260,8 @@ class Inbox(Screen):
int(state.trash_count) + 1)
state.all_count = str(
int(state.all_count) - 1)
if int(state.inbox_count) <= 0:
self.ids.identi_tag.children[0].text = ''
self.ids.ml.remove_widget(
instance.parent.parent)
toast('Deleted')
@ -303,13 +305,13 @@ class Inbox(Screen):
class MyAddress(Screen):
"""MyAddress screen uses screen to show widgets of screens."""
"""MyAddress screen uses screen to show widgets of screens"""
addresses_list = ListProperty()
has_refreshed = True
is_add_created = False
def __init__(self, *args, **kwargs):
"""Clock schdule for method Myaddress accounts."""
"""Clock schdule for method Myaddress accounts"""
super(MyAddress, self).__init__(*args, **kwargs)
Clock.schedule_once(self.init_ui, 0)
@ -319,12 +321,12 @@ class MyAddress(Screen):
self.addresses_list = state.kivyapp.variable_1
if state.searcing_text:
self.ids.refresh_layout.scroll_y = 1.0
filtered_list = filter(
lambda addr: self.filter_address(
addr), BMConfigParser().addresses())
filtered_list = [x for x in BMConfigParser().addresses() if self.filter_address(x)]
self.addresses_list = filtered_list
self.addresses_list = [obj for obj in reversed(self.addresses_list)]
self.ids.identi_tag.children[0].text = ''
if self.addresses_list:
self.ids.identi_tag.children[0].text = 'My Addresses'
self.has_refreshed = True
self.set_mdList(0, 15)
self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y)
@ -395,7 +397,7 @@ class MyAddress(Screen):
"""Method used for loading the myaddress screen data"""
state.searcing_text = ''
state.kivyapp.root.ids.sc10.children[2].active = False
self.children[2].children[1].ids.search_field.text = ''
self.children[2].children[2].ids.search_field.text = ''
self.has_refreshed = True
self.ids.ml.clear_widgets()
self.init_ui()
@ -406,9 +408,7 @@ class MyAddress(Screen):
@staticmethod
def filter_address(address):
"""Method will filter the my address list data"""
if filter(lambda x: (state.searcing_text).lower() in x, [
BMConfigParser().get(
address, 'label').lower(), address.lower()]):
if [x for x in [BMConfigParser().get(address, 'label').lower(), address.lower()] if (state.searcing_text).lower() in x]:
return True
return False
@ -439,10 +439,12 @@ class AddressBook(Screen):
where = ['label', 'address']
what = state.searcing_text
xAddress = ''
self.ids.identi_tag.children[0].text = ''
self.queryreturn = kivy_helper_search.search_sql(
xAddress, account, "addressbook", where, what, False)
self.queryreturn = [obj for obj in reversed(self.queryreturn)]
if self.queryreturn:
self.ids.identi_tag.children[0].text = 'Address Book'
self.has_refreshed = True
self.set_mdList(0, 20)
self.ids.scroll_y.bind(scroll_y=self.check_scroll_y)
@ -518,19 +520,22 @@ class AddressBook(Screen):
def delete_address(self, address, instance, *args):
"""Delete inbox mail from inbox listing"""
self.ids.ml.remove_widget(instance.parent.parent)
if len(self.ids.ml.children) == 0:
self.ids.identi_tag.children[0].text = ''
sqlExecute(
"DELETE FROM addressbook WHERE address = '{}';".format(address))
class SelectableRecycleBoxLayout(
FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout):
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
"""Adds selection and focus behaviour to the view"""
# pylint: disable = too-many-ancestors, duplicate-bases
# pylint: disable = duplicate-bases
pass
class SelectableLabel(RecycleDataViewBehavior, Label):
"""Add selection support to the Label"""
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
@ -541,7 +546,6 @@ class SelectableLabel(RecycleDataViewBehavior, Label):
return super(SelectableLabel, self).refresh_view_attrs(
rv, index, data)
# pylint: disable=inconsistent-return-statements
def on_touch_down(self, touch):
"""Add selection on touch down"""
if super(SelectableLabel, self).on_touch_down(touch):
@ -560,6 +564,7 @@ class SelectableLabel(RecycleDataViewBehavior, Label):
class RV(RecycleView):
"""Recycling View"""
def __init__(self, **kwargs): # pylint: disable=useless-super-delegation
"""Recycling Method"""
super(RV, self).__init__(**kwargs)
@ -568,7 +573,6 @@ class RV(RecycleView):
class DropDownWidget(BoxLayout):
"""Adding Dropdown Widget"""
# pylint: disable=too-many-statements, too-many-locals
# pylint: disable=inconsistent-return-statements
txt_input = ObjectProperty()
rv = ObjectProperty()
@ -583,6 +587,7 @@ class DropDownWidget(BoxLayout):
sendMessageToPeople = True
if sendMessageToPeople:
if toAddress != '' and subject and message:
from addresses import decodeAddress
status, addressVersionNumber, streamNumber, ripe = (
decodeAddress(toAddress))
if status == 'success':
@ -601,13 +606,15 @@ class DropDownWidget(BoxLayout):
state.send_draft_mail)
self.parent.parent.screens[15].clear_widgets()
self.parent.parent.screens[15].add_widget(Draft())
# state.detailPageType = ''
# state.send_draft_mail = None
else:
from addresses import addBMIfNotPresent
toAddress = addBMIfNotPresent(toAddress)
statusIconColor = 'red'
if (addressVersionNumber > 4) or (
addressVersionNumber <= 1):
print ("addressVersionNumber > 4"\
" or addressVersionNumber <= 1")
print("addressVersionNumber > 4 or addressVersionNumber <= 1")
if streamNumber > 1 or streamNumber == 0:
print("streamNumber > 1 or streamNumber == 0")
if statusIconColor == 'red':
@ -674,9 +681,10 @@ class DropDownWidget(BoxLayout):
# pylint: disable=attribute-defined-outside-init
def address_error_message(self, msg):
"""Generates error message"""
width = .8 if platform == 'android' else .55
msg_dialog = MDDialog(
text=msg,
title='', size_hint=(.8, .25), text_button_ok='Ok',
title='', size_hint=(width, .25), text_button_ok='Ok',
events_callback=self.callback_for_menu_items)
msg_dialog.open()
@ -702,6 +710,7 @@ class DropDownWidget(BoxLayout):
class MyTextInput(TextInput):
"""Takes the text input in the field"""
txt_input = ObjectProperty()
flt_list = ObjectProperty()
word_list = ListProperty()
@ -757,12 +766,14 @@ class Payment(Screen):
class Credits(Screen):
"""Credits Module"""
available_credits = StringProperty('{0}'.format('0'))
"""Credits Method"""
available_credits = StringProperty(
'{0}'.format('0'))
class Login(Screen):
"""Login Screeen"""
pass
@ -802,6 +813,7 @@ class NetworkStat(Screen):
class ContentNavigationDrawer(Navigatorss):
"""Navigate Content Drawer"""
# pylint: disable=too-many-arguments
pass
@ -872,7 +884,7 @@ class Sent(Screen):
account = StringProperty()
def __init__(self, *args, **kwargs):
"""Association with the screen."""
"""Association with the screen"""
super(Sent, self).__init__(*args, **kwargs)
if state.association == '':
if BMConfigParser().addresses():
@ -885,7 +897,7 @@ class Sent(Screen):
print(dt)
def loadSent(self, where="", what=""):
"""Load Sent list for Sent messages."""
"""Load Sent list for Sent messages"""
self.account = state.association
if state.searcing_text:
self.ids.scroll_y.scroll_y = 1.0
@ -893,8 +905,10 @@ class Sent(Screen):
what = state.searcing_text
xAddress = 'fromaddress'
data = []
self.ids.identi_tag.children[0].text = ''
self.sentDataQuery(xAddress, where, what)
if self.queryreturn:
self.ids.identi_tag.children[0].text = 'Sent'
self.set_sentCount(state.sent_count)
for mail in self.queryreturn:
data.append({
@ -923,7 +937,7 @@ class Sent(Screen):
self.queryreturn = kivy_helper_search.search_sql(
xAddress,
self.account,
"sent",
'sent',
where,
what,
False,
@ -1056,6 +1070,8 @@ class Sent(Screen):
state.sent_count = str(int(state.sent_count) - 1)
state.trash_count = str(int(state.trash_count) + 1)
state.all_count = str(int(state.all_count) - 1)
if int(state.sent_count) <= 0:
self.ids.identi_tag.children[0].text = ''
sqlExecute(
"UPDATE sent SET folder = 'trash'"
" WHERE ackdata = ?;", data_index)
@ -1089,7 +1105,7 @@ class Trash(Screen):
"""Trash Screen uses screen to show widgets of screens"""
trash_messages = ListProperty()
has_refreshed = True
delete_index = StringProperty()
# delete_index = StringProperty()
table_name = StringProperty()
def __init__(self, *args, **kwargs):
@ -1098,12 +1114,14 @@ class Trash(Screen):
Clock.schedule_once(self.init_ui, 0)
def init_ui(self, dt=0):
"""Clock Schdule for method trash screen."""
"""Clock Schdule for method trash screen"""
if state.association == '':
if BMConfigParser().addresses():
state.association = BMConfigParser().addresses()[0]
self.ids.identi_tag.children[0].text = ''
self.trashDataQuery(0, 20)
if self.trash_messages:
self.ids.identi_tag.children[0].text = 'Trash'
src_mng_obj = state.kivyapp.root.children[2].children[0].ids
src_mng_obj.trash_cnt.badge_text = state.trash_count
self.set_mdList()
@ -1194,17 +1212,18 @@ class Trash(Screen):
def delete_confirmation(self):
"""Show confirmation delete popup"""
width = .8 if platform == 'android' else .55
delete_msg_dialog = MDDialog(
text='Are you sure you want to delete this'
' message permanently from trash?',
title='',
size_hint=(.8, .25),
size_hint=(width, .25),
text_button_ok='Yes',
text_button_cancel='No',
events_callback=self.callback_for_delete_msg)
delete_msg_dialog.open()
def callback_for_delete_msg(self, text_item):
def callback_for_delete_msg(self, text_item, *arg):
"""Getting the callback of alert box"""
if text_item == 'Yes':
self.delete_message_from_trash()
@ -1215,11 +1234,9 @@ class Trash(Screen):
"""Deleting message from trash"""
self.children[1].active = True
if self.table_name == 'inbox':
sqlExecute("DELETE FROM inbox WHERE msgid = ?;", str(
self.delete_index))
sqlExecute("DELETE FROM inbox WHERE msgid = ?;", self.delete_index)
elif self.table_name == 'sent':
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str(
self.delete_index))
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", self.delete_index)
msg_count_objs = state.kivyapp.root.children[2].children[0].ids
if int(state.trash_count) > 0:
msg_count_objs.trash_cnt.badge_text = str(
@ -1230,6 +1247,7 @@ class Trash(Screen):
class Page(Screen):
"""Page Screen show widgets of page"""
pass
@ -1249,6 +1267,7 @@ class Create(Screen):
class Setting(Screen):
"""Setting the Screen components"""
pass
@ -1261,6 +1280,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
nav_drawer = ObjectProperty()
state.screen_density = Window.size
window_size = state.screen_density
app_platform = platform
title = "PyBitmessage"
imgstatus = False
count = 0
@ -1283,7 +1303,6 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
def build(self):
"""Method builds the widget"""
print("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSss")
print(os.path.join(os.path.dirname(__file__), 'main.kv'))
main_widget = Builder.load_file(
os.path.join(os.path.dirname(__file__), 'main.kv'))
@ -1327,12 +1346,12 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
Clock.schedule_once(self.setCurrentAccountData, 0.5)
def setCurrentAccountData(self, dt=0):
"""This method set the current accout data on all the screens."""
"""This method set the current accout data on all the screens"""
self.root.ids.sc1.ids.ml.clear_widgets()
self.root.ids.sc1.loadMessagelist(state.association)
self.root.ids.sc4.ids.ml.clear_widgets()
self.root.ids.sc4.children[2].children[1].ids.search_field.text = ''
self.root.ids.sc4.children[2].children[2].ids.search_field.text = ''
self.root.ids.sc4.loadSent(state.association)
self.root.ids.sc16.clear_widgets()
@ -1636,30 +1655,30 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
if state.search_screen == 'inbox':
try:
self.root.ids.sc1.children[
3].children[1].ids.search_field.text = ''
3].children[2].ids.search_field.text = ''
except Exception:
self.root.ids.sc1.children[
2].children[1].ids.search_field.text = ''
2].children[2].ids.search_field.text = ''
self.root.ids.sc1.children[1].active = True
Clock.schedule_once(self.search_callback, 0.5)
elif state.search_screen == 'addressbook':
self.root.ids.sc11.children[
2].children[1].ids.search_field.text = ''
2].children[2].ids.search_field.text = ''
self.root.ids.sc11.children[
1].active = True
Clock.schedule_once(self.search_callback, 0.5)
elif state.search_screen == 'myaddress':
try:
self.root.ids.sc10.children[
3].children[1].ids.search_field.text = ''
3].children[2].ids.search_field.text = ''
except Exception:
self.root.ids.sc10.children[
2].children[1].ids.search_field.text = ''
2].children[2].ids.search_field.text = ''
self.root.ids.sc10.children[1].active = True
Clock.schedule_once(self.search_callback, 0.5)
else:
self.root.ids.sc4.children[
2].children[1].ids.search_field.text = ''
2].children[2].ids.search_field.text = ''
self.root.ids.sc4.children[1].active = True
Clock.schedule_once(self.search_callback, 0.5)
return
@ -1699,7 +1718,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
self.root.ids.scr_mngr.current = 'allmails'
try:
self.root.ids.sc17.children[1].active = True
except Exception as e:
except Exception:
self.root.ids.sc17.children[0].children[1].active = True
Clock.schedule_once(partial(self.load_screen_callback, instance), 1)
@ -1710,11 +1729,15 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods
self.root.ids.sc1.loadMessagelist(state.association)
self.root.ids.sc1.children[1].active = False
elif instance.text == 'All Mails':
if len(self.root.ids.sc17.ids.ml.children) <= 2:
self.root.ids.sc17.clear_widgets()
self.root.ids.sc17.add_widget(Allmails())
else:
self.root.ids.sc17.ids.ml.clear_widgets()
self.root.ids.sc17.loadMessagelist()
try:
self.root.ids.sc17.children[1].active = False
except Exception as e:
except Exception:
self.root.ids.sc17.children[0].children[1].active = False
@ -1753,26 +1776,6 @@ class GrashofPopup(Popup):
self.parent.children[1].ids.scr_mngr.current = 'addressbook'
toast('Saved')
# pylint: disable=attribute-defined-outside-init
def show_error_message(self):
"""Showing error message"""
content = MDLabel(
font_style='Body1',
theme_text_color='Secondary',
text="Hey you are not allowed to save blank address contact. "
"That's wrong!",
size_hint_y=None,
valign='top')
content.bind(texture_size=content.setter('size'))
self.dialog = MDDialog(content=content,
size_hint=(.8, None),
height=dp(200),
auto_dismiss=False)
self.dialog.add_action_button("ok",
action=lambda *x: self.dialog.dismiss())
self.dialog.open()
@staticmethod
def close_pop():
"""Pop is Canceled"""
@ -1834,8 +1837,7 @@ class GrashofPopup(Popup):
elif status == 'checksumfailed':
text = "The address is not typed or copied correctly(the checksum failed)."
elif status == 'versiontoohigh':
text = "The version number of this address is higher"\
" than this software can support. Please upgrade Bitmessage."
text = "The version number of this address is higher than this software can support. Please upgrade Bitmessage."
elif status == 'invalidcharacters':
text = "The address contains invalid characters."
elif status == 'ripetooshort':
@ -1849,22 +1851,26 @@ class GrashofPopup(Popup):
class AvatarSampleWidget(ILeftBody, Image):
"""Avatar Sample Widget"""
pass
class IconLeftSampleWidget(ILeftBodyTouch, MDIconButton):
"""Left icon sample widget"""
pass
class IconRightSampleWidget(IRightBodyTouch, MDCheckbox):
"""Right icon sample widget"""
pass
class NavigationDrawerTwoLineListItem(
TwoLineListItem, NavigationDrawerHeaderBase):
"""Navigation Drawer in Listitems"""
address_property = StringProperty()
def __init__(self, **kwargs):
@ -1940,7 +1946,7 @@ class MailDetail(Screen):
self.children[0].children[0].active = True
if state.detailPageType == 'sent':
state.kivyapp.root.ids.sc4.children[
2].children[1].ids.search_field.text = ''
2].children[2].ids.search_field.text = ''
sqlExecute(
"UPDATE sent SET folder = 'trash' WHERE"
" ackdata = ?;", state.mail_id)
@ -1950,12 +1956,12 @@ class MailDetail(Screen):
self.parent.screens[3].loadSent(state.association)
elif state.detailPageType == 'inbox':
state.kivyapp.root.ids.sc1.children[
2].children[1].ids.search_field.text = ''
2].children[2].ids.search_field.text = ''
self.parent.screens[0].children[2].children[
1].ids.search_field.text = ''
2].ids.search_field.text = ''
sqlExecute(
"UPDATE inbox SET folder = 'trash' WHERE"
" msgid = ?;", str(state.mail_id))
" msgid = ?;", state.mail_id)
msg_count_objs.inbox_cnt.badge_text = str(
int(state.inbox_count) - 1)
state.inbox_count = str(int(state.inbox_count) - 1)
@ -1963,8 +1969,7 @@ class MailDetail(Screen):
self.parent.screens[0].loadMessagelist(state.association)
elif state.detailPageType == 'draft':
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str(
state.mail_id))
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", state.mail_id)
msg_count_objs.draft_cnt.badge_text = str(
int(state.draft_count) - 1)
state.draft_count = str(int(state.draft_count) - 1)
@ -1982,8 +1987,8 @@ class MailDetail(Screen):
state.all_count = str(int(state.all_count) - 1)
self.parent.screens[4].clear_widgets()
self.parent.screens[4].add_widget(Trash())
self.parent.screens[16].ids.ml.clear_widgets()
self.parent.screens[16].init_ui(dt=0)
self.parent.screens[16].clear_widgets()
self.parent.screens[16].add_widget(Allmails())
Clock.schedule_once(self.callback_for_delete, 4)
def callback_for_delete(self, dt=0):
@ -1999,7 +2004,7 @@ class MailDetail(Screen):
"""Reply inbox messages"""
data = sqlQuery(
"select toaddress, fromaddress, subject, message from inbox where"
" msgid = ?;", str(state.mail_id))
" msgid = ?;", state.mail_id)
composer_obj = self.parent.screens[2].children[1].ids
composer_obj.ti.text = data[0][0]
composer_obj.btn.text = data[0][0]
@ -2138,7 +2143,7 @@ class ShowQRCode(Screen):
"""ShowQRCode Screen uses to show the detail of mails"""
def qrdisplay(self):
"""Showing QR Code"""
"""Method used for showing QR Code"""
# self.manager.parent.parent.parent.ids.search_bar.clear_widgets()
self.ids.qr.clear_widgets()
from kivy.garden.qrcode import QRCodeWidget
@ -2168,18 +2173,20 @@ class Draft(Screen):
print(dt)
def sentaccounts(self):
"""Load draft accounts."""
"""Load draft accounts"""
self.account = state.association
self.loadDraft()
def loadDraft(self, where="", what=""):
"""Load draft list for Draft messages."""
"""Load draft list for Draft messages"""
xAddress = 'fromaddress'
self.ids.identi_tag.children[0].text = ''
self.draftDataQuery(xAddress, where, what)
if state.msg_counter_objs:
state.msg_counter_objs.draft_cnt.badge_text = str(
len(self.queryreturn))
if self.queryreturn:
self.ids.identi_tag.children[0].text = 'Draft'
src_mng_obj = state.kivyapp.root.children[2].children[0].ids
src_mng_obj.draft_cnt.badge_text = state.draft_count
self.set_mdList()
@ -2276,12 +2283,10 @@ class Draft(Screen):
def delete_draft(self, data_index, instance, *args):
"""Delete draft message permanently"""
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str(
data_index))
sqlExecute("DELETE FROM sent WHERE ackdata = ?;", data_index)
try:
msg_count_objs = (
self.parent.parent.parent.parent.parent.parent.children[
2].children[0].ids)
self.parent.parent.parent.parent.parent.children[2].children[0].ids)
except Exception:
msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[
2].children[0].ids
@ -2291,6 +2296,8 @@ class Draft(Screen):
msg_count_objs.draft_cnt.badge_text = str(
int(state.draft_count) - 1)
state.draft_count = str(int(state.draft_count) - 1)
if int(state.draft_count) <= 0:
self.ids.identi_tag.children[0].text = ''
self.ids.ml.remove_widget(instance.parent.parent)
toast('Deleted')
@ -2305,7 +2312,9 @@ class Draft(Screen):
encoding = 3
sendMessageToPeople = True
if sendMessageToPeople:
from addresses import decodeAddress
streamNumber, ripe = decodeAddress(toAddress)[2:]
from addresses import addBMIfNotPresent
toAddress = addBMIfNotPresent(toAddress)
stealthLevel = BMConfigParser().safeGetInt(
'bitmessagesettings', 'ackstealthlevel')
@ -2328,9 +2337,7 @@ class Draft(Screen):
0,
'draft',
encoding,
int(BMConfigParser().safeGet(
'bitmessagesettings', 'ttl')))
int(BMConfigParser().safeGet('bitmessagesettings', 'ttl')))
state.msg_counter_objs = src_object.children[2].children[0].ids
state.draft_count = str(int(state.draft_count) + 1)
src_object.ids.sc16.clear_widgets()
@ -2343,7 +2350,7 @@ class CustomSpinner(Spinner):
"""This class is used for setting spinner size"""
def __init__(self, *args, **kwargs):
"""Setting size of spinner"""
"""Method used for setting size of spinner"""
super(CustomSpinner, self).__init__(*args, **kwargs)
self.dropdown_cls.max_height = Window.size[1] / 3
@ -2356,7 +2363,7 @@ class Allmails(Screen):
account = StringProperty()
def __init__(self, *args, **kwargs):
"""Method Parsing the address."""
"""Method Parsing the address"""
super(Allmails, self).__init__(*args, **kwargs)
if state.association == '':
if BMConfigParser().addresses():
@ -2369,10 +2376,12 @@ class Allmails(Screen):
print(dt)
def loadMessagelist(self):
"""Load Inbox, Sent anf Draft list of messages."""
"""Load Inbox, Sent anf Draft list of messages"""
self.account = state.association
self.ids.identi_tag.children[0].text = ''
self.allMessageQuery(0, 20)
if self.all_mails:
self.ids.identi_tag.children[0].text = 'All Mails'
state.kivyapp.get_inbox_count()
state.kivyapp.get_sent_count()
state.all_count = str(
@ -2502,6 +2511,8 @@ class Allmails(Screen):
int(state.all_count) - 1)
state.trash_count = str(int(state.trash_count) + 1)
state.all_count = str(int(state.all_count) - 1)
if int(state.all_count) <= 0:
self.ids.identi_tag.children[0].text = ''
nav_lay_obj.sc5.clear_widgets()
nav_lay_obj.sc5.add_widget(Trash())
nav_lay_obj.sc17.remove_widget(instance.parent.parent)
@ -2547,16 +2558,19 @@ def avatarImageFirstLetter(letter_string):
class Starred(Screen):
"""Starred Screen show widgets of page"""
pass
class Archieve(Screen):
"""Archieve Screen show widgets of page"""
pass
class Spam(Screen):
"""Spam Screen show widgets of page"""
pass
@ -2571,3 +2585,8 @@ class LoadingPopup(Popup):
def dismiss_popup(self, dt):
"""Dismiss popups"""
self.dismiss()
class AddressDropdown(OneLineIconListItem):
"""AddressDropdown showns all the addresses"""
pass

View File

@ -1,12 +1,15 @@
"""
Ui Singnaler for kivy interface
"""
from threading import Thread
import state
import queues
import state
from semaphores import kivyuisignaler
from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
class UIkivySignaler(Thread):
"""Kivy ui signaler"""
def run(self):
kivyuisignaler.acquire()
@ -14,13 +17,12 @@ class UIkivySignaler(Thread):
try:
command, data = queues.UISignalQueue.get()
if command == 'writeNewAddressToTable':
label, address, streamNumber = data
address = data[1]
state.kivyapp.variable_1.append(address)
# elif command == 'rerenderAddressBook':
# state.kivyapp.obj_1.refreshs()
# Need to discuss this
elif command == 'updateSentItemStatusByAckdata':
state.kivyapp.status_dispatching(data)
except Exception as e:
print(e)

View File

@ -9,7 +9,6 @@ The PyBitmessage startup script
# Right now, PyBitmessage only support connecting to stream 1. It doesn't
# yet contain logic to expand into further streams.
import os
import sys
import ctypes
@ -30,7 +29,8 @@ import state
import shutdown
from bmconfigparser import BMConfigParser
from debug import logger # this should go before any threads
# this should go before any threads
from debug import logger
from helper_startup import (
isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections,
start_proxyconfig
@ -198,7 +198,8 @@ class Main(object):
if os.path.isfile(os.path.join(
state.appdata, 'unittest.lock')):
daemon = True
state.enableGUI = False # run without a UI
# run without a UI
state.enableGUI = False
# Fallback: in case when no api command was issued
state.last_api_response = time.time()
# Apply special settings
@ -214,7 +215,8 @@ class Main(object):
)
if daemon:
state.enableGUI = False # run without a UI
# run without a UI
state.enableGUI = False
# is the application already running? If yes then exit.
if state.enableGUI and not state.curses and not state.kivy and not depends.check_pyqt():
@ -245,11 +247,10 @@ class Main(object):
set_thread_name("PyBitmessage")
state.dandelion = config.safeGetInt('network', 'dandelion')
state.dandelion = config.safeGet('network', 'dandelion')
# dandelion requires outbound connections, without them,
# stem objects will get stuck forever
if state.dandelion and not config.safeGetBoolean(
'bitmessagesettings', 'sendoutgoingconnections'):
if state.dandelion and not (config.safeGet('bitmessagesettings', 'sendoutgoingconnections') == 'True'):
state.dandelion = 0
if state.testmode or config.safeGetBoolean(
@ -261,7 +262,6 @@ class Main(object):
readKnownNodes()
# Not needed if objproc is disabled
if state.enableObjProc:
@ -320,7 +320,8 @@ class Main(object):
shared.reloadBroadcastSendersForWhichImWatching()
# API is also objproc dependent
if config.safeGetBoolean('bitmessagesettings', 'apienabled'):
import api # pylint: disable=relative-import
# pylint: disable=relative-import
import api
singleAPIThread = api.singleAPI()
# close the main program even if there are threads left
singleAPIThread.daemon = True
@ -415,7 +416,8 @@ class Main(object):
pass
else:
parentPid = os.getpid()
shared.thisapp.lock() # relock
# relock
shared.thisapp.lock()
os.umask(0)
try:
@ -430,14 +432,16 @@ class Main(object):
# wait until child ready
while True:
time.sleep(1)
os._exit(0) # pylint: disable=protected-access
# pylint: disable=protected-access
os._exit(0)
except AttributeError:
# fork not implemented
pass
else:
shared.thisapp.lock() # relock
shared.thisapp.lockPid = None # indicate we're the final child
# relock
shared.thisapp.lock()
# indicate we're the final child
shared.thisapp.lockPid = None
sys.stdout.flush()
sys.stderr.flush()
if not sys.platform.startswith('win'):
@ -460,7 +464,6 @@ class Main(object):
# signal.signal(signal.SIGINT, signal.SIG_DFL)
@staticmethod
def usage():
"""Displaying the usages"""
print('Usage: ' + sys.argv[0] + ' [OPTIONS]')

View File

@ -1,7 +1,7 @@
"""
BMConfigParser class definition and default configuration settings
"""
# pylint: disable=no-self-use, arguments-differ
import configparser
import shutil
import os
@ -45,7 +45,7 @@ BMConfigDefaults = {
class BMConfigParser(configparser.ConfigParser):
"""Singleton class inherited from ConfigParsedadfeConfigParser
with additional methods specific to bitmessage config."""
# pylint: disable=too-many-ancestors
_temp = {}
def set(self, section, option, value=None):
@ -56,7 +56,8 @@ class BMConfigParser(configparser.ConfigParser):
raise ValueError("Invalid value %s" % value)
return configparser.ConfigParser.set(self, section, option, value)
def get(self, section, option, raw=False, variables=None): # pylint: disable=arguments-differ
def get(self, section, option, raw=False, variables=None):
# pylint: disable=unused-argument
try:
if section == "bitmessagesettings" and option == "timeformat":
return configparser.ConfigParser.get(
@ -84,8 +85,8 @@ class BMConfigParser(configparser.ConfigParser):
self._temp[section] = {option: value}
def safeGetBoolean(self, section, field):
"""Return value as boolean, False on exceptions"""
config = configparser.ConfigParser()
try:
# Used in the python2.7
# return self.getboolean(section, field)
@ -96,6 +97,8 @@ class BMConfigParser(configparser.ConfigParser):
return False
def safeGetInt(self, section, field, default=0):
"""Return value as integer, default on exceptions,
0 if default missing"""
config = configparser.ConfigParser()
try:
@ -116,12 +119,14 @@ class BMConfigParser(configparser.ConfigParser):
return default
def items(self, section, raw=False, variables=None):
"""Return section variables as parent,
but override the "raw" argument to always True"""
return configparser.ConfigParser.items(self, section, True, variables)
def addresses(self):
"""Return a list of local bitmessage addresses (from section labels)"""
return [x for x in BMConfigParser().sections() if x.startswith('BM-')]
def read(self, filenames):
configparser.ConfigParser.read(self, filenames)
for section in self.sections():
@ -167,7 +172,8 @@ class BMConfigParser(configparser.ConfigParser):
def validate(self, section, option, value):
"""Input validator interface (using factory pattern)"""
try:
return getattr(self, 'validate_{}_{}'.format(section, option))(value)
return getattr(self, 'validate_{}_{}'.format(
section, option))(value)
except AttributeError:
return True

View File

@ -13,8 +13,14 @@ DATA_FILES = [
('bitmsghash', ['bitmsghash/bitmsghash.cl', 'bitmsghash/bitmsghash.so']),
('translations', glob('translations/*.qm')),
('ui', glob('bitmessageqt/*.ui')),
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')),
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')),
('translations', glob(
str(
QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')),
('translations', glob(
str(
QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')),
]
setup(

View File

@ -20,7 +20,6 @@ from network.threads import StoppableThread
class addressGenerator(StoppableThread):
"""A thread for creating addresses"""
name = "addressGenerator"
def stopThread(self):
@ -35,7 +34,8 @@ class addressGenerator(StoppableThread):
Process the requests for addresses generation
from `.queues.addressGeneratorQueue`
"""
# pylint: disable=too-many-locals, too-many-branches, protected-access, too-many-statements
# pylint: disable=too-many-locals, too-many-branches
# pylint: disable=protected-access, too-many-statements
while state.shutdown == 0:
queueValue = queues.addressGeneratorQueue.get()
nonceTrialsPerByte = 0
@ -206,9 +206,14 @@ class addressGenerator(StoppableThread):
queues.workerQueue.put((
'sendOutOrStoreMyV4Pubkey', address))
elif command == 'createDeterministicAddresses' \
or command == 'getDeterministicAddress' \
or command == 'createChan' or command == 'joinChan':
# elif command == 'createDeterministicAddresses' \
# or command == 'getDeterministicAddress' \
# or command == 'createChan' or command == 'joinChan':
elif command in (
'createDeterministicAddresses',
'getDeterministicAddress',
'createChan',
'joinChan'):
if not deterministicPassphrase:
self.logger.warning(
'You are creating deterministic'
@ -333,8 +338,8 @@ class addressGenerator(StoppableThread):
BMConfigParser().set(address, 'label', label)
BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().set(address, 'decoy', 'false')
if command == 'joinChan' \
or command == 'createChan':
# if command == 'joinChan' or command == 'createChan':
if command in ('joinChan', 'createChan'):
BMConfigParser().set(address, 'chan', 'true')
BMConfigParser().set(
address, 'noncetrialsperbyte',
@ -385,8 +390,12 @@ class addressGenerator(StoppableThread):
address)
# Done generating addresses.
if command == 'createDeterministicAddresses' \
or command == 'joinChan' or command == 'createChan':
# if command == 'createDeterministicAddresses' \
# or command == 'joinChan' or command == 'createChan':
if command in (
'createDeterministicAddresses',
'joinChan',
'createChan'):
queues.apiAddressGeneratorReturnQueue.put(
listOfNewAddressesToSendOutThroughTheAPI)
elif command == 'getDeterministicAddress':

View File

@ -34,7 +34,8 @@ import tr
from fallback import RIPEMD160Hash
import l10n
# pylint: disable=too-many-locals, too-many-return-statements, too-many-branches, too-many-statements
# pylint: disable=too-many-locals, too-many-return-statements
# pylint: disable=too-many-branches, too-many-statements
logger = logging.getLogger('default')
@ -140,7 +141,7 @@ class objectProcessor(threading.Thread):
# bypass nonce and time, retain object type/version/stream + body
readPosition = 16
if data[readPosition:] in shared.ackdataForWhichImWatching:
if bytes(data[readPosition:]) in shared.ackdataForWhichImWatching:
logger.info('This object is an acknowledgement bound for me.')
del shared.ackdataForWhichImWatching[data[readPosition:]]
sqlExecute(
@ -152,9 +153,8 @@ class objectProcessor(threading.Thread):
(data[readPosition:],
tr._translate(
"MainWindow",
"Acknowledgement of the message received %1"
).arg(l10n.formatTimestamp()))
))
"Acknowledgement of the message received %1").arg(
l10n.formatTimestamp()))))
else:
logger.debug('This object is not an acknowledgement bound for me.')
@ -221,7 +221,7 @@ class objectProcessor(threading.Thread):
'the hash requested in this getpubkey request is: %s',
hexlify(requestedHash))
# if this address hash is one of mine
if requestedHash in shared.myAddressesByHash:
if bytes(requestedHash) in shared.myAddressesByHash:
myAddress = shared.myAddressesByHash[requestedHash]
elif requestedAddressVersionNumber >= 4:
requestedTag = data[readPosition:readPosition + 32]
@ -233,7 +233,7 @@ class objectProcessor(threading.Thread):
logger.debug(
'the tag requested in this getpubkey request is: %s',
hexlify(requestedTag))
if requestedTag in shared.myAddressesByTag:
if bytes(requestedTag) in shared.myAddressesByTag:
myAddress = shared.myAddressesByTag[requestedTag]
if myAddress == '':
@ -328,7 +328,7 @@ class objectProcessor(threading.Thread):
dataToStore = data[20:readPosition]
sha = hashlib.new('sha512')
sha.update(
'\x04' + publicSigningKey + '\x04' + publicEncryptionKey)
'\x04'.encode() + publicSigningKey + '\x04'.encode() + publicEncryptionKey)
ripe = RIPEMD160Hash(sha.digest()).digest()
if logger.isEnabledFor(logging.DEBUG):
@ -367,9 +367,9 @@ class objectProcessor(threading.Thread):
' Sanity check failed.')
return
readPosition += 4
publicSigningKey = '\x04' + data[readPosition:readPosition + 64]
publicSigningKey = ('\x04').encode() + data[readPosition:readPosition + 64]
readPosition += 64
publicEncryptionKey = '\x04' + data[readPosition:readPosition + 64]
publicEncryptionKey = ('\x04').encode() + data[readPosition:readPosition + 64]
readPosition += 64
_, specifiedNonceTrialsPerByteLength = decodeVarint(
data[readPosition:readPosition + 10])
@ -433,7 +433,7 @@ class objectProcessor(threading.Thread):
return
tag = data[readPosition:readPosition + 32]
if tag not in state.neededPubkeys:
if tag not in bytes(state.neededPubkeys):
logger.info(
'We don\'t need this v4 pubkey. We didn\'t ask for it.')
return
@ -645,7 +645,8 @@ class objectProcessor(threading.Thread):
if decodeAddress(toAddress)[1] >= 3 \
and not BMConfigParser().safeGetBoolean(toAddress, 'chan'):
# If I'm not friendly with this person:
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress):
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(
fromAddress):
requiredNonceTrialsPerByte = BMConfigParser().getint(
toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = BMConfigParser().getint(
@ -865,7 +866,7 @@ class objectProcessor(threading.Thread):
elif broadcastVersion == 5:
embeddedTag = data[readPosition:readPosition + 32]
readPosition += 32
if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
if bytes(embeddedTag) not in shared.MyECSubscriptionCryptorObjects:
logger.debug('We\'re not interested in this broadcast.')
return
# We are interested in this broadcast because of its tag.

View File

@ -1,24 +0,0 @@
import queue as Queue
import threading
import time
class ObjectProcessorQueue(Queue.Queue):
maxSize = 32000000
def __init__(self):
Queue.Queue.__init__(self)
self.sizeLock = threading.Lock()
self.curSize = 0 # in Bytes. We maintain this to prevent nodes from flooing us with objects which take up too much memory. If this gets too big we'll sleep before asking for further objects.
def put(self, item, block = True, timeout = None):
while self.curSize >= self.maxSize:
time.sleep(1)
with self.sizeLock:
self.curSize += len(item[1])
Queue.Queue.put(self, item, block, timeout)
def get(self, block = True, timeout = None):
item = Queue.Queue.get(self, block, timeout)
with self.sizeLock:
self.curSize -= len(item[1])
return item

View File

@ -35,6 +35,7 @@ from inventory import Inventory
from network.connectionpool import BMConnectionPool
from network.threads import StoppableThread
class singleCleaner(StoppableThread):
"""The singleCleaner thread class"""
name = "singleCleaner"
@ -200,6 +201,10 @@ def deleteTrashMsgPermonantly():
"""This method is used to delete old messages"""
ndays_before_time = datetime.now() - timedelta(days=30)
old_messages = time.mktime(ndays_before_time.timetuple())
sqlExecute("delete from sent where folder = 'trash' and lastactiontime <= ?;", int(old_messages))
sqlExecute("delete from inbox where folder = 'trash' and received <= ?;", int(old_messages))
sqlExecute(
"delete from sent where folder = 'trash' and lastactiontime <= ?;",
int(old_messages))
sqlExecute(
"delete from inbox where folder = 'trash' and received <= ?;",
int(old_messages))
return

View File

@ -23,7 +23,8 @@ import queues
import shared
import state
import tr
from addresses import calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint
from addresses import (
calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint)
from bmconfigparser import BMConfigParser
from helper_sql import sqlExecute, sqlQuery
from inventory import Inventory

View File

@ -3,7 +3,6 @@ src/class_smtpDeliver.py
========================
"""
# pylint: disable=unused-variable
import smtplib
import urlparse
from email.header import Header
@ -24,7 +23,8 @@ class smtpDeliver(StoppableThread):
def stopThread(self):
try:
queues.UISignallerQueue.put(("stopThread", "data")) # pylint: disable=no-member
# pylint: disable=no-member
queues.UISignallerQueue.put(("stopThread", "data"))
except:
pass
super(smtpDeliver, self).stopThread()
@ -50,23 +50,27 @@ class smtpDeliver(StoppableThread):
ackData, message = data
elif command == 'displayNewInboxMessage':
inventoryHash, toAddress, fromAddress, subject, body = data
dest = BMConfigParser().safeGet("bitmessagesettings", "smtpdeliver", '')
dest = BMConfigParser().safeGet(
"bitmessagesettings", "smtpdeliver", '')
if dest == '':
continue
try:
# pylint: disable=deprecated-lambda
u = urlparse.urlparse(dest)
to = urlparse.parse_qs(u.query)['to']
client = smtplib.SMTP(u.hostname, u.port)
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = fromAddress + '@' + SMTPDOMAIN
toLabel = map( # pylint: disable=deprecated-lambda
toLabel = map(
lambda y: BMConfigParser().safeGet(y, "label"),
filter( # pylint: disable=deprecated-lambda
filter(
lambda x: x == toAddress, BMConfigParser().addresses())
)
if toLabel:
msg['To'] = "\"%s\" <%s>" % (Header(toLabel[0], 'utf-8'), toAddress + '@' + SMTPDOMAIN)
msg['To'] = "\"%s\" <%s>" % (
Header(toLabel[0], 'utf-8'),
toAddress + '@' + SMTPDOMAIN)
else:
msg['To'] = toAddress + '@' + SMTPDOMAIN
client.ehlo()
@ -80,7 +84,8 @@ class smtpDeliver(StoppableThread):
except:
self.logger.error('smtp delivery error', exc_info=True)
elif command == 'displayNewSentMessage':
toAddress, fromLabel, fromAddress, subject, message, ackdata = data
toAddress, fromLabel, fromAddress, subject, message, ackdata = \
data
elif command == 'updateNetworkStatusTab':
pass
elif command == 'updateNumberOfMessagesProcessed':

View File

@ -114,8 +114,9 @@ class smtpServerPyBitmessage(smtpd.SMTPServer):
return ret
def process_message(self, peer, mailfrom, rcpttos, data): # pylint: disable=too-many-locals, too-many-branches
def process_message(self, peer, mailfrom, rcpttos, data):
"""Process an email"""
# pylint: disable=too-many-locals, too-many-branches
# print 'Receiving message from:', peer
p = re.compile(".*<([^>]+)>")
if not hasattr(self.channel, "auth") or not self.channel.auth:

View File

@ -214,7 +214,8 @@ class sqlThread(threading.Thread):
parameters = ''
self.cur.execute(item, parameters)
currentVersion = int(self.cur.fetchall()[0][0])
if currentVersion == 1 or currentVersion == 3:
# if currentVersion == 1 or currentVersion == 3:
if currentVersion in (1, 3):
logger.debug(
'In messages.dat database, adding tag field to'
' the inventory table.')
@ -572,23 +573,10 @@ class sqlThread(threading.Thread):
rowcount = 0
# print 'item', item
# print 'parameters', parameters
# print('++++454++++++++++++++++++++++++')
# print ('parameters')
# print (parameters)
# print ('+++++++++++++++++++++++++++++')
try:
if 'sent' == parameters[1] and 'B' in parameters[0]:
item = '''SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent WHERE fromaddress = ? ORDER BY lastactiontime DESC '''
parameters = (parameters[0],)
except (IndexError,TypeError) as e:
pass
try:
self.cur.execute(item, parameters)
rowcount = self.cur.rowcount
except Exception as err:
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
print('inside the expectation')
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
if str(err) == 'database or disk is full':
logger.fatal(
'(while cur.execute) Alert: Your disk or data storage volume is full.'

View File

@ -231,12 +231,13 @@ def check_sqlite():
conn.close()
def check_openssl(): # pylint: disable=too-many-branches, too-many-return-statements
def check_openssl():
"""Do openssl dependency check.
Here we are checking for openssl with its all dependent libraries
and version checking.
"""
# pylint: disable=too-many-branches, too-many-return-statements
# pylint: disable=protected-access, redefined-outer-name
ctypes = try_import('ctypes')
if not ctypes:
@ -365,6 +366,7 @@ def check_pyqt():
Here we are checking for PyQt4 with its version, as for it require
PyQt 4.8 or later.
"""
QtCore = try_import(
'PyQt4.QtCore', 'PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.')

View File

@ -53,3 +53,4 @@ def calculateTestnetAddressFromPubkey(pubkey):
numberOfZeroBytesOnBinaryBitcoinAddress += 1
binaryBitcoinAddress = binaryBitcoinAddress[1:]
base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58)
return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded

View File

@ -7,6 +7,7 @@ try:
haveQt = True
except ImportError:
haveQt = False
# pylint: disable=too-many-arguments
def search_translate(context, text):
@ -18,7 +19,7 @@ def search_translate(context, text):
def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False):
"""Perform a search in mailbox tables"""
# pylint: disable=too-many-arguments, too-many-branches
# pylint: disable=too-many-branches
if what is not None and what != "":
what = "%" + what + "%"
if where == search_translate("MainWindow", "To"):
@ -75,7 +76,6 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w
def check_match(toAddress, fromAddress, subject, message, where=None, what=None):
"""Check if a single message matches a filter (used when new messages are added to messagelists)"""
# pylint: disable=too-many-arguments
if what is not None and what != "":
if where in (search_translate("MainWindow", "To"), search_translate("MainWindow", "All")):
if what.lower() not in toAddress.lower():

View File

@ -1,8 +1,8 @@
"""
Insert values into sent table
"""
from helper_sql import sqlExecute
from helper_sql import *
def insert(t):
"""Perform an insert into the `sent` table"""

View File

@ -101,7 +101,7 @@ def sqlStoredProcedure(procName):
sqlLock.release()
class SqlBulkExecute(object):
class SqlBulkExecute(object): # pylint: disable=no-init
"""This is used when you have to execute the same statement in a cycle."""
def __enter__(self):

View File

@ -3,9 +3,7 @@ Startup operations.
"""
# pylint: disable=too-many-branches,too-many-statements
# import configparser
import logging
import os
import platform
import sys
@ -30,6 +28,7 @@ logger = logging.getLogger('default')
# the config files to stay in the application data folder.
StoreConfigFilesInSameDirectoryAsProgramByDefault = False
def loadConfig():
"""Load the config"""
config = BMConfigParser()
@ -127,7 +126,6 @@ def loadConfig():
updateConfig()
def updateConfig():
"""Save the config"""
config = BMConfigParser()

View File

@ -1,8 +1,8 @@
"""The Inventory singleton"""
# TODO make this dynamic, and watch out for frozen, like with messagetypes
import storage.sqlite
import storage.filesystem
import storage.sqlite
from bmconfigparser import BMConfigParser
from singleton import Singleton

View File

@ -1,13 +1,13 @@
from .addrthread import AddrThread
from .announcethread import AnnounceThread
from .connectionpool import BMConnectionPool
from .dandelion import Dandelion
from .downloadthread import DownloadThread
from .invthread import InvThread
from .networkthread import BMNetworkThread
from .receivequeuethread import ReceiveQueueThread
from .threads import StoppableThread
from .uploadthread import UploadThread
from network.addrthread import AddrThread
from network.announcethread import AnnounceThread
from network.connectionpool import BMConnectionPool
from network.dandelion import Dandelion
from network.downloadthread import DownloadThread
from network.invthread import InvThread
from network.networkthread import BMNetworkThread
from network.receivequeuethread import ReceiveQueueThread
from network.threads import StoppableThread
from network.uploadthread import UploadThread
__all__ = [

View File

@ -1,4 +1,3 @@
# import queue as Queue
"""
Announce addresses as they are received from other hosts
"""

View File

@ -3,7 +3,6 @@ src/network/advanceddispatcher.py
=================================
"""
# pylint: disable=attribute-defined-outside-init
# import pdb;pdb.set_trace()
import socket
import threading
import time
@ -32,7 +31,7 @@ class AdvancedDispatcher(asyncore.dispatcher):
# python 2 below condition is used
# if not hasattr(self, '_map'):
# python 3 below condition is used
if not '_map' in dir(self):
if '_map' not in dir(self):
asyncore.dispatcher.__init__(self, sock)
self.read_buf = bytearray()
self.write_buf = bytearray()

View File

@ -11,7 +11,7 @@ from bmconfigparser import BMConfigParser
from network.assemble import assemble_addr
from network.connectionpool import BMConnectionPool
from network.udp import UDPSocket
from .node import Peer
from network.node import Peer
from network.threads import StoppableThread
@ -38,11 +38,9 @@ class AnnounceThread(StoppableThread):
for stream in state.streamsInWhichIAmParticipating:
addr = (
stream,
# state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))),
# int(time.time()))
# connection.append_write_buf(BMProto.assembleAddr([addr]))
Peer(
'127.0.0.1',
BMConfigParser().safeGetInt('bitmessagesettings', 'port')),

View File

@ -13,7 +13,7 @@ from protocol import CreatePacket, encodeHost
def assemble_addr(peerList):
"""Create address command"""
if isinstance(peerList, Peer):
peerList = (peerList)
peerList = [peerList]
if not peerList:
return b''
retval = b''
@ -22,7 +22,7 @@ def assemble_addr(peerList):
len(peerList[i:i + MAX_ADDR_COUNT]))
for stream, peer, timestamp in peerList[i:i + MAX_ADDR_COUNT]:
payload += struct.pack(
'>Q', timestamp) # 64-bit time
'>Q', int(timestamp)) # 64-bit time
payload += struct.pack('>I', stream)
payload += struct.pack(
'>q', 1) # service bit flags offered by this node

View File

@ -102,7 +102,9 @@ def _strerror(err):
return os.strerror(err)
except (ValueError, OverflowError, NameError):
if err in errorcode:
ret18 ("Unknown error {}".format(err))
return errorcode[err]
return "Unknown error %s" % err
# ret18 ("Unknown error {}".format(err))
class ExitNow(Exception):
@ -477,7 +479,7 @@ def kqueue_poller(timeout=0.0, map=None):
current_thread().stop.wait(timeout)
def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None):
def loop(timeout=30.0, _=False, map=None, count=None, poller=None):
"""Poll in a loop, until count or timeout is reached"""
# pylint: disable=redefined-builtin
@ -518,7 +520,7 @@ def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None):
count = count - 1
class dispatcher:
class dispatcher(object):
"""Dispatcher for socket objects"""
# pylint: disable=too-many-public-methods,too-many-instance-attributes,old-style-class

View File

@ -32,7 +32,7 @@ from network.bmobject import (
BMObjectInvalidError, BMObjectAlreadyHaveError)
from network.proxy import ProxyError
from network.objectracker import missingObjects, ObjectTracker
from .node import Node, Peer
from network.node import Node, Peer
from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue
from network.randomtrackingdict import RandomTrackingDict
@ -52,6 +52,7 @@ count = 0
logger = logging.getLogger('default')
class BMProtoError(ProxyError):
"""A Bitmessage Protocol Base Error"""
errorCodes = ("Protocol error")
@ -94,12 +95,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.object = None
def state_bm_header(self):
"""Process incoming header"""
self.magic, self.command, self.payloadLength, self.checksum = \
protocol.Header.unpack(self.read_buf[:protocol.Header.size])
# its shoule be in string
self.command = self.command.rstrip('\x00'.encode('utf-8'))
# pylint: disable=global-statement
global count, addr_version, addr_count, addr_verack
count += 1
if self.command == 'verack'.encode():
@ -132,7 +133,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
length=protocol.Header.size, expectBytes=self.payloadLength)
return True
def state_bm_command(self): # pylint: disable=too-many-branches
def state_bm_command(self): # pylint: disable=too-many-branches, too-many-statements
"""Process incoming command"""
self.payload = self.read_buf[:self.payloadLength]
if self.checksum != hashlib.sha512(self.payload).digest()[0:4]:
@ -171,9 +172,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
except BMObjectAlreadyHaveError:
logger.debug(
'%(host)s:%(port)i already got object, skipping',
self.destination._asdict())
self.destinaestion._asdict())
except struct.error:
logger.debug('decoding error, skipping')
except ValueError:
pass
elif self.socket.type == socket.SOCK_DGRAM:
# broken read, ignore
pass
@ -205,9 +208,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"""Decode node details from the payload"""
# protocol.checkIPAddress()
services, host, port = self.decode_payload_content("Q16sH")
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape'):
host = socket.inet_ntop(socket.AF_INET, host[12:16])
elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43':
elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43'.encode('raw_unicode_escape'):
# Onion, based on BMD/bitcoind
host = base64.b32encode(host[6:]).lower() + ".onion"
else:
@ -346,8 +349,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
def bm_command_error(self):
"""Decode an error message and log it"""
fatalStatus, banTime, inventoryVector, errorText = \
self.decode_payload_content("vvlsls")
err_values = self.decode_payload_content("vvlsls")
fatalStatus = err_values[0]
# banTime = err_values[1]
# inventoryVector = err_values[2]
errorText = err_values[3]
logger.error(
'%s:%i error: %i, %s', self.destination.host,
self.destination.port, fatalStatus, errorText)
@ -381,7 +387,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
if dandelion and not state.dandelion:
return True
for i in map(str, items):
for i in map(bytes, items):
if i in Inventory() and not Dandelion().hasHash(i):
continue
if dandelion and not Dandelion().hasHash(i):
@ -434,7 +440,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
try:
self.object.checkObjectByType()
objectProcessorQueue.put((
self.object.objectType, buffer(self.object.data)))
self.object.objectType, memoryview(self.object.data)))
except BMObjectInvalidError:
BMProto.stopDownloadingObject(self.object.inventoryHash, True)
else:
@ -445,12 +451,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash):
Dandelion().removeHash(self.object.inventoryHash, "cycle detection")
Inventory()[self.object.inventoryHash] = (
[self.object.inventoryHash] = (
self.object.objectType, self.object.streamNumber,
buffer(self.payload[objectOffset:]), self.object.expiresTime,
buffer(self.object.tag)
memoryview(self.payload[objectOffset:]), self.object.expiresTime,
memoryview(self.object.tag)
)
Inventory()[self.object.inventoryHash]
self.handleReceivedObject(
self.object.streamNumber, self.object.inventoryHash)
invQueue.put((
@ -467,7 +473,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"""Incoming addresses, process them"""
addresses = self._decode_addr() # pylint: disable=redefined-outer-name
for i in addresses:
seenTime, stream, services, ip, port = i
seenTime, stream, _, ip, port = i
decodedIP = protocol.checkIPAddress(ip)
if stream not in state.streamsInWhichIAmParticipating:
continue
@ -533,6 +539,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"tls_init" if self.isSSL else "connection_fully_established",
length=self.payloadLength, expectBytes=0)
return False
def bm_command_version(self):
# print('inside the bmproto ')
"""
@ -566,7 +573,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
logger.debug(
'%(host)s:%(port)i sending version',
self.destination._asdict())
if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL)):
if self.services & protocol.NODE_SSL == protocol.NODE_SSL:
# self.isSSL = True
pass
if not self.verackReceived:
@ -660,10 +667,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
"Closed connection to %s because I'm connected to myself.",
self.destination)
return False
return True
@staticmethod
def stopDownloadingObject(hashId, forwardAnyway=False):
"""Stop downloading an object"""

View File

@ -17,11 +17,11 @@ from bmconfigparser import BMConfigParser
from network.connectionchooser import chooseConnection
from network.proxy import Proxy
from .node import Peer
from singleton import Singleton
from network.tcp import (
TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap)
from network.udp import UDPSocket
from singleton import Singleton
from .node import Peer
logger = logging.getLogger('default')
@ -430,14 +430,13 @@ class BMConnectionPool(object):
# list(self.udpSockets.values())
# ):
for i in (
# [inboundConnections for inboundConnections in self.inboundConnections.values()] +
# [outboundConnections for outboundConnections in self.outboundConnections.values()] +
# [listeningSockets for listeningSockets in self.listeningSockets.values()] +
# [udpSockets for udpSockets in self.udpSockets.values()]
self.connections()
+ [listeningSockets for listeningSockets in self.listeningSockets.values()] + [udpSockets for udpSockets in self.udpSockets.values()]
self.connections() +
[listeningSockets for listeningSockets in self.listeningSockets.values()] +
[udpSockets for udpSockets in self.udpSockets.values()]
):
if not (i.accepting or i.connecting or i.connected):
reaper.append(i)

View File

@ -28,7 +28,7 @@ logger = logging.getLogger('default')
@Singleton
class Dandelion(): # pylint: disable=old-style-class
class Dandelion(object):
"""Dandelion class for tracking stem/fluff stages."""
def __init__(self):
# currently assignable child stems

View File

@ -44,7 +44,8 @@ class DownloadThread(StoppableThread):
# Choose downloading peers randomly
# connections = [
# x for x in
# list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values())
# list(BMConnectionPool().inboundConnections.values()) +
# list(BMConnectionPool().outboundConnections.values())
# if x.fullyEstablished]
connections = BMConnectionPool().establishedConnections()

View File

@ -1,3 +1,4 @@
# pylint: disable=redefined-outer-name, too-many-ancestors, missing-docstring
import socket
from advanceddispatcher import AdvancedDispatcher
@ -12,7 +13,7 @@ class HttpError(ProxyError):
class HttpConnection(AdvancedDispatcher):
def __init__(self, host, path="/"): # pylint: disable=redefined-outer-name
def __init__(self, host, path="/"):
AdvancedDispatcher.__init__(self)
self.path = path
self.destination = (host, 80)
@ -38,7 +39,7 @@ class HttpConnection(AdvancedDispatcher):
class Socks5HttpConnection(Socks5Connection, HttpConnection):
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called
self.path = path
Socks5Connection.__init__(self, address=(host, 80))
@ -48,7 +49,7 @@ class Socks5HttpConnection(Socks5Connection, HttpConnection):
class Socks4aHttpConnection(Socks4aConnection, HttpConnection):
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called, redefined-outer-name
def __init__(self, host, path="/"): # pylint: disable=super-init-not-called
Socks4aConnection.__init__(self, address=(host, 80))
self.path = path

View File

@ -1,3 +1,6 @@
"""
src/network/http_old.py
"""
import asyncore
import socket
import time

View File

@ -5,7 +5,7 @@ src/network/httpd.py
import asyncore
import socket
from tls import TLSHandshake
from .tls import TLSHandshake
class HTTPRequestHandler(asyncore.dispatcher):
@ -129,7 +129,7 @@ class HTTPServer(asyncore.dispatcher):
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
sock, _ = pair
# print 'Incoming connection from %s' % repr(addr)
self.connections += 1
# if self.connections % 1000 == 0:
@ -148,7 +148,7 @@ class HTTPSServer(HTTPServer):
def handle_accept(self):
pair = self.accept()
if pair is not None:
sock, addr = pair
sock, _ = pair
# print 'Incoming connection from %s' % repr(addr)
self.connections += 1
# if self.connections % 1000 == 0:

View File

@ -1,8 +1,8 @@
# pylint: disable=missing-docstring
import asyncore
from http import HTTPClient
from tls import TLSHandshake
from .http import HTTPClient
from .tls import TLSHandshake
"""
self.sslSock = ssl.wrap_socket(
self.sock,
@ -17,6 +17,7 @@ self.sslSock = ssl.wrap_socket(
class HTTPSClient(HTTPClient, TLSHandshake):
def __init__(self, host, path):
# pylint: disable=non-parent-init-called
if not hasattr(self, '_map'):
asyncore.dispatcher.__init__(self)
self.tlsDone = False

View File

@ -90,7 +90,7 @@ class TCPConnection(BMProto, TLSDispatcher):
ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called
self.bm_proto_reset()
# print('--------------tcp------------------')
from network import stats
# from network import stats
self.set_state("bm_header", expectBytes=protocol.Header.size)
def antiIntersectionDelay(self, initial=False):

View File

@ -1,7 +1,6 @@
"""
SSL/TLS negotiation.
"""
import logging
import os
import socket

View File

@ -294,7 +294,7 @@ def init():
global bitmsglib, bmpow
openclpow.initCL()
if "win32" == sys.platform:
if sys.platform == "win32":
if ctypes.sizeof(ctypes.c_voidp) == 4:
bitmsglib = 'bitmsghash32.dll'
else:
@ -323,7 +323,7 @@ def init():
elif platform == "android":
try:
bso = ctypes.CDLL('libbitmsghash.so')
except Exception as e:
except Exception:
bso = None
else:

View File

@ -185,7 +185,8 @@ def checkIPv4Address(host, hostStandardFormat, private=False):
logger.debug(
'Ignoring IP address in private range: %s', hostStandardFormat)
return hostStandardFormat if private else False
if host[0:2] >= '\xAC\x10'.encode('raw_unicode_escape') and host[0:2] < '\xAC\x20'.encode('raw_unicode_escape'): # 172.16/12
# 172.16/12
if host[0:2] >= '\xAC\x10'.encode('raw_unicode_escape') and host[0:2] < '\xAC\x20'.encode('raw_unicode_escape'):
if not private:
logger.debug(
'Ignoring IP address in private range: %s', hostStandardFormat)
@ -277,14 +278,13 @@ def isProofOfWorkSufficient(
def CreatePacket(command, payload=''):
"""Construct and return a number of bytes from a payload"""
payload = payload if type(payload) == bytes else payload.encode()
payload = payload if type(payload) in [bytes,bytearray] else payload.encode()
payload_length = len(payload)
checksum = hashlib.sha512(payload).digest()[0:4]
byte = bytearray(Header.size + payload_length)
Header.pack_into(byte, 0, 0xE9BEB4D9, command.encode(), payload_length, checksum)
byte[Header.size:] = payload
return byte
return bytes(byte)
def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=False, nodeid=None):
@ -324,10 +324,8 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=
(NODE_DANDELION if state.dandelion else 0)
)
# = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
#python3 need to check
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433)
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape') + pack('>L', 2130706433)
# we have a separate extPort and incoming over clearnet
# or outgoing through clearnet
extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport')
@ -342,7 +340,6 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=
else: # no extport and not incoming over Tor
payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'port')))
if nodeid is not None:
payload += nodeid[0:8]
else:

View File

@ -1,6 +1,5 @@
import queue as Queue
"""Most of the queues used by bitmessage threads are defined here."""
import queue as Queue
import threading
import time

View File

@ -101,6 +101,7 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address):
return True
return False
def decodeWalletImportFormat(WIFstring):
# pylint: disable=inconsistent-return-statements
"""
@ -116,7 +117,7 @@ def decodeWalletImportFormat(WIFstring):
' 6 characters of the PRIVATE key: {}'.format(str(WIFstring)[:6])
)
os._exit(0)
os._exit(0) # pylint: disable=protected-access
if privkey[0:1] == '\x80'.encode()[1:]: # checksum passed
return privkey[1:]

View File

@ -95,7 +95,7 @@ class singleinstance(object):
os.close(self.fd)
else:
fcntl.lockf(self.fp, fcntl.LOCK_UN)
except Exception as e:
except Exception:
pass
return
print("Cleaning up lockfile")

View File

@ -1,43 +1,30 @@
"""
Global runtime variables.
src/state.py
=================================
"""
import collections
neededPubkeys = {}
streamsInWhichIAmParticipating = []
# For UPnP
extPort = None
"""For UPnP"""
# for Tor hidden service
socksIP = None
"""for Tor hidden service"""
appdata = ''
"""holds the location of the application data storage directory"""
# Network protocols availability, initialised below
networkProtocolAvailability = None
appdata = '' # holds the location of the application data storage directory
# Set to 1 by the doCleanShutdown function.
# Used to tell the proof of work worker threads to exit.
shutdown = 0
"""
Set to 1 by the `.shutdown.doCleanShutdown` function.
Used to tell the threads to exit.
"""
# Component control flags - set on startup, do not change during runtime
# The defaults are for standalone GUI (default operating mode)
enableNetwork = True
"""enable network threads"""
enableObjProc = True
"""enable object processing thread"""
enableAPI = True
"""enable API (if configured)"""
enableGUI = True
"""enable GUI (QT or ncurses)"""
enableSTDIO = False
"""enable STDIO threads"""
enableNetwork = True # enable network threads
enableObjProc = True # enable object processing threads
enableAPI = True # enable API (if configured)
enableGUI = True # enable GUI (QT or ncurses)
enableSTDIO = False # enable STDIO threads
curses = False
sqlReady = False
"""set to true by `.threads.sqlThread` when ready for processing"""
sqlReady = False # set to true by sqlTread when ready for processing
maximumNumberOfHalfOpenConnections = 0
invThread = None
addrThread = None
@ -68,8 +55,6 @@ def resetNetworkProtocolAvailability():
resetNetworkProtocolAvailability()
discoveredPeers = {}
dandelion = 0
testmode = False

View File

@ -39,15 +39,20 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors
return True
def __getitem__(self, hash_):
print('----------__getitem__------------------')
if hash_ == 0:
hash_ = bytes()
with self.lock:
try:
if hash_ in self._inventory:
return self._inventory[hash_]
rows = sqlQuery(
'SELECT objecttype, streamnumber, payload, expirestime, tag FROM inventory WHERE hash=?',
sqlite3.Binary(hash_))
if not rows:
raise KeyError(hash_)
pass
# raise KeyError(hash_)
except:
pass
return InventoryItem(*rows[0])
def __setitem__(self, hash_, value):

View File

@ -6,17 +6,17 @@ import os
import state
class translateClass:
class translateClass(object):
"""
This is used so that the translateText function can be used
when we are in daemon mode and not using any QT functions.
"""
# pylint: disable=old-style-class,too-few-public-methods
# pylint: disable=too-few-public-methods
def __init__(self, context, text):
self.context = context
self.text = text
def arg(self, argument): # pylint: disable=unused-argument
def arg(self, _):
"""Replace argument placeholders"""
if '%' in self.text:
return translateClass(self.context, self.text.replace('%', '', 1))

View File

@ -1,8 +1,8 @@
# pylint: disable=too-many-statements,too-many-branches,protected-access,no-self-use
"""
"""
Complete UPnP port forwarding implementation in separate thread.
Reference: http://mattscodecave.com/posts/using-python-and-upnp-to-forward-a-port
"""
# pylint: disable=too-many-statements,too-many-branches,protected-access,no-self-use
import httplib
import socket
@ -19,8 +19,8 @@ import tr
from bmconfigparser import BMConfigParser
from debug import logger
from network.connectionpool import BMConnectionPool
from network.threads import StoppableThread
from network.node import Peer
from network.threads import StoppableThread
def createRequestXML(service, action, arguments=None):
@ -83,6 +83,7 @@ class UPnPError(Exception):
class Router: # pylint: disable=old-style-class
"""Encapulate routing"""
name = ""
path = ""
address = None
@ -152,7 +153,6 @@ class Router: # pylint: disable=old-style-class
def DeletePortMapping(self, externalPort, protocol):
"""Delete UPnP port mapping"""
resp = self.soapRequest(self.upnp_schema + ':1', 'DeletePortMapping', [
('NewRemoteHost', ''),
('NewExternalPort', str(externalPort)),
@ -163,16 +163,12 @@ class Router: # pylint: disable=old-style-class
def GetExternalIPAddress(self):
"""Get the external address"""
resp = self.soapRequest(
self.upnp_schema + ':1', 'GetExternalIPAddress')
resp = self.soapRequest(self.upnp_schema + ':1', 'GetExternalIPAddress')
dom = parseString(resp.read())
return dom.getElementsByTagName(
'NewExternalIPAddress')[0].childNodes[0].data
return dom.getElementsByTagName('NewExternalIPAddress')[0].childNodes[0].data
def soapRequest(self, service, action, arguments=None):
"""Make a request to a router"""
conn = httplib.HTTPConnection(self.routerPath.hostname, self.routerPath.port)
conn.request(
'POST',
@ -223,7 +219,6 @@ class uPnPThread(StoppableThread):
def run(self):
"""Start the thread to manage UPnP activity"""
logger.debug("Starting UPnP thread")
logger.debug("Local IP: %s", self.localIP)
lastSent = 0
@ -261,16 +256,12 @@ class uPnPThread(StoppableThread):
self.routers.append(newRouter)
self.createPortMapping(newRouter)
try:
self_peer = Peer(
newRouter.GetExternalIPAddress(),
self.extPort
)
self_peer = Peer(newRouter.GetExternalIPAddress(), self.extPort)
except:
logger.debug('Failed to get external IP')
else:
with knownnodes.knownNodesLock:
knownnodes.addKnownNode(
1, self_peer, is_self=True)
knownnodes.addKnownNode(1, self_peer, is_self=True)
queues.UISignalQueue.put(('updateStatusBar', tr._translate(
"MainWindow", 'UPnP port mapping established on port %1'
).arg(str(self.extPort))))
@ -296,12 +287,12 @@ class uPnPThread(StoppableThread):
deleted = True
self.deletePortMapping(router)
if deleted:
queues.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed')))
queues.UISignalQueue.put(
('updateStatusBar', tr._translate("MainWindow", 'UPnP port mapping removed')))
logger.debug("UPnP thread done")
def getLocalIP(self):
"""Get the local IP of the node"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect((uPnPThread.GOOGLE_DNS, 1))
@ -309,7 +300,6 @@ class uPnPThread(StoppableThread):
def sendSearchRouter(self):
"""Querying for UPnP services"""
ssdpRequest = "M-SEARCH * HTTP/1.1\r\n" + \
"HOST: %s:%d\r\n" % (uPnPThread.SSDP_ADDR, uPnPThread.SSDP_PORT) + \
"MAN: \"ssdp:discover\"\r\n" + \
@ -324,7 +314,6 @@ class uPnPThread(StoppableThread):
def createPortMapping(self, router):
"""Add a port mapping"""
for i in range(50):
try:
localIP = self.localIP
@ -336,10 +325,7 @@ class uPnPThread(StoppableThread):
extPort = randint(32767, 65535)
logger.debug(
"Attempt %i, requesting UPnP mapping for %s:%i on external port %i",
i,
localIP,
self.localPort,
extPort)
i, localIP, self.localPort, extPort)
router.AddPortMapping(extPort, self.localPort, localIP, 'TCP', 'BitMessage')
self.extPort = extPort
BMConfigParser().set('bitmessagesettings', 'extport', str(extPort))