From afb368e7706f4af9394d1311da6dcd078ebb78b9 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Thu, 26 Sep 2019 19:38:19 +0530 Subject: [PATCH 01/54] initial commit for python forward porting --- src/addresses.py | 6 +-- src/bitmessagekivy/mpybit.py | 1 + src/bitmessagemain.py | 37 +++++++++---------- src/bitmessageqt/statusbar.py | 2 +- src/bmconfigparser.py | 59 +++++++++++++++++------------- src/class_objectProcessorQueue.py | 2 +- src/class_sqlThread.py | 12 +++--- src/debug.py | 7 ++-- src/depends.py | 10 ++--- src/helper_bitcoin.py | 6 ++- src/helper_sql.py | 2 +- src/helper_startup.py | 9 +++-- src/highlevelcrypto.py | 3 +- src/knownnodes.py | 7 ++-- src/l10n.py | 24 ++++++++---- src/messagetypes/__init__.py | 2 +- src/multiqueue.py | 2 +- src/network/addrthread.py | 2 +- src/network/advanceddispatcher.py | 5 ++- src/network/asyncore_pollchoose.py | 7 ++-- src/network/bmproto.py | 6 +-- src/network/connectionpool.py | 13 +++---- src/network/dandelion.py | 2 +- src/network/downloadthread.py | 4 +- src/network/http.py | 2 +- src/network/invthread.py | 2 +- src/network/objectracker.py | 2 +- src/network/proxy.py | 4 +- src/network/randomtrackingdict.py | 10 ++--- src/network/receivequeuethread.py | 2 +- src/network/socks4a.py | 4 +- src/network/socks5.py | 4 +- src/network/stats.py | 2 +- src/network/tcp.py | 4 +- src/network/tls.py | 7 +++- src/network/udp.py | 4 +- src/network/uploadthread.py | 2 +- src/openclpow.py | 5 ++- src/pyelliptic/arithmetic.py | 4 +- src/pyelliptic/cipher.py | 2 +- src/pyelliptic/ecc.py | 9 +++-- src/pyelliptic/hash.py | 2 +- src/pyelliptic/openssl.py | 5 ++- src/queues.py | 2 +- src/shared.py | 9 ++--- src/shutdown.py | 2 +- src/singleinstance.py | 6 +-- src/storage/filesystem.py | 4 +- src/storage/sqlite.py | 1 + src/suravata.py | 32 ---------------- src/tests/core.py | 2 +- src/tr.py | 6 +-- 52 files changed, 187 insertions(+), 183 deletions(-) delete mode 100644 src/suravata.py diff --git a/src/addresses.py b/src/addresses.py index 533ec169..4d200332 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -180,7 +180,6 @@ def decodeAddress(address): data (almost certainly a ripe hash)) """ # pylint: disable=too-many-return-statements,too-many-statements,too-many-return-statements,too-many-branches - address = str(address).strip() if address[:3] == 'BM-': @@ -192,7 +191,8 @@ def decodeAddress(address): return status, 0, 0, '' # after converting to hex, the string will be prepended # with a 0x and appended with a L - hexdata = hex(integer)[2:-1] + # import pdb;pdb.set_trace() + hexdata = hex(integer)[2:] if len(hexdata) % 2 != 0: hexdata = '0' + hexdata @@ -248,7 +248,7 @@ def decodeAddress(address): embeddedRipeData elif len(embeddedRipeData) == 18: return status, addressVersionNumber, streamNumber, \ - '\x00\x00' + embeddedRipeData + '\x00\x00'.encode('utf-8') + embeddedRipeData elif len(embeddedRipeData) < 18: return 'ripetooshort', 0, 0, '' elif len(embeddedRipeData) > 20: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 39005727..70f51b29 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -984,6 +984,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods def build(self): """Method builds the widget.""" + import os main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) self.nav_drawer = Navigatorss() diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index ee4b7eb9..e066dd06 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -179,13 +179,13 @@ def signal_handler(signum, frame): if shared.thisapp.daemon or not state.enableGUI: shutdown.doCleanShutdown() else: - print '# Thread: %s(%d)' % (thread.name, thread.ident) + print ('# Thread: {}({})'.format(thread.name, thread.ident)) for filename, lineno, name, line in traceback.extract_stack(frame): - print 'File: "%s", line %d, in %s' % (filename, lineno, name) + print ("File: '{}', line {}, in {}" .format(filename, lineno, name)) if line: - print ' %s' % line.strip() - print 'Unfortunately you cannot use Ctrl+C when running the UI \ - because the UI captures the signal.' + print (' {}'.format(line.strip())) + print('Unfortunately you cannot use Ctrl+C when running the UI \ + because the UI captures the signal.') class Main: # pylint: disable=no-init, old-style-class @@ -282,7 +282,7 @@ class Main: # pylint: disable=no-init, old-style-class if daemon: with shared.printLock: - print 'Running as a daemon. Send TERM signal to end.' + print('Running as a daemon. Send TERM signal to end.') self.daemonize() self.setSignalHandler() @@ -405,7 +405,7 @@ class Main: # pylint: disable=no-init, old-style-class if state.curses: if not depends.check_curses(): sys.exit() - print 'Running with curses' + print('Running with curses') import bitmessagecurses bitmessagecurses.runwrapper() @@ -498,23 +498,22 @@ class Main: # pylint: disable=no-init, old-style-class # signal.signal(signal.SIGINT, signal.SIG_DFL) @staticmethod - def usage(): - """After passing argument, method displays the usages""" - print 'Usage: ' + sys.argv[0] + ' [OPTIONS]' - print ''' -Options: - -h, --help show this help message and exit - -c, --curses use curses (text mode) interface - -d, --daemon run in daemon (background) mode - -t, --test dryrun, make testing + def usage(self): + print('Usage: ' + sys.argv[0] + ' [OPTIONS]') + print (''' + Options: + -h, --help show this help message and exit + -c, --curses use curses (text mode) interface + -d, --daemon run in daemon (background) mode + -t, --test dryrun, make testing -All parameters are optional. -''' + All parameters are optional. + ''') def stop(self): # pylint: disable=no-self-use """Method helps to stop the Bitmessage Deamon""" with shared.printLock: - print 'Stopping Bitmessage Deamon.' + print('Stopping Bitmessage Deamon.') shutdown.doCleanShutdown() # ..todo: nice function but no one is using this diff --git a/src/bitmessageqt/statusbar.py b/src/bitmessageqt/statusbar.py index 65a5acfb..7f559197 100644 --- a/src/bitmessageqt/statusbar.py +++ b/src/bitmessageqt/statusbar.py @@ -1,5 +1,5 @@ from PyQt4 import QtCore, QtGui -from Queue import Queue +from queue.Queue import Queue from time import time class BMStatusBar(QtGui.QStatusBar): diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 726d32eb..6f5660e0 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -2,7 +2,7 @@ BMConfigParser class definition and default configuration settings """ -import ConfigParser +import configparser import shutil import os from datetime import datetime @@ -42,35 +42,35 @@ BMConfigDefaults = { @Singleton -class BMConfigParser(ConfigParser.SafeConfigParser): - """Singleton class inherited from ConfigParser.SafeConfigParser +class BMConfigParser(configparser.ConfigParser): + """Singleton class inherited from ConfigParsedadfeConfigParser with additional methods specific to bitmessage config.""" _temp = {} def set(self, section, option, value=None): if self._optcre is self.OPTCRE or value: - if not isinstance(value, basestring): + if not isinstance(value, str): raise TypeError("option values must be strings") if not self.validate(section, option, value): raise ValueError("Invalid value %s" % value) - return ConfigParser.ConfigParser.set(self, section, option, value) + return configparser.ConfigParser.set(self, section, option, value) def get(self, section, option, raw=False, variables=None): try: if section == "bitmessagesettings" and option == "timeformat": - return ConfigParser.ConfigParser.get( - self, section, option, raw, variables) + return configparser.ConfigParser.get( + self, section, option, raw=True, vars=variables) try: return self._temp[section][option] except KeyError: pass - return ConfigParser.ConfigParser.get( - self, section, option, True, variables) - except ConfigParser.InterpolationError: - return ConfigParser.ConfigParser.get( - self, section, option, True, variables) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError) as e: + return configparser.ConfigParser.get( + self, section, option, raw=True, vars=variables) + except configparser.InterpolationError: + return configparser.ConfigParser.get( + self, section, option, raw=True, vars=variables) + except (configparser.NoSectionError, configparser.NoOptionError) as e: try: return BMConfigDefaults[section][option] except (KeyError, ValueError, AttributeError): @@ -84,49 +84,56 @@ class BMConfigParser(ConfigParser.SafeConfigParser): self._temp[section] = {option: value} def safeGetBoolean(self, section, field): + config = configparser.ConfigParser() try: - return self.getboolean(section, field) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, + #Used in the python2.7 + # return self.getboolean(section, field) + #Used in the python3.5.2 + return config.getboolean(section, field) + except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return False def safeGetInt(self, section, field, default=0): + config = configparser.ConfigParser() try: - return self.getint(section, field) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, + #Used in the python2.7 + # return self.getint(section, field) + #Used in the python3.5.2 + return config.getint(section, field) + except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return default def safeGet(self, section, option, default=None): try: return self.get(section, option) - except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, + except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return default def items(self, section, raw=False, variables=None): - return ConfigParser.ConfigParser.items(self, section, True, variables) + return configparser.ConfigParser.items(self, section, True, variables) def addresses(self): - return filter( - lambda x: x.startswith('BM-'), BMConfigParser().sections()) + return [x for x in BMConfigParser().sections() if x.startswith('BM-')] def read(self, filenames): - ConfigParser.ConfigParser.read(self, filenames) + configparser.ConfigParser.read(self, filenames) for section in self.sections(): for option in self.options(section): try: if not self.validate( section, option, - ConfigParser.ConfigParser.get(self, section, option) + configparser.ConfigParser.get(self, section, option) ): try: newVal = BMConfigDefaults[section][option] except KeyError: continue - ConfigParser.ConfigParser.set( + configparser.ConfigParser.set( self, section, option, newVal) - except ConfigParser.InterpolationError: + except configparser.InterpolationError: continue def save(self): @@ -144,7 +151,7 @@ class BMConfigParser(ConfigParser.SafeConfigParser): # didn't exist before. fileNameExisted = False # write the file - with open(fileName, 'wb') as configfile: + with open(fileName, 'w') as configfile: self.write(configfile) # delete the backup if fileNameExisted: diff --git a/src/class_objectProcessorQueue.py b/src/class_objectProcessorQueue.py index b6628816..24c24023 100644 --- a/src/class_objectProcessorQueue.py +++ b/src/class_objectProcessorQueue.py @@ -1,4 +1,4 @@ -import Queue +import queue as Queue import threading import time diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index a45571e0..bf0e67d9 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -51,8 +51,8 @@ class sqlThread(threading.Thread): '''INSERT INTO subscriptions VALUES('Bitmessage new releases/announcements','BM-GtovgYdgs7qXPkoYaRgrLFuFKz1SFpsw',1)''') self.cur.execute( '''CREATE TABLE settings (key blob, value blob, UNIQUE(key) ON CONFLICT REPLACE)''' ) - self.cur.execute( '''INSERT INTO settings VALUES('version','10')''') - self.cur.execute( '''INSERT INTO settings VALUES('lastvacuumtime',?)''', ( + self.cur.execute('''INSERT INTO settings VALUES('version','10')''') + self.cur.execute('''INSERT INTO settings VALUES('lastvacuumtime',?)''', ( int(time.time()),)) self.cur.execute( '''CREATE TABLE objectprocessorqueue (objecttype int, data blob, UNIQUE(objecttype, data) ON CONFLICT REPLACE)''' ) @@ -70,9 +70,11 @@ class sqlThread(threading.Thread): # If the settings version is equal to 2 or 3 then the # sqlThread will modify the pubkeys table and change # the settings version to 4. - settingsversion = BMConfigParser().getint( - 'bitmessagesettings', 'settingsversion') - + # settingsversion = BMConfigParser().getint('bitmessagesettings', 'settingsversion') + # In the Python3 I am below condition converting into int + # settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \ + # if BMConfigParser().get('bitmessagesettings', 'settingsversion') else 0) + settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion') # People running earlier versions of PyBitmessage do not have the # usedpersonally field in their pubkeys table. Let's add it. if settingsversion == 2: diff --git a/src/debug.py b/src/debug.py index 8393bb50..0caf1956 100644 --- a/src/debug.py +++ b/src/debug.py @@ -23,7 +23,7 @@ Use: `from debug import logger` to import this facility into whatever module you """ -import ConfigParser +import configparser import logging import logging.config import os @@ -47,12 +47,13 @@ def configureLogging(): fail_msg = '' try: logging_config = os.path.join(state.appdata, 'logging.dat') - logging.config.fileConfig(logging_config) + # right now I am commenting the logger + # logging.config.fileConfig(logging_config, disable_existing_loggers=False) return ( False, 'Loaded logger configuration from %s' % logging_config ) - except (OSError, ConfigParser.NoSectionError): + except (OSError, configparser.NoSectionError): if os.path.isfile(logging_config): fail_msg = \ 'Failed to load logger configuration from %s, using default' \ diff --git a/src/depends.py b/src/depends.py index dc35b529..b0d0beb4 100755 --- a/src/depends.py +++ b/src/depends.py @@ -419,11 +419,11 @@ def check_dependencies(verbose=False, optional=False): 'PyBitmessage requires Python 2.7.4 or greater' ' (but not Python 3+)') has_all_dependencies = False - if sys.hexversion >= 0x3000000: - logger.error( - 'PyBitmessage does not support Python 3+. Python 2.7.4' - ' or greater is required.') - has_all_dependencies = False + # if sys.hexversion >= 0x3000000: + # logger.error( + # 'PyBitmessage does not support Python 3+. Python 2.7.4' + # ' or greater is required.') + # has_all_dependencies = False check_functions = [check_ripemd160, check_sqlite, check_openssl] if optional: diff --git a/src/helper_bitcoin.py b/src/helper_bitcoin.py index d56e395b..b4f34cf1 100644 --- a/src/helper_bitcoin.py +++ b/src/helper_bitcoin.py @@ -4,7 +4,8 @@ from pyelliptic import arithmetic # This function expects that pubkey begin with \x04 def calculateBitcoinAddressFromPubkey(pubkey): if len(pubkey) != 65: - print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' + print ('Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was'\ + '{}, bytes long rather than 65.'.format(len(pubkey))) return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') @@ -25,7 +26,8 @@ def calculateBitcoinAddressFromPubkey(pubkey): def calculateTestnetAddressFromPubkey(pubkey): if len(pubkey) != 65: - print 'Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was', len(pubkey), 'bytes long rather than 65.' + print ('Could not calculate Bitcoin address from pubkey because function was passed a pubkey that was',\ + '{}, bytes long rather than 65.'.format(pubkey)) return "error" ripe = hashlib.new('ripemd160') sha = hashlib.new('sha256') diff --git a/src/helper_sql.py b/src/helper_sql.py index 2b558f62..8bf6ce4d 100644 --- a/src/helper_sql.py +++ b/src/helper_sql.py @@ -1,7 +1,7 @@ """Helper Sql performs sql operations.""" import threading -import Queue +import queue as Queue sqlSubmitQueue = Queue.Queue() # SQLITE3 is so thread-unsafe that they won't even let you call it from different threads using your own locks. diff --git a/src/helper_startup.py b/src/helper_startup.py index 5d1614c7..0d3523e3 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -7,7 +7,7 @@ Helper Start performs all the startup operations. # pylint: disable=too-many-branches,too-many-statements from __future__ import print_function -import ConfigParser +import configparser import os import platform import sys @@ -27,7 +27,7 @@ StoreConfigFilesInSameDirectoryAsProgramByDefault = False def _loadTrustedPeer(): try: trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer') - except ConfigParser.Error: + except configparser.Error: # This probably means the trusted peer wasn't specified so we # can just leave it as None return @@ -137,11 +137,12 @@ def loadConfig(): _loadTrustedPeer() - def updateConfig(): """Save the config""" config = BMConfigParser() - settingsversion = config.getint('bitmessagesettings', 'settingsversion') + # Used python2.7 + # settingsversion = int(BMConfigParser().get('bitmessagesettings', 'settingsversion') \ + settingsversion = BMConfigParser().safeGetInt('bitmessagesettings', 'settingsvesion') if settingsversion == 1: config.set('bitmessagesettings', 'socksproxytype', 'none') config.set('bitmessagesettings', 'sockshostname', 'localhost') diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 02fb85ab..c235072c 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -13,10 +13,11 @@ from pyelliptic import arithmetic as a def makeCryptor(privkey): """Return a private pyelliptic.ECC() instance""" + # import pdb;pdb.set_trace() private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) privkey_bin = '\x02\xca\x00\x20' + private_key - pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32] + '\x00\x20' + public_key[-32:] + pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32].decode() + '\x00\x20' + public_key[-32:].decode() cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/knownnodes.py b/src/knownnodes.py index ba21bac7..b30ca770 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -40,12 +40,13 @@ def json_serialize_knownnodes(output): Reorganize knownnodes dict and write it as JSON to output """ _serialized = [] - for stream, peers in knownNodes.iteritems(): - for peer, info in peers.iteritems(): + for stream, peers in iter(knownNodes.items()): + for peer, info in iter(peers.items()): info.update(rating=round(info.get('rating', 0), 2)) _serialized.append({ 'stream': stream, 'peer': peer._asdict(), 'info': info }) + # import pdb;pdb.set_trace() json.dump(_serialized, output, indent=4) @@ -85,7 +86,7 @@ def saveKnownNodes(dirName=None): if dirName is None: dirName = state.appdata with knownNodesLock: - with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output: + with open(os.path.join(dirName, 'knownnodes.dat'), 'w') as output: json_serialize_knownnodes(output) diff --git a/src/l10n.py b/src/l10n.py index b3b16341..890f9491 100644 --- a/src/l10n.py +++ b/src/l10n.py @@ -64,20 +64,30 @@ else: if time_format != DEFAULT_TIME_FORMAT: try: #Check day names - for i in xrange(7): - unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) + new_time_format = time_format + import sys + if sys.version_info >= (3, 0, 0) and time_format == '%%c': + time_format = '%c' + for i in range(7): + #this work for python2.7 + # unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) + #this code for the python3 + (time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode() #Check month names - for i in xrange(1, 13): - unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) + for i in range(1, 13): + # unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) + (time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0))).encode() + #Check AM/PM - unicode(time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0)), encoding) - unicode(time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0)), encoding) + (time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode() + (time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode() #Check DST - unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1)), encoding) + (time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode() except: logger.exception('Could not decode locale formatted timestamp') time_format = DEFAULT_TIME_FORMAT encoding = DEFAULT_ENCODING + time_format = new_time_format def setlocale(category, newlocale): locale.setlocale(category, newlocale) diff --git a/src/messagetypes/__init__.py b/src/messagetypes/__init__.py index 53d23de7..ea3de756 100644 --- a/src/messagetypes/__init__.py +++ b/src/messagetypes/__init__.py @@ -4,7 +4,7 @@ src/messagetypes/__init__.py """ from importlib import import_module from os import path, listdir -from string import lower + try: from kivy.utils import platform except: diff --git a/src/multiqueue.py b/src/multiqueue.py index 8c64d33d..a41e2033 100644 --- a/src/multiqueue.py +++ b/src/multiqueue.py @@ -3,7 +3,7 @@ src/multiqueue.py ================= """ -import Queue +import queue as Queue from collections import deque import helper_random diff --git a/src/network/addrthread.py b/src/network/addrthread.py index 9f516e80..76f1c184 100644 --- a/src/network/addrthread.py +++ b/src/network/addrthread.py @@ -1,4 +1,4 @@ -import Queue +import queue as Queue from helper_threading import StoppableThread from network.connectionpool import BMConnectionPool diff --git a/src/network/advanceddispatcher.py b/src/network/advanceddispatcher.py index c8f125f0..bec91c60 100644 --- a/src/network/advanceddispatcher.py +++ b/src/network/advanceddispatcher.py @@ -30,7 +30,10 @@ class AdvancedDispatcher(asyncore.dispatcher): _buf_len = 131072 # 128kB def __init__(self, sock=None): - if not hasattr(self, '_map'): + # python 2 below condition is used + # if not hasattr(self, '_map'): + # python 3 below condition is used + if not '_map' in dir(self): asyncore.dispatcher.__init__(self, sock) self.read_buf = bytearray() self.write_buf = bytearray() diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 3337c0f0..3137797c 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -767,10 +767,11 @@ class dispatcher: # references to the underlying socket object. def __getattr__(self, attr): try: + # import pdb;pdb.set_trace() retattr = getattr(self.socket, attr) except AttributeError: - raise AttributeError("%s instance has no attribute '%s'" - % (self.__class__.__name__, attr)) + raise AttributeError("{} instance has no attribute {}" + .format(self.__class__.__name__, attr)) else: msg = "%(me)s.%(attr)s is deprecated; use %(me)s.socket.%(attr)s " \ "instead" % {'me': self.__class__.__name__, 'attr': attr} @@ -788,7 +789,7 @@ class dispatcher: def log_info(self, message, log_type='info'): """Conditionally print a message""" if log_type not in self.ignore_log_types: - print '%s: %s' % (log_type, message) + print ('{}: {}'.format((log_type, message))) def handle_read_event(self): """Handle a read event""" diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 0a2cdc7e..813d5b97 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -11,7 +11,7 @@ import time from binascii import hexlify import addresses -import connectionpool +import network.connectionpool import knownnodes import protocol import state @@ -26,9 +26,9 @@ from network.bmobject import ( BMObjectInvalidError, BMObjectAlreadyHaveError) from network.node import Node from network.proxy import ProxyError -from objectracker import missingObjects, ObjectTracker +from network.objectracker import missingObjects, ObjectTracker from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue -from randomtrackingdict import RandomTrackingDict +from network.randomtrackingdict import RandomTrackingDict class BMProtoError(ProxyError): diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 4d16df49..a50d83b6 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -7,20 +7,19 @@ import re import socket import time -import asyncore_pollchoose as asyncore +import network.asyncore_pollchoose as asyncore import helper_random import knownnodes import protocol import state from bmconfigparser import BMConfigParser -from connectionchooser import chooseConnection +from network.connectionchooser import chooseConnection from debug import logger -from proxy import Proxy +from network.proxy import Proxy from singleton import Singleton -from tcp import ( - bootstrap, Socks4aBMConnection, Socks5BMConnection, - TCPConnection, TCPServer) -from udp import UDPSocket +from network.tcp import ( + TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection) +from network.udp import UDPSocket @Singleton diff --git a/src/network/dandelion.py b/src/network/dandelion.py index fa9081cb..abba16ba 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -7,7 +7,7 @@ from random import choice, sample, expovariate from threading import RLock from time import time -import connectionpool +import network.connectionpool import state from debug import logging from queues import invQueue diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index a4b58862..a09d0c1d 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -7,12 +7,12 @@ import time import addresses import helper_random import protocol -from dandelion import Dandelion +from network.dandelion import Dandelion from debug import logger from helper_threading import StoppableThread from inventory import Inventory from network.connectionpool import BMConnectionPool -from objectracker import missingObjects +from network.objectracker import missingObjects class DownloadThread(StoppableThread): diff --git a/src/network/http.py b/src/network/http.py index 8bba38ac..fdfe8370 100644 --- a/src/network/http.py +++ b/src/network/http.py @@ -2,7 +2,7 @@ import socket from advanceddispatcher import AdvancedDispatcher import asyncore_pollchoose as asyncore -from proxy import ProxyError +from network.proxy import ProxyError from socks5 import Socks5Connection, Socks5Resolver from socks4a import Socks4aConnection, Socks4aResolver diff --git a/src/network/invthread.py b/src/network/invthread.py index ad3a0764..1d2b790d 100644 --- a/src/network/invthread.py +++ b/src/network/invthread.py @@ -2,7 +2,7 @@ src/network/invthread.py ======================== """ -import Queue +import queue as Queue import random from time import time diff --git a/src/network/objectracker.py b/src/network/objectracker.py index a8e3292a..40a0f582 100644 --- a/src/network/objectracker.py +++ b/src/network/objectracker.py @@ -7,7 +7,7 @@ from threading import RLock import network.connectionpool from network.dandelion import Dandelion -from randomtrackingdict import RandomTrackingDict +from network.randomtrackingdict import RandomTrackingDict haveBloom = False diff --git a/src/network/proxy.py b/src/network/proxy.py index 479663d3..c3f13ad2 100644 --- a/src/network/proxy.py +++ b/src/network/proxy.py @@ -6,9 +6,9 @@ src/network/proxy.py import socket import time -import asyncore_pollchoose as asyncore +import network.asyncore_pollchoose as asyncore import state -from advanceddispatcher import AdvancedDispatcher +from network.advanceddispatcher import AdvancedDispatcher from bmconfigparser import BMConfigParser from debug import logger diff --git a/src/network/randomtrackingdict.py b/src/network/randomtrackingdict.py index 6c3300ab..16eb63e1 100644 --- a/src/network/randomtrackingdict.py +++ b/src/network/randomtrackingdict.py @@ -140,20 +140,20 @@ if __name__ == '__main__': k = RandomTrackingDict() d = {} - print "populating random tracking dict" + print ("populating random tracking dict") a.append(time()) for i in range(50000): k[randString()] = True a.append(time()) - print "done" + print ("done") while k: retval = k.randomKeys(1000) if not retval: - print "error getting random keys" + print ("error getting random keys") try: k.randomKeys(100) - print "bad" + print( "bad") except KeyError: pass for i in retval: @@ -161,4 +161,4 @@ if __name__ == '__main__': a.append(time()) for x in range(len(a) - 1): - print "%i: %.3f" % (x, a[x + 1] - a[x]) + print("{}i: {}.3f".format(x, a[x + 1] - a[x])) diff --git a/src/network/receivequeuethread.py b/src/network/receivequeuethread.py index 5d8cbd37..f836b74b 100644 --- a/src/network/receivequeuethread.py +++ b/src/network/receivequeuethread.py @@ -1,5 +1,5 @@ import errno -import Queue +import queue as Queue import socket from debug import logger diff --git a/src/network/socks4a.py b/src/network/socks4a.py index f0b234f5..b92e53a5 100644 --- a/src/network/socks4a.py +++ b/src/network/socks4a.py @@ -6,7 +6,7 @@ src/network/socks4a.py import socket import struct -from proxy import Proxy, ProxyError, GeneralProxyError +from network.proxy import Proxy, ProxyError, GeneralProxyError class Socks4aError(ProxyError): @@ -141,4 +141,4 @@ class Socks4aResolver(Socks4a): PyBitmessage, a callback needs to be implemented which hasn't been done yet. """ - print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) + print("Resolved {} as {}".format(self.host, self.proxy_sock_name())) diff --git a/src/network/socks5.py b/src/network/socks5.py index e0cb7202..8a7d922e 100644 --- a/src/network/socks5.py +++ b/src/network/socks5.py @@ -9,7 +9,7 @@ import socket import struct import state -from proxy import GeneralProxyError, Proxy, ProxyError +from network.proxy import GeneralProxyError, Proxy, ProxyError class Socks5AuthError(ProxyError): @@ -218,4 +218,4 @@ class Socks5Resolver(Socks5): To use this within PyBitmessage, a callback needs to be implemented which hasn't been done yet. """ - print "Resolved %s as %s" % (self.host, self.proxy_sock_name()) + print("Resolved {} as {}".format(self.host, self.proxy_sock_name())) diff --git a/src/network/stats.py b/src/network/stats.py index fedfbbc1..7b9a1e0d 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -6,7 +6,7 @@ import time import asyncore_pollchoose as asyncore from network.connectionpool import BMConnectionPool -from objectracker import missingObjects +from network.objectracker import missingObjects lastReceivedTimestamp = time.time() diff --git a/src/network/tcp.py b/src/network/tcp.py index da02df2f..31346e22 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -10,8 +10,8 @@ import socket import time import addresses -import asyncore_pollchoose as asyncore -import connectionpool +import network.asyncore_pollchoose as asyncore +import network.connectionpool import helper_random import knownnodes import protocol diff --git a/src/network/tls.py b/src/network/tls.py index 17b1ee1f..5f4be3b9 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -21,7 +21,12 @@ if sys.version_info >= (2, 7, 13): # this means TLSv1 or higher # in the future change to # ssl.PROTOCOL_TLS1.2 - sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member + # Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I + # have used try and catch + try: + sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member + except AttributeError: + sslProtocolVersion = ssl.PROTOCOL_SSLv23 elif sys.version_info >= (2, 7, 9): # this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created sslProtocolVersion = ssl.PROTOCOL_SSLv23 diff --git a/src/network/udp.py b/src/network/udp.py index 01dc1f7b..c3e4ce44 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -7,9 +7,9 @@ import socket import state import protocol -from bmproto import BMProto +from network.bmproto import BMProto from debug import logger -from objectracker import ObjectTracker +from network.objectracker import ObjectTracker from queues import receiveDataQueue diff --git a/src/network/uploadthread.py b/src/network/uploadthread.py index 9b29ef0a..1b06af23 100644 --- a/src/network/uploadthread.py +++ b/src/network/uploadthread.py @@ -11,7 +11,7 @@ from helper_threading import StoppableThread from inventory import Inventory from network.connectionpool import BMConnectionPool from network.dandelion import Dandelion -from randomtrackingdict import RandomTrackingDict +from network.randomtrackingdict import RandomTrackingDict class UploadThread(StoppableThread): diff --git a/src/openclpow.py b/src/openclpow.py index eb91a07f..e56c04c1 100644 --- a/src/openclpow.py +++ b/src/openclpow.py @@ -107,9 +107,10 @@ def do_opencl_pow(hash, target): #initCL() if __name__ == "__main__": - target = 54227212183L + #in python3 I have change this 54227212183L to 54227212183 + target = 54227212183 initialHash = "3758f55b5a8d902fd3597e4ce6a2d3f23daff735f65d9698c270987f4e67ad590b93f3ffeba0ef2fd08a8dc2f87b68ae5a0dc819ab57f22ad2c4c9c8618a43b3".decode("hex") nonce = do_opencl_pow(initialHash.encode("hex"), target) trialValue, = unpack('>Q',hashlib.sha512(hashlib.sha512(pack('>Q',nonce) + initialHash).digest()).digest()[0:8]) - print "{} - value {} < {}".format(nonce, trialValue, target) + print ("{} - value {} < {}".format(nonce, trialValue, target)) diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 95c85b93..43166006 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -39,7 +39,7 @@ def encode(val, base, minlen=0): code_string = get_code_string(base) result = "" while val > 0: - result = code_string[val % base] + result + result = code_string[round(val % base)] + result val /= base if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result @@ -53,7 +53,7 @@ def decode(string, base): string = string.lower() while string: result *= base - result += code_string.find(string[0]) + result += code_string.find(string.decode()[0]) string = string[1:] return result diff --git a/src/pyelliptic/cipher.py b/src/pyelliptic/cipher.py index d02b743a..e0bb9ac9 100644 --- a/src/pyelliptic/cipher.py +++ b/src/pyelliptic/cipher.py @@ -8,7 +8,7 @@ src/pyelliptic/cipher.py # Copyright (C) 2011 Yann GUIBET # See LICENSE for details. -from openssl import OpenSSL +from .openssl import OpenSSL # pylint: disable=redefined-builtin diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index 2de0bfe9..14adca42 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -12,9 +12,9 @@ src/pyelliptic/ecc.py from hashlib import sha512 from struct import pack, unpack -from cipher import Cipher -from hash import equals, hmac_sha256 -from openssl import OpenSSL +from pyelliptic.cipher import Cipher +from pyelliptic.hash import equals, hmac_sha256 +from pyelliptic.openssl import OpenSSL class ECC(object): @@ -129,7 +129,8 @@ class ECC(object): )) @staticmethod - def _decode_pubkey(pubkey): + def _decode_pubkey( pubkey): + pubkey = pubkey.encode() i = 0 curve = unpack('!H', pubkey[i:i + 2])[0] i += 2 diff --git a/src/pyelliptic/hash.py b/src/pyelliptic/hash.py index c21dd6a4..9ea8eb6d 100644 --- a/src/pyelliptic/hash.py +++ b/src/pyelliptic/hash.py @@ -7,7 +7,7 @@ src/pyelliptic/hash.py # Copyright (C) 2011 Yann GUIBET # See LICENSE for details. -from openssl import OpenSSL +from .openssl import OpenSSL # For python3 diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 6c5c4a84..35e7933a 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -90,7 +90,7 @@ class _OpenSSL: """Build the wrapper""" self._lib = ctypes.CDLL(library) self._version, self._hexversion, self._cflags = get_version(self._lib) - self._libreSSL = self._version.startswith("LibreSSL") + self._libreSSL = (self._version).decode("utf-8").startswith("OpenSSL") self.pointer = ctypes.pointer self.c_int = ctypes.c_int @@ -674,6 +674,7 @@ def loadOpenSSL(): elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) else: + libdir.extend([ path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libssl.so'), @@ -709,7 +710,7 @@ def loadOpenSSL(): pass elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(find_library('libeay32')) - for library in libdir: + for library in libdir: try: OpenSSL = _OpenSSL(library) return diff --git a/src/queues.py b/src/queues.py index 7b6bbade..1bdcd9fb 100644 --- a/src/queues.py +++ b/src/queues.py @@ -1,4 +1,4 @@ -import Queue +import queue as Queue from class_objectProcessorQueue import ObjectProcessorQueue from multiqueue import MultiQueue diff --git a/src/shared.py b/src/shared.py index dacd4a5f..2a53452a 100644 --- a/src/shared.py +++ b/src/shared.py @@ -174,12 +174,11 @@ def reloadBroadcastSendersForWhichImWatching(): # Now, for all addresses, even version 2 addresses, # we should create Cryptor objects in a dictionary which we will # use to attempt to decrypt encrypted broadcast messages. - + # import pdb;pdb.set_trace() if addressVersionNumber <= 3: - privEncryptionKey = hashlib.sha512( - encodeVarint(addressVersionNumber) + - encodeVarint(streamNumber) + hash - ).digest()[:32] + privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \ + + encodeVarint(streamNumber) + hash)).digest()[:32] + # import pdb;pdb.set_trace() MyECSubscriptionCryptorObjects[hash] = \ highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) else: diff --git a/src/shutdown.py b/src/shutdown.py index f136ac75..418d3b37 100644 --- a/src/shutdown.py +++ b/src/shutdown.py @@ -1,5 +1,5 @@ import os -import Queue +import queue as Queue import threading import time diff --git a/src/singleinstance.py b/src/singleinstance.py index a495bea0..554ce826 100644 --- a/src/singleinstance.py +++ b/src/singleinstance.py @@ -75,7 +75,7 @@ class singleinstance: fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) self.lockPid = os.getpid() except IOError: - print 'Another instance of this application is already running' + print ('Another instance of this application is already running') sys.exit(-1) else: pidLine = "%i\n" % self.lockPid @@ -94,11 +94,11 @@ class singleinstance: os.close(self.fd) else: fcntl.lockf(self.fp, fcntl.LOCK_UN) - except Exception, e: + except Exception as e: pass return - print "Cleaning up lockfile" + print ("Cleaning up lockfile") try: if sys.platform == 'win32': if hasattr(self, 'fd'): diff --git a/src/storage/filesystem.py b/src/storage/filesystem.py index 43ba03fc..74aee4fa 100644 --- a/src/storage/filesystem.py +++ b/src/storage/filesystem.py @@ -9,7 +9,7 @@ from threading import RLock import time from paths import lookupAppdataFolder -from storage import InventoryStorage, InventoryItem +from storage.storage import InventoryStorage, InventoryItem class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ancestors, abstract-method @@ -144,7 +144,7 @@ class FilesystemInventory(InventoryStorage): # pylint: disable=too-many-ances newInventory[streamNumber][hashId] = InventoryItem( objectType, streamNumber, None, expiresTime, tag) except KeyError: - print "error loading %s" % (hexlify(hashId)) + print ("error loading {}".format((hexlify(hashId)))) self._inventory = newInventory # for i, v in self._inventory.items(): # print "loaded stream: %s, %i items" % (i, len(v)) diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 0c2b4afa..54913830 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -6,6 +6,7 @@ import sqlite3 import time from threading import RLock + from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute from storage import InventoryStorage, InventoryItem diff --git a/src/suravata.py b/src/suravata.py deleted file mode 100644 index 18541989..00000000 --- a/src/suravata.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -# Import the libraries. -import pdb;pdb.set_trace() -import pydenticon100000000000000000000000 -import hashlib -# Set-up some test data. -users = ["alice", "bob", "eve", "dave"] -# Set-up a list of foreground colours (taken from Sigil). -foreground = ["rgb(45,79,255)", - "rgb(254,180,44)", - "rgb(226,121,234)", - "rgb(30,179,253)", - "rgb(232,77,65)", - "rgb(49,203,115)", - "rgb(141,69,170)"] -# Set-up a background colour (taken from Sigil). -background = "rgb(224,224,224)" -# Set-up the padding (top, bottom, left, right) in pixels. -padding = (20, 20, 20, 20) -# Instantiate a generator that will create 5x5 block identicons using SHA1 -# digest. -generator = pydenticon.Generator(5, 5, digest=hashlib.sha1, foreground=foreground, background=background) - -# identicon_ascii = generator.generate("john.doe@example.com", 200, 200, -# output_format="ascii") - -# print identicon_ascii -for user in users: - identicon = generator.generate(user, 200, 200, padding=padding, output_format="png") - filename = user + ".png" - with open(filename, "wb") as f: - f.write(identicon) \ No newline at end of file diff --git a/src/tests/core.py b/src/tests/core.py index b01c6b69..9021e4ff 100644 --- a/src/tests/core.py +++ b/src/tests/core.py @@ -5,7 +5,7 @@ Tests for core and those that do not work outside import os import pickle # nosec -import Queue +import queue as Queue import random # nosec import string import time diff --git a/src/tr.py b/src/tr.py index 5ce623cd..577354cc 100644 --- a/src/tr.py +++ b/src/tr.py @@ -46,11 +46,11 @@ def translateText(context, text, n=None): try: from PyQt4 import QtCore, QtGui except Exception as err: - print 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ + print ('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ .You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download\ or by searching Google for \'PyQt Download\'.\ - If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon' - print 'Error message:', err + If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon') + print ('Error message:', err) os._exit(0) # pylint: disable=protected-access if n is None: return QtGui.QApplication.translate(context, text) From 42ee9d910b205028e5c6127245f632dddd27439b Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Tue, 1 Oct 2019 20:19:03 +0530 Subject: [PATCH 02/54] launch py3 convert app for first phase(need to do more checks) --- src/bitmessagekivy/identiconGeneration.py | 4 +- src/bitmessagekivy/main.kv | 236 +++++++--------------- src/bitmessagekivy/mpybit.py | 50 ++--- src/bitmessagemain.py | 5 +- src/helper_startup.py | 7 +- src/highlevelcrypto.py | 5 +- src/knownnodes.py | 3 +- src/network/connectionpool.py | 9 +- src/network/stats.py | 7 +- src/pyelliptic/arithmetic.py | 18 +- src/pyelliptic/ecc.py | 37 ++-- src/storage/sqlite.py | 2 +- 12 files changed, 167 insertions(+), 216 deletions(-) diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index a5dcf3d0..14a31403 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -46,13 +46,13 @@ def generate_hash(string): # make input case insensitive string = str.lower(string) hash_object = hashlib.md5(str.encode(string)) - print hash_object.hexdigest() + 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." + print("Error: Please enter a string as an argument.") def random_color(hash_string): diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index be6f76e9..18f1ac6a 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -1,43 +1,38 @@ -#:import Toolbar kivymd.toolbar.Toolbar +#:import MDToolbar kivymd.uix.toolbar.MDToolbar #:import ThemeManager kivymd.theming.ThemeManager -#:import MDNavigationDrawer kivymd.navigationdrawer.MDNavigationDrawer -#:import NavigationLayout kivymd.navigationdrawer.NavigationLayout -#:import NavigationDrawerDivider kivymd.navigationdrawer.NavigationDrawerDivider -#:import NavigationDrawerToolbar kivymd.navigationdrawer.NavigationDrawerToolbar -#:import NavigationDrawerSubheader kivymd.navigationdrawer.NavigationDrawerSubheader -#:import MDCheckbox kivymd.selectioncontrols.MDCheckbox -#:import MDSwitch kivymd.selectioncontrols.MDSwitch -#:import MDList kivymd.list.MDList -#:import OneLineListItem kivymd.list.OneLineListItem -#:import TwoLineListItem kivymd.list.TwoLineListItem -#:import ThreeLineListItem kivymd.list.ThreeLineListItem -#:import OneLineAvatarListItem kivymd.list.OneLineAvatarListItem -#:import OneLineIconListItem kivymd.list.OneLineIconListItem -#:import OneLineAvatarIconListItem kivymd.list.OneLineAvatarIconListItem -#:import MDTextField kivymd.textfields.MDTextField -#:import MDSpinner kivymd.spinner.MDSpinner -#:import MDCard kivymd.card.MDCard -#:import MDSeparator kivymd.card.MDSeparator -#:import MDDropdownMenu kivymd.menu.MDDropdownMenu +#:import MDNavigationDrawer kivymd.uix.navigationdrawer.MDNavigationDrawer +#:import NavigationLayout kivymd.uix.navigationdrawer.NavigationLayout +#:import NavigationDrawerDivider kivymd.uix.navigationdrawer.NavigationDrawerDivider +#:import NavigationDrawerToolbar kivymd.uix.navigationdrawer.NavigationDrawerToolbar +#:import NavigationDrawerSubheader kivymd.uix.navigationdrawer.NavigationDrawerSubheader +#:import MDCheckbox kivymd.uix.selectioncontrol.MDCheckbox +#:import MDSwitch kivymd.uix.selectioncontrol.MDSwitch +#:import MDList kivymd.uix.list.MDList +#:import OneLineListItem kivymd.uix.list.OneLineListItem +#:import TwoLineListItem kivymd.uix.list.TwoLineListItem +#:import ThreeLineListItem kivymd.uix.list.ThreeLineListItem +#:import OneLineAvatarListItem kivymd.uix.list.OneLineAvatarListItem +#:import OneLineIconListItem kivymd.uix.list.OneLineIconListItem +#:import OneLineAvatarIconListItem kivymd.uix.list.OneLineAvatarIconListItem +#:import MDTextField kivymd.uix.textfield.MDTextField +#:import MDSpinner kivymd.uix.spinner.MDSpinner +#:import MDCard kivymd.uix.card.MDCard +#:import MDSeparator kivymd.uix.card.MDSeparator +#:import MDDropdownMenu kivymd.uix.menu.MDDropdownMenu #:import get_color_from_hex kivy.utils.get_color_from_hex #:import colors kivymd.color_definitions.colors -#:import SmartTile kivymd.grid.SmartTile -#:import MDSlider kivymd.slider.MDSlider -#:import MDTabbedPanel kivymd.tabs.MDTabbedPanel -#:import MDTab kivymd.tabs.MDTab -#:import MDProgressBar kivymd.progressbar.MDProgressBar -#:import MDAccordion kivymd.accordion.MDAccordion -#:import MDAccordionItem kivymd.accordion.MDAccordionItem -#:import MDAccordionSubItem kivymd.accordion.MDAccordionSubItem -#:import MDThemePicker kivymd.theme_picker.MDThemePicker -#:import MDBottomNavigation kivymd.tabs.MDBottomNavigation -#:import MDBottomNavigationItem kivymd.tabs.MDBottomNavigationItem -#:import MDFloatingActionButton kivymd.button.MDFloatingActionButton +#:import MDSlider kivymd.uix.slider.MDSlider +#:import MDTabs kivymd.uix.tab.MDTabs +#:import MDProgressBar kivymd.uix.progressbar.MDProgressBar +#:import MDAccordion kivymd.uix.accordion.MDAccordion +#:import MDAccordionItem kivymd.uix.accordion.MDAccordionItem +#:import MDAccordionSubItem kivymd.uix.accordion.MDAccordionSubItem +#:import MDFloatingActionButton kivymd.uix.button.MDFloatingActionButton #:import Factory kivy.factory.Factory -#:import MDTextButton kivymd.button.MDTextButton +#:import MDTextButton kivymd.uix.button.MDTextButton #:import FadeTransition kivy.uix.screenmanager.FadeTransition -#:import MDScrollViewRefreshLayout kivymd.refreshlayout.MDScrollViewRefreshLayout +#:import MDScrollViewRefreshLayout kivymd.uix.refreshlayout.MDScrollViewRefreshLayout #:set color_button (0.784, 0.443, 0.216, 1) # brown #:set color_button_pressed (0.659, 0.522, 0.431, 1) # darker brown @@ -176,7 +171,7 @@ NavigationLayout: BoxLayout: id: box_layout orientation: 'vertical' - Toolbar: + MDToolbar: id: toolbar title: app.current_address_label() opacity: 1 if app.addressexist() else 0 @@ -342,7 +337,7 @@ NavigationLayout: size_hint: .6, .35 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: root.available_credits font_size: '13sp' color: (1,1,1,1) @@ -423,7 +418,7 @@ NavigationLayout: height: dp(40) on_press: root.reset_composer() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'reset' font_size: '13sp' color: (1,1,1,1) @@ -521,7 +516,7 @@ NavigationLayout: height: dp(40) on_press: app.root.ids.scr_mngr.current = 'random' MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'proceed' font_size: '13sp' color: (1,1,1,1) @@ -566,7 +561,7 @@ NavigationLayout: on_release: root.generateaddress(app) opposite_colors: True MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'next' font_size: '13sp' color: (1,1,1,1) @@ -594,7 +589,7 @@ NavigationLayout: size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Server' font_size: '13sp' color: (1,1,1,1) @@ -607,7 +602,7 @@ NavigationLayout: size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Import or export data' font_size: '13sp' color: (1,1,1,1) @@ -620,7 +615,7 @@ NavigationLayout: size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Restart background service' font_size: '13sp' color: (1,1,1,1) @@ -698,20 +693,20 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'Platinum' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: 'We provide subscriptions for proof of work calculation for first month. ' halign: 'center' color: 1,1,1,1 MDLabel: id: free_pak - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: '€ 50.0' halign: 'center' @@ -727,7 +722,7 @@ NavigationLayout: height: dp(40) on_press: root.get_available_credits(self) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Get Free Credits' font_size: '13sp' color: (0,0,0,1) @@ -744,19 +739,19 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'Silver' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: 'We provide for proof of work calculation for six month. ' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: '€ 100.0' halign: 'center' @@ -771,7 +766,7 @@ NavigationLayout: size_hint: 1, None height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Get Monthly Credits' font_size: '13sp' color: (0,0,0,1) @@ -788,19 +783,19 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'Gold' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: 'We provide for proof of work calculation for 1years. ' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: '€ 500.0' halign: 'center' @@ -815,7 +810,7 @@ NavigationLayout: size_hint: 1, None height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Get Yearly Credits' font_size: '13sp' color: (0,0,0,1) @@ -862,7 +857,7 @@ NavigationLayout: on_release: root.savecontact() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Save' font_size: '13sp' color: (1,1,1,1) @@ -873,7 +868,7 @@ NavigationLayout: on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) @@ -882,7 +877,7 @@ NavigationLayout: size_hint: 2, None height: dp(40) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Scan QR code' font_size: '13sp' color: (1,1,1,1) @@ -891,93 +886,8 @@ NavigationLayout: : name: 'networkstat' - MDTabbedPanel: - id: tab_panel - tab_display_mode:'text' - - MDTab: - name: 'connections' - text: "Total connections" - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(200) - OneLineListItem: - text: "Total Connections" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .6, .35 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_1 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDTab: - name: 'processes' - text: 'Processes' - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(500) - OneLineListItem: - text: "person-to-person" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_2 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "Brodcast" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_3 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "publickeys" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_4 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "objects" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .6 - height: dp(40) - MDLabel: - font_style: 'Title' - text: root.text_variable_5 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' + Label: + text:"surbhi" : name: 'mailDetail' @@ -989,31 +899,31 @@ NavigationLayout: height: dp(500) + self.minimum_height padding: dp(32) MDLabel: - font_style: 'Headline' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: root.subject halign: 'left' font_size: '20sp' CopyTextBtn: MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: "From: " + root.from_addr halign: 'left' CopyTextBtn: MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: "To: " + root.to_addr halign: 'left' CopyTextBtn: MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.status halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.message halign: 'left' @@ -1072,25 +982,25 @@ NavigationLayout: spacing:dp(25) MDLabel: id: myaddr_label - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Label" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.address_label font_size: '15sp' halign: 'left' MDLabel: - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Address" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.address font_size: '15sp' @@ -1104,7 +1014,7 @@ NavigationLayout: height: dp(40) on_press: root.send_message_from() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Send message from' font_size: '13sp' color: (1,1,1,1) @@ -1116,7 +1026,7 @@ NavigationLayout: on_press: app.root.ids.scr_mngr.current = 'showqrcode' on_press: app.root.ids.sc15.qrdisplay() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Show QR code' font_size: '13sp' color: (1,1,1,1) @@ -1127,7 +1037,7 @@ NavigationLayout: on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) @@ -1151,14 +1061,14 @@ NavigationLayout: orientation: 'vertical' spacing:dp(20) MDLabel: - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Label" font_size: '17sp' halign: 'left' MDTextField: id: add_label - font_style: 'Subhead' + font_style: 'H4' font_size: '15sp' halign: 'left' text: root.address_label @@ -1166,13 +1076,13 @@ NavigationLayout: required: True helper_text_mode: "on_error" MDLabel: - font_style: 'Title' + font_style: 'H4' theme_text_color: 'Primary' text: "Address" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'Subhead' + font_style: 'H4' theme_text_color: 'Primary' text: root.address font_size: '15sp' @@ -1186,7 +1096,7 @@ NavigationLayout: height: dp(40) on_press: root.send_message_to() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Send message to' font_size: '13sp' color: (1,1,1,1) @@ -1197,7 +1107,7 @@ NavigationLayout: font_size: '10sp' on_press: root.update_addbook_label(root.address) MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Save' font_size: '13sp' color: (1,1,1,1) @@ -1208,7 +1118,7 @@ NavigationLayout: on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'Title' + font_style: 'H4' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 70f51b29..6f7b1cc6 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -35,27 +35,31 @@ from kivy.uix.screenmanager import Screen from kivy.uix.spinner import Spinner from kivy.uix.textinput import TextInput from kivy.utils import platform -import kivy_helper_search -from kivymd.button import MDIconButton -from kivymd.dialog import MDDialog -from kivymd.label import MDLabel -from kivymd.list import ( +from bitmessagekivy import kivy_helper_search +from kivymd.uix.dialog import MDDialog +from kivymd.uix.button import MDIconButton +from kivymd.uix.label import MDLabel +from kivymd.uix.list import ( ILeftBody, ILeftBodyTouch, IRightBodyTouch, TwoLineAvatarIconListItem, TwoLineListItem) -from kivymd.navigationdrawer import ( +from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, NavigationDrawerHeaderBase) -from kivymd.selectioncontrols import MDCheckbox +from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.theming import ThemeManager import queues from semaphores import kivyuisignaler import state -from uikivysignaler import UIkivySignaler -import identiconGeneration +from bitmessagekivy.uikivysignaler import UIkivySignaler +# pylint: disable=unused-argument, too-few-public-methods, import-error + +from bitmessagekivy import identiconGeneration +import os +from kivy.core.clipboard import Clipboard # pylint: disable=unused-argument, too-few-public-methods @@ -89,7 +93,7 @@ class Inbox(Screen): def init_ui(self, dt=0): """Clock Schdule for method inbox accounts.""" self.inboxaccounts() - print dt + print (dt) def inboxaccounts(self): """Load inbox accounts.""" @@ -329,7 +333,7 @@ class AddressBook(Screen): def init_ui(self, dt=0): """Clock Schdule for method AddressBook.""" self.loadAddresslist(None, 'All', '') - print dt + print (dt) def loadAddresslist(self, account, where="", what=""): """Clock Schdule for method AddressBook.""" @@ -428,7 +432,7 @@ class SelectableLabel(RecycleDataViewBehavior, Label): """Respond to the selection of items in the view.""" self.selected = is_selected if is_selected: - print "selection changed to {0}".format(rv.data[index]) + print("selection changed to {0}".format(rv.data[index])) rv.parent.txt_input.text = rv.parent.txt_input.text.replace( rv.parent.txt_input.text, rv.data[index]['text']) @@ -455,7 +459,7 @@ class DropDownWidget(BoxLayout): subject = self.ids.subject.text.encode('utf-8').strip() message = self.ids.body.text.encode('utf-8').strip() encoding = 3 - print "message: ", self.ids.body.text + print ("message: ", self.ids.body.text) sendMessageToPeople = True if sendMessageToPeople: if toAddress != '' and subject and message: @@ -483,12 +487,12 @@ class DropDownWidget(BoxLayout): 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" + print("streamNumber > 1 or streamNumber == 0") if statusIconColor == 'red': - print "shared.statusIconColor == 'red'" + print("shared.statusIconColor == 'red'") stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') from helper_ackPayload import genAckPayload @@ -523,7 +527,7 @@ class DropDownWidget(BoxLayout): toLabel = '' queues.workerQueue.put(('sendmessage', toAddress)) - print "sqlExecute successfully #######################" + print ("sqlExecute successfully #######################") self.parent.parent.current = 'inbox' state.in_composer = True navApp.back_press() @@ -718,7 +722,7 @@ class Sent(Screen): def init_ui(self, dt=0): """Clock Schdule for method sent accounts.""" self.sentaccounts() - print dt + print(dt) def sentaccounts(self): """Load sent accounts.""" @@ -1088,7 +1092,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods if not os.path.exists(directory): os.makedirs(directory) except OSError: - print 'Error: Creating directory. ' + directory + print('Error: Creating directory. ' + directory) @staticmethod def get_default_image(): @@ -1179,7 +1183,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods @staticmethod def on_stop(): """On stop methos is used for stoping the runing script.""" - print "*******************EXITING FROM APPLICATION*******************" + print("*******************EXITING FROM APPLICATION*******************") import shutdown shutdown.doCleanShutdown() @@ -1633,7 +1637,7 @@ class Draft(Screen): def init_ui(self, dt=0): """Clock Schdule for method draft accounts.""" self.sentaccounts() - print dt + print (dt) def sentaccounts(self): """Load draft accounts.""" @@ -1801,7 +1805,7 @@ class Allmails(Screen): def init_ui(self, dt=0): """Clock Schdule for method all mails.""" self.mailaccounts() - print dt + print (dt) def mailaccounts(self): """Load all mails for account.""" diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index e066dd06..6e8206ef 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -200,6 +200,7 @@ class Main: # pylint: disable=no-init, old-style-class from plugins.plugin import get_plugin try: proxyconfig_start = time.time() + import pdb;pdb.set_trace if not get_plugin('proxyconfig', name=proxy_type)(config): raise TypeError except TypeError: @@ -358,7 +359,7 @@ class Main: # pylint: disable=no-init, old-style-class # Not needed if objproc disabled if state.enableObjProc: shared.reloadMyAddressHashes() - shared.reloadBroadcastSendersForWhichImWatching() + # shared.reloadBroadcastSendersForWhichImWatching() # API is also objproc dependent if config.safeGetBoolean('bitmessagesettings', 'apienabled'): import api # pylint: disable=relative-import @@ -373,7 +374,7 @@ class Main: # pylint: disable=no-init, old-style-class asyncoreThread = BMNetworkThread() asyncoreThread.daemon = True asyncoreThread.start() - for i in range(config.getint('threads', 'receive')): + for i in range(config.safeGet('threads', 'receive')): receiveQueueThread = ReceiveQueueThread(i) receiveQueueThread.daemon = True receiveQueueThread.start() diff --git a/src/helper_startup.py b/src/helper_startup.py index 0d3523e3..f0457638 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -25,6 +25,7 @@ StoreConfigFilesInSameDirectoryAsProgramByDefault = False def _loadTrustedPeer(): + trustedPeer = '' try: trustedPeer = BMConfigParser().get('bitmessagesettings', 'trustedpeer') except configparser.Error: @@ -32,13 +33,15 @@ def _loadTrustedPeer(): # can just leave it as None return try: - host, port = trustedPeer.split(':') + # import pdb;pdb.set_trace() + if trustedPeer != None: + host, port = trustedPeer.split(':') + state.trustedPeer = state.Peer(host, int(port)) except ValueError: sys.exit( 'Bad trustedpeer config setting! It should be set as' ' trustedpeer=:' ) - state.trustedPeer = state.Peer(host, int(port)) def loadConfig(): diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index c235072c..648e11a7 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -16,8 +16,9 @@ def makeCryptor(privkey): # import pdb;pdb.set_trace() private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) - privkey_bin = '\x02\xca\x00\x20' + private_key - pubkey_bin = '\x02\xca\x00\x20' + public_key[1:-32].decode() + '\x00\x20' + public_key[-32:].decode() + privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key + pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] + import pdb;pdb.set_trace() cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/knownnodes.py b/src/knownnodes.py index b30ca770..35d105bc 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -55,6 +55,7 @@ def json_deserialize_knownnodes(source): Read JSON from source and make knownnodes dict """ global knownNodesActual # pylint: disable=global-statement + # import pdb;pdb.set_trace() for node in json.load(source): peer = node['peer'] info = node['info'] @@ -107,7 +108,7 @@ def createDefaultKnownNodes(): def readKnownNodes(): try: - with open(state.appdata + 'knownnodes.dat', 'rb') as source: + with open(state.appdata + 'knownnodes.dat', 'r') as source: with knownNodesLock: try: json_deserialize_knownnodes(source) diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index a50d83b6..313f3924 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -274,10 +274,15 @@ class BMConnectionPool(object): continue self.lastSpawned = time.time() + + print('++++++++++++++++++++++++++++++++++++++++++') + print('self.inboundConnections.values()-{}'.format(self.inboundConnections.values())) + print('self.outboundConnections.values() -{}'.format(self.outboundConnections.values())) + print('+++++++++++++++++++++++++++++++++++++++++++') else: for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + list(self.inboundConnections.values()) + + list(self.outboundConnections.values()) ): # FIXME: rating will be increased after next connection i.handle_close() diff --git a/src/network/stats.py b/src/network/stats.py index 7b9a1e0d..31ffcbf3 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -4,7 +4,7 @@ src/network/stats.py """ import time -import asyncore_pollchoose as asyncore +from network import asyncore_pollchoose as asyncore from network.connectionpool import BMConnectionPool from network.objectracker import missingObjects @@ -20,8 +20,9 @@ currentSentSpeed = 0 def connectedHostsList(): """List of all the connected hosts""" retval = [] - for i in BMConnectionPool().inboundConnections.values() + \ - BMConnectionPool().outboundConnections.values(): + # import pdb;pdb.set_trace() + for i in list(BMConnectionPool().inboundConnections.values()) + \ + list(BMConnectionPool().outboundConnections.values()): if not i.fullyEstablished: continue try: diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 43166006..7b7a477b 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -30,7 +30,9 @@ def get_code_string(base): elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" elif base == 256: - return ''.join([chr(x) for x in range(256)]) + '''raw_unicode_escape is used because in the python3 after range(161) its genreate the' + the speical character so avoiding that function we have used the raw_unicode method ''' + return ''.join([chr(x) for x in range(256)]).encode('raw_unicode_escape') else: raise ValueError("Invalid base!") @@ -38,9 +40,16 @@ def get_code_string(base): def encode(val, base, minlen=0): code_string = get_code_string(base) result = "" + result = str.encode(result) + count = 0 + # import pdb;pdb.set_trace() while val > 0: - result = code_string[round(val % base)] + result - val /= base + count += 1 + # import pdb;pdb.set_trace() + result = code_string[int(val) % base:int(val) % base + 1] + result + # print('the value of the result-{}'.format(result)) + val = int(val / base) + # import pdb;pdb.set_trace() if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result return result @@ -48,10 +57,12 @@ def encode(val, base, minlen=0): def decode(string, base): code_string = get_code_string(base) + string.decode() result = 0 if base == 16: string = string.lower() while string: + # import pdb;pdb.set_trace() result *= base result += code_string.find(string.decode()[0]) string = string[1:] @@ -59,6 +70,7 @@ def decode(string, base): def changebase(string, frm, to, minlen=0): + # import pdb;pdb.set_trace() return encode(decode(string, frm), to, minlen) diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index 14adca42..63748287 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -74,11 +74,13 @@ class ECC(object): if curve != curve2: raise Exception("Bad ECC keys ...") self.curve = curve + import pdb;pdb.set_trace() self._set_keys(pubkey_x, pubkey_y, raw_privkey) else: self.privkey, self.pubkey_x, self.pubkey_y = self._generate() def _set_keys(self, pubkey_x, pubkey_y, privkey): + import pdb;pdb.set_trace() if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: self.pubkey_x = None self.pubkey_y = None @@ -114,7 +116,7 @@ class ECC(object): pack('!H', len(self.pubkey_x)), self.pubkey_x, pack('!H', len(self.pubkey_y)), - self.pubkey_y, + self.pubkey_y, )) def get_privkey(self): @@ -129,27 +131,37 @@ class ECC(object): )) @staticmethod - def _decode_pubkey( pubkey): - pubkey = pubkey.encode() + def _decode_pubkey(pubkey): + # pubkey = pubkey.encode() + import pdb;pdb.set_trace() i = 0 - curve = unpack('!H', pubkey[i:i + 2])[0] + # curve = unpack('!H', pubkey[i:i + 2])[0] + curve = pack('!s', pubkey[i:i + 1])[0] + i += 2 - tmplen = unpack('!H', pubkey[i:i + 2])[0] + # tmplen = unpack('!H', pubkey[i:i + 2])[0] + tmplen = pack('!s', pubkey[i:i + 1])[0] i += 2 pubkey_x = pubkey[i:i + tmplen] - i += tmplen - tmplen = unpack('!H', pubkey[i:i + 2])[0] - i += 2 + # i += tmplen + i += int(tmplen / 3) + # tmplen = unpack('!H', pubkey[i:i + 2])[0] + tmplen = pack('!s', pubkey[i:i + 1])[0] + # i += 2 pubkey_y = pubkey[i:i + tmplen] - i += tmplen - return curve, pubkey_x, pubkey_y, i + # i += tmplen + return curve, pubkey_x, pubkey_y, int(i) @staticmethod def _decode_privkey(privkey): i = 0 - curve = unpack('!H', privkey[i:i + 2])[0] + # import pdb;pdb.set_trace() + # curve = unpack('!H', privkey[i:i + 2])[0] + curve = pack('!s', privkey[i:i + 1])[0] + i += 2 - tmplen = unpack('!H', privkey[i:i + 2])[0] + # tmplen = unpack('!H', privkey[i:i + 2])[0] + tmplen = pack('!s', privkey[i:i + 1])[0] i += 2 privkey = privkey[i:i + tmplen] i += tmplen @@ -276,6 +288,7 @@ class ECC(object): return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve) def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None): + import pdb;pdb.set_trace() """Check key validity, key is supplied as binary data""" # pylint: disable=too-many-branches if curve is None: diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 54913830..03265fd1 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -8,7 +8,7 @@ from threading import RLock from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute -from storage import InventoryStorage, InventoryItem +from storage.storage import InventoryStorage, InventoryItem class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors From c813f679ae82fc4b802c896b5d5f75cd8e21700f Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Thu, 3 Oct 2019 20:27:22 +0530 Subject: [PATCH 03/54] Solved bmconfigparser python3 incompatibility issue and removed unrequired comment and line of code which are added during python3 plotting --- src/addresses.py | 1 - src/bitmessagekivy/mpybit.py | 3 ++- src/bitmessagemain.py | 1 - src/bmconfigparser.py | 6 ++++-- src/helper_startup.py | 2 +- src/highlevelcrypto.py | 2 -- src/knownnodes.py | 2 -- src/network/asyncore_pollchoose.py | 1 - src/network/connectionpool.py | 2 +- src/network/dandelion.py | 18 +++++++++--------- src/network/downloadthread.py | 4 ++-- src/network/stats.py | 1 - src/network/uploadthread.py | 4 ++-- src/pyelliptic/arithmetic.py | 6 ------ src/pyelliptic/ecc.py | 27 +++++++-------------------- src/shared.py | 2 -- 16 files changed, 28 insertions(+), 54 deletions(-) diff --git a/src/addresses.py b/src/addresses.py index 4d200332..a55fc415 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -191,7 +191,6 @@ def decodeAddress(address): return status, 0, 0, '' # after converting to hex, the string will be prepended # with a 0x and appended with a L - # import pdb;pdb.set_trace() hexdata = hex(integer)[2:] if len(hexdata) % 2 != 0: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 6f7b1cc6..aa55d35b 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -93,7 +93,7 @@ class Inbox(Screen): def init_ui(self, dt=0): """Clock Schdule for method inbox accounts.""" self.inboxaccounts() - print (dt) + print(dt) def inboxaccounts(self): """Load inbox accounts.""" @@ -309,6 +309,7 @@ class MyAddress(Screen): self.init_ui() self.ids.refresh_layout.refresh_done() self.tick = 0 + Clock.schedule_once(refresh_callback, 1) @staticmethod diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 6e8206ef..dcf03118 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -200,7 +200,6 @@ class Main: # pylint: disable=no-init, old-style-class from plugins.plugin import get_plugin try: proxyconfig_start = time.time() - import pdb;pdb.set_trace if not get_plugin('proxyconfig', name=proxy_type)(config): raise TypeError except TypeError: diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 6f5660e0..d05787d9 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -125,10 +125,12 @@ class BMConfigParser(configparser.ConfigParser): try: if not self.validate( section, option, - configparser.ConfigParser.get(self, section, option) + self[section][option] ): try: newVal = BMConfigDefaults[section][option] + except configparser.NoSectionError: + continue except KeyError: continue configparser.ConfigParser.set( @@ -159,7 +161,7 @@ class BMConfigParser(configparser.ConfigParser): def validate(self, section, option, value): try: - return getattr(self, 'validate_%s_%s' % (section, option))(value) + return getattr(self, 'validate_{}_{}'.format(section, option))(value) except AttributeError: return True diff --git a/src/helper_startup.py b/src/helper_startup.py index f0457638..110110b6 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -33,7 +33,7 @@ def _loadTrustedPeer(): # can just leave it as None return try: - # import pdb;pdb.set_trace() + if trustedPeer != None: host, port = trustedPeer.split(':') state.trustedPeer = state.Peer(host, int(port)) diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 648e11a7..512c55b5 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -13,12 +13,10 @@ from pyelliptic import arithmetic as a def makeCryptor(privkey): """Return a private pyelliptic.ECC() instance""" - # import pdb;pdb.set_trace() private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] - import pdb;pdb.set_trace() cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/knownnodes.py b/src/knownnodes.py index 35d105bc..4052e3ae 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -46,7 +46,6 @@ def json_serialize_knownnodes(output): _serialized.append({ 'stream': stream, 'peer': peer._asdict(), 'info': info }) - # import pdb;pdb.set_trace() json.dump(_serialized, output, indent=4) @@ -55,7 +54,6 @@ def json_deserialize_knownnodes(source): Read JSON from source and make knownnodes dict """ global knownNodesActual # pylint: disable=global-statement - # import pdb;pdb.set_trace() for node in json.load(source): peer = node['peer'] info = node['info'] diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 3137797c..1c93283f 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -767,7 +767,6 @@ class dispatcher: # references to the underlying socket object. def __getattr__(self, attr): try: - # import pdb;pdb.set_trace() retattr = getattr(self.socket, attr) except AttributeError: raise AttributeError("{} instance has no attribute {}" diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 313f3924..adc8cf51 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -236,7 +236,7 @@ class BMConnectionPool(object): except ValueError: Proxy.onion_proxy = None established = sum( - 1 for c in self.outboundConnections.values() + 1 for c in list(self.outboundConnections.values()) if (c.connected and c.fullyEstablished)) pending = len(self.outboundConnections) - established if established < BMConfigParser().safeGetInt( diff --git a/src/network/dandelion.py b/src/network/dandelion.py index abba16ba..e51df5d1 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -99,12 +99,12 @@ class Dandelion(): # pylint: disable=old-style-class with self.lock: if len(self.stem) < MAX_STEMS: self.stem.append(connection) - for k in (k for k, v in self.nodeMap.iteritems() if v is None): + for k in (k for k, v in iter(self.nodeMap.items()) if v is None): self.nodeMap[k] = connection - for k, v in { - k: v for k, v in self.hashMap.iteritems() + for k, v in iter({ + k: v for k, v in iter(self.hashMap.items()) if v.child is None - }.iteritems(): + }).items(): self.hashMap[k] = Stem( connection, v.stream, self.poissonTimeout()) invQueue.put((v.stream, k, v.child)) @@ -120,13 +120,13 @@ class Dandelion(): # pylint: disable=old-style-class self.stem.remove(connection) # active mappings to pointing to the removed node for k in ( - k for k, v in self.nodeMap.iteritems() if v == connection + k for k, v in iter(self.nodeMap.items()) if v == connection ): self.nodeMap[k] = None - for k, v in { - k: v for k, v in self.hashMap.iteritems() + for k, v in iter({ + k: v for k, v in iter(self.hashMap.items()) if v.child == connection - }.iteritems(): + }).items(): self.hashMap[k] = Stem( None, v.stream, self.poissonTimeout()) @@ -167,7 +167,7 @@ class Dandelion(): # pylint: disable=old-style-class with self.lock: deadline = time() toDelete = [ - [v.stream, k, v.child] for k, v in self.hashMap.iteritems() + [v.stream, k, v.child] for k, v in iter(self.hashMap.items()) if v.timeout < deadline ] diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index a09d0c1d..561fd342 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -32,7 +32,7 @@ class DownloadThread(StoppableThread): """Expire pending downloads eventually""" deadline = time.time() - DownloadThread.requestExpires try: - toDelete = [k for k, v in missingObjects.iteritems() if v < deadline] + toDelete = [k for k, v in iter(missingObjects.items()) if v < deadline] except RuntimeError: pass else: @@ -46,7 +46,7 @@ class DownloadThread(StoppableThread): # Choose downloading peers randomly connections = [ x for x in - BMConnectionPool().inboundConnections.values() + BMConnectionPool().outboundConnections.values() + list(BMConnectionPool().inboundConnections.values()) + list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished] helper_random.randomshuffle(connections) try: diff --git a/src/network/stats.py b/src/network/stats.py index 31ffcbf3..1a57629d 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -20,7 +20,6 @@ currentSentSpeed = 0 def connectedHostsList(): """List of all the connected hosts""" retval = [] - # import pdb;pdb.set_trace() for i in list(BMConnectionPool().inboundConnections.values()) + \ list(BMConnectionPool().outboundConnections.values()): if not i.fullyEstablished: diff --git a/src/network/uploadthread.py b/src/network/uploadthread.py index 1b06af23..a0329c83 100644 --- a/src/network/uploadthread.py +++ b/src/network/uploadthread.py @@ -26,8 +26,8 @@ class UploadThread(StoppableThread): while not self._stopped: uploaded = 0 # Choose downloading peers randomly - connections = [x for x in BMConnectionPool().inboundConnections.values() + - BMConnectionPool().outboundConnections.values() if x.fullyEstablished] + connections = [x for x in list(BMConnectionPool().inboundConnections.values()) + + list(BMConnectionPool().outboundConnections.values()) if x.fullyEstablished] helper_random.randomshuffle(connections) for i in connections: now = time.time() diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 7b7a477b..f5106768 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -42,14 +42,10 @@ def encode(val, base, minlen=0): result = "" result = str.encode(result) count = 0 - # import pdb;pdb.set_trace() while val > 0: count += 1 - # import pdb;pdb.set_trace() result = code_string[int(val) % base:int(val) % base + 1] + result - # print('the value of the result-{}'.format(result)) val = int(val / base) - # import pdb;pdb.set_trace() if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result return result @@ -62,7 +58,6 @@ def decode(string, base): if base == 16: string = string.lower() while string: - # import pdb;pdb.set_trace() result *= base result += code_string.find(string.decode()[0]) string = string[1:] @@ -70,7 +65,6 @@ def decode(string, base): def changebase(string, frm, to, minlen=0): - # import pdb;pdb.set_trace() return encode(decode(string, frm), to, minlen) diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index 63748287..f0cba579 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -74,13 +74,11 @@ class ECC(object): if curve != curve2: raise Exception("Bad ECC keys ...") self.curve = curve - import pdb;pdb.set_trace() self._set_keys(pubkey_x, pubkey_y, raw_privkey) else: self.privkey, self.pubkey_x, self.pubkey_y = self._generate() def _set_keys(self, pubkey_x, pubkey_y, privkey): - import pdb;pdb.set_trace() if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: self.pubkey_x = None self.pubkey_y = None @@ -132,35 +130,25 @@ class ECC(object): @staticmethod def _decode_pubkey(pubkey): - # pubkey = pubkey.encode() - import pdb;pdb.set_trace() i = 0 - # curve = unpack('!H', pubkey[i:i + 2])[0] - curve = pack('!s', pubkey[i:i + 1])[0] - + curve = unpack('!H', pubkey[i:i + 2])[0] i += 2 - # tmplen = unpack('!H', pubkey[i:i + 2])[0] - tmplen = pack('!s', pubkey[i:i + 1])[0] + tmplen = unpack('!H', pubkey[i:i + 2])[0] i += 2 pubkey_x = pubkey[i:i + tmplen] - # i += tmplen + i += tmplen i += int(tmplen / 3) - # tmplen = unpack('!H', pubkey[i:i + 2])[0] - tmplen = pack('!s', pubkey[i:i + 1])[0] - # i += 2 + tmplen = unpack('!H', pubkey[i:i + 2])[0] + i += 2 pubkey_y = pubkey[i:i + tmplen] - # i += tmplen + i += tmplen return curve, pubkey_x, pubkey_y, int(i) @staticmethod def _decode_privkey(privkey): i = 0 - # import pdb;pdb.set_trace() - # curve = unpack('!H', privkey[i:i + 2])[0] - curve = pack('!s', privkey[i:i + 1])[0] - + curve = unpack('!H', privkey[i:i + 2])[0] i += 2 - # tmplen = unpack('!H', privkey[i:i + 2])[0] tmplen = pack('!s', privkey[i:i + 1])[0] i += 2 privkey = privkey[i:i + tmplen] @@ -288,7 +276,6 @@ class ECC(object): return self.raw_check_key(raw_privkey, pubkey_x, pubkey_y, curve) def raw_check_key(self, privkey, pubkey_x, pubkey_y, curve=None): - import pdb;pdb.set_trace() """Check key validity, key is supplied as binary data""" # pylint: disable=too-many-branches if curve is None: diff --git a/src/shared.py b/src/shared.py index 2a53452a..60c35096 100644 --- a/src/shared.py +++ b/src/shared.py @@ -174,11 +174,9 @@ def reloadBroadcastSendersForWhichImWatching(): # Now, for all addresses, even version 2 addresses, # we should create Cryptor objects in a dictionary which we will # use to attempt to decrypt encrypted broadcast messages. - # import pdb;pdb.set_trace() if addressVersionNumber <= 3: privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \ + encodeVarint(streamNumber) + hash)).digest()[:32] - # import pdb;pdb.set_trace() MyECSubscriptionCryptorObjects[hash] = \ highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) else: From 95990d8deff7fa205dfde9b37cc260f8258eeb8d Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Wed, 9 Oct 2019 18:21:29 +0530 Subject: [PATCH 04/54] Solved new address creations issues --- src/addresses.py | 5 +++-- src/bitmessagekivy/main.kv | 24 ------------------------ src/class_addressGenerator.py | 8 ++++---- src/class_singleCleaner.py | 4 ++-- src/network/bmproto.py | 2 +- src/network/connectionpool.py | 12 ++++++------ src/network/dandelion.py | 6 +++--- src/network/tcp.py | 2 +- src/protocol.py | 4 ++-- src/pyelliptic/arithmetic.py | 9 +++++---- src/shared.py | 2 +- 11 files changed, 28 insertions(+), 50 deletions(-) diff --git a/src/addresses.py b/src/addresses.py index a55fc415..c0903841 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -158,7 +158,7 @@ def encodeAddress(version, stream, ripe): raise Exception( 'Programming error in encodeAddress: The length of' ' a given ripe hash was not 20.') - ripe = ripe.lstrip('\x00') + ripe = ripe.lstrip('\x00'.encode('utf-8')) storedBinaryData = encodeVarint(version) + encodeVarint(stream) + ripe @@ -264,7 +264,8 @@ def decodeAddress(address): return 'ripetoolong', 0, 0, '' elif len(embeddedRipeData) < 4: return 'ripetooshort', 0, 0, '' - x00string = '\x00' * (20 - len(embeddedRipeData)) + x00string = '\x00'.encode('utf-8') * (20 - len(embeddedRipeData)) + return status, addressVersionNumber, streamNumber, \ x00string + embeddedRipeData diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 18f1ac6a..93d12393 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -334,7 +334,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .35 height: dp(40) MDLabel: font_style: 'H4' @@ -383,7 +382,6 @@ NavigationLayout: txt_input: txt_input rv: rv size : (890, 60) - size_hint: 1,1 MyTextInput: id: txt_input size_hint_y: None @@ -414,7 +412,6 @@ NavigationLayout: spacing:50 AnchorLayout: MDRaisedButton: - size_hint: 1, None height: dp(40) on_press: root.reset_composer() MDLabel: @@ -512,7 +509,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .5, .35 height: dp(40) on_press: app.root.ids.scr_mngr.current = 'random' MDLabel: @@ -556,7 +552,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .5, None height: dp(40) on_release: root.generateaddress(app) opposite_colors: True @@ -586,7 +581,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .55 height: dp(40) MDLabel: font_style: 'H4' @@ -599,7 +593,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .55 height: dp(40) MDLabel: font_style: 'H4' @@ -612,7 +605,6 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: - size_hint: .6, .55 height: dp(40) MDLabel: font_style: 'H4' @@ -633,7 +625,6 @@ NavigationLayout: BoxLayout: MDCheckbox: id: chkbox - size_hint: None, None size: dp(48), dp(64) active: True MDLabel: @@ -718,7 +709,6 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size - size_hint: 1, None height: dp(40) on_press: root.get_available_credits(self) MDLabel: @@ -763,7 +753,6 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size - size_hint: 1, None height: dp(40) MDLabel: font_style: 'H4' @@ -807,7 +796,6 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size - size_hint: 1, None height: dp(40) MDLabel: font_style: 'H4' @@ -819,7 +807,6 @@ NavigationLayout: : id: popup - size_hint : (None,None) height: 2*(label.height + address.height) + 10 width :app.window_size[0] - app.window_size[0]/10 title: 'add contact\'s' @@ -852,7 +839,6 @@ NavigationLayout: orientation: 'horizontal' MDRaisedButton: id: save_addr - size_hint: 1.5, None height: dp(40) on_release: root.savecontact() @@ -863,7 +849,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() @@ -874,7 +859,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 2, None height: dp(40) MDLabel: font_style: 'H4' @@ -965,7 +949,6 @@ 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 background: './images/popup.jpeg' @@ -1010,7 +993,6 @@ NavigationLayout: spacing:5 orientation: 'horizontal' MDRaisedButton: - size_hint: 2, None height: dp(40) on_press: root.send_message_from() MDLabel: @@ -1020,7 +1002,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: app.root.ids.scr_mngr.current = 'showqrcode' @@ -1032,7 +1013,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() @@ -1045,7 +1025,6 @@ NavigationLayout: : id: addbook_popup - size_hint : (None,None) height: 4*(add_label.height) width :app.window_size[0] - app.window_size[0]/10 background: './images/popup.jpeg' @@ -1092,7 +1071,6 @@ NavigationLayout: spacing:5 orientation: 'horizontal' MDRaisedButton: - size_hint: 2, None height: dp(40) on_press: root.send_message_to() MDLabel: @@ -1102,7 +1080,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) font_size: '10sp' on_press: root.update_addbook_label(root.address) @@ -1113,7 +1090,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' MDRaisedButton: - size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index b5c0cbcd..e4bf1d13 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -29,7 +29,6 @@ class addressGenerator(StoppableThread): super(addressGenerator, self).stopThread() def run(self): - while state.shutdown == 0: queueValue = queues.addressGeneratorQueue.get() nonceTrialsPerByte = 0 @@ -134,7 +133,7 @@ class addressGenerator(StoppableThread): ripe = RIPEMD160Hash(sha.digest()).digest() if ( ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == - '\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash + '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash ): break logger.info( @@ -151,19 +150,20 @@ class addressGenerator(StoppableThread): # The user must have a pretty fast computer. # time.time() - startTime equaled zero. pass + address = encodeAddress( addressVersionNumber, streamNumber, ripe) # An excellent way for us to store our keys # is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format - privSigningKey = '\x80' + potentialPrivSigningKey + privSigningKey = '\x80'.encode('utf-8') + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) - privEncryptionKey = '\x80' + potentialPrivEncryptionKey + privEncryptionKey = '\x80'.encode('utf-8') + potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index 9a2916c7..de7508ef 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -143,8 +143,8 @@ class singleCleaner(StoppableThread): # inv/object tracking for connection in \ - BMConnectionPool().inboundConnections.values() + \ - BMConnectionPool().outboundConnections.values(): + list(BMConnectionPool().inboundConnections.values()) + \ + list(BMConnectionPool().outboundConnections.values()): connection.clean() # discovery tracking diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 813d5b97..cfd6672f 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -86,7 +86,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): """Process incoming header""" self.magic, self.command, self.payloadLength, self.checksum = \ protocol.Header.unpack(self.read_buf[:protocol.Header.size]) - self.command = self.command.rstrip('\x00') + self.command = self.command.rstrip('\x00'.encode('utf-8')) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync self.set_state("bm_header", length=1) diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index adc8cf51..aad45e59 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -328,8 +328,8 @@ class BMConnectionPool(object): reaper = [] for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + list(self.inboundConnections.values()) + + list(self.outboundConnections.values()) ): minTx = time.time() - 20 if i.fullyEstablished: @@ -342,10 +342,10 @@ class BMConnectionPool(object): time.time() - i.lastTx) i.set_state("close") for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + - self.listeningSockets.values() + - self.udpSockets.values() + list(self.inboundConnections.values()) + + list(self.outboundConnections.values()) + + list(self.listeningSockets.values()) + + list(self.udpSockets.values()) ): if not (i.accepting or i.connecting or i.connected): reaper.append(i) diff --git a/src/network/dandelion.py b/src/network/dandelion.py index e51df5d1..2c23da5d 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -7,7 +7,7 @@ from random import choice, sample, expovariate from threading import RLock from time import time -import network.connectionpool +from network import connectionpool import state from debug import logging from queues import invQueue @@ -182,8 +182,8 @@ class Dandelion(): # pylint: disable=old-style-class try: # random two connections self.stem = sample( - connectionpool.BMConnectionPool( - ).outboundConnections.values(), MAX_STEMS) + list(connectionpool.BMConnectionPool( + ).outboundConnections.values()), MAX_STEMS) # not enough stems available except ValueError: self.stem = connectionpool.BMConnectionPool( diff --git a/src/network/tcp.py b/src/network/tcp.py index 31346e22..3ed19462 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -362,7 +362,7 @@ class TCPServer(AdvancedDispatcher): """TCP connection server for Bitmessage protocol""" def __init__(self, host='127.0.0.1', port=8444): - if not hasattr(self, '_map'): + if not '_map' in dir(self): AdvancedDispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() diff --git a/src/protocol.py b/src/protocol.py index 1031b950..abb310db 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -94,9 +94,9 @@ def isBitSetWithinBitfield(fourByteString, n): def encodeHost(host): """Encode a given host to be used in low-level socket operations""" if host.find('.onion') > -1: - return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True) + return '\xfd\x87\xd8\x7e\xeb\x43'.encode('utf-8') + base64.b32decode(host.split(".")[0], True) elif host.find(':') == -1: - return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ + return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('utf-8') + \ socket.inet_aton(host) return socket.inet_pton(socket.AF_INET6, host) diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index f5106768..1c9dcec4 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -39,11 +39,13 @@ def get_code_string(base): def encode(val, base, minlen=0): code_string = get_code_string(base) - result = "" - result = str.encode(result) + result = '' + # result = str.encode(result) count = 0 while val > 0: count += 1 + print(f'code_string[int(val) % base:int(val) % base + 1] -{code_string[int(val) % base:int(val) % base + 1]}') + print(f'result-{result}') result = code_string[int(val) % base:int(val) % base + 1] + result val = int(val / base) if len(result) < minlen: @@ -53,13 +55,12 @@ def encode(val, base, minlen=0): def decode(string, base): code_string = get_code_string(base) - string.decode() result = 0 if base == 16: string = string.lower() while string: result *= base - result += code_string.find(string.decode()[0]) + result += code_string.find(string[0]) string = string[1:] return result diff --git a/src/shared.py b/src/shared.py index 60c35096..8cd86e6c 100644 --- a/src/shared.py +++ b/src/shared.py @@ -125,7 +125,7 @@ def reloadMyAddressHashes(): keyfileSecure = checkSensitiveFilePermissions(state.appdata + 'keys.dat') hasEnabledKeys = False for addressInKeysFile in BMConfigParser().addresses(): - isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled') + isEnabled = BMConfigParser().safeGet(addressInKeysFile, 'enabled') if isEnabled: hasEnabledKeys = True # status From 66c00b61655e53bbeee73d3be32f099692742e13 Mon Sep 17 00:00:00 2001 From: navjot Date: Fri, 18 Oct 2019 19:30:43 +0530 Subject: [PATCH 05/54] Kivy fixes issue part 1 --- src/bitmessagekivy/main.kv | 214 ++++++++++++++++++++++++----------- src/bitmessagekivy/mpybit.py | 65 +++++------ 2 files changed, 181 insertions(+), 98 deletions(-) diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 93d12393..3afc794b 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -33,6 +33,9 @@ #:import MDTextButton kivymd.uix.button.MDTextButton #:import FadeTransition kivy.uix.screenmanager.FadeTransition #:import MDScrollViewRefreshLayout kivymd.uix.refreshlayout.MDScrollViewRefreshLayout +#:import MDTabsBase kivymd.uix.tab.MDTabsBase + + #:set color_button (0.784, 0.443, 0.216, 1) # brown #:set color_button_pressed (0.659, 0.522, 0.431, 1) # darker brown @@ -50,8 +53,7 @@ : drawer_logo: app.address_identicon() NavigationDrawerDivider: - - NavigationDrawerTwoLineListItem: + NavigationDrawerSubheader: text: "Accounts" NavigationDrawerIconButton: CustomSpinner: @@ -138,7 +140,7 @@ on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "Subscriptions/Payment" - icon:'wallet' + icon:'bell' on_release: app.root.ids.scr_mngr.current = 'payment' on_press: app.refreshScreen(self) NavigationDrawerIconButton: @@ -410,16 +412,6 @@ NavigationLayout: helper_text_mode: "on_error" BoxLayout: spacing:50 - AnchorLayout: - MDRaisedButton: - height: dp(40) - on_press: root.reset_composer() - MDLabel: - font_style: 'H4' - text: 'reset' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' : readonly: False @@ -465,19 +457,17 @@ NavigationLayout: padding: dp(10) BoxLayout: MDLabel: - font_style: 'Body1' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "You may generate addresses by using either random numbers or by using a passphrase If you use a passphrase, the address is called a deterministic; address The Random Number option is selected by default but deterministic addresses have several \n pros and cons:\n" halign: 'center' - bold: True color:app.theme_cls.primary_dark BoxLayout: MDLabel: - font_style: 'Caption' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "If talk about pros You can recreate your addresses on any computer from memory, You need-not worry about backing up your keys.dat file as long as you can remember your passphrase and aside talk about cons You must remember (or write down) your You must remember the address version number and the stream number along with your passphrase If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you" halign: 'center' - bold: True color:app.theme_cls.primary_dark MDCheckbox: id: grp_chkbox_1 @@ -485,12 +475,11 @@ NavigationLayout: active: True allow_no_selection: False MDLabel: - font_style: 'Caption' + font_style: 'Body2' theme_text_color: 'Primary' text: "use a random number generator to make an address" halign: 'center' size_hint_y: None - bold: True height: self.texture_size[1] + dp(4) color: [0.941, 0, 0,1] MDCheckbox: @@ -498,12 +487,11 @@ NavigationLayout: group: 'test' allow_no_selection: False MDLabel: - font_style: 'Caption' + font_style: 'Body2' theme_text_color: 'Primary' text: "use a pseudo number generator to make an address" halign: 'center' size_hint_y: None - bold: True color: [0.941, 0, 0,1] height: self.texture_size[1] + dp(4) BoxLayout: @@ -512,7 +500,7 @@ NavigationLayout: height: dp(40) on_press: app.root.ids.scr_mngr.current = 'random' MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'proceed' font_size: '13sp' color: (1,1,1,1) @@ -528,19 +516,17 @@ NavigationLayout: padding: dp(20) spacing: 100 MDLabel: - font_style: 'Body1' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "Random Addresses" halign: 'center' - bold: True color:app.theme_cls.primary_dark MDLabel: - font_style: 'Body1' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged" halign: 'center' - bold: True color:app.theme_cls.primary_dark MDTextField: @@ -556,7 +542,7 @@ NavigationLayout: on_release: root.generateaddress(app) opposite_colors: True MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'next' font_size: '13sp' color: (1,1,1,1) @@ -581,9 +567,10 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: + size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Server' font_size: '13sp' color: (1,1,1,1) @@ -593,9 +580,10 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: + size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Import or export data' font_size: '13sp' color: (1,1,1,1) @@ -605,9 +593,10 @@ NavigationLayout: BoxLayout: AnchorLayout: MDRaisedButton: + size_hint: .6, .55 height: dp(40) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Restart background service' font_size: '13sp' color: (1,1,1,1) @@ -619,12 +608,12 @@ NavigationLayout: theme_text_color: 'Primary' text: "bitmessage is 11 seconds behind the network" halign: 'center' - bold: True color: [0.941, 0, 0,1] BoxLayout: MDCheckbox: id: chkbox + size_hint: None, None size: dp(48), dp(64) active: True MDLabel: @@ -632,7 +621,6 @@ NavigationLayout: theme_text_color: 'Primary' text: "show settings (for advanced users only)" halign: 'left' - bold: True color: app.theme_cls.primary_dark : @@ -684,20 +672,20 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Subtitle1' + font_style: 'H5' theme_text_color: 'Primary' text: 'Platinum' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'H4' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'We provide subscriptions for proof of work calculation for first month. ' halign: 'center' color: 1,1,1,1 MDLabel: id: free_pak - font_style: 'Subtitle1' + font_style: 'H5' theme_text_color: 'Primary' text: '€ 50.0' halign: 'center' @@ -709,10 +697,11 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size + size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 height: dp(40) on_press: root.get_available_credits(self) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Get Free Credits' font_size: '13sp' color: (0,0,0,1) @@ -729,19 +718,19 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Subtitle1' + font_style: 'H5' theme_text_color: 'Primary' text: 'Silver' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'H4' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'We provide for proof of work calculation for six month. ' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subtitle1' + font_style: 'H5' theme_text_color: 'Primary' text: '€ 100.0' halign: 'center' @@ -753,9 +742,10 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size + size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 height: dp(40) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Get Monthly Credits' font_size: '13sp' color: (0,0,0,1) @@ -772,19 +762,19 @@ NavigationLayout: size: self.size MDLabel: size_hint_y: None - font_style: 'Subtitle1' + font_style: 'H5' theme_text_color: 'Primary' text: 'Gold' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'H4' + font_style: 'Subtitle1' theme_text_color: 'Primary' text: 'We provide for proof of work calculation for 1years. ' halign: 'center' color: 1,1,1,1 MDLabel: - font_style: 'Subtitle1' + font_style: 'H5' theme_text_color: 'Primary' text: '€ 500.0' halign: 'center' @@ -796,9 +786,10 @@ NavigationLayout: Rectangle: pos: self.pos size: self.size + size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 height: dp(40) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Get Yearly Credits' font_size: '13sp' color: (0,0,0,1) @@ -807,6 +798,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 title: 'add contact\'s' @@ -839,29 +831,32 @@ NavigationLayout: orientation: 'horizontal' MDRaisedButton: id: save_addr + size_hint: 1.5, None height: dp(40) on_release: root.savecontact() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Save' font_size: '13sp' color: (1,1,1,1) halign: 'center' MDRaisedButton: + size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) halign: 'center' MDRaisedButton: + size_hint: 2, None height: dp(40) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Scan QR code' font_size: '13sp' color: (1,1,1,1) @@ -870,8 +865,91 @@ NavigationLayout: : name: 'networkstat' - Label: - text:"surbhi" + MDTabs: + id: tab_panel + tab_display_mode:'text' + + Tab: + text: "Total connections" + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(200) + OneLineListItem: + text: "Total Connections" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .6, .3 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_1 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + Tab: + text: 'Processes' + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(500) + OneLineListItem: + text: "person-to-person" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_2 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "Brodcast" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_3 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "publickeys" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_4 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "objects" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_5 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' : name: 'mailDetail' @@ -949,6 +1027,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 background: './images/popup.jpeg' @@ -965,25 +1044,25 @@ NavigationLayout: spacing:dp(25) MDLabel: id: myaddr_label - font_style: 'H4' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "Label" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'H4' + font_style: 'Body1' theme_text_color: 'Primary' text: root.address_label font_size: '15sp' halign: 'left' MDLabel: - font_style: 'H4' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "Address" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'H4' + font_style: 'Body1' theme_text_color: 'Primary' text: root.address font_size: '15sp' @@ -993,31 +1072,34 @@ NavigationLayout: spacing:5 orientation: 'horizontal' MDRaisedButton: + size_hint: 2, None height: dp(40) on_press: root.send_message_from() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Send message from' font_size: '13sp' color: (1,1,1,1) halign: 'center' MDRaisedButton: + size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: app.root.ids.scr_mngr.current = 'showqrcode' on_press: app.root.ids.sc15.qrdisplay() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Show QR code' font_size: '13sp' color: (1,1,1,1) halign: 'center' MDRaisedButton: + size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) @@ -1025,6 +1107,7 @@ NavigationLayout: : id: addbook_popup + size_hint : (None,None) height: 4*(add_label.height) width :app.window_size[0] - app.window_size[0]/10 background: './images/popup.jpeg' @@ -1040,14 +1123,14 @@ NavigationLayout: orientation: 'vertical' spacing:dp(20) MDLabel: - font_style: 'H4' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "Label" font_size: '17sp' halign: 'left' MDTextField: id: add_label - font_style: 'H4' + font_style: 'Body1' font_size: '15sp' halign: 'left' text: root.address_label @@ -1055,13 +1138,13 @@ NavigationLayout: required: True helper_text_mode: "on_error" MDLabel: - font_style: 'H4' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: "Address" font_size: '17sp' halign: 'left' MDLabel: - font_style: 'H4' + font_style: 'Body1' theme_text_color: 'Primary' text: root.address font_size: '15sp' @@ -1071,30 +1154,33 @@ NavigationLayout: spacing:5 orientation: 'horizontal' MDRaisedButton: + size_hint: 2, None height: dp(40) on_press: root.send_message_to() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Send message to' font_size: '13sp' color: (1,1,1,1) halign: 'center' MDRaisedButton: + size_hint: 1.5, None height: dp(40) font_size: '10sp' on_press: root.update_addbook_label(root.address) MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Save' font_size: '13sp' color: (1,1,1,1) halign: 'center' MDRaisedButton: + size_hint: 1.5, None height: dp(40) on_press: root.dismiss() on_press: root.close_pop() MDLabel: - font_style: 'H4' + font_style: 'H6' text: 'Cancel' font_size: '13sp' color: (1,1,1,1) @@ -1125,4 +1211,4 @@ NavigationLayout: MDTextField: id: search_field hint_text: 'Search' - on_text: app.searchQuery(self) + on_text: app.searchQuery(self) \ No newline at end of file diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index aa55d35b..42b2532e 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -65,9 +65,8 @@ from kivy.core.clipboard import Clipboard def toast(text): """Method will display the toast message.""" - if platform == 'linux': - from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name - toast(text) + from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name + toast(text) return @@ -157,12 +156,11 @@ class Inbox(Screen): self.ids.ml.add_widget(carousel) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="No message found!" if state.searcing_text else "yet no message for this account!!!!!!!!!!!!!", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -276,12 +274,11 @@ class MyAddress(Screen): self.ids.ml.add_widget(meny) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="No address found!" if state.searcing_text else "yet no address is created by user!!!!!!!!!!!!!", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -371,12 +368,11 @@ class AddressBook(Screen): self.ids.ml.add_widget(carousel) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="No contact found!" if state.searcing_text else "No contact found yet...... ", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -384,8 +380,9 @@ class AddressBook(Screen): @staticmethod def refreshs(*args): """Refresh the Widget.""" - state.navinstance.ids.sc11.ids.ml.clear_widgets() - state.navinstance.ids.sc11.loadAddresslist(None, 'All', '') + # state.navinstance.ids.sc11.ids.ml.clear_widgets() + # state.navinstance.ids.sc11.loadAddresslist(None, 'All', '') + pass @staticmethod def addBook_detail(address, label, *args): @@ -563,6 +560,7 @@ class DropDownWidget(BoxLayout): self.ids.txt_input.text = '' self.ids.subject.text = '' self.ids.body.text = '' + toast("Reset message") def auto_fill_fromaddr(self): """Mehtod used to fill the text automatically From Address.""" @@ -699,6 +697,7 @@ class Random(Screen): self.parent.parent.parent.parent.ids.toolbar.opacity = 1 self.parent.parent.parent.parent.ids.toolbar.disabled = False self.parent.parent.parent.parent.ids.sc10.ids.ml.clear_widgets() + self.manager.current = 'myaddress' self.parent.parent.parent.parent.ids.sc10.init_ui() self.manager.current = 'myaddress' toast('New address created') @@ -791,12 +790,11 @@ class Sent(Screen): self.ids.ml.add_widget(carousel) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="No message found!" if state.searcing_text else "yet no message for this account!!!!!!!!!!!!!", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -917,11 +915,10 @@ class Trash(Screen): self.ids.ml.add_widget(carousel) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="yet no trashed message for this account!!!!!!!!!!!!!", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -1100,7 +1097,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods """Getting default image on address""" if BMConfigParser().addresses(): return './images/default_identicon/{}.png'.format(BMConfigParser().addresses()[0]) - return '' + return './images/no_identicons.png' @staticmethod def addressexist(): @@ -1164,6 +1161,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.toolbar.left_action_items = [ ['arrow-left', lambda x: self.back_press()]] self.root.ids.toolbar.right_action_items = [ + ['refresh', lambda x: self.root.ids.sc3.children[0].reset_composer()], ['send', lambda x: self.root.ids.sc3.children[0].send(self)]] def back_press(self): @@ -1173,7 +1171,9 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.toolbar.left_action_items = \ [['menu', lambda x: self.root.toggle_nav_drawer()]] self.root.ids.scr_mngr.current = 'inbox' \ - if state.in_composer else 'allmails' if state.is_allmail else state.detailPageType + if state.in_composer else 'allmails'\ + if state.is_allmail else state.detailPageType\ + if state.detailPageType else 'inbox' self.root.ids.scr_mngr.transition.direction = 'right' self.root.ids.scr_mngr.transition.bind(on_complete=self.reset) if state.is_allmail or state.detailPageType == 'draft': @@ -1305,10 +1305,12 @@ class GrashofPopup(Popup): stored_address = [addr[1] for addr in kivy_helper_search.search_sql( folder="addressbook")] if label and address and address not in stored_address: - state.navinstance = self.parent.children[1] + # state.navinstance = self.parent.children[1] queues.UISignalQueue.put(('rerenderAddressBook', '')) self.dismiss() sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address) + state.kivyapp.root.ids.sc11.ids.ml.clear_widgets() + state.kivyapp.root.ids.sc11.loadAddresslist(None, 'All', '') self.parent.children[1].ids.scr_mngr.current = 'addressbook' toast('Saved') @@ -1469,6 +1471,8 @@ class MailDetail(Screen): sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE \ msgid = ?;", str(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) self.parent.screens[0].ids.ml.clear_widgets() self.parent.screens[0].loadMessagelist(state.association) elif state.detailPageType == 'draft': @@ -1597,7 +1601,7 @@ class AddbookDetailPopup(Popup): window_obj = self.parent.children[1].ids window_obj.sc3.children[0].ids.txt_input.text = self.address window_obj.sc3.children[0].ids.ti.text = '' - window_obj.sc3.children[0].ids.btn.text = '' + window_obj.sc3.children[0].ids.btn.text = 'Select' window_obj.sc3.children[0].ids.subject.text = '' window_obj.sc3.children[0].ids.body.text = '' window_obj.scr_mngr.current = 'create' @@ -1692,11 +1696,10 @@ class Draft(Screen): self.ids.ml.add_widget(carousel) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="yet no message for this account!!!!!!!!!!!!!", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -1815,16 +1818,11 @@ class Allmails(Screen): def loadMessagelist(self, account, where="", what=""): """Load Inbox, Sent anf Draft list of messages.""" - inbox = sqlQuery( - "SELECT toaddress, fromaddress, subject, message, folder, msgid from\ - inbox WHERE folder = 'inbox' and toaddress = '{}';".format( - account)) - sent_and_draft = sqlQuery( - "SELECT toaddress, fromaddress, subject, message, folder, ackdata from sent \ - WHERE folder = 'sent' and fromaddress = '{}';".format( - account)) - - all_mails = inbox + sent_and_draft + all_mails = sqlQuery( + "SELECT toaddress, fromaddress, subject, message, folder, ackdata As id, DATE(lastactiontime)" + " As actionTime FROM sent WHERE folder = 'sent' UNION" + " SELECT toaddress, fromaddress, subject, message, folder, msgid As id, DATE(received) As" + " actionTime FROM inbox WHERE folder = 'inbox' ORDER BY actionTime DESC") if all_mails: state.kivyapp.root.children[2].children[0].ids.allmail_cnt.badge_text = str(len(all_mails)) state.all_count = str(len(all_mails)) @@ -1858,11 +1856,10 @@ class Allmails(Screen): self.ids.ml.add_widget(carousel) else: content = MDLabel( - font_style='Body1', + font_style='Caption', theme_text_color='Primary', text="yet no message for this account!!!!!!!!!!!!!", halign='center', - bold=True, size_hint_y=None, valign='top') self.ids.ml.add_widget(content) @@ -1966,4 +1963,4 @@ class Archieve(Screen): class Spam(Screen): """Spam Screen show widgets of page.""" - pass + pass \ No newline at end of file From f4d14c11e9e1d1f548310cfba9f5fda8b99fd32a Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Tue, 22 Oct 2019 13:07:54 +0530 Subject: [PATCH 06/54] Solved encode-decode, pack-unpack, new address creation issues --- src/class_addressGenerator.py | 4 ++-- src/highlevelcrypto.py | 4 ++-- src/pyelliptic/arithmetic.py | 20 +++++++------------- src/pyelliptic/ecc.py | 9 +++------ src/pyelliptic/openssl.py | 6 +++--- src/shared.py | 12 ++++-------- 6 files changed, 21 insertions(+), 34 deletions(-) diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index e4bf1d13..7300537f 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -157,13 +157,13 @@ class addressGenerator(StoppableThread): # An excellent way for us to store our keys # is in Wallet Import Format. Let us convert now. # https://en.bitcoin.it/wiki/Wallet_import_format - privSigningKey = '\x80'.encode('utf-8') + potentialPrivSigningKey + privSigningKey = '\x80'.encode('utf-8')[1:] + potentialPrivSigningKey checksum = hashlib.sha256(hashlib.sha256( privSigningKey).digest()).digest()[0:4] privSigningKeyWIF = arithmetic.changebase( privSigningKey + checksum, 256, 58) - privEncryptionKey = '\x80'.encode('utf-8') + potentialPrivEncryptionKey + privEncryptionKey = '\x80'.encode('utf-8')[1:] + potentialPrivEncryptionKey checksum = hashlib.sha256(hashlib.sha256( privEncryptionKey).digest()).digest()[0:4] privEncryptionKeyWIF = arithmetic.changebase( diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 512c55b5..b9088f32 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -15,8 +15,8 @@ def makeCryptor(privkey): """Return a private pyelliptic.ECC() instance""" private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) - privkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + private_key - pubkey_bin = '\x02\xca\x00\x20'.encode('utf-8') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] + privkey_bin = '\x02\xca\x00\x20'.encode('raw_unicode_escape') + private_key + pubkey_bin = '\x02\xca\x00\x20'.encode('raw_unicode_escape') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 1c9dcec4..2a5d29a9 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -1,4 +1,4 @@ -# pylint: disable=missing-docstring,too-many-function-args +0# pylint: disable=missing-docstring,too-many-function-args import hashlib import re @@ -26,33 +26,27 @@ def get_code_string(base): elif base == 10: return '0123456789' elif base == 16: - return "0123456789abcdef" + return ("0123456789abcdef").encode() elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" elif base == 256: '''raw_unicode_escape is used because in the python3 after range(161) its genreate the' the speical character so avoiding that function we have used the raw_unicode method ''' - return ''.join([chr(x) for x in range(256)]).encode('raw_unicode_escape') + return bytes(range(0, 256)) else: raise ValueError("Invalid base!") def encode(val, base, minlen=0): code_string = get_code_string(base) - result = '' - # result = str.encode(result) - count = 0 + result = str.encode('') if type(code_string) == bytes else '' while val > 0: - count += 1 - print(f'code_string[int(val) % base:int(val) % base + 1] -{code_string[int(val) % base:int(val) % base + 1]}') - print(f'result-{result}') - result = code_string[int(val) % base:int(val) % base + 1] + result - val = int(val / base) + result = code_string[val % base:val % base + 1] + result + val = val // base if len(result) < minlen: result = code_string[0] * (minlen - len(result)) + result return result - def decode(string, base): code_string = get_code_string(base) result = 0 @@ -60,7 +54,7 @@ def decode(string, base): string = string.lower() while string: result *= base - result += code_string.find(string[0]) + result += code_string.find(string[0:1]) string = string[1:] return result diff --git a/src/pyelliptic/ecc.py b/src/pyelliptic/ecc.py index f0cba579..fdff0733 100644 --- a/src/pyelliptic/ecc.py +++ b/src/pyelliptic/ecc.py @@ -64,7 +64,6 @@ class ECC(object): self.curve = OpenSSL.get_curve(curve) else: self.curve = curve - if pubkey_x is not None and pubkey_y is not None: self._set_keys(pubkey_x, pubkey_y, raw_privkey) elif pubkey is not None: @@ -114,7 +113,7 @@ class ECC(object): pack('!H', len(self.pubkey_x)), self.pubkey_x, pack('!H', len(self.pubkey_y)), - self.pubkey_y, + self.pubkey_y, )) def get_privkey(self): @@ -137,19 +136,18 @@ class ECC(object): i += 2 pubkey_x = pubkey[i:i + tmplen] i += tmplen - i += int(tmplen / 3) tmplen = unpack('!H', pubkey[i:i + 2])[0] i += 2 pubkey_y = pubkey[i:i + tmplen] i += tmplen - return curve, pubkey_x, pubkey_y, int(i) + return curve, pubkey_x, pubkey_y, i @staticmethod def _decode_privkey(privkey): i = 0 curve = unpack('!H', privkey[i:i + 2])[0] i += 2 - tmplen = pack('!s', privkey[i:i + 1])[0] + tmplen = unpack('!H', privkey[i:i + 2])[0] i += 2 privkey = privkey[i:i + tmplen] i += tmplen @@ -297,7 +295,6 @@ class ECC(object): if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: raise Exception( "[OpenSSL] EC_KEY_set_private_key FAIL ...") - group = OpenSSL.EC_KEY_get0_group(key) pub_key = OpenSSL.EC_POINT_new(group) diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 35e7933a..23de093e 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -674,13 +674,12 @@ def loadOpenSSL(): elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(path.join(sys._MEIPASS, 'libeay32.dll')) else: - libdir.extend([ path.join(sys._MEIPASS, 'libcrypto.so'), path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libcrypto.so.1.1.0'), path.join(sys._MEIPASS, 'libssl.so.1.1.0'), - path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), + path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), path.join(sys._MEIPASS, 'libssl.so.1.0.2'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.1'), path.join(sys._MEIPASS, 'libssl.so.1.0.1'), @@ -703,6 +702,7 @@ def loadOpenSSL(): libdir.append('libssl.so') libdir.append('libcrypto.so.1.0.0') libdir.append('libssl.so.1.0.0') + libdir.append('libcrypto.so.1.0.2') if 'linux' in sys.platform or 'darwin' in sys.platform or 'bsd' in sys.platform: try: libdir.append(find_library('ssl')) @@ -710,7 +710,7 @@ def loadOpenSSL(): pass elif 'win32' in sys.platform or 'win64' in sys.platform: libdir.append(find_library('libeay32')) - for library in libdir: + for library in libdir: try: OpenSSL = _OpenSSL(library) return diff --git a/src/shared.py b/src/shared.py index 8cd86e6c..9ab64f68 100644 --- a/src/shared.py +++ b/src/shared.py @@ -89,27 +89,23 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address): return True return False - def decodeWalletImportFormat(WIFstring): fullString = arithmetic.changebase(WIFstring, 58, 256) privkey = fullString[:-4] - if fullString[-4:] != \ - hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]: + if fullString[-4:] != hashlib.sha256(hashlib.sha256(privkey).digest()).digest()[:4]: logger.critical( 'Major problem! When trying to decode one of your' ' private keys, the checksum failed. Here are the first' - ' 6 characters of the PRIVATE key: %s', - str(WIFstring)[:6] + ' 6 characters of the PRIVATE key: {}'.format(str(WIFstring)[:6]) ) os._exit(0) - # return "" - elif privkey[0] == '\x80': # checksum passed + if privkey[0:1] == '\x80'.encode()[1:]: # checksum passed return privkey[1:] logger.critical( 'Major problem! When trying to decode one of your private keys,' ' the checksum passed but the key doesn\'t begin with hex 80.' - ' Here is the PRIVATE key: %s', WIFstring + ' Here is the PRIVATE key: {}'.format(WIFstring) ) os._exit(0) From 3f70ae8c4d51fec1701fb9a6afd306b0779cd215 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Tue, 22 Oct 2019 13:14:10 +0530 Subject: [PATCH 07/54] Added python3 requirements.txt file --- python3_requirements.txt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 python3_requirements.txt diff --git a/python3_requirements.txt b/python3_requirements.txt new file mode 100644 index 00000000..5709432a --- /dev/null +++ b/python3_requirements.txt @@ -0,0 +1,15 @@ +certifi==2019.9.11 +chardet==3.0.4 +docutils==0.15.2 +idna==2.8 +Kivy==1.11.1 +Kivy-Garden==0.1.4 +kivymd==0.100.2 +Pillow==6.1.0 +pkg-resources==0.0.0 +pydenticon==0.3.1 +Pygments==2.4.2 +qrcode==6.1 +requests==2.22.0 +six==1.12.0 +urllib3==1.25.6 From d68085869b61e7b481c21999af6fd1997a9eec27 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 21 Oct 2019 14:45:31 +0530 Subject: [PATCH 08/54] mpybit py3 fixes --- src/bitmessagekivy/mpybit.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 42b2532e..f74bcf20 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -50,16 +50,14 @@ from kivymd.uix.navigationdrawer import ( NavigationDrawerHeaderBase) from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.theming import ThemeManager + import queues from semaphores import kivyuisignaler + import state from bitmessagekivy.uikivysignaler import UIkivySignaler -# pylint: disable=unused-argument, too-few-public-methods, import-error - from bitmessagekivy import identiconGeneration -import os -from kivy.core.clipboard import Clipboard # pylint: disable=unused-argument, too-few-public-methods @@ -986,7 +984,6 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods def build(self): """Method builds the widget.""" - import os main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) self.nav_drawer = Navigatorss() @@ -1963,4 +1960,4 @@ class Archieve(Screen): class Spam(Screen): """Spam Screen show widgets of page.""" - pass \ No newline at end of file + pass From 55085af2087a03713a522c67970a2a738c5f5068 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 22 Oct 2019 19:04:32 +0530 Subject: [PATCH 09/54] py3 quality fixes --- src/highlevelcrypto.py | 4 +++- src/pyelliptic/arithmetic.py | 7 ++++--- src/pyelliptic/openssl.py | 2 +- src/shared.py | 10 ++++++---- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index b9088f32..329ad68c 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -16,7 +16,9 @@ def makeCryptor(privkey): private_key = a.changebase(privkey, 16, 256, minlen=32) public_key = pointMult(private_key) privkey_bin = '\x02\xca\x00\x20'.encode('raw_unicode_escape') + private_key - pubkey_bin = '\x02\xca\x00\x20'.encode('raw_unicode_escape') + public_key[1:-32] + '\x00\x20'.encode('utf-8') + public_key[-32:] + pubkey_bin = '\x02\xca\x00\x20'.encode( + 'raw_unicode_escape') + public_key[1:-32] + '\x00\x20'.encode( + 'utf-8') + public_key[-32:] cryptor = pyelliptic.ECC(curve='secp256k1', privkey=privkey_bin, pubkey=pubkey_bin) return cryptor diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 2a5d29a9..031db6ae 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -1,4 +1,4 @@ -0# pylint: disable=missing-docstring,too-many-function-args +# pylint: disable=missing-docstring,too-many-function-args import hashlib import re @@ -30,7 +30,7 @@ def get_code_string(base): elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" elif base == 256: - '''raw_unicode_escape is used because in the python3 after range(161) its genreate the' + '''raw_unicode_escape is used because in the python3 after range(161) its genreate the speical character so avoiding that function we have used the raw_unicode method ''' return bytes(range(0, 256)) else: @@ -39,7 +39,7 @@ def get_code_string(base): def encode(val, base, minlen=0): code_string = get_code_string(base) - result = str.encode('') if type(code_string) == bytes else '' + result = str.encode('') if type(code_string) is bytes else '' while val > 0: result = code_string[val % base:val % base + 1] + result val = val // base @@ -47,6 +47,7 @@ def encode(val, base, minlen=0): result = code_string[0] * (minlen - len(result)) + result return result + def decode(string, base): code_string = get_code_string(base) result = 0 diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 23de093e..3545fa52 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -679,7 +679,7 @@ def loadOpenSSL(): path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libcrypto.so.1.1.0'), path.join(sys._MEIPASS, 'libssl.so.1.1.0'), - path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), + path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), path.join(sys._MEIPASS, 'libssl.so.1.0.2'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.1'), path.join(sys._MEIPASS, 'libssl.so.1.0.1'), diff --git a/src/shared.py b/src/shared.py index 9ab64f68..09830bde 100644 --- a/src/shared.py +++ b/src/shared.py @@ -89,6 +89,7 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address): return True return False + def decodeWalletImportFormat(WIFstring): fullString = arithmetic.changebase(WIFstring, 58, 256) privkey = fullString[:-4] @@ -171,8 +172,9 @@ def reloadBroadcastSendersForWhichImWatching(): # we should create Cryptor objects in a dictionary which we will # use to attempt to decrypt encrypted broadcast messages. if addressVersionNumber <= 3: - privEncryptionKey = hashlib.sha512((encodeVarint(addressVersionNumber) \ - + encodeVarint(streamNumber) + hash)).digest()[:32] + privEncryptionKey = hashlib.sha512(( + encodeVarint(addressVersionNumber) + + encodeVarint(streamNumber) + hash)).digest()[:32] MyECSubscriptionCryptorObjects[hash] = \ highlevelcrypto.makeCryptor(hexlify(privEncryptionKey)) else: @@ -191,8 +193,8 @@ def fixPotentiallyInvalidUTF8Data(text): unicode(text, 'utf-8') return text except: - return 'Part of the message is corrupt. The message cannot be' \ - ' displayed the normal way.\n\n' + repr(text) + return 'Part of the message is corrupt. The message cannot be'\ + ' displayed the normal way.\n\n' + repr(text) # Checks sensitive file permissions for inappropriate umask From f3cb78557bb2979c60262125a8c2450c9e8d8fb8 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Tue, 22 Oct 2019 13:07:54 +0530 Subject: [PATCH 10/54] Solved encode-decode, pack-unpack, new address creation issues --- src/pyelliptic/arithmetic.py | 1 - src/pyelliptic/openssl.py | 2 +- src/shared.py | 1 - 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 031db6ae..fc9e8c6f 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -47,7 +47,6 @@ def encode(val, base, minlen=0): result = code_string[0] * (minlen - len(result)) + result return result - def decode(string, base): code_string = get_code_string(base) result = 0 diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 3545fa52..23de093e 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -679,7 +679,7 @@ def loadOpenSSL(): path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libcrypto.so.1.1.0'), path.join(sys._MEIPASS, 'libssl.so.1.1.0'), - path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), + path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), path.join(sys._MEIPASS, 'libssl.so.1.0.2'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.1'), path.join(sys._MEIPASS, 'libssl.so.1.0.1'), diff --git a/src/shared.py b/src/shared.py index 09830bde..9e6fc991 100644 --- a/src/shared.py +++ b/src/shared.py @@ -89,7 +89,6 @@ def isAddressInMyAddressBookSubscriptionsListOrWhitelist(address): return True return False - def decodeWalletImportFormat(WIFstring): fullString = arithmetic.changebase(WIFstring, 58, 256) privkey = fullString[:-4] From fdbf7ad0f2c89db7d387b7fae3fa9cc6d5915ff4 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Thu, 14 Nov 2019 20:39:26 +0530 Subject: [PATCH 11/54] Worked on the network issues --- src/bitmessagekivy/mpybit.py | 8 ++-- src/bitmessagemain.py | 2 +- src/knownnodes.py | 4 +- src/network/announcethread.py | 8 ++-- src/network/bmproto.py | 46 ++++++++++++++------- src/network/connectionchooser.py | 2 +- src/network/connectionpool.py | 71 ++++++++++++++++++++------------ src/network/dandelion.py | 16 ++++++- src/network/objectracker.py | 2 +- src/network/stats.py | 9 +++- src/network/tcp.py | 20 ++++----- src/network/tls.py | 5 ++- src/protocol.py | 38 +++++++++-------- src/storage/sqlite.py | 2 +- 14 files changed, 144 insertions(+), 89 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index f74bcf20..5c41577e 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -452,8 +452,8 @@ class DropDownWidget(BoxLayout): # pylint: disable=too-many-locals fromAddress = str(self.ids.ti.text) toAddress = str(self.ids.txt_input.text) - subject = self.ids.subject.text.encode('utf-8').strip() - message = self.ids.body.text.encode('utf-8').strip() + subject = self.ids.subject.text.strip() + message = self.ids.body.text.strip() encoding = 3 print ("message: ", self.ids.body.text) sendMessageToPeople = True @@ -511,8 +511,8 @@ class DropDownWidget(BoxLayout): 0, 'sent', encoding, - BMConfigParser().getint( - 'bitmessagesettings', 'ttl')) + int(BMConfigParser().safeGet( + 'bitmessagesettings', 'ttl'))) state.check_sent_acc = fromAddress state.msg_counter_objs = self.parent.parent.parent.parent\ .parent.parent.children[0].children[2].children[0].ids diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index dcf03118..b7735904 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -358,7 +358,7 @@ class Main: # pylint: disable=no-init, old-style-class # Not needed if objproc disabled if state.enableObjProc: shared.reloadMyAddressHashes() - # shared.reloadBroadcastSendersForWhichImWatching() + shared.reloadBroadcastSendersForWhichImWatching() # API is also objproc dependent if config.safeGetBoolean('bitmessagesettings', 'apienabled'): import api # pylint: disable=relative-import diff --git a/src/knownnodes.py b/src/knownnodes.py index 4052e3ae..7708e16f 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -134,7 +134,7 @@ def increaseRating(peer): increaseAmount = 0.1 maxRating = 1 with knownNodesLock: - for stream in knownNodes.keys(): + for stream in [key for key in knownNodes.keys()]: try: knownNodes[stream][peer]["rating"] = min( knownNodes[stream][peer]["rating"] + increaseAmount, @@ -160,7 +160,7 @@ def decreaseRating(peer): def trimKnownNodes(recAddrStream=1): if len(knownNodes[recAddrStream]) < \ - BMConfigParser().safeGetInt("knownnodes", "maxnodes"): + int(BMConfigParser().safeGet("knownnodes", "maxnodes")): return with knownNodesLock: oldestList = sorted( diff --git a/src/network/announcethread.py b/src/network/announcethread.py index 59fad128..b6f21eae 100644 --- a/src/network/announcethread.py +++ b/src/network/announcethread.py @@ -32,12 +32,12 @@ class AnnounceThread(StoppableThread): @staticmethod def announceSelf(): """Announce our presence""" - for connection in BMConnectionPool().udpSockets.values(): + for connection in [ udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]: if not connection.announcing: continue for stream in state.streamsInWhichIAmParticipating: addr = ( stream, - state.Peer('127.0.0.1', BMConfigParser().safeGetInt("bitmessagesettings", "port")), - time.time()) - connection.append_write_buf(BMProto.assembleAddr([addr])) + state.Peer('127.0.0.1',int( BMConfigParser().safeGet("bitmessagesettings", "port"))), + int(time.time())) + connection.append_write_buf(BMProto.assembleAddr([addr])) \ No newline at end of file diff --git a/src/network/bmproto.py b/src/network/bmproto.py index cfd6672f..69f1debb 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -11,7 +11,7 @@ import time from binascii import hexlify import addresses -import network.connectionpool +from network import connectionpool import knownnodes import protocol import state @@ -83,12 +83,16 @@ 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')) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync + #in the advancedispatched and length commend's + #escape the 1 length self.set_state("bm_header", length=1) self.bm_proto_reset() logger.debug('Bad magic') @@ -111,15 +115,17 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.invalid = True retval = True if not self.fullyEstablished and self.command not in ( - "error", "version", "verack"): + "error".encode(), "version".encode(), "verack".encode()): logger.error( - 'Received command %s before connection was fully' - ' established, ignoring', self.command) + 'Received command {} before connection was fully' + ' established, ignoring'.format (self.command)) self.invalid = True if not self.invalid: try: + command = self.command.decode() if self.command else self.command + retval = getattr( - self, "bm_command_" + str(self.command).lower())() + self, "bm_command_" +command)() except AttributeError: # unimplemented command logger.debug('unimplemented command %s', self.command) @@ -147,11 +153,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker): # broken read, ignore pass else: - logger.debug('Closing due to invalid command %s', self.command) - self.close_reason = "Invalid command %s" % self.command + logger.debug('Closing due to invalid command {}'.format(self.command)) + self.close_reason = ("Invalid command {}".format(self.command)) self.set_state("close") return False if retval: + print('if retval is true and inside the if ') self.set_state("bm_header", length=self.payloadLength) self.bm_proto_reset() # else assume the command requires a different state to follow @@ -174,16 +181,16 @@ class BMProto(AdvancedDispatcher, ObjectTracker): # 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': - host = socket.inet_ntop(socket.AF_INET, str(host[12:16])) + host = socket.inet_ntop(socket.AF_INET, host[12:16]) elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43': # Onion, based on BMD/bitcoind host = base64.b32encode(host[6:]).lower() + ".onion" else: - host = socket.inet_ntop(socket.AF_INET6, str(host)) + host = socket.inet_ntop(socket.AF_INET6, host) if host == "": # This can happen on Windows systems which are not 64-bit # compatible so let us drop the IPv6 address. - host = socket.inet_ntop(socket.AF_INET, str(host[12:16])) + host = socket.inet_ntop(socket.AF_INET, host[12:16]) return Node(services, host, port) @@ -327,6 +334,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): If we have them and some other conditions are fulfilled, append them to the write queue. """ + #32 an array bit long strings items = self.decode_payload_content("l32s") # skip? now = time.time() @@ -429,11 +437,13 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return self.decode_payload_content("LQIQ16sH") def bm_command_addr(self): + print('+++++++++++++++++++++++++++\ + bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') """Incoming addresses, process them""" addresses = self._decode_addr() # pylint: disable=redefined-outer-name for i in addresses: seenTime, stream, services, ip, port = i - decodedIP = protocol.checkIPAddress(str(ip)) + decodedIP = protocol.checkIPAddress(ip) if stream not in state.streamsInWhichIAmParticipating: continue if ( @@ -495,8 +505,8 @@ 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 ') """ Incoming version. Parse and log, remember important things, like streams, bitfields, etc. @@ -533,6 +543,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.isSSL = True if not self.verackReceived: return True + print('inside the bmproto line 546') self.set_state( "tls_init" if self.isSSL else "connection_fully_established", length=self.payloadLength, expectBytes=0) @@ -578,13 +589,16 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return False if self.destination in connectionpool.BMConnectionPool().inboundConnections: try: + print('+++++++++++++++++++++++++++') + print('self destination host -{}'.format(self.destination.host)) + print('++++++++++++++++++++++++++++++') if not protocol.checkSocksIP(self.destination.host): self.append_write_buf(protocol.assembleErrorMessage( errorText="Too many connections from your IP." - " Closing connection.", fatal=2)) + " Closing connection.", fatal=2)) logger.debug( - 'Closed connection to %s because we are already connected' - ' to that IP.', self.destination) + 'Closed connection to {} because we are already connected' + ' to that IP.'.format(self.destination)) return False except: pass @@ -631,7 +645,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): for address in peerList[i:i + BMProto.maxAddrCount]: stream, peer, timestamp = address 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 diff --git a/src/network/connectionchooser.py b/src/network/connectionchooser.py index 53ce30b7..eb7c0f6e 100644 --- a/src/network/connectionchooser.py +++ b/src/network/connectionchooser.py @@ -37,7 +37,7 @@ def chooseConnection(stream): # discovered peers are already filtered by allowed streams return getDiscoveredPeer() for _ in range(50): - peer = random.choice(knownnodes.knownNodes[stream].keys()) + peer = random.choice(list(knownnodes.knownNodes[stream].keys())) try: peer_info = knownnodes.knownNodes[stream][peer] if peer_info.get('self'): diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index aad45e59..374ebc62 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -18,7 +18,7 @@ from debug import logger from network.proxy import Proxy from singleton import Singleton from network.tcp import ( - TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection) + TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection,bootstrap) from network.udp import UDPSocket @@ -71,9 +71,13 @@ class BMConnectionPool(object): def isAlreadyConnected(self, nodeid): """Check if we're already connected to this peer""" + # for i in ( + # self.inboundConnections.values() + + # self.outboundConnections.values() + # ): for i in ( - self.inboundConnections.values() + - self.outboundConnections.values() + [inboundConnections for inboundConnections in self.inboundConnections.values()] + + [outboundConnections for outboundConnections in self.outboundConnections.values()] ): try: if nodeid == i.nodeid: @@ -138,8 +142,9 @@ class BMConnectionPool(object): def startListening(self, bind=None): """Open a listening socket and start accepting connections on it""" if bind is None: + "this return blank host" bind = self.getListeningIP() - port = BMConfigParser().safeGetInt("bitmessagesettings", "port") + port = int(BMConfigParser().safeGet("bitmessagesettings", "port")) # correct port even if it changed ls = TCPServer(host=bind, port=port) self.listeningSockets[ls.destination] = ls @@ -178,11 +183,10 @@ class BMConnectionPool(object): # This should never happen because socksproxytype setting # is handled in bitmessagemain before starting the connectionpool return - bootstrapper = bootstrap(connection_base) if not hostname: port = helper_random.randomchoice([8080, 8444]) - hostname = 'bootstrap%s.bitmessage.org' % port + hostname = ('bootstrap{}.bitmessage.org'.format(port)) else: port = 8444 self.addConnection(bootstrapper(hostname, port)) @@ -195,8 +199,8 @@ class BMConnectionPool(object): if BMConfigParser().safeGetBoolean( 'bitmessagesettings', 'dontconnect'): acceptConnections = False - elif BMConfigParser().safeGetBoolean( - 'bitmessagesettings', 'sendoutgoingconnections'): + elif bool(BMConfigParser().safeGet( + 'bitmessagesettings', 'sendoutgoingconnections')): spawnConnections = True socksproxytype = BMConfigParser().safeGet( 'bitmessagesettings', 'socksproxytype', '') @@ -219,8 +223,8 @@ class BMConnectionPool(object): Proxy.proxy = ( BMConfigParser().safeGet( 'bitmessagesettings', 'sockshostname'), - BMConfigParser().safeGetInt( - 'bitmessagesettings', 'socksport') + int(BMConfigParser().safeGet( + 'bitmessagesettings', 'socksport')) ) # TODO AUTH # TODO reset based on GUI settings changes @@ -236,11 +240,11 @@ class BMConnectionPool(object): except ValueError: Proxy.onion_proxy = None established = sum( - 1 for c in list(self.outboundConnections.values()) + 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] if (c.connected and c.fullyEstablished)) pending = len(self.outboundConnections) - established - if established < BMConfigParser().safeGetInt( - 'bitmessagesettings', 'maxoutboundconnections'): + if established < int(BMConfigParser().safeGet( + 'bitmessagesettings', 'maxoutboundconnections')): for i in range( state.maximumNumberOfHalfOpenConnections - pending): try: @@ -275,18 +279,22 @@ class BMConnectionPool(object): self.lastSpawned = time.time() - print('++++++++++++++++++++++++++++++++++++++++++') - print('self.inboundConnections.values()-{}'.format(self.inboundConnections.values())) - print('self.outboundConnections.values() -{}'.format(self.outboundConnections.values())) - print('+++++++++++++++++++++++++++++++++++++++++++') + # print('++++++++++++++++++++++++++++++++++++++++++') + # print('self.inboundConnections.values()-{}'.format(self.inboundConnections.values())) + # print('self.outboundConnections.values() -{}'.format(self.outboundConnections.values())) + # print('+++++++++++++++++++++++++++++++++++++++++++') else: + + # for i in ( + # list(self.inboundConnections.values()) + + # list(self.outboundConnections.values()) + # ): for i in ( - list(self.inboundConnections.values()) + - list(self.outboundConnections.values()) + [inboundConnections for inboundConnections in self.inboundConnections.values()] + + [inboundConnections for inboundConnections in self.outboundConnections.values()] ): # FIXME: rating will be increased after next connection i.handle_close() - if acceptConnections: if not self.listeningSockets: if BMConfigParser().safeGet('network', 'bind') == '': @@ -299,6 +307,7 @@ class BMConnectionPool(object): self.startListening(bind) logger.info('Listening for incoming connections.') if not self.udpSockets: + # self.udpSockets :- {'0.0.0.0': } if BMConfigParser().safeGet('network', 'bind') == '': self.startUDPSocket() else: @@ -327,9 +336,13 @@ class BMConnectionPool(object): asyncore.loop(timeout=loopTime, count=1000) reaper = [] + # for i in ( + # list(self.inboundConnections.values()) + + # list(self.outboundConnections.values()) + # ): for i in ( - list(self.inboundConnections.values()) + - list(self.outboundConnections.values()) + [inboundConnections for inboundConnections in self.inboundConnections.values()] + + [outboundConnections for outboundConnections in self.outboundConnections.values()] ): minTx = time.time() - 20 if i.fullyEstablished: @@ -341,11 +354,17 @@ class BMConnectionPool(object): i.close_reason = "Timeout (%is)" % ( time.time() - i.lastTx) i.set_state("close") + # for i in ( + # list(self.inboundConnections.values()) + + # list(self.outboundConnections.values()) + + # list(self.listeningSockets.values()) + + # list(self.udpSockets.values()) + # ): for i in ( - list(self.inboundConnections.values()) + - list(self.outboundConnections.values()) + - list(self.listeningSockets.values()) + - list(self.udpSockets.values()) + [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()] ): if not (i.accepting or i.connecting or i.connected): reaper.append(i) diff --git a/src/network/dandelion.py b/src/network/dandelion.py index 2c23da5d..0adeddd6 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -101,13 +101,27 @@ class Dandelion(): # pylint: disable=old-style-class self.stem.append(connection) for k in (k for k, v in iter(self.nodeMap.items()) if v is None): self.nodeMap[k] = connection + #The Purpose of adding this condition that if self + #hashMap is has any value + # if not [hasmap for hasmap in self.hashMap.items()] ==[]: + try: for k, v in iter({ - k: v for k, v in iter(self.hashMap.items()) + k: v for k, v in iter([hasmap for hasamp in self.hashMap.items()]) if v.child is None }).items(): self.hashMap[k] = Stem( connection, v.stream, self.poissonTimeout()) invQueue.put((v.stream, k, v.child)) + except AttributeError: + pass + + # for k, v in iter({ + # k: v for k, v in iter([hasmap for hasamp in self.hashMap.items()]) + # if v.child is None + # }).items(): + # self.hashMap[k] = Stem( + # connection, v.stream, self.poissonTimeout()) + # invQueue.put((v.stream, k, v.child)) def maybeRemoveStem(self, connection): """ diff --git a/src/network/objectracker.py b/src/network/objectracker.py index 40a0f582..21bd6fea 100644 --- a/src/network/objectracker.py +++ b/src/network/objectracker.py @@ -71,7 +71,7 @@ class ObjectTracker(object): # release memory deadline = time.time() - ObjectTracker.trackingExpires with self.objectsNewToThemLock: - self.objectsNewToThem = {k: v for k, v in self.objectsNewToThem.iteritems() if v >= deadline} + self.objectsNewToThem = {k: v for k, v in iter(self.objectsNewToThem.items()) if v >= deadline} self.lastCleaned = time.time() def hasObj(self, hashid): diff --git a/src/network/stats.py b/src/network/stats.py index 1a57629d..7d6a5550 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -20,14 +20,19 @@ currentSentSpeed = 0 def connectedHostsList(): """List of all the connected hosts""" retval = [] - for i in list(BMConnectionPool().inboundConnections.values()) + \ - list(BMConnectionPool().outboundConnections.values()): + # for i in list(BMConnectionPool().inboundConnections.values()) + \ + # list(BMConnectionPool().outboundConnections.values()): + + outBoundConnections = [outConnection for outConnection in BMConnectionPool().outboundConnections.values()] + inBoundConnections = [inConnection for inConnection in BMConnectionPool().inboundConnections.values()] + for i in outBoundConnections+inBoundConnections: if not i.fullyEstablished: continue try: retval.append(i) except AttributeError: pass + print('#################### retval -{}'.format(retval)) return retval diff --git a/src/network/tcp.py b/src/network/tcp.py index 3ed19462..61285080 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -11,7 +11,7 @@ import time import addresses import network.asyncore_pollchoose as asyncore -import network.connectionpool +from network import connectionpool import helper_random import knownnodes import protocol @@ -71,8 +71,8 @@ class TCPConnection(BMProto, TLSDispatcher): TLSDispatcher.__init__(self, sock, server_side=False) self.connect(self.destination) logger.debug( - 'Connecting to %s:%i', - self.destination.host, self.destination.port) + 'Connecting to {}:{}'.format( + self.destination.host, self.destination.port)) try: self.local = ( protocol.checkIPAddress( @@ -131,15 +131,15 @@ class TCPConnection(BMProto, TLSDispatcher): def set_connection_fully_established(self): """Initiate inventory synchronisation.""" - if not self.isOutbound and not self.local: - shared.clientHasReceivedIncomingConnections = True - UISignalQueue.put(('setStatusIcon', 'green')) + shared.clientHasReceivedIncomingConnections = True + UISignalQueue.put(('setStatusIcon', 'green')) UISignalQueue.put(( 'updateNetworkStatusTab', (self.isOutbound, True, self.destination) )) self.antiIntersectionDelay(True) self.fullyEstablished = True + print('inside the set_connection_fully_established in tcp file') if self.isOutbound: knownnodes.increaseRating(self.destination) Dandelion().maybeAddStem(self) @@ -165,7 +165,7 @@ class TCPConnection(BMProto, TLSDispatcher): # only if more recent than 3 hours # and having positive or neutral rating filtered = [ - (k, v) for k, v in nodes.iteritems() + (k, v) for k, v in iter(nodes.items()) if v["lastseen"] > int(time.time()) - shared.maximumAgeOfNodesThatIAdvertiseToOthers and v["rating"] >= 0 and len(k.host) <= 22 @@ -191,8 +191,8 @@ class TCPConnection(BMProto, TLSDispatcher): if objectCount == 0: return logger.debug( - 'Sending huge inv message with %i objects to just this' - ' one peer', objectCount) + 'Sending huge inv message with {} objects to jcust this' + ' one peer'.format(objectCount)) self.append_write_buf(protocol.CreatePacket( 'inv', addresses.encodeVarint(objectCount) + payload)) @@ -208,7 +208,7 @@ class TCPConnection(BMProto, TLSDispatcher): continue bigInvList[objHash] = 0 objectCount = 0 - payload = b'' + payload = bytes() # Now let us start appending all of these hashes together. They will be # sent out in a big inv message to our new peer. for obj_hash, _ in bigInvList.items(): diff --git a/src/network/tls.py b/src/network/tls.py index 5f4be3b9..5a0f4c99 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -21,8 +21,8 @@ if sys.version_info >= (2, 7, 13): # this means TLSv1 or higher # in the future change to # ssl.PROTOCOL_TLS1.2 - # Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I - # have used try and catch + # Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I + # have used try and catch try: sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member except AttributeError: @@ -83,6 +83,7 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc # also exclude TLSv1 and TLSv1.1 in the future context.options = ssl.OP_ALL | ssl.OP_NO_SSLv2 |\ ssl.OP_NO_SSLv3 | ssl.OP_SINGLE_ECDH_USE | ssl.OP_CIPHER_SERVER_PREFERENCE + self.sslSocket = context.wrap_socket( self.socket, server_side=self.server_side, do_handshake_on_connect=False) else: diff --git a/src/protocol.py b/src/protocol.py index abb310db..a8d5a9a3 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -96,7 +96,7 @@ def encodeHost(host): if host.find('.onion') > -1: return '\xfd\x87\xd8\x7e\xeb\x43'.encode('utf-8') + base64.b32decode(host.split(".")[0], True) elif host.find(':') == -1: - return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('utf-8') + \ + return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape') + \ socket.inet_aton(host) return socket.inet_pton(socket.AF_INET6, host) @@ -156,17 +156,17 @@ def checkIPv4Address(host, hostStandardFormat, private=False): def checkIPv6Address(host, hostStandardFormat, private=False): """Returns hostStandardFormat if it is an IPv6 address, otherwise returns False""" - if host == ('\x00' * 15) + '\x01': + if host == ('\x00'.encode() * 15) + '\x01'.encode(): if not private: - logger.debug('Ignoring loopback address: %s', hostStandardFormat) + logger.debug('Ignoring loopback address: {}'.format( hostStandardFormat)) return False if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80: if not private: - logger.debug('Ignoring local address: %s', hostStandardFormat) + logger.debug('Ignoring local address: {}'.format( hostStandardFormat)) return hostStandardFormat if private else False - if (ord(host[0]) & 0xfe) == 0xfc: + if (ord(host[0:1]) & 0xfe) == 0xfc: if not private: - logger.debug('Ignoring unique local address: %s', hostStandardFormat) + logger.debug('Ignoring unique local address: {}'.format( hostStandardFormat)) return hostStandardFormat if private else False return False if private else hostStandardFormat @@ -234,18 +234,18 @@ def isProofOfWorkSufficient(data, def CreatePacket(command, payload=''): """Construct and return a number of bytes from a payload""" + payload = payload if type(payload) == bytes else payload.encode() payload_length = len(payload) checksum = hashlib.sha512(payload).digest()[0:4] - - b = bytearray(Header.size + payload_length) - Header.pack_into(b, 0, 0xE9BEB4D9, command, payload_length, checksum) - b[Header.size:] = payload - return bytes(b) + byte = bytearray(Header.size + payload_length) + Header.pack_into(byte, 0, 0xE9BEB4D9, command.encode(), payload_length, checksum) + byte[Header.size:] = payload + return byte def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=False, nodeid=None): """Construct the payload of a version message, return the resultng bytes of running CreatePacket() on it""" - payload = '' + payload = bytes() payload += pack('>L', 3) # protocol version. # bitflags of the services I offer. payload += pack( @@ -278,7 +278,9 @@ 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. - payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack('>L', 2130706433) + + #python3 need to check + payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433) # we have a separate extPort and incoming over clearnet # or outgoing through clearnet extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport') @@ -289,9 +291,9 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= ): payload += pack('>H', extport) elif checkSocksIP(remoteHost) and server: # incoming connection over Tor - payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'onionport')) + payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport'))) else: # no extport and not incoming over Tor - payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'port')) + payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'port'))) if nodeid is not None: payload += nodeid[0:8] @@ -299,7 +301,7 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf userAgent = '/PyBitmessage:' + softwareVersion + '/' payload += encodeVarint(len(userAgent)) - payload += userAgent + payload += userAgent.encode() # Streams payload += encodeVarint(len(participatingStreams)) @@ -319,9 +321,9 @@ def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''): payload = encodeVarint(fatal) payload += encodeVarint(banTime) payload += encodeVarint(len(inventoryVector)) - payload += inventoryVector + payload += inventoryVector.encode() if type(payload) == bytes else inventoryVector payload += encodeVarint(len(errorText)) - payload += errorText + payload += errorText.encode() if type(payload)== bytes else errorText return CreatePacket('error', payload) diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 03265fd1..8b69ad1b 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -79,7 +79,7 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors with self.lock: t = int(time.time()) hashes = [x for x, value in self._inventory.items() if value.stream == stream and value.expires > t] - hashes += (str(payload) for payload, in sqlQuery( + hashes += (payload for payload, in sqlQuery( 'SELECT hash FROM inventory WHERE streamnumber=? AND expirestime>?', stream, t)) return hashes From a08b0707bb75f7d78839a7861c6ab2bf740cfd6f Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Fri, 15 Nov 2019 16:01:14 +0530 Subject: [PATCH 12/54] Working on the network issues --- src/network/bmproto.py | 4 +++- src/network/dandelion.py | 18 ++++++++++-------- src/network/networkthread.py | 6 +++--- src/network/tcp.py | 2 +- src/network/tls.py | 5 +++++ 5 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 69f1debb..a175fc43 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -543,10 +543,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.isSSL = True if not self.verackReceived: return True - print('inside the bmproto line 546') + print('inside the bmproto line') + print('before the value of state are :-{}'.format(self.state)) self.set_state( "tls_init" if self.isSSL else "connection_fully_established", length=self.payloadLength, expectBytes=0) + print('After the value of state are :-{}'.format(self.state)) return False def peerValidityChecks(self): # pylint: disable=too-many-return-statements diff --git a/src/network/dandelion.py b/src/network/dandelion.py index 0adeddd6..6c34f525 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -105,13 +105,14 @@ class Dandelion(): # pylint: disable=old-style-class #hashMap is has any value # if not [hasmap for hasmap in self.hashMap.items()] ==[]: try: - for k, v in iter({ - k: v for k, v in iter([hasmap for hasamp in self.hashMap.items()]) - if v.child is None - }).items(): - self.hashMap[k] = Stem( - connection, v.stream, self.poissonTimeout()) - invQueue.put((v.stream, k, v.child)) + if self.hashMap: + for k, v in iter({ + k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) + if v.child is None + }).items(): + self.hashMap[k] = Stem( + connection, v.stream, self.poissonTimeout()) + invQueue.put((v.stream, k, v.child)) except AttributeError: pass @@ -133,12 +134,13 @@ class Dandelion(): # pylint: disable=old-style-class if connection in self.stem: self.stem.remove(connection) # active mappings to pointing to the removed node + for k in ( k for k, v in iter(self.nodeMap.items()) if v == connection ): self.nodeMap[k] = None for k, v in iter({ - k: v for k, v in iter(self.hashMap.items()) + k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) if v.child == connection }).items(): self.hashMap[k] = Stem( diff --git a/src/network/networkthread.py b/src/network/networkthread.py index 2a22367f..ca7cb56c 100644 --- a/src/network/networkthread.py +++ b/src/network/networkthread.py @@ -26,17 +26,17 @@ class BMNetworkThread(StoppableThread): def stopThread(self): super(BMNetworkThread, self).stopThread() - for i in BMConnectionPool().listeningSockets.values(): + for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]: try: i.close() except: pass - for i in BMConnectionPool().outboundConnections.values(): + for i in [ outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]: try: i.close() except: pass - for i in BMConnectionPool().inboundConnections.values(): + for i in [inboundConnections for inboundConnections in BMConnectionPool().inboundConnections.values()]: try: i.close() except: diff --git a/src/network/tcp.py b/src/network/tcp.py index 61285080..f07d9b1c 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -362,7 +362,7 @@ class TCPServer(AdvancedDispatcher): """TCP connection server for Bitmessage protocol""" def __init__(self, host='127.0.0.1', port=8444): - if not '_map' in dir(self): + if '_map' not in dir(self): AdvancedDispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() diff --git a/src/network/tls.py b/src/network/tls.py index 5a0f4c99..33e04f7f 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -67,6 +67,7 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc self.isSSL = False def state_tls_init(self): + print() """Prepare sockets for TLS handshake""" # pylint: disable=attribute-defined-outside-init self.isSSL = True @@ -94,13 +95,16 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc ciphers=self.ciphers, do_handshake_on_connect=False) self.sslSocket.setblocking(0) self.want_read = self.want_write = True + print('before tls file python 98 state are :- {}'.format(self.state)) self.set_state("tls_handshake") + print('after tls file python 100 state are :- {}'.format(self.state)) return False # if hasattr(self.socket, "context"): # self.socket.context.set_ecdh_curve("secp256k1") @staticmethod def state_tls_handshake(): + print("tls's state_tls_handshake method in line 107") """Do nothing while TLS handshake is pending, as during this phase we need to react to callbacks instead""" return False @@ -178,6 +182,7 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc return def tls_handshake(self): + print('inside the tls_handshake') """Perform TLS handshake and handle its stages""" # wait for flush if self.write_buf: From 0e593b66ad7bf2a4fb750ce4770a5ca7e268b429 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Fri, 15 Nov 2019 20:12:19 +0530 Subject: [PATCH 13/54] Added iteritems issues --- src/network/dandelion.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/src/network/dandelion.py b/src/network/dandelion.py index 6c34f525..e661fffb 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -105,14 +105,13 @@ class Dandelion(): # pylint: disable=old-style-class #hashMap is has any value # if not [hasmap for hasmap in self.hashMap.items()] ==[]: try: - if self.hashMap: - for k, v in iter({ - k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) - if v.child is None - }).items(): - self.hashMap[k] = Stem( - connection, v.stream, self.poissonTimeout()) - invQueue.put((v.stream, k, v.child)) + for k, v in { + k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) + if v.child is None + }.items(): + self.hashMap[k] = Stem( + connection, v.stream, self.poissonTimeout()) + invQueue.put((v.stream, k, v.child)) except AttributeError: pass @@ -139,10 +138,10 @@ class Dandelion(): # pylint: disable=old-style-class k for k, v in iter(self.nodeMap.items()) if v == connection ): self.nodeMap[k] = None - for k, v in iter({ + for k, v in { k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) if v.child == connection - }).items(): + }.items(): self.hashMap[k] = Stem( None, v.stream, self.poissonTimeout()) From ded1defb1f86835c27e4e7e10d828bec2f715909 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Sat, 30 Nov 2019 13:18:15 +0530 Subject: [PATCH 14/54] Worked on network issue and stopped the udp connection aand required the select's epoll condition and instead used select pollar method --- src/network/asyncore_pollchoose.py | 57 +++++++++++++++--------------- src/network/bmproto.py | 51 ++++++++++++++++++++------ src/network/connectionchooser.py | 7 ++-- src/network/connectionpool.py | 7 ++-- src/network/stats.py | 2 +- src/network/tcp.py | 3 ++ src/network/tls.py | 10 +++--- src/network/udp.py | 11 +++--- src/protocol.py | 1 + 9 files changed, 96 insertions(+), 53 deletions(-) diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 1c93283f..0c7198db 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -102,8 +102,7 @@ def _strerror(err): return os.strerror(err) except (ValueError, OverflowError, NameError): if err in errorcode: - return errorcode[err] - return "Unknown error %s" % err + ret18 ("Unknown error {}".format(err)) class ExitNow(Exception): @@ -247,25 +246,24 @@ def select_poller(timeout=0.0, map=None): if map is None: map = socket_map if map: - r = [] - w = [] - e = [] - for fd, obj in list(map.items()): + rd = [] + wt = [] + ex = [] + for fd, obj in map.items(): is_r = obj.readable() is_w = obj.writable() if is_r: - r.append(fd) + rd.append(fd) # accepting sockets should not be writable if is_w and not obj.accepting: - w.append(fd) + wt.append(fd) if is_r or is_w: - e.append(fd) - if [] == r == w == e: + ex.append(fd) + if [] == rd == wt == ex: time.sleep(timeout) return - try: - r, w, e = select.select(r, w, e, timeout) + rd, wt, ex = select.select(rd, wt, ex, timeout) except KeyboardInterrupt: return except socket.error as err: @@ -275,19 +273,19 @@ def select_poller(timeout=0.0, map=None): if err.args[0] in (WSAENOTSOCK, ): return - for fd in helper_random.randomsample(r, len(r)): + for fd in helper_random.randomsample(rd, len(rd)): obj = map.get(fd) if obj is None: continue read(obj) - for fd in helper_random.randomsample(w, len(w)): + for fd in helper_random.randomsample(wt, len(wt)): obj = map.get(fd) if obj is None: continue write(obj) - for fd in e: + for fd in ex: obj = map.get(fd) if obj is None: continue @@ -491,18 +489,18 @@ def loop(timeout=30.0, use_poll=False, map=None, count=None, poller=None): # argument which should no longer be used in favor of # "poller" - if poller is None: - if use_poll: - poller = poll_poller - elif hasattr(select, 'epoll'): - poller = epoll_poller - elif hasattr(select, 'kqueue'): - poller = kqueue_poller - elif hasattr(select, 'poll'): - poller = poll_poller - elif hasattr(select, 'select'): - poller = select_poller - + # if poller is None: + # if use_poll: + # poller = poll_poller + # elif hasattr(select, 'epoll'): + # poller = epoll_poller + # elif hasattr(select, 'kqueue'): + # poller = kqueue_poller + # elif hasattr(select, 'poll'): + # poller = poll_poller + # elif hasattr(select, 'select'): + # poller = select_poller + poller = select_poller if timeout == 0: deadline = 0 else: @@ -662,6 +660,9 @@ class dispatcher: def readable(self): """Predicate to indicate download throttle status""" + print('-------------------------------------') + print('---------------asyncore--------------') + print('-------------------------------------') if maxDownloadRate > 0: return downloadBucket > dispatcher.minTx return True @@ -788,7 +789,7 @@ class dispatcher: def log_info(self, message, log_type='info'): """Conditionally print a message""" if log_type not in self.ignore_log_types: - print ('{}: {}'.format((log_type, message))) + print ('{}: {}'.format(log_type, message)) def handle_read_event(self): """Handle a read event""" diff --git a/src/network/bmproto.py b/src/network/bmproto.py index a175fc43..f6ded3ca 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -30,6 +30,19 @@ from network.objectracker import missingObjects, ObjectTracker from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from network.randomtrackingdict import RandomTrackingDict +global addr_count +addr_count = 0 + +global addr_verack +addr_verack = 0 + +global addr_version +addr_version = 0 + +# global addr_count +# addr_count = 0 + +count = 0 class BMProtoError(ProxyError): """A Bitmessage Protocol Base Error""" @@ -89,6 +102,24 @@ class BMProto(AdvancedDispatcher, ObjectTracker): protocol.Header.unpack(self.read_buf[:protocol.Header.size]) #its shoule be in string self.command = self.command.rstrip('\x00'.encode('utf-8')) + global count,addr_version,addr_count,addr_verack + count+=1 + if self.command == 'verack'.encode(): + addr_verack+=1 + print('the addr_verack count are -{}'.format(addr_verack)) + + if self.command == 'version'.encode(): + addr_version+=1 + print('the addr_version count are -{}'.format(addr_version)) + + if self.command == 'addr'.encode(): + addr_count+=1 + print('the addr_count count are -{}'.format(addr_count)) + + # print('The count of the excaution are -{}'.format(count)) + # print('-----------count---------------{}'.format(count)) + # print('------self command-----------{}'.format(self.command)) + # print('----------self---------------{}'.format(self)) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync #in the advancedispatched and length commend's @@ -158,7 +189,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.set_state("close") return False if retval: - print('if retval is true and inside the if ') + # print('if retval is true and inside the if ') self.set_state("bm_header", length=self.payloadLength) self.bm_proto_reset() # else assume the command requires a different state to follow @@ -437,8 +468,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return self.decode_payload_content("LQIQ16sH") def bm_command_addr(self): - print('+++++++++++++++++++++++++++\ - bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') + # print('+++++++++++++++++++++++++++\ + # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') """Incoming addresses, process them""" addresses = self._decode_addr() # pylint: disable=redefined-outer-name for i in addresses: @@ -506,7 +537,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): length=self.payloadLength, expectBytes=0) return False def bm_command_version(self): - print('inside the bmproto ') + # print('inside the bmproto ') """ Incoming version. Parse and log, remember important things, like streams, bitfields, etc. @@ -543,12 +574,12 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.isSSL = True if not self.verackReceived: return True - print('inside the bmproto line') - print('before the value of state are :-{}'.format(self.state)) + # print('inside the bmproto line') + # print('before the value of state are :-{}'.format(self.state)) self.set_state( "tls_init" if self.isSSL else "connection_fully_established", length=self.payloadLength, expectBytes=0) - print('After the value of state are :-{}'.format(self.state)) + # print('After the value of state are :-{}'.format(self.state)) return False def peerValidityChecks(self): # pylint: disable=too-many-return-statements @@ -591,9 +622,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return False if self.destination in connectionpool.BMConnectionPool().inboundConnections: try: - print('+++++++++++++++++++++++++++') - print('self destination host -{}'.format(self.destination.host)) - print('++++++++++++++++++++++++++++++') + # print('+++++++++++++++++++++++++++') + # print('self destination host -{}'.format(self.destination.host)) + # print('++++++++++++++++++++++++++++++') if not protocol.checkSocksIP(self.destination.host): self.append_write_buf(protocol.assembleErrorMessage( errorText="Too many connections from your IP." diff --git a/src/network/connectionchooser.py b/src/network/connectionchooser.py index eb7c0f6e..99876135 100644 --- a/src/network/connectionchooser.py +++ b/src/network/connectionchooser.py @@ -11,7 +11,7 @@ from queues import Queue, portCheckerQueue def getDiscoveredPeer(): try: - peer = random.choice(state.discoveredPeers.keys()) + peer = random.choice([key for key in state.discoveredPeers.keys()]) except (IndexError, KeyError): raise ValueError try: @@ -24,6 +24,7 @@ def getDiscoveredPeer(): def chooseConnection(stream): haveOnion = BMConfigParser().safeGet( "bitmessagesettings", "socksproxytype")[0:5] == 'SOCKS' + if state.trustedPeer: return state.trustedPeer try: @@ -37,14 +38,14 @@ def chooseConnection(stream): # discovered peers are already filtered by allowed streams return getDiscoveredPeer() for _ in range(50): - peer = random.choice(list(knownnodes.knownNodes[stream].keys())) + peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()]) try: peer_info = knownnodes.knownNodes[stream][peer] if peer_info.get('self'): continue rating = peer_info["rating"] except TypeError: - logger.warning('Error in %s', peer) + logger.warning('Error in {}'.format(peer)) rating = 0 if haveOnion: # onion addresses have a higher priority when SOCKS diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 374ebc62..509c0d1f 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -18,7 +18,7 @@ from debug import logger from network.proxy import Proxy from singleton import Singleton from network.tcp import ( - TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection,bootstrap) + TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection,bootstrap) from network.udp import UDPSocket @@ -147,6 +147,7 @@ class BMConnectionPool(object): port = int(BMConfigParser().safeGet("bitmessagesettings", "port")) # correct port even if it changed ls = TCPServer(host=bind, port=port) + print('inside the startListening method') self.listeningSockets[ls.destination] = ls def startUDPSocket(self, bind=None): @@ -219,6 +220,7 @@ class BMConnectionPool(object): self.startBootstrappers() knownnodes.knownNodesActual = True if not self.bootstrapped: + self.bootstrapped = True Proxy.proxy = ( BMConfigParser().safeGet( @@ -295,6 +297,7 @@ class BMConnectionPool(object): ): # FIXME: rating will be increased after next connection i.handle_close() + if acceptConnections: if not self.listeningSockets: if BMConfigParser().safeGet('network', 'bind') == '': @@ -306,7 +309,7 @@ class BMConnectionPool(object): ).split(): self.startListening(bind) logger.info('Listening for incoming connections.') - if not self.udpSockets: + if False: # self.udpSockets :- {'0.0.0.0': } if BMConfigParser().safeGet('network', 'bind') == '': self.startUDPSocket() diff --git a/src/network/stats.py b/src/network/stats.py index 7d6a5550..b6ac4f4b 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -32,7 +32,7 @@ def connectedHostsList(): retval.append(i) except AttributeError: pass - print('#################### retval -{}'.format(retval)) + # print('#################### retval -{}'.format(retval)) return retval diff --git a/src/network/tcp.py b/src/network/tcp.py index f07d9b1c..945740a0 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -367,8 +367,10 @@ class TCPServer(AdvancedDispatcher): self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() for attempt in range(50): + print('inside the attempt of line 371') try: if attempt > 0: + print('inside the if condition attempt in 373') port = random.randint(32767, 65535) self.bind((host, port)) except socket.error as e: @@ -376,6 +378,7 @@ class TCPServer(AdvancedDispatcher): continue else: if attempt > 0: + print('inside the if condition attempt in 381') BMConfigParser().set( 'bitmessagesettings', 'port', str(port)) BMConfigParser().save() diff --git a/src/network/tls.py b/src/network/tls.py index 33e04f7f..73f64e4e 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -67,7 +67,7 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc self.isSSL = False def state_tls_init(self): - print() + # print() """Prepare sockets for TLS handshake""" # pylint: disable=attribute-defined-outside-init self.isSSL = True @@ -95,16 +95,16 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc ciphers=self.ciphers, do_handshake_on_connect=False) self.sslSocket.setblocking(0) self.want_read = self.want_write = True - print('before tls file python 98 state are :- {}'.format(self.state)) + # print('before tls file python 98 state are :- {}'.format(self.state)) self.set_state("tls_handshake") - print('after tls file python 100 state are :- {}'.format(self.state)) + # print('after tls file python 100 state are :- {}'.format(self.state)) return False # if hasattr(self.socket, "context"): # self.socket.context.set_ecdh_curve("secp256k1") @staticmethod def state_tls_handshake(): - print("tls's state_tls_handshake method in line 107") + # print("tls's state_tls_handshake method in line 107") """Do nothing while TLS handshake is pending, as during this phase we need to react to callbacks instead""" return False @@ -182,7 +182,7 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc return def tls_handshake(self): - print('inside the tls_handshake') + # print('inside the tls_handshake') """Perform TLS handshake and handle its stages""" # wait for flush if self.write_buf: diff --git a/src/network/udp.py b/src/network/udp.py index c3e4ce44..2280b77f 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -72,11 +72,14 @@ class UDPSocket(BMProto): # pylint: disable=too-many-instance-attribut addresses = self._decode_addr() # only allow peer discovery from private IPs in order to avoid # attacks from random IPs on the internet - if not self.local: - return True + # if not self.local: + # return True + self.local = True remoteport = False for seenTime, stream, services, ip, port in addresses: - decodedIP = protocol.checkIPAddress(str(ip)) + # decodedIP = bool(protocol.checkIPAddress(ip)) + decodedIP = False + if stream not in state.streamsInWhichIAmParticipating: continue if (seenTime < time.time() - self.maxTimeOffset or seenTime > time.time() + self.maxTimeOffset): @@ -88,7 +91,7 @@ class UDPSocket(BMProto): # pylint: disable=too-many-instance-attribut if remoteport is False: return True logger.debug( - "received peer discovery from %s:%i (port %i):", + "received peer discovery from {}:{} (port {}):", self.destination.host, self.destination.port, remoteport) if self.local: state.discoveredPeers[ diff --git a/src/protocol.py b/src/protocol.py index a8d5a9a3..cf030954 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -178,6 +178,7 @@ def haveSSL(server=False): python < 2.7.9's ssl library does not support ECDSA server due to missing initialisation of available curves, but client works ok """ + return False if not server: return True elif sys.version_info >= (2, 7, 9): From d8d57024db2f30e033babf438434879349559da0 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Sat, 7 Dec 2019 20:07:35 +0530 Subject: [PATCH 15/54] Added new changes for the network issue --- src/network/asyncore_pollchoose.py | 5 +---- src/network/bmproto.py | 24 ++++++++++-------------- src/network/stats.py | 2 +- src/network/tls.py | 1 - 4 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 0c7198db..3f6e8ad0 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -249,7 +249,7 @@ def select_poller(timeout=0.0, map=None): rd = [] wt = [] ex = [] - for fd, obj in map.items(): + for fd, obj in list(map.items()): is_r = obj.readable() is_w = obj.writable() if is_r: @@ -660,9 +660,6 @@ class dispatcher: def readable(self): """Predicate to indicate download throttle status""" - print('-------------------------------------') - print('---------------asyncore--------------') - print('-------------------------------------') if maxDownloadRate > 0: return downloadBucket > dispatcher.minTx return True diff --git a/src/network/bmproto.py b/src/network/bmproto.py index f6ded3ca..772e4eaf 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -106,20 +106,16 @@ class BMProto(AdvancedDispatcher, ObjectTracker): count+=1 if self.command == 'verack'.encode(): addr_verack+=1 - print('the addr_verack count are -{}'.format(addr_verack)) + # print('the addr_verack count are -{}'.format(addr_verack)) if self.command == 'version'.encode(): addr_version+=1 - print('the addr_version count are -{}'.format(addr_version)) + # print('the addr_version count are -{}'.format(addr_version)) if self.command == 'addr'.encode(): addr_count+=1 - print('the addr_count count are -{}'.format(addr_count)) + # print('the addr_count count are -{}'.format(addr_count)) - # print('The count of the excaution are -{}'.format(count)) - # print('-----------count---------------{}'.format(count)) - # print('------self command-----------{}'.format(self.command)) - # print('----------self---------------{}'.format(self)) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync #in the advancedispatched and length commend's @@ -569,17 +565,17 @@ class BMProto(AdvancedDispatcher, ObjectTracker): logger.debug( '%(host)s:%(port)i sending version', self.destination._asdict()) - if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL) and - protocol.haveSSL(not self.isOutbound)): - self.isSSL = True + if ((self.services & protocol.NODE_SSL == protocol.NODE_SSL)): + # self.isSSL = True + pass if not self.verackReceived: return True - # print('inside the bmproto line') - # print('before the value of state are :-{}'.format(self.state)) + # self.set_state( + # "tls_init" if self.isSSL else "connection_fully_established", + # length=self.payloadLength, expectBytes=0) self.set_state( - "tls_init" if self.isSSL else "connection_fully_established", + "connection_fully_established", length=self.payloadLength, expectBytes=0) - # print('After the value of state are :-{}'.format(self.state)) return False def peerValidityChecks(self): # pylint: disable=too-many-return-statements diff --git a/src/network/stats.py b/src/network/stats.py index b6ac4f4b..e6c37499 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -32,7 +32,7 @@ def connectedHostsList(): retval.append(i) except AttributeError: pass - # print('#################### retval -{}'.format(retval)) + return retval diff --git a/src/network/tls.py b/src/network/tls.py index 73f64e4e..0a6bcd91 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -84,7 +84,6 @@ class TLSDispatcher(AdvancedDispatcher): # pylint: disable=too-many-instanc # also exclude TLSv1 and TLSv1.1 in the future context.options = ssl.OP_ALL | ssl.OP_NO_SSLv2 |\ ssl.OP_NO_SSLv3 | ssl.OP_SINGLE_ECDH_USE | ssl.OP_CIPHER_SERVER_PREFERENCE - self.sslSocket = context.wrap_socket( self.socket, server_side=self.server_side, do_handshake_on_connect=False) else: From fda6e5605adde3597ae6009cb9e363f11a5f7260 Mon Sep 17 00:00:00 2001 From: navjot Date: Thu, 12 Dec 2019 20:08:07 +0530 Subject: [PATCH 16/54] Kivy code update part 1 --- src/bitmessagekivy/kivy_helper_search.py | 24 +- src/bitmessagekivy/main.kv | 276 ++-- src/bitmessagekivy/mpybit.py | 1901 ++++++++++++++-------- src/images/loader.zip | Bin 0 -> 15918 bytes src/state.py | 4 + 5 files changed, 1433 insertions(+), 772 deletions(-) create mode 100644 src/images/loader.zip diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index a1fe4a99..48e77cb2 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -1,11 +1,10 @@ """ -src/bitmessagekivy/kivy_helper_search.py -================================= +Sql queries for bitmessagekivy """ from helper_sql import sqlQuery -def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False): +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 != "": @@ -14,14 +13,15 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w what = None if folder == "sent" or folder == "draft": - sqlStatementBase = ''' - SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime - FROM sent ''' + sqlStatementBase = ( + '''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 ''' + sqlStatementBase = ( + '''SELECT folder, msgid, toaddress, message, fromaddress, subject,''' + ''' received, read FROM inbox ''') sqlStatementParts = [] sqlArguments = [] @@ -58,8 +58,10 @@ 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 == "sent": - sqlStatementBase += " ORDER BY lastactiontime DESC" + if folder == "sent" or folder == "draft": + sqlStatementBase += " ORDER BY lastactiontime DESC limit {0}, {1}".format(start_indx, end_indx) elif folder == "inbox": - sqlStatementBase += " ORDER BY received DESC" + 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) diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 3afc794b..b360a534 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -1,38 +1,21 @@ #:import MDToolbar kivymd.uix.toolbar.MDToolbar -#:import ThemeManager kivymd.theming.ThemeManager -#:import MDNavigationDrawer kivymd.uix.navigationdrawer.MDNavigationDrawer #:import NavigationLayout kivymd.uix.navigationdrawer.NavigationLayout #:import NavigationDrawerDivider kivymd.uix.navigationdrawer.NavigationDrawerDivider -#:import NavigationDrawerToolbar kivymd.uix.navigationdrawer.NavigationDrawerToolbar #:import NavigationDrawerSubheader kivymd.uix.navigationdrawer.NavigationDrawerSubheader #:import MDCheckbox kivymd.uix.selectioncontrol.MDCheckbox -#:import MDSwitch kivymd.uix.selectioncontrol.MDSwitch #:import MDList kivymd.uix.list.MDList #:import OneLineListItem kivymd.uix.list.OneLineListItem -#:import TwoLineListItem kivymd.uix.list.TwoLineListItem -#:import ThreeLineListItem kivymd.uix.list.ThreeLineListItem -#:import OneLineAvatarListItem kivymd.uix.list.OneLineAvatarListItem -#:import OneLineIconListItem kivymd.uix.list.OneLineIconListItem -#:import OneLineAvatarIconListItem kivymd.uix.list.OneLineAvatarIconListItem #:import MDTextField kivymd.uix.textfield.MDTextField -#:import MDSpinner kivymd.uix.spinner.MDSpinner -#:import MDCard kivymd.uix.card.MDCard -#:import MDSeparator kivymd.uix.card.MDSeparator -#:import MDDropdownMenu kivymd.uix.menu.MDDropdownMenu #:import get_color_from_hex kivy.utils.get_color_from_hex +#:import MDCard kivymd.uix.card.MDCard #:import colors kivymd.color_definitions.colors -#:import MDSlider kivymd.uix.slider.MDSlider #:import MDTabs kivymd.uix.tab.MDTabs -#:import MDProgressBar kivymd.uix.progressbar.MDProgressBar -#:import MDAccordion kivymd.uix.accordion.MDAccordion -#:import MDAccordionItem kivymd.uix.accordion.MDAccordionItem -#:import MDAccordionSubItem kivymd.uix.accordion.MDAccordionSubItem #:import MDFloatingActionButton kivymd.uix.button.MDFloatingActionButton #:import Factory kivy.factory.Factory -#:import MDTextButton kivymd.uix.button.MDTextButton -#:import FadeTransition kivy.uix.screenmanager.FadeTransition #:import MDScrollViewRefreshLayout kivymd.uix.refreshlayout.MDScrollViewRefreshLayout +#:import MDSpinner kivymd.uix.spinner.MDSpinner +#:import NoTransition kivy.uix.screenmanager.NoTransition #:import MDTabsBase kivymd.uix.tab.MDTabsBase @@ -51,8 +34,9 @@ color: color_font : - drawer_logo: app.address_identicon() + drawer_logo: './images/drawer_logo1.png' NavigationDrawerDivider: + height: dp(7) NavigationDrawerSubheader: text: "Accounts" NavigationDrawerIconButton: @@ -79,52 +63,47 @@ text: "Inbox" on_release: app.root.ids.scr_mngr.current = 'inbox' badge_text: "0" - on_press: app.refreshScreen(self) + on_press: app.load_screen(self) NavigationDrawerIconButton: id: send_cnt icon: 'send' text: "Sent" on_release: app.root.ids.scr_mngr.current = 'sent' badge_text: "0" - on_press: app.refreshScreen(self) NavigationDrawerIconButton: id: draft_cnt icon: 'message-draw' text: "Draft" on_release: app.root.ids.scr_mngr.current = 'draft' badge_text: "0" - on_press: app.refreshScreen(self) - NavigationDrawerIconButton: - text: "Starred" - icon:'star' - on_release: app.root.ids.scr_mngr.current = 'starred' - on_press: app.refreshScreen(self) - NavigationDrawerIconButton: - icon: 'archive' - text: "Archieve" - on_release: app.root.ids.scr_mngr.current = 'archieve' - badge_text: "0" - on_press: app.refreshScreen(self) - NavigationDrawerIconButton: - icon: 'email-open-outline' - text: "Spam" - on_release: app.root.ids.scr_mngr.current = 'spam' - badge_text: "0" - on_press: app.refreshScreen(self) + #NavigationDrawerIconButton: + #text: "Starred" + #icon:'star' + #on_release: app.root.ids.scr_mngr.current = 'starred' + #badge_text: "0" + #NavigationDrawerIconButton: + #icon: 'archive' + #text: "Archieve" + #on_release: app.root.ids.scr_mngr.current = 'archieve' + #badge_text: "0" + #NavigationDrawerIconButton: + #icon: 'email-open-outline' + #text: "Spam" + #on_release: app.root.ids.scr_mngr.current = 'spam' + #badge_text: "0" NavigationDrawerIconButton: id: trash_cnt icon: 'delete' text: "Trash" on_release: app.root.ids.scr_mngr.current = 'trash' badge_text: "0" - on_press: app.refreshScreen(self) NavigationDrawerIconButton: id: allmail_cnt text: "All Mails" icon:'contact-mail' on_release: app.root.ids.scr_mngr.current = 'allmails' badge_text: "0" - on_press: app.refreshScreen(self) + on_press: app.load_screen(self) NavigationDrawerDivider: NavigationDrawerSubheader: text: "All labels" @@ -132,37 +111,30 @@ text: "Address Book" icon:'book-multiple' on_release: app.root.ids.scr_mngr.current = 'addressbook' - on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "Settings" icon:'settings' on_release: app.root.ids.scr_mngr.current = 'set' - on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "Subscriptions/Payment" icon:'bell' on_release: app.root.ids.scr_mngr.current = 'payment' - on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "Credits" icon:'wallet' on_release: app.root.ids.scr_mngr.current = 'credits' - on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "new address" icon:'account-plus' on_release: app.root.ids.scr_mngr.current = 'login' - on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "Network Status" icon:'server-network' on_release: app.root.ids.scr_mngr.current = 'networkstat' - on_press: app.refreshScreen(self) NavigationDrawerIconButton: text: "My Addresses" icon:'account-multiple' on_release: app.root.ids.scr_mngr.current = 'myaddress' - on_press: app.refreshScreen(self) NavigationLayout: id: nav_layout @@ -170,78 +142,87 @@ NavigationLayout: ContentNavigationDrawer: id: nav_drawer - BoxLayout: - id: box_layout - orientation: 'vertical' - MDToolbar: - id: toolbar - title: app.current_address_label() - opacity: 1 if app.addressexist() else 0 - disabled: False if app.addressexist() else True - md_bg_color: app.theme_cls.primary_color - background_palette: 'Primary' - background_hue: '500' - left_action_items: [['menu', lambda x: app.root.toggle_nav_drawer()]] - right_action_items: [['account-plus', lambda x: app.addingtoaddressbook()]] + FloatLayout: + id: float_box + BoxLayout: + id: box_layout + orientation: 'vertical' + MDToolbar: + id: toolbar + title: app.current_address_label() + opacity: 1 if app.addressexist() else 0 + disabled: False if app.addressexist() else True + md_bg_color: app.theme_cls.primary_color + background_palette: 'Primary' + background_hue: '500' + left_action_items: [['menu', lambda x: app.root.toggle_nav_drawer()]] + right_action_items: [['account-plus', lambda x: app.addingtoaddressbook()]] - ScreenManager: - id: scr_mngr - Inbox: - id:sc1 - Page: - id:sc2 - Create: - id:sc3 - Sent: - id:sc4 - Trash: - id:sc5 - Login: - id:sc6 - Random: - id:sc7 - AddressSuccessful: - id:sc8 - Setting: - id:sc9 - MyAddress: - id:sc10 - AddressBook: - id:sc11 - Payment: - id:sc12 - NetworkStat: - id:sc13 - MailDetail: - id:sc14 - ShowQRCode: - id:sc15 - Draft: - id:sc16 - Allmails: - id:sc17 - Credits: - id:sc18 - Starred: - id:sc19 - Archieve: - id:sc20 - Spam: - id:sc21 + ScreenManager: + id: scr_mngr + Inbox: + id:sc1 + Page: + id:sc2 + Create: + id:sc3 + Sent: + id:sc4 + Trash: + id:sc5 + Login: + id:sc6 + Random: + id:sc7 + Spam: + id:sc8 + Setting: + id:sc9 + MyAddress: + id:sc10 + AddressBook: + id:sc11 + Payment: + id:sc12 + NetworkStat: + id:sc13 + MailDetail: + id:sc14 + ShowQRCode: + id:sc15 + Draft: + id:sc16 + Allmails: + id:sc17 + Credits: + id:sc18 + Starred: + id:sc19 + Archieve: + id:sc20 : name: 'inbox' + transition: NoTransition() BoxLayout: orientation: 'vertical' spacing: dp(10) SearchBar: - FloatLayout: - MDScrollViewRefreshLayout: - id: refresh_layout - refresh_callback: root.refresh_callback - root_layout: root + #FloatLayout: + # MDScrollViewRefreshLayout: + # id: refresh_layout + # refresh_callback: root.refresh_callback + # root_layout: root.set_root_layout() + # MDList: + # id: ml + BoxLayout: + orientation:'vertical' + ScrollView: + id: scroll_y + do_scroll_x: False MDList: id: ml + Loader: ComposerButton: : @@ -252,22 +233,27 @@ NavigationLayout: BoxLayout: orientation:'vertical' ScrollView: + id: scroll_y do_scroll_x: False MDList: id: ml + Loader: ComposerButton: : name: 'trash' ScrollView: + id: scroll_y do_scroll_x: False MDList: id: ml + Loader: ComposerButton: : name: 'draft' ScrollView: + id: scroll_y do_scroll_x: False MDList: id: ml @@ -299,13 +285,21 @@ NavigationLayout: : name: 'allmails' - FloatLayout: - MDScrollViewRefreshLayout: - id: refresh_layout - refresh_callback: root.refresh_callback - root_layout: root + #FloatLayout: + # MDScrollViewRefreshLayout: + # id: refresh_layout + # refresh_callback: root.refresh_callback + # root_layout: root.set_root_layout() + # MDList: + # id: ml + BoxLayout: + orientation:'vertical' + ScrollView: + id: scroll_y + do_scroll_x: False MDList: id: ml + Loader: ComposerButton: : @@ -322,6 +316,7 @@ NavigationLayout: : name: 'create' + Loader: : name: 'credits' @@ -389,7 +384,7 @@ NavigationLayout: size_hint_y: None font_size: '13sp' height: self.parent.height/2 - hint_text: 'type or search recipients address starting with BM-' + hint_text: 'type, select or scan QR code for recipients address' RV: id: rv MDTextField: @@ -499,6 +494,7 @@ NavigationLayout: MDRaisedButton: height: dp(40) on_press: app.root.ids.scr_mngr.current = 'random' + on_press: app.root.ids.sc7.reset_address_label() MDLabel: font_style: 'H6' text: 'proceed' @@ -535,6 +531,7 @@ NavigationLayout: hint_text: "Label" required: True helper_text_mode: "on_error" + on_text: root.add_validation(self) BoxLayout: AnchorLayout: MDRaisedButton: @@ -632,9 +629,10 @@ NavigationLayout: MDScrollViewRefreshLayout: id: refresh_layout refresh_callback: root.refresh_callback - root_layout: root + root_layout: root.set_root_layout() MDList: id: ml + Loader: ComposerButton: : @@ -645,9 +643,11 @@ NavigationLayout: BoxLayout: orientation:'vertical' ScrollView: + id: scroll_y do_scroll_x: False MDList: id: ml + Loader: ComposerButton: : @@ -656,7 +656,7 @@ NavigationLayout: do_scroll_x: False BoxLayout: orientation: 'vertical' - padding: [dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1), dp(10)] + padding: [dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/6 if app.window_size[0] <= 800 else app.window_size[0]/18), dp(10)] spacing: 12 size_hint_y: None height: self.minimum_height + dp(app.window_size[1]) if app.window_size[1] > app.window_size[0] else dp(app.window_size[0]) @@ -820,6 +820,7 @@ NavigationLayout: hint_text: "Label" required: True helper_text_mode: "on_error" + on_text: root.checkLabel_valid(self) MDTextField: id: address hint_text: "Address" @@ -968,24 +969,24 @@ NavigationLayout: font_size: '20sp' CopyTextBtn: MDLabel: - font_style: 'H4' + font_style: 'Body1' theme_text_color: 'Primary' text: "From: " + root.from_addr halign: 'left' CopyTextBtn: MDLabel: - font_style: 'H4' + font_style: 'Body1' theme_text_color: 'Primary' text: "To: " + root.to_addr halign: 'left' CopyTextBtn: MDLabel: - font_style: 'H4' + font_style: 'Body1' theme_text_color: 'Primary' text: root.status halign: 'left' MDLabel: - font_style: 'H4' + font_style: 'Subtitle2' theme_text_color: 'Primary' text: root.message halign: 'left' @@ -995,6 +996,7 @@ NavigationLayout: orientation: 'vertical' size_hint_y: None height: dp(100) + self.minimum_height + Loader: : id: cpyButton @@ -1137,6 +1139,7 @@ NavigationLayout: theme_text_color: 'Primary' required: True helper_text_mode: "on_error" + on_text: root.checkLabel_valid(self) MDLabel: font_style: 'Subtitle2' theme_text_color: 'Primary' @@ -1144,6 +1147,7 @@ NavigationLayout: font_size: '17sp' halign: 'left' MDLabel: + id: address font_style: 'Body1' theme_text_color: 'Primary' text: root.address @@ -1211,4 +1215,26 @@ NavigationLayout: MDTextField: id: search_field hint_text: 'Search' - on_text: app.searchQuery(self) \ No newline at end of file + on_text: app.searchQuery(self) + + +: + separator_color: 1, 1, 1, 1 + background: "White.png" + Button: + id: btn + disabled: True + background_disabled_normal: "White.png" + Image: + source: './images/loader.zip' + anim_delay: 0 + #mipmap: True + size: root.size + + +: + id: spinner + size_hint: None, None + size: dp(46), dp(46) + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + active: False \ No newline at end of file diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 5c41577e..1a0d13f2 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -5,8 +5,8 @@ src/bitmessagekivy/mpybit.py # pylint: disable=relative-import, unused-variable, import-error, no-name-in-module, too-many-lines import os import time -from functools import partial from bmconfigparser import BMConfigParser +from functools import partial from helper_sql import sqlExecute, sqlQuery from kivy.app import App from kivy.clock import Clock @@ -19,7 +19,8 @@ from kivy.properties import ( ListProperty, NumericProperty, ObjectProperty, - StringProperty) + StringProperty +) from kivy.uix.behaviors import FocusBehavior from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button @@ -44,7 +45,8 @@ from kivymd.uix.list import ( ILeftBodyTouch, IRightBodyTouch, TwoLineAvatarIconListItem, - TwoLineListItem) + TwoLineListItem +) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, NavigationDrawerHeaderBase) @@ -58,6 +60,7 @@ import state from bitmessagekivy.uikivysignaler import UIkivySignaler from bitmessagekivy import identiconGeneration +from addresses import addBMIfNotPresent, decodeAddress, encodeVarint # pylint: disable=unused-argument, too-few-public-methods @@ -78,80 +81,54 @@ class Navigatorss(MDNavigationDrawer): class Inbox(Screen): """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.""" super(Inbox, self).__init__(*args, **kwargs) + Clock.schedule_once(self.init_ui, 0) + + @staticmethod + def set_defaultAddress(): + """This method set default address""" if state.association == '': if BMConfigParser().addresses(): state.association = BMConfigParser().addresses()[0] - Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method inbox accounts.""" - self.inboxaccounts() - print(dt) + """Clock schdule for method inbox accounts.""" + self.loadMessagelist() - def inboxaccounts(self): - """Load inbox accounts.""" - account = state.association - self.loadMessagelist(account, 'All', '') - - def loadMessagelist(self, account, where="", what=""): + def loadMessagelist(self, where="", what=""): """Load Inbox list for Inbox messages.""" # pylint: disable=too-many-locals + self.set_defaultAddress() + self.account = state.association if state.searcing_text: + self.children[2].children[0].children[0].scroll_y = 1.0 where = ['subject', 'message'] what = state.searcing_text xAddress = 'toaddress' data = [] - queryreturn = kivy_helper_search.search_sql( - xAddress, account, "inbox", where, what, False) - if queryreturn: + self.inboxDataQuery(xAddress, where, what) + if self.queryreturn: + state.kivyapp.get_inbox_count() src_mng_obj = state.kivyapp.root.children[2].children[0].ids - src_mng_obj.inbox_cnt.badge_text = str(len(queryreturn)) - state.inbox_count = str(len(queryreturn)) - state.kivyapp.root.ids.sc17.clear_widgets() - state.kivyapp.root.ids.sc17.add_widget(Allmails()) - for mail in queryreturn: - third_text = mail[3].replace('\n', ' ') + src_mng_obj.inbox_cnt.badge_text = state.inbox_count + for mail in self.queryreturn: + # third_text = mail[3].replace('\n', ' ') data.append({ 'text': mail[4].strip(), 'secondary_text': mail[5][:50] + '........' if len( - mail[5]) >= 50 else ( - mail[5] + ',' + mail[3].replace('\n', ''))[0:50] + '........', + mail[5]) >= 50 else (mail[5] + ',' + mail[3].replace( + '\n', ''))[0:50] + '........', 'msgid': mail[1]}) - for item in data: - meny = TwoLineAvatarIconListItem( - text=item['text'], - secondary_text=item['secondary_text'], - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - meny.add_widget(AvatarSampleWidget( - source='./images/text_images/{}.png'.format( - avatarImageFirstLetter(item['secondary_text'].strip())))) - meny.bind(on_press=partial( - self.inbox_detail, item['msgid'])) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Delete') - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) - del_btn.bind(on_press=partial( - self.delete, item['msgid'])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - ach_btn = Button(text='Achieve') - ach_btn.background_color = (0, 1, 0, 1) - ach_btn.bind(on_press=partial( - self.archive, item['msgid'])) - carousel.add_widget(ach_btn) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + self.has_refreshed = True + self.set_mdList(data) + self.children[2].children[0].children[0].bind( + scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -163,8 +140,90 @@ class Inbox(Screen): valign='top') self.ids.ml.add_widget(content) + # pylint: disable=too-many-arguments + def inboxDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): + """This method used for retrieving inbox data""" + self.queryreturn = kivy_helper_search.search_sql( + xAddress, + self.account, + "inbox", + where, + what, + False, + start_indx, + end_indx) + + def set_mdList(self, data): + """This method is used to create the mdList""" + total_message = len(self.ids.ml.children) + for item in data: + meny = TwoLineAvatarIconListItem( + text=item['text'], + secondary_text=item['secondary_text'], + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + meny.add_widget( + AvatarSampleWidget( + source='./images/text_images/{}.png'.format( + avatarImageFirstLetter( + item['secondary_text'].strip())))) + meny.bind( + on_press=partial( + self.inbox_detail, item['msgid'])) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Delete') + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) + del_btn.bind( + on_press=partial( + self.delete, item['msgid'])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + ach_btn = Button(text='Achieve') + ach_btn.background_color = (0, 1, 0, 1) + ach_btn.bind( + on_press=partial( + self.archive, item['msgid'])) + carousel.add_widget(ach_btn) + carousel.index = 1 + self.ids.ml.add_widget(carousel) + update_message = len(self.ids.ml.children) + self.has_refreshed = True if total_message != update_message else False + + def check_scroll_y(self, instance, somethingelse): + """This method is used to load data on scroll""" + if self.children[2].children[0].children[ + 0].scroll_y <= -0.0 and self.has_refreshed: + self.children[2].children[0].children[0].scroll_y = 0.06 + total_message = len(self.ids.ml.children) + self.update_inbox_screen_on_scroll(total_message) + else: + pass + + def update_inbox_screen_on_scroll(self, total_message, where="", what=""): + """This method is used to load more data on scroll down""" + data = [] + if state.searcing_text: + where = ['subject', 'message'] + what = state.searcing_text + self.inboxDataQuery('toaddress', where, what, total_message, 5) + for mail in self.queryreturn: + # third_text = mail[3].replace('\n', ' ') + data.append({ + 'text': mail[4].strip(), + 'secondary_text': mail[5][:50] + '........' if len( + mail[5]) >= 50 else (mail[5] + ',' + mail[3].replace( + '\n', ''))[0:50] + '........', + 'msgid': mail[1]}) + self.set_mdList(data) + def inbox_detail(self, msg_id, *args): - """Load inbox page details.""" + """Load inbox page details""" state.detailPageType = 'inbox' state.mail_id = msg_id if self.manager: @@ -176,16 +235,17 @@ class Inbox(Screen): src_mng_obj.current = 'mailDetail' def delete(self, data_index, instance, *args): - """Delete inbox mail from inbox listing.""" + """Delete inbox mail from inbox listing""" sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( data_index)) try: - msg_count_objs = \ - self.parent.parent.parent.parent.children[2].children[0].ids - except Exception as e: - msg_count_objs = \ - self.parent.parent.parent.parent.parent.children[2].children[0].ids + msg_count_objs = ( + self.parent.parent.parent.parent.children[2].children[0].ids) + except Exception: + msg_count_objs = ( + self.parent.parent.parent.parent.parent.children[ + 2].children[0].ids) if int(state.inbox_count) > 0: msg_count_objs.inbox_cnt.badge_text = str( int(state.inbox_count) - 1) @@ -205,7 +265,7 @@ class Inbox(Screen): self.update_trash() def archive(self, data_index, instance, *args): - """Archive inbox mail from inbox listing.""" + """Archive inbox mail from inbox listing""" sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( data_index)) @@ -213,7 +273,7 @@ class Inbox(Screen): self.update_trash() def update_trash(self): - """Update trash screen mails which is deleted from inbox.""" + """Update trash screen mails which is deleted from inbox""" try: self.parent.screens[4].clear_widgets() self.parent.screens[4].add_widget(Trash()) @@ -223,53 +283,51 @@ class Inbox(Screen): # pylint: disable=attribute-defined-outside-init def refresh_callback(self, *args): - """Method updates the state of application, While the spinner remains on the screen.""" + """Method updates the state of application, + While the spinner remains on the screen""" def refresh_callback(interval): - """Method used for loading the inbox screen data.""" + """Method used for loading the inbox screen data""" state.searcing_text = '' self.children[2].children[1].ids.search_field.text = '' self.ids.ml.clear_widgets() self.loadMessagelist(state.association) + self.has_refreshed = True self.ids.refresh_layout.refresh_done() self.tick = 0 Clock.schedule_once(refresh_callback, 1) + # def set_root_layout(self): + # """Setting root layout""" + # return self.parent.parent.parent + 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 inbox accounts.""" + """Clock schdule for method Myaddress accounts.""" super(MyAddress, self).__init__(*args, **kwargs) Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method inbox accounts.""" + """Clock schdule for method Myaddress accounts""" # pylint: disable=unnecessary-lambda, deprecated-lambda - addresses_list = state.kivyapp.variable_1 + 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()) - addresses_list = filtered_list - if addresses_list: - data = [] - for address in addresses_list: - data.append({ - 'text': BMConfigParser().get(address, 'label'), - 'secondary_text': address}) - for item in data: - meny = TwoLineAvatarIconListItem( - text=item['text'], - secondary_text=item['secondary_text'], - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - meny.add_widget(AvatarSampleWidget( - source='./images/text_images/{}.png'.format(avatarImageFirstLetter(item['text'].strip())))) - meny.bind(on_press=partial( - self.myadd_detail, item['secondary_text'], item['text'])) - self.ids.ml.add_widget(meny) + self.addresses_list = filtered_list + self.addresses_list = [obj for obj in reversed(self.addresses_list)] + if self.addresses_list: + self.has_refreshed = True + self.set_mdList(0, 15) + self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -280,90 +338,114 @@ class MyAddress(Screen): size_hint_y=None, valign='top') self.ids.ml.add_widget(content) - if not state.searcing_text: + if not state.searcing_text and not self.is_add_created: try: self.manager.current = 'login' except Exception: pass + def set_mdList(self, first_index, last_index): + """Creating the mdlist""" + data = [] + for address in self.addresses_list[first_index:last_index]: + data.append({ + 'text': BMConfigParser().get(address, 'label'), + 'secondary_text': address}) + for item in data: + meny = TwoLineAvatarIconListItem( + text=item['text'], + secondary_text=item['secondary_text'], + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + meny.add_widget(AvatarSampleWidget( + source='./images/text_images/{}.png'.format( + avatarImageFirstLetter(item['text'].strip())))) + meny.bind(on_press=partial( + self.myadd_detail, item['secondary_text'], item['text'])) + self.ids.ml.add_widget(meny) + + def check_scroll_y(self, instance, somethingelse): + """Load data on scroll down""" + if self.ids.refresh_layout.scroll_y <= -0.0 and self.has_refreshed: + self.ids.refresh_layout.scroll_y = 0.06 + my_addresses = len(self.ids.ml.children) + if my_addresses != len(self.addresses_list): + self.update_addressBook_on_scroll(my_addresses) + self.has_refreshed = True if my_addresses != len( + self.addresses_list) else False + else: + pass + + def update_addressBook_on_scroll(self, my_addresses): + """Loads more data on scroll down""" + self.set_mdList(my_addresses, my_addresses + 20) + @staticmethod def myadd_detail(fromaddress, label, *args): - """Myaddress Details.""" + """Load myaddresses details""" p = MyaddDetailPopup() p.open() p.set_address(fromaddress, label) # pylint: disable=attribute-defined-outside-init def refresh_callback(self, *args): - """Method updates the state of application, While the spinner remains on the screen.""" + """Method updates the state of application, + While the spinner remains on the screen""" def refresh_callback(interval): - """Method used for loading the myaddress screen data.""" + """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.has_refreshed = True self.ids.ml.clear_widgets() self.init_ui() self.ids.refresh_layout.refresh_done() self.tick = 0 - Clock.schedule_once(refresh_callback, 1) @staticmethod def filter_address(address): - """Method will filter the my address list data.""" - # pylint: disable=deprecated-lambda + """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()]): return True return False + def set_root_layout(self): + """Setting root layout""" + return self.manager.parent.parent + class AddressBook(Screen): - """AddressBook Screen uses screen to show widgets of screens.""" + """AddressBook Screen uses screen to show widgets of screens""" + queryreturn = ListProperty() + has_refreshed = True def __init__(self, *args, **kwargs): - """Getting AddressBook Details.""" + """Getting AddressBook Details""" super(AddressBook, self).__init__(*args, **kwargs) Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method AddressBook.""" + """Clock Schdule for method AddressBook""" self.loadAddresslist(None, 'All', '') - print (dt) + print(dt) def loadAddresslist(self, account, where="", what=""): - """Clock Schdule for method AddressBook.""" + """Clock Schdule for method AddressBook""" if state.searcing_text: + self.ids.scroll_y.scroll_y = 1.0 where = ['label', 'address'] what = state.searcing_text xAddress = '' - queryreturn = kivy_helper_search.search_sql( + self.queryreturn = kivy_helper_search.search_sql( xAddress, account, "addressbook", where, what, False) - if queryreturn: - for item in queryreturn: - meny = TwoLineAvatarIconListItem( - text=item[0], - secondary_text=item[1], - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - meny.add_widget(AvatarSampleWidget( - source='./images/text_images/{}.png'.format(avatarImageFirstLetter(item[0].strip())))) - meny.bind(on_press=partial( - self.addBook_detail, item[1], item[0])) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Delete') - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) - del_btn.bind(on_press=partial(self.delete_address, item[1])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + self.queryreturn = [obj for obj in reversed(self.queryreturn)] + if self.queryreturn: + self.has_refreshed = True + self.set_mdList(0, 20) + self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -375,22 +457,66 @@ class AddressBook(Screen): valign='top') self.ids.ml.add_widget(content) + def set_mdList(self, start_index, end_index): + """Creating the mdList""" + for item in self.queryreturn[start_index:end_index]: + meny = TwoLineAvatarIconListItem( + text=item[0], + secondary_text=item[1], + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + meny.add_widget(AvatarSampleWidget( + source='./images/text_images/{}.png'.format( + avatarImageFirstLetter(item[0].strip())))) + meny.bind(on_press=partial( + self.addBook_detail, item[1], item[0])) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Delete') + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) + del_btn.bind(on_press=partial(self.delete_address, item[1])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + carousel.index = 1 + self.ids.ml.add_widget(carousel) + + def check_scroll_y(self, instance, somethingelse): + """Load data on scroll""" + if self.ids.scroll_y.scroll_y <= -0.0 and self.has_refreshed: + self.ids.scroll_y.scroll_y = 0.06 + exist_addresses = len(self.ids.ml.children) + if exist_addresses != len(self.queryreturn): + self.update_addressBook_on_scroll(exist_addresses) + self.has_refreshed = True if exist_addresses != len( + self.queryreturn) else False + else: + pass + + def update_addressBook_on_scroll(self, exist_addresses): + """Load more data on scroll down""" + self.set_mdList(exist_addresses, exist_addresses + 5) + @staticmethod def refreshs(*args): - """Refresh the Widget.""" + """Refresh the Widget""" # state.navinstance.ids.sc11.ids.ml.clear_widgets() # state.navinstance.ids.sc11.loadAddresslist(None, 'All', '') pass @staticmethod def addBook_detail(address, label, *args): - """Addressbook Details.""" + """Addressbook details""" p = AddbookDetailPopup() p.open() p.set_addbook_data(address, label) def delete_address(self, address, instance, *args): - """Delete inbox mail from inbox listing.""" + """Delete inbox mail from inbox listing""" self.ids.ml.remove_widget(instance.parent.parent) sqlExecute( "DELETE FROM addressbook WHERE address = '{}';".format(address)) @@ -442,33 +568,35 @@ class RV(RecycleView): class DropDownWidget(BoxLayout): - """Adding Dropdown Widget.""" - + """Adding Dropdown Widget""" + # pylint: disable=too-many-statements, too-many-locals + # pylint: disable=inconsistent-return-statements txt_input = ObjectProperty() rv = ObjectProperty() - def send(self, navApp): # pylint: disable=too-many-statements, inconsistent-return-statements - """Send message from one address to another.""" - # pylint: disable=too-many-locals + def send(self, navApp): + """Send message from one address to another""" fromAddress = str(self.ids.ti.text) toAddress = str(self.ids.txt_input.text) subject = self.ids.subject.text.strip() - message = self.ids.body.text.strip() + message = self.ids.subject.text.strip() encoding = 3 print ("message: ", self.ids.body.text) sendMessageToPeople = True if sendMessageToPeople: if toAddress != '' and subject and message: from addresses import decodeAddress - status, addressVersionNumber, streamNumber, ripe = \ - decodeAddress(toAddress) + status, addressVersionNumber, streamNumber, ripe = ( + decodeAddress(toAddress)) if status == 'success': - if state.detailPageType == 'draft' and state.send_draft_mail: + navApp.root.ids.sc3.children[0].active = True + if state.detailPageType == 'draft' \ + and state.send_draft_mail: sqlExecute( - "UPDATE sent SET toaddress = ? \ - , fromaddress = ? , subject = ?\ - , message = ?, folder = 'sent'\ - WHERE ackdata = ?;", + "UPDATE sent SET toaddress = ?" + ", fromaddress = ? , subject = ?" + ", message = ?, folder = 'sent'" + " WHERE ackdata = ?;", toAddress, fromAddress, subject, @@ -482,18 +610,19 @@ class DropDownWidget(BoxLayout): from addresses import addBMIfNotPresent toAddress = addBMIfNotPresent(toAddress) statusIconColor = 'red' - if addressVersionNumber > 4 or addressVersionNumber <= 1: - print("addressVersionNumber > 4 \ - or addressVersionNumber <= 1") + if (addressVersionNumber > 4) or ( + addressVersionNumber <= 1): + print ("addressVersionNumber > 4"\ + " or addressVersionNumber <= 1") if streamNumber > 1 or streamNumber == 0: - print("streamNumber > 1 or streamNumber == 0") + print ("streamNumber > 1 or streamNumber == 0") if statusIconColor == 'red': - print("shared.statusIconColor == 'red'") + print ("shared.statusIconColor == 'red'") stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') from helper_ackPayload import genAckPayload ackdata = genAckPayload(streamNumber, stealthLevel) - t = () + # t = () sqlExecute( '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', @@ -515,20 +644,17 @@ class DropDownWidget(BoxLayout): 'bitmessagesettings', 'ttl'))) state.check_sent_acc = fromAddress state.msg_counter_objs = self.parent.parent.parent.parent\ - .parent.parent.children[0].children[2].children[0].ids - self.parent.parent.screens[3].ids.ml.clear_widgets() - self.parent.parent.screens[3].loadSent(state.association) - self.parent.parent.screens[16].clear_widgets() - self.parent.parent.screens[16].add_widget(Allmails()) - toLabel = '' - + .parent.parent.children[2].children[0].ids + # self.parent.parent.screens[0].ids.ml.clear_widgets() + # self.parent.parent.screens[0].loadMessagelist(state.association) + self.parent.parent.screens[3].update_sent_messagelist() + # self.parent.parent.screens[16].clear_widgets() + # self.parent.parent.screens[16].add_widget(Allmails()) + Clock.schedule_once(self.callback_for_msgsend, 3) queues.workerQueue.put(('sendmessage', toAddress)) print ("sqlExecute successfully #######################") - self.parent.parent.current = 'inbox' state.in_composer = True - navApp.back_press() - toast('send') - return None + return else: msg = 'Enter a valid recipients address' elif not toAddress: @@ -537,9 +663,17 @@ class DropDownWidget(BoxLayout): msg = 'Please fill the form' self.address_error_message(msg) + @staticmethod + def callback_for_msgsend(dt=0): + """Callback method for messagesend""" + state.kivyapp.root.ids.sc3.children[0].active = False + state.in_sent_method = True + state.kivyapp.back_press() + toast('sent') + # pylint: disable=attribute-defined-outside-init def address_error_message(self, msg): - """Show Error Message.""" + """Generates error message""" msg_dialog = MDDialog( text=msg, title='', size_hint=(.8, .25), text_button_ok='Ok', @@ -548,11 +682,11 @@ class DropDownWidget(BoxLayout): @staticmethod def callback_for_menu_items(text_item): - """Method is used for getting the callback of alert box""" + """Callback of alert box""" toast(text_item) def reset_composer(self): - """Method will reset composer.""" + """Method will reset composer""" self.ids.ti.text = '' self.ids.btn.text = 'Select' self.ids.txt_input.text = '' @@ -561,7 +695,7 @@ class DropDownWidget(BoxLayout): toast("Reset message") def auto_fill_fromaddr(self): - """Mehtod used to fill the text automatically From Address.""" + """Fill the text automatically From Address""" self.ids.ti.text = self.ids.btn.text self.ids.ti.focus = True @@ -604,18 +738,23 @@ class MyTextInput(TextInput): class Payment(Screen): - """Payment Method.""" + """Payment module""" - def get_available_credits(self, instance): # pylint: disable=no-self-use - """Method helps to get the available credits""" + def get_available_credits(self, instance): # pylint: disable=no-self-use + """Get the available credits""" state.availabe_credit = instance.parent.children[1].text - existing_credits = state.kivyapp.root.ids.sc18.ids.ml.children[0].children[0].children[0].children[0].text + existing_credits = ( + state.kivyapp.root.ids.sc18.ids.ml.children[0].children[ + 0].children[0].children[0].text) if len(existing_credits.split(' ')) > 1: - toast('We already have added free coins for the subscription to your account!') + toast( + 'We already have added free coins' + ' for the subscription to your account!') else: toast('Coins added to your account!') - state.kivyapp.root.ids.sc18.ids.ml.children[0].children[0].children[ - 0].children[0].text = '{0}'.format(state.availabe_credit) + state.kivyapp.root.ids.sc18.ids.ml.children[0].children[ + 0].children[0].children[0].text = '{0}'.format( + state.availabe_credit) class Credits(Screen): @@ -631,8 +770,7 @@ class Login(Screen): class NetworkStat(Screen): - """Method used to show network stat.""" - + """Method used to show network stat""" text_variable_1 = StringProperty( '{0}::{1}'.format('Total Connections', '0')) text_variable_2 = StringProperty( @@ -644,12 +782,12 @@ class NetworkStat(Screen): 'Processed {0} object to be synced'.format('0')) def __init__(self, *args, **kwargs): - """Init method for network stat.""" + """Init method for network stat""" super(NetworkStat, self).__init__(*args, **kwargs) Clock.schedule_interval(self.init_ui, 1) def init_ui(self, dt=0): - """Clock Schdule for method inbox accounts.""" + """Clock Schdule for method networkstat screen""" import network.stats import shared from network import objectracker @@ -672,19 +810,22 @@ class ContentNavigationDrawer(Navigatorss): class Random(Screen): - """Generates Random Address.""" - + """Generates Random Address""" is_active = BooleanProperty(False) checked = StringProperty("") def generateaddress(self, navApp): - """Method for Address Generator.""" + """Method for Address Generator""" + entered_label = str(self.ids.label.text).strip() streamNumberForAddress = 1 label = self.ids.label.text eighteenByteRipe = False nonceTrialsPerByte = 1000 payloadLengthExtraBytes = 1000 - if str(self.ids.label.text).strip(): + lables = [BMConfigParser().get(obj, 'label') + for obj in BMConfigParser().addresses()] + if entered_label and entered_label not in lables: + toast('Address Creating...') queues.addressGeneratorQueue.put(( 'createRandomAddress', 4, streamNumberForAddress, @@ -692,13 +833,40 @@ class Random(Screen): nonceTrialsPerByte, payloadLengthExtraBytes)) self.ids.label.text = '' - self.parent.parent.parent.parent.ids.toolbar.opacity = 1 - self.parent.parent.parent.parent.ids.toolbar.disabled = False - self.parent.parent.parent.parent.ids.sc10.ids.ml.clear_widgets() + self.parent.parent.children[1].opacity = 1 + self.parent.parent.children[1].disabled = False + state.kivyapp.root.ids.sc10.children[1].active = True self.manager.current = 'myaddress' - self.parent.parent.parent.parent.ids.sc10.init_ui() - self.manager.current = 'myaddress' - toast('New address created') + Clock.schedule_once(self.address_created_callback, 6) + + @staticmethod + def address_created_callback(dt=0): + """New address created""" + state.kivyapp.root.ids.sc10.children[1].active = False + state.kivyapp.root.ids.sc10.ids.ml.clear_widgets() + state.kivyapp.root.ids.sc10.is_add_created = True + state.kivyapp.root.ids.sc10.init_ui() + toast('New address created') + + def add_validation(self, instance): + """Checking validation at address creation time""" + entered_label = str(instance.text.strip()) + lables = [BMConfigParser().get(obj, 'label') + for obj in BMConfigParser().addresses()] + if entered_label in lables: + self.ids.label.error = True + self.ids.label.helper_text = 'Label name is already exist you'\ + ' can try this Ex. ( {0}_1, {0}_2 )'.format( + entered_label) + elif entered_label: + self.ids.label.error = False + else: + self.ids.label.error = False + self.ids.label.helper_text = 'This field is required' + + def reset_address_label(self): + """Resetting address labels""" + self.ids.label.text = '' class AddressSuccessful(Screen): @@ -708,7 +876,11 @@ class AddressSuccessful(Screen): class Sent(Screen): - """Sent Screen uses screen to show widgets of screens.""" + """Sent Screen uses screen to show widgets of screens""" + queryreturn = ListProperty() + has_refreshed = True + account = StringProperty() + def __init__(self, *args, **kwargs): """Association with the screen.""" super(Sent, self).__init__(*args, **kwargs) @@ -718,74 +890,32 @@ class Sent(Screen): Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method sent accounts.""" - self.sentaccounts() + """Clock Schdule for method sent accounts""" + self.loadSent() print(dt) - def sentaccounts(self): - """Load sent accounts.""" - account = state.association - self.loadSent(account, 'All', '') - - def loadSent(self, account, where="", what=""): + def loadSent(self, where="", what=""): """Load Sent list for Sent messages.""" + self.account = state.association if state.searcing_text: + self.ids.scroll_y.scroll_y = 1.0 where = ['subject', 'message'] what = state.searcing_text xAddress = 'fromaddress' data = [] - queryreturn = kivy_helper_search.search_sql( - xAddress, account, "sent", where, what, False) - if state.msg_counter_objs and state.association == \ - state.check_sent_acc: - state.msg_counter_objs.send_cnt.badge_text = str(len(queryreturn)) - state.sent_count = str(int(state.sent_count) + 1) - state.all_count = str(int(state.all_count) + 1) - state.msg_counter_objs.allmail_cnt.badge_text = state.all_count - state.check_sent_acc = None - - if queryreturn: - src_mng_obj = state.kivyapp.root.children[2].children[0].ids - src_mng_obj.send_cnt.badge_text = str(len(queryreturn)) - state.sent_count = str(len(queryreturn)) - for mail in queryreturn: + self.sentDataQuery(xAddress, where, what) + if self.queryreturn: + self.set_sentCount(state.sent_count) + for mail in self.queryreturn: data.append({ 'text': mail[1].strip(), 'secondary_text': mail[2][:50] + '........' if len( - mail[2]) >= 50 else ( - mail[2] + ',' + mail[3].replace('\n', ''))[0:50] + '........', + mail[2]) >= 50 else (mail[2] + ',' + mail[3].replace( + '\n', ''))[0:50] + '........', 'ackdata': mail[5]}) - for item in data: - meny = TwoLineAvatarIconListItem( - text=item['text'], - secondary_text=item['secondary_text'], - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - meny.add_widget(AvatarSampleWidget( - source='./images/text_images/{}.png'.format( - avatarImageFirstLetter(item['secondary_text'].strip())))) - meny.bind(on_press=partial( - self.sent_detail, item['ackdata'])) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Delete') - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) - del_btn.bind(on_press=partial( - self.delete, item['ackdata'])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - ach_btn = Button(text='Achieve') - ach_btn.background_color = (0, 1, 0, 1) - ach_btn.bind(on_press=partial( - self.archive, item['ackdata'])) - carousel.add_widget(ach_btn) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + self.set_mdlist(data, 0) + self.has_refreshed = True + self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -797,8 +927,117 @@ class Sent(Screen): valign='top') self.ids.ml.add_widget(content) + # pylint: disable=too-many-arguments + def sentDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): + """This method is used to retrieving data from sent table""" + self.queryreturn = kivy_helper_search.search_sql( + xAddress, + self.account, + "sent", + where, + what, + False, + start_indx, + end_indx) + + def set_mdlist(self, data, set_index=0): + """This method is used to create the mdList""" + total_sent_msg = len(self.ids.ml.children) + for item in data: + meny = TwoLineAvatarIconListItem( + text=item['text'], + secondary_text=item['secondary_text'], + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + meny.add_widget(AvatarSampleWidget( + source='./images/text_images/{}.png'.format( + avatarImageFirstLetter(item['secondary_text'].strip())))) + meny.bind(on_press=partial( + self.sent_detail, item['ackdata'])) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Delete') + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) + del_btn.bind(on_press=partial( + self.delete, item['ackdata'])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + ach_btn = Button(text='Achieve') + ach_btn.background_color = (0, 1, 0, 1) + ach_btn.bind(on_press=partial( + self.archive, item['ackdata'])) + carousel.add_widget(ach_btn) + carousel.index = 1 + self.ids.ml.add_widget(carousel, index=set_index) + updated_msgs = len(self.ids.ml.children) + self.has_refreshed = True if total_sent_msg != updated_msgs else False + + def update_sent_messagelist(self): + """This method is used to update screen when new mail is sent""" + self.account = state.association + if len(self.ids.ml.children) < 3: + self.ids.ml.clear_widgets() + self.loadSent() + total_sent = int(state.sent_count) + 1 + self.set_sentCount(total_sent) + else: + data = [] + self.sentDataQuery('fromaddress', '', '', 0, 1) + total_sent = int(state.sent_count) + 1 + self.set_sentCount(total_sent) + for mail in self.queryreturn: + data.append({ + 'text': mail[1].strip(), + 'secondary_text': mail[2][:50] + '........' if len( + mail[2]) >= 50 else (mail[2] + ',' + mail[3].replace( + '\n', ''))[0:50] + '........', + 'ackdata': mail[5]}) + self.set_mdlist(data, total_sent - 1) + if state.msg_counter_objs and state.association == ( + state.check_sent_acc): + state.all_count = str(int(state.all_count) + 1) + state.msg_counter_objs.allmail_cnt.badge_text = state.all_count + state.check_sent_acc = None + + def check_scroll_y(self, instance, somethingelse): + """Load data on scroll down""" + if self.ids.scroll_y.scroll_y <= -0.0 and self.has_refreshed: + self.ids.scroll_y.scroll_y = 0.06 + total_sent_msg = len(self.ids.ml.children) + self.update_sent_screen_on_scroll(total_sent_msg) + else: + pass + + def update_sent_screen_on_scroll(self, total_sent_msg, where="", what=""): + """This method is used to load more data on scroll down""" + if state.searcing_text: + where = ['subject', 'message'] + what = state.searcing_text + self.sentDataQuery('fromaddress', where, what, total_sent_msg, 5) + data = [] + for mail in self.queryreturn: + data.append({ + 'text': mail[1].strip(), + 'secondary_text': mail[2][:50] + '........' if len( + mail[2]) >= 50 else (mail[2] + ',' + mail[3].replace( + '\n', ''))[0:50] + '........', + 'ackdata': mail[5]}) + self.set_mdlist(data, 0) + + @staticmethod + def set_sentCount(total_sent): + """Set the total no. of sent message count""" + src_mng_obj = state.kivyapp.root.children[2].children[0].ids + src_mng_obj.send_cnt.badge_text = str(total_sent) + state.sent_count = str(total_sent) + def sent_detail(self, ackdata, *args): - """Load sent mail details.""" + """Load sent mail details""" state.detailPageType = 'sent' state.mail_id = ackdata if self.manager: @@ -810,7 +1049,7 @@ class Sent(Screen): src_mng_obj.current = 'mailDetail' def delete(self, data_index, instance, *args): - """Delete sent mail from sent mail listing.""" + """Delete sent mail from sent mail listing""" try: msg_count_objs = self.parent.parent.parent.parent.children[ 2].children[0].ids @@ -828,22 +1067,22 @@ class Sent(Screen): state.trash_count = str(int(state.trash_count) + 1) state.all_count = str(int(state.all_count) - 1) sqlExecute( - "UPDATE sent SET folder = 'trash' \ - WHERE ackdata = ?;", str(data_index)) + "UPDATE sent SET folder = 'trash'" + " WHERE ackdata = ?;", str(data_index)) self.ids.ml.remove_widget(instance.parent.parent) toast('Deleted') self.update_trash() def archive(self, data_index, instance, *args): - """Archive sent mail from sent mail listing.""" + """Archive sent mail from sent mail listing""" sqlExecute( - "UPDATE sent SET folder = 'trash' \ - WHERE ackdata = ?;", str(data_index)) + "UPDATE sent SET folder = 'trash'" + " WHERE ackdata = ?;", str(data_index)) self.ids.ml.remove_widget(instance.parent.parent) self.update_trash() def update_trash(self): - """Update trash screen mails which is deleted from inbox.""" + """Update trash screen mails which is deleted from inbox""" try: self.parent.screens[4].clear_widgets() self.parent.screens[4].add_widget(Trash()) @@ -857,60 +1096,28 @@ class Sent(Screen): class Trash(Screen): - """Trash Screen uses screen to show widgets of screens.""" + """Trash Screen uses screen to show widgets of screens""" + trash_messages = ListProperty() + has_refreshed = True + delete_index = StringProperty() + table_name = StringProperty() def __init__(self, *args, **kwargs): - """Trash method, delete sent message and add in Trash.""" + """Trash method, delete sent message and add in Trash""" super(Trash, self).__init__(*args, **kwargs) Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method inbox accounts.""" + """Clock Schdule for method trash screen.""" if state.association == '': if BMConfigParser().addresses(): state.association = BMConfigParser().addresses()[0] - - inbox = sqlQuery( - "SELECT toaddress, fromaddress, subject, message, folder, received from \ - inbox WHERE folder = 'trash' and toaddress = '{}';".format( - state.association)) - sent = sqlQuery( - "SELECT toaddress, fromaddress, subject, message, folder, lastactiontime from \ - sent WHERE folder = 'trash' and fromaddress = '{}';".format( - state.association)) - trash_data = inbox + sent - - if trash_data: + self.trashDataQuery(0, 20) + if self.trash_messages: src_mng_obj = state.kivyapp.root.children[2].children[0].ids - src_mng_obj.trash_cnt.badge_text = str(len(trash_data)) - state.trash_count = str(len(trash_data)) - for item in trash_data: - meny = TwoLineAvatarIconListItem( - text=item[1], - secondary_text=item[2][:50] + '........' if len( - item[2]) >= 50 else ( - item[2] + ',' + item[3].replace('\n', ''))[0:50] + '........', - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - img_latter = './images/text_images/{}.png'.format( - item[2][0].upper() if (item[2][0].upper() >= 'A' and item[ - 2][0].upper() <= 'Z') else '!') - meny.add_widget(AvatarSampleWidget(source=img_latter)) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Delete') - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) - del_btn.bind(on_press=partial( - self.delete_permanently, item[5])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + src_mng_obj.trash_cnt.badge_text = state.trash_count + self.set_mdList() + self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -921,9 +1128,114 @@ class Trash(Screen): valign='top') self.ids.ml.add_widget(content) - def delete_permanently(self, data_index, instance, *args): - """Deleting trash mail permanently.""" - pass + def trashDataQuery(self, start_indx, end_indx): + """Trash message query""" + self.trash_messages = sqlQuery( + "SELECT toaddress, fromaddress, subject, message," + " folder ||',' || 'sent' as folder, ackdata As" + " id, DATE(lastactiontime) As actionTime FROM sent" + " WHERE folder = 'trash' and fromaddress = '{0}' UNION" + " SELECT toaddress, fromaddress, subject, message," + " folder ||',' || 'inbox' as folder, msgid As id," + " DATE(received) As actionTime FROM inbox" + " WHERE folder = 'trash' and toaddress = '{0}'" + " ORDER BY actionTime DESC limit {1}, {2}".format( + state.association, start_indx, end_indx)) + + def set_mdList(self): + """This method is used to create the mdlist""" + total_trash_msg = len(self.ids.ml.children) + for item in self.trash_messages: + meny = TwoLineAvatarIconListItem( + text=item[1], + secondary_text=item[2][:50] + '........' if len( + item[2]) >= 50 else (item[2] + ',' + item[3].replace( + '\n', ''))[0:50] + '........', + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + img_latter = './images/text_images/{}.png'.format( + item[2][0].upper() if (item[2][0].upper() >= 'A' and item[ + 2][0].upper() <= 'Z') else '!') + meny.add_widget(AvatarSampleWidget(source=img_latter)) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Delete') + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) + del_btn.bind(on_press=partial( + self.delete_permanently, item[5], item[4])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + carousel.index = 1 + self.ids.ml.add_widget(carousel) + self.has_refreshed = True if total_trash_msg != len( + self.ids.ml.children) else False + + def check_scroll_y(self, instance, somethingelse): + """Load data on scroll""" + if self.ids.scroll_y.scroll_y <= -0.0 and self.has_refreshed: + self.ids.scroll_y.scroll_y = 0.06 + total_trash_msg = len(self.ids.ml.children) + self.update_trash_screen_on_scroll(total_trash_msg) + else: + pass + + def update_trash_screen_on_scroll(self, total_trash_msg): + """Load more data on scroll down""" + self.trashDataQuery(total_trash_msg, 5) + self.set_mdList() + + def delete_permanently(self, data_index, folder, instance, *args): + """Deleting trash mail permanently""" + self.table_name = folder.split(',')[1] + self.delete_index = data_index + self.delete_confirmation() + + def callback_for_screen_load(self, dt=0): + """This methos is for loading screen""" + self.ids.ml.clear_widgets() + self.init_ui(0) + self.children[1].active = False + toast('Message is permanently deleted') + + def delete_confirmation(self): + """Show confirmation delete popup""" + delete_msg_dialog = MDDialog( + text='Are you sure you want to delete this' + ' message permanently from trash?', + title='', + size_hint=(.8, .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): + """Getting the callback of alert box""" + if text_item == 'Yes': + self.delete_message_from_trash() + else: + toast(text_item) + + def delete_message_from_trash(self): + """Deleting message from trash""" + self.children[1].active = True + if self.table_name == 'inbox': + sqlExecute("DELETE FROM inbox WHERE msgid = ?;", str( + self.delete_index)) + elif self.table_name == 'sent': + sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( + 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( + int(state.trash_count) - 1) + state.trash_count = str(int(state.trash_count) - 1) + Clock.schedule_once(self.callback_for_screen_load, 1) class Page(Screen): @@ -952,9 +1264,8 @@ class Setting(Screen): pass -class NavigateApp(App): # pylint: disable=too-many-public-methods - """Navigation Layout of class.""" - +class NavigateApp(App): # pylint: disable=too-many-public-methods + """Navigation Layout of class""" theme_cls = ThemeManager() previous_date = ObjectProperty() obj_1 = ObjectProperty() @@ -983,7 +1294,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods ] def build(self): - """Method builds the widget.""" + """Method builds the widget""" main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) self.nav_drawer = Navigatorss() @@ -995,14 +1306,14 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods return main_widget def run(self): - """Running the widgets.""" + """Running the widgets""" kivyuisignaler.release() super(NavigateApp, self).run() # pylint: disable=inconsistent-return-statements @staticmethod def showmeaddresses(name="text"): - """Show the addresses in spinner to make as dropdown.""" + """Show the addresses in spinner to make as dropdown""" if name == "text": if BMConfigParser().addresses(): return BMConfigParser().addresses()[0][:16] + '..' @@ -1014,111 +1325,109 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods return "valuesdemo" def getCurrentAccountData(self, text): - """Get Current Address Account Data.""" + """Get Current Address Account Data""" self.set_identicon(text) address_label = self.current_address_label( BMConfigParser().get(text, 'label'), text) self.root_window.children[1].ids.toolbar.title = address_label state.association = text state.searcing_text = '' + LoadingPopup().open() + self.set_message_count() + Clock.schedule_once(self.setCurrentAccountData, 0.5) + + def setCurrentAccountData(self, dt=0): + """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.loadSent(state.association) + + self.root.ids.sc16.clear_widgets() + self.root.ids.sc16.add_widget(Draft()) + + self.root.ids.sc5.clear_widgets() + self.root.ids.sc5.add_widget(Trash()) + + self.root.ids.sc17.clear_widgets() + self.root.ids.sc17.add_widget(Allmails()) + self.root.ids.scr_mngr.current = 'inbox' - msg_counter_objs = \ - self.root_window.children[1].children[2].children[0].ids - state.sent_count = str( - sqlQuery( - "SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and \ - folder = 'sent' ;".format(state.association))[0][0]) - state.inbox_count = str( - sqlQuery( - "SELECT COUNT(*) FROM inbox WHERE toaddress = '{}' and \ - folder = 'inbox' ;".format(state.association))[0][0]) - state.trash_count = str(sqlQuery("SELECT (SELECT count(*) FROM sent \ - where fromaddress = '{0}' and folder = 'trash' ) \ - +(SELECT count(*) FROM inbox where toaddress = '{0}' and \ - folder = 'trash') AS SumCount".format(state.association))[0][0]) - state.draft_count = str( - sqlQuery( - "SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and \ - folder = 'draft' ;".format(state.association))[0][0]) - state.all_count = str(int(state.sent_count) + int(state.inbox_count)) - - if msg_counter_objs: - msg_counter_objs.send_cnt.badge_text = state.sent_count - msg_counter_objs.inbox_cnt.badge_text = state.inbox_count - msg_counter_objs.trash_cnt.badge_text = state.trash_count - msg_counter_objs.draft_cnt.badge_text = state.draft_count - msg_counter_objs.allmail_cnt.badge_text = state.all_count - @staticmethod def getCurrentAccount(): - """It uses to get current account label.""" + """It uses to get current account label""" if state.association: return state.association return "Bitmessage Login" @staticmethod def addingtoaddressbook(): - """Adding to address Book.""" + """Adding to address Book""" p = GrashofPopup() p.open() def getDefaultAccData(self): - """Getting Default Account Data.""" + """Getting Default Account Data""" if BMConfigParser().addresses(): img = identiconGeneration.generate(BMConfigParser().addresses()[0]) self.createFolder('./images/default_identicon/') if platform == 'android': - # android_path = os.path.expanduser("~/user/0/org.test.bitapp/files/app/") - android_path = os.path.join(os.environ['ANDROID_PRIVATE'] + '/app/') + # android_path = os.path.expanduser + # ("~/user/0/org.test.bitapp/files/app/") + android_path = os.path.join( + os.environ['ANDROID_PRIVATE'] + '/app/') img.texture.save('{1}/images/default_identicon/{0}.png'.format( BMConfigParser().addresses()[0], android_path)) else: - img.texture.save('./images/default_identicon/{}.png'.format(BMConfigParser().addresses()[0])) + img.texture.save( + './images/default_identicon/{}.png'.format( + BMConfigParser().addresses()[0])) return BMConfigParser().addresses()[0] return 'Select Address' @staticmethod def createFolder(directory): - """This method is used to create the directory when app starts""" + """Create directory when app starts""" try: if not os.path.exists(directory): os.makedirs(directory) except OSError: - print('Error: Creating directory. ' + directory) + print ('Error: Creating directory. ' + directory) @staticmethod def get_default_image(): """Getting default image on address""" if BMConfigParser().addresses(): - return './images/default_identicon/{}.png'.format(BMConfigParser().addresses()[0]) + return './images/default_identicon/{}.png'.format( + BMConfigParser().addresses()[0]) return './images/no_identicons.png' @staticmethod def addressexist(): - """Checking address existence.""" + """Checking address existence""" if BMConfigParser().addresses(): return True return False def on_key(self, window, key, *args): - """Method is used for going on previous screen.""" + """Method is used for going on previous screen""" if key == 27: - if self.root.ids.scr_mngr.current == "mailDetail": + if state.in_search_mode and self.root.ids.scr_mngr.current != ( + "mailDetail"): + self.closeSearchScreen() + elif self.root.ids.scr_mngr.current == "mailDetail": self.root.ids.scr_mngr.current = 'sent'\ if state.detailPageType == 'sent' else 'inbox' \ if state.detailPageType == 'inbox' else 'draft' self.back_press() elif self.root.ids.scr_mngr.current == "create": - composer_objs = self.root - from_addr = str(self.root.ids.sc3.children[0].ids.ti.text) - to_addr = str(self.root.ids.sc3.children[0].ids.txt_input.text) - if from_addr and to_addr and state.detailPageType != 'draft': - Draft().draft_msg(composer_objs) + self.save_draft() + self.set_common_header() + state.in_composer = False self.root.ids.scr_mngr.current = 'inbox' - self.back_press() elif self.root.ids.scr_mngr.current == "showqrcode": self.root.ids.scr_mngr.current = 'myaddress' elif self.root.ids.scr_mngr.current == "random": @@ -1128,45 +1437,104 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.scr_mngr.transition.direction = 'right' self.root.ids.scr_mngr.transition.bind(on_complete=self.reset) return True + elif key == 13: + if state.search_screen == 'inbox' and state.searcing_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[1].active = True + Clock.schedule_once(self.search_callback, 0.5) + elif state.search_screen == 'myaddress': + self.root.ids.sc10.children[1].active = True + Clock.schedule_once(self.search_callback, 0.5) + elif state.search_screen == 'sent': + self.root.ids.sc4.children[1].active = True + Clock.schedule_once(self.search_callback, 0.5) + + def search_callback(self, dt=0): + """Show data after loader is loaded""" + if state.search_screen == 'inbox': + self.root.ids.sc1.ids.ml.clear_widgets() + self.root.ids.sc1.loadMessagelist(state.association) + self.root.ids.sc1.children[1].active = False + elif state.search_screen == 'addressbook': + self.root.ids.sc11.ids.ml.clear_widgets() + self.root.ids.sc11.loadAddresslist(None, 'All', '') + self.root.ids.sc11.children[1].active = False + elif state.search_screen == 'myaddress': + self.root.ids.sc10.ids.ml.clear_widgets() + self.root.ids.sc10.init_ui() + self.root.ids.sc10.children[1].active = False + else: + self.root.ids.sc4.ids.ml.clear_widgets() + self.root.ids.sc4.loadSent(state.association) + self.root.ids.sc4.children[1].active = False + self.root.ids.scr_mngr.current = state.search_screen + + def save_draft(self): + """Saving drafts messages""" + composer_objs = self.root + from_addr = str(self.root.ids.sc3.children[1].ids.ti.text) + to_addr = str(self.root.ids.sc3.children[1].ids.txt_input.text) + if from_addr and to_addr and state.detailPageType != 'draft' \ + and not state.in_sent_method: + Draft().draft_msg(composer_objs) + return def reset(self, *args): - """Method used to set transition direction.""" + """Set transition direction""" self.root.ids.scr_mngr.transition.direction = 'left' self.root.ids.scr_mngr.transition.unbind(on_complete=self.reset) @staticmethod def status_dispatching(data): - """Method used for status dispatching acknowledgment.""" + """Dispatching Status acknowledgment""" ackData, message = data if state.ackdata == ackData: state.status.status = message def clear_composer(self): - """If slow down the nwe will make new composer edit screen.""" + """If slow down, the new composer edit screen""" self.set_navbar_for_composer() - # self.root.ids.search_bar.clear_widgets() - composer_obj = self.root.ids.sc3.children[0].ids + composer_obj = self.root.ids.sc3.children[1].ids composer_obj.ti.text = '' composer_obj.btn.text = 'Select' composer_obj.txt_input.text = '' composer_obj.subject.text = '' composer_obj.body.text = '' state.in_composer = True + state.in_sent_method = False def set_navbar_for_composer(self): - """This method is used for clearing toolbar data when composer open""" + """Clearing toolbar data when composer open""" self.root.ids.toolbar.left_action_items = [ ['arrow-left', lambda x: self.back_press()]] self.root.ids.toolbar.right_action_items = [ - ['refresh', lambda x: self.root.ids.sc3.children[0].reset_composer()], - ['send', lambda x: self.root.ids.sc3.children[0].send(self)]] + ['refresh', + lambda x: self.root.ids.sc3.children[1].reset_composer()], + ['send', + lambda x: self.root.ids.sc3.children[1].send(self)]] + + def set_common_header(self): + """Common header for all window""" + self.root.ids.toolbar.right_action_items = [ + ['account-plus', lambda x: self.addingtoaddressbook()]] + self.root.ids.toolbar.left_action_items = [ + ['menu', lambda x: self.root.toggle_nav_drawer()]] + return def back_press(self): - """Method used for going back from composer to previous page.""" - self.root.ids.toolbar.right_action_items = \ - [['account-plus', lambda x: self.addingtoaddressbook()]] - self.root.ids.toolbar.left_action_items = \ - [['menu', lambda x: self.root.toggle_nav_drawer()]] + """Method for, reverting composer to previous page""" + self.save_draft() + if self.root.ids.scr_mngr.current == \ + 'mailDetail' and state.in_search_mode: + toolbar_obj = self.root.ids.toolbar + toolbar_obj.left_action_items = [ + ['arrow-left', lambda x: self.closeSearchScreen()]] + toolbar_obj.right_action_items = [] + self.root.ids.toolbar.title = '' + else: + self.set_common_header() self.root.ids.scr_mngr.current = 'inbox' \ if state.in_composer else 'allmails'\ if state.is_allmail else state.detailPageType\ @@ -1178,16 +1546,63 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods state.detailPageType = '' state.in_composer = False + @staticmethod + def get_inbox_count(): + """Getting inbox count""" + state.inbox_count = str( + sqlQuery( + "SELECT COUNT(*) FROM inbox WHERE toaddress = '{}' and" + " folder = 'inbox' ;".format(state.association))[0][0]) + + @staticmethod + def get_sent_count(): + """Getting sent count""" + state.sent_count = str( + sqlQuery( + "SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and" + " folder = 'sent' ;".format(state.association))[0][0]) + + def set_message_count(self): + """Setting message count""" + try: + msg_counter_objs = ( + self.root_window.children[0].children[2].children[0].ids) + except Exception: + msg_counter_objs = ( + self.root_window.children[2].children[2].children[0].ids) + self.get_inbox_count() + self.get_sent_count() + state.trash_count = str(sqlQuery( + "SELECT (SELECT count(*) FROM sent" + " where fromaddress = '{0}' and folder = 'trash' )" + "+(SELECT count(*) FROM inbox where toaddress = '{0}' and" + " folder = 'trash') AS SumCount".format(state.association))[0][0]) + state.draft_count = str( + sqlQuery( + "SELECT COUNT(*) FROM sent WHERE fromaddress = '{}' and" + " folder = 'draft' ;".format(state.association))[0][0]) + state.all_count = str(int(state.sent_count) + int(state.inbox_count)) + + if msg_counter_objs: + msg_counter_objs.send_cnt.badge_text = state.sent_count + msg_counter_objs.inbox_cnt.badge_text = state.inbox_count + msg_counter_objs.trash_cnt.badge_text = state.trash_count + msg_counter_objs.draft_cnt.badge_text = state.draft_count + msg_counter_objs.allmail_cnt.badge_text = state.all_count + + def on_start(self): + self.set_message_count() + @staticmethod def on_stop(): - """On stop methos is used for stoping the runing script.""" - print("*******************EXITING FROM APPLICATION*******************") + """On stop methos is used for stoping the runing script""" + print ("*******************EXITING FROM APPLICATION*******************") import shutdown shutdown.doCleanShutdown() @staticmethod def current_address_label(current_add_label=None, current_addr=None): - """Getting current address labels.""" + """Getting current address labels""" if BMConfigParser().addresses(): if current_add_label: first_name = current_add_label @@ -1196,99 +1611,133 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods addr = BMConfigParser().addresses()[0] first_name = BMConfigParser().get(addr, 'label') f_name = first_name.split() - label = f_name[0][:14].capitalize() + '...' if len(f_name[0]) > 15 else f_name[0].capitalize() + label = f_name[0][:14].capitalize() + '...' if len( + f_name[0]) > 15 else f_name[0].capitalize() address = ' (' + addr + '...)' return label + address return '' def searchQuery(self, instance): - """Method used for showing searched mails.""" + """Showing searched mails""" state.search_screen = self.root.ids.scr_mngr.current state.searcing_text = str(instance.text).strip() - if state.search_screen == 'inbox': - self.root.ids.sc1.ids.ml.clear_widgets() - self.root.ids.sc1.loadMessagelist(state.association) - elif state.search_screen == 'addressbook': - self.root.ids.sc11.ids.ml.clear_widgets() - self.root.ids.sc11.loadAddresslist(None, 'All', '') - elif state.search_screen == 'myaddress': - self.root.ids.sc10.ids.ml.clear_widgets() - self.root.ids.sc10.init_ui() - else: - self.root.ids.sc4.ids.ml.clear_widgets() - self.root.ids.sc4.loadSent(state.association) - self.root.ids.scr_mngr.current = state.search_screen + if instance.focus and state.searcing_text: + toolbar_obj = self.root.ids.toolbar + toolbar_obj.left_action_items = [ + ['arrow-left', lambda x: self.closeSearchScreen()]] + toolbar_obj.right_action_items = [] + self.root.ids.toolbar.title = '' + state.in_search_mode = True - def refreshScreen(self, instance): - """Method show search button only on inbox or sent screen.""" + def closeSearchScreen(self): + """Function for close search screen""" + self.set_common_header() + address_label = self.current_address_label( + BMConfigParser().get( + state.association, 'label'), state.association) + self.root.ids.toolbar.title = address_label state.searcing_text = '' - if instance.text == 'Sent': - self.root.ids.sc4.ids.ml.clear_widgets() - self.root.ids.sc4.children[1].children[1].ids.search_field.text = '' - self.root.ids.sc4.loadSent(state.association) - elif instance.text == 'Inbox': - self.root.ids.sc1.ids.ml.clear_widgets() + self.refreshScreen() + state.in_search_mode = False + + def refreshScreen(self): # pylint: disable=unused-variable + """Method show search button only on inbox or sent screen""" + state.searcing_text = '' + if state.search_screen == 'inbox': try: - self.root.ids.sc1.children[2].children[1].ids.search_field.text = '' - except Exception as e: - self.root.ids.sc1.children[1].children[1].ids.search_field.text = '' - self.root.ids.sc1.loadMessagelist(state.association) - elif instance.text == 'Draft': - self.root.ids.sc16.clear_widgets() - self.root.ids.sc16.add_widget(Draft()) - elif instance.text == 'Trash': - self.root.ids.sc5.clear_widgets() - self.root.ids.sc5.add_widget(Trash()) - elif instance.text == 'All Mails': - self.root.ids.sc17.clear_widgets() - self.root.ids.sc17.add_widget(Allmails()) - elif instance.text == 'Address Book': - self.root.ids.sc11.ids.ml.clear_widgets() - self.root.ids.sc11.children[1].children[1].ids.search_field.text = '' - self.root.ids.sc11.loadAddresslist(None, 'All', '') - elif instance.text == 'My Addresses': - self.root.ids.sc10.ids.ml.clear_widgets() + self.root.ids.sc1.children[ + 3].children[1].ids.search_field.text = '' + except Exception: + self.root.ids.sc1.children[ + 2].children[1].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 = '' + 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[1].children[1].ids.search_field.text = '' - except Exception as e: - self.root.ids.sc10.children[2].children[1].ids.search_field.text = '' - self.root.ids.sc10.init_ui() + self.root.ids.sc10.children[ + 3].children[1].ids.search_field.text = '' + except Exception: + self.root.ids.sc10.children[ + 2].children[1].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 = '' + self.root.ids.sc4.children[1].active = True + Clock.schedule_once(self.search_callback, 0.5) return def set_identicon(self, text): - """This method is use for showing identicon in address spinner""" + """Show identicon in address spinner""" img = identiconGeneration.generate(text) - self.root.children[2].children[0].ids.btn.children[1].texture = img.texture - - @staticmethod - def address_identicon(): - """Address identicon""" - return './images/drawer_logo1.png' + self.root.children[2].children[0].ids.btn.children[1].texture = ( + img.texture) def set_mail_detail_header(self): - """Method is used for setting the details of the page""" + """Setting the details of the page""" toolbar_obj = self.root.ids.toolbar - toolbar_obj.left_action_items = [['arrow-left', lambda x: self.back_press()]] - delete_btn = ['delete-forever', lambda x: self.root.ids.sc14.delete_mail()] + toolbar_obj.left_action_items = [ + ['arrow-left', lambda x: self.back_press()]] + delete_btn = ['delete-forever', + lambda x: self.root.ids.sc14.delete_mail()] dynamic_list = [] if state.detailPageType == 'inbox': - dynamic_list = [['reply', lambda x: self.root.ids.sc14.inbox_reply()], delete_btn] + dynamic_list = [ + ['reply', lambda x: self.root.ids.sc14.inbox_reply()], + delete_btn] elif state.detailPageType == 'sent': dynamic_list = [delete_btn] elif state.detailPageType == 'draft': - dynamic_list = [['pencil', lambda x: self.root.ids.sc14.write_msg(self)], delete_btn] + dynamic_list = [ + ['pencil', lambda x: self.root.ids.sc14.write_msg(self)], + delete_btn] toolbar_obj.right_action_items = dynamic_list + def load_screen(self, instance): + """This method is used for loading screen on every click""" + if instance.text == 'Inbox': + self.root.ids.scr_mngr.current = 'inbox' + self.root.ids.sc1.children[1].active = True + elif instance.text == 'All Mails': + self.root.ids.scr_mngr.current = 'allmails' + try: + self.root.ids.sc17.children[1].active = True + except Exception as e: + self.root.ids.sc17.children[0].children[1].active = True + Clock.schedule_once(partial(self.load_screen_callback, instance), 1) + + def load_screen_callback(self, instance, dt=0): + """This method is rotating loader for few seconds""" + if instance.text == 'Inbox': + self.root.ids.sc1.ids.ml.clear_widgets() + self.root.ids.sc1.loadMessagelist(state.association) + self.root.ids.sc1.children[1].active = False + elif instance.text == 'All Mails': + self.root.ids.sc17.clear_widgets() + self.root.ids.sc17.add_widget(Allmails()) + try: + self.root.ids.sc17.children[1].active = False + except Exception as e: + self.root.ids.sc17.children[0].children[1].active = False + class GrashofPopup(Popup): - """Methods for saving contacts, error messages.""" + """Moule for save contacts and error messages""" + valid = False - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation - """Grash of pop screen settings.""" + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + """Grash of pop screen settings""" super(GrashofPopup, self).__init__(**kwargs) def savecontact(self): - """Method is used for Saving Contacts.""" + """Method is used for saving contacts""" label = self.ids.label.text.strip() address = self.ids.address.text.strip() if label == '' and address == '': @@ -1301,19 +1750,22 @@ class GrashofPopup(Popup): stored_address = [addr[1] for addr in kivy_helper_search.search_sql( folder="addressbook")] - if label and address and address not in stored_address: + stored_labels = [labels[0] for labels in kivy_helper_search.search_sql( + folder="addressbook")] + if label and address and address not in stored_address \ + and label not in stored_labels and self.valid: # state.navinstance = self.parent.children[1] queues.UISignalQueue.put(('rerenderAddressBook', '')) self.dismiss() sqlExecute("INSERT INTO addressbook VALUES(?,?)", label, address) - state.kivyapp.root.ids.sc11.ids.ml.clear_widgets() - state.kivyapp.root.ids.sc11.loadAddresslist(None, 'All', '') + self.parent.children[1].ids.sc11.ids.ml.clear_widgets() + self.parent.children[1].ids.sc11.loadAddresslist(None, 'All', '') 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.""" + """Showing error message""" content = MDLabel( font_style='Body1', theme_text_color='Secondary', @@ -1333,12 +1785,13 @@ class GrashofPopup(Popup): @staticmethod def close_pop(): - """Pop is Canceled.""" + """Pop is Canceled""" toast('Canceled') def checkAddress_valid(self, instance): - """Checking is address is valid or not""" - my_addresses = self.parent.children[1].children[2].children[0].ids.btn.values + """Checking address is valid or not""" + my_addresses = ( + self.parent.children[1].children[2].children[0].ids.btn.values) add_book = [addr[1] for addr in kivy_helper_search.search_sql( folder="addressbook")] entered_text = str(instance.text).strip() @@ -1346,20 +1799,61 @@ class GrashofPopup(Popup): text = 'Address is already in the addressbook.' elif entered_text in my_addresses: text = 'You can not save your own address.' + elif entered_text: + text = self.addressChanged(entered_text) if entered_text in my_addresses or entered_text in add_book: - if len(self.ids.popup_box.children) <= 2: - err_msg = MDLabel( - id='erro_msg', - font_style='Body2', - text=text, - font_size=5) - err_msg.color = 1, 0, 0, 1 - self.ids.popup_box.add_widget(err_msg) - self.ids.save_addr.disabled = True - elif len(self.ids.popup_box.children) > 2: - self.ids.popup_box.remove_widget(self.ids.popup_box.children[0]) - self.ids.save_addr.disabled = False + self.ids.address.error = True + self.ids.address.helper_text = text + elif entered_text and self.valid: + self.ids.address.error = False + elif entered_text: + self.ids.address.error = True + self.ids.address.helper_text = text + else: + self.ids.address.error = False + self.ids.address.helper_text = 'This field is required' + + def checkLabel_valid(self, instance): + """Checking address label is unique or not""" + entered_label = instance.text.strip() + addr_labels = [labels[0] for labels in kivy_helper_search.search_sql( + folder="addressbook")] + if entered_label in addr_labels: + self.ids.label.error = True + self.ids.label.helper_text = 'label name already exists.' + elif entered_label: + self.ids.label.error = False + else: + self.ids.label.error = False + self.ids.label.helper_text = 'This field is required' + + def _onSuccess(self, addressVersion, streamNumber, ripe): + pass + + def addressChanged(self, addr): + """Address validation callback, performs validation and gives feedback""" + status, addressVersion, streamNumber, ripe = decodeAddress( + str(addr)) + self.valid = status == 'success' + if self.valid: + text = "Address is valid." + self._onSuccess(addressVersion, streamNumber, ripe) + elif status == 'missingbm': + text = "The address should start with ''BM-''" + 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." + elif status == 'invalidcharacters': + text = "The address contains invalid characters." + elif status == 'ripetooshort': + text = "Some data encoded in the address is too short." + elif status == 'ripetoolong': + text = "Some data encoded in the address is too long." + elif status == 'varintmalformed': + text = "Some data encoded in the address is malformed." + return text class AvatarSampleWidget(ILeftBody, Image): @@ -1407,8 +1901,7 @@ class NavigationDrawerTwoLineListItem( class MailDetail(Screen): - """MailDetail Screen uses to show the detail of mails.""" - + """MailDetail Screen uses to show the detail of mails""" to_addr = StringProperty() from_addr = StringProperty() subject = StringProperty() @@ -1417,30 +1910,30 @@ class MailDetail(Screen): page_type = StringProperty() def __init__(self, *args, **kwargs): - """Mail Details method.""" + """Mail Details method""" super(MailDetail, self).__init__(*args, **kwargs) Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method MailDetail mails.""" + """Clock Schdule for method MailDetail mails""" self.page_type = state.detailPageType if state.detailPageType else '' if state.detailPageType == 'sent' or state.detailPageType == 'draft': data = sqlQuery( - "select toaddress, fromaddress, subject, message, status, \ - ackdata from sent where ackdata = ?;", state.mail_id) + "select toaddress, fromaddress, subject, message, status," + " ackdata from sent where ackdata = ?;", state.mail_id) state.status = self state.ackdata = data[0][5] self.assign_mail_details(data) state.kivyapp.set_mail_detail_header() elif state.detailPageType == 'inbox': data = sqlQuery( - "select toaddress, fromaddress, subject, message from inbox \ - where msgid = ?;", str(state.mail_id)) + "select toaddress, fromaddress, subject, message from inbox" + " where msgid = ?;", str(state.mail_id)) self.assign_mail_details(data) state.kivyapp.set_mail_detail_header() def assign_mail_details(self, data): - """Assigning mail details.""" + """Assigning mail details""" self.to_addr = data[0][0] self.from_addr = data[0][1] self.subject = data[0][2].upper( @@ -1454,80 +1947,99 @@ class MailDetail(Screen): 'message': self.message} def delete_mail(self): - """Method for mail delete.""" + """Method for mail delete""" msg_count_objs = state.kivyapp.root.children[2].children[0].ids + state.searcing_text = '' + self.children[0].children[0].active = True if state.detailPageType == 'sent': + state.kivyapp.root.ids.sc4.children[ + 2].children[1].ids.search_field.text = '' sqlExecute( - "UPDATE sent SET folder = 'trash' WHERE \ - ackdata = ?;", str(state.mail_id)) + "UPDATE sent SET folder = 'trash' WHERE" + " ackdata = ?;", str(state.mail_id)) msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1) self.parent.screens[3].ids.ml.clear_widgets() self.parent.screens[3].loadSent(state.association) elif state.detailPageType == 'inbox': + state.kivyapp.root.ids.sc1.children[ + 2].children[1].ids.search_field.text = '' + self.parent.screens[0].children[2].children[ + 1].ids.search_field.text = '' sqlExecute( - "UPDATE inbox SET folder = 'trash' WHERE \ - msgid = ?;", str(state.mail_id)) - msg_count_objs.inbox_cnt.badge_text = str(int(state.inbox_count) - 1) + "UPDATE inbox SET folder = 'trash' WHERE" + " msgid = ?;", str(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) self.parent.screens[0].ids.ml.clear_widgets() self.parent.screens[0].loadMessagelist(state.association) + elif state.detailPageType == 'draft': sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( state.mail_id)) - msg_count_objs.draft_cnt.badge_text = str(int(state.draft_count) - 1) + msg_count_objs.draft_cnt.badge_text = str( + int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1) self.parent.screens[15].clear_widgets() self.parent.screens[15].add_widget(Draft()) - self.parent.current = 'allmails' if state.is_allmail else state.detailPageType + # self.parent.current = 'allmails' \ + # if state.is_allmail else state.detailPageType if state.detailPageType != 'draft': - msg_count_objs.trash_cnt.badge_text = str(int(state.trash_count) + 1) - msg_count_objs.allmail_cnt.badge_text = str(int(state.all_count) - 1) + msg_count_objs.trash_cnt.badge_text = str( + int(state.trash_count) + 1) + msg_count_objs.allmail_cnt.badge_text = str( + int(state.all_count) - 1) state.trash_count = str(int(state.trash_count) + 1) 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].clear_widgets() - self.parent.screens[16].add_widget(Allmails()) - state.kivyapp.back_press() + self.parent.screens[4].ids.ml.clear_widgets() + self.parent.screens[4].init_ui(dt=0) + self.parent.screens[16].ids.ml.clear_widgets() + self.parent.screens[16].init_ui(dt=0) + Clock.schedule_once(self.callback_for_delete, 4) + + def callback_for_delete(self, dt=0): + """Delete method from allmails""" + self.children[0].children[0].active = False + state.kivyapp.set_common_header() + self.parent.current = 'allmails' \ + if state.is_allmail else state.detailPageType + state.detailPageType = '' toast('Deleted') def inbox_reply(self): - """Method used for replying inbox messages.""" + """Reply inbox messages""" data = sqlQuery( - "select toaddress, fromaddress, subject, message from inbox where \ - msgid = ?;", str(state.mail_id)) - composer_obj = self.parent.screens[2].children[0].ids + "select toaddress, fromaddress, subject, message from inbox where" + " msgid = ?;", str(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] composer_obj.txt_input.text = data[0][1] composer_obj.subject.text = data[0][2] composer_obj.body.text = '' - state.kivyapp.root.ids.sc3.children[0].ids.rv.data = '' + state.kivyapp.root.ids.sc3.children[1].ids.rv.data = '' self.parent.current = 'create' state.kivyapp.set_navbar_for_composer() - def copy_sent_mail(self): - """Method used for copying sent mail to the composer.""" - pass - def write_msg(self, navApp): - """Method used to write on draft mail.""" + """Write on draft mail""" state.send_draft_mail = state.mail_id - composer_ids = \ - self.parent.parent.parent.parent.ids.sc3.children[0].ids + composer_ids = ( + self.parent.parent.parent.parent.parent.ids.sc3.children[1].ids) composer_ids.ti.text = state.write_msg['from_addr'] composer_ids.btn.text = state.write_msg['from_addr'] composer_ids.txt_input.text = state.write_msg['to_addr'] - composer_ids.subject.text = state.write_msg['subject'] + composer_ids.subject.text = state.write_msg[ + 'subject'] if state.write_msg['subject'] != '(no subject)' else '' composer_ids.body.text = state.write_msg['message'] self.parent.current = 'create' navApp.set_navbar_for_composer() @staticmethod def copy_composer_text(instance, *args): - """This method is used for copying the data from mail detail page""" + """Copy the data from mail detail page""" if len(instance.parent.text.split(':')) > 1: cpy_text = instance.parent.text.split(':')[1].strip() else: @@ -1537,78 +2049,103 @@ class MailDetail(Screen): class MyaddDetailPopup(Popup): - """MyaddDetailPopup pop is used for showing my address detail.""" - + """MyaddDetailPopup pop is used for showing my address detail""" address_label = StringProperty() address = StringProperty() - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation - """My Address Details screen setting.""" + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + """My Address Details screen setting""" super(MyaddDetailPopup, self).__init__(**kwargs) def set_address(self, address, label): - """Getting address for displaying details on popup.""" + """Getting address for displaying details on popup""" self.address_label = label self.address = address def send_message_from(self): - """Method used to fill from address of composer autofield.""" + """Method used to fill from address of composer autofield""" + state.kivyapp.set_navbar_for_composer() window_obj = self.parent.children[1].ids - window_obj.sc3.children[0].ids.ti.text = self.address - window_obj.sc3.children[0].ids.btn.text = self.address - window_obj.sc3.children[0].ids.txt_input.text = '' - window_obj.sc3.children[0].ids.subject.text = '' - window_obj.sc3.children[0].ids.body.text = '' + window_obj.sc3.children[1].ids.ti.text = self.address + window_obj.sc3.children[1].ids.btn.text = self.address + window_obj.sc3.children[1].ids.txt_input.text = '' + window_obj.sc3.children[1].ids.subject.text = '' + window_obj.sc3.children[1].ids.body.text = '' window_obj.scr_mngr.current = 'create' self.dismiss() @staticmethod def close_pop(): - """Pop is Canceled.""" + """Pop is Canceled""" toast('Canceled') class AddbookDetailPopup(Popup): - """AddbookDetailPopup pop is used for showing my address detail.""" - + """AddbookDetailPopup pop is used for showing my address detail""" address_label = StringProperty() address = StringProperty() - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation - """Method used set screen of address detail page.""" + def __init__(self, **kwargs): + """Set screen of address detail page""" + # pylint: disable=useless-super-delegation super(AddbookDetailPopup, self).__init__(**kwargs) def set_addbook_data(self, address, label): - """Getting address book data for detial dipaly.""" + """Getting address book data for detial dipaly""" self.address_label = label self.address = address def update_addbook_label(self, address): - """Updating the label of address book address.""" - if str(self.ids.add_label.text): - sqlExecute("UPDATE addressbook SET label = '{}' WHERE \ - address = '{}';".format(str(self.ids.add_label.text), address)) + """Updating the label of address book address""" + address_list = kivy_helper_search.search_sql(folder="addressbook") + stored_labels = [labels[0] for labels in address_list] + add_dict = dict(address_list) + label = str(self.ids.add_label.text) + if label in stored_labels and self.address == add_dict[label]: + stored_labels.remove(label) + if label and label not in stored_labels: + sqlExecute( + "UPDATE addressbook SET label = '{}' WHERE" + " address = '{}';".format( + str(self.ids.add_label.text), address)) self.parent.children[1].ids.sc11.ids.ml.clear_widgets() self.parent.children[1].ids.sc11.loadAddresslist(None, 'All', '') self.dismiss() toast('Saved') def send_message_to(self): - """Method used to fill to_address of composer autofield.""" + """Method used to fill to_address of composer autofield""" + state.kivyapp.set_navbar_for_composer() window_obj = self.parent.children[1].ids - window_obj.sc3.children[0].ids.txt_input.text = self.address - window_obj.sc3.children[0].ids.ti.text = '' - window_obj.sc3.children[0].ids.btn.text = 'Select' - window_obj.sc3.children[0].ids.subject.text = '' - window_obj.sc3.children[0].ids.body.text = '' + window_obj.sc3.children[1].ids.txt_input.text = self.address + window_obj.sc3.children[1].ids.ti.text = '' + window_obj.sc3.children[1].ids.btn.text = 'Select' + window_obj.sc3.children[1].ids.subject.text = '' + window_obj.sc3.children[1].ids.body.text = '' window_obj.scr_mngr.current = 'create' self.dismiss() @staticmethod def close_pop(): - """Pop is Canceled.""" + """Pop is Canceled""" toast('Canceled') + def checkLabel_valid(self, instance): + """Checking address label is unique of not""" + entered_label = str(instance.text.strip()) + address_list = kivy_helper_search.search_sql(folder="addressbook") + addr_labels = [labels[0] for labels in address_list] + add_dict = dict(address_list) + if self.address and entered_label in addr_labels \ + and self.address != add_dict[entered_label]: + self.ids.add_label.error = True + self.ids.add_label.helper_text = 'label name already exists.' + elif entered_label: + self.ids.add_label.error = False + else: + self.ids.add_label.error = False + self.ids.add_label.helper_text = 'This field is required' + class ShowQRCode(Screen): """ShowQRCode Screen uses to show the detail of mails.""" @@ -1624,12 +2161,14 @@ class ShowQRCode(Screen): class Draft(Screen): - """Draft screen is used to show the list of draft messages.""" - + """Draft screen is used to show the list of draft messages""" data = ListProperty() + account = StringProperty() + queryreturn = ListProperty() + has_refreshed = True def __init__(self, *args, **kwargs): - """Method used for storing draft messages.""" + """Method used for storing draft messages""" super(Draft, self).__init__(*args, **kwargs) if state.association == '': if BMConfigParser().addresses(): @@ -1637,60 +2176,27 @@ class Draft(Screen): Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method draft accounts.""" + """Clock Schdule for method draft accounts""" self.sentaccounts() - print (dt) + print(dt) def sentaccounts(self): """Load draft accounts.""" - account = state.association - self.loadDraft(account, 'All', '') + self.account = state.association + self.loadDraft() - def loadDraft(self, account, where="", what=""): + def loadDraft(self, where="", what=""): """Load draft list for Draft messages.""" xAddress = 'fromaddress' - queryreturn = kivy_helper_search.search_sql( - xAddress, account, "draft", where, what, False) + self.draftDataQuery(xAddress, where, what) if state.msg_counter_objs: - state.msg_counter_objs.draft_cnt.badge_text = str(len(queryreturn)) - if queryreturn: + state.msg_counter_objs.draft_cnt.badge_text = str( + len(self.queryreturn)) + if self.queryreturn: src_mng_obj = state.kivyapp.root.children[2].children[0].ids - src_mng_obj.draft_cnt.badge_text = str(len(queryreturn)) - state.draft_count = str(len(queryreturn)) - for mail in queryreturn: - third_text = mail[3].replace('\n', ' ') - self.data.append({ - 'text': mail[1].strip(), - 'secondary_text': mail[2][:10] + '...........' if len( - mail[2]) > 10 else mail[2] + '\n' + " " + ( - third_text[:25] + '...!') if len( - third_text) > 25 else third_text, - 'ackdata': mail[5]}) - for item in self.data: - meny = TwoLineAvatarIconListItem( - text='Draft', - secondary_text=item['text'], - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - meny.add_widget(AvatarSampleWidget( - source='./images/avatar.png')) - meny.bind(on_press=partial( - self.draft_detail, item['ackdata'])) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Delete') - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) - del_btn.bind(on_press=partial( - self.delete_draft, item['ackdata'])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + src_mng_obj.draft_cnt.badge_text = state.draft_count + self.set_mdList() + self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -1701,8 +2207,76 @@ class Draft(Screen): valign='top') self.ids.ml.add_widget(content) + # pylint: disable=too-many-arguments + def draftDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): + """This methosd is for retrieving draft messages""" + self.queryreturn = kivy_helper_search.search_sql( + xAddress, + self.account, + "draft", + where, + what, + False, + start_indx, + end_indx) + + def set_mdList(self): + """This method is used to create mdlist""" + data = [] + total_draft_msg = len(self.ids.ml.children) + for mail in self.queryreturn: + third_text = mail[3].replace('\n', ' ') + data.append({ + 'text': mail[1].strip(), + 'secondary_text': mail[2][:10] + '...........' if len( + mail[2]) > 10 else mail[2] + '\n' + " " + ( + third_text[:25] + '...!') if len( + third_text) > 25 else third_text, + 'ackdata': mail[5]}) + for item in data: + meny = TwoLineAvatarIconListItem( + text='Draft', + secondary_text=item['text'], + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + meny.add_widget(AvatarSampleWidget( + source='./images/avatar.png')) + meny.bind(on_press=partial( + self.draft_detail, item['ackdata'])) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Delete') + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) + del_btn.bind(on_press=partial( + self.delete_draft, item['ackdata'])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + carousel.index = 1 + self.ids.ml.add_widget(carousel) + updated_msg = len(self.ids.ml.children) + self.has_refreshed = True if total_draft_msg != updated_msg else False + + def check_scroll_y(self, instance, somethingelse): + """Load data on scroll""" + if self.ids.scroll_y.scroll_y <= -0.0 and self.has_refreshed: + self.ids.scroll_y.scroll_y = 0.06 + total_draft_msg = len(self.ids.ml.children) + self.update_draft_screen_on_scroll(total_draft_msg) + else: + pass + + def update_draft_screen_on_scroll(self, total_draft_msg, where='', what=''): + """Load more data on scroll down""" + self.draftDataQuery('fromaddress', where, what, total_draft_msg, 5) + self.set_mdList() + def draft_detail(self, ackdata, *args): - """Method used to show draft Details.""" + """Show draft Details""" state.detailPageType = 'draft' state.mail_id = ackdata if self.manager: @@ -1714,15 +2288,17 @@ class Draft(Screen): src_mng_obj.current = 'mailDetail' def delete_draft(self, data_index, instance, *args): - """Method used to delete draft message permanently.""" + """Delete draft message permanently""" sqlExecute("DELETE FROM sent WHERE ackdata = ?;", str( data_index)) try: - msg_count_objs = \ - self.parent.parent.parent.parent.children[2].children[0].ids + msg_count_objs = ( + self.parent.parent.parent.parent.parent.children[2].children[0].ids) except Exception: - msg_count_objs = self.parent.parent.parent.parent.parent.children[ + msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[ 2].children[0].ids + # msg_count_objs = self.parent.parent.parent.parent.parent.children[ + # 2].children[0].ids if int(state.draft_count) > 0: msg_count_objs.draft_cnt.badge_text = str( int(state.draft_count) - 1) @@ -1731,11 +2307,9 @@ class Draft(Screen): toast('Deleted') @staticmethod - def draft_msg(src_object): - """Method used for saving draft mails.""" - # pylint: disable=too-many-locals - composer_object = src_object.children[1].children[0].children[ - 0].children[0].children[0].ids + def draft_msg(src_object): # pylint: disable=too-many-locals + """Save draft mails""" + composer_object = state.kivyapp.root.ids.sc3.children[1].ids fromAddress = str(composer_object.ti.text) toAddress = str(composer_object.txt_input.text) subject = str(composer_object.subject.text) @@ -1744,16 +2318,13 @@ class Draft(Screen): sendMessageToPeople = True if sendMessageToPeople: from addresses import decodeAddress - status, addressVersionNumber, streamNumber, ripe = \ - decodeAddress(toAddress) + streamNumber, ripe = decodeAddress(toAddress)[2:] from addresses import addBMIfNotPresent toAddress = addBMIfNotPresent(toAddress) - statusIconColor = 'red' stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') from helper_ackPayload import genAckPayload ackdata = genAckPayload(streamNumber, stealthLevel) - t = () sqlExecute( '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', @@ -1771,7 +2342,8 @@ class Draft(Screen): 0, 'draft', encoding, - BMConfigParser().getint('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) @@ -1791,9 +2363,11 @@ class CustomSpinner(Spinner): class Allmails(Screen): - """all mails Screen uses screen to show widgets of screens.""" - + """All mails Screen uses screen to show widgets of screens""" data = ListProperty() + has_refreshed = True + all_mails = ListProperty() + account = StringProperty() def __init__(self, *args, **kwargs): """Method Parsing the address.""" @@ -1804,53 +2378,24 @@ class Allmails(Screen): Clock.schedule_once(self.init_ui, 0) def init_ui(self, dt=0): - """Clock Schdule for method all mails.""" - self.mailaccounts() + """Clock Schdule for method all mails""" + self.loadMessagelist() print (dt) - def mailaccounts(self): - """Load all mails for account.""" - account = state.association - self.loadMessagelist(account, 'All', '') - - def loadMessagelist(self, account, where="", what=""): + def loadMessagelist(self): """Load Inbox, Sent anf Draft list of messages.""" - all_mails = sqlQuery( - "SELECT toaddress, fromaddress, subject, message, folder, ackdata As id, DATE(lastactiontime)" - " As actionTime FROM sent WHERE folder = 'sent' UNION" - " SELECT toaddress, fromaddress, subject, message, folder, msgid As id, DATE(received) As" - " actionTime FROM inbox WHERE folder = 'inbox' ORDER BY actionTime DESC") - if all_mails: - state.kivyapp.root.children[2].children[0].ids.allmail_cnt.badge_text = str(len(all_mails)) - state.all_count = str(len(all_mails)) - for item in all_mails: - meny = TwoLineAvatarIconListItem( - text=item[1], - secondary_text=item[2][:50] + '........' if len( - item[2]) >= 50 else ( - item[2] + ',' + item[3].replace('\n', ''))[0:50] + '........', - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) - meny.add_widget(AvatarSampleWidget( - source='./images/text_images/{}.png'.format( - avatarImageFirstLetter(item[2].strip())))) - meny.bind(on_press=partial( - self.mail_detail, item[5], item[4])) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Delete') - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) - del_btn.bind(on_press=partial( - self.swipe_delete, item[5], item[4])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + self.account = state.association + self.allMessageQuery(0, 20) + if self.all_mails: + state.kivyapp.get_inbox_count() + state.kivyapp.get_sent_count() + state.all_count = str( + int(state.sent_count) + int(state.inbox_count)) + state.kivyapp.root.children[2].children[ + 0].ids.allmail_cnt.badge_text = state.all_count + self.set_mdlist() + # self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y) + self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: content = MDLabel( font_style='Caption', @@ -1861,8 +2406,70 @@ class Allmails(Screen): valign='top') self.ids.ml.add_widget(content) + def allMessageQuery(self, start_indx, end_indx): + """Retrieving data from inbox or sent both tables""" + self.all_mails = sqlQuery( + "SELECT toaddress, fromaddress, subject, message, folder, ackdata" + " As id, DATE(lastactiontime) As actionTime FROM sent WHERE" + " folder = 'sent' and fromaddress = '{0}'" + " UNION SELECT toaddress, fromaddress, subject, message, folder," + " msgid As id, DATE(received) As actionTime FROM inbox" + " WHERE folder = 'inbox' and toaddress = '{0}'" + " ORDER BY actionTime DESC limit {1}, {2}".format( + self.account, start_indx, end_indx)) + + def set_mdlist(self): + """This method is used to create mdList for allmaills""" + data_exist = len(self.ids.ml.children) + for item in self.all_mails: + meny = TwoLineAvatarIconListItem( + text=item[1], + secondary_text=item[2][:50] + '........' if len( + item[2]) >= 50 else ( + item[2] + ',' + item[3].replace( + '\n', ''))[0:50] + '........', + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color) + meny.add_widget(AvatarSampleWidget( + source='./images/text_images/{}.png'.format( + avatarImageFirstLetter(item[2].strip())))) + meny.bind(on_press=partial( + self.mail_detail, item[5], item[4])) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Delete') + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) + del_btn.bind(on_press=partial( + self.swipe_delete, item[5], item[4])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + carousel.index = 1 + self.ids.ml.add_widget(carousel) + updated_data = len(self.ids.ml.children) + self.has_refreshed = True if data_exist != updated_data else False + + def check_scroll_y(self, instance, somethingelse): + """Scroll fixed length""" + if self.ids.scroll_y.scroll_y <= -0.00 and self.has_refreshed: + self.ids.scroll_y.scroll_y = .06 + load_more = len(self.ids.ml.children) + self.updating_allmail(load_more) + else: + pass + + def updating_allmail(self, load_more): + """This method is used to update the all mail + listing value on the scroll of screen""" + self.allMessageQuery(load_more, 5) + self.set_mdlist() + def mail_detail(self, unique_id, folder, *args): - """Load sent and inbox mail details.""" + """Load sent and inbox mail details""" state.detailPageType = folder state.is_allmail = True state.mail_id = unique_id @@ -1875,7 +2482,7 @@ class Allmails(Screen): src_mng_obj.current = 'mailDetail' def swipe_delete(self, unique_id, folder, instance, *args): - """Delete inbox mail from all mail listing listing.""" + """Delete inbox mail from all mail listing""" if folder == 'inbox': sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( @@ -1886,13 +2493,13 @@ class Allmails(Screen): unique_id)) self.ids.ml.remove_widget(instance.parent.parent) try: - msg_count_objs = self.parent.parent.parent.parent.children[ - 2].children[0].ids - nav_lay_obj = self.parent.parent.parent.parent.ids - except Exception: msg_count_objs = self.parent.parent.parent.parent.parent.children[ 2].children[0].ids nav_lay_obj = self.parent.parent.parent.parent.parent.ids + except Exception: + msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[ + 2].children[0].ids + nav_lay_obj = self.parent.parent.parent.parent.parent.parent.ids if folder == 'inbox': msg_count_objs.inbox_cnt.badge_text = str( int(state.inbox_count) - 1) @@ -1913,14 +2520,14 @@ class Allmails(Screen): state.all_count = str(int(state.all_count) - 1) nav_lay_obj.sc5.clear_widgets() nav_lay_obj.sc5.add_widget(Trash()) - nav_lay_obj.sc17.clear_widgets() - nav_lay_obj.sc17.add_widget(Allmails()) + nav_lay_obj.sc17.remove_widget(instance.parent.parent) # pylint: disable=attribute-defined-outside-init def refresh_callback(self, *args): - """Method updates the state of application, While the spinner remains on the screen.""" + """Method updates the state of application, + While the spinner remains on the screen""" def refresh_callback(interval): - """Method used for loading the allmails screen data.""" + """Load the allmails screen data""" self.ids.ml.clear_widgets() self.remove_widget(self.children[1]) try: @@ -1932,16 +2539,25 @@ class Allmails(Screen): self.tick = 0 Clock.schedule_once(refresh_callback, 1) + def set_root_layout(self): + """Setting root layout""" + try: + return self.manager.parent.parent + except Exception: + return state.kivyapp.root.ids.float_box + def avatarImageFirstLetter(letter_string): - """This method is used to the first letter for the avatar image""" - if letter_string[0].upper() >= 'A' and letter_string[0].upper() <= 'Z': - img_latter = letter_string[0].upper() - elif int(letter_string[0]) >= 0 and int(letter_string[0]) <= 9: - img_latter = letter_string[0] + """This function is used to the first letter for the avatar image""" + if letter_string: + if letter_string[0].upper() >= 'A' and letter_string[0].upper() <= 'Z': + img_latter = letter_string[0].upper() + elif int(letter_string[0]) >= 0 and int(letter_string[0]) <= 9: + img_latter = letter_string[0] + else: + img_latter = '!' else: img_latter = '!' - return img_latter @@ -1961,3 +2577,16 @@ class Spam(Screen): """Spam Screen show widgets of page.""" pass + + +class LoadingPopup(Popup): + """Class for loading Popup""" + + def __init__(self, **kwargs): + super(LoadingPopup, self).__init__(**kwargs) + # call dismiss_popup in 2 seconds + Clock.schedule_once(self.dismiss_popup, 0.5) + + def dismiss_popup(self, dt): + """Dismiss popups""" + self.dismiss() diff --git a/src/images/loader.zip b/src/images/loader.zip new file mode 100644 index 0000000000000000000000000000000000000000..c80a3a17e22d05832db089959679ec1c995e0cb9 GIT binary patch literal 15918 zcmY*=LzE~AtYq7^ZQHhO+qP}nwr$(C-M4Lf-k;6z-Q3))tgY|%dZ*8xl9Q60oSb@k;`}~aDhdi1czAG7QCr(y zi@Ul$uhatt8eZ=WPfw@Qr>CYaFE2ZE?0kHBA|oY5MMaH`iL+3TSey^{ud#bCgy}ZWW-?>>?UlI}V!j;i+eAedY?L9n7dULloHdaZ(08wSIY7+1VL-$BrD{-AgigEHE(ed_I4COw7vClAMG@hu_cV$q7oX z+}rar4mNhb^O>Bzy}h8IprPU6;L=x z{466N5KvQd-RJuyL6Q_33mYor=;U;HeeL;ry;&-qh>4krPNx$SEiEA}JwG)?Nl9tU zbbRrAe{hh{Zof}QPahv2|KIihlcMtC;vynqT2itS1}u4WiqDgYf+gkl&VOipTwX{h zNT!X`>7*ifxL-@h*5+6B$kN=r-@P6+QlwA`esh}}6Z2+mog67r%*+g}sp-+ntDA_p z7zhX`9v>b83d+s>t)jZR-@pH8kJn9FIy){7E`GeaqQb`7+s@3ati1f~E*lFA3ldUN zyXNR4DLowYVqPvGs++M7C@T z3lo8`;E(1fYzRSsv*0cN=T8S2pc6PC;qev6O`JwaX1qLKc_%eO-Ib=Hp7ugAl?^WM zvYz&4nn0s`f_o(u*2EgO>KU`5o8Kkd!>D24Q1T?ht9qXo(o6S(d*%K7NBMK-fVaGy z6+ch3j@}=`>+}8C84RTOd}k!{LJDd51>3GF_sY1E3zds~-4|<$nU9-y=iB6vbel_c zv9#3h!gaKesvn&emfD_^JPb-VkJZm}-^I}MbF{g9pU=sdQL3(1cK__N*)=}Cg{_|c zUMe?AXIsm!Muvy;%dzBUv)=x@ZUwhA_@=gh9bI1?*MD>Gb)J53M`3aB?8g6hQ%C>f z{qf@|7Z;#z)Leix_?=NA7K#tqx@#hSblY-vB+?sfc0@YADnl}%zl9@NLSi9HR%seG zOLmQ_K0|iVS|>-A^wny%G&2T#c9-Q#hcVsm!`YE87-T)qd{ZJXbG~KWgCqacri&$C zwsrY8<@nI^-!g5zGCcq3r;gUAOLkhp4<|jt+sqla;3+)+SvU)wZ=dwtsvboI27j{y z{o~Vc=+Jq-G_)v8#~cy29Fs>Qhh(u+Bgw3bXJd+Kd9zB|F=meo|DDRIlILLQX({+M zNbYG=)6T(ZIO=KYbn0sC^mH3sEjJhSZ`wAGHKH`1cj@P*4FQaoZZs^pcT|4sOWR@0 zYb0LSUL)wo0%-8uN~Q47*MtYQ_ijq38*j3lI>BYg1gkVOKM&rnXjd^rcLSpSZBxXM+a&FolG z-nTcR20mT7-l=R(Ul;KnL0A@K>DoE8xC*JqC8dZT2LW6FOKTwt6o&!_xn5MGRBvGd?0@&@!-Lc-~sKDF;{kBDN3yjS|5jaQ%K}={BM$Pj}agOn)GhP zkR_rIc#9jzaA3`t8j#zy=Z-7~C>0E-adMu-%@Y#iY8)L}H34aWsK=xj8zYD%Gss4n zk2*+Nq)Y~IW_Oq%&}MTKs=)UNC9F?OQxy;j>bm^^==GBXAWa^vCZYu5lO7^n$(VpU z(m)+GXILZ3#{(;JK8)m#<@fEl+F z(5C@&9qc^lr9esmvO-;oERYs1cEq1xQz|ICbEhp;WvWDy4!!+2sT95Tlu0PH;xDo> zjs|qvtsg*aMBuTOASc2TK~4V&oqDr#A=c_1zD!hZF_hT@n-2s9p@fE^8*L>hR0Jl2 zo^GsJxp6HZ^erBSx}n;;Ey_gBe3P;Rm+=&GtOxN_?~ zdMjN7J2*osH%_2ARPJ7~X?bs`)KL$%zPT5F64Iv+b{RE4vEpbF7;XTw?1Li)=?oR@ zKR%Dws3`IcLOh)mgs(u)s}YmkpJX9TIX%kZs3Syseh+sC7?Lw&0QG?!;i16D4d(Fh zqb-nM*S$&k14M+|PWtX+V;`%ZC5Xr-96Acmv5$#h$XpNvz>+hIG{1M&w*x=j{ZD%S z5I)^mX#EeylP_X0C;ld2OoH>+&!VU6^36c`L=XZ<+>JEE4wzu8I2NqL_=@!&)O`tv zcV&!09X9Em=u;Ab2Mop4C41J?uGTr!5nRUM*-~FDk?t~ac4mp_hnty-y%_vF@lP8s z?E@(KvL-y^*usFaBUOdR?42%7J%ynNIe(m39erCiQK`n6`_RRL=^o8e%iGLgVRs;t zzW^0I&coKcJ++Vs;&|R9{zOZ^ca4t9*OE7a>!3E5V?kHApO>UnLsaX~yEy(?l?}Vg zYh=*V!on{W37W$7QeE2S7A}#ybV?V3g$?Pt_jma#RU$zN7e2Yw1v5&iQf$myDB}8G z9z0@#_P@uVNFhtc@MJnfy|z;`L!_UMSX#f*z<6gDR`q%(=fQPULKAL z4}BY9J69~CIPU5FWWdX&KZMs?JS*vXECSU&#WbqsPkaMlcsAD;masW)%isM|IO z2IK64i#~E-;dQ8P({z+NtP5{v&sPyrKFT&iq^&ImG(Ib!tbap-dEg`FBflBk{(-pL z@o2vP_PFZ&HUC&1(-96LzlT0bv7;Hn=zfSus~U6Fo|x)lJudyYI=a_79}zjv@TB9O z6cs)9x0`A2GcVctXAp&yia9(~WSu0*>n=}gn@+1F6A6OeMp~`Mf8Ka#zfRH%w_E95 z+XE=mfCiRhbN2m~BjCHRm`k2MM*{AX*~&A{#vutop+QuG^|!0<>SY|Xm-&KBig81B zX~RR+v=OJ!p0a)2Y-s){jm?!I1tjKbr8%0p3H{WCtduk0G4*nhXaI5${Ba)$E-=>e zpu%66`G}EFS%D{JQS#a}VTMLC7&_gO&d>R12j6Z?}8;)T} zW?;=iTjrB`+Vp%ph3(Rho0BYM&LAnv~>d!69mD|a|tvc%s8##=B)52)|`N_j0OGH>UfzX816D&A05L4{YGGX7N(I%f-Y~rc5=49}nr>jJ_#ou> zT&eA_UG(_K7yaK5D+U@#@{~q^S4o5sqxtYWW}GC>4p8o`;SE2Pcc!>KBC{P>S;qQW&*N zar=}Cx2gP2@Q|n^g^(gD)9f@yk3hRn(%I&ah{inULM@*UAAA zF#6vRh?OxRNe*6amxpnW-v$9Z!ou=7pd8Et)xs!=&g5nR=7Fn}%PZ4b0=l zCXpnR#JaoT58|C{ulGpY{z5vE4cwTDf_=aI-1QbfO0$pynSIn*O*^bDb5sNDCc7KZ z>)%p1Bf6G$PRJPsX%eW`f&C^aw8c_Hrse4debj?d9AWGdkYqRAwNxKftqYNG@Lk~K zvcs=g=o`?4-xm(wKs!UPcf!~?iGhpaR5HM!&4xR^7S;YMx^Wlv_eTe8vS|RtzMKscZ%q8SZZR@}!VX$P zj6@(Ov}8DN;y;OX4-YRr`E zBO|`$i;H#u2A_LoY^_ncJwE8r>W%vxVzT0kE%i;8cFr7N!!m9V1-FO2p8^L#k96k` z?tl()wx?%0V$w8SG6S*Tn_8P9Rk^SA3HvkiiGb@pu-9g^Go>k>M&{_Tf64*9163P7 zF?L{BlIXIofMoE~(8g4f2a#FAhhbt+bP5048D&+n!`~h*hA^)_!>6KF`88Bua~xp3 z73J_gH96#KzXAf?%hbZ}bY40`knR-`ds~#My`F}P_1z!|&@OH(c^uhGz5+vwZI%o~ ziKo%Lo@Xm1(0>G4yf}2#((F@U)@CJ7b8HxkMI=JcB@v)cno5Q{ng*l z5N0F6TQLGm=zs;kJ4zf?D+e9&9}Qb@q=yV0^x%owATuJY;;Ign6gLJrH^mAGLeL5k zTY6|8f&vGa9%jJAO^d;s2NLQDPpFg03Qb(|x?ydBqnRtD1)c zFZ}osKkwx;#hpeWDNIt_I7v+aRt1MHR**s{2w(z?(9dI9I2yQnwr-v`;7efeDI#HU zkhv=!M*e{i3@WFz2%Ld%m@H z!5(aDE4QI=KHzEGj;3w{AMUCs(ATsfqjzTq+|HAKo-8|S&Yrdl0(`$TxIYPNZG%&Z z`oo0}AstwvieUepFsVDZ%`8{cjmyaC2?fQ4MU zGb`*ih9y?hwlqMD5*JT7%}FIM#nNrvz6_!ghio5vB)oL;h2<82B!h!k&K?5(0;l-| z5VUQ?8&~M6;*{`~>6_?9Xfpg`x#n^N!Ryjrkt+gFquS0a-N@@gNSzh?!+ zq)r_$1JTi=+VP_{IGor~Re&|JxT{vDK+}QNhl;=G#6hE4nh9A0^m%dkGr3G5k_`0R zeYdcNFm0_cp+L6}EgAI*5c~`;7wDr?-{ah16_=LF@oy$r@zdzsb>eDKgf@{pc-QYv zU>FjR*7=)KgNr88Cm<~3093#JCax?1E&RAoO8c$605;MxP~vX|>Eit&nTvBm?(}f}+=;T3a<{Mg4duG15p~jp9_C=Zn zc-WxOoq>C*wV)ITgZ$RSHRA>%AXn`0_Ldm=ZG(XuaQ!Pvz-xW{H6npq^P-do0`9>K zoI>Ph{ZB-J8YPrA*qVV|S_W>p8)WZ@fc1jj4VVIa6EyGz{SAJs;%RsAyF+LsPXBs? zyPg>d9t{LP5rjvvBeToll=KIBv673%!y-qjbOZ5warjvmjs+(iNd@-9<#Ms3l1Pco zPB!;QF#2sT%Xa{W@VtaVFX5PPcU~H!DIC8He7tS<8O28KJ`Aa|qI)acZjYu1*xx6_ z8}1?KNM<;XxPSPO{Q395hGW5|ZTZm_!}xu2JU>Ap&^;4kkNm&UVu#%kc+fZ&4Wfsi zR`GHhiF-CYvIPILlh5wg1;}wet--n3%24iwGaHWiH{Uh$^Nr%ShPH<{A?17Y(0Pmo zWPF7D?d$96a#F_R`M;Rl7%%d%<3YU6zphup%lx;$7FcXFfJM6FwLZs$XZUPXd?dR^ z|KG5gwuj)&hIsdgXj=ttB>c7C!V}@ac7CqtYW&`J`hsF+sgBIIrv-XC*7R zmy>4eGOrFz47<5h=4N`Y+gEUyN%;P^tLwTf`0YMXb(wL0iWDg7EX9t6AJ+2U#jx0` zeaUW~Kd-xTlPAt~^m?3+47AHLh;utf>bCh#yOzUnv!B}p%Oy+$LYvQJ%>K}cq0oxg z(DRGXD}Qv1sA!q$QI7u6kgI6Pz%_wP2HEB*i>CW}^N2v72?R2QJ zbf`bNM$~lanzZTfwCQ?!brd@FHhOh=`t@(!e-w2qnzbumwJdu2mQ*^Hmim^tdX|6P zL#jGAEm}9P+Bdy@TlyVb8+}|nyzdW|Pk#FR`hQ&-@2;IcSC`N0_5S@(DE+mXzT5X-uTP)tvqSdUH~Ven{XainunI^4 zZ_owfp!e87CW!z)Isrcv12+)&Qv0HB{^}yym9xXIPhIPw{-rI8*)x1oepQ>46S%M=|AX8oBN*6WJQ9<7Lu- zcQvs5sR6@N&~2tfWcokw-SgZQr?lmsAA5bhe~n+S`g*fp{H>0qLCfD7_t1#kj5$X= z#1EDR3S4rdXp;%y-KMbG-_LI=j6m697Jj1*vCT`Q56&Q_5 z_#cdrZne{^OC3H(#sOKQSaE_fM%4`zV3V0cm%}qE4!R43QapNVWQsQj>!SZuJL+8s z9M>t4D~4h?NM=*E|3D(zB^?T?PHF7GtSD8cK=x8Ui9-9*Q5wvUVfJRPRFD-!b!SES ztcN7)LER!;H4*O~pTQ9Wv z3-rh5ht30Eisbl$$d9@4{%x$(PF%KcD5E}pCWku}(oPb7(5!2gU;_DzVgu_^^=Uc` zW-FlvXF_o6zITP(E3j@O&#JCgPwF8(-O1GnE_BLER@mpN@`TPO;^so3Cl_f%U7JA(5Z;{jhp&mZ`NUqpS#=6LyTK(2t10v!sWR~kU%w&!=W3xH$q;DE zHW4Dl*9L?o6LUQ3hfr^@miz_3{TDz11~n12feBw-CLVkQ$!Q9c7mdw7KM?` zP5sbP1Wqs`j^99!c$IzL)?{A%lWts+MP&oK^uZo)!;H`dxGPphB$W6f2oV z6{8Z`+&Y&S9*l$%SOpy3jpzX;@*WwkklcZU<~c9-ZZ^7UlR|cBJBG)&n@ZmKP??Ct z0RuI+Ad?{}BvlhhX*GKiLZ?)aq5rV*ov|%kohzV1W^gGgHf%oFbxYKk$4RPmH$3== zH@k2T$q2lGR&XV`7uhRPD3Awy3O;m$oH308qqM7)6gmYW4lbcWrh2YXa5R4~;@Ev+ zJZbd7P!2F?OW5u?8yQY%A&m@~E0NLbM9xCBaf}uso4CMSK1Dl>q`1_U1=8fb<{Flu zq?Y92a&tZ_jd(VD#4slVv?X9a3^#qTpkn9P8V_)LaeGx>hf}(TGc)Pj@y0;!125B- z3d29k?Rww^9?@k5gYFs_SfJ=p94psyX4FuVSM%uL?-uqg9Chz&rDGMs|C}-em;oj@ zTwlwW?D3uu;~fXyHtAmTx5budLQ@WNnq+uI?v;Qw zOrwuGNX~>{egBE+C)D1bO)xJ?0E`*KfCi<>;_sybhT+JhP)8FLGO4#^J-PKXjz?_} zW!@0ixjr-S3Ex#B_ew6#z+F|nsZ}^Kr9*f|N7el%dF)R`h?STmQNdKnB))DM58m#| zQk#KJ;%$wr6vnal@S$`03g2vPPiwl#2uSY8cvby4I=Su{x*b8U4r`Rft}-8*xh?(; zfGrfNquXa*4?*_CIZpyzi?Mm>UXw=nm%LcXTZ=2%Ysz829dIbnmqY<^@Pk zPu9H^@Ftx1TV^QSX9p{0$Jj~NVJ-l{+QA*(WP5C<3$idD65c~6}KrT=6V7P*0O>Rlj;g{o9Wl2r10Nk zG-|(p+n$la#NUv^v%fLN?O*7j#p0j+Wf-tx_%O$xsf6}0g@6kB1 zD=*3v4>;;QMrVzh3ys^4aLGrv>A$1*vZXDtSd(9S?NGGr6K{UCXfQe?dm0)&>a9D} zfqRW7jjOxHAuiv_Y+77UP<;75O9P8}u_on;t@vFuZD zBdMMwB8l`)i9wUmH8;xY^b1FWrrvKUWMJY+5*I-wFG(`BAzn#a`S`vvs0l^D`m-Gj zl!`x+uC`nc$p%L!wR|WYH0*u*u=y{9GG1Wy>$OQ~KebsWS4V--9rbR{I{>V+i*!ha zWgT50OA!ngYY_DEQ@7mR0j~v&;-HJPewi2Sv9LRb_iy>EFR-KH_O2x<@S# z?HLnFgLQ1yWCOy@pDS6NfUQn21T7{;5y^dx6o;;#}n)vg<^r1j57 z@8OmSfX%y2b$_)=Oy+8-arDjVEPa3_y$DUwDA^6~tyxRx8UMZba01so?)Vp38+I(I zxM(*3qPQPRphjLMKN;OhvEcoAiH-DB-LWlxMe6rGw1$35%{2me=ty}K(^~SjpA~B} z4q6>=9w)vp0vv-Q0%_^!ohb$H(zZv8*s&X0ZrwcgfW=;%%d zcV372H+^STh@eLIZ%0yI zufnV4{N&*Y1xS=4a{b;W6AlDaJBNcZh(+|C*L3?zP6B#!i5L%SGr$>STm(EM9Ro}L5N0ke}a8d@5R4Rtp+bl-Z|($RMg0O0_GE{hm#Ln zCt*6mvzEsB0ECnfk!|vc4y=#i{$1^qvG}rKz-@W@@tA`Rp;>6)5dmUUJ*GY|x*|%7 zpRZ;mZ-b3wE`qxZr4(C0#dLBn+RPhPV@tRzlpfP?GVmXB)^jtiBkG3_?*SK6!*C zWx}nN68*MSd`LpC5-j0A?IutWjC}!sJ5vYB1)R8E`ou{MYDfXZkw6SJ9>-3A;CqKH z_opTa1(|C`gANOb-L41&xPqzSt}MU40jN-Df$CkL)@#mRDN`wfVE|QN4dxTt995#l z>ik~W$Pq4JAPx3SD?L%c#OJE{dqUEwE8|PNHhfT$1+9mfJSjD@g_ACGln*#S7s}s5psHr!8K^eiJra-IL36tG`bz!6P*P91p3@i_`CxS5mrnTrQUx<&yK` z%~J>D&j7pFz_&=ilfKbd%MX<4Usw(~2JWbJ{A;4+yP@HGZM--Q{CUkMze2|3tf}pu)V~<#g7bT81{)S>g%9QdTnVIIb3rEI{N{clJT3xtPKb5^KWeo>dYlKT&0VohfwN`}v@{ z>llW{AyWwi=*%MiDl#;VF*>3|XBa}0{g7ABxKgkrmCLZ9!ejkJ(}|0(`^7V$nW z))_5`jXpMn&+jv0Jgu)7w<4jM~eS`a+x`Ld|iXfS$zAr@kOm~?jECI z-DgpQp?wekcxa|2_n!@Kynoh@j9Jv8<8|CW9iH0eeF3)n#5))XKDAlHmGL}DeMRJF93~)nmM<+GGmTZG zXZSoF7R3%+mu%)l|JT%9kpIB4GbUo$OwJoK=-xum|qm3h`b;<{ih7?x#_1 zcTksV8Iu9jUz=WaFPSgIof2*0)5mPg&z<3D0UN1M5+Bc$G^aO}t zEmzD0iR9{3Qxn5gdu?sL=wN93W#u-RX)@YN#64L2i1C{``p6~4u953_%QhSB zKM=V2B5 z^K!w$QS)!pDAvv$d1y2;C}7Swq2Z=}-mP#aJiJeBo*mQ8Wgs3M+TuJ$D_EG%^E%OP zF}~%F7o@&&kQ{rDt!<$eE3x%=7AX;{NtQjByQAB0)k1=b7<*Gl;T)uuT84A=<&ST) z`36`h%8?7Jmhh!mWq@7T$l1EISpS2GII^3N6Dznk(e3=JV?G%PTf7SkG2VBn?Yh3%u{4yZ0;S|Q)*WT?0tckhThEFWy|57dp7d1NlrSHVNqz)ITa8yVUZ z9pkM>c8eR0-Zb8voTocgceA*4gw3s00sHlbDkzSOjPgSwS+lwFYt_p{M(ZcvFg9q7 zj;4TAL}1|xl@-Q8Y4hA{_W|l(gy+Q*Lr#Ln8w)&A@a_e|9oL9(kL8amTph3an2iR` z(&=^Uh4fE3Bp;p6cf3kOM?@cOmBH+z`?56vZ>1)y%gy%ZmE$1`mGMU&|L+YU7>@Ns z0zEeds2ecxBOQPALAmt6W1J+yCQOOejHx*wX#GSWt&9QD_}f^}u7snc)_`f`IUO!C z9{W%%*+T*t@CPnqG~`Lt>65MA4NYHQaYais7n@8Aj6Sr<=X+8K^9L~-&*am--J&(0 zx)*djgl9Xz;-RZ`CMtOhY(99N`v5!1r6hDusmQDhjUJDrSa=|}&2Zc{dm6QBu*~cEzo7m4Ku8Mz2rwAbFWGj>7<1Vn8#Cpnee70*kE45h(FBA`u93R*C&UYIIA>Uu<3O!@Gkp zLgvLxM2SiQwftMH@KwDNbE8N5BD`Fpy!nd-rXqIC&kjkNGD^N$cK0=mkFW$Vw34^x z1Kl@)$mmCc%+b6D#Iv4zV;4*8?2Ymq-<^?sgquFVINxPcAS4tK*lY+_lnLW{B zh-px53$R4HQ~<~Ay?;jcOb(5lC{7bL(q`^iQj&bImkvw3a#nc$^!c=BDz26sVB(ax zwQ@;1%)t|D%1(rL=~+aYkZ0l}czzyB^q!MEuLK21m+#_8N59xKEw(BT0~yuEgBVcU zo{QtDgDWjXn2tEEn3LYFp`rOr0An_?IJ(p7-EdHn#u3?UzOT!m@H2Eec97^*T($o6^;#0ZH3v_8YJ#}qIPo`j?}wbNAzl?=IHI* z3xgh6aE)Sw$)XHGSdwiBu9vc`WkFJVr0$`Mcb&iKyPKzxL{lWJ4TswFsu7a#vZcvB z)Ff($3b;SDA;CmlegJhm8;&Ev4LZ__-I!;;VM#@=TA~&+z;{Lk*hu_!ze4kNI>sZW zhasPx@ZJSbk4d+1R;;Gt+?pD`MahkUxijP^%c9I!ixC4|k}wt0&thO03plNIT4uRZ z{5_+2tJsXmnhD;-wmD_J^n^p6 zrD7GR#Pw0}Alt#SGDXa!#hk@%O5VIsM%_ri4PB+BP5W!Fh*brS9> zS@A>^j7ZphKmbYTke{56K!R7OgHx%l#CWNgjN@@Q%l=$$;Sy&uB4+$sz>rT{oSUVV z8+Y3S=3`YO2k<*E#PVPDA-_4O%$_2c(-%lxHGy>9WMoKYY({LjCccwkR*qR{rAmq} zbYTBBqI`|KQ{3H+Q`ogEs6XEy;_K?$urI`#r?`(6f9CL4y-01(U`5uu`WlZ5A62Y| z%;Ox%g~y^Hw6;?*2E{FJvI+vP^Dj{CFT5V-Wv`{yhzMIj?mP?j&(z8Vl$i7aa&!Dv zF~mgGxWHI^2_#DjK&r3db=i)20Es&>P$tj1;}8MjXABx5eL@lmQc2;EsIa?&Q7~D5 z2^B--NHz-&B~SKwM}-bbF&3GuaxH~tVa>lb@XdT~ceQba$RSd4b90t!j?(}%_Co^A z8Wa2$SB12+NJ_no+)EB=-V0)SRp`~diDgiTc5{i{%c#v>Mz=Q%Ml~ADjw!^Z!=)o04GX_qGxDKU2>Ljqv=5C>WZ@xcy z92J=?_$xUcGXP+wd@+I>?-m@RT6D>r65Cr=3Em=gFvknf9}`U)m6$V{X3v*F(Cao( zr|EP(B!}uQF$VJFmpsXk@6bJwQCcblElX}w6tu16I+_8QkKGx`G_dbqWa$Q@;AFpr zI-S!*1SOo`^rap9Ur0vuRInVeL9F%!a4 ziK##4U9$DgDjI*{q<7mBDU5+RP0e+^X+~m+H#zHbzIRIInhKuw?S(5FJzk9K%R~e) z@YB#>Fm5^+EuxclX+(_8_ZZ-ru`UsRQ+nmpbM~iRolGoA$P@34gZIb>$5p%Ka@8?? z=oc4UWT`bm*sk)O2{z;wSJ;}-dAId*TK)~G%>zWIQ0CG5=k`XNy{Zr2-_~p6i zKf77}JO2LpOlSW4Dm(I@*^ZaQmML4TmH83kdf+uP>VA-YXU@FPk!_7$vV0IDkL)zk zrNIwK+}GjCBp%CF`{-J+5ZEla7^gek)zV-)&}icc3HS7#LTXdt`z8hkx*h=%;v!kF8tW z6E+9k53pY;8zkg!me^eab2_)(Y!8)$s{A5Pw_;4;eZ5>VS8|IF&rju?d;Q7$z8vc$iw6a+0_+YiS-<;#x+Q}fQVkD1=Pg`(DwWc`h3|LGy) zc1!hCpR<{Rag;RDiMOwi-@6KHjF@mdRVXG^7|ILzJq(ssA0GR@D6a8Ii|*gSf!uB! zRw+{BL2uDJe9T+PJ->~~M1-M7d*Xb_X)Y{w-M?WqGUAoT^L!IOw z%JjA1wEEmfJ#bVMg)qm;rYeFuQ=VbhUx2GN(R>2K(K!=Dw#-v6=}yIfKFp;^h37u@ zqVM)3rQ|7Md}fUhX~S7a&KJ>Lv%YnR^-+0rND3wNU|8urEH+as3r4=i7hrw18=g_o zHSB(II?+`EF1pN!x`sYNIZTGBsDQp<(QEa&J5YmbpBh!*qi7aW!H1v5HK2{fdT}z{ zq0SvYf-@m+a2ar_Y-7e!OFLsJ2bxNYJm;0pUG$A|OX{Ic>5^Z0R4V!!?d#QZxr2@2 z=5F%=!^ARL0$*I0tC+e}Tn_kAJYdWN3d=QCzGy4?!q|2I(8?gVzE!H&D1CI+ z-RVl*9>m-;_zVdNX=XU`rXj?=MyU$25tO*+)1jJoX2Uv6D5zKo>>n%QK5Ga5c zd$vmw>m6wDTv3%JJyi|du4)5rvcj!&$|E)GwdaxR5tsneQWLk_gN_T(zI81_~~T%eJ?m<+JIlSdXoDjp6+Fl`58ChLUmm_?IT;V(>iwXt(vNfG#Iov+v#$Z zrMGw%IP5FjZTB@kAYev>?KX#pOPFL@`HO~xTFSZrh~2WS1>ZM)_a*Q%?fi#B$5rk2 z68$@>2qLi^X7L?se!r`j2M6)fU|qNbzU~?^LKDeC(JM@{HOz`nAwiA#u4=_bS49GK zI{wE;dWXkPNlG-d;PU~{5m&~Azu!)pQ@%r}MVvN>3|Hm^d&vB?vqZ7(Uqh`a9>%Nh zen9M>KMU-h0nqXLbj0=Zt#9Cu;dte2bBw1|pa$PI~m`2TVzd8W=)_ zfpIOUOZjD&D5X?gkL9qMXh7fP%u55AmraN?*8W39h2>t6>c*>Y036y(a=0LOc!hJj zMJoG!n{$+G2++YD4@&;Y6Q`#W=xcAt$O>(qIlc+ln>Y%1UL+$;*m_SH_<2eW)nW+NjxQMX>y&9>Ik}gEe#a33PvO9(44K zK~jJ&_6OOmk?Ct6Yg4<#1dwqNdr97SM@@*Gud81d3}CNh@a^u3;pupz#%9o(4HwJ0 zO~Hj`(F<;vm;git)}zI$$UpDEL~-PZf|U-k2zEN>2JMIuu*&_7VCQ<{SBqnid7j~? z02-E3o1q-w=J76Ao}U(|fYv@G%H_}Q|9$M(e(Vna@NwsrvdbeBh)v@n z28HNk^%JI{7uxg;^Kb!%jD!sNtsErxXluXW8gfURo=?Q)XRms+GfTkbb|+2G0P1vu zx2|Rv>YAhQjUlDVSt&heDawGi^Yci!ux0tE`aAy#l`cLg9!92IxbP<=xaVIy@bU)_ zYLv|ATmsySDI^SK6k9I%vpInWTE3IO-NY$^^0eX6VUtBxSFP<+L_85 zygD1OQV$c7htYv{ckIK$qXX(?^g{Xsjh0;ZMQk-|b<+vTi|=9e*(~Z`!*SDFjEokf z|JzU06_2jG%nd9{>D^TR1%wozNZ2lskh}OoR$hHh0!F9W0UH9DGIbEPVlL!AF5(6C zZY39wEq`sjaOf&$P5(U#l01l4(i8-}2`%gqiz_nBPkUidl)oZT{eUbWE%DFHU-xXR zbRE>Qw5+o;t2LUm)e#Wnnv>V&a;&+{AVRH;-=tpxf5lHwlqSXK;RM1Y4-u-jvM zX8xS{^jvoF*v?n_mXn4N<9DzIKWcd^Q+2?4e}-;K!sIzuqBI@d^U}J@Cw1hWNc|+k zy$5-?l~u0S@kVL!wBek%w|OqKS~4BeiP36`0$1*btjap@HEd-2*=iWnY;gQJx>Mqx zNqJ;A3SO5|sAhK0#O{GJ>j!L|c?I?&lg*GTWz6=W#Gd(fUw<7_rp!h+q^=T@SDmbmc2(#xX*k}H`9IYtO zw&%^%UTm_`83*KOD|r%08BCAZAaotq74oA`AiJ`rI#|N#pkj$wgU?v~GK`VsD~5iyD%Z~4hVqPs|NCGz#@ zVsv*mflkNR`2CV!Y{q=QTRIcX<`xKl|o^mt+fAloub z9+Q)|H3yeiVY`w1oJD!i1c7*sv1=d|{ylFaV(1?)YtVOKU5cdKm6uX4cP$8BjzTpB z$~w&mD>SLqNUZ%T*{ww(j34EkjEDoVR6PGEfYo-uDp!9mhahO1*agBKOD5V#U=T{r zFw-Xzszvr6sfOuFnN>iYk>K4_NDV}`-EHSM_c5=qQ1j=pGERe24jagPCX5llfDoON zlJgRjCF+;*P|5_$f&dYH71|Tn%(26cUi8CAha(%M{EE!D3u6+X=m|>#^92{vp%EMt z=DTs~VX{D<7?+UqVfj*kTfX#<1%IOkP{fTvp{`ruf~lDJQqlzC>Mf%rNX;34T-j=J$s8D3AFqMA6rj*y}0ZMmHDT`0i|+()e$4X z0(d=2SDa_lh|X)CVEqO%&l<;f!g8;yxLzkMgH=*K%tLPyMk; zl@134grA1ep0SNUkAC$S7Jld-E1ZAK=djBkaM6Z6zc6f-*QLEQq5(F{!}kz+wQw9U zD6bT@4xqYza3Ne2i1A?^V1sFXPA)1-L2-xu3O%-9b+hgaFm6bY^I^~_OV_mUvR`L% z_XnyV4G!^C?R3(_3jjdQ4*;Mb4G4q+@c(Sy|9kd7Ht+u*|JU@bAPoxkKW)JOg89FE K`X3bl!2bc@Mkc@j literal 0 HcmV?d00001 diff --git a/src/state.py b/src/state.py index 4baf5614..54251270 100644 --- a/src/state.py +++ b/src/state.py @@ -106,3 +106,7 @@ in_composer = False write_msg = {} availabe_credit = 0 + +in_sent_method = False + +in_search_mode = False \ No newline at end of file From 4390a68b303ef1ad122f0c4224f3742be8d402f0 Mon Sep 17 00:00:00 2001 From: navjot Date: Fri, 13 Dec 2019 21:50:27 +0530 Subject: [PATCH 17/54] worked on Kivy fixes part 2 --- src/bitmessagekivy/kivy_helper_search.py | 2 +- src/bitmessagekivy/mpybit.py | 53 ++++++++++++------------ 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 48e77cb2..7e205543 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -20,7 +20,7 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w sqlStatementBase = '''SELECT label, address From addressbook ''' else: sqlStatementBase = ( - '''SELECT folder, msgid, toaddress, message, fromaddress, subject,''' + '''SELECT folder, toaddress, message, fromaddress, subject,''' ''' received, read FROM inbox ''') sqlStatementParts = [] diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 1a0d13f2..bab578de 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -237,8 +237,7 @@ class Inbox(Screen): def delete(self, data_index, instance, *args): """Delete inbox mail from inbox listing""" sqlExecute( - "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( - data_index)) + "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", data_index) try: msg_count_objs = ( self.parent.parent.parent.parent.children[2].children[0].ids) @@ -267,8 +266,7 @@ class Inbox(Screen): def archive(self, data_index, instance, *args): """Archive inbox mail from inbox listing""" sqlExecute( - "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( - data_index)) + "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", data_index) self.ids.ml.remove_widget(instance.parent.parent) self.update_trash() @@ -601,11 +599,11 @@ class DropDownWidget(BoxLayout): fromAddress, subject, message, - str(state.send_draft_mail)) + 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 + # state.detailPageType = '' + # state.send_draft_mail = None else: from addresses import addBMIfNotPresent toAddress = addBMIfNotPresent(toAddress) @@ -645,6 +643,12 @@ class DropDownWidget(BoxLayout): state.check_sent_acc = fromAddress state.msg_counter_objs = self.parent.parent.parent.parent\ .parent.parent.children[2].children[0].ids + if state.detailPageType == 'draft' \ + and state.send_draft_mail: + state.draft_count = str(int(state.draft_count) - 1) + state.msg_counter_objs.draft_cnt.badge_text = state.draft_count + state.detailPageType = '' + state.send_draft_mail = None # self.parent.parent.screens[0].ids.ml.clear_widgets() # self.parent.parent.screens[0].loadMessagelist(state.association) self.parent.parent.screens[3].update_sent_messagelist() @@ -681,7 +685,7 @@ class DropDownWidget(BoxLayout): msg_dialog.open() @staticmethod - def callback_for_menu_items(text_item): + def callback_for_menu_items(text_item, *arg): """Callback of alert box""" toast(text_item) @@ -1068,7 +1072,7 @@ class Sent(Screen): state.all_count = str(int(state.all_count) - 1) sqlExecute( "UPDATE sent SET folder = 'trash'" - " WHERE ackdata = ?;", str(data_index)) + " WHERE ackdata = ?;", data_index) self.ids.ml.remove_widget(instance.parent.parent) toast('Deleted') self.update_trash() @@ -1077,7 +1081,7 @@ class Sent(Screen): """Archive sent mail from sent mail listing""" sqlExecute( "UPDATE sent SET folder = 'trash'" - " WHERE ackdata = ?;", str(data_index)) + " WHERE ackdata = ?;", data_index) self.ids.ml.remove_widget(instance.parent.parent) self.update_trash() @@ -1099,7 +1103,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): @@ -1214,7 +1218,7 @@ class Trash(Screen): 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() @@ -1225,11 +1229,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( @@ -1956,7 +1958,7 @@ class MailDetail(Screen): 2].children[1].ids.search_field.text = '' sqlExecute( "UPDATE sent SET folder = 'trash' WHERE" - " ackdata = ?;", str(state.mail_id)) + " ackdata = ?;", state.mail_id) msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1) self.parent.screens[3].ids.ml.clear_widgets() @@ -1968,7 +1970,7 @@ class MailDetail(Screen): 1].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) @@ -1976,8 +1978,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) @@ -1993,8 +1994,8 @@ class MailDetail(Screen): int(state.all_count) - 1) state.trash_count = str(int(state.trash_count) + 1) state.all_count = str(int(state.all_count) - 1) - self.parent.screens[4].ids.ml.clear_widgets() - self.parent.screens[4].init_ui(dt=0) + 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) Clock.schedule_once(self.callback_for_delete, 4) @@ -2012,7 +2013,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] @@ -2485,12 +2486,10 @@ class Allmails(Screen): """Delete inbox mail from all mail listing""" if folder == 'inbox': sqlExecute( - "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", str( - unique_id)) + "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", unique_id) else: sqlExecute( - "UPDATE sent SET folder = 'trash' WHERE ackdata = ?;", str( - unique_id)) + "UPDATE sent SET folder = 'trash' WHERE ackdata = ?;", unique_id) self.ids.ml.remove_widget(instance.parent.parent) try: msg_count_objs = self.parent.parent.parent.parent.parent.children[ From 6d1ecb7d0c7cb094f60bfc133d501d547af6a217 Mon Sep 17 00:00:00 2001 From: navjot Date: Wed, 18 Dec 2019 21:47:07 +0530 Subject: [PATCH 18/54] worked on kivy fixes part 3 --- src/bitmessagekivy/kivy_helper_search.py | 2 +- src/bitmessagekivy/main.kv | 42 +++++++++++------------- src/bitmessagekivy/mpybit.py | 20 +++++------ 3 files changed, 30 insertions(+), 34 deletions(-) diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 7e205543..48e77cb2 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -20,7 +20,7 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w sqlStatementBase = '''SELECT label, address From addressbook ''' else: sqlStatementBase = ( - '''SELECT folder, toaddress, message, fromaddress, subject,''' + '''SELECT folder, msgid, toaddress, message, fromaddress, subject,''' ''' received, read FROM inbox ''') sqlStatementParts = [] diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index b360a534..83183084 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -25,7 +25,8 @@ #:set color_font (0.957, 0.890, 0.843, 1) # off white : - icon: 'checkbox-blank-circle' + font_style: 'Body1' + theme_text_color: 'Secondary' : 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' @@ -545,12 +547,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' -: - name: 'add_sucess' - Label: - text: 'Successfully created a new bit address' - color: 0,0,0,1 - : name: 'set' ScrollView: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index bab578de..22474819 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -45,7 +45,8 @@ from kivymd.uix.list import ( ILeftBodyTouch, IRightBodyTouch, TwoLineAvatarIconListItem, - TwoLineListItem + TwoLineListItem, + OneLineIconListItem ) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, @@ -873,12 +874,6 @@ class Random(Screen): self.ids.label.text = '' -class AddressSuccessful(Screen): - """Getting Address Detail.""" - - pass - - class Sent(Screen): """Sent Screen uses screen to show widgets of screens""" queryreturn = ListProperty() @@ -1439,8 +1434,8 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.scr_mngr.transition.direction = 'right' self.root.ids.scr_mngr.transition.bind(on_complete=self.reset) return True - elif key == 13: - if state.search_screen == 'inbox' and state.searcing_text: + elif key == 13 and state.searcing_text: + if state.search_screen == 'inbox': self.root.ids.sc1.children[1].active = True Clock.schedule_once(self.search_callback, 0.5) elif state.search_screen == 'addressbook': @@ -1930,7 +1925,7 @@ class MailDetail(Screen): elif state.detailPageType == 'inbox': data = sqlQuery( "select toaddress, fromaddress, subject, message from inbox" - " where msgid = ?;", str(state.mail_id)) + " where msgid = ?;", state.mail_id) self.assign_mail_details(data) state.kivyapp.set_mail_detail_header() @@ -2589,3 +2584,8 @@ class LoadingPopup(Popup): def dismiss_popup(self, dt): """Dismiss popups""" self.dismiss() + + +class AddressDropdown(OneLineIconListItem): + """AddressDropdown showns all the addresses""" + pass \ No newline at end of file From e21e2a785459b2f88ccd7887b686dad5d02c1fc1 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Tue, 17 Dec 2019 13:06:43 +0530 Subject: [PATCH 19/54] Solved issues bytes in the protocal for checkIPAddress --- src/class_sqlThread.py | 13 +++++++++++++ src/helper_sql.py | 1 - src/protocol.py | 25 +++++++++++-------------- src/storage/sqlite.py | 7 +++++++ 4 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index 59cbe976..d0d8a001 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -572,10 +572,23 @@ 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.' diff --git a/src/helper_sql.py b/src/helper_sql.py index ebfe0450..a13747e2 100644 --- a/src/helper_sql.py +++ b/src/helper_sql.py @@ -29,7 +29,6 @@ sqlLock = threading.Lock() def sqlQuery(sqlStatement, *args): """ Query sqlite and return results - :param str sqlStatement: SQL statement string :param list args: SQL query parameters :rtype: list diff --git a/src/protocol.py b/src/protocol.py index a7c04d30..246ee8ad 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -142,16 +142,14 @@ def network_group(host): def checkIPAddress(host, private=False): - """ - Returns hostStandardFormat if it is a valid IP address, - otherwise returns False - """ - if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': + + """Returns hostStandardFormat if it is a valid IP address, otherwise returns False""" + if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape'): hostStandardFormat = socket.inet_ntop(socket.AF_INET, host[12:]) return checkIPv4Address(host[12:], hostStandardFormat, private) - 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 - hostStandardFormat = base64.b32encode(host[6:]).lower() + ".onion" + hostStandardFormat = base64.b32encode(host[6:]) + ".onion".encode() if private: return False return hostStandardFormat @@ -168,22 +166,21 @@ def checkIPAddress(host, private=False): def checkIPv4Address(host, hostStandardFormat, private=False): - """ - Returns hostStandardFormat if it is an IPv4 address, - otherwise returns False - """ - if host[0] == '\x7F': # 127/8 + + """Returns hostStandardFormat if it is an IPv4 address, otherwise returns False""" + + if host[0] == '\x7F'.encode('raw_unicode_escape'): # 127/8 if not private: logger.debug( 'Ignoring IP address in loopback range: %s', hostStandardFormat) return hostStandardFormat if private else False - if host[0] == '\x0A': # 10/8 + if host[0] == '\x0A'.encode('raw_unicode_escape'): # 10/8 if not private: logger.debug( 'Ignoring IP address in private range: %s', hostStandardFormat) return hostStandardFormat if private else False - if host[0:2] == '\xC0\xA8': # 192.168/16 + if host[0:2] == '\xC0\xA8'.encode('raw_unicode_escape'): # 192.168/16 if not private: logger.debug( 'Ignoring IP address in private range: %s', hostStandardFormat) diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 8b69ad1b..3eec3be6 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -28,6 +28,7 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors self.lock = RLock() def __contains__(self, hash_): + print('----------contains------------------') with self.lock: if hash_ in self._objects: return True @@ -38,6 +39,7 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors return True def __getitem__(self, hash_): + print('----------__getitem__------------------') with self.lock: if hash_ in self._inventory: return self._inventory[hash_] @@ -49,25 +51,30 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors return InventoryItem(*rows[0]) def __setitem__(self, hash_, value): + print('----------__setitem__------------------') with self.lock: value = InventoryItem(*value) self._inventory[hash_] = value self._objects[hash_] = value.stream def __delitem__(self, hash_): + print('----------__delitem__------------------') raise NotImplementedError def __iter__(self): + print('----------__iter__------------------') with self.lock: hashes = self._inventory.keys()[:] hashes += (x for x, in sqlQuery('SELECT hash FROM inventory')) return hashes.__iter__() def __len__(self): + print('----------__len__------------------') with self.lock: return len(self._inventory) + sqlQuery('SELECT count(*) FROM inventory')[0][0] def by_type_and_tag(self, objectType, tag): + print('----------by_type_and_tag------------------') with self.lock: values = [value for value in self._inventory.values() if value.type == objectType and value.tag == tag] values += (InventoryItem(*value) for value in sqlQuery( From 4dea6d5ced8e30bc05a4f10ec130529c3be8b43f Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 23 Dec 2019 19:47:23 +0530 Subject: [PATCH 20/54] mpybit py3 fixes --- src/bitmessagekivy/identiconGeneration.py | 10 ------ src/bitmessagekivy/kivy_helper_search.py | 23 +++++++----- src/bitmessagekivy/mpybit.py | 43 +++++++++-------------- src/bitmessagekivy/uikivysignaler.py | 12 ++++--- 4 files changed, 38 insertions(+), 50 deletions(-) diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index 42b5816a..25bd2254 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -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 diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 48e77cb2..83683d15 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -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) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 64bbfc67..790cdb97 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1,8 +1,8 @@ """ Bitmessage android(mobile) interface """ -# 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,9 +36,7 @@ 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 bitmessagekivy import kivy_helper_search from kivymd.uix.button import MDIconButton from kivymd.uix.dialog import MDDialog from kivymd.uix.label import MDLabel @@ -48,7 +46,6 @@ from kivymd.uix.list import ( IRightBodyTouch, TwoLineAvatarIconListItem, TwoLineListItem, - OneLineIconListItem ) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, @@ -525,7 +522,7 @@ class AddressBook(Screen): 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 @@ -541,7 +538,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): @@ -568,7 +564,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() @@ -579,7 +574,7 @@ class DropDownWidget(BoxLayout): subject = self.ids.subject.text.strip() message = self.ids.subject.text.strip() encoding = 3 - print ("message: ", self.ids.body.text) + print("message: ", self.ids.body.text) sendMessageToPeople = True if sendMessageToPeople: if toAddress != '' and subject and message: @@ -606,12 +601,11 @@ class DropDownWidget(BoxLayout): 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") + print("streamNumber > 1 or streamNumber == 0") if statusIconColor == 'red': - print ("shared.statusIconColor == 'red'") + print("shared.statusIconColor == 'red'") stealthLevel = BMConfigParser().safeGetInt( 'bitmessagesettings', 'ackstealthlevel') from helper_ackPayload import genAckPayload @@ -652,7 +646,7 @@ class DropDownWidget(BoxLayout): # self.parent.parent.screens[16].add_widget(Allmails()) Clock.schedule_once(self.callback_for_msgsend, 3) queues.workerQueue.put(('sendmessage', toAddress)) - print ("sqlExecute successfully #######################") + print("sqlExecute successfully #######################") state.in_composer = True return else: @@ -708,7 +702,7 @@ class MyTextInput(TextInput): starting_no = NumericProperty(3) suggestion_text = '' - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """Getting Text Input.""" super(MyTextInput, self).__init__(**kwargs) @@ -802,6 +796,7 @@ class NetworkStat(Screen): class ContentNavigationDrawer(Navigatorss): """Navigate Content Drawer""" + # pylint: disable=too-many-arguments pass @@ -1283,8 +1278,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')) self.nav_drawer = Navigatorss() @@ -1385,7 +1378,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods if not os.path.exists(directory): os.makedirs(directory) except OSError: - print ('Error: Creating directory. ' + directory) + print('Error: Creating directory. ' + directory) @staticmethod def get_default_image(): @@ -1586,7 +1579,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods @staticmethod def on_stop(): """On stop methos is used for stoping the runing script""" - print ("*******************EXITING FROM APPLICATION*******************") + print("*******************EXITING FROM APPLICATION*******************") import shutdown shutdown.doCleanShutdown() @@ -1699,7 +1692,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) @@ -1714,7 +1707,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.sc17.add_widget(Allmails()) 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 @@ -2328,9 +2321,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() @@ -2366,7 +2357,7 @@ class Allmails(Screen): def init_ui(self, dt=0): """Clock Schdule for method all mails""" self.loadMessagelist() - print (dt) + print(dt) def loadMessagelist(self): """Load Inbox, Sent anf Draft list of messages.""" diff --git a/src/bitmessagekivy/uikivysignaler.py b/src/bitmessagekivy/uikivysignaler.py index cb9473e2..aac45fd5 100644 --- a/src/bitmessagekivy/uikivysignaler.py +++ b/src/bitmessagekivy/uikivysignaler.py @@ -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) From 0de9e3841523368ecf100320fb811b610938c253 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 24 Dec 2019 19:32:37 +0530 Subject: [PATCH 21/54] python3 fixes --- src/addresses.py | 14 ++++--- src/api.py | 65 +++++++++++++++++--------------- src/bitmessagecurses/__init__.py | 8 ++-- src/bitmessagemain.py | 42 ++++++++++++--------- src/bmconfigparser.py | 26 ++++++++----- src/build_osx.py | 10 ++++- 6 files changed, 95 insertions(+), 70 deletions(-) diff --git a/src/addresses.py b/src/addresses.py index 50602c5a..e58d06de 100644 --- a/src/addresses.py +++ b/src/addresses.py @@ -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: diff --git a/src/api.py b/src/api.py index f9d0a518..cceff623 100644 --- a/src/api.py +++ b/src/api.py @@ -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-2019 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 @@ -58,6 +55,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 +148,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 +172,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 +250,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 +275,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data = '{"addresses":[' for addressInKeysFile in BMConfigParser().addresses(): - status, addressVersionNumber, streamNumber, hash01 = decodeAddress( # pylint: disable=unused-variable + # pylint: disable=unused-variable + status, addressVersionNumber, streamNumber, hash01 = decodeAddress( addressInKeysFile) if len(data) > 20: data += ',' @@ -485,7 +486,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 +538,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 +609,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): label = str_chan + ' ' + passphrase except BaseException: label = str_chan + ' ' + repr(passphrase) - - status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( # pylint: disable=unused-variable + # pylint: disable=unused-variable + status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress) queues.apiAddressGeneratorReturnQueue.queue.clear() @@ -632,7 +635,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 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( @@ -654,7 +658,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): 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 +671,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 +699,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 +758,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 +787,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( @@ -1157,7 +1162,7 @@ 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 @@ -1206,7 +1211,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 +1229,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 +1242,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 +1259,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 @@ -1279,7 +1284,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 +1330,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()) diff --git a/src/bitmessagecurses/__init__.py b/src/bitmessagecurses/__init__.py index 80dc3f14..4b893852 100644 --- a/src/bitmessagecurses/__init__.py +++ b/src/bitmessagecurses/__init__.py @@ -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__ diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index bbed1741..bc78b96f 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -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 ) @@ -156,11 +156,11 @@ def signal_handler(signum, frame): if shared.thisapp.daemon or not state.enableGUI: shutdown.doCleanShutdown() else: - print ('# Thread: {}({})'.format(thread.name, thread.ident)) + print('# Thread: {}({})'.format(thread.name, thread.ident)) for filename, lineno, name, line in traceback.extract_stack(frame): - print ("File: '{}', line {}, in {}" .format(filename, lineno, name)) + print("File: '{}', line {}, in {}" .format(filename, lineno, name)) if line: - print (' {}'.format(line.strip())) + print(' {}'.format(line.strip())) print('Unfortunately you cannot use Ctrl+C when running the UI \ because the UI captures the signal.') @@ -189,8 +189,9 @@ class Main(object): 'Started proxy config plugin %s in %s sec', proxy_type, time.time() - proxyconfig_start) - def start(self): # pylint: disable=too-many-statements, too-many-branches, too-many-locals + def start(self): """Start main application""" + # pylint: disable=too-many-statements, too-many-branches, too-many-locals _fixSocket() config = BMConfigParser() @@ -218,7 +219,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 @@ -234,7 +236,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(): @@ -281,7 +284,6 @@ class Main(object): readKnownNodes() - # Not needed if objproc is disabled if state.enableObjProc: @@ -340,7 +342,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 @@ -405,7 +408,8 @@ class Main(object): if (state.testmode and time.time() - state.last_api_response >= 30): self.stop() elif not state.enableGUI: - from tests import core as test_core # pylint: disable=relative-import + # pylint: disable=relative-import + from tests import core as test_core test_core_result = test_core.run(self) state.enableGUI = True self.stop() @@ -429,13 +433,14 @@ class Main(object): while True: time.sleep(1) - os._exit(0) # pylint: disable=protected-access + os._exit(0) # pylint: disable=protected-access except AttributeError: # fork not implemented pass else: parentPid = os.getpid() - shared.thisapp.lock() # relock + # relock + shared.thisapp.lock() os.umask(0) try: @@ -450,14 +455,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'): @@ -480,7 +487,6 @@ class Main(object): # signal.signal(signal.SIGINT, signal.SIG_DFL) @staticmethod - def usage(): """Displaying the usages""" print('Usage: ' + sys.argv[0] + ' [OPTIONS]') diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 150333ec..3293c5b3 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -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,24 +85,26 @@ 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 + # Used in the python2.7 # return self.getboolean(section, field) - #Used in the python3.5.2 + # Used in the python3.5.2 return config.getboolean(section, field) except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return False def safeGetInt(self, section, field, default=0): + """Return value as integer, default on exceptions, + 0 if default missing""" config = configparser.ConfigParser() try: - #Used in the python2.7 + # Used in the python2.7 # return self.getint(section, field) - #Used in the python3.5.2 + # Used in the python3.5.2 return config.getint(section, field) except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): @@ -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 diff --git a/src/build_osx.py b/src/build_osx.py index 7ab74dc2..6618d5da 100644 --- a/src/build_osx.py +++ b/src/build_osx.py @@ -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( From ca6a56fcb9af1a3d9cc9e832ee7d54d0d371be75 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Wed, 25 Dec 2019 20:21:08 +0530 Subject: [PATCH 22/54] python3 formatting and indentation fixes --- src/class_addressGenerator.py | 29 +++++++++++++++++++---------- src/class_objectProcessor.py | 5 ++--- src/class_objectProcessorQueue.py | 24 ------------------------ src/class_singleCleaner.py | 9 +++++++-- src/class_singleWorker.py | 3 ++- src/class_smtpDeliver.py | 19 ++++++++++++------- src/class_sqlThread.py | 11 ++++++++--- src/debug.py | 2 +- 8 files changed, 51 insertions(+), 51 deletions(-) delete mode 100644 src/class_objectProcessorQueue.py diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index 8cd63099..1f60e051 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -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 @@ -140,7 +140,7 @@ class addressGenerator(StoppableThread): ripe = RIPEMD160Hash(sha.digest()).digest() if ( ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == - '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash + '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash ): break self.logger.info( @@ -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': diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 2c741661..298b12bf 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -152,9 +152,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.') diff --git a/src/class_objectProcessorQueue.py b/src/class_objectProcessorQueue.py deleted file mode 100644 index 24c24023..00000000 --- a/src/class_objectProcessorQueue.py +++ /dev/null @@ -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 diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index f5442837..3c905b22 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -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 diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 9f1d39bd..b5bf2e43 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -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 diff --git a/src/class_smtpDeliver.py b/src/class_smtpDeliver.py index 58cd4631..6186f3ac 100644 --- a/src/class_smtpDeliver.py +++ b/src/class_smtpDeliver.py @@ -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': diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index d0d8a001..5de53b27 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -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.') @@ -578,9 +579,13 @@ class sqlThread(threading.Thread): # 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 ''' + 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: + except(IndexError, TypeError): pass try: self.cur.execute(item, parameters) diff --git a/src/debug.py b/src/debug.py index 685844ab..99994d22 100644 --- a/src/debug.py +++ b/src/debug.py @@ -151,7 +151,7 @@ def resetLogging(): try: preconfigured, msg = configureLogging() if msg: - logger.log(logging.WARNING if preconfigured else logging.INFO, msg) + logger.log(logging.WARNING if preconfigured else logging.INFO, msg) except: pass From 4ada9f68b3b95b0e4f801d3830bf39564dd098ab Mon Sep 17 00:00:00 2001 From: navjot Date: Thu, 26 Dec 2019 21:26:04 +0530 Subject: [PATCH 23/54] Kivy fixes part 4 --- src/bitmessagekivy/kivy_helper_search.py | 2 +- src/bitmessagekivy/main.kv | 42 ++++---- src/bitmessagekivy/mpybit.py | 117 +++++++++++++---------- src/class_sqlThread.py | 17 ---- src/state.py | 45 +++------ 5 files changed, 103 insertions(+), 120 deletions(-) diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 83683d15..c05e69d4 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -69,4 +69,4 @@ def search_sql( start_indx, end_indx) # elif folder == "addressbook": # sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx) - return sqlQuery(sqlStatementBase, sqlArguments) + return sqlQuery(sqlStatementBase, sqlArguments) \ No newline at end of file diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index b360a534..83183084 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -25,7 +25,8 @@ #:set color_font (0.957, 0.890, 0.843, 1) # off white : - icon: 'checkbox-blank-circle' + font_style: 'Body1' + theme_text_color: 'Secondary' : 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' @@ -545,12 +547,6 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' -: - name: 'add_sucess' - Label: - text: 'Successfully created a new bit address' - color: 0,0,0,1 - : name: 'set' ScrollView: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 790cdb97..5b03ffd8 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1,5 +1,6 @@ """ -Bitmessage android(mobile) interface +src/bitmessagekivy/mpybit.py +================================= """ # pylint: disable=import-error, no-name-in-module, too-many-lines # pylint: disable=too-few-public-methods, unused-argument, too-many-ancestors @@ -46,6 +47,7 @@ from kivymd.uix.list import ( IRightBodyTouch, TwoLineAvatarIconListItem, TwoLineListItem, + OneLineIconListItem, ) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, @@ -57,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) @@ -97,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 @@ -300,13 +303,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) @@ -316,9 +319,7 @@ 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)] if self.addresses_list: @@ -403,9 +404,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 @@ -519,8 +518,8 @@ class AddressBook(Screen): "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 = duplicate-bases pass @@ -528,6 +527,7 @@ class SelectableRecycleBoxLayout( class SelectableLabel(RecycleDataViewBehavior, Label): """Add selection support to the Label""" + index = None selected = BooleanProperty(False) selectable = BooleanProperty(True) @@ -556,7 +556,8 @@ class SelectableLabel(RecycleDataViewBehavior, Label): class RV(RecycleView): """Recycling View""" - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """Recycling Method""" super(RV, self).__init__(**kwargs) @@ -578,6 +579,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': @@ -596,7 +598,10 @@ 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 ( @@ -696,6 +701,7 @@ class DropDownWidget(BoxLayout): class MyTextInput(TextInput): """Takes the text input in the field""" + txt_input = ObjectProperty() flt_list = ObjectProperty() word_list = ListProperty() @@ -751,12 +757,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 @@ -867,7 +875,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(): @@ -880,7 +888,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 @@ -918,7 +926,7 @@ class Sent(Screen): self.queryreturn = kivy_helper_search.search_sql( xAddress, self.account, - "sent", + 'sent', where, what, False, @@ -1084,7 +1092,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): @@ -1093,7 +1101,7 @@ 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] @@ -1199,7 +1207,7 @@ class Trash(Screen): 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() @@ -1210,11 +1218,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( @@ -1225,6 +1231,7 @@ class Trash(Screen): class Page(Screen): """Page Screen show widgets of page""" + pass @@ -1244,6 +1251,7 @@ class Create(Screen): class Setting(Screen): """Setting the Screen components""" + pass @@ -1320,7 +1328,7 @@ 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) @@ -1827,8 +1835,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': @@ -1842,22 +1849,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): @@ -1948,7 +1959,7 @@ class MailDetail(Screen): 1].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) @@ -1956,8 +1967,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) @@ -1992,7 +2002,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] @@ -2131,7 +2141,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 @@ -2161,12 +2171,12 @@ 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.draftDataQuery(xAddress, where, what) if state.msg_counter_objs: @@ -2273,8 +2283,7 @@ class Draft(Screen): 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 @@ -2298,7 +2307,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') @@ -2334,7 +2345,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 @@ -2347,7 +2358,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(): @@ -2360,7 +2371,7 @@ 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.allMessageQuery(0, 20) if self.all_mails: @@ -2538,16 +2549,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 @@ -2562,3 +2576,8 @@ class LoadingPopup(Popup): def dismiss_popup(self, dt): """Dismiss popups""" self.dismiss() + + +class AddressDropdown(OneLineIconListItem): + """AddressDropdown showns all the addresses""" + pass \ No newline at end of file diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index 5de53b27..d7bb158f 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -573,27 +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): - 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.' diff --git a/src/state.py b/src/state.py index 038e0e0a..54251270 100644 --- a/src/state.py +++ b/src/state.py @@ -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 From 5a1b5e177fd3b4920c488539847bddc50271cb2d Mon Sep 17 00:00:00 2001 From: navjot Date: Mon, 30 Dec 2019 13:35:07 +0530 Subject: [PATCH 24/54] kivy fixes part 5 --- src/bitmessagekivy/main.kv | 121 +++++++++++++++++++++++++++++------ src/bitmessagekivy/mpybit.py | 86 ++++++++++++++----------- 2 files changed, 148 insertions(+), 59 deletions(-) diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 83183084..67f24e01 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -208,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 @@ -231,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: @@ -244,21 +263,50 @@ NavigationLayout: : name: 'trash' - ScrollView: - id: scroll_y - do_scroll_x: False - 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: + id: scroll_y + do_scroll_x: False + MDList: + id: ml Loader: ComposerButton: : name: 'draft' - ScrollView: - id: scroll_y - do_scroll_x: False - MDList: - id: ml + 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 + MDList: + id: ml ComposerButton: : @@ -295,12 +343,25 @@ NavigationLayout: # MDList: # id: ml BoxLayout: - orientation:'vertical' - ScrollView: - id: scroll_y - do_scroll_x: False - MDList: - id: ml + 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 + MDList: + id: ml Loader: ComposerButton: @@ -620,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 @@ -635,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: @@ -796,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) @@ -1027,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 @@ -1107,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 diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 5b03ffd8..df0e1c26 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -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') @@ -322,7 +324,9 @@ class MyAddress(Screen): 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) @@ -393,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() @@ -435,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) @@ -514,6 +520,8 @@ 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)) @@ -673,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() @@ -896,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({ @@ -1059,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) @@ -1105,8 +1118,10 @@ class 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() @@ -1197,11 +1212,12 @@ 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) @@ -1264,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 @@ -1333,7 +1350,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods 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() @@ -1637,30 +1654,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 @@ -1711,8 +1728,12 @@ 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': - self.root.ids.sc17.clear_widgets() - self.root.ids.sc17.add_widget(Allmails()) + 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: @@ -1754,26 +1775,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""" @@ -1944,7 +1945,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) @@ -1954,9 +1955,9 @@ 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 = ?;", state.mail_id) @@ -1985,8 +1986,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): @@ -2178,11 +2179,13 @@ class Draft(Screen): def loadDraft(self, where="", what=""): """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() @@ -2279,8 +2282,7 @@ 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.children[2].children[0].ids) @@ -2293,6 +2295,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') @@ -2373,8 +2377,10 @@ class Allmails(Screen): def loadMessagelist(self): """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( @@ -2504,6 +2510,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) From 256ca151abb6ad5c3b203978e87cccb0637ed1b8 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 30 Dec 2019 17:40:02 +0530 Subject: [PATCH 25/54] py3 fixes --- src/api.py | 10 +- src/bitmessagecli.py | 614 +++++++++++++++++------------------ src/class_objectProcessor.py | 6 +- src/class_smtpServer.py | 3 +- src/depends.py | 4 +- src/helper_ackPayload.py | 6 +- src/helper_bitcoin.py | 1 + src/helper_search.py | 4 +- src/helper_sent.py | 2 +- src/helper_sql.py | 2 +- src/helper_startup.py | 3 +- src/inventory.py | 2 +- src/l10n.py | 12 +- src/openclpow.py | 2 +- src/proofofwork.py | 4 +- src/protocol.py | 16 +- src/queues.py | 3 +- src/semaphores.py | 2 +- src/shared.py | 3 +- src/singleinstance.py | 6 +- src/state.py | 2 +- src/tr.py | 14 +- src/upnp.py | 36 +- 23 files changed, 371 insertions(+), 386 deletions(-) diff --git a/src/api.py b/src/api.py index cceff623..6c1191a4 100644 --- a/src/api.py +++ b/src/api.py @@ -37,6 +37,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]' @@ -275,7 +276,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): data = '{"addresses":[' for addressInKeysFile in BMConfigParser().addresses(): - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, hash01 = decodeAddress( addressInKeysFile) if len(data) > 20: @@ -609,7 +609,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): label = str_chan + ' ' + passphrase except BaseException: label = str_chan + ' ' + repr(passphrase) - # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress) @@ -634,7 +633,6 @@ 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) address = addBMIfNotPresent(address) @@ -657,7 +655,6 @@ 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) address = addBMIfNotPresent(address) @@ -878,7 +875,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: @@ -988,7 +985,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) @@ -1165,7 +1161,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): def ListSubscriptions(self, params): """Handle a request to list susbcriptions""" - # pylint: disable=unused-variable queryreturn = sqlQuery( "SELECT label, address, enabled FROM subscriptions") data = {'subscriptions': []} @@ -1271,7 +1266,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler): pubkeyReadPosition += 8 else: pubkeyReadPosition += 4 - # pylint: disable=unused-variable addressVersion, addressVersionLength = decodeVarint( payload[pubkeyReadPosition:pubkeyReadPosition + 10]) pubkeyReadPosition += addressVersionLength diff --git a/src/bitmessagecli.py b/src/bitmessagecli.py index 02fed7e9..ff8fb290 100644 --- a/src/bitmessagecli.py +++ b/src/bitmessagecli.py @@ -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 ' 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(' 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: diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 298b12bf..19f4861c 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -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') @@ -644,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( diff --git a/src/class_smtpServer.py b/src/class_smtpServer.py index cdf867a9..013420cd 100644 --- a/src/class_smtpServer.py +++ b/src/class_smtpServer.py @@ -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: diff --git a/src/depends.py b/src/depends.py index 8182fca3..ead33cae 100755 --- a/src/depends.py +++ b/src/depends.py @@ -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.') diff --git a/src/helper_ackPayload.py b/src/helper_ackPayload.py index dcce3153..2f89d540 100644 --- a/src/helper_ackPayload.py +++ b/src/helper_ackPayload.py @@ -22,7 +22,7 @@ def genAckPayload(streamNumber=1, stealthLevel=0): - level 1: a getpubkey request for a (random) dummy key hash - level 2: a standard message, encrypted to a random pubkey """ - if stealthLevel == 2: # Generate privacy-enhanced payload + if stealthLevel == 2: # Generate privacy-enhanced payload # Generate a dummy privkey and derive the pubkey dummyPubKeyHex = highlevelcrypto.privToPub( hexlify(helper_random.randomBytes(32))) @@ -35,12 +35,12 @@ def genAckPayload(streamNumber=1, stealthLevel=0): acktype = 2 # message version = 1 - elif stealthLevel == 1: # Basic privacy payload (random getpubkey) + elif stealthLevel == 1: # Basic privacy payload (random getpubkey) ackdata = helper_random.randomBytes(32) acktype = 0 # getpubkey version = 4 - else: # Minimum viable payload (non stealth) + else: # Minimum viable payload (non stealth) ackdata = helper_random.randomBytes(32) acktype = 2 # message version = 1 diff --git a/src/helper_bitcoin.py b/src/helper_bitcoin.py index 695bdbcf..d4f1d105 100644 --- a/src/helper_bitcoin.py +++ b/src/helper_bitcoin.py @@ -53,3 +53,4 @@ def calculateTestnetAddressFromPubkey(pubkey): numberOfZeroBytesOnBinaryBitcoinAddress += 1 binaryBitcoinAddress = binaryBitcoinAddress[1:] base58encoded = arithmetic.changebase(binaryBitcoinAddress, 256, 58) + return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded diff --git a/src/helper_search.py b/src/helper_search.py index 69acec43..2384ff01 100644 --- a/src/helper_search.py +++ b/src/helper_search.py @@ -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(): diff --git a/src/helper_sent.py b/src/helper_sent.py index 5a345fe7..47fc5bb4 100644 --- a/src/helper_sent.py +++ b/src/helper_sent.py @@ -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""" diff --git a/src/helper_sql.py b/src/helper_sql.py index a13747e2..f848ee24 100644 --- a/src/helper_sql.py +++ b/src/helper_sql.py @@ -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): diff --git a/src/helper_startup.py b/src/helper_startup.py index 8434f8ff..bc0ede92 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -4,7 +4,6 @@ Startup operations. # pylint: disable=too-many-branches,too-many-statements from __future__ import print_function -import configparser import os import platform import sys @@ -21,6 +20,7 @@ from bmconfigparser import BMConfigParser # the config files to stay in the application data folder. StoreConfigFilesInSameDirectoryAsProgramByDefault = False + def loadConfig(): """Load the config""" config = BMConfigParser() @@ -116,7 +116,6 @@ def loadConfig(): updateConfig() - def updateConfig(): """Save the config""" config = BMConfigParser() diff --git a/src/inventory.py b/src/inventory.py index 4b9ad226..fc06e455 100644 --- a/src/inventory.py +++ b/src/inventory.py @@ -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 diff --git a/src/l10n.py b/src/l10n.py index a3237cb0..bf727244 100644 --- a/src/l10n.py +++ b/src/l10n.py @@ -64,25 +64,25 @@ else: # comprehensive decoding tests if time_format != DEFAULT_TIME_FORMAT: try: - #Check day names + # Check day names new_time_format = time_format import sys if sys.version_info >= (3, 0, 0) and time_format == '%%c': time_format = '%c' for i in range(7): - #this work for python2.7 + # this work for python2.7 # unicode(time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0)), encoding) - #this code for the python3 + # this code for the python3 (time.strftime(time_format, (0, 0, 0, 0, 0, 0, i, 0, 0))).encode() - #Check month names + # Check month names for i in range(1, 13): # unicode(time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0)), encoding) (time.strftime(time_format, (0, i, 0, 0, 0, 0, 0, 0, 0))).encode() - #Check AM/PM + # Check AM/PM (time.strftime(time_format, (0, 0, 0, 11, 0, 0, 0, 0, 0))).encode() (time.strftime(time_format, (0, 0, 0, 13, 0, 0, 0, 0, 0))).encode() - #Check DST + # Check DST (time.strftime(time_format, (0, 0, 0, 0, 0, 0, 0, 0, 1))).encode() except: diff --git a/src/openclpow.py b/src/openclpow.py index 717acc93..d90e55d1 100644 --- a/src/openclpow.py +++ b/src/openclpow.py @@ -119,4 +119,4 @@ if __name__ == "__main__": nonce = do_opencl_pow(initialHash.encode("hex"), target_) trialValue, = unpack( '>Q', hashlib.sha512(hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8]) - print ("{} - value {} < {}".format(nonce, trialValue, target_)) + print("{} - value {} < {}".format(nonce, trialValue, target_)) diff --git a/src/proofofwork.py b/src/proofofwork.py index 6fefb196..e79efc3b 100644 --- a/src/proofofwork.py +++ b/src/proofofwork.py @@ -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: diff --git a/src/protocol.py b/src/protocol.py index 246ee8ad..fba68fe3 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -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) @@ -198,15 +199,15 @@ def checkIPv6Address(host, hostStandardFormat, private=False): if host == ('\x00'.encode() * 15) + '\x01'.encode(): if not private: - logger.debug('Ignoring loopback address: {}'.format( hostStandardFormat)) + logger.debug('Ignoring loopback address: {}'.format(hostStandardFormat)) return False if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80: if not private: - logger.debug('Ignoring local address: {}'.format( hostStandardFormat)) + logger.debug('Ignoring local address: {}'.format(hostStandardFormat)) return hostStandardFormat if private else False if (ord(host[0:1]) & 0xfe) == 0xfc: if not private: - logger.debug('Ignoring unique local address: {}'.format( hostStandardFormat)) + logger.debug('Ignoring unique local address: {}'.format(hostStandardFormat)) return hostStandardFormat if private else False return False if private else hostStandardFormat @@ -325,7 +326,7 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= ) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. - #python3 need to check + # python3 need to check payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode() + pack('>L', 2130706433) # we have a separate extPort and incoming over clearnet @@ -338,11 +339,10 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= ): payload += pack('>H', extport) elif checkSocksIP(remoteHost) and server: # incoming connection over Tor - payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport'))) + payload += pack('>H', int(BMConfigParser().safeGet('bitmessagesettings', 'onionport'))) 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: @@ -374,7 +374,7 @@ def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''): payload += encodeVarint(len(inventoryVector)) payload += inventoryVector.encode() if type(payload) == bytes else inventoryVector payload += encodeVarint(len(errorText)) - payload += errorText.encode() if type(payload)== bytes else errorText + payload += errorText.encode() if type(payload) == bytes else errorText return CreatePacket('error', payload) diff --git a/src/queues.py b/src/queues.py index bce5eb32..6a76adb6 100644 --- a/src/queues.py +++ b/src/queues.py @@ -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 diff --git a/src/semaphores.py b/src/semaphores.py index 04120fe7..960d86a9 100644 --- a/src/semaphores.py +++ b/src/semaphores.py @@ -1,3 +1,3 @@ from threading import Semaphore -kivyuisignaler = Semaphore(0) \ No newline at end of file +kivyuisignaler = Semaphore(0) diff --git a/src/shared.py b/src/shared.py index d02578ce..98f47d19 100644 --- a/src/shared.py +++ b/src/shared.py @@ -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:] diff --git a/src/singleinstance.py b/src/singleinstance.py index 169613a3..2936e49b 100644 --- a/src/singleinstance.py +++ b/src/singleinstance.py @@ -75,7 +75,7 @@ class singleinstance(object): fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) self.lockPid = os.getpid() except IOError: - print ('Another instance of this application is already running') + print('Another instance of this application is already running') sys.exit(-1) else: pidLine = "%i\n" % self.lockPid @@ -95,10 +95,10 @@ 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") + print("Cleaning up lockfile") try: if sys.platform == 'win32': if hasattr(self, 'fd'): diff --git a/src/state.py b/src/state.py index 54251270..5207099f 100644 --- a/src/state.py +++ b/src/state.py @@ -109,4 +109,4 @@ availabe_credit = 0 in_sent_method = False -in_search_mode = False \ No newline at end of file +in_search_mode = False diff --git a/src/tr.py b/src/tr.py index ce8edc8e..f3498037 100644 --- a/src/tr.py +++ b/src/tr.py @@ -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)) @@ -25,7 +25,7 @@ class translateClass: return self.text -def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument +def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument return translateText(context, text, n) @@ -39,12 +39,12 @@ def translateText(context, text, n=None): try: from PyQt4 import QtCore, QtGui except Exception as err: - print ('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ + print('PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API\ .You can download PyQt from http://www.riverbankcomputing.com/software/pyqt/download\ or by searching Google for \'PyQt Download\'.\ If you want to run in daemon mode, see https://bitmessage.org/wiki/Daemon') - print ('Error message:', err) - os._exit(0) # pylint: disable=protected-access + print('Error message:', err) + os._exit(0) # pylint: disable=protected-access if n is None: return QtGui.QApplication.translate(context, text) diff --git a/src/upnp.py b/src/upnp.py index 9ef4c4e8..93753de3 100644 --- a/src/upnp.py +++ b/src/upnp.py @@ -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)) From 69eedf7bc2910dcba65b18893cc483f077082bd9 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 31 Dec 2019 18:22:56 +0530 Subject: [PATCH 26/54] network files fixes python3 --- src/network/__init__.py | 20 ++++++------- src/network/addrthread.py | 1 - src/network/advanceddispatcher.py | 3 +- src/network/announcethread.py | 12 ++++---- src/network/assemble.py | 2 +- src/network/asyncore_pollchoose.py | 10 ++++--- src/network/bmproto.py | 47 ++++++++++++++++-------------- src/network/connectionchooser.py | 2 +- src/network/connectionpool.py | 27 +++++++++-------- src/network/dandelion.py | 10 +++---- src/network/downloadthread.py | 3 +- src/network/http.py | 7 +++-- src/network/http_old.py | 3 ++ src/network/httpd.py | 6 ++-- src/network/https.py | 7 +++-- src/network/networkthread.py | 4 +-- src/network/randomtrackingdict.py | 8 ++--- src/network/tcp.py | 6 ++-- src/network/tls.py | 3 +- 19 files changed, 93 insertions(+), 88 deletions(-) diff --git a/src/network/__init__.py b/src/network/__init__.py index 77b80b5c..72865e87 100644 --- a/src/network/__init__.py +++ b/src/network/__init__.py @@ -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__ = [ diff --git a/src/network/addrthread.py b/src/network/addrthread.py index 861da3ef..c041695f 100644 --- a/src/network/addrthread.py +++ b/src/network/addrthread.py @@ -1,4 +1,3 @@ -# import queue as Queue """ Announce addresses as they are received from other hosts """ diff --git a/src/network/advanceddispatcher.py b/src/network/advanceddispatcher.py index a21b946f..2eb0e46d 100644 --- a/src/network/advanceddispatcher.py +++ b/src/network/advanceddispatcher.py @@ -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() diff --git a/src/network/announcethread.py b/src/network/announcethread.py index 938599d5..7929417e 100644 --- a/src/network/announcethread.py +++ b/src/network/announcethread.py @@ -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 @@ -32,17 +32,15 @@ class AnnounceThread(StoppableThread): @staticmethod def announceSelf(): """Announce our presence""" - for connection in [ udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]: + for connection in [udpSockets for udpSockets in BMConnectionPool().udpSockets.values()]: if not connection.announcing: continue 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])) - + # 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')), diff --git a/src/network/assemble.py b/src/network/assemble.py index 2d31914c..9ae853f7 100644 --- a/src/network/assemble.py +++ b/src/network/assemble.py @@ -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'' diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index 3f6e8ad0..43bebdcf 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -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 @@ -786,7 +788,7 @@ class dispatcher: def log_info(self, message, log_type='info'): """Conditionally print a message""" if log_type not in self.ignore_log_types: - print ('{}: {}'.format(log_type, message)) + print('{}: {}'.format(log_type, message)) def handle_read_event(self): """Handle a read event""" diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 12e26972..ad2260fa 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -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,30 +95,30 @@ 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 + # its shoule be in string self.command = self.command.rstrip('\x00'.encode('utf-8')) - global count,addr_version,addr_count,addr_verack - count+=1 + # pylint: disable=global-statement + global count, addr_version, addr_count, addr_verack + count += 1 if self.command == 'verack'.encode(): - addr_verack+=1 + addr_verack += 1 # print('the addr_verack count are -{}'.format(addr_verack)) if self.command == 'version'.encode(): - addr_version+=1 + addr_version += 1 # print('the addr_version count are -{}'.format(addr_version)) if self.command == 'addr'.encode(): - addr_count+=1 + addr_count += 1 # print('the addr_count count are -{}'.format(addr_count)) if self.magic != 0xE9BEB4D9: # skip 1 byte in order to sync - #in the advancedispatched and length commend's - #escape the 1 length + # in the advancedispatched and length commend's + # escape the 1 length self.set_state("bm_header", length=1) self.bm_proto_reset() logger.debug('Bad magic') @@ -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]: @@ -143,14 +144,14 @@ class BMProto(AdvancedDispatcher, ObjectTracker): "error".encode(), "version".encode(), "verack".encode()): logger.error( 'Received command {} before connection was fully' - ' established, ignoring'.format (self.command)) + ' established, ignoring'.format(self.command)) self.invalid = True if not self.invalid: try: command = self.command.decode() if self.command else self.command retval = getattr( - self, "bm_command_" +command)() + self, "bm_command_" + command)() except AttributeError: # unimplemented command logger.debug('unimplemented command %s', self.command) @@ -346,8 +347,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) @@ -359,7 +363,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): If we have them and some other conditions are fulfilled, append them to the write queue. """ - #32 an array bit long strings + # 32 an array bit long strings items = self.decode_payload_content("l32s") # skip? now = time.time() @@ -463,11 +467,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker): def bm_command_addr(self): # print('+++++++++++++++++++++++++++\ - # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') + # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') """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 +537,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 +571,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: @@ -625,7 +630,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if not protocol.checkSocksIP(self.destination.host): self.append_write_buf(protocol.assembleErrorMessage( errorText="Too many connections from your IP." - " Closing connection.", fatal=2)) + " Closing connection.", fatal=2)) logger.debug( 'Closed connection to {} because we are already connected' ' to that IP.'.format(self.destination)) @@ -660,10 +665,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""" diff --git a/src/network/connectionchooser.py b/src/network/connectionchooser.py index 0e090b62..bd5b3d7d 100644 --- a/src/network/connectionchooser.py +++ b/src/network/connectionchooser.py @@ -39,7 +39,7 @@ def chooseConnection(stream): # discovered peers are already filtered by allowed streams return getDiscoveredPeer() for _ in range(50): - peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()]) + peer = random.choice([key for key in knownnodes.knownNodes[stream].keys()]) try: peer_info = knownnodes.knownNodes[stream][peer] if peer_info.get('self'): diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index a9bbe2e7..4b9ab62b 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -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) + TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap) from network.udp import UDPSocket +from singleton import Singleton +from .node import Peer logger = logging.getLogger('default') @@ -78,8 +78,8 @@ class BMConnectionPool(object): `inboundConnections` and `outboundConnections` dicts """ inboundConnections = [inboundConnections for inboundConnections in self.inboundConnections.values()] - outboundConnections = [outboundConnections for outboundConnections in self.outboundConnections.values()] - return [ connections for connections in inboundConnections +outboundConnections] + outboundConnections = [outboundConnections for outboundConnections in self.outboundConnections.values()] + return [connections for connections in inboundConnections + outboundConnections] def establishedConnections(self): """Shortcut for list of connections having fullyEstablished == True""" @@ -292,7 +292,7 @@ class BMConnectionPool(object): except ValueError: Proxy.onion_proxy = None established = sum( - 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] + 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] if (c.connected and c.fullyEstablished)) pending = len(self.outboundConnections) - established if established < int(BMConfigParser().safeGet( @@ -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()] + # [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()] ): if not (i.accepting or i.connecting or i.connected): reaper.append(i) diff --git a/src/network/dandelion.py b/src/network/dandelion.py index 7e059f7f..ec9384e5 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -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 @@ -104,12 +104,12 @@ class Dandelion(): # pylint: disable=old-style-class self.stem.append(connection) for k in (k for k, v in iter(self.nodeMap.items()) if v is None): self.nodeMap[k] = connection - #The Purpose of adding this condition that if self - #hashMap is has any value + # The Purpose of adding this condition that if self + # hashMap is has any value # if not [hasmap for hasmap in self.hashMap.items()] ==[]: try: for k, v in { - k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) + k: v for k, v in iter([hasmap for hasmap in self.hashMap.items()]) if v.child is None }.items(): self.hashMap[k] = Stem( @@ -142,7 +142,7 @@ class Dandelion(): # pylint: disable=old-style-class ): self.nodeMap[k] = None for k, v in { - k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) + k: v for k, v in iter(iter([hasmap for hasmap in self.hashMap.items()])) if v.child == connection }.items(): self.hashMap[k] = Stem( diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index c4519bb4..6e1f9ca8 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -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() diff --git a/src/network/http.py b/src/network/http.py index fdfe8370..4a21b63e 100644 --- a/src/network/http.py +++ b/src/network/http.py @@ -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 diff --git a/src/network/http_old.py b/src/network/http_old.py index 64d09983..c46a5d09 100644 --- a/src/network/http_old.py +++ b/src/network/http_old.py @@ -1,3 +1,6 @@ +""" +src/network/http_old.py +""" import asyncore import socket import time diff --git a/src/network/httpd.py b/src/network/httpd.py index b69ffa99..1679f864 100644 --- a/src/network/httpd.py +++ b/src/network/httpd.py @@ -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: diff --git a/src/network/https.py b/src/network/https.py index a7b8b57c..fc944d97 100644 --- a/src/network/https.py +++ b/src/network/https.py @@ -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 diff --git a/src/network/networkthread.py b/src/network/networkthread.py index 34c94bf2..9b4ba1e5 100644 --- a/src/network/networkthread.py +++ b/src/network/networkthread.py @@ -19,12 +19,12 @@ class BMNetworkThread(StoppableThread): def stopThread(self): super(BMNetworkThread, self).stopThread() - for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]: + for i in [listeningSockets for listeningSockets in BMConnectionPool().listeningSockets.values()]: try: i.close() except: pass - for i in [ outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]: + for i in [outboundConnections for outboundConnections in BMConnectionPool().outboundConnections.values()]: try: i.close() except: diff --git a/src/network/randomtrackingdict.py b/src/network/randomtrackingdict.py index 16eb63e1..c5c460b4 100644 --- a/src/network/randomtrackingdict.py +++ b/src/network/randomtrackingdict.py @@ -140,20 +140,20 @@ if __name__ == '__main__': k = RandomTrackingDict() d = {} - print ("populating random tracking dict") + print("populating random tracking dict") a.append(time()) for i in range(50000): k[randString()] = True a.append(time()) - print ("done") + print("done") while k: retval = k.randomKeys(1000) if not retval: - print ("error getting random keys") + print("error getting random keys") try: k.randomKeys(100) - print( "bad") + print("bad") except KeyError: pass for i in retval: diff --git a/src/network/tcp.py b/src/network/tcp.py index c7f5aa01..7dff0122 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -77,7 +77,7 @@ class TCPConnection(BMProto, TLSDispatcher): self.connect(self.destination) logger.debug( 'Connecting to {}:{}'.format( - self.destination.host, self.destination.port)) + self.destination.host, self.destination.port)) try: self.local = ( protocol.checkIPAddress( @@ -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): @@ -370,7 +370,7 @@ class TCPServer(AdvancedDispatcher): """TCP connection server for Bitmessage protocol""" def __init__(self, host='127.0.0.1', port=8444): - if '_map' not in dir(self): + if '_map' not in dir(self): AdvancedDispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() diff --git a/src/network/tls.py b/src/network/tls.py index 479fe4de..08969227 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -1,7 +1,6 @@ """ SSL/TLS negotiation. """ - import logging import os import socket @@ -23,7 +22,7 @@ if sys.version_info >= (2, 7, 13): # in the future change to # ssl.PROTOCOL_TLS1.2 # Right now I am using the python3.5.2 and I faced the ssl for protocol due to this I - # have used try and catch + # have used try and catch try: sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member except AttributeError: From e436b8ecf63bb473c415fb156032aee03cdaf7f6 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 6 Jan 2020 16:44:13 +0530 Subject: [PATCH 27/54] commit after conflicts --- COPYING | 2 +- LICENSE | 2 +- checkdeps.py | 2 +- requirements.txt | 1 - src/api.py | 3 +- src/bitmessagekivy/mpybit.py | 1 + src/bitmessagemain.py | 20 +++--- src/bitmessageqt/about.ui | 2 +- src/bitmessageqt/dialogs.py | 2 +- src/bitmessageqt/settings.py | 111 +++++++++++++++++++------------- src/bitmessageqt/settings.ui | 6 +- src/bitmessageqt/support.py | 4 +- src/class_objectProcessor.py | 18 +++--- src/class_singleWorker.py | 4 +- src/helper_startup.py | 51 ++++++++++++--- src/network/assemble.py | 2 +- src/network/bmproto.py | 20 +++--- src/network/udp.py | 5 +- src/plugins/__init__.py | 7 ++ src/plugins/plugin.py | 27 ++++++-- src/plugins/proxyconfig_stem.py | 33 +++++++--- src/protocol.py | 11 ++-- src/storage/sqlite.py | 21 +++--- src/tests/core.py | 53 +++++++++------ 24 files changed, 262 insertions(+), 146 deletions(-) diff --git a/COPYING b/COPYING index 2e0ae6c1..078bf213 100644 --- a/COPYING +++ b/COPYING @@ -1,5 +1,5 @@ Copyright (c) 2012-2016 Jonathan Warren -Copyright (c) 2012-2019 The Bitmessage Developers +Copyright (c) 2012-2020 The Bitmessage Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/LICENSE b/LICENSE index 3be738c0..6bb86242 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) Copyright (c) 2012-2016 Jonathan Warren -Copyright (c) 2012-2019 The Bitmessage Developers +Copyright (c) 2012-2020 The Bitmessage Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/checkdeps.py b/checkdeps.py index 03782037..45dc2fc9 100755 --- a/checkdeps.py +++ b/checkdeps.py @@ -164,7 +164,7 @@ if (not compiler or prereqs) and OPSYS in PACKAGE_MANAGER: if not compiler: compilerToPackages() prereqToPackages() - if mandatory: + if prereqs and mandatory: sys.exit(1) else: print("All the dependencies satisfied, you can install PyBitmessage") diff --git a/requirements.txt b/requirements.txt index be429a9f..c55e5cf1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ python_prctl psutil pycrypto -stem diff --git a/src/api.py b/src/api.py index 6c1191a4..bfbe45fa 100644 --- a/src/api.py +++ b/src/api.py @@ -30,7 +30,8 @@ import queues import shared import shutdown import state -from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError + +from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError from bmconfigparser import BMConfigParser from debug import logger from helper_ackPayload import genAckPayload diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index df0e1c26..bcb7c511 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1303,6 +1303,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods def build(self): """Method builds the widget""" + print(os.path.join(os.path.dirname(__file__), 'main.kv')) main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) self.nav_drawer = Navigatorss() diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index bc78b96f..2a03858b 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -3,7 +3,7 @@ The PyBitmessage startup script """ # Copyright (c) 2012-2016 Jonathan Warren -# Copyright (c) 2012-2019 The Bitmessage developers +# Copyright (c) 2012-2020 The Bitmessage developers # Distributed under the MIT/X11 software license. See the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. @@ -32,7 +32,8 @@ from bmconfigparser import BMConfigParser # this should go before any threads from debug import logger from helper_startup import ( - isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections + isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections, + start_proxyconfig ) from inventory import Inventory from knownnodes import readKnownNodes @@ -188,10 +189,9 @@ class Main(object): logger.info( 'Started proxy config plugin %s in %s sec', proxy_type, time.time() - proxyconfig_start) - def start(self): """Start main application""" - # pylint: disable=too-many-statements, too-many-branches, too-many-locals + # pylint: disable=too-many-statements,too-many-branches,too-many-locals _fixSocket() config = BMConfigParser() @@ -268,11 +268,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( @@ -350,7 +349,7 @@ class Main(object): singleAPIThread.start() # start network components if networking is enabled if state.enableNetwork: - self.start_proxyconfig(config) + start_proxyconfig() BMConnectionPool() asyncoreThread = BMNetworkThread() asyncoreThread.daemon = True @@ -408,9 +407,8 @@ class Main(object): if (state.testmode and time.time() - state.last_api_response >= 30): self.stop() elif not state.enableGUI: - # pylint: disable=relative-import - from tests import core as test_core - test_core_result = test_core.run(self) + from tests import core as test_core # pylint: disable=relative-import + test_core_result = test_core.run() state.enableGUI = True self.stop() test_core.cleanup() diff --git a/src/bitmessageqt/about.ui b/src/bitmessageqt/about.ui index a912927a..7073bbd1 100644 --- a/src/bitmessageqt/about.ui +++ b/src/bitmessageqt/about.ui @@ -46,7 +46,7 @@ - <html><head/><body><p>Copyright © 2012-2016 Jonathan Warren<br/>Copyright © 2012-2019 The Bitmessage Developers</p></body></html> + <html><head/><body><p>Copyright © 2012-2016 Jonathan Warren<br/>Copyright © 2012-2020 The Bitmessage Developers</p></body></html> Qt::AlignLeft diff --git a/src/bitmessageqt/dialogs.py b/src/bitmessageqt/dialogs.py index b4bcd2fd..c667edb1 100644 --- a/src/bitmessageqt/dialogs.py +++ b/src/bitmessageqt/dialogs.py @@ -47,7 +47,7 @@ class AboutDialog(QtGui.QDialog, RetranslateMixin): try: self.label_2.setText( self.label_2.text().replace( - '2019', str(last_commit.get('time').year) + '2020', str(last_commit.get('time').year) )) except AttributeError: pass diff --git a/src/bitmessageqt/settings.py b/src/bitmessageqt/settings.py index 982328cc..011d38ed 100644 --- a/src/bitmessageqt/settings.py +++ b/src/bitmessageqt/settings.py @@ -1,3 +1,4 @@ +import ConfigParser import os import sys @@ -16,10 +17,24 @@ import tempfile import widgets from bmconfigparser import BMConfigParser from helper_sql import sqlExecute, sqlStoredProcedure +from helper_startup import start_proxyconfig from network.asyncore_pollchoose import set_rates from tr import _translate +def getSOCKSProxyType(config): + """Get user socksproxytype setting from *config*""" + try: + result = ConfigParser.SafeConfigParser.get( + config, 'bitmessagesettings', 'socksproxytype') + except (ConfigParser.NoSectionError, ConfigParser.NoOptionError): + return + else: + if result.lower() in ('', 'none', 'false'): + result = None + return result + + class SettingsDialog(QtGui.QDialog): """The "Settings" dialog""" def __init__(self, parent=None, firstrun=False): @@ -32,6 +47,16 @@ class SettingsDialog(QtGui.QDialog): self.net_restart_needed = False self.timer = QtCore.QTimer() + try: + import pkg_resources + except ImportError: + pass + else: + # Append proxy types defined in plugins + for ep in pkg_resources.iter_entry_points( + 'bitmessage.proxyconfig'): + self.comboBoxProxyType.addItem(ep.name) + self.lineEditMaxOutboundConnections.setValidator( QtGui.QIntValidator(0, 8, self.lineEditMaxOutboundConnections)) @@ -47,20 +72,33 @@ class SettingsDialog(QtGui.QDialog): def adjust_from_config(self, config): """Adjust all widgets state according to config settings""" # pylint: disable=too-many-branches,too-many-statements - self.checkBoxStartOnLogon.setChecked( - config.getboolean('bitmessagesettings', 'startonlogon')) - self.checkBoxMinimizeToTray.setChecked( - config.getboolean('bitmessagesettings', 'minimizetotray')) - self.checkBoxTrayOnClose.setChecked( - config.safeGetBoolean('bitmessagesettings', 'trayonclose')) + if not self.parent.tray.isSystemTrayAvailable(): + self.groupBoxTray.setEnabled(False) + self.groupBoxTray.setTitle(_translate( + "MainWindow", "Tray (not available in your system)")) + for setting in ( + 'minimizetotray', 'trayonclose', 'startintray'): + config.set('bitmessagesettings', setting, 'false') + else: + self.checkBoxMinimizeToTray.setChecked( + config.getboolean('bitmessagesettings', 'minimizetotray')) + self.checkBoxTrayOnClose.setChecked( + config.safeGetBoolean('bitmessagesettings', 'trayonclose')) + self.checkBoxStartInTray.setChecked( + config.getboolean('bitmessagesettings', 'startintray')) + self.checkBoxHideTrayConnectionNotifications.setChecked( - config.getboolean("bitmessagesettings", "hidetrayconnectionnotifications")) + config.getboolean( + 'bitmessagesettings', 'hidetrayconnectionnotifications')) self.checkBoxShowTrayNotifications.setChecked( config.getboolean('bitmessagesettings', 'showtraynotifications')) - self.checkBoxStartInTray.setChecked( - config.getboolean('bitmessagesettings', 'startintray')) + + self.checkBoxStartOnLogon.setChecked( + config.getboolean('bitmessagesettings', 'startonlogon')) + self.checkBoxWillinglySendToMobile.setChecked( - config.safeGetBoolean('bitmessagesettings', 'willinglysendtomobile')) + config.safeGetBoolean( + 'bitmessagesettings', 'willinglysendtomobile')) self.checkBoxUseIdenticons.setChecked( config.safeGetBoolean('bitmessagesettings', 'useidenticons')) self.checkBoxReplyBelow.setChecked( @@ -82,10 +120,12 @@ class SettingsDialog(QtGui.QDialog): "MainWindow", "Start-on-login not yet supported on your OS.")) self.checkBoxMinimizeToTray.setDisabled(True) self.checkBoxMinimizeToTray.setText(_translate( - "MainWindow", "Minimize-to-tray not yet supported on your OS.")) + "MainWindow", + "Minimize-to-tray not yet supported on your OS.")) self.checkBoxShowTrayNotifications.setDisabled(True) self.checkBoxShowTrayNotifications.setText(_translate( - "MainWindow", "Tray notifications not yet supported on your OS.")) + "MainWindow", + "Tray notifications not yet supported on your OS.")) elif 'linux' in sys.platform: self.checkBoxStartOnLogon.setDisabled(True) self.checkBoxStartOnLogon.setText(_translate( @@ -102,21 +142,11 @@ class SettingsDialog(QtGui.QDialog): self.checkBoxOnionOnly.setChecked( config.safeGetBoolean('bitmessagesettings', 'onionservicesonly')) - proxy_type = config.safeGet( - 'bitmessagesettings', 'socksproxytype', 'none') - if proxy_type == 'none': - self.comboBoxProxyType.setCurrentIndex(0) - self.lineEditSocksHostname.setEnabled(False) - self.lineEditSocksPort.setEnabled(False) - self.lineEditSocksUsername.setEnabled(False) - self.lineEditSocksPassword.setEnabled(False) - self.checkBoxAuthentication.setEnabled(False) - self.checkBoxSocksListen.setEnabled(False) - self.checkBoxOnionOnly.setEnabled(False) - elif proxy_type == 'SOCKS4a': - self.comboBoxProxyType.setCurrentIndex(1) - elif proxy_type == 'SOCKS5': - self.comboBoxProxyType.setCurrentIndex(2) + self._proxy_type = getSOCKSProxyType(config) + self.comboBoxProxyType.setCurrentIndex( + 0 if not self._proxy_type + else self.comboBoxProxyType.findText(self._proxy_type)) + self.comboBoxProxyTypeChanged(self.comboBoxProxyType.currentIndex()) self.lineEditSocksHostname.setText( config.get('bitmessagesettings', 'sockshostname')) @@ -204,7 +234,7 @@ class SettingsDialog(QtGui.QDialog): self.checkBoxAuthentication.setEnabled(False) self.checkBoxSocksListen.setEnabled(False) self.checkBoxOnionOnly.setEnabled(False) - elif comboBoxIndex in (1, 2): + else: self.lineEditSocksHostname.setEnabled(True) self.lineEditSocksPort.setEnabled(True) self.checkBoxAuthentication.setEnabled(True) @@ -306,27 +336,22 @@ class SettingsDialog(QtGui.QDialog): upnpThread = upnp.uPnPThread() upnpThread.start() - proxy_type = self.config.safeGet( - 'bitmessagesettings', 'socksproxytype', 'none') - if ( - proxy_type == 'none' and - self.comboBoxProxyType.currentText()[0:5] == 'SOCKS' and - shared.statusIconColor != 'red' - ): - self.net_restart_needed = True - if ( - proxy_type[0:5] == 'SOCKS' and - self.comboBoxProxyType.currentText()[0:5] != 'SOCKS' - ): + proxytype_index = self.comboBoxProxyType.currentIndex() + if proxytype_index == 0: + if self._proxy_type and shared.statusIconColor != 'red': + self.net_restart_needed = True + elif self.comboBoxProxyType.currentText() != self._proxy_type: self.net_restart_needed = True self.parent.statusbar.clearMessage() self.config.set( 'bitmessagesettings', 'socksproxytype', - str(self.comboBoxProxyType.currentText()) - if self.comboBoxProxyType.currentText()[0:5] == 'SOCKS' - else 'none' + 'none' if self.comboBoxProxyType.currentIndex() == 0 + else str(self.comboBoxProxyType.currentText()) ) + if proxytype_index > 2: # last literal proxytype in ui + start_proxyconfig() + self.config.set('bitmessagesettings', 'socksauthentication', str( self.checkBoxAuthentication.isChecked())) self.config.set('bitmessagesettings', 'sockshostname', str( diff --git a/src/bitmessageqt/settings.ui b/src/bitmessageqt/settings.ui index 963f2e64..0ffbf442 100644 --- a/src/bitmessageqt/settings.ui +++ b/src/bitmessageqt/settings.ui @@ -75,7 +75,7 @@ Minimize to tray - true + false @@ -419,12 +419,12 @@ - SOCKS4a + SOCKS4a - SOCKS5 + SOCKS5 diff --git a/src/bitmessageqt/support.py b/src/bitmessageqt/support.py index 2a1ddb18..d6d4543d 100644 --- a/src/bitmessageqt/support.py +++ b/src/bitmessageqt/support.py @@ -15,6 +15,7 @@ from openclpow import openclAvailable, openclEnabled import paths import proofofwork from pyelliptic.openssl import OpenSSL +from settings import getSOCKSProxyType import queues import network.stats import state @@ -118,8 +119,7 @@ def createSupportMessage(myapp): BMConfigParser().safeGet('bitmessagesettings', 'opencl') ) if openclEnabled() else "None" locale = getTranslationLanguage() - socks = BMConfigParser().safeGet( - 'bitmessagesettings', 'socksproxytype', "N/A") + socks = getSOCKSProxyType(BMConfigParser()) or "N/A" upnp = BMConfigParser().safeGet('bitmessagesettings', 'upnp', "N/A") connectedhosts = len(network.stats.connectedHostsList()) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 19f4861c..3e3261ad 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -141,13 +141,13 @@ 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( 'UPDATE sent SET status=?, lastactiontime=?' ' WHERE ackdata=?', - 'ackreceived', int(time.time()), data[readPosition:]) + ' ackreceived', int(time.time()), data[readPosition:]) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', (data[readPosition:], @@ -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 @@ -866,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. diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index b5bf2e43..7c0b5842 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -471,8 +471,8 @@ class singleWorker(StoppableThread): def sendOnionPeerObj(self, peer=None): """Send onionpeer object representing peer""" if not peer: # find own onionhostname - for peer_ in state.ownAddresses: - if peer_.host.endswith('.onion'): + for peer in state.ownAddresses: + if peer.host.endswith('.onion'): break else: return diff --git a/src/helper_startup.py b/src/helper_startup.py index bc0ede92..52a600ed 100644 --- a/src/helper_startup.py +++ b/src/helper_startup.py @@ -2,11 +2,12 @@ Startup operations. """ # pylint: disable=too-many-branches,too-many-statements -from __future__ import print_function - +# import configparser +import logging import os import platform import sys +import time from distutils.version import StrictVersion import defaults @@ -15,6 +16,13 @@ import paths import state from bmconfigparser import BMConfigParser +try: + from plugins.plugin import get_plugin +except ImportError: + get_plugin = None + + +logger = logging.getLogger('default') # The user may de-select Portable Mode in the settings if they want # the config files to stay in the application data folder. @@ -31,14 +39,14 @@ def loadConfig(): needToCreateKeysFile = config.safeGet( 'bitmessagesettings', 'settingsversion') is None if not needToCreateKeysFile: - print( + logger.info( 'Loading config files from directory specified' - ' on startup: %s' % state.appdata) + ' on startup: %s', state.appdata) else: config.read(paths.lookupExeFolder() + 'keys.dat') try: config.get('bitmessagesettings', 'settingsversion') - print('Loading config files from same directory as program.') + logger.info('Loading config files from same directory as program.') needToCreateKeysFile = False state.appdata = paths.lookupExeFolder() except: @@ -49,7 +57,8 @@ def loadConfig(): needToCreateKeysFile = config.safeGet( 'bitmessagesettings', 'settingsversion') is None if not needToCreateKeysFile: - print('Loading existing config files from', state.appdata) + logger.info( + 'Loading existing config files from %s', state.appdata) if needToCreateKeysFile: @@ -104,9 +113,10 @@ def loadConfig(): # Just use the same directory as the program and forget about # the appdata folder state.appdata = '' - print('Creating new config files in same directory as program.') + logger.info( + 'Creating new config files in same directory as program.') else: - print('Creating new config files in', state.appdata) + logger.info('Creating new config files in %s', state.appdata) if not os.path.exists(state.appdata): os.makedirs(state.appdata) if not sys.platform.startswith('win'): @@ -258,7 +268,7 @@ def updateConfig(): 'bitmessagesettings', 'hidetrayconnectionnotifications', 'false') if config.safeGetInt('bitmessagesettings', 'maxoutboundconnections') < 1: config.set('bitmessagesettings', 'maxoutboundconnections', '8') - print('WARNING: your maximum outbound connections must be a number.') + logger.warning('Your maximum outbound connections must be a number.') # TTL is now user-specifiable. Let's add an option to save # whatever the user selects. @@ -281,3 +291,26 @@ def isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections(): return False except Exception: pass + + +def start_proxyconfig(): + """Check socksproxytype and start any proxy configuration plugin""" + if not get_plugin: + return + config = BMConfigParser() + proxy_type = config.safeGet('bitmessagesettings', 'socksproxytype') + if proxy_type and proxy_type not in ('none', 'SOCKS4a', 'SOCKS5'): + try: + proxyconfig_start = time.time() + if not get_plugin('proxyconfig', name=proxy_type)(config): + raise TypeError() + except TypeError: + # cannot import shutdown here ): + logger.error( + 'Failed to run proxy config plugin %s', + proxy_type, exc_info=True) + os._exit(0) # pylint: disable=protected-access + else: + logger.info( + 'Started proxy config plugin %s in %s sec', + proxy_type, time.time() - proxyconfig_start) diff --git a/src/network/assemble.py b/src/network/assemble.py index 9ae853f7..82f37533 100644 --- a/src/network/assemble.py +++ b/src/network/assemble.py @@ -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 diff --git a/src/network/bmproto.py b/src/network/bmproto.py index ad2260fa..cd839a96 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -172,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 @@ -206,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: @@ -385,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): @@ -438,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: @@ -449,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(( diff --git a/src/network/udp.py b/src/network/udp.py index 0743776a..d3421806 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -149,6 +149,9 @@ class UDPSocket(BMProto): # pylint: disable=too-many-instance-attributes retval = self.socket.sendto( self.write_buf, ('', self.port)) except socket.error as e: - logger.error("socket error on sendato: %s", e) + logger.error("socket error on sendto: %s", e) + if e.errno == 101: + self.announcing = False + self.socket.close() retval = 0 self.slice_write_buf(retval) diff --git a/src/plugins/__init__.py b/src/plugins/__init__.py index e69de29b..285009df 100644 --- a/src/plugins/__init__.py +++ b/src/plugins/__init__.py @@ -0,0 +1,7 @@ +""" +Simple plugin system based on setuptools +---------------------------------------- + + +""" +# .. include:: pybitmessage.plugins.plugin.rst diff --git a/src/plugins/plugin.py b/src/plugins/plugin.py index e671a73f..629de0a6 100644 --- a/src/plugins/plugin.py +++ b/src/plugins/plugin.py @@ -1,19 +1,28 @@ # -*- coding: utf-8 -*- """ -src/plugins/plugin.py -=================================== +Operating with plugins """ +import logging + import pkg_resources +logger = logging.getLogger('default') + + def get_plugins(group, point='', name=None, fallback=None): """ - Iterate through plugins (`connect_plugin` attribute of entry point) - which name starts with `point` or equals to `name`. - If `fallback` kwarg specified, plugin with that name yield last. + :param str group: plugin group + :param str point: plugin name prefix + :param name: exact plugin name + :param fallback: fallback plugin name + + Iterate through plugins (``connect_plugin`` attribute of entry point) + which name starts with ``point`` or equals to ``name``. + If ``fallback`` kwarg specified, plugin with that name yield last. """ for ep in pkg_resources.iter_entry_points('bitmessage.' + group): - if name and ep.name == name or ep.name.startswith(point): + if name and ep.name == name or not point or ep.name.startswith(point): try: plugin = ep.load().connect_plugin if ep.name == fallback: @@ -25,6 +34,8 @@ def get_plugins(group, point='', name=None, fallback=None): ValueError, pkg_resources.DistributionNotFound, pkg_resources.UnknownExtra): + logger.debug( + 'Problem while loading %s', ep.name, exc_info=True) continue try: yield _fallback @@ -33,6 +44,8 @@ def get_plugins(group, point='', name=None, fallback=None): def get_plugin(*args, **kwargs): - """Returns first available plugin `from get_plugins()` if any.""" + """ + :return: first available plugin from :func:`get_plugins` if any. + """ for plugin in get_plugins(*args, **kwargs): return plugin diff --git a/src/plugins/proxyconfig_stem.py b/src/plugins/proxyconfig_stem.py index bdbfe8ca..494519f2 100644 --- a/src/plugins/proxyconfig_stem.py +++ b/src/plugins/proxyconfig_stem.py @@ -1,7 +1,15 @@ # -*- coding: utf-8 -*- """ -src/plugins/proxyconfig_stem.py -=================================== +Configure tor proxy and hidden service with +`stem `_ depending on *bitmessagesettings*: + + * try to start own tor instance on *socksport* if *sockshostname* + is unset or set to localhost; + * if *socksport* is already in use that instance is used only for + hidden service (if *sockslisten* is also set True); + * create ephemeral hidden service v3 if there is already *onionhostname*; + * otherwise use stem's 'BEST' version and save onion keys to the new + section using *onionhostname* as name for future use. """ import os import logging @@ -36,13 +44,20 @@ class DebugLogger(object): def connect_plugin(config): # pylint: disable=too-many-branches - """Run stem proxy configurator""" + """ + Run stem proxy configurator + + :param config: current configuration instance + :type config: :class:`pybitmessage.bmconfigparser.BMConfigParser` + :return: True if configuration was done successfully + """ logwrite = DebugLogger() - if config.safeGet('bitmessagesettings', 'sockshostname') not in ( - 'localhost', '127.0.0.1', '' + if config.safeGet('bitmessagesettings', 'sockshostname', '') not in ( + 'localhost', '127.0.0.1', '' ): # remote proxy is choosen for outbound connections, # nothing to do here, but need to set socksproxytype to SOCKS5! + config.set('bitmessagesettings', 'socksproxytype', 'SOCKS5') logwrite( 'sockshostname is set to remote address,' ' aborting stem proxy configuration') @@ -77,6 +92,8 @@ def connect_plugin(config): # pylint: disable=too-many-branches logwrite('Started tor on port %s' % port) break + config.setTemp('bitmessagesettings', 'socksproxytype', 'SOCKS5') + if config.safeGetBoolean('bitmessagesettings', 'sockslisten'): # need a hidden service for inbound connections try: @@ -95,7 +112,8 @@ def connect_plugin(config): # pylint: disable=too-many-branches onionkeytype = config.safeGet(onionhostname, 'keytype') response = controller.create_ephemeral_hidden_service( - config.safeGetInt('bitmessagesettings', 'onionport', 8444), + {config.safeGetInt('bitmessagesettings', 'onionport', 8444): + config.safeGetInt('bitmessagesettings', 'port', 8444)}, key_type=(onionkeytype or 'NEW'), key_content=(onionkey or onionhostname and 'ED25519-V3' or 'BEST') ) @@ -117,6 +135,5 @@ def connect_plugin(config): # pylint: disable=too-many-branches config.set( onionhostname, 'keytype', response.private_key_type) config.save() - config.set('bitmessagesettings', 'socksproxytype', 'SOCKS5') - return True + return True diff --git a/src/protocol.py b/src/protocol.py index fba68fe3..fd3ce26b 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -278,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): @@ -325,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) - + #python3 need to check + 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') diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 3eec3be6..c272f4ed 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -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: - 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_) + 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: + pass + # raise KeyError(hash_) + except: + pass return InventoryItem(*rows[0]) def __setitem__(self, hash_, value): diff --git a/src/tests/core.py b/src/tests/core.py index 27102a1c..7b89e5b0 100644 --- a/src/tests/core.py +++ b/src/tests/core.py @@ -15,14 +15,20 @@ import knownnodes import state from bmconfigparser import BMConfigParser from helper_msgcoding import MsgEncode, MsgDecode +from helper_startup import start_proxyconfig from network import asyncore_pollchoose as asyncore from network.connectionpool import BMConnectionPool from network.node import Peer from network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection from queues import excQueue +try: + import stem.version as stem_version +except ImportError: + stem_version = None + + knownnodes_file = os.path.join(state.appdata, 'knownnodes.dat') -program = None def pickle_knownnodes(): @@ -170,12 +176,29 @@ class TestCore(unittest.TestCase): self.assertIsInstance(con, connection_base) self.assertNotEqual(peer.host, '127.0.0.1') return - else: # pylint: disable=useless-else-on-loop - self.fail( - 'Failed to connect during %s sec' % (time.time() - _started)) + self.fail( + 'Failed to connect during %s sec' % (time.time() - _started)) - def test_onionservicesonly(self): - """test onionservicesonly networking mode""" + def test_bootstrap(self): + """test bootstrapping""" + self._initiate_bootstrap() + self._check_bootstrap() + + @unittest.skipUnless(stem_version, 'No stem, skipping tor dependent test') + def test_bootstrap_tor(self): + """test bootstrapping with tor""" + self._initiate_bootstrap() + BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'stem') + start_proxyconfig() + self._check_bootstrap() + + @unittest.skipUnless(stem_version, 'No stem, skipping tor dependent test') + def test_onionservicesonly(self): # this should start after bootstrap + """ + set onionservicesonly, wait for 3 connections and check them all + are onions + """ + BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'SOCKS5') BMConfigParser().set('bitmessagesettings', 'onionservicesonly', 'true') self._initiate_bootstrap() BMConfigParser().remove_option('bitmessagesettings', 'dontconnect') @@ -184,26 +207,18 @@ class TestCore(unittest.TestCase): for n, peer in enumerate(BMConnectionPool().outboundConnections): if n > 2: return - if not peer.host.endswith('.onion'): + if ( + not peer.host.endswith('.onion') + and not peer.host.startswith('bootstrap') + ): self.fail( 'Found non onion hostname %s in outbound connections!' % peer.host) self.fail('Failed to connect to at least 3 nodes within 360 sec') - def test_bootstrap(self): - """test bootstrapping""" - self._initiate_bootstrap() - self._check_bootstrap() - self._initiate_bootstrap() - BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'stem') - program.start_proxyconfig(BMConfigParser()) - self._check_bootstrap() - -def run(prog): +def run(): """Starts all tests defined in this module""" - global program # pylint: disable=global-statement - program = prog loader = unittest.TestLoader() loader.sortTestMethodsUsing = None suite = loader.loadTestsFromTestCase(TestCore) From 5a8fbbe4295d8f4f1a7aa8e57618a7e19231a7d0 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Sat, 4 Jan 2020 20:29:54 +0530 Subject: [PATCH 28/54] Solved person-to-person,brodcast,publickey,objects In network section via using the python2 database --- src/network/bmproto.py | 2 -- src/protocol.py | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/network/bmproto.py b/src/network/bmproto.py index cd839a96..66950380 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -468,8 +468,6 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return self.decode_payload_content("LQIQ16sH") def bm_command_addr(self): - # print('+++++++++++++++++++++++++++\ - # bm_command_addr bm_command_addr bm_command_addr ++++++++++++++++') """Incoming addresses, process them""" addresses = self._decode_addr() # pylint: disable=redefined-outer-name for i in addresses: diff --git a/src/protocol.py b/src/protocol.py index fd3ce26b..dd3af795 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -326,6 +326,7 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server= # = 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('raw_unicode_escape') + pack('>L', 2130706433) + # we have a separate extPort and incoming over clearnet # or outgoing through clearnet extport = BMConfigParser().safeGetInt('bitmessagesettings', 'extport') From 381be6e104e058b42ae7e53ed6c008587750e1de Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Wed, 8 Jan 2020 17:15:45 +0530 Subject: [PATCH 29/54] ECDSA Issue Solved --- src/class_objectProcessor.py | 6 +++--- src/highlevelcrypto.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 3e3261ad..cad8fe63 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -147,7 +147,7 @@ class objectProcessor(threading.Thread): sqlExecute( 'UPDATE sent SET status=?, lastactiontime=?' ' WHERE ackdata=?', - ' ackreceived', int(time.time()), data[readPosition:]) + 'ackreceived', int(time.time()), data[readPosition:]) queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', (data[readPosition:], @@ -383,9 +383,9 @@ class objectProcessor(threading.Thread): signatureLength, signatureLengthLength = decodeVarint( data[readPosition:readPosition + 10]) readPosition += signatureLengthLength - signature = data[readPosition:readPosition + signatureLength] + signature = bytes(data[readPosition:readPosition + signatureLength]) if highlevelcrypto.verify( - data[8:endOfSignedDataPosition], + bytes(data[8:endOfSignedDataPosition]), signature, hexlify(publicSigningKey)): logger.debug('ECDSA verify passed (within processpubkey)') else: diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index c2d9ebb2..03e2d1d3 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -30,7 +30,7 @@ def makeCryptor(privkey): def hexToPubkey(pubkey): """Convert a pubkey from hex to binary""" pubkey_raw = a.changebase(pubkey[2:], 16, 256, minlen=64) - pubkey_bin = '\x02\xca\x00 ' + pubkey_raw[:32] + '\x00 ' + pubkey_raw[32:] + pubkey_bin = '\x02\xca\x00 '.encode('raw_unicode_escape') + pubkey_raw[:32] + '\x00 '.encode() + pubkey_raw[32:] return pubkey_bin From 9e99bb6165aa502019a8c19d23ee18bf19a100e1 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Sat, 4 Jan 2020 19:47:44 +0530 Subject: [PATCH 30/54] mpybit fixes --- src/bitmessagekivy/mpybit.py | 89 +++++++++++++++++------------------- 1 file changed, 42 insertions(+), 47 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index bcb7c511..d2371000 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1,11 +1,13 @@ """ -src/bitmessagekivy/mpybit.py -================================= +Bitmessage android(mobile) interface """ -# pylint: disable=import-error, no-name-in-module, too-many-lines -# pylint: disable=too-few-public-methods, unused-argument, too-many-ancestors +# pylint: disable=import-error,no-name-in-module,unused-argument,too-few-public-methods,too-many-arguments +# pylint: disable=too-many-ancestors,too-many-locals,useless-super-delegation,attribute-defined-outside-init import os import time +from bitmessagekivy import identiconGeneration +from bitmessagekivy import kivy_helper_search +from bitmessagekivy.uikivysignaler import UIkivySignaler from bmconfigparser import BMConfigParser from functools import partial from helper_sql import sqlExecute, sqlQuery @@ -14,7 +16,6 @@ from kivy.clock import Clock from kivy.core.clipboard import Clipboard from kivy.core.window import Window from kivy.lang import Builder -from kivy.metrics import dp from kivy.properties import ( BooleanProperty, ListProperty, @@ -37,7 +38,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 from kivymd.uix.label import MDLabel @@ -51,7 +51,8 @@ from kivymd.uix.list import ( ) from kivymd.uix.navigationdrawer import ( MDNavigationDrawer, - NavigationDrawerHeaderBase) + NavigationDrawerHeaderBase +) from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.theming import ThemeManager @@ -59,16 +60,13 @@ import queues from semaphores import kivyuisignaler import state - -from bitmessagekivy.uikivysignaler import UIkivySignaler -from bitmessagekivy import identiconGeneration -from addresses import addBMIfNotPresent, decodeAddress, encodeVarint -# pylint: disable=unused-argument, too-few-public-methods +from addresses import decodeAddress def toast(text): """Method will display the toast message""" - from kivymd.toast.kivytoast import toast # pylint: disable=redefined-outer-name + # pylint: disable=redefined-outer-name + from kivymd.toast.kivytoast import toast toast(text) return @@ -105,7 +103,6 @@ class Inbox(Screen): def loadMessagelist(self, where="", what=""): """Load Inbox list for Inbox messages""" - # pylint: disable=too-many-locals self.set_defaultAddress() self.account = state.association if state.searcing_text: @@ -142,7 +139,6 @@ class Inbox(Screen): valign='top') self.ids.ml.add_widget(content) - # pylint: disable=too-many-arguments def inboxDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): """This method used for retrieving inbox data""" self.queryreturn = kivy_helper_search.search_sql( @@ -283,7 +279,6 @@ class Inbox(Screen): self.parent.parent.screens[4].clear_widgets() self.parent.parent.screens[4].add_widget(Trash()) - # pylint: disable=attribute-defined-outside-init def refresh_callback(self, *args): """Method updates the state of application, While the spinner remains on the screen""" @@ -389,7 +384,6 @@ class MyAddress(Screen): p.open() p.set_address(fromaddress, label) - # pylint: disable=attribute-defined-outside-init def refresh_callback(self, *args): """Method updates the state of application, While the spinner remains on the screen""" @@ -408,7 +402,13 @@ class MyAddress(Screen): @staticmethod def filter_address(address): """Method will filter the my address list data""" - if [x for x in [BMConfigParser().get(address, 'label').lower(), address.lower()] if (state.searcing_text).lower() in x]: + if [ + x for x in [ + BMConfigParser().get(address, 'label').lower(), + address.lower() + ] + if (state.searcing_text).lower() in x + ]: return True return False @@ -526,8 +526,8 @@ class AddressBook(Screen): "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 = duplicate-bases pass @@ -565,14 +565,14 @@ class SelectableLabel(RecycleDataViewBehavior, Label): class RV(RecycleView): """Recycling View""" - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + def __init__(self, **kwargs): """Recycling Method""" super(RV, self).__init__(**kwargs) class DropDownWidget(BoxLayout): """Adding Dropdown Widget""" - # pylint: disable=too-many-statements, too-many-locals + # pylint: disable=too-many-statements txt_input = ObjectProperty() rv = ObjectProperty() @@ -587,7 +587,6 @@ 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': @@ -678,7 +677,6 @@ class DropDownWidget(BoxLayout): state.kivyapp.back_press() toast('sent') - # pylint: disable=attribute-defined-outside-init def address_error_message(self, msg): """Generates error message""" width = .8 if platform == 'android' else .55 @@ -717,7 +715,7 @@ class MyTextInput(TextInput): starting_no = NumericProperty(3) suggestion_text = '' - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + def __init__(self, **kwargs): """Getting Text Input.""" super(MyTextInput, self).__init__(**kwargs) @@ -748,8 +746,9 @@ class MyTextInput(TextInput): class Payment(Screen): """Payment module""" - def get_available_credits(self, instance): # pylint: disable=no-self-use + def get_available_credits(self, instance): """Get the available credits""" + # pylint: disable=no-self-use state.availabe_credit = instance.parent.children[1].text existing_credits = ( state.kivyapp.root.ids.sc18.ids.ml.children[0].children[ @@ -813,7 +812,6 @@ class NetworkStat(Screen): class ContentNavigationDrawer(Navigatorss): """Navigate Content Drawer""" - # pylint: disable=too-many-arguments pass @@ -931,7 +929,6 @@ class Sent(Screen): valign='top') self.ids.ml.add_widget(content) - # pylint: disable=too-many-arguments def sentDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): """This method is used to retrieving data from sent table""" self.queryreturn = kivy_helper_search.search_sql( @@ -1271,8 +1268,9 @@ class Setting(Screen): pass -class NavigateApp(App): # pylint: disable=too-many-public-methods +class NavigateApp(App): """Navigation Layout of class""" + # pylint: disable=too-many-public-methods theme_cls = ThemeManager() previous_date = ObjectProperty() obj_1 = ObjectProperty() @@ -1319,10 +1317,10 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods kivyuisignaler.release() super(NavigateApp, self).run() - # pylint: disable=inconsistent-return-statements @staticmethod def showmeaddresses(name="text"): """Show the addresses in spinner to make as dropdown""" + # pylint: disable=inconsistent-return-statements if name == "text": if BMConfigParser().addresses(): return BMConfigParser().addresses()[0][:16] + '..' @@ -1649,8 +1647,9 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.refreshScreen() state.in_search_mode = False - def refreshScreen(self): # pylint: disable=unused-variable + def refreshScreen(self): """Method show search button only on inbox or sent screen""" + # pylint: disable=unused-variable state.searcing_text = '' if state.search_screen == 'inbox': try: @@ -1745,7 +1744,7 @@ class GrashofPopup(Popup): """Moule for save contacts and error messages""" valid = False - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + def __init__(self, **kwargs): """Grash of pop screen settings""" super(GrashofPopup, self).__init__(**kwargs) @@ -1837,7 +1836,9 @@ 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': @@ -2045,7 +2046,7 @@ class MyaddDetailPopup(Popup): address_label = StringProperty() address = StringProperty() - def __init__(self, **kwargs): # pylint: disable=useless-super-delegation + def __init__(self, **kwargs): """My Address Details screen setting""" super(MyaddDetailPopup, self).__init__(**kwargs) @@ -2079,7 +2080,6 @@ class AddbookDetailPopup(Popup): def __init__(self, **kwargs): """Set screen of address detail page""" - # pylint: disable=useless-super-delegation super(AddbookDetailPopup, self).__init__(**kwargs) def set_addbook_data(self, address, label): @@ -2201,7 +2201,6 @@ class Draft(Screen): valign='top') self.ids.ml.add_widget(content) - # pylint: disable=too-many-arguments def draftDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): """This methosd is for retrieving draft messages""" self.queryreturn = kivy_helper_search.search_sql( @@ -2229,8 +2228,7 @@ class Draft(Screen): 'ackdata': mail[5]}) for item in data: meny = TwoLineAvatarIconListItem( - text='Draft', - secondary_text=item['text'], + text='Draft', secondary_text=item['text'], theme_text_color='Custom', text_color=NavigateApp().theme_cls.primary_color) meny.add_widget(AvatarSampleWidget( @@ -2302,7 +2300,7 @@ class Draft(Screen): toast('Deleted') @staticmethod - def draft_msg(src_object): # pylint: disable=too-many-locals + def draft_msg(src_object): """Save draft mails""" composer_object = state.kivyapp.root.ids.sc3.children[1].ids fromAddress = str(composer_object.ti.text) @@ -2312,7 +2310,6 @@ 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) @@ -2480,10 +2477,12 @@ class Allmails(Screen): """Delete inbox mail from all mail listing""" if folder == 'inbox': sqlExecute( - "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", unique_id) + "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", + unique_id) else: sqlExecute( - "UPDATE sent SET folder = 'trash' WHERE ackdata = ?;", unique_id) + "UPDATE sent SET folder = 'trash' WHERE ackdata = ?;", + unique_id) self.ids.ml.remove_widget(instance.parent.parent) try: msg_count_objs = self.parent.parent.parent.parent.parent.children[ @@ -2517,7 +2516,6 @@ class Allmails(Screen): nav_lay_obj.sc5.add_widget(Trash()) nav_lay_obj.sc17.remove_widget(instance.parent.parent) - # pylint: disable=attribute-defined-outside-init def refresh_callback(self, *args): """Method updates the state of application, While the spinner remains on the screen""" @@ -2558,19 +2556,16 @@ 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 @@ -2589,4 +2584,4 @@ class LoadingPopup(Popup): class AddressDropdown(OneLineIconListItem): """AddressDropdown showns all the addresses""" - pass \ No newline at end of file + pass From 03db10675e20f9a6b6513615832a055e5aecb5d8 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 7 Jan 2020 16:58:29 +0530 Subject: [PATCH 31/54] new fix --- src/bitmessagekivy/identiconGeneration.py | 4 +- src/bitmessagekivy/kivy_helper_search.py | 14 +++--- src/bitmessagekivy/mpybit.py | 57 ++++++++++++++++++----- 3 files changed, 54 insertions(+), 21 deletions(-) diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index 25bd2254..faa72013 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -59,8 +59,7 @@ def random_color(hash_string): 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) + color = (int(r, 16), int(g, 16), int(b, 16), 0xFF) return color @@ -78,6 +77,5 @@ def generate_image(image, color, hash_string): if int(hash_string[index], 16) % 2 == 0: image.putpixel((x, y), color) image.putpixel((limit_x - x, y), color) - index = index + 1 return image diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index c05e69d4..9f740597 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -7,22 +7,24 @@ 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): - """Method helping for searching mails""" # pylint: disable=too-many-arguments, too-many-branches + """Method helping for searching mails""" if what is not None and what != "": what = "%" + what + "%" else: what = None - if folder == "sent" or folder == "draft": + if folder in ("sent", "draft"): sqlStatementBase = ( '''SELECT toaddress, fromaddress, subject, message, status,''' - ''' ackdata, lastactiontime FROM sent ''') + ''' 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 ''') + ''' subject, received, read FROM inbox ''' + ) sqlStatementParts = [] sqlArguments = [] if account is not None: @@ -59,7 +61,7 @@ def search_sql( if sqlStatementParts: sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts) # if folder in ("sent", "draft"): - if folder == "sent" or folder == "draft": + if folder in ("sent", "draft"): sqlStatementBase += \ "ORDER BY lastactiontime DESC limit {0}, {1}".format( start_indx, end_indx) @@ -69,4 +71,4 @@ def search_sql( start_indx, end_indx) # elif folder == "addressbook": # sqlStatementBase += " limit {0}, {1}".format(start_indx, end_indx) - return sqlQuery(sqlStatementBase, sqlArguments) \ No newline at end of file + return sqlQuery(sqlStatementBase, sqlArguments) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index d2371000..45eec8fb 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -81,6 +81,7 @@ class Navigatorss(MDNavigationDrawer): class Inbox(Screen): """Inbox Screen uses screen to show widgets of screens""" + queryreturn = ListProperty() has_refreshed = True account = StringProperty() @@ -301,6 +302,7 @@ class Inbox(Screen): class MyAddress(Screen): """MyAddress screen uses screen to show widgets of screens""" + addresses_list = ListProperty() has_refreshed = True is_add_created = False @@ -316,7 +318,10 @@ class MyAddress(Screen): self.addresses_list = state.kivyapp.variable_1 if state.searcing_text: self.ids.refresh_layout.scroll_y = 1.0 - filtered_list = [x for x in BMConfigParser().addresses() if self.filter_address(x)] + 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 = '' @@ -419,6 +424,7 @@ class MyAddress(Screen): class AddressBook(Screen): """AddressBook Screen uses screen to show widgets of screens""" + queryreturn = ListProperty() has_refreshed = True @@ -530,6 +536,7 @@ class SelectableRecycleBoxLayout( FocusBehavior, LayoutSelectionBehavior, RecycleBoxLayout): """Adds selection and focus behaviour to the view""" # pylint: disable = duplicate-bases + pass @@ -573,6 +580,7 @@ class RV(RecycleView): class DropDownWidget(BoxLayout): """Adding Dropdown Widget""" # pylint: disable=too-many-statements + txt_input = ObjectProperty() rv = ObjectProperty() @@ -613,7 +621,9 @@ class DropDownWidget(BoxLayout): 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': @@ -648,7 +658,8 @@ class DropDownWidget(BoxLayout): if state.detailPageType == 'draft' \ and state.send_draft_mail: state.draft_count = str(int(state.draft_count) - 1) - state.msg_counter_objs.draft_cnt.badge_text = state.draft_count + state.msg_counter_objs.draft_cnt.badge_text = ( + state.draft_count) state.detailPageType = '' state.send_draft_mail = None # self.parent.parent.screens[0].ids.ml.clear_widgets() @@ -766,6 +777,7 @@ class Payment(Screen): class Credits(Screen): """Credits Method""" + available_credits = StringProperty( '{0}'.format('0')) @@ -778,13 +790,15 @@ class Login(Screen): class NetworkStat(Screen): """Method used to show network stat""" + text_variable_1 = StringProperty( '{0}::{1}'.format('Total Connections', '0')) text_variable_2 = StringProperty( 'Processed {0} per-to-per messages'.format('0')) text_variable_3 = StringProperty( 'Processed {0} brodcast messages'.format('0')) - text_variable_4 = StringProperty('Processed {0} public keys'.format('0')) + text_variable_4 = StringProperty( + 'Processed {0} public keys'.format('0')) text_variable_5 = StringProperty( 'Processed {0} object to be synced'.format('0')) @@ -812,11 +826,13 @@ class NetworkStat(Screen): class ContentNavigationDrawer(Navigatorss): """Navigate Content Drawer""" + pass class Random(Screen): """Generates Random Address""" + is_active = BooleanProperty(False) checked = StringProperty("") @@ -877,6 +893,7 @@ class Random(Screen): class Sent(Screen): """Sent Screen uses screen to show widgets of screens""" + queryreturn = ListProperty() has_refreshed = True account = StringProperty() @@ -1100,6 +1117,7 @@ class Sent(Screen): class Trash(Screen): """Trash Screen uses screen to show widgets of screens""" + trash_messages = ListProperty() has_refreshed = True # delete_index = StringProperty() @@ -1231,9 +1249,11 @@ class Trash(Screen): """Deleting message from trash""" self.children[1].active = True if self.table_name == 'inbox': - sqlExecute("DELETE FROM inbox WHERE msgid = ?;", self.delete_index) + sqlExecute( + "DELETE FROM inbox WHERE msgid = ?;", self.delete_index) elif self.table_name == 'sent': - sqlExecute("DELETE FROM sent WHERE ackdata = ?;", 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( @@ -1271,6 +1291,7 @@ class Setting(Screen): class NavigateApp(App): """Navigation Layout of class""" # pylint: disable=too-many-public-methods + theme_cls = ThemeManager() previous_date = ObjectProperty() obj_1 = ObjectProperty() @@ -1742,6 +1763,7 @@ class NavigateApp(App): class GrashofPopup(Popup): """Moule for save contacts and error messages""" + valid = False def __init__(self, **kwargs): @@ -1834,7 +1856,9 @@ class GrashofPopup(Popup): elif status == 'missingbm': text = "The address should start with ''BM-''" elif status == 'checksumfailed': - text = "The address is not typed or copied correctly(the checksum failed)." + 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" @@ -1896,6 +1920,7 @@ class NavigationDrawerTwoLineListItem( class MailDetail(Screen): """MailDetail Screen uses to show the detail of mails""" + to_addr = StringProperty() from_addr = StringProperty() subject = StringProperty() @@ -2043,6 +2068,7 @@ class MailDetail(Screen): class MyaddDetailPopup(Popup): """MyaddDetailPopup pop is used for showing my address detail""" + address_label = StringProperty() address = StringProperty() @@ -2075,6 +2101,7 @@ class MyaddDetailPopup(Popup): class AddbookDetailPopup(Popup): """AddbookDetailPopup pop is used for showing my address detail""" + address_label = StringProperty() address = StringProperty() @@ -2154,6 +2181,7 @@ class ShowQRCode(Screen): class Draft(Screen): """Draft screen is used to show the list of draft messages""" + data = ListProperty() account = StringProperty() queryreturn = ListProperty() @@ -2284,10 +2312,12 @@ class Draft(Screen): sqlExecute("DELETE FROM sent WHERE ackdata = ?;", data_index) try: msg_count_objs = ( - self.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 + msg_count_objs = ( + self.parent.parent.parent.parent.parent.parent.children[ + 2].children[0].ids) # msg_count_objs = self.parent.parent.parent.parent.parent.children[ # 2].children[0].ids if int(state.draft_count) > 0: @@ -2354,6 +2384,7 @@ class CustomSpinner(Spinner): class Allmails(Screen): """All mails Screen uses screen to show widgets of screens""" + data = ListProperty() has_refreshed = True all_mails = ListProperty() @@ -2489,8 +2520,9 @@ class Allmails(Screen): 2].children[0].ids nav_lay_obj = self.parent.parent.parent.parent.parent.ids except Exception: - msg_count_objs = self.parent.parent.parent.parent.parent.parent.children[ - 2].children[0].ids + msg_count_objs = ( + self.parent.parent.parent.parent.parent.parent.children[ + 2].children[0].ids) nav_lay_obj = self.parent.parent.parent.parent.parent.parent.ids if folder == 'inbox': msg_count_objs.inbox_cnt.badge_text = str( @@ -2584,4 +2616,5 @@ class LoadingPopup(Popup): class AddressDropdown(OneLineIconListItem): """AddressDropdown showns all the addresses""" + pass From 32748d716c5cd182896aa3dc6d1d8df992071d23 Mon Sep 17 00:00:00 2001 From: navjot Date: Thu, 9 Jan 2020 20:39:01 +0530 Subject: [PATCH 32/54] kivy fixed part 6 --- src/bitmessagekivy/main.kv | 1158 +++++++++++++++++----------------- src/bitmessagekivy/mpybit.py | 202 +++--- 2 files changed, 674 insertions(+), 686 deletions(-) diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 67f24e01..0a9d7d80 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -1,8 +1,8 @@ +#:import IconLeftWidget kivymd.uix.list.IconLeftWidget +#:import images_path kivymd.images_path +#:import Spinner kivy.uix.spinner.Spinner +#:import Factory kivy.factory.Factory -#:import MDToolbar kivymd.uix.toolbar.MDToolbar -#:import NavigationLayout kivymd.uix.navigationdrawer.NavigationLayout -#:import NavigationDrawerDivider kivymd.uix.navigationdrawer.NavigationDrawerDivider -#:import NavigationDrawerSubheader kivymd.uix.navigationdrawer.NavigationDrawerSubheader #:import MDCheckbox kivymd.uix.selectioncontrol.MDCheckbox #:import MDList kivymd.uix.list.MDList #:import OneLineListItem kivymd.uix.list.OneLineListItem @@ -15,197 +15,216 @@ #:import Factory kivy.factory.Factory #:import MDScrollViewRefreshLayout kivymd.uix.refreshlayout.MDScrollViewRefreshLayout #:import MDSpinner kivymd.uix.spinner.MDSpinner -#:import NoTransition kivy.uix.screenmanager.NoTransition #:import MDTabsBase kivymd.uix.tab.MDTabsBase - #:set color_button (0.784, 0.443, 0.216, 1) # brown #:set color_button_pressed (0.659, 0.522, 0.431, 1) # darker brown #:set color_font (0.957, 0.890, 0.843, 1) # off white -: - font_style: 'Body1' - theme_text_color: 'Secondary' - : font_size: '12.5sp' background_color: color_button if self.state == 'down' else color_button_pressed background_down: 'atlas://data/images/defaulttheme/button' color: color_font -: - drawer_logo: './images/drawer_logo1.png' - NavigationDrawerDivider: - height: dp(7) - NavigationDrawerSubheader: - text: "Accounts" - AddressDropdown: - CustomSpinner: - id: btn - pos_hint:{"x":0,"y":.25} - option_cls: Factory.get("MySpinnerOption") - font_size: '11.9sp' - text: app.getDefaultAccData() - background_color: color_button if self.state == 'normal' else color_button_pressed - background_down: 'atlas://data/images/defaulttheme/spinner' - color: color_font - values: app.variable_1 - on_text:app.getCurrentAccountData(self.text) - Image: - source: app.get_default_image() - x: self.width/6 - y: self.parent.y + self.parent.height/4 - size: self.parent.height/2, self.parent.height/2 - ArrowImg: - 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) - MyNavigationDrawerIconButton: - id: send_cnt - icon: 'send' - text: "Sent" - #use_active: False - on_release: app.root.ids.scr_mngr.current = 'sent' - badge_text: "0" - MyNavigationDrawerIconButton: - id: draft_cnt - icon: 'message-draw' - text: "Draft" - on_release: app.root.ids.scr_mngr.current = 'draft' - badge_text: "0" - #MyNavigationDrawerIconButton: - #text: "Starred" - #icon:'star' - #on_release: app.root.ids.scr_mngr.current = 'starred' - #badge_text: "0" - #MyNavigationDrawerIconButton: - #icon: 'archive' - #text: "Archieve" - #on_release: app.root.ids.scr_mngr.current = 'archieve' - #badge_text: "0" - #MyNavigationDrawerIconButton: - #icon: 'email-open-outline' - #text: "Spam" - #on_release: app.root.ids.scr_mngr.current = 'spam' - #badge_text: "0" - MyNavigationDrawerIconButton: - id: trash_cnt - icon: 'delete' - text: "Trash" - on_release: app.root.ids.scr_mngr.current = 'trash' - badge_text: "0" - MyNavigationDrawerIconButton: - id: allmail_cnt - text: "All Mails" - icon:'contact-mail' - on_release: app.root.ids.scr_mngr.current = 'allmails' - badge_text: "0" - on_press: app.load_screen(self) - NavigationDrawerDivider: - NavigationDrawerSubheader: - text: "All labels" - MyNavigationDrawerIconButton: - text: "Address Book" - icon:'book-multiple' - on_release: app.root.ids.scr_mngr.current = 'addressbook' - MyNavigationDrawerIconButton: - text: "Settings" - icon:'settings' - on_release: app.root.ids.scr_mngr.current = 'set' - MyNavigationDrawerIconButton: - text: "Subscriptions/Payment" - icon:'bell' - on_release: app.root.ids.scr_mngr.current = 'payment' - MyNavigationDrawerIconButton: - text: "Credits" - icon:'wallet' - on_release: app.root.ids.scr_mngr.current = 'credits' - MyNavigationDrawerIconButton: - text: "new address" - icon:'account-plus' - on_release: app.root.ids.scr_mngr.current = 'login' - MyNavigationDrawerIconButton: - text: "Network Status" - icon:'server-network' - on_release: app.root.ids.scr_mngr.current = 'networkstat' - MyNavigationDrawerIconButton: - text: "My Addresses" - icon:'account-multiple' - on_release: app.root.ids.scr_mngr.current = 'myaddress' + + theme_text_color: 'Custom' + divider: None + + IconLeftWidget: + icon: root.icon + + + + + BoxLayout: + orientation: 'vertical' + + FloatLayout: + size_hint_y: None + height: "200dp" + + BoxLayout: + id: top_box + size_hint_y: None + height: "200dp" + #padding: "10dp" + x: root.parent.x + pos_hint: {"top": 1} + Image: + source: './images/drawer_logo1.png' + + ScrollView: + pos_hint: {"top": 1} + + GridLayout: + id: box_item + cols: 1 + size_hint_y: None + height: self.minimum_height + NavigationItem: + Spinner: + id: btn + pos_hint:{"x":0,"y":.1} + option_cls: Factory.get("MySpinnerOption") + font_size: '11.9sp' + text: app.getDefaultAccData() + background_color: color_button if self.state == 'normal' else color_button_pressed + background_down: 'atlas://data/images/defaulttheme/spinner' + color: color_font + values: app.variable_1 + on_text:app.getCurrentAccountData(self.text) + Image: + source: app.get_default_image() + x: self.width/6 + y: self.parent.y + self.parent.height/4 + size: self.parent.height/2, self.parent.height/2 + ArrowImg: + NavigationItem: + text: 'Inbox' + icon: 'email-open' + divider: None + badge_text: "0" + on_release: app.root.ids.scr_mngr.current = 'inbox' + on_release: root.parent.toggle_nav_drawer() + on_press: app.load_screen(self) + NavigationItem: + text: 'Sent' + icon: 'send' + divider: None + on_release: app.root.ids.scr_mngr.current = 'sent' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'Draft' + icon: 'message-draw' + divider: None + on_release: app.root.ids.scr_mngr.current = 'draft' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'Trash' + icon: 'delete' + divider: None + on_release: app.root.ids.scr_mngr.current = 'trash' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'All Mails' + icon: 'contact-mail' + divider: None + on_release: app.root.ids.scr_mngr.current = 'allmails' + on_release: root.parent.toggle_nav_drawer() + on_press: app.load_screen(self) + NavigationItem: + text: 'Address Book' + icon: 'book-multiple' + divider: None + on_release: app.root.ids.scr_mngr.current = 'addressbook' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'Settings' + icon: 'settings' + divider: None + on_release: app.root.ids.scr_mngr.current = 'set' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'Payment' + icon: 'bell' + divider: None + on_release: app.root.ids.scr_mngr.current = 'payment' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'Credits' + icon: 'wallet' + divider: None + on_release: app.root.ids.scr_mngr.current = 'credits' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'New address' + icon: 'account-plus' + divider: None + on_release: app.root.ids.scr_mngr.current = 'login' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'Network status' + icon: 'server-network' + divider: None + on_release: app.root.ids.scr_mngr.current = 'networkstat' + on_release: root.parent.toggle_nav_drawer() + NavigationItem: + text: 'My addresses' + icon: 'account-multiple' + divider: None + on_release: app.root.ids.scr_mngr.current = 'myaddress' + on_release: root.parent.toggle_nav_drawer() NavigationLayout: id: nav_layout - ContentNavigationDrawer: + MDToolbar: + id: toolbar + title: app.current_address_label() + opacity: 1 if app.addressexist() else 0 + disabled: False if app.addressexist() else True + pos_hint: {"top": 1} + md_bg_color: app.theme_cls.primary_color + elevation: 10 + left_action_items: [['menu', lambda x: nav_drawer.toggle_nav_drawer()]] + right_action_items: [['account-plus', lambda x: app.addingtoaddressbook()]] + + ScreenManager: + id: scr_mngr + size_hint_y: None + height: root.height - toolbar.height + Inbox: + id:sc1 + Page: + id:sc2 + Create: + id:sc3 + Sent: + id:sc4 + Trash: + id:sc5 + Login: + id:sc6 + Random: + id:sc7 + Spam: + id:sc8 + Setting: + id:sc9 + MyAddress: + id:sc10 + AddressBook: + id:sc11 + Payment: + id:sc12 + NetworkStat: + id:sc13 + MailDetail: + id:sc14 + ShowQRCode: + id:sc15 + Draft: + id:sc16 + Allmails: + id:sc17 + Credits: + id:sc18 + Starred: + id:sc19 + Archieve: + id:sc20 + + MDNavigationDrawer: id: nav_drawer - FloatLayout: - id: float_box - BoxLayout: - id: box_layout - orientation: 'vertical' - MDToolbar: - id: toolbar - title: app.current_address_label() - opacity: 1 if app.addressexist() else 0 - disabled: False if app.addressexist() else True - md_bg_color: app.theme_cls.primary_color - background_palette: 'Primary' - background_hue: '500' - left_action_items: [['menu', lambda x: app.root.toggle_nav_drawer()]] - right_action_items: [['account-plus', lambda x: app.addingtoaddressbook()]] - - ScreenManager: - id: scr_mngr - Inbox: - id:sc1 - Page: - id:sc2 - Create: - id:sc3 - Sent: - id:sc4 - Trash: - id:sc5 - Login: - id:sc6 - Random: - id:sc7 - Spam: - id:sc8 - Setting: - id:sc9 - MyAddress: - id:sc10 - AddressBook: - id:sc11 - Payment: - id:sc12 - NetworkStat: - id:sc13 - MailDetail: - id:sc14 - ShowQRCode: - id:sc15 - Draft: - id:sc16 - Allmails: - id:sc17 - Credits: - id:sc18 - Starred: - id:sc19 - Archieve: - id:sc20 + ContentNavigationDrawer: + id: content_drawer : name: 'inbox' - transition: NoTransition() + #transition: NoTransition() BoxLayout: orientation: 'vertical' spacing: dp(5) @@ -261,6 +280,16 @@ NavigationLayout: Loader: ComposerButton: +: + name: 'page' + Label: + text:"I am in Page" + color: 0,0,0,1 + +: + name: 'create' + Loader: + : name: 'trash' BoxLayout: @@ -285,224 +314,6 @@ NavigationLayout: id: ml Loader: ComposerButton: - -: - 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 - MDList: - id: ml - ComposerButton: - -: - name: 'starred' - ScrollView: - do_scroll_x: False - MDList: - id: ml - ComposerButton: - -: - name: 'archieve' - ScrollView: - do_scroll_x: False - MDList: - id: ml - ComposerButton: - -: - name: 'spam' - ScrollView: - do_scroll_x: False - MDList: - id: ml - ComposerButton: - -: - name: 'allmails' - #FloatLayout: - # MDScrollViewRefreshLayout: - # id: refresh_layout - # refresh_callback: root.refresh_callback - # 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: - id: scroll_y - do_scroll_x: False - MDList: - id: ml - Loader: - ComposerButton: - -: - name: 'test' - Label: - text:"I am in test" - color: 0,0,0,1 - -: - name: 'page' - Label: - text:"I am on page" - color: 0,0,0,1 - -: - name: 'create' - Loader: - -: - name: 'credits' - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(200) - OneLineListItem: - text: "Available Credits" - BoxLayout: - AnchorLayout: - MDRaisedButton: - height: dp(40) - MDLabel: - font_style: 'H4' - text: root.available_credits - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - -: - ScrollView: - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: self.minimum_height + 2 * self.parent.height/4 - padding: dp(32) - spacing: 15 - BoxLayout: - orientation: 'vertical' - MDTextField: - id: ti - hint_text: 'type or select sender address' - size_hint_y: None - height: 100 - font_size: '13sp' - multiline: False - required: True - helper_text_mode: "on_error" - - BoxLayout: - size_hint_y: None - height: dp(40) - CustomSpinner: - background_color: app.theme_cls.primary_dark - id: btn - values: app.variable_1 - on_text: root.auto_fill_fromaddr() if self.text != 'Select' else '' - option_cls: Factory.get("MySpinnerOption") - background_color: color_button if self.state == 'normal' else color_button_pressed - background_down: 'atlas://data/images/defaulttheme/spinner' - color: color_font - font_size: '12.5sp' - ArrowImg: - - BoxLayout: - orientation: 'vertical' - txt_input: txt_input - rv: rv - size : (890, 60) - MyTextInput: - id: txt_input - size_hint_y: None - font_size: '13sp' - height: self.parent.height/2 - hint_text: 'type, select or scan QR code for recipients address' - RV: - id: rv - MDTextField: - id: subject - hint_text: 'subject' - required: True - height: 100 - font_size: '13sp' - size_hint_y: None - multiline: False - helper_text_mode: "on_error" - - MDTextField: - id: body - multiline: True - hint_text: 'body' - size_hint_y: None - font_size: '13sp' - required: True - helper_text_mode: "on_error" - BoxLayout: - spacing:50 - -: - readonly: False - multiline: False - -: - # Draw a background to indicate selection - color: 0,0,0,1 - canvas.before: - Color: - rgba: app.theme_cls.primary_dark if self.selected else (1, 1, 1, 0) - Rectangle: - pos: self.pos - size: self.size - -: - canvas: - Color: - rgba: 0,0,0,.2 - - Line: - rectangle: self.x +1 , self.y, self.width - 2, self.height -2 - bar_width: 10 - scroll_type:['bars'] - viewclass: 'SelectableLabel' - SelectableRecycleBoxLayout: - default_size: None, dp(20) - default_size_hint: 1, None - size_hint_y: None - height: self.minimum_height - orientation: 'vertical' - multiselect: False - : name: 'login' @@ -608,6 +419,12 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' +: + name: 'spam' + Label: + text:"I am in Spam" + color: 0,0,0,1 + : name: 'set' ScrollView: @@ -696,7 +513,7 @@ NavigationLayout: MDScrollViewRefreshLayout: id: refresh_layout refresh_callback: root.refresh_callback - root_layout: root.set_root_layout() + root_layout: root MDList: id: ml Loader: @@ -871,75 +688,6 @@ NavigationLayout: font_size: '13sp' color: (0,0,0,1) halign: 'center' - - -: - id: popup - size_hint : (None,None) - height: 2*(label.height + address.height) + 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) - title_color: 0.4, 0.3765, 0.3451, 1 - auto_dismiss: False - separator_color: 0.3529, 0.3922, 0.102, 0.7 - BoxLayout: - size_hint_y: 0.5 - orientation: 'vertical' - spacing:dp(20) - id: popup_box - BoxLayout: - orientation: 'vertical' - MDTextField: - id: label - multiline: False - hint_text: "Label" - required: True - helper_text_mode: "on_error" - on_text: root.checkLabel_valid(self) - MDTextField: - id: address - hint_text: "Address" - required: True - helper_text_mode: "on_error" - on_text: root.checkAddress_valid(self) - BoxLayout: - spacing:5 - orientation: 'horizontal' - MDRaisedButton: - id: save_addr - size_hint: 1.5, None - height: dp(40) - on_release: - root.savecontact() - MDLabel: - font_style: 'H6' - text: 'Save' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 1.5, None - height: dp(40) - on_press: root.dismiss() - on_press: root.close_pop() - MDLabel: - font_style: 'H6' - text: 'Cancel' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 2, None - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Scan QR code' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - : name: 'networkstat' @@ -1075,18 +823,130 @@ NavigationLayout: height: dp(100) + self.minimum_height Loader: -: - id: cpyButton - color: 0,0,0,1 - background_color: (0,0,0,0) - center_x: self.parent.center_x * 2 - self.parent.parent.padding[0]/2 - center_y: self.parent.center_y - on_press:app.root.ids.sc14.copy_composer_text(self) - Image: - source: './images/copy_text.png' - center_x: self.parent.center_x - center_y: self.parent.center_y - size: 20, 20 +: + name: 'showqrcode' + BoxLayout: + orientation: 'vertical' + id: qr + +: + 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 + MDList: + id: ml + ComposerButton: + +: + name: 'allmails' + #FloatLayout: + # MDScrollViewRefreshLayout: + # id: refresh_layout + # refresh_callback: root.refresh_callback + # 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: + id: scroll_y + do_scroll_x: False + MDList: + id: ml + Loader: + ComposerButton: + +: + name: 'credits' + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(200) + OneLineListItem: + text: "Available Credits" + BoxLayout: + AnchorLayout: + MDRaisedButton: + height: dp(40) + MDLabel: + font_style: 'H4' + text: root.available_credits + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + +: + name: 'starred' + Label: + text:"I am in Starred" + color: 0,0,0,1 + + color: 0,0,0,1 + +: + name: 'archieve' + Label: + text:"I am in Archieve" + color: 0,0,0,1 + + color: 0,0,0,1 + + +: + source: './images/down-arrow.png' if self.parent.is_open == True else './images/right-arrow.png' + size: 15, 15 + x: self.parent.x + self.parent.width - self.width - 5 + y: self.parent.y + self.parent.height/2 - self.height + 5 + +: + id: search_bar + size_hint_y: None + height: self.minimum_height + + MDIconButton: + icon: 'magnify' + + MDTextField: + id: search_field + hint_text: 'Search' + on_text: app.searchQuery(self) + +: + id: spinner + size_hint: None, None + size: dp(46), dp(46) + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + active: False : size_hint_y: None @@ -1104,71 +964,180 @@ NavigationLayout: on_press: app.root.ids.scr_mngr.current = 'create' on_press: app.clear_composer() -: - 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 if app.app_platform == 'android' else app.window_size[0]/4) - background: './images/popup.jpeg' - auto_dismiss: False - separator_height: 0 - BoxLayout: - id: myadd_popup_box - size_hint_y: None - spacing:dp(70) - orientation: 'vertical' + +: + ScrollView: BoxLayout: - size_hint_y: None orientation: 'vertical' - spacing:dp(25) - MDLabel: - id: myaddr_label - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Label" - font_size: '17sp' - halign: 'left' - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: root.address_label - font_size: '15sp' - halign: 'left' - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Address" - font_size: '17sp' - halign: 'left' - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: root.address - font_size: '15sp' - halign: 'left' + size_hint_y: None + height: self.minimum_height + 2 * self.parent.height/4 + padding: dp(32) + spacing: 15 + BoxLayout: + orientation: 'vertical' + MDTextField: + id: ti + hint_text: 'type or select sender address' + size_hint_y: None + height: 100 + font_size: '13sp' + multiline: False + required: True + helper_text_mode: "on_error" + + BoxLayout: + size_hint_y: None + height: dp(40) + Spinner: + id: btn + background_color: app.theme_cls.primary_dark + values: app.variable_1 + on_text: root.auto_fill_fromaddr() if self.text != 'Select' else '' + option_cls: Factory.get("MySpinnerOption") + background_color: color_button if self.state == 'normal' else color_button_pressed + background_down: 'atlas://data/images/defaulttheme/spinner' + color: color_font + font_size: '12.5sp' + ArrowImg: + + BoxLayout: + orientation: 'vertical' + txt_input: txt_input + rv: rv + size : (890, 60) + MyTextInput: + id: txt_input + size_hint_y: None + font_size: '13sp' + height: self.parent.height/2 + hint_text: 'type, select or scan QR code for recipients address' + RV: + id: rv + MDTextField: + id: subject + hint_text: 'subject' + required: True + height: 100 + font_size: '13sp' + size_hint_y: None + multiline: False + helper_text_mode: "on_error" + + MDTextField: + id: body + multiline: True + hint_text: 'body' + size_hint_y: None + font_size: '13sp' + required: True + helper_text_mode: "on_error" + BoxLayout: + spacing:50 + +: + readonly: False + multiline: False + + +: + # Draw a background to indicate selection + color: 0,0,0,1 + canvas.before: + Color: + rgba: app.theme_cls.primary_dark if self.selected else (1, 1, 1, 0) + Rectangle: + pos: self.pos + size: self.size + +: + canvas: + Color: + rgba: 0,0,0,.2 + + Line: + rectangle: self.x +1 , self.y, self.width - 2, self.height -2 + bar_width: 10 + scroll_type:['bars'] + viewclass: 'SelectableLabel' + SelectableRecycleBoxLayout: + default_size: None, dp(20) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height + orientation: 'vertical' + multiselect: False + + +: + separator_color: 1, 1, 1, 1 + background: "White.png" + Button: + id: btn + disabled: True + background_disabled_normal: "White.png" + Image: + source: './images/loader.zip' + anim_delay: 0 + #mipmap: True + size: root.size + +: + id: cpyButton + color: 0,0,0,1 + background_color: (0,0,0,0) + center_x: self.parent.center_x * 2 - self.parent.parent.padding[0]/2 + center_y: self.parent.center_y + on_press:app.root.ids.sc14.copy_composer_text(self) + Image: + source: './images/copy_text.png' + center_x: self.parent.center_x + center_y: self.parent.center_y + size: 20, 20 + + +: + id: popup + size_hint : (None,None) + height: 2*(label.height + address.height) + 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) + title_color: 0.4, 0.3765, 0.3451, 1 + auto_dismiss: False + separator_color: 0.3529, 0.3922, 0.102, 0.7 + BoxLayout: + size_hint_y: 0.5 + orientation: 'vertical' + spacing:dp(20) + id: popup_box + BoxLayout: + orientation: 'vertical' + MDTextField: + id: label + multiline: False + hint_text: "Label" + required: True + helper_text_mode: "on_error" + on_text: root.checkLabel_valid(self) + MDTextField: + id: address + hint_text: "Address" + required: True + helper_text_mode: "on_error" + on_text: root.checkAddress_valid(self) BoxLayout: - id: my_add_btn spacing:5 orientation: 'horizontal' MDRaisedButton: - size_hint: 2, None - height: dp(40) - on_press: root.send_message_from() - MDLabel: - font_style: 'H6' - text: 'Send message from' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: + id: save_addr size_hint: 1.5, None height: dp(40) - on_press: root.dismiss() - on_press: app.root.ids.scr_mngr.current = 'showqrcode' - on_press: app.root.ids.sc15.qrdisplay() + on_release: + root.savecontact() MDLabel: font_style: 'H6' - text: 'Show QR code' + text: 'Save' font_size: '13sp' color: (1,1,1,1) halign: 'center' @@ -1183,6 +1152,15 @@ NavigationLayout: font_size: '13sp' color: (1,1,1,1) halign: 'center' + MDRaisedButton: + size_hint: 2, None + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Scan QR code' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' : id: addbook_popup @@ -1267,51 +1245,83 @@ NavigationLayout: color: (1,1,1,1) halign: 'center' -: - name: 'showqrcode' + +: + 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 if app.app_platform == 'android' else app.window_size[0]/4) + background: './images/popup.jpeg' + auto_dismiss: False + separator_height: 0 BoxLayout: + id: myadd_popup_box + size_hint_y: None + spacing:dp(70) orientation: 'vertical' - id: qr - - -: - source: './images/down-arrow.png' if self.parent.is_open == True else './images/right-arrow.png' - size: 15, 15 - x: self.parent.x + self.parent.width - self.width - 5 - y: self.parent.y + self.parent.height/2 - self.height + 5 - - -: - id: search_bar - size_hint_y: None - height: self.minimum_height - - MDIconButton: - icon: 'magnify' - - MDTextField: - id: search_field - hint_text: 'Search' - on_text: app.searchQuery(self) - - -: - separator_color: 1, 1, 1, 1 - background: "White.png" - Button: - id: btn - disabled: True - background_disabled_normal: "White.png" - Image: - source: './images/loader.zip' - anim_delay: 0 - #mipmap: True - size: root.size - - -: - id: spinner - size_hint: None, None - size: dp(46), dp(46) - pos_hint: {'center_x': 0.5, 'center_y': 0.5} - active: False \ No newline at end of file + BoxLayout: + size_hint_y: None + orientation: 'vertical' + spacing:dp(25) + MDLabel: + id: myaddr_label + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Label" + font_size: '17sp' + halign: 'left' + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: root.address_label + font_size: '15sp' + halign: 'left' + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Address" + font_size: '17sp' + halign: 'left' + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: root.address + font_size: '15sp' + halign: 'left' + BoxLayout: + id: my_add_btn + spacing:5 + orientation: 'horizontal' + MDRaisedButton: + size_hint: 2, None + height: dp(40) + on_press: root.send_message_from() + MDLabel: + font_style: 'H6' + text: 'Send message from' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.dismiss() + on_press: app.root.ids.scr_mngr.current = 'showqrcode' + on_press: app.root.ids.sc15.qrdisplay() + MDLabel: + font_style: 'H6' + text: 'Show QR code' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.dismiss() + on_press: root.close_pop() + MDLabel: + font_style: 'H6' + text: 'Cancel' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' \ No newline at end of file diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 45eec8fb..5ceecba9 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -11,7 +11,7 @@ from bitmessagekivy.uikivysignaler import UIkivySignaler from bmconfigparser import BMConfigParser from functools import partial from helper_sql import sqlExecute, sqlQuery -from kivy.app import App +from kivymd.app import MDApp from kivy.clock import Clock from kivy.core.clipboard import Clipboard from kivy.core.window import Window @@ -48,11 +48,13 @@ from kivymd.uix.list import ( TwoLineAvatarIconListItem, TwoLineListItem, OneLineIconListItem, + OneLineAvatarListItem, + IRightBody ) -from kivymd.uix.navigationdrawer import ( - MDNavigationDrawer, - NavigationDrawerHeaderBase -) +# from kivymd.uix.navigationdrawer import ( +# MDNavigationDrawer, +# NavigationDrawerHeaderBase +# ) from kivymd.uix.selectioncontrol import MDCheckbox from kivymd.theming import ThemeManager @@ -71,14 +73,6 @@ def toast(text): return -class Navigatorss(MDNavigationDrawer): - """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""" @@ -115,8 +109,8 @@ class Inbox(Screen): self.inboxDataQuery(xAddress, where, what) if self.queryreturn: state.kivyapp.get_inbox_count() - src_mng_obj = state.kivyapp.root.children[2].children[0].ids - src_mng_obj.inbox_cnt.badge_text = state.inbox_count + # src_mng_obj = state.kivyapp.root.children[2].children[0].ids + # src_mng_obj.inbox_cnt.badge_text = state.inbox_count for mail in self.queryreturn: # third_text = mail[3].replace('\n', ' ') data.append({ @@ -395,8 +389,9 @@ class MyAddress(Screen): def refresh_callback(interval): """Method used for loading the myaddress screen data""" state.searcing_text = '' - state.kivyapp.root.ids.sc10.children[2].active = False - self.children[2].children[2].ids.search_field.text = '' + #state.kivyapp.root.ids.sc10.children[2].active = False + # self.children[2].children[2].ids.search_field.text = '' + self.children[3].children[2].ids.search_field.text = '' self.has_refreshed = True self.ids.ml.clear_widgets() self.init_ui() @@ -417,10 +412,6 @@ class MyAddress(Screen): return True return False - def set_root_layout(self): - """Setting root layout""" - return self.manager.parent.parent - class AddressBook(Screen): """AddressBook Screen uses screen to show widgets of screens""" @@ -653,20 +644,16 @@ class DropDownWidget(BoxLayout): int(BMConfigParser().safeGet( 'bitmessagesettings', 'ttl'))) state.check_sent_acc = fromAddress - state.msg_counter_objs = self.parent.parent.parent.parent\ - .parent.parent.children[2].children[0].ids + # state.msg_counter_objs = self.parent.parent.parent.parent\ + # .parent.parent.children[2].children[0].ids if state.detailPageType == 'draft' \ and state.send_draft_mail: state.draft_count = str(int(state.draft_count) - 1) - state.msg_counter_objs.draft_cnt.badge_text = ( - state.draft_count) + # state.msg_counter_objs.draft_cnt.badge_text = ( + # state.draft_count) state.detailPageType = '' state.send_draft_mail = None - # self.parent.parent.screens[0].ids.ml.clear_widgets() - # self.parent.parent.screens[0].loadMessagelist(state.association) self.parent.parent.screens[3].update_sent_messagelist() - # self.parent.parent.screens[16].clear_widgets() - # self.parent.parent.screens[16].add_widget(Allmails()) Clock.schedule_once(self.callback_for_msgsend, 3) queues.workerQueue.put(('sendmessage', toAddress)) print("sqlExecute successfully #######################") @@ -824,7 +811,7 @@ class NetworkStat(Screen): len(objectracker.missingObjects)) -class ContentNavigationDrawer(Navigatorss): +class ContentNavigationDrawer(BoxLayout): """Navigate Content Drawer""" pass @@ -857,14 +844,14 @@ class Random(Screen): self.ids.label.text = '' self.parent.parent.children[1].opacity = 1 self.parent.parent.children[1].disabled = False - state.kivyapp.root.ids.sc10.children[1].active = True + state.kivyapp.loadMyAddressScreen(True) self.manager.current = 'myaddress' Clock.schedule_once(self.address_created_callback, 6) @staticmethod def address_created_callback(dt=0): """New address created""" - state.kivyapp.root.ids.sc10.children[1].active = False + state.kivyapp.loadMyAddressScreen(False) state.kivyapp.root.ids.sc10.ids.ml.clear_widgets() state.kivyapp.root.ids.sc10.is_add_created = True state.kivyapp.root.ids.sc10.init_ui() @@ -1050,8 +1037,8 @@ class Sent(Screen): @staticmethod def set_sentCount(total_sent): """Set the total no. of sent message count""" - src_mng_obj = state.kivyapp.root.children[2].children[0].ids - src_mng_obj.send_cnt.badge_text = str(total_sent) + # src_mng_obj = state.kivyapp.root.children[2].children[0].ids + # src_mng_obj.send_cnt.badge_text = str(total_sent) state.sent_count = str(total_sent) def sent_detail(self, ackdata, *args): @@ -1068,19 +1055,19 @@ class Sent(Screen): def delete(self, data_index, instance, *args): """Delete sent mail from sent mail listing""" - try: - msg_count_objs = self.parent.parent.parent.parent.children[ - 2].children[0].ids - except Exception: - msg_count_objs = self.parent.parent.parent.parent.parent.children[ - 2].children[0].ids + # try: + # msg_count_objs = self.parent.parent.parent.parent.children[ + # 2].children[0].ids + # except Exception: + # msg_count_objs = self.parent.parent.parent.parent.parent.children[ + # 2].children[0].ids if int(state.sent_count) > 0: - msg_count_objs.send_cnt.badge_text = str( - int(state.sent_count) - 1) - msg_count_objs.trash_cnt.badge_text = str( - int(state.trash_count) + 1) - msg_count_objs.allmail_cnt.badge_text = str( - int(state.all_count) - 1) + # msg_count_objs.send_cnt.badge_text = str( + # int(state.sent_count) - 1) + # msg_count_objs.trash_cnt.badge_text = str( + # int(state.trash_count) + 1) + # msg_count_objs.allmail_cnt.badge_text = str( + # int(state.all_count) - 1) 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) @@ -1137,8 +1124,8 @@ class Trash(Screen): 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 + # src_mng_obj = state.kivyapp.root.children[2].children[0].ids + # src_mng_obj.trash_cnt.badge_text = state.trash_count self.set_mdList() self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: @@ -1256,8 +1243,8 @@ class Trash(Screen): "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( - int(state.trash_count) - 1) + # msg_count_objs.trash_cnt.badge_text = str( + # int(state.trash_count) - 1) state.trash_count = str(int(state.trash_count) - 1) Clock.schedule_once(self.callback_for_screen_load, 1) @@ -1288,11 +1275,11 @@ class Setting(Screen): pass -class NavigateApp(App): +class NavigateApp(MDApp): """Navigation Layout of class""" # pylint: disable=too-many-public-methods - theme_cls = ThemeManager() + # theme_cls = ThemeManager() previous_date = ObjectProperty() obj_1 = ObjectProperty() variable_1 = ListProperty(BMConfigParser().addresses()) @@ -1325,7 +1312,6 @@ class NavigateApp(App): print(os.path.join(os.path.dirname(__file__), 'main.kv')) main_widget = Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) - self.nav_drawer = Navigatorss() self.obj_1 = AddressBook() kivysignalthread = UIkivySignaler() kivysignalthread.daemon = True @@ -1473,7 +1459,7 @@ class NavigateApp(App): self.root.ids.sc11.children[1].active = True Clock.schedule_once(self.search_callback, 0.5) elif state.search_screen == 'myaddress': - self.root.ids.sc10.children[1].active = True + self.loadMyAddressScreen(True) Clock.schedule_once(self.search_callback, 0.5) elif state.search_screen == 'sent': self.root.ids.sc4.children[1].active = True @@ -1492,13 +1478,20 @@ class NavigateApp(App): elif state.search_screen == 'myaddress': self.root.ids.sc10.ids.ml.clear_widgets() self.root.ids.sc10.init_ui() - self.root.ids.sc10.children[1].active = False + self.loadMyAddressScreen(False) else: self.root.ids.sc4.ids.ml.clear_widgets() self.root.ids.sc4.loadSent(state.association) self.root.ids.sc4.children[1].active = False self.root.ids.scr_mngr.current = state.search_screen + def loadMyAddressScreen(self, action): + """loadMyAddressScreen method spin the loader""" + if len(self.root.ids.sc10.children) <=3: + self.root.ids.sc10.children[1].active = action + else: + self.root.ids.sc10.children[2].active = action + def save_draft(self): """Saving drafts messages""" composer_objs = self.root @@ -1547,8 +1540,10 @@ class NavigateApp(App): """Common header for all window""" self.root.ids.toolbar.right_action_items = [ ['account-plus', lambda x: self.addingtoaddressbook()]] + # self.root.ids.toolbar.left_action_items = [ + # ['menu', lambda x: self.root.toggle_nav_drawer()]] self.root.ids.toolbar.left_action_items = [ - ['menu', lambda x: self.root.toggle_nav_drawer()]] + ['menu', lambda x: self.root.ids.nav_drawer.toggle_nav_drawer()]] return def back_press(self): @@ -1694,7 +1689,7 @@ class NavigateApp(App): except Exception: self.root.ids.sc10.children[ 2].children[2].ids.search_field.text = '' - self.root.ids.sc10.children[1].active = True + self.loadMyAddressScreen(True) Clock.schedule_once(self.search_callback, 0.5) else: self.root.ids.sc4.children[ @@ -1706,8 +1701,9 @@ class NavigateApp(App): def set_identicon(self, text): """Show identicon in address spinner""" img = identiconGeneration.generate(text) - self.root.children[2].children[0].ids.btn.children[1].texture = ( - img.texture) + # self.root.children[2].children[0].ids.btn.children[1].texture = ( + # img.texture) + self.root.children[0].children[0].ids.btn.texture = (img.texture) def set_mail_detail_header(self): """Setting the details of the page""" @@ -1804,8 +1800,10 @@ class GrashofPopup(Popup): def checkAddress_valid(self, instance): """Checking address is valid or not""" + # my_addresses = ( + # self.parent.children[1].children[2].children[0].ids.btn.values) my_addresses = ( - self.parent.children[1].children[2].children[0].ids.btn.values) + self.parent.children[1].children[0].children[0].ids.btn.values) add_book = [addr[1] for addr in kivy_helper_search.search_sql( folder="addressbook")] entered_text = str(instance.text).strip() @@ -1892,31 +1890,6 @@ class IconRightSampleWidget(IRightBodyTouch, MDCheckbox): pass -class NavigationDrawerTwoLineListItem( - TwoLineListItem, NavigationDrawerHeaderBase): - """Navigation Drawer in Listitems""" - - address_property = StringProperty() - - def __init__(self, **kwargs): - """Method for Navigation Drawer""" - super(NavigationDrawerTwoLineListItem, self).__init__(**kwargs) - Clock.schedule_once(lambda dt: self.setup()) - - def setup(self): - """Bind Controller.current_account property""" - pass - - def on_current_account(self, account): - """Account detail""" - pass - - def _update_specific_text_color(self, instance, value): - pass - - def _set_active(self, active, list_): - pass - class MailDetail(Screen): """MailDetail Screen uses to show the detail of mails""" @@ -1976,7 +1949,7 @@ class MailDetail(Screen): sqlExecute( "UPDATE sent SET folder = 'trash' WHERE" " ackdata = ?;", state.mail_id) - msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1) + # msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1) self.parent.screens[3].ids.ml.clear_widgets() self.parent.screens[3].loadSent(state.association) @@ -1988,27 +1961,25 @@ class MailDetail(Screen): sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE" " msgid = ?;", state.mail_id) - msg_count_objs.inbox_cnt.badge_text = str( - int(state.inbox_count) - 1) + # msg_count_objs.inbox_cnt.badge_text = str( + # int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1) self.parent.screens[0].ids.ml.clear_widgets() self.parent.screens[0].loadMessagelist(state.association) elif state.detailPageType == 'draft': sqlExecute("DELETE FROM sent WHERE ackdata = ?;", state.mail_id) - msg_count_objs.draft_cnt.badge_text = str( - int(state.draft_count) - 1) + # msg_count_objs.draft_cnt.badge_text = str( + # int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1) self.parent.screens[15].clear_widgets() self.parent.screens[15].add_widget(Draft()) - # self.parent.current = 'allmails' \ - # if state.is_allmail else state.detailPageType if state.detailPageType != 'draft': - msg_count_objs.trash_cnt.badge_text = str( - int(state.trash_count) + 1) - msg_count_objs.allmail_cnt.badge_text = str( - int(state.all_count) - 1) + # msg_count_objs.trash_cnt.badge_text = str( + # int(state.trash_count) + 1) + # msg_count_objs.allmail_cnt.badge_text = str( + # int(state.all_count) - 1) state.trash_count = str(int(state.trash_count) + 1) state.all_count = str(int(state.all_count) - 1) self.parent.screens[4].clear_widgets() @@ -2044,8 +2015,10 @@ class MailDetail(Screen): def write_msg(self, navApp): """Write on draft mail""" state.send_draft_mail = state.mail_id + # composer_ids = ( + # self.parent.parent.parent.parent.parent.ids.sc3.children[1].ids) composer_ids = ( - self.parent.parent.parent.parent.parent.ids.sc3.children[1].ids) + self.parent.parent.ids.sc3.children[1].ids) composer_ids.ti.text = state.write_msg['from_addr'] composer_ids.btn.text = state.write_msg['from_addr'] composer_ids.txt_input.text = state.write_msg['to_addr'] @@ -2215,8 +2188,8 @@ class Draft(Screen): 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 + # src_mng_obj = state.kivyapp.root.children[2].children[0].ids + # src_mng_obj.draft_cnt.badge_text = state.draft_count self.set_mdList() self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: @@ -2414,8 +2387,8 @@ class Allmails(Screen): state.kivyapp.get_sent_count() state.all_count = str( int(state.sent_count) + int(state.inbox_count)) - state.kivyapp.root.children[2].children[ - 0].ids.allmail_cnt.badge_text = state.all_count + # state.kivyapp.root.children[2].children[ + # 0].ids.allmail_cnt.badge_text = state.all_count self.set_mdlist() # self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y) self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) @@ -2516,30 +2489,30 @@ class Allmails(Screen): unique_id) self.ids.ml.remove_widget(instance.parent.parent) try: - msg_count_objs = self.parent.parent.parent.parent.parent.children[ - 2].children[0].ids - nav_lay_obj = self.parent.parent.parent.parent.parent.ids + # msg_count_objs = self.parent.parent.parent.parent.parent.children[ + # 2].children[0].ids + nav_lay_obj = self.parent.parent.parent.ids except Exception: msg_count_objs = ( self.parent.parent.parent.parent.parent.parent.children[ 2].children[0].ids) nav_lay_obj = self.parent.parent.parent.parent.parent.parent.ids if folder == 'inbox': - msg_count_objs.inbox_cnt.badge_text = str( - int(state.inbox_count) - 1) + # msg_count_objs.inbox_cnt.badge_text = str( + # int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1) nav_lay_obj.sc1.ids.ml.clear_widgets() nav_lay_obj.sc1.loadMessagelist(state.association) else: - msg_count_objs.send_cnt.badge_text = str( - int(state.sent_count) - 1) + # msg_count_objs.send_cnt.badge_text = str( + # int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1) nav_lay_obj.sc4.ids.ml.clear_widgets() nav_lay_obj.sc4.loadSent(state.association) - msg_count_objs.trash_cnt.badge_text = str( - int(state.trash_count) + 1) - msg_count_objs.allmail_cnt.badge_text = str( - int(state.all_count) - 1) + # msg_count_objs.trash_cnt.badge_text = str( + # int(state.trash_count) + 1) + # msg_count_objs.allmail_cnt.badge_text = str( + # 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: @@ -2618,3 +2591,8 @@ class AddressDropdown(OneLineIconListItem): """AddressDropdown showns all the addresses""" pass + + +class NavigationItem(OneLineAvatarListItem): + """NavigationItem class is for button behaviour""" + icon = StringProperty() \ No newline at end of file From 706ec5991e6f8c34d6a20f56283c1ba8a4515a78 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Fri, 10 Jan 2020 15:21:01 +0530 Subject: [PATCH 33/54] Updated the branch by origin and added changes on the knownNodes file --- python3_requirements.txt | 8 +++++++- src/knownnodes.py | 4 ++-- src/network/bmproto.py | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/python3_requirements.txt b/python3_requirements.txt index 5709432a..1115fe09 100644 --- a/python3_requirements.txt +++ b/python3_requirements.txt @@ -1,15 +1,21 @@ +astroid==2.3.3 certifi==2019.9.11 chardet==3.0.4 docutils==0.15.2 idna==2.8 +isort==4.3.21 Kivy==1.11.1 Kivy-Garden==0.1.4 -kivymd==0.100.2 +git+https://github.com/HeaTTheatR/KivyMD.git +lazy-object-proxy==1.4.3 +mccabe==0.6.1 Pillow==6.1.0 pkg-resources==0.0.0 pydenticon==0.3.1 Pygments==2.4.2 +pylint==2.4.4 qrcode==6.1 requests==2.22.0 six==1.12.0 +typed-ast==1.4.0 urllib3==1.25.6 diff --git a/src/knownnodes.py b/src/knownnodes.py index 08b71e57..c1d56ccc 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -114,14 +114,14 @@ def createDefaultKnownNodes(): def readKnownNodes(): """Load knownnodes from filesystem""" try: - with open(state.appdata + 'knownnodes.dat', 'r') as source: + with open(state.appdata + 'knownnodes.dat', 'rb') as source: with knownNodesLock: try: json_deserialize_knownnodes(source) except ValueError: source.seek(0) pickle_deserialize_old_knownnodes(source) - except (IOError, OSError, KeyError, EOFError): + except (IOError, OSError, KeyError, EOFError,pickle.UnpicklingError): logger.debug( 'Failed to read nodes from knownnodes.dat', exc_info=True) createDefaultKnownNodes() diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 66950380..dfb57092 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -472,7 +472,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): addresses = self._decode_addr() # pylint: disable=redefined-outer-name for i in addresses: seenTime, stream, _, ip, port = i - decodedIP = protocol.checkIPAddress(ip) + decodedIP = protocol.checkIPAddress(bytes(ip)) if stream not in state.streamsInWhichIAmParticipating: continue if ( From 5ff6c26efc9660fbc7032c8da6c9c4d011882a4f Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Fri, 10 Jan 2020 19:06:21 +0530 Subject: [PATCH 34/54] Solved python3 database issue and now network connection created via using the python3 db --- src/network/bmproto.py | 2 +- src/network/connectionpool.py | 6 +++++- src/network/tcp.py | 11 ++++++++--- src/protocol.py | 14 +++++++++++--- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/network/bmproto.py b/src/network/bmproto.py index dfb57092..099dc358 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -486,7 +486,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): continue except KeyError: pass - if len(knownnodes.knownNodes[stream]) < BMConfigParser().safeGetInt("knownnodes", "maxnodes"): + if len(knownnodes.knownNodes[stream]) < int(BMConfigParser().safeGet("knownnodes", "maxnodes")): with knownnodes.knownNodesLock: try: knownnodes.knownNodes[stream][peer]["lastseen"] = seenTime diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 4b9ab62b..719c798c 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -326,7 +326,11 @@ class BMConnectionPool(object): continue try: - if chosen.host.endswith(".onion") and Proxy.onion_proxy: + if type(chosen.host) == bytes: + onion= '.onion'.encode() + else: + onion = '.onion' + if chosen.host.endswith(onion) and Proxy.onion_proxy: if onionsocksproxytype == "SOCKS5": self.addConnection(Socks5BMConnection(chosen)) elif onionsocksproxytype == "SOCKS4a": diff --git a/src/network/tcp.py b/src/network/tcp.py index 7dff0122..586dedd6 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -69,9 +69,14 @@ class TCPConnection(BMProto, TLSDispatcher): else: self.destination = address self.isOutbound = True - self.create_socket( - socket.AF_INET6 if ":" in address.host else socket.AF_INET, - socket.SOCK_STREAM) + try: + self.create_socket( + socket.AF_INET6 if ":" in address.host else socket.AF_INET, + socket.SOCK_STREAM) + except TypeError: + self.create_socket( + socket.AF_INET6 if ':'.encode() in address.host else socket.AF_INET, + socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) TLSDispatcher.__init__(self, sock, server_side=False) self.connect(self.destination) diff --git a/src/protocol.py b/src/protocol.py index dd3af795..6fa989a3 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -96,9 +96,17 @@ def isBitSetWithinBitfield(fourByteString, n): def encodeHost(host): """Encode a given host to be used in low-level socket operations""" - if host.find('.onion') > -1: - return '\xfd\x87\xd8\x7e\xeb\x43'.encode('utf-8') + base64.b32decode(host.split(".")[0], True) - elif host.find(':') == -1: + if type(host) == bytes: + onion = 'onion'.encode() + colon = ':'.encode() + full_stop = '.'.encode() + else: + onion = 'onion' + colon = ':' + full_stop = '.' + if host.find(onion) > -1: + return '\xfd\x87\xd8\x7e\xeb\x43'.encode('raw_unicode_escape') + base64.b32decode(host.split(full_stop)[0], True) + elif host.find(colon) == -1: return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape') + \ socket.inet_aton(host) return socket.inet_pton(socket.AF_INET6, host) From 88b7a28ae76d058fca04c638f231e6100d9ed94d Mon Sep 17 00:00:00 2001 From: navjot Date: Fri, 10 Jan 2020 19:37:43 +0530 Subject: [PATCH 35/54] kivy fixes part 7 --- src/bitmessagekivy/kv/addressbook.kv | 24 + src/bitmessagekivy/kv/allmails.kv | 31 + src/bitmessagekivy/kv/common_widgets.kv | 55 ++ src/bitmessagekivy/kv/composer.kv | 101 +++ src/bitmessagekivy/kv/credits.kv | 20 + src/bitmessagekivy/kv/draft.kv | 22 + src/bitmessagekivy/kv/inbox.kv | 32 + src/bitmessagekivy/kv/login.kv | 103 +++ src/bitmessagekivy/kv/maildetail.kv | 45 + src/bitmessagekivy/kv/myaddress.kv | 24 + src/bitmessagekivy/kv/network.kv | 87 ++ src/bitmessagekivy/kv/payment.kv | 144 +++ src/bitmessagekivy/kv/popup.kv | 244 ++++++ src/bitmessagekivy/kv/sent.kv | 24 + src/bitmessagekivy/kv/settings.kv | 68 ++ src/bitmessagekivy/kv/trash.kv | 24 + src/bitmessagekivy/main.kv | 1066 ----------------------- src/bitmessagekivy/mpybit.py | 72 +- 18 files changed, 1081 insertions(+), 1105 deletions(-) create mode 100644 src/bitmessagekivy/kv/addressbook.kv create mode 100644 src/bitmessagekivy/kv/allmails.kv create mode 100644 src/bitmessagekivy/kv/common_widgets.kv create mode 100644 src/bitmessagekivy/kv/composer.kv create mode 100644 src/bitmessagekivy/kv/credits.kv create mode 100644 src/bitmessagekivy/kv/draft.kv create mode 100644 src/bitmessagekivy/kv/inbox.kv create mode 100644 src/bitmessagekivy/kv/login.kv create mode 100644 src/bitmessagekivy/kv/maildetail.kv create mode 100644 src/bitmessagekivy/kv/myaddress.kv create mode 100644 src/bitmessagekivy/kv/network.kv create mode 100644 src/bitmessagekivy/kv/payment.kv create mode 100644 src/bitmessagekivy/kv/popup.kv create mode 100644 src/bitmessagekivy/kv/sent.kv create mode 100644 src/bitmessagekivy/kv/settings.kv create mode 100644 src/bitmessagekivy/kv/trash.kv diff --git a/src/bitmessagekivy/kv/addressbook.kv b/src/bitmessagekivy/kv/addressbook.kv new file mode 100644 index 00000000..e789afa0 --- /dev/null +++ b/src/bitmessagekivy/kv/addressbook.kv @@ -0,0 +1,24 @@ +: + 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: + id: scroll_y + do_scroll_x: False + MDList: + id: ml + Loader: + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/allmails.kv b/src/bitmessagekivy/kv/allmails.kv new file mode 100644 index 00000000..4f099564 --- /dev/null +++ b/src/bitmessagekivy/kv/allmails.kv @@ -0,0 +1,31 @@ +: + name: 'allmails' + #FloatLayout: + # MDScrollViewRefreshLayout: + # id: refresh_layout + # refresh_callback: root.refresh_callback + # 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: + id: scroll_y + do_scroll_x: False + MDList: + id: ml + Loader: + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/common_widgets.kv b/src/bitmessagekivy/kv/common_widgets.kv new file mode 100644 index 00000000..2c041178 --- /dev/null +++ b/src/bitmessagekivy/kv/common_widgets.kv @@ -0,0 +1,55 @@ +: + source: './images/down-arrow.png' if self.parent.is_open == True else './images/right-arrow.png' + size: 15, 15 + x: self.parent.x + self.parent.width - self.width - 5 + y: self.parent.y + self.parent.height/2 - self.height + 5 + +: + id: search_bar + size_hint_y: None + height: self.minimum_height + + MDIconButton: + icon: 'magnify' + + MDTextField: + id: search_field + hint_text: 'Search' + on_text: app.searchQuery(self) + +: + id: spinner + size_hint: None, None + size: dp(46), dp(46) + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + active: False + +: + size_hint_y: None + height: dp(56) + spacing: '10dp' + pos_hint: {'center_x':0.45, 'center_y': .1} + + Widget: + + MDFloatingActionButton: + icon: 'plus' + opposite_colors: True + elevation_normal: 8 + md_bg_color: [0.941, 0, 0,1] + on_press: app.root.ids.scr_mngr.current = 'create' + on_press: app.clear_composer() + + +: + id: cpyButton + color: 0,0,0,1 + background_color: (0,0,0,0) + center_x: self.parent.center_x * 2 - self.parent.parent.padding[0]/2 + center_y: self.parent.center_y + on_press:app.root.ids.sc14.copy_composer_text(self) + Image: + source: './images/copy_text.png' + center_x: self.parent.center_x + center_y: self.parent.center_y + size: 20, 20 diff --git a/src/bitmessagekivy/kv/composer.kv b/src/bitmessagekivy/kv/composer.kv new file mode 100644 index 00000000..51cf7dc4 --- /dev/null +++ b/src/bitmessagekivy/kv/composer.kv @@ -0,0 +1,101 @@ +: + ScrollView: + BoxLayout: + orientation: 'vertical' + size_hint_y: None + height: self.minimum_height + 2 * self.parent.height/4 + padding: dp(32) + spacing: 15 + BoxLayout: + orientation: 'vertical' + MDTextField: + id: ti + hint_text: 'type or select sender address' + size_hint_y: None + height: 100 + font_size: '13sp' + multiline: False + required: True + helper_text_mode: "on_error" + + BoxLayout: + size_hint_y: None + height: dp(40) + Spinner: + id: btn + background_color: app.theme_cls.primary_dark + values: app.variable_1 + on_text: root.auto_fill_fromaddr() if self.text != 'Select' else '' + option_cls: Factory.get("MySpinnerOption") + background_color: color_button if self.state == 'normal' else color_button_pressed + background_down: 'atlas://data/images/defaulttheme/spinner' + color: color_font + font_size: '12.5sp' + ArrowImg: + + BoxLayout: + orientation: 'vertical' + txt_input: txt_input + rv: rv + size : (890, 60) + MyTextInput: + id: txt_input + size_hint_y: None + font_size: '13sp' + height: self.parent.height/2 + hint_text: 'type, select or scan QR code for recipients address' + RV: + id: rv + MDTextField: + id: subject + hint_text: 'subject' + required: True + height: 100 + font_size: '13sp' + size_hint_y: None + multiline: False + helper_text_mode: "on_error" + + MDTextField: + id: body + multiline: True + hint_text: 'body' + size_hint_y: None + font_size: '13sp' + required: True + helper_text_mode: "on_error" + BoxLayout: + spacing:50 + +: + readonly: False + multiline: False + + +: + # Draw a background to indicate selection + color: 0,0,0,1 + canvas.before: + Color: + rgba: app.theme_cls.primary_dark if self.selected else (1, 1, 1, 0) + Rectangle: + pos: self.pos + size: self.size + +: + canvas: + Color: + rgba: 0,0,0,.2 + + Line: + rectangle: self.x +1 , self.y, self.width - 2, self.height -2 + bar_width: 10 + scroll_type:['bars'] + viewclass: 'SelectableLabel' + SelectableRecycleBoxLayout: + default_size: None, dp(20) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height + orientation: 'vertical' + multiselect: False \ No newline at end of file diff --git a/src/bitmessagekivy/kv/credits.kv b/src/bitmessagekivy/kv/credits.kv new file mode 100644 index 00000000..9371311f --- /dev/null +++ b/src/bitmessagekivy/kv/credits.kv @@ -0,0 +1,20 @@ +: + name: 'credits' + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(200) + OneLineListItem: + text: "Available Credits" + BoxLayout: + AnchorLayout: + MDRaisedButton: + height: dp(40) + MDLabel: + font_style: 'H4' + text: root.available_credits + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' \ No newline at end of file diff --git a/src/bitmessagekivy/kv/draft.kv b/src/bitmessagekivy/kv/draft.kv new file mode 100644 index 00000000..8182d91e --- /dev/null +++ b/src/bitmessagekivy/kv/draft.kv @@ -0,0 +1,22 @@ +: + 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 + MDList: + id: ml + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/inbox.kv b/src/bitmessagekivy/kv/inbox.kv new file mode 100644 index 00000000..106d2d47 --- /dev/null +++ b/src/bitmessagekivy/kv/inbox.kv @@ -0,0 +1,32 @@ +: + name: 'inbox' + #transition: NoTransition() + 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' + #FloatLayout: + # MDScrollViewRefreshLayout: + # id: refresh_layout + # refresh_callback: root.refresh_callback + # root_layout: root.set_root_layout() + # MDList: + # id: ml + BoxLayout: + orientation:'vertical' + ScrollView: + id: scroll_y + do_scroll_x: False + MDList: + id: ml + Loader: + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/login.kv b/src/bitmessagekivy/kv/login.kv new file mode 100644 index 00000000..60d24f7f --- /dev/null +++ b/src/bitmessagekivy/kv/login.kv @@ -0,0 +1,103 @@ +: + name: 'login' + ScrollView: + do_scroll_x: False + BoxLayout: + orientation: 'vertical' + size_hint_y: None + height: dp(750) + padding: dp(10) + BoxLayout: + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "You may generate addresses by using either random numbers or by using a passphrase If you use a passphrase, the address is called a deterministic; address The Random Number option is selected by default but deterministic addresses have several \n pros and cons:\n" + halign: 'center' + color:app.theme_cls.primary_dark + BoxLayout: + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "If talk about pros You can recreate your addresses on any computer from memory, You need-not worry about backing up your keys.dat file as long as you can remember your passphrase and aside talk about cons You must remember (or write down) your You must remember the address version number and the stream number along with your passphrase If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you" + halign: 'center' + color:app.theme_cls.primary_dark + MDCheckbox: + id: grp_chkbox_1 + group: 'test' + active: True + allow_no_selection: False + MDLabel: + font_style: 'Body2' + theme_text_color: 'Primary' + text: "use a random number generator to make an address" + halign: 'center' + size_hint_y: None + height: self.texture_size[1] + dp(4) + color: [0.941, 0, 0,1] + MDCheckbox: + id: grp_chkbox_1 + group: 'test' + allow_no_selection: False + MDLabel: + font_style: 'Body2' + theme_text_color: 'Primary' + text: "use a pseudo number generator to make an address" + halign: 'center' + size_hint_y: None + color: [0.941, 0, 0,1] + height: self.texture_size[1] + dp(4) + BoxLayout: + AnchorLayout: + MDRaisedButton: + height: dp(40) + on_press: app.root.ids.scr_mngr.current = 'random' + on_press: app.root.ids.sc7.reset_address_label() + MDLabel: + font_style: 'H6' + text: 'proceed' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + +: + name: 'random' + ScrollView: + BoxLayout: + orientation: 'vertical' + size_hint_y: None + height: self.minimum_height + padding: dp(20) + spacing: 100 + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Random Addresses" + halign: 'center' + color:app.theme_cls.primary_dark + + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged" + halign: 'center' + color:app.theme_cls.primary_dark + + MDTextField: + id: label + multiline: True + hint_text: "Label" + required: True + helper_text_mode: "on_error" + on_text: root.add_validation(self) + BoxLayout: + AnchorLayout: + MDRaisedButton: + height: dp(40) + on_release: root.generateaddress(app) + opposite_colors: True + MDLabel: + font_style: 'H6' + text: 'next' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' diff --git a/src/bitmessagekivy/kv/maildetail.kv b/src/bitmessagekivy/kv/maildetail.kv new file mode 100644 index 00000000..ca6571a5 --- /dev/null +++ b/src/bitmessagekivy/kv/maildetail.kv @@ -0,0 +1,45 @@ +: + name: 'mailDetail' + ScrollView: + do_scroll_x: False + BoxLayout: + orientation: 'vertical' + size_hint_y: None + height: dp(500) + self.minimum_height + padding: dp(32) + MDLabel: + font_style: 'Subtitle1' + theme_text_color: 'Primary' + text: root.subject + halign: 'left' + font_size: '20sp' + CopyTextBtn: + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: "From: " + root.from_addr + halign: 'left' + CopyTextBtn: + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: "To: " + root.to_addr + halign: 'left' + CopyTextBtn: + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: root.status + halign: 'left' + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: root.message + halign: 'left' + bold: True + CopyTextBtn: + BoxLayout: + orientation: 'vertical' + size_hint_y: None + height: dp(100) + self.minimum_height + Loader: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/myaddress.kv b/src/bitmessagekivy/kv/myaddress.kv new file mode 100644 index 00000000..80db9c26 --- /dev/null +++ b/src/bitmessagekivy/kv/myaddress.kv @@ -0,0 +1,24 @@ +: + 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 + refresh_callback: root.refresh_callback + root_layout: root + MDList: + id: ml + Loader: + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/network.kv b/src/bitmessagekivy/kv/network.kv new file mode 100644 index 00000000..80d1bba1 --- /dev/null +++ b/src/bitmessagekivy/kv/network.kv @@ -0,0 +1,87 @@ +: + name: 'networkstat' + MDTabs: + id: tab_panel + tab_display_mode:'text' + + Tab: + text: "Total connections" + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(200) + OneLineListItem: + text: "Total Connections" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .6, .3 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_1 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + Tab: + text: 'Processes' + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(500) + OneLineListItem: + text: "person-to-person" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_2 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "Brodcast" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_3 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "publickeys" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_4 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "objects" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .7, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: root.text_variable_5 + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' \ No newline at end of file diff --git a/src/bitmessagekivy/kv/payment.kv b/src/bitmessagekivy/kv/payment.kv new file mode 100644 index 00000000..3eb92000 --- /dev/null +++ b/src/bitmessagekivy/kv/payment.kv @@ -0,0 +1,144 @@ +: + name: 'payment' + ScrollView: + do_scroll_x: False + BoxLayout: + orientation: 'vertical' + padding: [dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/6 if app.window_size[0] <= 800 else app.window_size[0]/18), dp(10)] + spacing: 12 + size_hint_y: None + height: self.minimum_height + dp(app.window_size[1]) if app.window_size[1] > app.window_size[0] else dp(app.window_size[0]) + BoxLayout: + orientation: 'vertical' + padding: dp(5) + canvas.before: + Color: + rgba: app.theme_cls.primary_dark + Rectangle: + # self here refers to the widget i.e FloatLayout + pos: self.pos + size: self.size + MDLabel: + size_hint_y: None + font_style: 'H5' + theme_text_color: 'Primary' + text: 'Platinum' + halign: 'center' + color: 1,1,1,1 + MDLabel: + font_style: 'Subtitle1' + theme_text_color: 'Primary' + text: 'We provide subscriptions for proof of work calculation for first month. ' + halign: 'center' + color: 1,1,1,1 + MDLabel: + id: free_pak + font_style: 'H5' + theme_text_color: 'Primary' + text: '€ 50.0' + halign: 'center' + color: 1,1,1,1 + MDRaisedButton: + canvas: + Color: + rgb: (0.93, 0.93, 0.93) + Rectangle: + pos: self.pos + size: self.size + size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 + height: dp(40) + on_press: root.get_available_credits(self) + MDLabel: + font_style: 'H6' + text: 'Get Free Credits' + font_size: '13sp' + color: (0,0,0,1) + halign: 'center' + BoxLayout: + orientation: 'vertical' + padding: dp(5) + canvas.before: + Color: + rgba: app.theme_cls.primary_dark + Rectangle: + # self here refers to the widget i.e FloatLayout + pos: self.pos + size: self.size + MDLabel: + size_hint_y: None + font_style: 'H5' + theme_text_color: 'Primary' + text: 'Silver' + halign: 'center' + color: 1,1,1,1 + MDLabel: + font_style: 'Subtitle1' + theme_text_color: 'Primary' + text: 'We provide for proof of work calculation for six month. ' + halign: 'center' + color: 1,1,1,1 + MDLabel: + font_style: 'H5' + theme_text_color: 'Primary' + text: '€ 100.0' + halign: 'center' + color: 1,1,1,1 + MDRaisedButton: + canvas: + Color: + rgb: (0.93, 0.93, 0.93) + Rectangle: + pos: self.pos + size: self.size + size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Get Monthly Credits' + font_size: '13sp' + color: (0,0,0,1) + halign: 'center' + BoxLayout: + orientation: 'vertical' + padding: dp(5) + canvas.before: + Color: + rgba: app.theme_cls.primary_dark + Rectangle: + # self here refers to the widget i.e FloatLayout + pos: self.pos + size: self.size + MDLabel: + size_hint_y: None + font_style: 'H5' + theme_text_color: 'Primary' + text: 'Gold' + halign: 'center' + color: 1,1,1,1 + MDLabel: + font_style: 'Subtitle1' + theme_text_color: 'Primary' + text: 'We provide for proof of work calculation for 1years. ' + halign: 'center' + color: 1,1,1,1 + MDLabel: + font_style: 'H5' + theme_text_color: 'Primary' + text: '€ 500.0' + halign: 'center' + color: 1,1,1,1 + MDRaisedButton: + canvas: + Color: + rgb: (0.93, 0.93, 0.93) + Rectangle: + pos: self.pos + size: self.size + size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Get Yearly Credits' + font_size: '13sp' + color: (0,0,0,1) + halign: 'center' \ No newline at end of file diff --git a/src/bitmessagekivy/kv/popup.kv b/src/bitmessagekivy/kv/popup.kv new file mode 100644 index 00000000..093e06a6 --- /dev/null +++ b/src/bitmessagekivy/kv/popup.kv @@ -0,0 +1,244 @@ +: + separator_color: 1, 1, 1, 1 + background: "White.png" + Button: + id: btn + disabled: True + background_disabled_normal: "White.png" + Image: + source: './images/loader.zip' + anim_delay: 0 + #mipmap: True + size: root.size + + +: + id: popup + size_hint : (None,None) + height: 2*(label.height + address.height) + 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) + title_color: 0.4, 0.3765, 0.3451, 1 + auto_dismiss: False + separator_color: 0.3529, 0.3922, 0.102, 0.7 + BoxLayout: + size_hint_y: 0.5 + orientation: 'vertical' + spacing:dp(20) + id: popup_box + BoxLayout: + orientation: 'vertical' + MDTextField: + id: label + multiline: False + hint_text: "Label" + required: True + helper_text_mode: "on_error" + on_text: root.checkLabel_valid(self) + MDTextField: + id: address + hint_text: "Address" + required: True + helper_text_mode: "on_error" + on_text: root.checkAddress_valid(self) + BoxLayout: + spacing:5 + orientation: 'horizontal' + MDRaisedButton: + id: save_addr + size_hint: 1.5, None + height: dp(40) + on_release: + root.savecontact() + MDLabel: + font_style: 'H6' + text: 'Save' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.dismiss() + on_press: root.close_pop() + MDLabel: + font_style: 'H6' + text: 'Cancel' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 2, None + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Scan QR code' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + +: + id: addbook_popup + size_hint : (None,None) + height: 4*(add_label.height) + 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 + BoxLayout: + size_hint_y: None + spacing:dp(70) + id: addbook_popup_box + orientation: 'vertical' + BoxLayout: + size_hint_y: None + orientation: 'vertical' + spacing:dp(20) + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Label" + font_size: '17sp' + halign: 'left' + MDTextField: + id: add_label + font_style: 'Body1' + font_size: '15sp' + halign: 'left' + text: root.address_label + theme_text_color: 'Primary' + required: True + helper_text_mode: "on_error" + on_text: root.checkLabel_valid(self) + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Address" + font_size: '17sp' + halign: 'left' + MDLabel: + id: address + font_style: 'Body1' + theme_text_color: 'Primary' + text: root.address + font_size: '15sp' + halign: 'left' + BoxLayout: + id: addbook_btn + spacing:5 + orientation: 'horizontal' + MDRaisedButton: + size_hint: 2, None + height: dp(40) + on_press: root.send_message_to() + MDLabel: + font_style: 'H6' + text: 'Send message to' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + font_size: '10sp' + on_press: root.update_addbook_label(root.address) + MDLabel: + font_style: 'H6' + text: 'Save' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.dismiss() + on_press: root.close_pop() + MDLabel: + font_style: 'H6' + text: 'Cancel' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + + +: + 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 if app.app_platform == 'android' else app.window_size[0]/4) + background: './images/popup.jpeg' + auto_dismiss: False + separator_height: 0 + BoxLayout: + id: myadd_popup_box + size_hint_y: None + spacing:dp(70) + orientation: 'vertical' + BoxLayout: + size_hint_y: None + orientation: 'vertical' + spacing:dp(25) + MDLabel: + id: myaddr_label + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Label" + font_size: '17sp' + halign: 'left' + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: root.address_label + font_size: '15sp' + halign: 'left' + MDLabel: + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Address" + font_size: '17sp' + halign: 'left' + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: root.address + font_size: '15sp' + halign: 'left' + BoxLayout: + id: my_add_btn + spacing:5 + orientation: 'horizontal' + MDRaisedButton: + size_hint: 2, None + height: dp(40) + on_press: root.send_message_from() + MDLabel: + font_style: 'H6' + text: 'Send message from' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.dismiss() + on_press: app.root.ids.scr_mngr.current = 'showqrcode' + on_press: app.root.ids.sc15.qrdisplay() + MDLabel: + font_style: 'H6' + text: 'Show QR code' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.dismiss() + on_press: root.close_pop() + MDLabel: + font_style: 'H6' + text: 'Cancel' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' \ No newline at end of file diff --git a/src/bitmessagekivy/kv/sent.kv b/src/bitmessagekivy/kv/sent.kv new file mode 100644 index 00000000..17fa0e2f --- /dev/null +++ b/src/bitmessagekivy/kv/sent.kv @@ -0,0 +1,24 @@ +: + 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: + id: scroll_y + do_scroll_x: False + MDList: + id: ml + Loader: + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/kv/settings.kv b/src/bitmessagekivy/kv/settings.kv new file mode 100644 index 00000000..efa3640b --- /dev/null +++ b/src/bitmessagekivy/kv/settings.kv @@ -0,0 +1,68 @@ +: + name: 'set' + ScrollView: + do_scroll_x: False + MDList: + id: ml + size_hint_y: None + height: dp(500) + OneLineListItem: + text: "SERVER SETTINGS" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .6, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Server' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "DATA SETTINGS" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .6, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Import or export data' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + OneLineListItem: + text: "OTHER SETTINGS" + BoxLayout: + AnchorLayout: + MDRaisedButton: + size_hint: .6, .55 + height: dp(40) + MDLabel: + font_style: 'H6' + text: 'Restart background service' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + BoxLayout: + AnchorLayout: + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: "bitmessage is 11 seconds behind the network" + halign: 'center' + color: [0.941, 0, 0,1] + + BoxLayout: + MDCheckbox: + id: chkbox + size_hint: None, None + size: dp(48), dp(64) + active: True + MDLabel: + font_style: 'Body1' + theme_text_color: 'Primary' + text: "show settings (for advanced users only)" + halign: 'left' + color: app.theme_cls.primary_dark \ No newline at end of file diff --git a/src/bitmessagekivy/kv/trash.kv b/src/bitmessagekivy/kv/trash.kv new file mode 100644 index 00000000..7475c334 --- /dev/null +++ b/src/bitmessagekivy/kv/trash.kv @@ -0,0 +1,24 @@ +: + 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 + MDList: + id: ml + Loader: + ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 0a9d7d80..0cc6f1a3 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -222,64 +222,6 @@ NavigationLayout: ContentNavigationDrawer: id: content_drawer -: - name: 'inbox' - #transition: NoTransition() - 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' - #FloatLayout: - # MDScrollViewRefreshLayout: - # id: refresh_layout - # refresh_callback: root.refresh_callback - # root_layout: root.set_root_layout() - # MDList: - # id: ml - BoxLayout: - orientation:'vertical' - ScrollView: - id: scroll_y - do_scroll_x: False - MDList: - id: ml - Loader: - ComposerButton: - -: - 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: - id: scroll_y - do_scroll_x: False - MDList: - id: ml - Loader: - ComposerButton: - : name: 'page' Label: @@ -290,621 +232,18 @@ NavigationLayout: name: 'create' Loader: -: - 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 - MDList: - id: ml - Loader: - ComposerButton: - -: - name: 'login' - ScrollView: - do_scroll_x: False - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: dp(750) - padding: dp(10) - BoxLayout: - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "You may generate addresses by using either random numbers or by using a passphrase If you use a passphrase, the address is called a deterministic; address The Random Number option is selected by default but deterministic addresses have several \n pros and cons:\n" - halign: 'center' - color:app.theme_cls.primary_dark - BoxLayout: - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "If talk about pros You can recreate your addresses on any computer from memory, You need-not worry about backing up your keys.dat file as long as you can remember your passphrase and aside talk about cons You must remember (or write down) your You must remember the address version number and the stream number along with your passphrase If you choose a weak passphrase and someone on the Internet can brute-force it, they can read your messages and send messages as you" - halign: 'center' - color:app.theme_cls.primary_dark - MDCheckbox: - id: grp_chkbox_1 - group: 'test' - active: True - allow_no_selection: False - MDLabel: - font_style: 'Body2' - theme_text_color: 'Primary' - text: "use a random number generator to make an address" - halign: 'center' - size_hint_y: None - height: self.texture_size[1] + dp(4) - color: [0.941, 0, 0,1] - MDCheckbox: - id: grp_chkbox_1 - group: 'test' - allow_no_selection: False - MDLabel: - font_style: 'Body2' - theme_text_color: 'Primary' - text: "use a pseudo number generator to make an address" - halign: 'center' - size_hint_y: None - color: [0.941, 0, 0,1] - height: self.texture_size[1] + dp(4) - BoxLayout: - AnchorLayout: - MDRaisedButton: - height: dp(40) - on_press: app.root.ids.scr_mngr.current = 'random' - on_press: app.root.ids.sc7.reset_address_label() - MDLabel: - font_style: 'H6' - text: 'proceed' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - -: - name: 'random' - ScrollView: - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: self.minimum_height - padding: dp(20) - spacing: 100 - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Random Addresses" - halign: 'center' - color:app.theme_cls.primary_dark - - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged" - halign: 'center' - color:app.theme_cls.primary_dark - - MDTextField: - id: label - multiline: True - hint_text: "Label" - required: True - helper_text_mode: "on_error" - on_text: root.add_validation(self) - BoxLayout: - AnchorLayout: - MDRaisedButton: - height: dp(40) - on_release: root.generateaddress(app) - opposite_colors: True - MDLabel: - font_style: 'H6' - text: 'next' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - : name: 'spam' Label: text:"I am in Spam" color: 0,0,0,1 -: - name: 'set' - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(500) - OneLineListItem: - text: "SERVER SETTINGS" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .6, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Server' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "DATA SETTINGS" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .6, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Import or export data' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "OTHER SETTINGS" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .6, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Restart background service' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - BoxLayout: - AnchorLayout: - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: "bitmessage is 11 seconds behind the network" - halign: 'center' - color: [0.941, 0, 0,1] - - BoxLayout: - MDCheckbox: - id: chkbox - size_hint: None, None - size: dp(48), dp(64) - active: True - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: "show settings (for advanced users only)" - halign: 'left' - color: app.theme_cls.primary_dark - -: - 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 - refresh_callback: root.refresh_callback - root_layout: root - MDList: - id: ml - Loader: - ComposerButton: - -: - 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: - id: scroll_y - do_scroll_x: False - MDList: - id: ml - Loader: - ComposerButton: - -: - name: 'payment' - ScrollView: - do_scroll_x: False - BoxLayout: - orientation: 'vertical' - padding: [dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/6 if app.window_size[0] <= 800 else app.window_size[0]/18), dp(10)] - spacing: 12 - size_hint_y: None - height: self.minimum_height + dp(app.window_size[1]) if app.window_size[1] > app.window_size[0] else dp(app.window_size[0]) - BoxLayout: - orientation: 'vertical' - padding: dp(5) - canvas.before: - Color: - rgba: app.theme_cls.primary_dark - Rectangle: - # self here refers to the widget i.e FloatLayout - pos: self.pos - size: self.size - MDLabel: - size_hint_y: None - font_style: 'H5' - theme_text_color: 'Primary' - text: 'Platinum' - halign: 'center' - color: 1,1,1,1 - MDLabel: - font_style: 'Subtitle1' - theme_text_color: 'Primary' - text: 'We provide subscriptions for proof of work calculation for first month. ' - halign: 'center' - color: 1,1,1,1 - MDLabel: - id: free_pak - font_style: 'H5' - theme_text_color: 'Primary' - text: '€ 50.0' - halign: 'center' - color: 1,1,1,1 - MDRaisedButton: - canvas: - Color: - rgb: (0.93, 0.93, 0.93) - Rectangle: - pos: self.pos - size: self.size - size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 - height: dp(40) - on_press: root.get_available_credits(self) - MDLabel: - font_style: 'H6' - text: 'Get Free Credits' - font_size: '13sp' - color: (0,0,0,1) - halign: 'center' - BoxLayout: - orientation: 'vertical' - padding: dp(5) - canvas.before: - Color: - rgba: app.theme_cls.primary_dark - Rectangle: - # self here refers to the widget i.e FloatLayout - pos: self.pos - size: self.size - MDLabel: - size_hint_y: None - font_style: 'H5' - theme_text_color: 'Primary' - text: 'Silver' - halign: 'center' - color: 1,1,1,1 - MDLabel: - font_style: 'Subtitle1' - theme_text_color: 'Primary' - text: 'We provide for proof of work calculation for six month. ' - halign: 'center' - color: 1,1,1,1 - MDLabel: - font_style: 'H5' - theme_text_color: 'Primary' - text: '€ 100.0' - halign: 'center' - color: 1,1,1,1 - MDRaisedButton: - canvas: - Color: - rgb: (0.93, 0.93, 0.93) - Rectangle: - pos: self.pos - size: self.size - size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Get Monthly Credits' - font_size: '13sp' - color: (0,0,0,1) - halign: 'center' - BoxLayout: - orientation: 'vertical' - padding: dp(5) - canvas.before: - Color: - rgba: app.theme_cls.primary_dark - Rectangle: - # self here refers to the widget i.e FloatLayout - pos: self.pos - size: self.size - MDLabel: - size_hint_y: None - font_style: 'H5' - theme_text_color: 'Primary' - text: 'Gold' - halign: 'center' - color: 1,1,1,1 - MDLabel: - font_style: 'Subtitle1' - theme_text_color: 'Primary' - text: 'We provide for proof of work calculation for 1years. ' - halign: 'center' - color: 1,1,1,1 - MDLabel: - font_style: 'H5' - theme_text_color: 'Primary' - text: '€ 500.0' - halign: 'center' - color: 1,1,1,1 - MDRaisedButton: - canvas: - Color: - rgb: (0.93, 0.93, 0.93) - Rectangle: - pos: self.pos - size: self.size - size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Get Yearly Credits' - font_size: '13sp' - color: (0,0,0,1) - halign: 'center' - -: - name: 'networkstat' - MDTabs: - id: tab_panel - tab_display_mode:'text' - - Tab: - text: "Total connections" - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(200) - OneLineListItem: - text: "Total Connections" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .6, .3 - height: dp(40) - MDLabel: - font_style: 'H6' - text: root.text_variable_1 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - Tab: - text: 'Processes' - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(500) - OneLineListItem: - text: "person-to-person" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: root.text_variable_2 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "Brodcast" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: root.text_variable_3 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "publickeys" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: root.text_variable_4 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - OneLineListItem: - text: "objects" - BoxLayout: - AnchorLayout: - MDRaisedButton: - size_hint: .7, .55 - height: dp(40) - MDLabel: - font_style: 'H6' - text: root.text_variable_5 - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - -: - name: 'mailDetail' - ScrollView: - do_scroll_x: False - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: dp(500) + self.minimum_height - padding: dp(32) - MDLabel: - font_style: 'Subtitle1' - theme_text_color: 'Primary' - text: root.subject - halign: 'left' - font_size: '20sp' - CopyTextBtn: - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: "From: " + root.from_addr - halign: 'left' - CopyTextBtn: - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: "To: " + root.to_addr - halign: 'left' - CopyTextBtn: - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: root.status - halign: 'left' - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: root.message - halign: 'left' - bold: True - CopyTextBtn: - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: dp(100) + self.minimum_height - Loader: - : name: 'showqrcode' BoxLayout: orientation: 'vertical' id: qr -: - 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 - MDList: - id: ml - ComposerButton: - -: - name: 'allmails' - #FloatLayout: - # MDScrollViewRefreshLayout: - # id: refresh_layout - # refresh_callback: root.refresh_callback - # 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: - id: scroll_y - do_scroll_x: False - MDList: - id: ml - Loader: - ComposerButton: - -: - name: 'credits' - ScrollView: - do_scroll_x: False - MDList: - id: ml - size_hint_y: None - height: dp(200) - OneLineListItem: - text: "Available Credits" - BoxLayout: - AnchorLayout: - MDRaisedButton: - height: dp(40) - MDLabel: - font_style: 'H4' - text: root.available_credits - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - : name: 'starred' Label: @@ -920,408 +259,3 @@ NavigationLayout: color: 0,0,0,1 color: 0,0,0,1 - - -: - source: './images/down-arrow.png' if self.parent.is_open == True else './images/right-arrow.png' - size: 15, 15 - x: self.parent.x + self.parent.width - self.width - 5 - y: self.parent.y + self.parent.height/2 - self.height + 5 - -: - id: search_bar - size_hint_y: None - height: self.minimum_height - - MDIconButton: - icon: 'magnify' - - MDTextField: - id: search_field - hint_text: 'Search' - on_text: app.searchQuery(self) - -: - id: spinner - size_hint: None, None - size: dp(46), dp(46) - pos_hint: {'center_x': 0.5, 'center_y': 0.5} - active: False - -: - size_hint_y: None - height: dp(56) - spacing: '10dp' - pos_hint: {'center_x':0.45, 'center_y': .1} - - Widget: - - MDFloatingActionButton: - icon: 'plus' - opposite_colors: True - elevation_normal: 8 - md_bg_color: [0.941, 0, 0,1] - on_press: app.root.ids.scr_mngr.current = 'create' - on_press: app.clear_composer() - - -: - ScrollView: - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: self.minimum_height + 2 * self.parent.height/4 - padding: dp(32) - spacing: 15 - BoxLayout: - orientation: 'vertical' - MDTextField: - id: ti - hint_text: 'type or select sender address' - size_hint_y: None - height: 100 - font_size: '13sp' - multiline: False - required: True - helper_text_mode: "on_error" - - BoxLayout: - size_hint_y: None - height: dp(40) - Spinner: - id: btn - background_color: app.theme_cls.primary_dark - values: app.variable_1 - on_text: root.auto_fill_fromaddr() if self.text != 'Select' else '' - option_cls: Factory.get("MySpinnerOption") - background_color: color_button if self.state == 'normal' else color_button_pressed - background_down: 'atlas://data/images/defaulttheme/spinner' - color: color_font - font_size: '12.5sp' - ArrowImg: - - BoxLayout: - orientation: 'vertical' - txt_input: txt_input - rv: rv - size : (890, 60) - MyTextInput: - id: txt_input - size_hint_y: None - font_size: '13sp' - height: self.parent.height/2 - hint_text: 'type, select or scan QR code for recipients address' - RV: - id: rv - MDTextField: - id: subject - hint_text: 'subject' - required: True - height: 100 - font_size: '13sp' - size_hint_y: None - multiline: False - helper_text_mode: "on_error" - - MDTextField: - id: body - multiline: True - hint_text: 'body' - size_hint_y: None - font_size: '13sp' - required: True - helper_text_mode: "on_error" - BoxLayout: - spacing:50 - -: - readonly: False - multiline: False - - -: - # Draw a background to indicate selection - color: 0,0,0,1 - canvas.before: - Color: - rgba: app.theme_cls.primary_dark if self.selected else (1, 1, 1, 0) - Rectangle: - pos: self.pos - size: self.size - -: - canvas: - Color: - rgba: 0,0,0,.2 - - Line: - rectangle: self.x +1 , self.y, self.width - 2, self.height -2 - bar_width: 10 - scroll_type:['bars'] - viewclass: 'SelectableLabel' - SelectableRecycleBoxLayout: - default_size: None, dp(20) - default_size_hint: 1, None - size_hint_y: None - height: self.minimum_height - orientation: 'vertical' - multiselect: False - - -: - separator_color: 1, 1, 1, 1 - background: "White.png" - Button: - id: btn - disabled: True - background_disabled_normal: "White.png" - Image: - source: './images/loader.zip' - anim_delay: 0 - #mipmap: True - size: root.size - -: - id: cpyButton - color: 0,0,0,1 - background_color: (0,0,0,0) - center_x: self.parent.center_x * 2 - self.parent.parent.padding[0]/2 - center_y: self.parent.center_y - on_press:app.root.ids.sc14.copy_composer_text(self) - Image: - source: './images/copy_text.png' - center_x: self.parent.center_x - center_y: self.parent.center_y - size: 20, 20 - - -: - id: popup - size_hint : (None,None) - height: 2*(label.height + address.height) + 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) - title_color: 0.4, 0.3765, 0.3451, 1 - auto_dismiss: False - separator_color: 0.3529, 0.3922, 0.102, 0.7 - BoxLayout: - size_hint_y: 0.5 - orientation: 'vertical' - spacing:dp(20) - id: popup_box - BoxLayout: - orientation: 'vertical' - MDTextField: - id: label - multiline: False - hint_text: "Label" - required: True - helper_text_mode: "on_error" - on_text: root.checkLabel_valid(self) - MDTextField: - id: address - hint_text: "Address" - required: True - helper_text_mode: "on_error" - on_text: root.checkAddress_valid(self) - BoxLayout: - spacing:5 - orientation: 'horizontal' - MDRaisedButton: - id: save_addr - size_hint: 1.5, None - height: dp(40) - on_release: - root.savecontact() - MDLabel: - font_style: 'H6' - text: 'Save' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 1.5, None - height: dp(40) - on_press: root.dismiss() - on_press: root.close_pop() - MDLabel: - font_style: 'H6' - text: 'Cancel' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 2, None - height: dp(40) - MDLabel: - font_style: 'H6' - text: 'Scan QR code' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - -: - id: addbook_popup - size_hint : (None,None) - height: 4*(add_label.height) - 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 - BoxLayout: - size_hint_y: None - spacing:dp(70) - id: addbook_popup_box - orientation: 'vertical' - BoxLayout: - size_hint_y: None - orientation: 'vertical' - spacing:dp(20) - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Label" - font_size: '17sp' - halign: 'left' - MDTextField: - id: add_label - font_style: 'Body1' - font_size: '15sp' - halign: 'left' - text: root.address_label - theme_text_color: 'Primary' - required: True - helper_text_mode: "on_error" - on_text: root.checkLabel_valid(self) - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Address" - font_size: '17sp' - halign: 'left' - MDLabel: - id: address - font_style: 'Body1' - theme_text_color: 'Primary' - text: root.address - font_size: '15sp' - halign: 'left' - BoxLayout: - id: addbook_btn - spacing:5 - orientation: 'horizontal' - MDRaisedButton: - size_hint: 2, None - height: dp(40) - on_press: root.send_message_to() - MDLabel: - font_style: 'H6' - text: 'Send message to' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 1.5, None - height: dp(40) - font_size: '10sp' - on_press: root.update_addbook_label(root.address) - MDLabel: - font_style: 'H6' - text: 'Save' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 1.5, None - height: dp(40) - on_press: root.dismiss() - on_press: root.close_pop() - MDLabel: - font_style: 'H6' - text: 'Cancel' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - - -: - 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 if app.app_platform == 'android' else app.window_size[0]/4) - background: './images/popup.jpeg' - auto_dismiss: False - separator_height: 0 - BoxLayout: - id: myadd_popup_box - size_hint_y: None - spacing:dp(70) - orientation: 'vertical' - BoxLayout: - size_hint_y: None - orientation: 'vertical' - spacing:dp(25) - MDLabel: - id: myaddr_label - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Label" - font_size: '17sp' - halign: 'left' - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: root.address_label - font_size: '15sp' - halign: 'left' - MDLabel: - font_style: 'Subtitle2' - theme_text_color: 'Primary' - text: "Address" - font_size: '17sp' - halign: 'left' - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: root.address - font_size: '15sp' - halign: 'left' - BoxLayout: - id: my_add_btn - spacing:5 - orientation: 'horizontal' - MDRaisedButton: - size_hint: 2, None - height: dp(40) - on_press: root.send_message_from() - MDLabel: - font_style: 'H6' - text: 'Send message from' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 1.5, None - height: dp(40) - on_press: root.dismiss() - on_press: app.root.ids.scr_mngr.current = 'showqrcode' - on_press: app.root.ids.sc15.qrdisplay() - MDLabel: - font_style: 'H6' - text: 'Show QR code' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' - MDRaisedButton: - size_hint: 1.5, None - height: dp(40) - on_press: root.dismiss() - on_press: root.close_pop() - MDLabel: - font_style: 'H6' - text: 'Cancel' - font_size: '13sp' - color: (1,1,1,1) - halign: 'center' \ No newline at end of file diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 5ceecba9..853302c3 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -65,6 +65,12 @@ import state from addresses import decodeAddress +KVFILES = ['settings', 'popup', 'allmails', 'draft', + 'maildetail', 'common_widgets', 'addressbook', + 'myaddress', 'composer', 'payment', 'sent', + 'network', 'login', 'credits', 'trash', 'inbox'] + + def toast(text): """Method will display the toast message""" # pylint: disable=redefined-outer-name @@ -842,8 +848,8 @@ class Random(Screen): nonceTrialsPerByte, payloadLengthExtraBytes)) self.ids.label.text = '' - self.parent.parent.children[1].opacity = 1 - self.parent.parent.children[1].disabled = False + self.parent.parent.ids.toolbar.opacity = 1 + self.parent.parent.ids.toolbar.disabled = False state.kivyapp.loadMyAddressScreen(True) self.manager.current = 'myaddress' Clock.schedule_once(self.address_created_callback, 6) @@ -1290,34 +1296,19 @@ class NavigateApp(MDApp): title = "PyBitmessage" imgstatus = False count = 0 - menu_items = [ - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - {'viewclass': 'MDMenuItem', - 'text': 'Example item'}, - ] def build(self): """Method builds the widget""" - print(os.path.join(os.path.dirname(__file__), 'main.kv')) - main_widget = Builder.load_file( - os.path.join(os.path.dirname(__file__), 'main.kv')) + for kv_file in KVFILES: + Builder.load_file( + os.path.join(os.path.dirname(__file__),f"kv/{kv_file}.kv")) self.obj_1 = AddressBook() kivysignalthread = UIkivySignaler() kivysignalthread.daemon = True kivysignalthread.start() Window.bind(on_keyboard=self.on_key) - return main_widget + return Builder.load_file( + os.path.join(os.path.dirname(__file__), 'main.kv')) def run(self): """Running the widgets""" @@ -1655,10 +1646,11 @@ class NavigateApp(MDApp): def closeSearchScreen(self): """Function for close search screen""" self.set_common_header() - address_label = self.current_address_label( - BMConfigParser().get( - state.association, 'label'), state.association) - self.root.ids.toolbar.title = address_label + if state.association: + address_label = self.current_address_label( + BMConfigParser().get( + state.association, 'label'), state.association) + self.root.ids.toolbar.title = address_label state.searcing_text = '' self.refreshScreen() state.in_search_mode = False @@ -2144,11 +2136,13 @@ class ShowQRCode(Screen): def qrdisplay(self): """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 - self.ids.qr.add_widget(QRCodeWidget( - data=self.manager.get_parent_window().children[0].address)) + try: + address = self.manager.get_parent_window().children[0].address + except Exception as e: + address = self.manager.get_parent_window().children[1].address + self.ids.qr.add_widget(QRCodeWidget(data=address)) toast('Show QR code') @@ -2283,19 +2277,19 @@ class Draft(Screen): def delete_draft(self, data_index, instance, *args): """Delete draft message permanently""" sqlExecute("DELETE FROM sent WHERE ackdata = ?;", data_index) - try: - msg_count_objs = ( - 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) + # try: + # msg_count_objs = ( + # 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) # msg_count_objs = self.parent.parent.parent.parent.parent.children[ # 2].children[0].ids if int(state.draft_count) > 0: - msg_count_objs.draft_cnt.badge_text = str( - int(state.draft_count) - 1) + # 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 = '' From eb98abbabf0998659ae3d5c06b26700a36519214 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Fri, 10 Jan 2020 19:43:59 +0530 Subject: [PATCH 36/54] Code Formatting --- src/network/bmproto.py | 3 --- src/network/connectionpool.py | 35 ------------------------------- src/network/dandelion.py | 8 ------- src/network/downloadthread.py | 7 ------- src/network/httpd.py | 6 ------ src/network/randomtrackingdict.py | 10 +++++---- src/network/stats.py | 22 ------------------- src/network/tcp.py | 2 -- 8 files changed, 6 insertions(+), 87 deletions(-) diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 099dc358..c778118c 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -624,9 +624,6 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return False if self.destination in connectionpool.BMConnectionPool().inboundConnections: try: - # print('+++++++++++++++++++++++++++') - # print('self destination host -{}'.format(self.destination.host)) - # print('++++++++++++++++++++++++++++++') if not protocol.checkSocksIP(self.destination.host): self.append_write_buf(protocol.assembleErrorMessage( errorText="Too many connections from your IP." diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 719c798c..df11c1b3 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -344,21 +344,6 @@ class BMConnectionPool(object): except socket.error as e: if e.errno == errno.ENETUNREACH: continue - # # print('++++++++++++++++++++++++++++++++++++++++++') - # # print('self.inboundConnections.values()-{}'.format(self.inboundConnections.values())) - # # print('self.outboundConnections.values() -{}'.format(self.outboundConnections.values())) - # # print('+++++++++++++++++++++++++++++++++++++++++++') - # else: - - # # for i in ( - # # list(self.inboundConnections.values()) + - # # list(self.outboundConnections.values()) - # # ): - # for i in ( - # [inboundConnections for inboundConnections in self.inboundConnections.values()] + - # [inboundConnections for inboundConnections in self.outboundConnections.values()] - # ): - self._lastSpawned = time.time() else: for i in self.connections(): @@ -377,7 +362,6 @@ class BMConnectionPool(object): self.startListening(bind) logger.info('Listening for incoming connections.') if False: - # self.udpSockets :- {'0.0.0.0': } if BMConfigParser().safeGet('network', 'bind') == '': self.startUDPSocket() else: @@ -407,15 +391,6 @@ class BMConnectionPool(object): reaper = [] - # # for i in ( - # # list(self.inboundConnections.values()) + - # # list(self.outboundConnections.values()) - # # ): - # for i in ( - # [inboundConnections for inboundConnections in self.inboundConnections.values()] + - # [outboundConnections for outboundConnections in self.outboundConnections.values()] - # ): - for i in self.connections(): minTx = time.time() - 20 if i.fullyEstablished: @@ -427,17 +402,7 @@ class BMConnectionPool(object): i.close_reason = "Timeout (%is)" % ( time.time() - i.lastTx) i.set_state("close") - # for i in ( - # list(self.inboundConnections.values()) + - # list(self.outboundConnections.values()) + - # list(self.listeningSockets.values()) + - # 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()] diff --git a/src/network/dandelion.py b/src/network/dandelion.py index ec9384e5..34654c2e 100644 --- a/src/network/dandelion.py +++ b/src/network/dandelion.py @@ -118,14 +118,6 @@ class Dandelion(object): except AttributeError: pass - # for k, v in iter({ - # k: v for k, v in iter([hasmap for hasamp in self.hashMap.items()]) - # if v.child is None - # }).items(): - # self.hashMap[k] = Stem( - # connection, v.stream, self.poissonTimeout()) - # invQueue.put((v.stream, k, v.child)) - def maybeRemoveStem(self, connection): """ Remove current connection from the stem list (called e.g. when diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index 6e1f9ca8..0ed89f9c 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -41,13 +41,6 @@ class DownloadThread(StoppableThread): def run(self): while not self._stopped: requested = 0 - # Choose downloading peers randomly - # connections = [ - # x for x in - # list(BMConnectionPool().inboundConnections.values()) + - # list(BMConnectionPool().outboundConnections.values()) - # if x.fullyEstablished] - connections = BMConnectionPool().establishedConnections() helper_random.randomshuffle(connections) requestChunk = max(int( diff --git a/src/network/httpd.py b/src/network/httpd.py index 1679f864..b92adbd7 100644 --- a/src/network/httpd.py +++ b/src/network/httpd.py @@ -130,10 +130,7 @@ class HTTPServer(asyncore.dispatcher): pair = self.accept() if pair is not None: sock, _ = pair - # print 'Incoming connection from %s' % repr(addr) self.connections += 1 - # if self.connections % 1000 == 0: - # print "Processed %i connections, active %i" % (self.connections, len(asyncore.socket_map)) HTTPRequestHandler(sock) @@ -149,10 +146,7 @@ class HTTPSServer(HTTPServer): pair = self.accept() if pair is not None: sock, _ = pair - # print 'Incoming connection from %s' % repr(addr) self.connections += 1 - # if self.connections % 1000 == 0: - # print "Processed %i connections, active %i" % (self.connections, len(asyncore.socket_map)) HTTPSRequestHandler(sock) diff --git a/src/network/randomtrackingdict.py b/src/network/randomtrackingdict.py index c5c460b4..1e81d3ad 100644 --- a/src/network/randomtrackingdict.py +++ b/src/network/randomtrackingdict.py @@ -14,10 +14,12 @@ class RandomTrackingDict(object): """ Dict with randomised order and tracking. - Keeps a track of how many items have been requested from the dict, and timeouts. Resets after all objects have been - retrieved and timed out. The main purpose of this isn't as much putting related code together as performance - optimisation and anonymisation of downloading of objects from other peers. If done using a standard dict or array, - it takes too much CPU (and looks convoluted). Randomisation helps with anonymity. + Keeps a track of how many items have been requested from the dict, and timeouts. + Resets after all objects have been retrieved and timed out. + The main purpose of this isn't as much putting related code together + as performance optimisation and anonymisation of downloading of objects from other peers. + If done using a standard dict or array, it takes too much CPU (and looks convoluted). + Randomisation helps with anonymity. """ # pylint: disable=too-many-instance-attributes maxPending = 10 diff --git a/src/network/stats.py b/src/network/stats.py index 8ce18226..caab3c19 100644 --- a/src/network/stats.py +++ b/src/network/stats.py @@ -19,21 +19,6 @@ currentSentSpeed = 0 def connectedHostsList(): """List of all the connected hosts""" - # retval = [] - # # for i in list(BMConnectionPool().inboundConnections.values()) + \ - # # list(BMConnectionPool().outboundConnections.values()): - - # outBoundConnections = [outConnection for outConnection in BMConnectionPool().outboundConnections.values()] - # inBoundConnections = [inConnection for inConnection in BMConnectionPool().inboundConnections.values()] - # for i in outBoundConnections+inBoundConnections: - # if not i.fullyEstablished: - # continue - # try: - # retval.append(i) - # except AttributeError: - # pass - - # return retval return BMConnectionPool().establishedConnections() @@ -81,11 +66,4 @@ def pendingDownload(): def pendingUpload(): """Getting pending uploads""" - # tmp = {} - # for connection in BMConnectionPool().inboundConnections.values() + \ - # BMConnectionPool().outboundConnections.values(): - # for k in connection.objectsNewToThem.keys(): - # tmp[k] = True - # This probably isn't the correct logic so it's disabled - # return len(tmp) return 0 diff --git a/src/network/tcp.py b/src/network/tcp.py index 586dedd6..dbf544d8 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -94,8 +94,6 @@ class TCPConnection(BMProto, TLSDispatcher): self.network_group = protocol.network_group(self.destination.host) ObjectTracker.__init__(self) # pylint: disable=non-parent-init-called self.bm_proto_reset() - # print('--------------tcp------------------') - # from network import stats self.set_state("bm_header", expectBytes=protocol.Header.size) def antiIntersectionDelay(self, initial=False): From 882aa9d9701730bab08abb434731677fd873d6f9 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Fri, 10 Jan 2020 19:52:17 +0530 Subject: [PATCH 37/54] remove useless code --- src/network/bmproto.py | 13 +------------ src/network/connectionpool.py | 1 - src/network/tcp.py | 2 -- src/network/tls.py | 8 -------- src/network/udp.py | 4 ---- 5 files changed, 1 insertion(+), 27 deletions(-) diff --git a/src/network/bmproto.py b/src/network/bmproto.py index c778118c..698f6df9 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -105,20 +105,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker): count += 1 if self.command == 'verack'.encode(): addr_verack += 1 - # print('the addr_verack count are -{}'.format(addr_verack)) - if self.command == 'version'.encode(): addr_version += 1 - # print('the addr_version count are -{}'.format(addr_version)) - if self.command == 'addr'.encode(): addr_count += 1 - # print('the addr_count count are -{}'.format(addr_count)) - if self.magic != 0xE9BEB4D9: - # skip 1 byte in order to sync - # in the advancedispatched and length commend's - # escape the 1 length self.set_state("bm_header", length=1) self.bm_proto_reset() logger.debug('Bad magic') @@ -186,7 +177,6 @@ class BMProto(AdvancedDispatcher, ObjectTracker): self.set_state("close") return False if retval: - # print('if retval is true and inside the if ') self.set_state("bm_header", length=self.payloadLength) self.bm_proto_reset() # else assume the command requires a different state to follow @@ -451,7 +441,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash): Dandelion().removeHash(self.object.inventoryHash, "cycle detection") - [self.object.inventoryHash] = ( + Inventory()[self.object.inventoryHash] = ( self.object.objectType, self.object.streamNumber, memoryview(self.payload[objectOffset:]), self.object.expiresTime, memoryview(self.object.tag) @@ -539,7 +529,6 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return False def bm_command_version(self): - # print('inside the bmproto ') """ Incoming version. Parse and log, remember important things, like streams, bitfields, etc. diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index df11c1b3..bbb09d7e 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -195,7 +195,6 @@ class BMConnectionPool(object): port = int(BMConfigParser().safeGet("bitmessagesettings", "port")) # correct port even if it changed ls = TCPServer(host=bind, port=port) - print('inside the startListening method') self.listeningSockets[ls.destination] = ls def startUDPSocket(self, bind=None): diff --git a/src/network/tcp.py b/src/network/tcp.py index dbf544d8..5cf96c6d 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -150,7 +150,6 @@ class TCPConnection(BMProto, TLSDispatcher): )) self.antiIntersectionDelay(True) self.fullyEstablished = True - # print('inside the set_connection_fully_established in tcp file') if self.isOutbound: knownnodes.increaseRating(self.destination) Dandelion().maybeAddStem(self) @@ -378,7 +377,6 @@ class TCPServer(AdvancedDispatcher): self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() for attempt in range(50): - print('inside the attempt of line 371') try: if attempt > 0: logger.warning('Failed to bind on port %s', port) diff --git a/src/network/tls.py b/src/network/tls.py index 08969227..040f5e4f 100644 --- a/src/network/tls.py +++ b/src/network/tls.py @@ -68,7 +68,6 @@ class TLSDispatcher(AdvancedDispatcher): self.isSSL = False def state_tls_init(self): - # print() """Prepare sockets for TLS handshake""" # pylint: disable=attribute-defined-outside-init self.isSSL = True @@ -95,9 +94,7 @@ class TLSDispatcher(AdvancedDispatcher): ciphers=self.ciphers, do_handshake_on_connect=False) self.sslSocket.setblocking(0) self.want_read = self.want_write = True - # print('before tls file python 98 state are :- {}'.format(self.state)) self.set_state("tls_handshake") - # print('after tls file python 100 state are :- {}'.format(self.state)) return False # if hasattr(self.socket, "context"): # self.socket.context.set_ecdh_curve("secp256k1") @@ -186,23 +183,18 @@ class TLSDispatcher(AdvancedDispatcher): return def tls_handshake(self): - # print('inside the tls_handshake') """Perform TLS handshake and handle its stages""" # wait for flush if self.write_buf: return False # Perform the handshake. try: - # print "handshaking (internal)" self.sslSocket.do_handshake() except ssl.SSLError as err: - # print "%s:%i: handshake fail" % (self.destination.host, self.destination.port) self.want_read = self.want_write = False if err.args[0] == ssl.SSL_ERROR_WANT_READ: - # print "want read" self.want_read = True if err.args[0] == ssl.SSL_ERROR_WANT_WRITE: - # print "want write" self.want_write = True if not (self.want_write or self.want_read): raise diff --git a/src/network/udp.py b/src/network/udp.py index d3421806..6f796331 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -65,19 +65,15 @@ class UDPSocket(BMProto): # pylint: disable=too-many-instance-attributes # only addr (peer discovery), error and object are implemented def bm_command_getdata(self): - # return BMProto.bm_command_getdata(self) return True def bm_command_inv(self): - # return BMProto.bm_command_inv(self) return True def bm_command_addr(self): addresses = self._decode_addr() # only allow peer discovery from private IPs in order to avoid # attacks from random IPs on the internet - # if not self.local: - # return True self.local = True remoteport = False for seenTime, stream, services, ip, port in addresses: From 480fc9b2e896fd97ea3deabf605c959fc84e2295 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Fri, 10 Jan 2020 21:10:10 +0530 Subject: [PATCH 38/54] Fixed Inventory issue --- src/network/bmproto.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 698f6df9..e56b2963 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -441,7 +441,7 @@ 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, memoryview(self.payload[objectOffset:]), self.object.expiresTime, memoryview(self.object.tag) From 1033e7eb34948b31075cf6328c383b80f08c445a Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Wed, 15 Jan 2020 13:44:30 +0530 Subject: [PATCH 39/54] Solved BMConfigParser's safeGetInt method issues --- src/bmconfigparser.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 3293c5b3..a5574156 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -99,13 +99,11 @@ class BMConfigParser(configparser.ConfigParser): def safeGetInt(self, section, field, default=0): """Return value as integer, default on exceptions, 0 if default missing""" - config = configparser.ConfigParser() - try: # Used in the python2.7 # return self.getint(section, field) - # Used in the python3.5.2 - return config.getint(section, field) + # Used in the python3.7.0 + return int(self.get(section, field)) except (configparser.NoSectionError, configparser.NoOptionError, ValueError, AttributeError): return default From 8e6c2f3cfd80ebe438adde26ae17736c4e157246 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Sat, 18 Jan 2020 17:13:06 +0530 Subject: [PATCH 40/54] Kivy database and safegetint issues --- src/bitmessagekivy/mpybit.py | 6 +++--- src/class_addressGenerator.py | 9 ++------- src/knownnodes.py | 13 +++++++++---- src/network/bmproto.py | 2 +- src/network/connectionpool.py | 10 +++++----- src/shared.py | 2 +- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 853302c3..865fc780 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -647,8 +647,8 @@ class DropDownWidget(BoxLayout): 0, 'sent', encoding, - int(BMConfigParser().safeGet( - 'bitmessagesettings', 'ttl'))) + BMConfigParser().safeGetInt( + 'bitmessagesettings', 'ttl')) state.check_sent_acc = fromAddress # state.msg_counter_objs = self.parent.parent.parent.parent\ # .parent.parent.children[2].children[0].ids @@ -2331,7 +2331,7 @@ class Draft(Screen): 0, 'draft', encoding, - int(BMConfigParser().safeGet('bitmessagesettings', 'ttl'))) + BMConfigParser().safeGetInt('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() diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index 1f60e051..179ba349 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -116,9 +116,7 @@ class addressGenerator(StoppableThread): payloadLengthExtraBytes = \ defaults.networkDefaultPayloadLengthExtraBytes if command == 'createRandomAddress': - queues.UISignalQueue.put(( - 'updateStatusBar' - )) + queues.UISignalQueue.put(('updateStatusBar', None)) # This next section is a little bit strange. We're going # to generate keys over and over until we find one # that starts with either \x00 or \x00\x00. Then when @@ -192,10 +190,7 @@ class addressGenerator(StoppableThread): # The API and the join and create Chan functionality # both need information back from the address generator. queues.apiAddressGeneratorReturnQueue.put(address) - - queues.UISignalQueue.put(( - 'updateStatusBar' - )) + queues.UISignalQueue.put(('updateStatusBar', None)) queues.UISignalQueue.put(('writeNewAddressToTable', ( label, address, streamNumber))) shared.reloadMyAddressHashes() diff --git a/src/knownnodes.py b/src/knownnodes.py index c1d56ccc..f8007bb6 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -49,9 +49,14 @@ def json_serialize_knownnodes(output): for stream, peers in iter(knownNodes.items()): for peer, info in iter(peers.items()): info.update(rating=round(info.get('rating', 0), 2)) - _serialized.append({ - 'stream': stream, 'peer': peer._asdict(), 'info': info - }) + if type(peer[0]) != bytes: + _serialized.append({'stream': stream, 'peer': peer._asdict(), 'info': info}) + else: + from collections import OrderedDict + _serialized.append({ + 'stream': stream, + 'peer': OrderedDict({'host': str(peer[0].decode()), 'port': int(peer[1])}), + 'info': info}) json.dump(_serialized, output, indent=4) @@ -171,7 +176,7 @@ def decreaseRating(peer): def trimKnownNodes(recAddrStream=1): """Triming Knownnodes""" if len(knownNodes[recAddrStream]) < \ - int(BMConfigParser().safeGet("knownnodes", "maxnodes")): + BMConfigParser().safeGetInt("knownnodes", "maxnodes"): return with knownNodesLock: oldestList = sorted( diff --git a/src/network/bmproto.py b/src/network/bmproto.py index a5da6b86..5c57748a 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -480,7 +480,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): continue except KeyError: pass - if len(knownnodes.knownNodes[stream]) < int(BMConfigParser().safeGet("knownnodes", "maxnodes")): + if len(knownnodes.knownNodes[stream]) < BMConfigParser().safeGetInt("knownnodes", "maxnodes"): with knownnodes.knownNodesLock: try: knownnodes.knownNodes[stream][peer]["lastseen"] = \ diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index bbb09d7e..82bf20a5 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -192,7 +192,7 @@ class BMConnectionPool(object): if bind is None: "this return blank host" bind = self.getListeningIP() - port = int(BMConfigParser().safeGet("bitmessagesettings", "port")) + port = BMConfigParser().safeGetInt("bitmessagesettings", "port") # correct port even if it changed ls = TCPServer(host=bind, port=port) self.listeningSockets[ls.destination] = ls @@ -274,8 +274,8 @@ class BMConnectionPool(object): Proxy.proxy = ( BMConfigParser().safeGet( 'bitmessagesettings', 'sockshostname'), - int(BMConfigParser().safeGet( - 'bitmessagesettings', 'socksport')) + BMConfigParser().safeGetInt( + 'bitmessagesettings', 'socksport') ) # TODO AUTH # TODO reset based on GUI settings changes @@ -294,8 +294,8 @@ class BMConnectionPool(object): 1 for c in [outboundConnections for outboundConnections in self.outboundConnections.values()] if (c.connected and c.fullyEstablished)) pending = len(self.outboundConnections) - established - if established < int(BMConfigParser().safeGet( - 'bitmessagesettings', 'maxoutboundconnections')): + if established < BMConfigParser().safeGetInt( + 'bitmessagesettings', 'maxoutboundconnections'): for i in range( state.maximumNumberOfHalfOpenConnections - pending): try: diff --git a/src/shared.py b/src/shared.py index 98f47d19..b1a19c08 100644 --- a/src/shared.py +++ b/src/shared.py @@ -241,7 +241,7 @@ def checkSensitiveFilePermissions(filename): shell=True, stderr=subprocess.STDOUT ) - if 'fuseblk' in fstype: + if 'fuseblk'.encode() in fstype: logger.info( 'Skipping file permissions check for %s.' ' Filesystem fuseblk detected.', filename) From 9dc3b3df129a969ae3a8dc02daf513e46b0cefa8 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Fri, 17 Jan 2020 19:39:26 +0530 Subject: [PATCH 41/54] Display popup on close window --- src/bitmessagekivy/mpybit.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 865fc780..32da1526 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1306,7 +1306,7 @@ class NavigateApp(MDApp): kivysignalthread = UIkivySignaler() kivysignalthread.daemon = True kivysignalthread.start() - Window.bind(on_keyboard=self.on_key) + Window.bind(on_keyboard=self.on_key, on_request_close=self.on_request_closee) return Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) @@ -1748,6 +1748,23 @@ class NavigateApp(MDApp): except Exception: self.root.ids.sc17.children[0].children[1].active = False + def on_request_closee(self, *args): + box = BoxLayout(orientation='vertical') + box.add_widget(Label( + text=( + "Bitmessage isn't connected to the network.\n" + "If you quit now, it may cause delivery delays.\n" + "Wait until connected and the synchronisation finishes?"))) + mybutton = Button(text='Yes', size_hint=(1, 0.50)) + box.add_widget(mybutton) + mybutton2 = Button(text='No', size_hint=(1, 0.50)) + box.add_widget(mybutton2) + mybutton3 = Button(text='Cancel', size_hint=(1, 0.50)) + box.add_widget(mybutton3) + popup = Popup(title="Window close", content=box, size_hint=(None, None), size=(500, 300)) + popup.open() + return True + class GrashofPopup(Popup): """Moule for save contacts and error messages""" From 13dcac299476e666d0dfbb7405a39ec7f9d7a7b4 Mon Sep 17 00:00:00 2001 From: navjot Date: Sat, 18 Jan 2020 16:01:50 +0530 Subject: [PATCH 42/54] wokred on implementing dynamic address logo feature --- src/bitmessagekivy/identiconGeneration.py | 2 +- src/bitmessagekivy/kv/allmails.kv | 7 - src/bitmessagekivy/kv/common_widgets.kv | 3 + src/bitmessagekivy/kv/composer.kv | 16 +- src/bitmessagekivy/kv/login.kv | 3 + src/bitmessagekivy/kv/popup.kv | 9 + src/bitmessagekivy/main.kv | 39 +++- src/bitmessagekivy/mpybit.py | 211 +++++++++++++--------- src/state.py | 2 - 9 files changed, 185 insertions(+), 107 deletions(-) diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index faa72013..0f8c4203 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -12,7 +12,7 @@ from kivy.uix.image import Image as kiImage # constants -RESOLUTION = 128, 128 +RESOLUTION = 300, 300 V_RESOLUTION = 7, 7 BACKGROUND_COLOR = 255, 255, 255, 255 MODE = "RGB" diff --git a/src/bitmessagekivy/kv/allmails.kv b/src/bitmessagekivy/kv/allmails.kv index 4f099564..a0514a48 100644 --- a/src/bitmessagekivy/kv/allmails.kv +++ b/src/bitmessagekivy/kv/allmails.kv @@ -1,12 +1,5 @@ : name: 'allmails' - #FloatLayout: - # MDScrollViewRefreshLayout: - # id: refresh_layout - # refresh_callback: root.refresh_callback - # root_layout: root.set_root_layout() - # MDList: - # id: ml BoxLayout: orientation: 'vertical' spacing: dp(5) diff --git a/src/bitmessagekivy/kv/common_widgets.kv b/src/bitmessagekivy/kv/common_widgets.kv index 2c041178..79ed3219 100644 --- a/src/bitmessagekivy/kv/common_widgets.kv +++ b/src/bitmessagekivy/kv/common_widgets.kv @@ -16,6 +16,9 @@ id: search_field hint_text: 'Search' on_text: app.searchQuery(self) + canvas.before: + Color: + rgba: (0,0,0,1) : id: spinner diff --git a/src/bitmessagekivy/kv/composer.kv b/src/bitmessagekivy/kv/composer.kv index 51cf7dc4..25bdae7e 100644 --- a/src/bitmessagekivy/kv/composer.kv +++ b/src/bitmessagekivy/kv/composer.kv @@ -8,7 +8,7 @@ spacing: 15 BoxLayout: orientation: 'vertical' - MDTextField: + MyMDTextField: id: ti hint_text: 'type or select sender address' size_hint_y: None @@ -21,7 +21,7 @@ BoxLayout: size_hint_y: None height: dp(40) - Spinner: + CustomSpinner: id: btn background_color: app.theme_cls.primary_dark values: app.variable_1 @@ -46,7 +46,7 @@ hint_text: 'type, select or scan QR code for recipients address' RV: id: rv - MDTextField: + MyMDTextField: id: subject hint_text: 'subject' required: True @@ -56,7 +56,7 @@ multiline: False helper_text_mode: "on_error" - MDTextField: + MyMDTextField: id: body multiline: True hint_text: 'body' @@ -98,4 +98,10 @@ size_hint_y: None height: self.minimum_height orientation: 'vertical' - multiselect: False \ No newline at end of file + multiselect: False + + +: + canvas.before: + Color: + rgba: (0,0,0,1) \ No newline at end of file diff --git a/src/bitmessagekivy/kv/login.kv b/src/bitmessagekivy/kv/login.kv index 60d24f7f..c668ebd1 100644 --- a/src/bitmessagekivy/kv/login.kv +++ b/src/bitmessagekivy/kv/login.kv @@ -89,6 +89,9 @@ required: True helper_text_mode: "on_error" on_text: root.add_validation(self) + canvas.before: + Color: + rgba: (0,0,0,1) BoxLayout: AnchorLayout: MDRaisedButton: diff --git a/src/bitmessagekivy/kv/popup.kv b/src/bitmessagekivy/kv/popup.kv index 093e06a6..52720bb1 100644 --- a/src/bitmessagekivy/kv/popup.kv +++ b/src/bitmessagekivy/kv/popup.kv @@ -37,12 +37,18 @@ required: True helper_text_mode: "on_error" on_text: root.checkLabel_valid(self) + canvas.before: + Color: + rgba: (0,0,0,1) MDTextField: id: address hint_text: "Address" required: True helper_text_mode: "on_error" on_text: root.checkAddress_valid(self) + canvas.before: + Color: + rgba: (0,0,0,1) BoxLayout: spacing:5 orientation: 'horizontal' @@ -112,6 +118,9 @@ required: True helper_text_mode: "on_error" on_text: root.checkLabel_valid(self) + canvas.before: + Color: + rgba: (0,0,0,1) MDLabel: font_style: 'Subtitle2' theme_text_color: 'Primary' diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 0cc6f1a3..1ecf10e3 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -29,12 +29,26 @@ color: color_font - theme_text_color: 'Custom' - divider: None + on_press: root.active = not root.active + active_color: root.theme_cls.primary_color if root.active else root.theme_cls.text_color IconLeftWidget: icon: root.icon + theme_text_color: "Custom" + text_color: root.active_color + BadgeText: + text: f"{root.badge_text}" + theme_text_color: "Custom" + text_color: root.active_color + halign: 'right' + +: + canvas: + Color: + rgba: self.theme_cls.divider_color + Line: + points: root.x, root.y + dp(8), root.x + self.width, root.y + dp(8) @@ -53,7 +67,8 @@ x: root.parent.x pos_hint: {"top": 1} Image: - source: './images/drawer_logo1.png' + #source: './images/drawer_logo1.png' + source: app.get_default_logo() ScrollView: pos_hint: {"top": 1} @@ -63,12 +78,15 @@ cols: 1 size_hint_y: None height: self.minimum_height + NavigationDrawerDivider: + NavigationDrawerSubheader: + text: "Accounts" NavigationItem: - Spinner: + CustomSpinner: id: btn - pos_hint:{"x":0,"y":.1} + pos_hint:{"x":0,"y":0} option_cls: Factory.get("MySpinnerOption") - font_size: '11.9sp' + font_size: '10.9sp' text: app.getDefaultAccData() background_color: color_button if self.state == 'normal' else color_button_pressed background_down: 'atlas://data/images/defaulttheme/spinner' @@ -82,38 +100,45 @@ size: self.parent.height/2, self.parent.height/2 ArrowImg: NavigationItem: + id: inbox_cnt text: 'Inbox' icon: 'email-open' divider: None - badge_text: "0" on_release: app.root.ids.scr_mngr.current = 'inbox' on_release: root.parent.toggle_nav_drawer() on_press: app.load_screen(self) NavigationItem: + id: send_cnt text: 'Sent' icon: 'send' divider: None on_release: app.root.ids.scr_mngr.current = 'sent' on_release: root.parent.toggle_nav_drawer() NavigationItem: + id: draft_cnt text: 'Draft' icon: 'message-draw' divider: None on_release: app.root.ids.scr_mngr.current = 'draft' on_release: root.parent.toggle_nav_drawer() NavigationItem: + id: trash_cnt text: 'Trash' icon: 'delete' divider: None on_release: app.root.ids.scr_mngr.current = 'trash' on_release: root.parent.toggle_nav_drawer() NavigationItem: + id: allmail_cnt text: 'All Mails' icon: 'contact-mail' divider: None on_release: app.root.ids.scr_mngr.current = 'allmails' on_release: root.parent.toggle_nav_drawer() on_press: app.load_screen(self) + NavigationDrawerDivider: + NavigationDrawerSubheader: + text: "All labels" NavigationItem: text: 'Address Book' icon: 'book-multiple' diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 32da1526..40fa3b4d 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -16,6 +16,7 @@ from kivy.clock import Clock from kivy.core.clipboard import Clipboard from kivy.core.window import Window from kivy.lang import Builder +from kivy.metrics import dp from kivy.properties import ( BooleanProperty, ListProperty, @@ -49,7 +50,10 @@ from kivymd.uix.list import ( TwoLineListItem, OneLineIconListItem, OneLineAvatarListItem, - IRightBody + IRightBody, + OneLineAvatarIconListItem, + IRightBodyTouch, + OneLineListItem ) # from kivymd.uix.navigationdrawer import ( # MDNavigationDrawer, @@ -79,6 +83,11 @@ def toast(text): return +def showLimitedCnt(total_msg): + """This method set the total count limit in badge_text""" + return "99+" if total_msg > 99 else str(total_msg) + + class Inbox(Screen): """Inbox Screen uses screen to show widgets of screens""" @@ -115,8 +124,7 @@ class Inbox(Screen): self.inboxDataQuery(xAddress, where, what) if self.queryreturn: state.kivyapp.get_inbox_count() - # src_mng_obj = state.kivyapp.root.children[2].children[0].ids - # src_mng_obj.inbox_cnt.badge_text = state.inbox_count + self.set_inboxCount(state.inbox_count) for mail in self.queryreturn: # third_text = mail[3].replace('\n', ' ') data.append({ @@ -130,6 +138,7 @@ class Inbox(Screen): self.children[2].children[0].children[0].bind( scroll_y=self.check_scroll_y) else: + self.set_inboxCount('0') content = MDLabel( font_style='Caption', theme_text_color='Primary', @@ -140,8 +149,13 @@ class Inbox(Screen): valign='top') self.ids.ml.add_widget(content) + def set_inboxCount(self, msgCnt): + """This method is used to sent inbox message count""" + src_mng_obj = state.kivyapp.root.ids.content_drawer.ids.inbox_cnt + src_mng_obj.children[0].children[0].text = showLimitedCnt(int(msgCnt)) + def inboxDataQuery(self, xAddress, where, what, start_indx=0, end_indx=20): - """This method used for retrieving inbox data""" + """This method is used for retrieving inbox data""" self.queryreturn = kivy_helper_search.search_sql( xAddress, self.account, @@ -245,12 +259,9 @@ class Inbox(Screen): self.parent.parent.parent.parent.parent.children[ 2].children[0].ids) if int(state.inbox_count) > 0: - msg_count_objs.inbox_cnt.badge_text = str( - int(state.inbox_count) - 1) - msg_count_objs.trash_cnt.badge_text = str( - int(state.trash_count) + 1) - msg_count_objs.allmail_cnt.badge_text = str( - int(state.all_count) - 1) + msg_count_objs.inbox_cnt.badge_text = showLimitedCnt(int(state.inbox_count) - 1) + msg_count_objs.trash_cnt.badge_text = showLimitedCnt(int(state.trash_count) + 1) + msg_count_objs.allmail_cnt.badge_text = showLimitedCnt(int(state.all_count) - 1) state.inbox_count = str( int(state.inbox_count) - 1) state.trash_count = str( @@ -295,10 +306,6 @@ class Inbox(Screen): Clock.schedule_once(refresh_callback, 1) - # def set_root_layout(self): - # """Setting root layout""" - # return self.parent.parent.parent - class MyAddress(Screen): """MyAddress screen uses screen to show widgets of screens""" @@ -586,7 +593,7 @@ class DropDownWidget(BoxLayout): fromAddress = str(self.ids.ti.text) toAddress = str(self.ids.txt_input.text) subject = self.ids.subject.text.strip() - message = self.ids.subject.text.strip() + message = self.ids.body.text.strip() encoding = 3 print("message: ", self.ids.body.text) sendMessageToPeople = True @@ -929,6 +936,7 @@ class Sent(Screen): self.has_refreshed = True self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: + self.set_sentCount('0') content = MDLabel( font_style='Caption', theme_text_color='Primary', @@ -1043,8 +1051,8 @@ class Sent(Screen): @staticmethod def set_sentCount(total_sent): """Set the total no. of sent message count""" - # src_mng_obj = state.kivyapp.root.children[2].children[0].ids - # src_mng_obj.send_cnt.badge_text = str(total_sent) + src_mng_obj = state.kivyapp.root.ids.content_drawer.ids.send_cnt + src_mng_obj.children[0].children[0].text = showLimitedCnt(int(total_sent)) state.sent_count = str(total_sent) def sent_detail(self, ackdata, *args): @@ -1061,19 +1069,11 @@ class Sent(Screen): def delete(self, data_index, instance, *args): """Delete sent mail from sent mail listing""" - # try: - # msg_count_objs = self.parent.parent.parent.parent.children[ - # 2].children[0].ids - # except Exception: - # msg_count_objs = self.parent.parent.parent.parent.parent.children[ - # 2].children[0].ids + msg_count_objs = self.parent.parent.ids.content_drawer.ids if int(state.sent_count) > 0: - # msg_count_objs.send_cnt.badge_text = str( - # int(state.sent_count) - 1) - # msg_count_objs.trash_cnt.badge_text = str( - # int(state.trash_count) + 1) - # msg_count_objs.allmail_cnt.badge_text = str( - # int(state.all_count) - 1) + msg_count_objs.send_cnt.children[0].children[0].text = showLimitedCnt(int(state.sent_count) - 1) + msg_count_objs.trash_cnt.children[0].children[0].text = showLimitedCnt(int(state.trash_count) + 1) + msg_count_objs.allmail_cnt.children[0].children[0].text = showLimitedCnt(int(state.all_count) - 1) 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) @@ -1132,9 +1132,11 @@ class Trash(Screen): 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_TrashCnt(state.trash_count) self.set_mdList() self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: + self.set_TrashCnt('0') content = MDLabel( font_style='Caption', theme_text_color='Primary', @@ -1158,6 +1160,11 @@ class Trash(Screen): " ORDER BY actionTime DESC limit {1}, {2}".format( state.association, start_indx, end_indx)) + def set_TrashCnt(self, Count): + """This method is used to set trash message count""" + trashCnt_obj = state.kivyapp.root.ids.content_drawer.ids.trash_cnt + trashCnt_obj.children[0].children[0].text = showLimitedCnt(int(Count)) + def set_mdList(self): """This method is used to create the mdlist""" total_trash_msg = len(self.ids.ml.children) @@ -1247,10 +1254,10 @@ class Trash(Screen): elif self.table_name == 'sent': 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( # int(state.trash_count) - 1) + self.set_TrashCnt(int(state.trash_count) - 1) state.trash_count = str(int(state.trash_count) - 1) Clock.schedule_once(self.callback_for_screen_load, 1) @@ -1410,6 +1417,14 @@ class NavigateApp(MDApp): BMConfigParser().addresses()[0]) return './images/no_identicons.png' + @staticmethod + def get_default_logo(): + """Getting default logo image""" + if BMConfigParser().addresses(): + return './images/default_identicon/{}.png'.format( + BMConfigParser().addresses()[0]) + return './images/drawer_logo1.png' + @staticmethod def addressexist(): """Checking address existence""" @@ -1693,9 +1708,9 @@ class NavigateApp(MDApp): def set_identicon(self, text): """Show identicon in address spinner""" img = identiconGeneration.generate(text) - # self.root.children[2].children[0].ids.btn.children[1].texture = ( - # img.texture) - self.root.children[0].children[0].ids.btn.texture = (img.texture) + self.root.children[0].children[0].ids.btn.children[1].texture = (img.texture) + #below line is for displaing logo + self.root.ids.content_drawer.ids.top_box.children[0].texture = (img.texture) def set_mail_detail_header(self): """Setting the details of the page""" @@ -1942,14 +1957,10 @@ class MailDetail(Screen): self.message = data[0][3] if len(data[0]) == 6: self.status = data[0][4] - state.write_msg = {'to_addr': self.to_addr, - 'from_addr': self.from_addr, - 'subject': self.subject, - 'message': self.message} def delete_mail(self): """Method for mail delete""" - msg_count_objs = state.kivyapp.root.children[2].children[0].ids + msg_count_objs = state.kivyapp.root.ids.content_drawer.ids state.searcing_text = '' self.children[0].children[0].active = True if state.detailPageType == 'sent': @@ -1958,7 +1969,7 @@ class MailDetail(Screen): sqlExecute( "UPDATE sent SET folder = 'trash' WHERE" " ackdata = ?;", state.mail_id) - # msg_count_objs.send_cnt.badge_text = str(int(state.sent_count) - 1) + msg_count_objs.send_cnt.children[0].children[0].text = str(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1) self.parent.screens[3].ids.ml.clear_widgets() self.parent.screens[3].loadSent(state.association) @@ -1970,25 +1981,25 @@ class MailDetail(Screen): sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE" " msgid = ?;", state.mail_id) - # msg_count_objs.inbox_cnt.badge_text = str( - # int(state.inbox_count) - 1) + msg_count_objs.inbox_cnt.children[0].children[0].text = str( + int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1) self.parent.screens[0].ids.ml.clear_widgets() self.parent.screens[0].loadMessagelist(state.association) elif state.detailPageType == 'draft': sqlExecute("DELETE FROM sent WHERE ackdata = ?;", state.mail_id) - # msg_count_objs.draft_cnt.badge_text = str( - # int(state.draft_count) - 1) + msg_count_objs.draft_cnt.children[0].children[0].text = str( + int(state.draft_count) - 1) state.draft_count = str(int(state.draft_count) - 1) self.parent.screens[15].clear_widgets() self.parent.screens[15].add_widget(Draft()) if state.detailPageType != 'draft': - # msg_count_objs.trash_cnt.badge_text = str( - # int(state.trash_count) + 1) - # msg_count_objs.allmail_cnt.badge_text = str( - # int(state.all_count) - 1) + msg_count_objs.trash_cnt.children[0].children[0].text = str( + int(state.trash_count) + 1) + msg_count_objs.allmail_cnt.children[0].children[0].text = str( + int(state.all_count) - 1) state.trash_count = str(int(state.trash_count) + 1) state.all_count = str(int(state.all_count) - 1) self.parent.screens[4].clear_widgets() @@ -2024,16 +2035,16 @@ class MailDetail(Screen): def write_msg(self, navApp): """Write on draft mail""" state.send_draft_mail = state.mail_id - # composer_ids = ( - # self.parent.parent.parent.parent.parent.ids.sc3.children[1].ids) + data = sqlQuery( + "select toaddress, fromaddress, subject, message from sent where" + " ackdata = ?;", state.mail_id) composer_ids = ( self.parent.parent.ids.sc3.children[1].ids) - composer_ids.ti.text = state.write_msg['from_addr'] - composer_ids.btn.text = state.write_msg['from_addr'] - composer_ids.txt_input.text = state.write_msg['to_addr'] - composer_ids.subject.text = state.write_msg[ - 'subject'] if state.write_msg['subject'] != '(no subject)' else '' - composer_ids.body.text = state.write_msg['message'] + composer_ids.ti.text = data[0][1] + composer_ids.btn.text = data[0][1] + composer_ids.txt_input.text = data[0][0] + composer_ids.subject.text = data[0][2] if data[0][2] != '(no subject)' else '' + composer_ids.body.text = data[0][3] self.parent.current = 'create' navApp.set_navbar_for_composer() @@ -2195,15 +2206,14 @@ class Draft(Screen): 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)) + state.msg_counter_objs.draft_cnt.children[0].children[0].text = showLimitedCnt(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_draftCnt(state.draft_count) self.set_mdList() self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: + self.set_draftCnt('0') content = MDLabel( font_style='Caption', theme_text_color='Primary', @@ -2225,6 +2235,11 @@ class Draft(Screen): start_indx, end_indx) + def set_draftCnt(self, Count): + """This method set the count of draft mails""" + draftCnt_obj = state.kivyapp.root.ids.content_drawer.ids.draft_cnt + draftCnt_obj.children[0].children[0].text = showLimitedCnt(int(Count)) + def set_mdList(self): """This method is used to create mdlist""" data = [] @@ -2308,6 +2323,7 @@ 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) + self.set_draftCnt(state.draft_count) if int(state.draft_count) <= 0: self.ids.identi_tag.children[0].text = '' self.ids.ml.remove_widget(instance.parent.parent) @@ -2398,12 +2414,12 @@ class Allmails(Screen): state.kivyapp.get_sent_count() state.all_count = str( int(state.sent_count) + int(state.inbox_count)) - # state.kivyapp.root.children[2].children[ - # 0].ids.allmail_cnt.badge_text = state.all_count + self.set_AllmailCnt(state.all_count) self.set_mdlist() # self.ids.refresh_layout.bind(scroll_y=self.check_scroll_y) self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) else: + self.set_AllmailCnt('0') content = MDLabel( font_style='Caption', theme_text_color='Primary', @@ -2425,6 +2441,11 @@ class Allmails(Screen): " ORDER BY actionTime DESC limit {1}, {2}".format( self.account, start_indx, end_indx)) + def set_AllmailCnt(self, Count): + """This method is used to set allmails message count""" + allmailCnt_obj = state.kivyapp.root.ids.content_drawer.ids.allmail_cnt + allmailCnt_obj.children[0].children[0].text = showLimitedCnt(int(Count)) + def set_mdlist(self): """This method is used to create mdList for allmaills""" data_exist = len(self.ids.ml.children) @@ -2500,30 +2521,23 @@ class Allmails(Screen): unique_id) self.ids.ml.remove_widget(instance.parent.parent) try: - # msg_count_objs = self.parent.parent.parent.parent.parent.children[ - # 2].children[0].ids - nav_lay_obj = self.parent.parent.parent.ids + msg_count_objs = self.parent.parent.ids.content_drawer.ids + nav_lay_obj = self.parent.parent.ids except Exception: - msg_count_objs = ( - self.parent.parent.parent.parent.parent.parent.children[ - 2].children[0].ids) - nav_lay_obj = self.parent.parent.parent.parent.parent.parent.ids + msg_count_objs = self.parent.parent.parent.ids.content_drawer.ids + nav_lay_obj = self.parent.parent.parent.ids if folder == 'inbox': - # msg_count_objs.inbox_cnt.badge_text = str( - # int(state.inbox_count) - 1) + msg_count_objs.inbox_cnt.children[0].children[0].text = showLimitedCnt(int(state.inbox_count) - 1) state.inbox_count = str(int(state.inbox_count) - 1) nav_lay_obj.sc1.ids.ml.clear_widgets() nav_lay_obj.sc1.loadMessagelist(state.association) else: - # msg_count_objs.send_cnt.badge_text = str( - # int(state.sent_count) - 1) + msg_count_objs.send_cnt.children[0].children[0].text = showLimitedCnt(int(state.sent_count) - 1) state.sent_count = str(int(state.sent_count) - 1) nav_lay_obj.sc4.ids.ml.clear_widgets() nav_lay_obj.sc4.loadSent(state.association) - # msg_count_objs.trash_cnt.badge_text = str( - # int(state.trash_count) + 1) - # msg_count_objs.allmail_cnt.badge_text = str( - # int(state.all_count) - 1) + msg_count_objs.trash_cnt.children[0].children[0].text = showLimitedCnt(int(state.trash_count) + 1) + msg_count_objs.allmail_cnt.children[0].children[0].text = showLimitedCnt(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: @@ -2548,13 +2562,6 @@ class Allmails(Screen): self.tick = 0 Clock.schedule_once(refresh_callback, 1) - def set_root_layout(self): - """Setting root layout""" - try: - return self.manager.parent.parent - except Exception: - return state.kivyapp.root.ids.float_box - def avatarImageFirstLetter(letter_string): """This function is used to the first letter for the avatar image""" @@ -2604,6 +2611,40 @@ class AddressDropdown(OneLineIconListItem): pass -class NavigationItem(OneLineAvatarListItem): +class BadgeText(IRightBodyTouch, MDLabel): + pass + + +class NavigationItem(OneLineAvatarIconListItem): """NavigationItem class is for button behaviour""" - icon = StringProperty() \ No newline at end of file + badge_text = StringProperty() + icon = StringProperty() + active = BooleanProperty(False) + + +class NavigationDrawerDivider(OneLineListItem): + """ + A small full-width divider that can be placed + in the :class:`MDNavigationDrawer` + """ + + disabled = True + divider = None + _txt_top_pad = NumericProperty(dp(8)) + _txt_bot_pad = NumericProperty(dp(8)) + + def __init__(self, **kwargs): + super(OneLineListItem, self).__init__(**kwargs) + self.height = dp(16) + + +class NavigationDrawerSubheader(OneLineListItem): + """ + A subheader for separating content in :class:`MDNavigationDrawer` + + Works well alongside :class:`NavigationDrawerDivider` + """ + + disabled = True + divider = None + theme_text_color = 'Secondary' \ No newline at end of file diff --git a/src/state.py b/src/state.py index 5207099f..c8ab8bf4 100644 --- a/src/state.py +++ b/src/state.py @@ -103,8 +103,6 @@ is_allmail = False in_composer = False -write_msg = {} - availabe_credit = 0 in_sent_method = False From e15ec61dee3443bc6980417a97f31b1c3ad6c4fc Mon Sep 17 00:00:00 2001 From: navjot Date: Mon, 20 Jan 2020 14:15:54 +0530 Subject: [PATCH 43/54] worked on designing app closing popup --- src/bitmessagekivy/kv/popup.kv | 61 ++++++++++++++++++++++++++++++++++ src/bitmessagekivy/mpybit.py | 50 +++++++++++++++------------- 2 files changed, 88 insertions(+), 23 deletions(-) diff --git a/src/bitmessagekivy/kv/popup.kv b/src/bitmessagekivy/kv/popup.kv index 52720bb1..b6d0106c 100644 --- a/src/bitmessagekivy/kv/popup.kv +++ b/src/bitmessagekivy/kv/popup.kv @@ -245,6 +245,67 @@ height: dp(40) on_press: root.dismiss() on_press: root.close_pop() + MDLabel: + font_style: 'H6' + text: 'Cancel' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + +: + id: closing_popup + size_hint : (None,None) + height: 1.3*(popup_label.height+ my_add_btn.children[0].height) + 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 + BoxLayout: + id: myadd_popup_box + size_hint_y: None + spacing:dp(70) + orientation: 'vertical' + BoxLayout: + size_hint_y: None + orientation: 'vertical' + spacing:dp(25) + MDLabel: + id: popup_label + font_style: 'Subtitle2' + theme_text_color: 'Primary' + text: "Bitmessage isn't connected to the network.\n If you quit now, it may cause delivery delays.\n Wait until connected and the synchronisation finishes?" + font_size: '17sp' + halign: 'left' + BoxLayout: + id: my_add_btn + spacing:5 + orientation: 'horizontal' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.closingAction(self.children[0].text) + on_press: app.stop() + MDLabel: + font_style: 'H6' + text: 'Yes' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + on_press: root.closingAction(self.children[0].text) + MDLabel: + font_style: 'H6' + text: 'No' + font_size: '13sp' + color: (1,1,1,1) + halign: 'center' + MDRaisedButton: + size_hint: 1.5, None + height: dp(40) + #on_press: root.dismiss() + on_press: root.closingAction(self.children[0].text) MDLabel: font_style: 'H6' text: 'Cancel' diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 40fa3b4d..dff156d3 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1313,7 +1313,7 @@ class NavigateApp(MDApp): kivysignalthread = UIkivySignaler() kivysignalthread.daemon = True kivysignalthread.start() - Window.bind(on_keyboard=self.on_key, on_request_close=self.on_request_closee) + Window.bind(on_keyboard=self.on_key, on_request_close=self.on_request_close) return Builder.load_file( os.path.join(os.path.dirname(__file__), 'main.kv')) @@ -1622,12 +1622,12 @@ class NavigateApp(MDApp): def on_start(self): self.set_message_count() - @staticmethod - def on_stop(): - """On stop methos is used for stoping the runing script""" - print("*******************EXITING FROM APPLICATION*******************") - import shutdown - shutdown.doCleanShutdown() + # @staticmethod + # def on_stop(): + # """On stop methos is used for stoping the runing script""" + # print("*******************EXITING FROM APPLICATION*******************") + # import shutdown + # shutdown.doCleanShutdown() @staticmethod def current_address_label(current_add_label=None, current_addr=None): @@ -1763,21 +1763,9 @@ class NavigateApp(MDApp): except Exception: self.root.ids.sc17.children[0].children[1].active = False - def on_request_closee(self, *args): - box = BoxLayout(orientation='vertical') - box.add_widget(Label( - text=( - "Bitmessage isn't connected to the network.\n" - "If you quit now, it may cause delivery delays.\n" - "Wait until connected and the synchronisation finishes?"))) - mybutton = Button(text='Yes', size_hint=(1, 0.50)) - box.add_widget(mybutton) - mybutton2 = Button(text='No', size_hint=(1, 0.50)) - box.add_widget(mybutton2) - mybutton3 = Button(text='Cancel', size_hint=(1, 0.50)) - box.add_widget(mybutton3) - popup = Popup(title="Window close", content=box, size_hint=(None, None), size=(500, 300)) - popup.open() + def on_request_close(self, *args): + """This method is for app closing request""" + AppClosingPopup().open() return True @@ -2647,4 +2635,20 @@ class NavigationDrawerSubheader(OneLineListItem): disabled = True divider = None - theme_text_color = 'Secondary' \ No newline at end of file + theme_text_color = 'Secondary' + + +class AppClosingPopup(Popup): + """Class for app closing popup""" + + def __init__(self, **kwargs): + super(AppClosingPopup, self).__init__(**kwargs) + + def closingAction(self, text): + if text == 'Yes': + print("*******************EXITING FROM APPLICATION*******************") + import shutdown + shutdown.doCleanShutdown() + else: + self.dismiss() + toast(text) \ No newline at end of file From 4d385a9c791dfc6a28e92361fc5dc4c6b7039560 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 20 Jan 2020 18:29:02 +0530 Subject: [PATCH 44/54] Code quality issues fixes --- src/api.py | 2 +- src/bitmessagekivy/mpybit.py | 52 +++++++++++++++++------------------ src/bitmessagemain.py | 1 + src/knownnodes.py | 2 +- src/messagetypes/__init__.py | 2 +- src/network/connectionpool.py | 2 +- src/protocol.py | 8 ++++-- src/pyelliptic/arithmetic.py | 1 + src/pyelliptic/openssl.py | 2 +- 9 files changed, 37 insertions(+), 35 deletions(-) diff --git a/src/api.py b/src/api.py index bfbe45fa..428cf637 100644 --- a/src/api.py +++ b/src/api.py @@ -31,7 +31,7 @@ import shared import shutdown import state -from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError +from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError from bmconfigparser import BMConfigParser from debug import logger from helper_ackPayload import genAckPayload diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index dff156d3..da611b03 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -47,12 +47,8 @@ from kivymd.uix.list import ( ILeftBodyTouch, IRightBodyTouch, TwoLineAvatarIconListItem, - TwoLineListItem, OneLineIconListItem, - OneLineAvatarListItem, - IRightBody, OneLineAvatarIconListItem, - IRightBodyTouch, OneLineListItem ) # from kivymd.uix.navigationdrawer import ( @@ -60,7 +56,6 @@ from kivymd.uix.list import ( # NavigationDrawerHeaderBase # ) from kivymd.uix.selectioncontrol import MDCheckbox -from kivymd.theming import ThemeManager import queues from semaphores import kivyuisignaler @@ -69,10 +64,12 @@ import state from addresses import decodeAddress -KVFILES = ['settings', 'popup', 'allmails', 'draft', - 'maildetail', 'common_widgets', 'addressbook', - 'myaddress', 'composer', 'payment', 'sent', - 'network', 'login', 'credits', 'trash', 'inbox'] +KVFILES = [ + 'settings', 'popup', 'allmails', 'draft', + 'maildetail', 'common_widgets', 'addressbook', + 'myaddress', 'composer', 'payment', 'sent', + 'network', 'login', 'credits', 'trash', 'inbox' +] def toast(text): @@ -149,7 +146,7 @@ class Inbox(Screen): valign='top') self.ids.ml.add_widget(content) - def set_inboxCount(self, msgCnt): + def set_inboxCount(self, msgCnt): # pylint: disable=no-self-use """This method is used to sent inbox message count""" src_mng_obj = state.kivyapp.root.ids.content_drawer.ids.inbox_cnt src_mng_obj.children[0].children[0].text = showLimitedCnt(int(msgCnt)) @@ -321,7 +318,6 @@ class MyAddress(Screen): def init_ui(self, dt=0): """Clock schdule for method Myaddress accounts""" - # pylint: disable=unnecessary-lambda, deprecated-lambda self.addresses_list = state.kivyapp.variable_1 if state.searcing_text: self.ids.refresh_layout.scroll_y = 1.0 @@ -402,7 +398,7 @@ class MyAddress(Screen): def refresh_callback(interval): """Method used for loading the myaddress screen data""" state.searcing_text = '' - #state.kivyapp.root.ids.sc10.children[2].active = False + # state.kivyapp.root.ids.sc10.children[2].active = False # self.children[2].children[2].ids.search_field.text = '' self.children[3].children[2].ids.search_field.text = '' self.has_refreshed = True @@ -557,7 +553,7 @@ class SelectableLabel(RecycleDataViewBehavior, Label): return super(SelectableLabel, self).refresh_view_attrs( rv, index, data) - def on_touch_down(self, touch): + def on_touch_down(self, touch): # pylint: disable=inconsistent-return-statements """Add selection on touch down""" if super(SelectableLabel, self).on_touch_down(touch): return True @@ -1160,7 +1156,7 @@ class Trash(Screen): " ORDER BY actionTime DESC limit {1}, {2}".format( state.association, start_indx, end_indx)) - def set_TrashCnt(self, Count): + def set_TrashCnt(self, Count): # pylint: disable=no-self-use """This method is used to set trash message count""" trashCnt_obj = state.kivyapp.root.ids.content_drawer.ids.trash_cnt trashCnt_obj.children[0].children[0].text = showLimitedCnt(int(Count)) @@ -1308,7 +1304,7 @@ class NavigateApp(MDApp): """Method builds the widget""" for kv_file in KVFILES: Builder.load_file( - os.path.join(os.path.dirname(__file__),f"kv/{kv_file}.kv")) + os.path.join(os.path.dirname(__file__), f"kv/{kv_file}.kv")) self.obj_1 = AddressBook() kivysignalthread = UIkivySignaler() kivysignalthread.daemon = True @@ -1433,6 +1429,7 @@ class NavigateApp(MDApp): return False def on_key(self, window, key, *args): + # pylint: disable=inconsistent-return-statements """Method is used for going on previous screen""" if key == 27: if state.in_search_mode and self.root.ids.scr_mngr.current != ( @@ -1493,7 +1490,7 @@ class NavigateApp(MDApp): def loadMyAddressScreen(self, action): """loadMyAddressScreen method spin the loader""" - if len(self.root.ids.sc10.children) <=3: + if len(self.root.ids.sc10.children) <= 3: self.root.ids.sc10.children[1].active = action else: self.root.ids.sc10.children[2].active = action @@ -1709,7 +1706,7 @@ class NavigateApp(MDApp): """Show identicon in address spinner""" img = identiconGeneration.generate(text) self.root.children[0].children[0].ids.btn.children[1].texture = (img.texture) - #below line is for displaing logo + # below line is for displaing logo self.root.ids.content_drawer.ids.top_box.children[0].texture = (img.texture) def set_mail_detail_header(self): @@ -1763,11 +1760,11 @@ class NavigateApp(MDApp): except Exception: self.root.ids.sc17.children[0].children[1].active = False - def on_request_close(self, *args): + def on_request_close(self, *args): # pylint: disable=no-self-use """This method is for app closing request""" AppClosingPopup().open() return True - + class GrashofPopup(Popup): """Moule for save contacts and error messages""" @@ -1902,7 +1899,6 @@ class IconRightSampleWidget(IRightBodyTouch, MDCheckbox): pass - class MailDetail(Screen): """MailDetail Screen uses to show the detail of mails""" @@ -2156,8 +2152,8 @@ class ShowQRCode(Screen): from kivy.garden.qrcode import QRCodeWidget try: address = self.manager.get_parent_window().children[0].address - except Exception as e: - address = self.manager.get_parent_window().children[1].address + except Exception: + address = self.manager.get_parent_window().children[1].address self.ids.qr.add_widget(QRCodeWidget(data=address)) toast('Show QR code') @@ -2223,7 +2219,7 @@ class Draft(Screen): start_indx, end_indx) - def set_draftCnt(self, Count): + def set_draftCnt(self, Count): # pylint: disable=no-self-use """This method set the count of draft mails""" draftCnt_obj = state.kivyapp.root.ids.content_drawer.ids.draft_cnt draftCnt_obj.children[0].children[0].text = showLimitedCnt(int(Count)) @@ -2305,8 +2301,8 @@ class Draft(Screen): # msg_count_objs = ( # self.parent.parent.parent.parent.parent.parent.children[ # 2].children[0].ids) - # msg_count_objs = self.parent.parent.parent.parent.parent.children[ - # 2].children[0].ids + # msg_count_objs = self.parent.parent.parent.parent.parent.children[ + # 2].children[0].ids if int(state.draft_count) > 0: # msg_count_objs.draft_cnt.badge_text = str( # int(state.draft_count) - 1) @@ -2429,7 +2425,7 @@ class Allmails(Screen): " ORDER BY actionTime DESC limit {1}, {2}".format( self.account, start_indx, end_indx)) - def set_AllmailCnt(self, Count): + def set_AllmailCnt(self, Count): # pylint: disable=no-self-use """This method is used to set allmails message count""" allmailCnt_obj = state.kivyapp.root.ids.content_drawer.ids.allmail_cnt allmailCnt_obj.children[0].children[0].text = showLimitedCnt(int(Count)) @@ -2600,6 +2596,7 @@ class AddressDropdown(OneLineIconListItem): class BadgeText(IRightBodyTouch, MDLabel): + """Class for badgetext""" pass @@ -2645,10 +2642,11 @@ class AppClosingPopup(Popup): super(AppClosingPopup, self).__init__(**kwargs) def closingAction(self, text): + """Action on closing window""" if text == 'Yes': print("*******************EXITING FROM APPLICATION*******************") import shutdown shutdown.doCleanShutdown() else: self.dismiss() - toast(text) \ No newline at end of file + toast(text) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index a2522053..65afbe7f 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -371,6 +371,7 @@ class Main(object): elif state.kivy: config.remove_option('bitmessagesettings', 'dontconnect') + # pylint: disable=no-member, import-error from bitmessagekivy.mpybit import NavigateApp state.kivyapp = NavigateApp() state.kivyapp.run() diff --git a/src/knownnodes.py b/src/knownnodes.py index f8007bb6..a2327625 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -126,7 +126,7 @@ def readKnownNodes(): except ValueError: source.seek(0) pickle_deserialize_old_knownnodes(source) - except (IOError, OSError, KeyError, EOFError,pickle.UnpicklingError): + except (IOError, OSError, KeyError, EOFError, pickle.UnpicklingError): logger.debug( 'Failed to read nodes from knownnodes.dat', exc_info=True) createDefaultKnownNodes() diff --git a/src/messagetypes/__init__.py b/src/messagetypes/__init__.py index ee4ae048..ef8b7f18 100644 --- a/src/messagetypes/__init__.py +++ b/src/messagetypes/__init__.py @@ -16,7 +16,7 @@ logger = logging.getLogger('default') class MsgBase(object): # pylint: disable=too-few-public-methods """Base class for message types""" def __init__(self): - self.data = {"": lower(type(self).__name__)} + self.data = {"": (type(self).__name__).lower()} def constructObject(data): diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 82bf20a5..5e59d99d 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -326,7 +326,7 @@ class BMConnectionPool(object): try: if type(chosen.host) == bytes: - onion= '.onion'.encode() + onion = '.onion'.encode() else: onion = '.onion' if chosen.host.endswith(onion) and Proxy.onion_proxy: diff --git a/src/protocol.py b/src/protocol.py index 6fa989a3..8b6a71d8 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -105,7 +105,9 @@ def encodeHost(host): colon = ':' full_stop = '.' if host.find(onion) > -1: - return '\xfd\x87\xd8\x7e\xeb\x43'.encode('raw_unicode_escape') + base64.b32decode(host.split(full_stop)[0], True) + return '\xfd\x87\xd8\x7e\xeb\x43'.encode( + 'raw_unicode_escape') + base64.b32decode( + host.split(full_stop)[0], True) elif host.find(colon) == -1: return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'.encode('raw_unicode_escape') + \ socket.inet_aton(host) @@ -286,7 +288,7 @@ def isProofOfWorkSufficient( def CreatePacket(command, payload=''): """Construct and return a number of bytes from a payload""" - payload = payload if type(payload) in [bytes,bytearray] 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) @@ -332,7 +334,7 @@ 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 + # python3 need to check 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 diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 71bb9d5a..566be794 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -51,6 +51,7 @@ def encode(val, base, minlen=0): result = code_string[0] * (minlen - len(result)) + result return result + def decode(string, base): """Returns the decoded string""" code_string = get_code_string(base) diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 23cecc60..57a7a851 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -698,7 +698,7 @@ def loadOpenSSL(): path.join(sys._MEIPASS, 'libssl.so'), path.join(sys._MEIPASS, 'libcrypto.so.1.1.0'), path.join(sys._MEIPASS, 'libssl.so.1.1.0'), - path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), + path.join(sys._MEIPASS, 'libcrypto.so.1.0.2'), path.join(sys._MEIPASS, 'libssl.so.1.0.2'), path.join(sys._MEIPASS, 'libcrypto.so.1.0.1'), path.join(sys._MEIPASS, 'libssl.so.1.0.1'), From 26d75d99fdad813ced9b72c724824de01a37f1c6 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Mon, 20 Jan 2020 19:57:58 +0530 Subject: [PATCH 45/54] Logging and modules issues fixes --- src/bitmessagemain.py | 2 +- src/network/udp.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 65afbe7f..b99f071a 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -371,7 +371,7 @@ class Main(object): elif state.kivy: config.remove_option('bitmessagesettings', 'dontconnect') - # pylint: disable=no-member, import-error + # pylint: disable=no-member, import-error, no-name-in-module from bitmessagekivy.mpybit import NavigateApp state.kivyapp = NavigateApp() state.kivyapp.run() diff --git a/src/network/udp.py b/src/network/udp.py index b6228fa4..ddd27fe3 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -91,8 +91,8 @@ class UDPSocket(BMProto): # pylint: disable=too-many-instance-attributes if remoteport is False: return True logger.debug( - "received peer discovery from {}:{} (port {}):", - self.destination.host, self.destination.port, remoteport) + "received peer discovery from {}:{} (port {}):".format( + self.destination.host, self.destination.port, remoteport)) if self.local: state.discoveredPeers[Peer(self.destination.host, remoteport)] = \ time.time() From 1decaad15691ba88a1e5ed47fb682052dc73849d Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 21 Jan 2020 13:39:56 +0530 Subject: [PATCH 46/54] invalid syntax pylint issue resolve --- src/bitmessagekivy/mpybit.py | 17 +++++++++-------- src/bitmessagemain.py | 2 +- src/network/udp.py | 1 + 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 0a483621..641da408 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1,8 +1,8 @@ """ Bitmessage android(mobile) interface """ -# pylint: disable=import-error,no-name-in-module,unused-argument,too-few-public-methods,too-many-arguments -# pylint: disable=too-many-ancestors,too-many-locals,useless-super-delegation,attribute-defined-outside-init +# pylint: disable=too-many-lines,import-error,no-name-in-module,unused-argument +# pylint: disable=too-many-ancestors,too-many-locals,useless-super-delegation import os import time from bitmessagekivy import identiconGeneration @@ -62,7 +62,7 @@ from semaphores import kivyuisignaler import state from addresses import decodeAddress - +# pylint: disable=too-few-public-methods,too-many-arguments,attribute-defined-outside-init KVFILES = [ 'settings', 'popup', 'allmails', 'draft', @@ -509,7 +509,8 @@ 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: + # if len(self.ids.ml.children) == 0: + if self.ids.ml.children is not None: self.ids.identi_tag.children[0].text = '' sqlExecute( "DELETE FROM addressbook WHERE address = '{}';".format(address)) @@ -1263,7 +1264,7 @@ class Setting(Screen): class NavigateApp(MDApp): """Navigation Layout of class""" - # pylint: disable=too-many-public-methods + # pylint: disable=too-many-public-methods,inconsistent-return-statements # theme_cls = ThemeManager() previous_date = ObjectProperty() @@ -1280,8 +1281,7 @@ class NavigateApp(MDApp): def build(self): """Method builds the widget""" for kv_file in KVFILES: - Builder.load_file( - os.path.join(os.path.dirname(__file__), f"kv/{kv_file}.kv")) + Builder.load_file(os.path.join(os.path.dirname(__file__), "kv/{}.kv").format(kv_file)) self.obj_1 = AddressBook() kivysignalthread = UIkivySignaler() kivysignalthread.daemon = True @@ -1298,7 +1298,6 @@ class NavigateApp(MDApp): @staticmethod def showmeaddresses(name="text"): """Show the addresses in spinner to make as dropdown""" - # pylint: disable=inconsistent-return-statements if name == "text": if BMConfigParser().addresses(): return BMConfigParser().addresses()[0][:16] + '..' @@ -1590,6 +1589,7 @@ class NavigateApp(MDApp): msg_counter_objs.allmail_cnt.badge_text = state.all_count def on_start(self): + """Setting message count""" self.set_message_count() # @staticmethod @@ -2585,6 +2585,7 @@ class NavigationDrawerDivider(OneLineListItem): _txt_bot_pad = NumericProperty(dp(8)) def __init__(self, **kwargs): + # pylint: disable=bad-super-call super(OneLineListItem, self).__init__(**kwargs) self.height = dp(16) diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index b99f071a..4a62a8fe 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -371,7 +371,7 @@ class Main(object): elif state.kivy: config.remove_option('bitmessagesettings', 'dontconnect') - # pylint: disable=no-member, import-error, no-name-in-module + # pylint: disable=no-member,import-error,no-name-in-module,relative-import from bitmessagekivy.mpybit import NavigateApp state.kivyapp = NavigateApp() state.kivyapp.run() diff --git a/src/network/udp.py b/src/network/udp.py index ddd27fe3..aac32554 100644 --- a/src/network/udp.py +++ b/src/network/udp.py @@ -14,6 +14,7 @@ import state from queues import receiveDataQueue logger = logging.getLogger('default') +# pylint: disable=logging-format-interpolation class UDPSocket(BMProto): # pylint: disable=too-many-instance-attributes From fe3a98c2b61ea0ad4656b73d7d9c51686709bb61 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 21 Jan 2020 15:48:21 +0530 Subject: [PATCH 47/54] unidiomatic-typecheck and logging-format-interpolation issue suprressed --- pybitmessage | 1 - src/bmconfigparser.py | 1 + src/multiqueue.py | 2 +- src/network/bmproto.py | 5 +++-- src/network/connectionchooser.py | 2 +- src/network/connectionpool.py | 2 +- src/network/tcp.py | 2 +- src/protocol.py | 3 ++- src/shared.py | 2 +- src/tests/test_networkgroup.py | 1 + 10 files changed, 12 insertions(+), 9 deletions(-) delete mode 120000 pybitmessage diff --git a/pybitmessage b/pybitmessage deleted file mode 120000 index e8310385..00000000 --- a/pybitmessage +++ /dev/null @@ -1 +0,0 @@ -src \ No newline at end of file diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index a5574156..d96d994d 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -117,6 +117,7 @@ class BMConfigParser(configparser.ConfigParser): return default def items(self, section, raw=False, variables=None): + # pylint: disable=signature-differs """Return section variables as parent, but override the "raw" argument to always True""" return configparser.ConfigParser.items(self, section, True, variables) diff --git a/src/multiqueue.py b/src/multiqueue.py index 4230d050..792427a0 100644 --- a/src/multiqueue.py +++ b/src/multiqueue.py @@ -22,7 +22,7 @@ class MultiQueue(Queue.Queue): Queue.Queue.__init__(self, maxsize) # Initialize the queue representation - def _init(self, maxsize): + def _init(self, _): self.iter = 0 self.queues = [] for _ in range(self.queueCount): diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 5c57748a..adca21f5 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -1,7 +1,7 @@ """ Bitmessage Protocol """ -# pylint: disable=attribute-defined-outside-init, too-few-public-methods +# pylint: disable=attribute-defined-outside-init, too-few-public-methods, logging-format-interpolation import base64 import hashlib import logging @@ -123,7 +123,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker): length=protocol.Header.size, expectBytes=self.payloadLength) return True - def state_bm_command(self): # pylint: disable=too-many-branches, too-many-statements + 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]: diff --git a/src/network/connectionchooser.py b/src/network/connectionchooser.py index 87fea685..4ea36a02 100644 --- a/src/network/connectionchooser.py +++ b/src/network/connectionchooser.py @@ -1,7 +1,7 @@ """ Select which node to connect to """ -# pylint: disable=too-many-branches +# pylint: disable=too-many-branches, logging-format-interpolation, unidiomatic-typecheck import logging import random # nosec diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 5e59d99d..36f8c2b3 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -190,7 +190,7 @@ class BMConnectionPool(object): def startListening(self, bind=None): """Open a listening socket and start accepting connections on it""" if bind is None: - "this return blank host" + """this return blank host""" bind = self.getListeningIP() port = BMConfigParser().safeGetInt("bitmessagesettings", "port") # correct port even if it changed diff --git a/src/network/tcp.py b/src/network/tcp.py index 33ac4df5..47553751 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -30,7 +30,7 @@ from network.socks5 import Socks5Connection from network.tls import TLSDispatcher from .node import Peer from queues import UISignalQueue, invQueue, receiveDataQueue - +# pylint: disable=logging-format-interpolation logger = logging.getLogger('default') diff --git a/src/protocol.py b/src/protocol.py index 8b6a71d8..6f84236e 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -2,7 +2,7 @@ Low-level protocol-related functions. """ # pylint: disable=too-many-boolean-expressions,too-many-return-statements -# pylint: disable=too-many-locals,too-many-statements +# pylint: disable=too-many-locals,too-many-statements,logging-format-interpolation import base64 import hashlib @@ -65,6 +65,7 @@ Header = Struct('!L12sL4s') VersionPacket = Struct('>LqQ20s4s36sH') # Bitfield +# pylint: disable=unidiomatic-typecheck def getBitfield(address): diff --git a/src/shared.py b/src/shared.py index b1a19c08..0f2a816c 100644 --- a/src/shared.py +++ b/src/shared.py @@ -24,7 +24,7 @@ from addresses import decodeAddress, encodeVarint from bmconfigparser import BMConfigParser from debug import logger from helper_sql import sqlQuery - +# pylint: disable=logging-format-interpolation verbose = 1 # This is obsolete with the change to protocol v3 diff --git a/src/tests/test_networkgroup.py b/src/tests/test_networkgroup.py index 76cfb033..14e61a8e 100644 --- a/src/tests/test_networkgroup.py +++ b/src/tests/test_networkgroup.py @@ -10,6 +10,7 @@ class TestNetworkGroup(unittest.TestCase): """ def test_network_group(self): """Test various types of network groups""" + # pylint: disable=import-error from pybitmessage.protocol import network_group test_ip = '1.2.3.4' From c613c6d439e1c98a7a532e94fc189bce8122d7a0 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Tue, 21 Jan 2020 17:43:09 +0530 Subject: [PATCH 48/54] pylint fixes 2 --- src/bitmessagecurses/__init__.py | 2 +- src/bitmessageqt/statusbar.py | 1 - src/knownnodes.py | 1 + src/network/connectionpool.py | 2 +- src/pyelliptic/arithmetic.py | 4 ++-- src/queues.py | 2 ++ 6 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/bitmessagecurses/__init__.py b/src/bitmessagecurses/__init__.py index a3cf5398..d4b72f8c 100644 --- a/src/bitmessagecurses/__init__.py +++ b/src/bitmessagecurses/__init__.py @@ -258,7 +258,7 @@ def drawtab(stdscr): stdscr.addstr(6, 18, "Connections", curses.A_BOLD) stdscr.hline(7, 6, '-', 23) streamcount = [] - for host, stream in connected_hosts: + for _, stream in connected_hosts: if stream >= len(streamcount): streamcount.append(1) else: diff --git a/src/bitmessageqt/statusbar.py b/src/bitmessageqt/statusbar.py index 7f559197..68ddba3f 100644 --- a/src/bitmessageqt/statusbar.py +++ b/src/bitmessageqt/statusbar.py @@ -1,5 +1,4 @@ from PyQt4 import QtCore, QtGui -from queue.Queue import Queue from time import time class BMStatusBar(QtGui.QStatusBar): diff --git a/src/knownnodes.py b/src/knownnodes.py index a2327625..48194d9d 100644 --- a/src/knownnodes.py +++ b/src/knownnodes.py @@ -49,6 +49,7 @@ def json_serialize_knownnodes(output): for stream, peers in iter(knownNodes.items()): for peer, info in iter(peers.items()): info.update(rating=round(info.get('rating', 0), 2)) + # pylint: disable=unidiomatic-typecheck if type(peer[0]) != bytes: _serialized.append({'stream': stream, 'peer': peer._asdict(), 'info': info}) else: diff --git a/src/network/connectionpool.py b/src/network/connectionpool.py index 36f8c2b3..159f66f3 100644 --- a/src/network/connectionpool.py +++ b/src/network/connectionpool.py @@ -190,7 +190,6 @@ class BMConnectionPool(object): def startListening(self, bind=None): """Open a listening socket and start accepting connections on it""" if bind is None: - """this return blank host""" bind = self.getListeningIP() port = BMConfigParser().safeGetInt("bitmessagesettings", "port") # correct port even if it changed @@ -325,6 +324,7 @@ class BMConnectionPool(object): continue try: + # pylint: disable=unidiomatic-typecheck if type(chosen.host) == bytes: onion = '.onion'.encode() else: diff --git a/src/pyelliptic/arithmetic.py b/src/pyelliptic/arithmetic.py index 566be794..f6690a25 100644 --- a/src/pyelliptic/arithmetic.py +++ b/src/pyelliptic/arithmetic.py @@ -33,8 +33,8 @@ def get_code_string(base): elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" elif base == 256: - '''raw_unicode_escape is used because in the python3 after range(161) its genreate - the speical character so avoiding that function we have used the raw_unicode method ''' + # raw_unicode_escape is used because in the python3 after range(161) its genreate + # the speical character so avoiding that function we have used the raw_unicode method return bytes(range(0, 256)) else: raise ValueError("Invalid base!") diff --git a/src/queues.py b/src/queues.py index 6a76adb6..bbd13fb7 100644 --- a/src/queues.py +++ b/src/queues.py @@ -21,6 +21,7 @@ class ObjectProcessorQueue(Queue.Queue): self.curSize = 0 def put(self, item, block=True, timeout=None): + """Putting values in queues""" while self.curSize >= self.maxSize: time.sleep(1) with self.sizeLock: @@ -28,6 +29,7 @@ class ObjectProcessorQueue(Queue.Queue): Queue.Queue.put(self, item, block, timeout) def get(self, block=True, timeout=None): + """Getting values from queues""" item = Queue.Queue.get(self, block, timeout) with self.sizeLock: self.curSize -= len(item[1]) From eb2b948576a12b2e8f54ea0ec13ee7d59a079f13 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Thu, 23 Jan 2020 14:12:32 +0530 Subject: [PATCH 49/54] Added changes for inventory and inbox issues --- src/bitmessagekivy/kivy_helper_search.py | 6 +- src/class_objectProcessor.py | 16 +++-- src/class_singleWorker.py | 84 +++++++++++++++--------- src/class_sqlThread.py | 2 + src/highlevelcrypto.py | 1 + src/inventory.py | 3 + src/l10n.py | 3 +- src/network/bmproto.py | 26 ++++++-- src/network/invthread.py | 6 +- src/network/tcp.py | 23 +++---- src/network/uploadthread.py | 1 + src/proofofwork.py | 19 ++++-- src/protocol.py | 14 ++-- src/storage/sqlite.py | 51 +++++++++----- 14 files changed, 167 insertions(+), 88 deletions(-) diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 9f740597..1c410df0 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -22,12 +22,16 @@ def search_sql( sqlStatementBase = '''SELECT label, address From addressbook ''' else: sqlStatementBase = ( - '''SELECT folder, msgid, toaddress, message, fromaddress,''' + '''SELECT folder, toaddress, message, fromaddress,''' ''' subject, received, read FROM inbox ''' ) sqlStatementParts = [] sqlArguments = [] if account is not None: + #xAddress = 'toaddress' + #where = ['subject', 'message'] + #what = None + #unreadOnly = False if xAddress == 'both': sqlStatementParts.append("(fromaddress = ? OR toaddress = ?)") sqlArguments.append(account) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index fc87ce50..f7930dce 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -48,7 +48,7 @@ class objectProcessor(threading.Thread): def __init__(self): threading.Thread.__init__(self, name="objectProcessor") random.seed() - # It may be the case that the last time Bitmessage was running, + # It may be the case that the last time Bitmes0sage was running, # the user closed it before it finished processing everything in the # objectProcessorQueue. Assuming that Bitmessage wasn't closed # forcefully, it should have saved the data in the queue into the @@ -69,9 +69,7 @@ class objectProcessor(threading.Thread): """Process the objects from `.queues.objectProcessorQueue`""" while True: objectType, data = queues.objectProcessorQueue.get() - self.checkackdata(data) - try: if objectType == protocol.OBJECT_GETPUBKEY: self.processgetpubkey(data) @@ -236,8 +234,9 @@ class objectProcessor(threading.Thread): logger.debug( 'the tag requested in this getpubkey request is: %s', hexlify(requestedTag)) + # import pdb;pdb.set_trace() if bytes(requestedTag) in shared.myAddressesByTag: - myAddress = shared.myAddressesByTag[requestedTag] + myAddress = shared.myAddressesByTag[bytes(requestedTag)] if myAddress == '': logger.info('This getpubkey request is not for any of my keys.') @@ -436,18 +435,21 @@ class objectProcessor(threading.Thread): return tag = data[readPosition:readPosition + 32] - if tag not in bytes(state.neededPubkeys): + if bytes(tag) not in state.neededPubkeys: logger.info( 'We don\'t need this v4 pubkey. We didn\'t ask for it.') return # Let us try to decrypt the pubkey - toAddress, _ = state.neededPubkeys[tag] - if protocol.decryptAndCheckPubkeyPayload(data, toAddress) == \ + print("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT#################################################", tag) + toAddress, _ = state.neededPubkeys[bytes(tag)] #check with py2 + # import pdb;pdb.set_trace() + if protocol.decryptAndCheckPubkeyPayload(bytes(data), toAddress) == \ 'successful': # At this point we know that we have been waiting on this # pubkey. This function will command the workerThread # to start work on the messages that require it. + print("decryptAndCheckPubkeyPayload completed#########################################################") self.possibleNewPubkey(toAddress) # Display timing data diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 7c0b5842..486308d7 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -679,6 +679,7 @@ class singleWorker(StoppableThread): """Send a message-type object (assemble the object, perform PoW and put it to the inv announcement queue)""" # pylint: disable=too-many-nested-blocks # Reset just in case + # import pdb;pdb.set_trace() sqlExecute( '''UPDATE sent SET status='msgqueued' ''' ''' WHERE status IN ('doingpubkeypow', 'doingmsgpow')''') @@ -689,6 +690,7 @@ class singleWorker(StoppableThread): ''' and folder LIKE '%sent%' ''') # while we have a msg that needs some work for row in queryreturn: + print(row, "rowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowv") toaddress, fromaddress, subject, message, \ ackdata, status, TTL, retryNumber, encoding = row # toStatus @@ -730,6 +732,7 @@ class singleWorker(StoppableThread): toaddress ) # If we have the needed pubkey in the pubkey table already, + print("sendmsg line no 734#####################################################################") if queryreturn != []: # set the status of this msg to doingmsgpow sqlExecute( @@ -750,6 +753,7 @@ class singleWorker(StoppableThread): ) # We don't have the needed pubkey in the pubkeys table already. else: + print("sendmsg line no 756#####################################################################") if toAddressVersionNumber <= 3: toTag = '' else: @@ -759,14 +763,16 @@ class singleWorker(StoppableThread): ).digest()).digest()[32:] if toaddress in state.neededPubkeys or \ toTag in state.neededPubkeys: + print("sendmsg line no 766#####################################################################") # We already sent a request for the pubkey sqlExecute( '''UPDATE sent SET status='awaitingpubkey', ''' ''' sleeptill=? WHERE toaddress=? ''' ''' AND status='msgqueued' ''', - int(time.time()) + 2.5 * 24 * 60 * 60, + int(10), toaddress ) + print("sendmsg line no 774#####################################################################") queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( toaddress, @@ -774,9 +780,11 @@ class singleWorker(StoppableThread): "MainWindow", "Encryption key was requested earlier.")) )) + print("sendmsg line no 783#####################################################################") # on with the next msg on which we can do some work continue else: + print("sendmsg line no 785#####################################################################") # We have not yet sent a request for the pubkey needToRequestPubkey = True # If we are trying to send to address @@ -850,19 +858,19 @@ class singleWorker(StoppableThread): self.requestPubKey(toaddress) # on with the next msg on which we can do some work continue - + print("sendmsg line no 856#####################################################################") # At this point we know that we have the necessary pubkey # in the pubkeys table. - TTL *= 2**retryNumber if TTL > 28 * 24 * 60 * 60: TTL = 28 * 24 * 60 * 60 # add some randomness to the TTL TTL = int(TTL + helper_random.randomrandrange(-300, 300)) embeddedTime = int(time.time() + TTL) - + print("sendmsg line no 870#####################################################################") # if we aren't sending this to ourselves or a chan if not BMConfigParser().has_section(toaddress): + print("sendmsg line no 873#####################################################################") shared.ackdataForWhichImWatching[ackdata] = 0 queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( @@ -1047,6 +1055,7 @@ class singleWorker(StoppableThread): l10n.formatTimestamp())))) continue else: # if we are sending a message to ourselves or a chan.. + print("sendmsg line no 1058#####################################################################") self.logger.info('Sending a message.') self.logger.debug( 'First 150 characters of message: %r', message[:150]) @@ -1088,7 +1097,7 @@ class singleWorker(StoppableThread): "MainWindow", "Doing work necessary to send message.")) )) - + print("sendmsg line no 1093#####################################################################") # Now we can start to assemble our message. payload = encodeVarint(fromAddressVersionNumber) payload += encodeVarint(fromStreamNumber) @@ -1096,9 +1105,10 @@ class singleWorker(StoppableThread): # that can be expected from me. (See # https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features) payload += protocol.getBitfield(fromaddress) - + print("sendmsg line no 1101#####################################################################") # We need to convert our private keys to public keys in order # to include them. + # import pdb; pdb.set_trace() try: privSigningKeyHex, privEncryptionKeyHex, \ pubSigningKey, pubEncryptionKey = self._getKeysForAddress( @@ -1113,7 +1123,7 @@ class singleWorker(StoppableThread): " (your address) in the keys.dat file.")) )) continue - + print("sendmsg line no 1119#####################################################################") payload += pubSigningKey + pubEncryptionKey if fromAddressVersionNumber >= 3: @@ -1128,16 +1138,17 @@ class singleWorker(StoppableThread): payload += encodeVarint( defaults.networkDefaultPayloadLengthExtraBytes) else: - payload += encodeVarint(BMConfigParser().getint( - fromaddress, 'noncetrialsperbyte')) - payload += encodeVarint(BMConfigParser().getint( - fromaddress, 'payloadlengthextrabytes')) - + payload += encodeVarint(int(BMConfigParser().get( + fromaddress, 'noncetrialsperbyte'))) + payload += encodeVarint(int(BMConfigParser().get( + fromaddress, 'payloadlengthextrabytes'))) + print('@@@@@@@@@@@@@@ before payload creating@@@@@@@@@@@@@@@@') # This hash will be checked by the receiver of the message # to verify that toRipe belongs to them. This prevents # a Surreptitious Forwarding Attack. payload += toRipe payload += encodeVarint(encoding) # message encoding type + # import pdb;pdb.set_trace() encodedMessage = helper_msgcoding.MsgEncode( {"subject": subject, "body": message}, encoding ) @@ -1163,8 +1174,8 @@ class singleWorker(StoppableThread): fullAckPayload = self.generateFullAckMessage( ackdata, toStreamNumber, TTL) payload += encodeVarint(len(fullAckPayload)) - payload += fullAckPayload - dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02' + \ + payload += fullAckPayload.encode() + dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02'.encode() + \ encodeVarint(1) + encodeVarint(toStreamNumber) + payload signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex) payload += encodeVarint(len(signature)) @@ -1173,7 +1184,7 @@ class singleWorker(StoppableThread): # We have assembled the data that will be encrypted. try: encrypted = highlevelcrypto.encrypt( - payload, "04" + hexlify(pubEncryptionKeyBase256) + payload, "04".encode() + hexlify(pubEncryptionKeyBase256) ) except: sqlExecute( @@ -1190,9 +1201,9 @@ class singleWorker(StoppableThread): ).arg(l10n.formatTimestamp())) )) continue - + print('@@@@@@@@@@@@@@ before encryptedPayload creating@@@@@@@@@@@@@@@@') encryptedPayload = pack('>Q', embeddedTime) - encryptedPayload += '\x00\x00\x00\x02' # object type: msg + encryptedPayload += '\x00\x00\x00\x02'.encode() # object type: msg encryptedPayload += encodeVarint(1) # msg version encryptedPayload += encodeVarint(toStreamNumber) + encrypted target = 2 ** 64 / ( @@ -1206,15 +1217,17 @@ class singleWorker(StoppableThread): )) self.logger.info( '(For msg message) Doing proof of work. Total required' - ' difficulty: %f. Required small message difficulty: %f.', - float(requiredAverageProofOfWorkNonceTrialsPerByte) / + ' difficulty: {}. Required small message difficulty: {}.'.format + (float(requiredAverageProofOfWorkNonceTrialsPerByte) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte, float(requiredPayloadLengthExtraBytes) / - defaults.networkDefaultPayloadLengthExtraBytes + defaults.networkDefaultPayloadLengthExtraBytes) ) powStartTime = time.time() initialHash = hashlib.sha512(encryptedPayload).digest() + # import pdb; pdb.set_trace() + trialValue, nonce = proofofwork.run(target, initialHash) print("nonce calculated value#############################", nonce) self.logger.info( @@ -1229,7 +1242,8 @@ class singleWorker(StoppableThread): ) except: pass - + print("line no 1234#########################################") + # import pdb; pdb.set_trace() encryptedPayload = pack('>Q', nonce) + encryptedPayload # Sanity check. The encryptedPayload size should never be @@ -1243,11 +1257,18 @@ class singleWorker(StoppableThread): len(encryptedPayload) ) continue - + print("line no 1248#########################################") inventoryHash = calculateInventoryHash(encryptedPayload) + print("line no 1250248#########################################") objectType = 2 - Inventory()[inventoryHash] = ( - objectType, toStreamNumber, encryptedPayload, embeddedTime, '') + print("line no 1252#########################################") + # import pdb; pdb.set_trace() + inventoryHashlist = ( + objectType, toStreamNumber,encryptedPayload, embeddedTime, '') + print("line no 1255#########################################") + # import pdb; pdb.set_trace() + Inventory()[inventoryHashlist] + print("line no 1257#########################################") if BMConfigParser().has_section(toaddress) or \ not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK): queues.UISignalQueue.put(( @@ -1255,7 +1276,7 @@ class singleWorker(StoppableThread): ackdata, tr._translate( "MainWindow", - "Message sent. Sent at %1" + "Mobileessage sent. Sent at %1" ).arg(l10n.formatTimestamp())))) else: # not sending to a chan or one of my addresses @@ -1268,14 +1289,15 @@ class singleWorker(StoppableThread): " Sent on %1" ).arg(l10n.formatTimestamp())) )) + print("line no 1282#########################################") self.logger.info( 'Broadcasting inv for my msg(within sendmsg function): %s', hexlify(inventoryHash) ) queues.invQueue.put((toStreamNumber, inventoryHash)) - # Update the sent message in the sent table with the # necessary information. + print("line no 1290#########################################") if BMConfigParser().has_section(toaddress) or \ not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK): newStatus = 'msgsentnoackexpected' @@ -1289,9 +1311,9 @@ class singleWorker(StoppableThread): inventoryHash, newStatus, retryNumber + 1, sleepTill, int(time.time()), ackdata ) - # If we are sending to ourselves or a chan, let's put # the message in our own inbox. + print("line no 1306#########################################") if BMConfigParser().has_section(toaddress): # Used to detect and ignore duplicate messages in our inbox sigHash = hashlib.sha512(hashlib.sha512( @@ -1318,6 +1340,7 @@ class singleWorker(StoppableThread): def requestPubKey(self, toAddress): """Send a getpubkey object""" + # import pdb;pdb.set_trace() toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress( toAddress) if toStatus != 'success': @@ -1378,7 +1401,7 @@ class singleWorker(StoppableThread): TTL = TTL + helper_random.randomrandrange(-300, 300) embeddedTime = int(time.time() + TTL) payload = pack('>Q', embeddedTime) - payload += '\x00\x00\x00\x00' # object type: getpubkey + payload += '\x00\x00\x00\x00'.encode() # object type: getpubkey payload += encodeVarint(addressVersionNumber) payload += encodeVarint(streamNumber) if addressVersionNumber <= 3: @@ -1406,8 +1429,9 @@ class singleWorker(StoppableThread): inventoryHash = calculateInventoryHash(payload) objectType = 1 - Inventory()[inventoryHash] = ( + inventoryHashlist = ( objectType, streamNumber, payload, embeddedTime, '') + Inventory()[inventoryHashlist] self.logger.info('sending inv (for the getpubkey message)') queues.invQueue.put((streamNumber, inventoryHash)) @@ -1437,7 +1461,7 @@ class singleWorker(StoppableThread): ).arg(l10n.formatTimestamp())) )) - def generateFullAckMessage(self, ackdata, _, TTL): + def generateFullAckMessage(self, ackdata, _, TTL): """ It might be perfectly fine to just use the same TTL for the ackdata that we use for the message. But I would rather it be more difficult for attackers to associate ackData with the associated msg object. However, users diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index d7bb158f..c655439c 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -573,6 +573,8 @@ class sqlThread(threading.Thread): rowcount = 0 # print 'item', item # print 'parameters', parameters + # if 'inbox' in item: + # import pdb; pdb.set_trace() try: self.cur.execute(item, parameters) rowcount = self.cur.rowcount diff --git a/src/highlevelcrypto.py b/src/highlevelcrypto.py index 03e2d1d3..ad073e47 100644 --- a/src/highlevelcrypto.py +++ b/src/highlevelcrypto.py @@ -54,6 +54,7 @@ def encrypt(msg, hexPubkey): def decrypt(msg, hexPrivkey): + print("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS#################################################") """Decrypts message with hex private key""" return makeCryptor(hexPrivkey).decrypt(msg) diff --git a/src/inventory.py b/src/inventory.py index fc06e455..e1566db5 100644 --- a/src/inventory.py +++ b/src/inventory.py @@ -24,6 +24,8 @@ class Inventory(): # cheap inheritance copied from asyncore def __getattr__(self, attr): + # attr = '__contains__' + print('$$$$$$$$$$$$$ inside the __getattr__ item $$$$$$$$$$$$$$$$') if attr == "__contains__": self.numberOfInventoryLookupsPerformed += 1 try: @@ -38,4 +40,5 @@ class Inventory(): # hint for pylint: this is dictionary like object def __getitem__(self, key): + print('@@@@@@@@@@@@@@@@@@ inside the __getitem__ item @@@@@@@@@@@@@@@') return self._realInventory[key] diff --git a/src/l10n.py b/src/l10n.py index bf727244..59c53cc2 100644 --- a/src/l10n.py +++ b/src/l10n.py @@ -123,7 +123,8 @@ def formatTimestamp(timestamp=None, as_unicode=True): timestring = time.strftime(time_format) if as_unicode: - return unicode(timestring, encoding) + return (timestring.encode('utf-8')) + # return unicode(timestring, encoding) return timestring diff --git a/src/network/bmproto.py b/src/network/bmproto.py index adca21f5..4e89fdfe 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -364,7 +364,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if now < self.skipUntil: return True for i in items: - self.pendingUpload[str(i)] = now + self.pendingUpload[bytes(i)] = now return True def _command_inv(self, dandelion=False): @@ -380,6 +380,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker): return True for i in map(bytes, items): + import pdb;pdb.set_trace() if i in Inventory() and not Dandelion().hasHash(i): continue if dandelion and not Dandelion().hasHash(i): @@ -443,13 +444,26 @@ class BMProto(AdvancedDispatcher, ObjectTracker): if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash): Dandelion().removeHash(self.object.inventoryHash, "cycle detection") - [self.object.inventoryHash] = ( + # import pdb; pdb.set_trace() - self.object.objectType, self.object.streamNumber, + inventoryHash_list = [self.object.objectType, self.object.streamNumber, memoryview(self.payload[objectOffset:]), self.object.expiresTime, - memoryview(self.object.tag) - ) - Inventory()[self.object.inventoryHash] + memoryview(self.object.tag)] + # [self.object.inventoryHash] = ( + + # self.object.objectType, self.object.streamNumber, + # memoryview(self.payload[objectOffset:]), self.object.expiresTime, + # memoryview(self.object.tag) + # ) + + + + # Inventory()[self.object.inventoryHash] = (self.object.objectType, self.object.streamNumber, + # buffer(self.payload[objectOffset:]), self.object.expiresTime, + # buffer(self.object.tag)) + + + self.handleReceivedObject( self.object.streamNumber, self.object.inventoryHash) invQueue.put(( diff --git a/src/network/invthread.py b/src/network/invthread.py index fa38e7c3..a4edb8a2 100644 --- a/src/network/invthread.py +++ b/src/network/invthread.py @@ -87,19 +87,19 @@ class InvThread(StoppableThread): fluffs.append(inv[1]) except KeyError: fluffs.append(inv[1]) - if fluffs: + # import pdb; pdb.set_trace() random.shuffle(fluffs) connection.append_write_buf(protocol.CreatePacket( 'inv', addresses.encodeVarint( - len(fluffs)) + ''.join(fluffs))) + len(fluffs)) + ('').encode().join([x for x in fluffs]))) #compare result with python2 if stems: random.shuffle(stems) connection.append_write_buf(protocol.CreatePacket( 'dinv', addresses.encodeVarint( - len(stems)) + ''.join(stems))) + len(stems)) + ('').encode().join([x for x in stems]))) #compare result with python2 invQueue.iterate() for _ in range(len(chunk)): diff --git a/src/network/tcp.py b/src/network/tcp.py index 47553751..8e5c92f4 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -211,6 +211,7 @@ class TCPConnection(BMProto, TLSDispatcher): # may lock for a long time, but I think it's better than # thousands of small locks with self.objectsNewToThemLock: + # import pdb;pdb.set_trace() for objHash in Inventory().unexpired_hashes_by_stream(stream): # don't advertise stem objects on bigInv if Dandelion().hasHash(objHash): @@ -220,18 +221,18 @@ class TCPConnection(BMProto, TLSDispatcher): payload = bytes() # Now let us start appending all of these hashes together. They will be # sent out in a big inv message to our new peer. + if len(bigInvList) is not 0: + for obj_hash, _ in bigInvList.items(): + payload += obj_hash + objectCount += 1 - for obj_hash, _ in bigInvList.items(): - payload += obj_hash - objectCount += 1 - - # Remove -1 below when sufficient time has passed for users to - # upgrade to versions of PyBitmessage that accept inv with 50,000 - # items - if objectCount >= MAX_OBJECT_COUNT - 1: - sendChunk() - payload = b'' - objectCount = 0 + # Remove -1 below when sufficient time has passed for users to + # upgrade to versions of PyBitmessage that accept inv with 50,000 + # items + if objectCount >= MAX_OBJECT_COUNT - 1: + sendChunk() + payload = b'' + objectCount = 0 # flush sendChunk() diff --git a/src/network/uploadthread.py b/src/network/uploadthread.py index 33daf525..2fcf039d 100644 --- a/src/network/uploadthread.py +++ b/src/network/uploadthread.py @@ -45,6 +45,7 @@ class UploadThread(StoppableThread): if Dandelion().hasHash(chunk) and \ i != Dandelion().objectChildStem(chunk): i.antiIntersectionDelay() + print self.logger.info( '%s asked for a stem object we didn\'t offer to it.', i.destination) diff --git a/src/proofofwork.py b/src/proofofwork.py index 18d8f332..8c2abff0 100644 --- a/src/proofofwork.py +++ b/src/proofofwork.py @@ -108,13 +108,13 @@ def _doFastPoW(target, initialHash): logger.debug("Fast PoW done") return result[0], result[1] time.sleep(0.2) + def _doCPoW(target, initialHash): - h = initialHash - m = target - out_h = ctypes.pointer(ctypes.create_string_buffer(h, 64)) - out_m = ctypes.c_ulonglong(m) + # import pdb; pdb.set_trace() + out_h = ctypes.pointer(ctypes.create_string_buffer(initialHash, 64)) + out_m = ctypes.c_ulonglong(target) logger.debug("C PoW start") nonce = bmpow(out_h, out_m) trialValue, = unpack('>Q', hashlib.sha512(hashlib.sha512(pack('>Q', nonce) + initialHash).digest()).digest()[0:8]) @@ -241,7 +241,6 @@ def buildCPoW(): def run(target, initialHash): """Run the proof of work thread""" - if state.shutdown != 0: raise # pylint: disable=misplaced-bare-raise target = int(target) @@ -254,6 +253,7 @@ def run(target, initialHash): pass # fallback if bmpow: try: + print('-------------inside the proofofwork-----------------') return _doCPoW(target, initialHash) except StopIteration: raise @@ -294,6 +294,8 @@ def init(): openclpow.initCL() if sys.platform == "win32": + print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') + print('inside the sys.platform == "win32"') if ctypes.sizeof(ctypes.c_voidp) == 4: bitmsglib = 'bitmsghash32.dll' else: @@ -326,13 +328,16 @@ def init(): bso = None else: + # import pdb; pdb.set_trace() + print('####################################') + print('else else else eles else ') try: bso = ctypes.CDLL(os.path.join(paths.codePath(), "bitmsghash", bitmsglib)) except OSError: import glob try: bso = ctypes.CDLL(glob.glob(os.path.join( - paths.codePath(), "bitmsghash", "bitmsghash*.so" + paths.codePath(), " ", "bitmsghash*.so" ))[0]) except (OSError, IndexError): bso = None @@ -349,4 +354,6 @@ def init(): else: bmpow = None if bmpow is None: + print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$') + print('intailed the bmpow') buildCPoW() diff --git a/src/protocol.py b/src/protocol.py index 6f84236e..029205a9 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -431,7 +431,7 @@ def decryptAndCheckPubkeyPayload(data, address): encryptedData = data[readPosition:] # Let us try to decrypt the pubkey - toAddress, cryptorObject = state.neededPubkeys[tag] + toAddress, cryptorObject = state.neededPubkeys[bytes(tag)] if toAddress != address: logger.critical( 'decryptAndCheckPubkeyPayload failed due to toAddress' @@ -444,6 +444,7 @@ def decryptAndCheckPubkeyPayload(data, address): # That sort of address-malleability should have been caught # by the UI or API and an error given to the user. return 'failed' + print("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW#################################################") try: decryptedData = cryptorObject.decrypt(encryptedData) except: @@ -451,13 +452,13 @@ def decryptAndCheckPubkeyPayload(data, address): # but tagged it with a tag for which we are watching. logger.info('Pubkey decryption was unsuccessful.') return 'failed' - readPosition = 0 # bitfieldBehaviors = decryptedData[readPosition:readPosition + 4] readPosition += 4 - publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64] + print("working fine till here#################################################################") + publicSigningKey = '\x04'.encode() + decryptedData[readPosition:readPosition + 64] readPosition += 64 - publicEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64] + publicEncryptionKey = '\x04'.encode() + decryptedData[readPosition:readPosition + 64] readPosition += 64 specifiedNonceTrialsPerByteLength = decodeVarint( decryptedData[readPosition:readPosition + 10])[1] @@ -471,7 +472,6 @@ def decryptAndCheckPubkeyPayload(data, address): decryptedData[readPosition:readPosition + 10]) readPosition += signatureLengthLength signature = decryptedData[readPosition:readPosition + signatureLength] - if not highlevelcrypto.verify( signedData, signature, hexlify(publicSigningKey)): logger.info( @@ -480,11 +480,9 @@ def decryptAndCheckPubkeyPayload(data, address): logger.info( 'ECDSA verify passed (within decryptAndCheckPubkeyPayload)') - sha = hashlib.new('sha512') sha.update(publicSigningKey + publicEncryptionKey) embeddedRipe = RIPEMD160Hash(sha.digest()).digest() - if embeddedRipe != ripe: # Although this pubkey object had the tag were were looking for # and was encrypted with the correct encryption key, @@ -503,9 +501,9 @@ def decryptAndCheckPubkeyPayload(data, address): addressVersion, streamNumber, hexlify(ripe), hexlify(publicSigningKey), hexlify(publicEncryptionKey) ) - t = (address, addressVersion, storedData, int(time.time()), 'yes') sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t) + print("successful Insertion of pubkey hurray#################################################") return 'successful' except varintDecodeError: logger.info( diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index e0eea823..37bb75a1 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -13,6 +13,7 @@ from storage.storage import InventoryStorage, InventoryItem class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors """Inventory using SQLite""" def __init__(self): + # import pdb;pdb.set_trace() super(SqliteInventory, self).__init__() # of objects (like msg payloads and pubkey payloads) # Does not include protocol headers (the first 24 bytes of each packet). @@ -29,7 +30,8 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors self.lock = RLock() def __contains__(self, hash_): - print('----------contains------------------') + print('__contains__(self, hash_)__contains__(self, hash_)__contains__(self, hash_) ',hash_) + hash_ = str(hash_).encode() if type(hash_) == int else hash_ with self.lock: if hash_ in self._objects: return True @@ -41,23 +43,38 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors self._objects[hash_] = rows[0][0] return True + # def __getitem__(self, hash_): + # raw = [None] + # # some think broke + # 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 + # except: + # rows = [hash_] + # return InventoryItem(*rows[0]) + def __getitem__(self, hash_): - if hash_ == 0: - hash_ = bytes() + # import pdb;pdb.set_trace() 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: - pass - # raise KeyError(hash_) - except: - pass + if hash_ in self._inventory: + return self._inventory[hash_] + rows = sqlQuery( + 'SELECT objecttype, streamnumber, payload, expirestime, tag' + ' FROM inventory WHERE hash=?', sqlite3.Binary(bytes(hash_))) + if not rows: + raise KeyError(hash_) return InventoryItem(*rows[0]) + def __setitem__(self, hash_, value): print('----------__setitem__------------------') with self.lock: @@ -95,13 +112,17 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors def unexpired_hashes_by_stream(self, stream): """Return unexpired inventory vectors filtered by stream""" + # print ('self._inventory.items() self._inventory.items() self._inventory.items()' ,self._inventory.items()) + # import pdb;pdb.set_trace() with self.lock: t = int(time.time()) hashes = [x for x, value in self._inventory.items() if value.stream == stream and value.expires > t] - hashes += (str(payload) for payload, in sqlQuery( + # print ('hasheshasheshasheshasheshasheshasheshasheshashes',hashes) + hashes += (payload for payload, in sqlQuery( 'SELECT hash FROM inventory WHERE streamnumber=?' ' AND expirestime>?', stream, t)) + # print ('hasheshasheshasheshasheshasheshasheshasheshashes aaaaaaaaffter',hashes) return hashes def flush(self): From ec618d9d1a198d1e7216101f2aff1bd8d011c3fd Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Mon, 27 Jan 2020 21:41:46 +0530 Subject: [PATCH 50/54] Solved sending message issues --- src/class_objectProcessor.py | 8 +-- src/class_singleWorker.py | 92 +++++++++-------------------------- src/class_sqlThread.py | 1 - src/inventory.py | 3 -- src/network/bmobject.py | 2 +- src/network/bmproto.py | 55 ++++----------------- src/network/downloadthread.py | 2 +- src/network/invthread.py | 1 - src/network/tcp.py | 27 +++++----- src/proofofwork.py | 9 ---- src/storage/sqlite.py | 39 ++------------- 11 files changed, 54 insertions(+), 185 deletions(-) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index f7930dce..6a832aa7 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -141,7 +141,7 @@ class objectProcessor(threading.Thread): if bytes(data[readPosition:]) in shared.ackdataForWhichImWatching: logger.info('This object is an acknowledgement bound for me.') - del shared.ackdataForWhichImWatching[data[readPosition:]] + del shared.ackdataForWhichImWatching[bytes(data[readPosition:])] sqlExecute( 'UPDATE sent SET status=?, lastactiontime=?' ' WHERE ackdata=?', @@ -234,7 +234,6 @@ class objectProcessor(threading.Thread): logger.debug( 'the tag requested in this getpubkey request is: %s', hexlify(requestedTag)) - # import pdb;pdb.set_trace() if bytes(requestedTag) in shared.myAddressesByTag: myAddress = shared.myAddressesByTag[bytes(requestedTag)] @@ -441,15 +440,12 @@ class objectProcessor(threading.Thread): return # Let us try to decrypt the pubkey - print("TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT#################################################", tag) toAddress, _ = state.neededPubkeys[bytes(tag)] #check with py2 - # import pdb;pdb.set_trace() - if protocol.decryptAndCheckPubkeyPayload(bytes(data), toAddress) == \ + if protocol.decryptAndCheckPubkeyPayload(bytes(data), toAddress) == \ 'successful': # At this point we know that we have been waiting on this # pubkey. This function will command the workerThread # to start work on the messages that require it. - print("decryptAndCheckPubkeyPayload completed#########################################################") self.possibleNewPubkey(toAddress) # Display timing data diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index 486308d7..f6494198 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -224,6 +224,7 @@ class singleWorker(StoppableThread): if log_time: start_time = time.time() trialValue, nonce = proofofwork.run(target, initialHash) + print("nonce calculated value#############################", nonce) self.logger.info( '%s Found proof of work %s Nonce: %s', log_prefix, trialValue, nonce @@ -679,7 +680,6 @@ class singleWorker(StoppableThread): """Send a message-type object (assemble the object, perform PoW and put it to the inv announcement queue)""" # pylint: disable=too-many-nested-blocks # Reset just in case - # import pdb;pdb.set_trace() sqlExecute( '''UPDATE sent SET status='msgqueued' ''' ''' WHERE status IN ('doingpubkeypow', 'doingmsgpow')''') @@ -690,7 +690,6 @@ class singleWorker(StoppableThread): ''' and folder LIKE '%sent%' ''') # while we have a msg that needs some work for row in queryreturn: - print(row, "rowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowrowv") toaddress, fromaddress, subject, message, \ ackdata, status, TTL, retryNumber, encoding = row # toStatus @@ -732,7 +731,6 @@ class singleWorker(StoppableThread): toaddress ) # If we have the needed pubkey in the pubkey table already, - print("sendmsg line no 734#####################################################################") if queryreturn != []: # set the status of this msg to doingmsgpow sqlExecute( @@ -753,7 +751,6 @@ class singleWorker(StoppableThread): ) # We don't have the needed pubkey in the pubkeys table already. else: - print("sendmsg line no 756#####################################################################") if toAddressVersionNumber <= 3: toTag = '' else: @@ -763,16 +760,14 @@ class singleWorker(StoppableThread): ).digest()).digest()[32:] if toaddress in state.neededPubkeys or \ toTag in state.neededPubkeys: - print("sendmsg line no 766#####################################################################") # We already sent a request for the pubkey sqlExecute( '''UPDATE sent SET status='awaitingpubkey', ''' ''' sleeptill=? WHERE toaddress=? ''' ''' AND status='msgqueued' ''', - int(10), + int(time.time()) + 2.5 * 24 * 60 * 60, toaddress ) - print("sendmsg line no 774#####################################################################") queues.UISignalQueue.put(( 'updateSentItemStatusByToAddress', ( toaddress, @@ -780,11 +775,9 @@ class singleWorker(StoppableThread): "MainWindow", "Encryption key was requested earlier.")) )) - print("sendmsg line no 783#####################################################################") # on with the next msg on which we can do some work continue else: - print("sendmsg line no 785#####################################################################") # We have not yet sent a request for the pubkey needToRequestPubkey = True # If we are trying to send to address @@ -812,7 +805,6 @@ class singleWorker(StoppableThread): highlevelcrypto.makeCryptor( hexlify(privEncryptionKey)) ) - for value in Inventory().by_type_and_tag(1, toTag): # if valid, this function also puts it # in the pubkeys table. @@ -858,7 +850,6 @@ class singleWorker(StoppableThread): self.requestPubKey(toaddress) # on with the next msg on which we can do some work continue - print("sendmsg line no 856#####################################################################") # At this point we know that we have the necessary pubkey # in the pubkeys table. TTL *= 2**retryNumber @@ -867,10 +858,8 @@ class singleWorker(StoppableThread): # add some randomness to the TTL TTL = int(TTL + helper_random.randomrandrange(-300, 300)) embeddedTime = int(time.time() + TTL) - print("sendmsg line no 870#####################################################################") # if we aren't sending this to ourselves or a chan if not BMConfigParser().has_section(toaddress): - print("sendmsg line no 873#####################################################################") shared.ackdataForWhichImWatching[ackdata] = 0 queues.UISignalQueue.put(( 'updateSentItemStatusByAckdata', ( @@ -878,22 +867,23 @@ class singleWorker(StoppableThread): tr._translate( "MainWindow", "Looking up the receiver\'s public key")) - )) + )) self.logger.info('Sending a message.') - self.logger.debug( - 'First 150 characters of message: %s', - repr(message[:150]) - ) + # self.logger.debug( + # 'First 150 characters of message: %s', + # repr(message[:150]) + # ) # Let us fetch the recipient's public key out of # our database. If the required proof of work difficulty # is too hard then we'll abort. + queryreturn = sqlQuery( 'SELECT transmitdata FROM pubkeys WHERE address=?', toaddress) for row in queryreturn: # pylint: disable=redefined-outer-name pubkeyPayload, = row - + # The pubkey message is stored with the following items # all appended: # -address version @@ -917,7 +907,7 @@ class singleWorker(StoppableThread): # if receiver is a mobile device who expects that their # address RIPE is included unencrypted on the front of - # the message.. + # the message.. if protocol.isBitSetWithinBitfield(behaviorBitfield, 30): # if we are Not willing to include the receiver's # RIPE hash on the message.. @@ -954,9 +944,8 @@ class singleWorker(StoppableThread): pubEncryptionKeyBase256 = pubkeyPayload[ readPosition:readPosition + 64] readPosition += 64 - # Let us fetch the amount of work required by the recipient. - if toAddressVersionNumber == 2: + if toAddressVersionNumber == 2: requiredAverageProofOfWorkNonceTrialsPerByte = \ defaults.networkDefaultProofOfWorkNonceTrialsPerByte requiredPayloadLengthExtraBytes = \ @@ -970,6 +959,7 @@ class singleWorker(StoppableThread): "There is no required difficulty for" " version 2 addresses like this.")) )) + elif toAddressVersionNumber >= 3: requiredAverageProofOfWorkNonceTrialsPerByte, \ varintLength = decodeVarint( @@ -996,7 +986,6 @@ class singleWorker(StoppableThread): requiredAverageProofOfWorkNonceTrialsPerByte, requiredPayloadLengthExtraBytes ) - queues.UISignalQueue.put( ( 'updateSentItemStatusByAckdata', @@ -1021,17 +1010,15 @@ class singleWorker(StoppableThread): ) ) ) - if status != 'forcepow': - maxacceptablenoncetrialsperbyte = BMConfigParser().getint( - 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte') - maxacceptablepayloadlengthextrabytes = BMConfigParser().getint( - 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes') + maxacceptablenoncetrialsperbyte = int(BMConfigParser().get( + 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) + maxacceptablepayloadlengthextrabytes = int(BMConfigParser().get( + 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) cond1 = maxacceptablenoncetrialsperbyte and \ requiredAverageProofOfWorkNonceTrialsPerByte > maxacceptablenoncetrialsperbyte cond2 = maxacceptablepayloadlengthextrabytes and \ requiredPayloadLengthExtraBytes > maxacceptablepayloadlengthextrabytes - if cond1 or cond2: # The demanded difficulty is more than # we are willing to do. @@ -1055,12 +1042,10 @@ class singleWorker(StoppableThread): l10n.formatTimestamp())))) continue else: # if we are sending a message to ourselves or a chan.. - print("sendmsg line no 1058#####################################################################") self.logger.info('Sending a message.') self.logger.debug( 'First 150 characters of message: %r', message[:150]) behaviorBitfield = protocol.getBitfield(fromaddress) - try: privEncryptionKeyBase58 = BMConfigParser().get( toaddress, 'privencryptionkey') @@ -1097,7 +1082,6 @@ class singleWorker(StoppableThread): "MainWindow", "Doing work necessary to send message.")) )) - print("sendmsg line no 1093#####################################################################") # Now we can start to assemble our message. payload = encodeVarint(fromAddressVersionNumber) payload += encodeVarint(fromStreamNumber) @@ -1105,10 +1089,8 @@ class singleWorker(StoppableThread): # that can be expected from me. (See # https://bitmessage.org/wiki/Protocol_specification#Pubkey_bitfield_features) payload += protocol.getBitfield(fromaddress) - print("sendmsg line no 1101#####################################################################") # We need to convert our private keys to public keys in order # to include them. - # import pdb; pdb.set_trace() try: privSigningKeyHex, privEncryptionKeyHex, \ pubSigningKey, pubEncryptionKey = self._getKeysForAddress( @@ -1123,9 +1105,7 @@ class singleWorker(StoppableThread): " (your address) in the keys.dat file.")) )) continue - print("sendmsg line no 1119#####################################################################") payload += pubSigningKey + pubEncryptionKey - if fromAddressVersionNumber >= 3: # If the receiver of our message is in our address book, # subscriptions list, or whitelist then we will allow them to @@ -1142,13 +1122,11 @@ class singleWorker(StoppableThread): fromaddress, 'noncetrialsperbyte'))) payload += encodeVarint(int(BMConfigParser().get( fromaddress, 'payloadlengthextrabytes'))) - print('@@@@@@@@@@@@@@ before payload creating@@@@@@@@@@@@@@@@') # This hash will be checked by the receiver of the message # to verify that toRipe belongs to them. This prevents # a Surreptitious Forwarding Attack. payload += toRipe payload += encodeVarint(encoding) # message encoding type - # import pdb;pdb.set_trace() encodedMessage = helper_msgcoding.MsgEncode( {"subject": subject, "body": message}, encoding ) @@ -1174,7 +1152,7 @@ class singleWorker(StoppableThread): fullAckPayload = self.generateFullAckMessage( ackdata, toStreamNumber, TTL) payload += encodeVarint(len(fullAckPayload)) - payload += fullAckPayload.encode() + payload += fullAckPayload if isinstance(fullAckPayload,bytes) else fullAckPayload.encode() dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02'.encode() + \ encodeVarint(1) + encodeVarint(toStreamNumber) + payload signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex) @@ -1201,7 +1179,6 @@ class singleWorker(StoppableThread): ).arg(l10n.formatTimestamp())) )) continue - print('@@@@@@@@@@@@@@ before encryptedPayload creating@@@@@@@@@@@@@@@@') encryptedPayload = pack('>Q', embeddedTime) encryptedPayload += '\x00\x00\x00\x02'.encode() # object type: msg encryptedPayload += encodeVarint(1) # msg version @@ -1226,10 +1203,7 @@ class singleWorker(StoppableThread): powStartTime = time.time() initialHash = hashlib.sha512(encryptedPayload).digest() - # import pdb; pdb.set_trace() - trialValue, nonce = proofofwork.run(target, initialHash) - print("nonce calculated value#############################", nonce) self.logger.info( '(For msg message) Found proof of work %s Nonce: %s', trialValue, nonce @@ -1242,8 +1216,6 @@ class singleWorker(StoppableThread): ) except: pass - print("line no 1234#########################################") - # import pdb; pdb.set_trace() encryptedPayload = pack('>Q', nonce) + encryptedPayload # Sanity check. The encryptedPayload size should never be @@ -1257,18 +1229,12 @@ class singleWorker(StoppableThread): len(encryptedPayload) ) continue - print("line no 1248#########################################") inventoryHash = calculateInventoryHash(encryptedPayload) - print("line no 1250248#########################################") objectType = 2 - print("line no 1252#########################################") - # import pdb; pdb.set_trace() inventoryHashlist = ( objectType, toStreamNumber,encryptedPayload, embeddedTime, '') - print("line no 1255#########################################") - # import pdb; pdb.set_trace() - Inventory()[inventoryHashlist] - print("line no 1257#########################################") + Inventory()._realInventory[inventoryHash] = ( + objectType, toStreamNumber, encryptedPayload, embeddedTime, '') if BMConfigParser().has_section(toaddress) or \ not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK): queues.UISignalQueue.put(( @@ -1289,7 +1255,6 @@ class singleWorker(StoppableThread): " Sent on %1" ).arg(l10n.formatTimestamp())) )) - print("line no 1282#########################################") self.logger.info( 'Broadcasting inv for my msg(within sendmsg function): %s', hexlify(inventoryHash) @@ -1297,7 +1262,6 @@ class singleWorker(StoppableThread): queues.invQueue.put((toStreamNumber, inventoryHash)) # Update the sent message in the sent table with the # necessary information. - print("line no 1290#########################################") if BMConfigParser().has_section(toaddress) or \ not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK): newStatus = 'msgsentnoackexpected' @@ -1313,7 +1277,6 @@ class singleWorker(StoppableThread): ) # If we are sending to ourselves or a chan, let's put # the message in our own inbox. - print("line no 1306#########################################") if BMConfigParser().has_section(toaddress): # Used to detect and ignore duplicate messages in our inbox sigHash = hashlib.sha512(hashlib.sha512( @@ -1340,7 +1303,6 @@ class singleWorker(StoppableThread): def requestPubKey(self, toAddress): """Send a getpubkey object""" - # import pdb;pdb.set_trace() toStatus, addressVersionNumber, streamNumber, ripe = decodeAddress( toAddress) if toStatus != 'success': @@ -1350,7 +1312,6 @@ class singleWorker(StoppableThread): toAddress ) return - queryReturn = sqlQuery( '''SELECT retrynumber FROM sent WHERE toaddress=? ''' ''' AND (status='doingpubkeypow' OR status='awaitingpubkey') ''' @@ -1365,10 +1326,9 @@ class singleWorker(StoppableThread): ) return retryNumber = queryReturn[0][0] - - if addressVersionNumber <= 3: + if addressVersionNumber <= 3: state.neededPubkeys[toAddress] = 0 - elif addressVersionNumber >= 4: + elif addressVersionNumber >= 4: # If the user just clicked 'send' then the tag # (and other information) will already be in the # neededPubkeys dictionary. But if we are recovering @@ -1424,17 +1384,14 @@ class singleWorker(StoppableThread): "MainWindow", "Doing work necessary to request encryption key.")) )) - payload = self._doPOWDefaults(payload, TTL) - inventoryHash = calculateInventoryHash(payload) objectType = 1 - inventoryHashlist = ( + Inventory()._realInventory[inventoryHash] = ( objectType, streamNumber, payload, embeddedTime, '') - Inventory()[inventoryHashlist] + # Inventory()._realInventory[inventoryHashlist] self.logger.info('sending inv (for the getpubkey message)') queues.invQueue.put((streamNumber, inventoryHash)) - # wait 10% past expiration sleeptill = int(time.time() + TTL * 1.1) sqlExecute( @@ -1443,7 +1400,6 @@ class singleWorker(StoppableThread): ''' WHERE toaddress=? AND (status='doingpubkeypow' OR ''' ''' status='awaitingpubkey') ''', int(time.time()), retryNumber + 1, sleeptill, toAddress) - queues.UISignalQueue.put(( 'updateStatusBar', tr._translate( @@ -1461,7 +1417,7 @@ class singleWorker(StoppableThread): ).arg(l10n.formatTimestamp())) )) - def generateFullAckMessage(self, ackdata, _, TTL): + def generateFullAckMessage(self, ackdata, _, TTL): """ It might be perfectly fine to just use the same TTL for the ackdata that we use for the message. But I would rather it be more difficult for attackers to associate ackData with the associated msg object. However, users diff --git a/src/class_sqlThread.py b/src/class_sqlThread.py index c655439c..7decb304 100644 --- a/src/class_sqlThread.py +++ b/src/class_sqlThread.py @@ -574,7 +574,6 @@ class sqlThread(threading.Thread): # print 'item', item # print 'parameters', parameters # if 'inbox' in item: - # import pdb; pdb.set_trace() try: self.cur.execute(item, parameters) rowcount = self.cur.rowcount diff --git a/src/inventory.py b/src/inventory.py index e1566db5..fc06e455 100644 --- a/src/inventory.py +++ b/src/inventory.py @@ -24,8 +24,6 @@ class Inventory(): # cheap inheritance copied from asyncore def __getattr__(self, attr): - # attr = '__contains__' - print('$$$$$$$$$$$$$ inside the __getattr__ item $$$$$$$$$$$$$$$$') if attr == "__contains__": self.numberOfInventoryLookupsPerformed += 1 try: @@ -40,5 +38,4 @@ class Inventory(): # hint for pylint: this is dictionary like object def __getitem__(self, key): - print('@@@@@@@@@@@@@@@@@@ inside the __getitem__ item @@@@@@@@@@@@@@@') return self._realInventory[key] diff --git a/src/network/bmobject.py b/src/network/bmobject.py index 12b997d7..ee3bd388 100644 --- a/src/network/bmobject.py +++ b/src/network/bmobject.py @@ -116,7 +116,7 @@ class BMObject(object): # pylint: disable=too-many-instance-attributes # if it's a stem duplicate, pretend we don't have it if Dandelion().hasHash(self.inventoryHash): return - if self.inventoryHash in Inventory(): + if self.inventoryHash in Inventory()._realInventory: raise BMObjectAlreadyHaveError() def checkObjectByType(self): diff --git a/src/network/bmproto.py b/src/network/bmproto.py index 4e89fdfe..cd29a38a 100644 --- a/src/network/bmproto.py +++ b/src/network/bmproto.py @@ -34,20 +34,6 @@ from network.node import Node, Peer from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from network.randomtrackingdict import RandomTrackingDict -global addr_count -addr_count = 0 - -global addr_verack -addr_verack = 0 - -global addr_version -addr_version = 0 - -# global addr_count -# addr_count = 0 - -count = 0 - logger = logging.getLogger('default') @@ -100,14 +86,6 @@ class BMProto(AdvancedDispatcher, ObjectTracker): # 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(): - addr_verack += 1 - if self.command == 'version'.encode(): - addr_version += 1 - if self.command == 'addr'.encode(): - addr_count += 1 if self.magic != 0xE9BEB4D9: self.set_state("bm_header", length=1) self.bm_proto_reset() @@ -377,11 +355,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker): # ignore dinv if dandelion turned off if dandelion and not state.dandelion: - return True - + return True for i in map(bytes, items): - import pdb;pdb.set_trace() - if i in Inventory() and not Dandelion().hasHash(i): + if i in Inventory()._realInventory and not Dandelion().hasHash(i): continue if dandelion and not Dandelion().hasHash(i): Dandelion().addHash(i, self) @@ -442,28 +418,15 @@ class BMProto(AdvancedDispatcher, ObjectTracker): except KeyError: pass - if self.object.inventoryHash in Inventory() and Dandelion().hasHash(self.object.inventoryHash): + if self.object.inventoryHash in Inventory()._realInventory and Dandelion().hasHash(self.object.inventoryHash): Dandelion().removeHash(self.object.inventoryHash, "cycle detection") - # import pdb; pdb.set_trace() + [self.object.inventoryHash] = ( - inventoryHash_list = [self.object.objectType, self.object.streamNumber, + self.object.objectType, self.object.streamNumber, memoryview(self.payload[objectOffset:]), self.object.expiresTime, - memoryview(self.object.tag)] - # [self.object.inventoryHash] = ( - - # self.object.objectType, self.object.streamNumber, - # memoryview(self.payload[objectOffset:]), self.object.expiresTime, - # memoryview(self.object.tag) - # ) - - - - # Inventory()[self.object.inventoryHash] = (self.object.objectType, self.object.streamNumber, - # buffer(self.payload[objectOffset:]), self.object.expiresTime, - # buffer(self.object.tag)) - - - + memoryview(self.object.tag) + ) + Inventory()[self.object.inventoryHash] self.handleReceivedObject( self.object.streamNumber, self.object.inventoryHash) invQueue.put(( @@ -738,4 +701,4 @@ class BMStringParser(BMProto): except Exception as e: logger.debug( 'Exception of type %s while sending ACK', - type(e), exc_info=True) + type(e), exc_info=True) \ No newline at end of file diff --git a/src/network/downloadthread.py b/src/network/downloadthread.py index 323819ca..bf0344b3 100644 --- a/src/network/downloadthread.py +++ b/src/network/downloadthread.py @@ -61,7 +61,7 @@ class DownloadThread(StoppableThread): payload = bytearray() chunkCount = 0 for chunk in request: - if chunk in Inventory() and not Dandelion().hasHash(chunk): + if chunk in Inventory()._realInventory and not Dandelion().hasHash(chunk): try: del i.objectsNewToMe[chunk] except KeyError: diff --git a/src/network/invthread.py b/src/network/invthread.py index a4edb8a2..1a4b7514 100644 --- a/src/network/invthread.py +++ b/src/network/invthread.py @@ -88,7 +88,6 @@ class InvThread(StoppableThread): except KeyError: fluffs.append(inv[1]) if fluffs: - # import pdb; pdb.set_trace() random.shuffle(fluffs) connection.append_write_buf(protocol.CreatePacket( 'inv', diff --git a/src/network/tcp.py b/src/network/tcp.py index 8e5c92f4..72a66772 100644 --- a/src/network/tcp.py +++ b/src/network/tcp.py @@ -211,8 +211,7 @@ class TCPConnection(BMProto, TLSDispatcher): # may lock for a long time, but I think it's better than # thousands of small locks with self.objectsNewToThemLock: - # import pdb;pdb.set_trace() - for objHash in Inventory().unexpired_hashes_by_stream(stream): + for objHash in Inventory()._realInventory.unexpired_hashes_by_stream(stream): # don't advertise stem objects on bigInv if Dandelion().hasHash(objHash): continue @@ -221,18 +220,18 @@ class TCPConnection(BMProto, TLSDispatcher): payload = bytes() # Now let us start appending all of these hashes together. They will be # sent out in a big inv message to our new peer. - if len(bigInvList) is not 0: - for obj_hash, _ in bigInvList.items(): - payload += obj_hash - objectCount += 1 - # Remove -1 below when sufficient time has passed for users to - # upgrade to versions of PyBitmessage that accept inv with 50,000 - # items - if objectCount >= MAX_OBJECT_COUNT - 1: - sendChunk() - payload = b'' - objectCount = 0 + for obj_hash, _ in bigInvList.items(): + payload += obj_hash + objectCount += 1 + + # Remove -1 below when sufficient time has passed for users to + # upgrade to versions of PyBitmessage that accept inv with 50,000 + # items + if objectCount >= MAX_OBJECT_COUNT - 1: + sendChunk() + payload = b'' + objectCount = 0 # flush sendChunk() @@ -429,4 +428,4 @@ class TCPServer(AdvancedDispatcher): connectionpool.BMConnectionPool().addConnection( TCPConnection(sock=sock)) except socket.error: - pass + pass \ No newline at end of file diff --git a/src/proofofwork.py b/src/proofofwork.py index 8c2abff0..945eb7ec 100644 --- a/src/proofofwork.py +++ b/src/proofofwork.py @@ -112,7 +112,6 @@ def _doFastPoW(target, initialHash): def _doCPoW(target, initialHash): - # import pdb; pdb.set_trace() out_h = ctypes.pointer(ctypes.create_string_buffer(initialHash, 64)) out_m = ctypes.c_ulonglong(target) logger.debug("C PoW start") @@ -253,7 +252,6 @@ def run(target, initialHash): pass # fallback if bmpow: try: - print('-------------inside the proofofwork-----------------') return _doCPoW(target, initialHash) except StopIteration: raise @@ -294,8 +292,6 @@ def init(): openclpow.initCL() if sys.platform == "win32": - print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@') - print('inside the sys.platform == "win32"') if ctypes.sizeof(ctypes.c_voidp) == 4: bitmsglib = 'bitmsghash32.dll' else: @@ -328,9 +324,6 @@ def init(): bso = None else: - # import pdb; pdb.set_trace() - print('####################################') - print('else else else eles else ') try: bso = ctypes.CDLL(os.path.join(paths.codePath(), "bitmsghash", bitmsglib)) except OSError: @@ -354,6 +347,4 @@ def init(): else: bmpow = None if bmpow is None: - print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$') - print('intailed the bmpow') buildCPoW() diff --git a/src/storage/sqlite.py b/src/storage/sqlite.py index 37bb75a1..912caf0d 100644 --- a/src/storage/sqlite.py +++ b/src/storage/sqlite.py @@ -13,7 +13,6 @@ from storage.storage import InventoryStorage, InventoryItem class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors """Inventory using SQLite""" def __init__(self): - # import pdb;pdb.set_trace() super(SqliteInventory, self).__init__() # of objects (like msg payloads and pubkey payloads) # Does not include protocol headers (the first 24 bytes of each packet). @@ -30,8 +29,6 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors self.lock = RLock() def __contains__(self, hash_): - print('__contains__(self, hash_)__contains__(self, hash_)__contains__(self, hash_) ',hash_) - hash_ = str(hash_).encode() if type(hash_) == int else hash_ with self.lock: if hash_ in self._objects: return True @@ -42,59 +39,34 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors return False self._objects[hash_] = rows[0][0] return True - - # def __getitem__(self, hash_): - # raw = [None] - # # some think broke - # 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 - # except: - # rows = [hash_] - # return InventoryItem(*rows[0]) - + def __getitem__(self, hash_): - # import pdb;pdb.set_trace() with self.lock: if hash_ in self._inventory: return self._inventory[hash_] rows = sqlQuery( 'SELECT objecttype, streamnumber, payload, expirestime, tag' - ' FROM inventory WHERE hash=?', sqlite3.Binary(bytes(hash_))) + ' FROM inventory WHERE hash=?', sqlite3.Binary(hash_)) if not rows: raise KeyError(hash_) - return InventoryItem(*rows[0]) - + return InventoryItem(*rows[0]) def __setitem__(self, hash_, value): - print('----------__setitem__------------------') with self.lock: value = InventoryItem(*value) self._inventory[hash_] = value self._objects[hash_] = value.stream def __delitem__(self, hash_): - print('----------__delitem__------------------') raise NotImplementedError def __iter__(self): - print('----------__iter__------------------') with self.lock: hashes = self._inventory.keys()[:] hashes += (x for x, in sqlQuery('SELECT hash FROM inventory')) return hashes.__iter__() def __len__(self): - print('----------__len__------------------') with self.lock: return len(self._inventory) + sqlQuery( 'SELECT count(*) FROM inventory')[0][0] @@ -112,17 +84,14 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors def unexpired_hashes_by_stream(self, stream): """Return unexpired inventory vectors filtered by stream""" - # print ('self._inventory.items() self._inventory.items() self._inventory.items()' ,self._inventory.items()) - # import pdb;pdb.set_trace() with self.lock: t = int(time.time()) hashes = [x for x, value in self._inventory.items() if value.stream == stream and value.expires > t] - # print ('hasheshasheshasheshasheshasheshasheshasheshashes',hashes) hashes += (payload for payload, in sqlQuery( 'SELECT hash FROM inventory WHERE streamnumber=?' ' AND expirestime>?', stream, t)) - # print ('hasheshasheshasheshasheshasheshasheshasheshashes aaaaaaaaffter',hashes) + # print('sqlllllllllllllllllllllllllllllllllll',hashes) return hashes def flush(self): From ca538668abe2d853b950d39e59c73d5c5b7a2272 Mon Sep 17 00:00:00 2001 From: navjot Date: Tue, 28 Jan 2020 15:49:11 +0530 Subject: [PATCH 51/54] worked on time text or address disable and enable feature --- src/bitmessagekivy/kivy_helper_search.py | 10 +- src/bitmessagekivy/kv/composer.kv | 6 +- src/bitmessagekivy/kv/payment.kv | 6 +- src/bitmessagekivy/kv/popup.kv | 2 +- src/bitmessagekivy/main.kv | 41 ++++--- src/bitmessagekivy/mpybit.py | 139 +++++++++++++++++++---- 6 files changed, 149 insertions(+), 55 deletions(-) diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index 1c410df0..5842d116 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -16,22 +16,18 @@ def search_sql( if folder in ("sent", "draft"): sqlStatementBase = ( '''SELECT toaddress, fromaddress, subject, message, status,''' - ''' ackdata, lastactiontime FROM sent ''' + ''' ackdata, senttime FROM sent ''' ) elif folder == "addressbook": sqlStatementBase = '''SELECT label, address From addressbook ''' else: sqlStatementBase = ( - '''SELECT folder, toaddress, message, fromaddress,''' + '''SELECT folder, msgid, toaddress, message, fromaddress,''' ''' subject, received, read FROM inbox ''' ) sqlStatementParts = [] sqlArguments = [] if account is not None: - #xAddress = 'toaddress' - #where = ['subject', 'message'] - #what = None - #unreadOnly = False if xAddress == 'both': sqlStatementParts.append("(fromaddress = ? OR toaddress = ?)") sqlArguments.append(account) @@ -67,7 +63,7 @@ def search_sql( # if folder in ("sent", "draft"): if folder in ("sent", "draft"): sqlStatementBase += \ - "ORDER BY lastactiontime DESC limit {0}, {1}".format( + "ORDER BY senttime DESC limit {0}, {1}".format( start_indx, end_indx) elif folder == "inbox": sqlStatementBase += \ diff --git a/src/bitmessagekivy/kv/composer.kv b/src/bitmessagekivy/kv/composer.kv index 25bdae7e..25a47e3d 100644 --- a/src/bitmessagekivy/kv/composer.kv +++ b/src/bitmessagekivy/kv/composer.kv @@ -27,8 +27,10 @@ values: app.variable_1 on_text: root.auto_fill_fromaddr() if self.text != 'Select' else '' option_cls: Factory.get("MySpinnerOption") - background_color: color_button if self.state == 'normal' else color_button_pressed - background_down: 'atlas://data/images/defaulttheme/spinner' + #background_color: color_button if self.state == 'normal' else color_button_pressed + #background_down: 'atlas://data/images/defaulttheme/spinner' + background_normal: '' + background_color: app.theme_cls.primary_color color: color_font font_size: '12.5sp' ArrowImg: diff --git a/src/bitmessagekivy/kv/payment.kv b/src/bitmessagekivy/kv/payment.kv index 3eb92000..2398817f 100644 --- a/src/bitmessagekivy/kv/payment.kv +++ b/src/bitmessagekivy/kv/payment.kv @@ -45,7 +45,7 @@ Rectangle: pos: self.pos size: self.size - size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 + size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1 height: dp(40) on_press: root.get_available_credits(self) MDLabel: @@ -90,7 +90,7 @@ Rectangle: pos: self.pos size: self.size - size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 + size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1 height: dp(40) MDLabel: font_style: 'H6' @@ -134,7 +134,7 @@ Rectangle: pos: self.pos size: self.size - size: dp(app.window_size[0]) - 2*dp(app.window_size[0]/16 if app.window_size[0] <= 720 else app.window_size[0]/4*1.1) - 10 , 1 + size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1 height: dp(40) MDLabel: font_style: 'H6' diff --git a/src/bitmessagekivy/kv/popup.kv b/src/bitmessagekivy/kv/popup.kv index b6d0106c..b83ef5d7 100644 --- a/src/bitmessagekivy/kv/popup.kv +++ b/src/bitmessagekivy/kv/popup.kv @@ -275,7 +275,7 @@ theme_text_color: 'Primary' text: "Bitmessage isn't connected to the network.\n If you quit now, it may cause delivery delays.\n Wait until connected and the synchronisation finishes?" font_size: '17sp' - halign: 'left' + halign: 'center' BoxLayout: id: my_add_btn spacing:5 diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 1ecf10e3..a6cba9c0 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -24,8 +24,10 @@ : font_size: '12.5sp' - background_color: color_button if self.state == 'down' else color_button_pressed - background_down: 'atlas://data/images/defaulttheme/button' + #background_color: color_button if self.state == 'down' else color_button_pressed + #background_down: 'atlas://data/images/defaulttheme/button' + background_normal: '' + background_color: app.theme_cls.primary_color color: color_font @@ -81,16 +83,21 @@ NavigationDrawerDivider: NavigationDrawerSubheader: text: "Accounts" + height:"35dp" NavigationItem: + size: 50,50 CustomSpinner: id: btn pos_hint:{"x":0,"y":0} option_cls: Factory.get("MySpinnerOption") font_size: '10.9sp' text: app.getDefaultAccData() - background_color: color_button if self.state == 'normal' else color_button_pressed - background_down: 'atlas://data/images/defaulttheme/spinner' + #background_color: color_button if self.state == 'normal' else color_button_pressed + #background_down: 'atlas://data/images/defaulttheme/spinner' color: color_font + background_normal: '' + background_color: app.theme_cls.primary_color + #background_color: (0.62,0.67,0.72,1) values: app.variable_1 on_text:app.getCurrentAccountData(self.text) Image: @@ -105,7 +112,7 @@ icon: 'email-open' divider: None on_release: app.root.ids.scr_mngr.current = 'inbox' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() on_press: app.load_screen(self) NavigationItem: id: send_cnt @@ -113,28 +120,28 @@ icon: 'send' divider: None on_release: app.root.ids.scr_mngr.current = 'sent' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: id: draft_cnt text: 'Draft' icon: 'message-draw' divider: None on_release: app.root.ids.scr_mngr.current = 'draft' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: id: trash_cnt text: 'Trash' icon: 'delete' divider: None on_release: app.root.ids.scr_mngr.current = 'trash' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: id: allmail_cnt text: 'All Mails' icon: 'contact-mail' divider: None on_release: app.root.ids.scr_mngr.current = 'allmails' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() on_press: app.load_screen(self) NavigationDrawerDivider: NavigationDrawerSubheader: @@ -144,43 +151,43 @@ icon: 'book-multiple' divider: None on_release: app.root.ids.scr_mngr.current = 'addressbook' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: text: 'Settings' icon: 'settings' divider: None on_release: app.root.ids.scr_mngr.current = 'set' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: text: 'Payment' icon: 'bell' divider: None on_release: app.root.ids.scr_mngr.current = 'payment' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: text: 'Credits' icon: 'wallet' divider: None on_release: app.root.ids.scr_mngr.current = 'credits' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: text: 'New address' icon: 'account-plus' divider: None on_release: app.root.ids.scr_mngr.current = 'login' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: text: 'Network status' icon: 'server-network' divider: None on_release: app.root.ids.scr_mngr.current = 'networkstat' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationItem: text: 'My addresses' icon: 'account-multiple' divider: None on_release: app.root.ids.scr_mngr.current = 'myaddress' - on_release: root.parent.toggle_nav_drawer() + on_release: root.parent.set_state() NavigationLayout: id: nav_layout @@ -193,7 +200,7 @@ NavigationLayout: pos_hint: {"top": 1} md_bg_color: app.theme_cls.primary_color elevation: 10 - left_action_items: [['menu', lambda x: nav_drawer.toggle_nav_drawer()]] + left_action_items: [['menu', lambda x: nav_drawer.set_state("toggle")]] right_action_items: [['account-plus', lambda x: app.addingtoaddressbook()]] ScreenManager: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 641da408..847653c3 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -62,6 +62,8 @@ from semaphores import kivyuisignaler import state from addresses import decodeAddress +from kivy.config import Config +Config.set('input', 'mouse', 'mouse,multitouch_on_demand') # pylint: disable=too-few-public-methods,too-many-arguments,attribute-defined-outside-init KVFILES = [ @@ -85,6 +87,30 @@ def showLimitedCnt(total_msg): return "99+" if total_msg > 99 else str(total_msg) +def ShowTimeHistoy(act_time): + """This method is used to return the message sent or receive time""" + from datetime import datetime + action_time = datetime.fromtimestamp(int(act_time)) + crnt_date = datetime.now() + duration = crnt_date - action_time + display_data = (action_time.strftime('%d/%m/%Y') + if duration.days >= 365 else action_time.strftime('%I:%M %p').lstrip('0') + if duration.days == 0 and crnt_date.strftime('%d/%m/%Y') == action_time.strftime('%d/%m/%Y') + else action_time.strftime("%d %b")) + return display_data + + +def AddTimeWidget(time): + """This method is used to create TimeWidget""" + action_time = BadgeText( + size_hint= (None, None), + text= f"{ShowTimeHistoy(time)}", + halign='right', + font_style='Caption', + size= [65,70]) + return action_time + + class Inbox(Screen): """Inbox Screen uses screen to show widgets of screens""" @@ -118,6 +144,7 @@ class Inbox(Screen): what = state.searcing_text xAddress = 'toaddress' data = [] + self.ids.identi_tag.children[0].text = '' self.inboxDataQuery(xAddress, where, what) self.ids.identi_tag.children[0].text = '' if self.queryreturn: @@ -131,7 +158,7 @@ class Inbox(Screen): 'secondary_text': mail[5][:50] + '........' if len( mail[5]) >= 50 else (mail[5] + ',' + mail[3].replace( '\n', ''))[0:50] + '........', - 'msgid': mail[1]}) + 'msgid': mail[1], 'received': mail[6]}) self.has_refreshed = True self.set_mdList(data) self.children[2].children[0].children[0].bind( @@ -171,6 +198,7 @@ class Inbox(Screen): source='./images/text_images/{}.png'.format( avatarImageFirstLetter(item['secondary_text'].strip())))) meny.bind(on_press=partial(self.inbox_detail, item['msgid'])) + meny.add_widget(AddTimeWidget(item['received'])) carousel = Carousel(direction='right') carousel.height = meny.height carousel.size_hint_y = None @@ -183,10 +211,10 @@ class Inbox(Screen): del_btn.bind(on_press=partial(self.delete, item['msgid'])) carousel.add_widget(del_btn) carousel.add_widget(meny) - ach_btn = Button(text='Achieve') - ach_btn.background_color = (0, 1, 0, 1) - ach_btn.bind(on_press=partial(self.archive, item['msgid'])) - carousel.add_widget(ach_btn) + # ach_btn = Button(text='Achieve') + # ach_btn.background_color = (0, 1, 0, 1) + # ach_btn.bind(on_press=partial(self.archive, item['msgid'])) + # carousel.add_widget(ach_btn) carousel.index = 1 self.ids.ml.add_widget(carousel) update_message = len(self.ids.ml.children) @@ -304,7 +332,9 @@ class MyAddress(Screen): def init_ui(self, dt=0): """Clock schdule for method Myaddress accounts""" - self.addresses_list = state.kivyapp.variable_1 + # pylint: disable=unnecessary-lambda, deprecated-lambda + # self.addresses_list = state.kivyapp.variable_1 + self.addresses_list = BMConfigParser().addresses() if state.searcing_text: self.ids.refresh_layout.scroll_y = 1.0 filtered_list = [ @@ -343,16 +373,34 @@ class MyAddress(Screen): 'text': BMConfigParser().get(address, 'label'), 'secondary_text': address}) for item in data: + is_enable = BMConfigParser().get(item['secondary_text'], 'enabled') meny = TwoLineAvatarIconListItem( text=item['text'], secondary_text=item['secondary_text'], - theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) + theme_text_color='Custom' if is_enable == 'true' else 'Primary', + text_color=NavigateApp().theme_cls.primary_color, + disabled=False if is_enable == 'true' else True) meny.add_widget(AvatarSampleWidget( source='./images/text_images/{}.png'.format( avatarImageFirstLetter(item['text'].strip())))) meny.bind(on_press=partial( self.myadd_detail, item['secondary_text'], item['text'])) - self.ids.ml.add_widget(meny) + carousel = Carousel(direction='right') + carousel.height = meny.height + carousel.size_hint_y = None + carousel.ignore_perpendicular_swipes = True + carousel.data_index = 0 + carousel.min_move = 0.2 + del_btn = Button(text='Disable' if is_enable == 'true' else 'Enable') + if is_enable == 'true': + del_btn.background_normal = '' + del_btn.background_color = (1, 0, 0, 1) if is_enable == 'true' else (0, 1, 0, 1) + del_btn.bind( + on_press=partial( + self.disableAddress if is_enable == 'true' else self.enableAddress , item['secondary_text'])) + carousel.add_widget(del_btn) + carousel.add_widget(meny) + carousel.index = 1 + self.ids.ml.add_widget(carousel) def check_scroll_y(self, instance, somethingelse): """Load data on scroll down""" @@ -406,6 +454,33 @@ class MyAddress(Screen): return True return False + def disableAddress(self, address, instance, *args): + """This method is use for disabling address""" + BMConfigParser().set(str(address), 'enabled', 'false') + BMConfigParser().save() + state.kivyapp.loadMyAddressScreen(True) + state.kivyapp.root.ids.sc10.ids.ml.clear_widgets() + Clock.schedule_once(self.address_permision_callback, 0) + # state.kivyapp.root.ids.sc10.init_ui() + pass + + def enableAddress(self, address, instance, *args): + """This method is use for enabling address""" + BMConfigParser().set(address, 'enabled', 'true') + BMConfigParser().save() + state.kivyapp.loadMyAddressScreen(True) + state.kivyapp.root.ids.sc10.ids.ml.clear_widgets() + Clock.schedule_once(self.address_permision_callback, 0) + + # @staticmethod + def address_permision_callback(self, dt=0): + """New address created""" + state.kivyapp.loadMyAddressScreen(False) + state.kivyapp.root.ids.sc10.init_ui() + addresses = [addr for addr in BMConfigParser().addresses() + if BMConfigParser().get(str(addr), 'enabled') == 'true'] + self.parent.parent.ids.content_drawer.ids.btn.values = addresses + self.parent.parent.ids.sc3.children[1].ids.btn.values = addresses class AddressBook(Screen): """AddressBook Screen uses screen to show widgets of screens""" @@ -570,8 +645,8 @@ class DropDownWidget(BoxLayout): def send(self, navApp): """Send message from one address to another""" - fromAddress = str(self.ids.ti.text) - toAddress = str(self.ids.txt_input.text) + fromAddress = self.ids.ti.text.strip() + toAddress = self.ids.txt_input.text.strip() subject = self.ids.subject.text.strip() message = self.ids.body.text.strip() encoding = 3 @@ -909,7 +984,7 @@ class Sent(Screen): 'secondary_text': mail[2][:50] + '........' if len( mail[2]) >= 50 else (mail[2] + ',' + mail[3].replace( '\n', ''))[0:50] + '........', - 'ackdata': mail[5]}) + 'ackdata': mail[5], 'senttime': mail[6]},) self.set_mdlist(data, 0) self.has_refreshed = True self.ids.scroll_y.bind(scroll_y=self.check_scroll_y) @@ -944,11 +1019,13 @@ class Sent(Screen): meny = TwoLineAvatarIconListItem( text=item['text'], secondary_text=item['secondary_text'], theme_text_color='Custom', - text_color=NavigateApp().theme_cls.primary_color) + text_color=NavigateApp().theme_cls.primary_color + ) meny.add_widget(AvatarSampleWidget( source='./images/text_images/{}.png'.format( avatarImageFirstLetter(item['secondary_text'].strip())))) meny.bind(on_press=partial(self.sent_detail, item['ackdata'])) + meny.add_widget(AddTimeWidget(item['senttime'])) carousel = Carousel(direction='right') carousel.height = meny.height carousel.size_hint_y = None @@ -961,10 +1038,10 @@ class Sent(Screen): del_btn.bind(on_press=partial(self.delete, item['ackdata'])) carousel.add_widget(del_btn) carousel.add_widget(meny) - ach_btn = Button(text='Achieve') - ach_btn.background_color = (0, 1, 0, 1) - ach_btn.bind(on_press=partial(self.archive, item['ackdata'])) - carousel.add_widget(ach_btn) + # ach_btn = Button(text='Achieve') + # ach_btn.background_color = (0, 1, 0, 1) + # ach_btn.bind(on_press=partial(self.archive, item['ackdata'])) + # carousel.add_widget(ach_btn) carousel.index = 1 self.ids.ml.add_widget(carousel, index=set_index) updated_msgs = len(self.ids.ml.children) @@ -989,7 +1066,7 @@ class Sent(Screen): 'secondary_text': mail[2][:50] + '........' if len( mail[2]) >= 50 else (mail[2] + ',' + mail[3].replace( '\n', ''))[0:50] + '........', - 'ackdata': mail[5]}) + 'ackdata': mail[5], 'senttime': mail[6]}) self.set_mdlist(data, total_sent - 1) if state.msg_counter_objs and state.association == ( state.check_sent_acc): @@ -1026,8 +1103,11 @@ class Sent(Screen): def set_sentCount(total_sent): """Set the total no. of sent message count""" src_mng_obj = state.kivyapp.root.ids.content_drawer.ids.send_cnt - src_mng_obj.children[0].children[0].text = showLimitedCnt(int(total_sent)) - state.sent_count = str(total_sent) + if state.association: + src_mng_obj.children[0].children[0].text = showLimitedCnt(int(total_sent)) + # state.sent_count = str(total_sent) + else: + src_mng_obj.children[0].children[0].text = '0' def sent_detail(self, ackdata, *args): """Load sent mail details""" @@ -1125,7 +1205,7 @@ class Trash(Screen): self.trash_messages = sqlQuery( "SELECT toaddress, fromaddress, subject, message," " folder ||',' || 'sent' as folder, ackdata As" - " id, DATE(lastactiontime) As actionTime FROM sent" + " id, DATE(senttime) As actionTime FROM sent" " WHERE folder = 'trash' and fromaddress = '{0}' UNION" " SELECT toaddress, fromaddress, subject, message," " folder ||',' || 'inbox' as folder, msgid As id," @@ -1269,7 +1349,8 @@ class NavigateApp(MDApp): # theme_cls = ThemeManager() previous_date = ObjectProperty() obj_1 = ObjectProperty() - variable_1 = ListProperty(BMConfigParser().addresses()) + variable_1 = ListProperty(addr for addr in BMConfigParser().addresses() + if BMConfigParser().get(str(addr), 'enabled') == 'true') nav_drawer = ObjectProperty() state.screen_density = Window.size window_size = state.screen_density @@ -1515,6 +1596,12 @@ class NavigateApp(MDApp): ['send', lambda x: self.root.ids.sc3.children[1].send(self)]] + def set_toolbar_for_QrCode(self): + """This method is use for setting Qr code toolbar.""" + self.root.ids.toolbar.left_action_items = [ + ['arrow-left', lambda x: self.back_press()]] + self.root.ids.toolbar.right_action_items = [] + def set_common_header(self): """Common header for all window""" self.root.ids.toolbar.right_action_items = [ @@ -1522,7 +1609,7 @@ class NavigateApp(MDApp): # self.root.ids.toolbar.left_action_items = [ # ['menu', lambda x: self.root.toggle_nav_drawer()]] self.root.ids.toolbar.left_action_items = [ - ['menu', lambda x: self.root.ids.nav_drawer.toggle_nav_drawer()]] + ['menu', lambda x: self.root.ids.nav_drawer.set_state("toggle")]] return def back_press(self): @@ -1540,7 +1627,8 @@ class NavigateApp(MDApp): self.root.ids.scr_mngr.current = 'inbox' \ if state.in_composer else 'allmails'\ if state.is_allmail else state.detailPageType\ - if state.detailPageType else 'inbox' + if state.detailPageType else 'myaddress'\ + if self.root.ids.scr_mngr.current == 'showqrcode' else 'inbox' self.root.ids.scr_mngr.transition.direction = 'right' self.root.ids.scr_mngr.transition.bind(on_complete=self.reset) if state.is_allmail or state.detailPageType == 'draft': @@ -2122,6 +2210,7 @@ class ShowQRCode(Screen): def qrdisplay(self): """Method used for showing QR Code""" self.ids.qr.clear_widgets() + state.kivyapp.set_toolbar_for_QrCode() from kivy.garden.qrcode import QRCodeWidget try: address = self.manager.get_parent_window().children[0].address @@ -2383,7 +2472,7 @@ class Allmails(Screen): """Retrieving data from inbox or sent both tables""" self.all_mails = sqlQuery( "SELECT toaddress, fromaddress, subject, message, folder, ackdata" - " As id, DATE(lastactiontime) As actionTime FROM sent WHERE" + " As id, DATE(senttime) As actionTime FROM sent WHERE" " folder = 'sent' and fromaddress = '{0}'" " UNION SELECT toaddress, fromaddress, subject, message, folder," " msgid As id, DATE(received) As actionTime FROM inbox" From 34f9ed0153bf79bf979a2c4b639e6d518dcf1dda Mon Sep 17 00:00:00 2001 From: navjot Date: Wed, 29 Jan 2020 21:44:39 +0530 Subject: [PATCH 52/54] worked on implementing toggle button funcationality on myaddress screen --- src/bitmessagekivy/kv/common_widgets.kv | 7 ++ src/bitmessagekivy/kv/myaddress.kv | 1 - src/bitmessagekivy/mpybit.py | 131 +++++++++++++----------- 3 files changed, 81 insertions(+), 58 deletions(-) diff --git a/src/bitmessagekivy/kv/common_widgets.kv b/src/bitmessagekivy/kv/common_widgets.kv index 79ed3219..dfcde98e 100644 --- a/src/bitmessagekivy/kv/common_widgets.kv +++ b/src/bitmessagekivy/kv/common_widgets.kv @@ -56,3 +56,10 @@ center_x: self.parent.center_x center_y: self.parent.center_y size: 20, 20 + + +: + #size_hint: None, None + size: dp(36), dp(48) + pos_hint: {'center_x': .95, 'center_y': .4} + on_press: app.root.ids.sc10.toggleAction(self) diff --git a/src/bitmessagekivy/kv/myaddress.kv b/src/bitmessagekivy/kv/myaddress.kv index 80db9c26..a150d59f 100644 --- a/src/bitmessagekivy/kv/myaddress.kv +++ b/src/bitmessagekivy/kv/myaddress.kv @@ -21,4 +21,3 @@ MDList: id: ml Loader: - ComposerButton: \ No newline at end of file diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 847653c3..e1c07bdb 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -55,7 +55,7 @@ from kivymd.uix.list import ( # MDNavigationDrawer, # NavigationDrawerHeaderBase # ) -from kivymd.uix.selectioncontrol import MDCheckbox +from kivymd.uix.selectioncontrol import MDCheckbox, MDSwitch import queues from semaphores import kivyuisignaler @@ -263,17 +263,11 @@ class Inbox(Screen): """Delete inbox mail from inbox listing""" sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE msgid = ?;", data_index) - try: - msg_count_objs = ( - self.parent.parent.parent.parent.children[2].children[0].ids) - except Exception: - msg_count_objs = ( - self.parent.parent.parent.parent.parent.children[ - 2].children[0].ids) + msg_count_objs = self.parent.parent.ids.content_drawer.ids if int(state.inbox_count) > 0: - msg_count_objs.inbox_cnt.badge_text = showLimitedCnt(int(state.inbox_count) - 1) - msg_count_objs.trash_cnt.badge_text = showLimitedCnt(int(state.trash_count) + 1) - msg_count_objs.allmail_cnt.badge_text = showLimitedCnt(int(state.all_count) - 1) + msg_count_objs.inbox_cnt.children[0].children[0].text = showLimitedCnt(int(state.inbox_count) - 1) + msg_count_objs.trash_cnt.children[0].children[0].text = showLimitedCnt(int(state.trash_count) + 1) + msg_count_objs.allmail_cnt.children[0].children[0].text = showLimitedCnt(int(state.all_count) - 1) state.inbox_count = str( int(state.inbox_count) - 1) state.trash_count = str( @@ -378,29 +372,37 @@ class MyAddress(Screen): text=item['text'], secondary_text=item['secondary_text'], theme_text_color='Custom' if is_enable == 'true' else 'Primary', text_color=NavigateApp().theme_cls.primary_color, - disabled=False if is_enable == 'true' else True) + ) meny.add_widget(AvatarSampleWidget( source='./images/text_images/{}.png'.format( avatarImageFirstLetter(item['text'].strip())))) meny.bind(on_press=partial( self.myadd_detail, item['secondary_text'], item['text'])) - carousel = Carousel(direction='right') - carousel.height = meny.height - carousel.size_hint_y = None - carousel.ignore_perpendicular_swipes = True - carousel.data_index = 0 - carousel.min_move = 0.2 - del_btn = Button(text='Disable' if is_enable == 'true' else 'Enable') - if is_enable == 'true': - del_btn.background_normal = '' - del_btn.background_color = (1, 0, 0, 1) if is_enable == 'true' else (0, 1, 0, 1) - del_btn.bind( - on_press=partial( - self.disableAddress if is_enable == 'true' else self.enableAddress , item['secondary_text'])) - carousel.add_widget(del_btn) - carousel.add_widget(meny) - carousel.index = 1 - self.ids.ml.add_widget(carousel) + if state.association == item['secondary_text']: + meny.add_widget(BadgeText(size_hint= (None, None), + text='Active', halign='right', + font_style='Body1', size= [50,60], + theme_text_color='Custom', + text_color=NavigateApp().theme_cls.primary_color)) + else: + meny.add_widget(ToggleBtn(active = True if is_enable == 'true' else False)) + # carousel = Carousel(direction='right') + # carousel.height = meny.height + # carousel.size_hint_y = None + # carousel.ignore_perpendicular_swipes = True + # carousel.data_index = 0 + # carousel.min_move = 0.2 + # del_btn = Button(text='Disable' if is_enable == 'true' else 'Enable') + # if is_enable == 'true': + # del_btn.background_normal = '' + # del_btn.background_color = (1, 0, 0, 1) if is_enable == 'true' else (0, 1, 0, 1) + # del_btn.bind( + # on_press=partial( + # self.disableAddress if is_enable == 'true' else self.enableAddress , item['secondary_text'])) + # carousel.add_widget(del_btn) + # carousel.add_widget(meny) + # carousel.index = 1 + self.ids.ml.add_widget(meny) def check_scroll_y(self, instance, somethingelse): """Load data on scroll down""" @@ -421,9 +423,10 @@ class MyAddress(Screen): @staticmethod def myadd_detail(fromaddress, label, *args): """Load myaddresses details""" - p = MyaddDetailPopup() - p.open() - p.set_address(fromaddress, label) + if BMConfigParser().get(fromaddress, 'enabled') == 'true': + p = MyaddDetailPopup() + p.open() + p.set_address(fromaddress, label) def refresh_callback(self, *args): """Method updates the state of application, @@ -432,8 +435,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[2].ids.search_field.text = '' - self.children[3].children[2].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() @@ -454,34 +456,39 @@ class MyAddress(Screen): return True return False - def disableAddress(self, address, instance, *args): + + def disableAddress(self, address, instance): """This method is use for disabling address""" BMConfigParser().set(str(address), 'enabled', 'false') BMConfigParser().save() - state.kivyapp.loadMyAddressScreen(True) - state.kivyapp.root.ids.sc10.ids.ml.clear_widgets() + instance.parent.parent.theme_text_color = 'Primary' + toast('Address disabled') Clock.schedule_once(self.address_permision_callback, 0) - # state.kivyapp.root.ids.sc10.init_ui() - pass - def enableAddress(self, address, instance, *args): + def enableAddress(self, address, instance): """This method is use for enabling address""" BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().save() - state.kivyapp.loadMyAddressScreen(True) - state.kivyapp.root.ids.sc10.ids.ml.clear_widgets() + instance.parent.parent.theme_text_color = 'Custom' + toast('Address Enabled') Clock.schedule_once(self.address_permision_callback, 0) - # @staticmethod def address_permision_callback(self, dt=0): - """New address created""" - state.kivyapp.loadMyAddressScreen(False) - state.kivyapp.root.ids.sc10.init_ui() + """callback for enable or disable addresses""" addresses = [addr for addr in BMConfigParser().addresses() if BMConfigParser().get(str(addr), 'enabled') == 'true'] self.parent.parent.ids.content_drawer.ids.btn.values = addresses self.parent.parent.ids.sc3.children[1].ids.btn.values = addresses + def toggleAction(self, instance): + """This method is used for enable or disable address""" + addr = instance.parent.parent.secondary_text + if instance.active: + self.disableAddress(addr, instance) + else: + self.enableAddress(addr, instance) + + class AddressBook(Screen): """AddressBook Screen uses screen to show widgets of screens""" @@ -1105,7 +1112,7 @@ class Sent(Screen): src_mng_obj = state.kivyapp.root.ids.content_drawer.ids.send_cnt if state.association: src_mng_obj.children[0].children[0].text = showLimitedCnt(int(total_sent)) - # state.sent_count = str(total_sent) + state.sent_count = str(total_sent) else: src_mng_obj.children[0].children[0].text = '0' @@ -1419,6 +1426,9 @@ class NavigateApp(MDApp): self.root.ids.sc17.clear_widgets() self.root.ids.sc17.add_widget(Allmails()) + self.root.ids.sc10.ids.ml.clear_widgets() + self.root.ids.sc10.init_ui() + self.root.ids.scr_mngr.current = 'inbox' @staticmethod @@ -1547,10 +1557,10 @@ class NavigateApp(MDApp): def loadMyAddressScreen(self, action): """loadMyAddressScreen method spin the loader""" - if len(self.root.ids.sc10.children) <= 3: - self.root.ids.sc10.children[1].active = action + if len(self.root.ids.sc10.children) <= 2: + self.root.ids.sc10.children[0].active = action else: - self.root.ids.sc10.children[2].active = action + self.root.ids.sc10.children[1].active = action def save_draft(self): """Saving drafts messages""" @@ -1750,7 +1760,7 @@ class NavigateApp(MDApp): elif state.search_screen == 'myaddress': try: self.root.ids.sc10.children[ - 3].children[2].ids.search_field.text = '' + 1].children[2].ids.search_field.text = '' except Exception: self.root.ids.sc10.children[ 2].children[2].ids.search_field.text = '' @@ -1810,12 +1820,14 @@ class NavigateApp(MDApp): 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() + # 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() + self.root.ids.sc17.clear_widgets() + self.root.ids.sc17.add_widget(Allmails()) try: self.root.ids.sc17.children[1].active = False except Exception: @@ -1960,6 +1972,11 @@ class IconRightSampleWidget(IRightBodyTouch, MDCheckbox): pass +class ToggleBtn(IRightBodyTouch, MDSwitch): + """Right toggle button widget""" + pass + + class MailDetail(Screen): """MailDetail Screen uses to show the detail of mails""" From e4676243d1871f936312db375d6f8b13e9065275 Mon Sep 17 00:00:00 2001 From: navjot Date: Wed, 5 Feb 2020 14:23:04 +0530 Subject: [PATCH 53/54] worked on message detail screen UI designing or time tag implementation --- src/bitmessagekivy/kv/maildetail.kv | 99 ++++++++++++++++++++--------- src/bitmessagekivy/main.kv | 5 +- src/bitmessagekivy/mpybit.py | 45 +++++++++---- 3 files changed, 104 insertions(+), 45 deletions(-) diff --git a/src/bitmessagekivy/kv/maildetail.kv b/src/bitmessagekivy/kv/maildetail.kv index ca6571a5..710a49c7 100644 --- a/src/bitmessagekivy/kv/maildetail.kv +++ b/src/bitmessagekivy/kv/maildetail.kv @@ -1,45 +1,84 @@ : name: 'mailDetail' + # ScrollView: + # do_scroll_x: False + # BoxLayout: + # orientation: 'vertical' + # size_hint_y: None + # height: dp(500) + self.minimum_height + # padding: dp(32) + # MDLabel: + # font_style: 'Subtitle1' + # theme_text_color: 'Primary' + # text: root.subject + # halign: 'left' + # font_size: '20sp' + # CopyTextBtn: + # MDLabel: + # font_style: 'Body1' + # theme_text_color: 'Primary' + # text: "From: " + root.from_addr + # halign: 'left' + # CopyTextBtn: + # MDLabel: + # font_style: 'Body1' + # theme_text_color: 'Primary' + # text: "To: " + root.to_addr + # halign: 'left' + # CopyTextBtn: + # MDLabel: + # font_style: 'Body1' + # theme_text_color: 'Primary' + # text: root.status + # halign: 'left' + # MDLabel: + # font_style: 'Subtitle2' + # theme_text_color: 'Primary' + # text: root.message + # halign: 'left' + # bold: True + # CopyTextBtn: + # BoxLayout: + # orientation: 'vertical' + # size_hint_y: None + # height: dp(100) + self.minimum_height ScrollView: do_scroll_x: False BoxLayout: - orientation: 'vertical' size_hint_y: None - height: dp(500) + self.minimum_height - padding: dp(32) - MDLabel: - font_style: 'Subtitle1' - theme_text_color: 'Primary' + orientation: 'vertical' + height: dp(bod.height) + self.minimum_height + padding: dp(20) + OneLineListItem: + id: subj text: root.subject - halign: 'left' - font_size: '20sp' - CopyTextBtn: - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: "From: " + root.from_addr - halign: 'left' - CopyTextBtn: - MDLabel: - font_style: 'Body1' - theme_text_color: 'Primary' - text: "To: " + root.to_addr - halign: 'left' - CopyTextBtn: - MDLabel: - font_style: 'Body1' + divider: None + disabled: True + font_style: 'H5' theme_text_color: 'Primary' + TwoLineAvatarIconListItem: + id: subaft + text: root.from_addr + secondary_text: 'to ' + root.to_addr + divider: None + BadgeText: + text: root.time_tag + halign:'right' + font_style:'Caption' + AvatarSampleWidget: + source: root.avatarImg + OneLineListItem: text: root.status - halign: 'left' + divider: None + disabled: True + font_style: 'Body2' + theme_text_color: 'Primary' + halign:'left' MDLabel: + id: bod font_style: 'Subtitle2' theme_text_color: 'Primary' text: root.message halign: 'left' - bold: True - CopyTextBtn: - BoxLayout: - orientation: 'vertical' - size_hint_y: None - height: dp(100) + self.minimum_height + height: self.texture_size[1] Loader: \ No newline at end of file diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index a6cba9c0..42a924a8 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -31,7 +31,8 @@ color: color_font - on_press: root.active = not root.active + #on_press: root.active = not root.active + on_press: root.currentlyActive() active_color: root.theme_cls.primary_color if root.active else root.theme_cls.text_color IconLeftWidget: @@ -42,7 +43,7 @@ BadgeText: text: f"{root.badge_text}" theme_text_color: "Custom" - text_color: root.active_color + #text_color: root.active_color halign: 'right' : diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index e1c07bdb..5f6a01d3 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -671,11 +671,14 @@ class DropDownWidget(BoxLayout): "UPDATE sent SET toaddress = ?" ", fromaddress = ? , subject = ?" ", message = ?, folder = 'sent'" + ", senttime = ?, lastactiontime = ?" " WHERE ackdata = ?;", toAddress, fromAddress, subject, message, + int(time.time()), + int(time.time()), state.send_draft_mail) self.parent.parent.screens[15].clear_widgets() self.parent.parent.screens[15].add_widget(Draft()) @@ -1112,7 +1115,7 @@ class Sent(Screen): src_mng_obj = state.kivyapp.root.ids.content_drawer.ids.send_cnt if state.association: src_mng_obj.children[0].children[0].text = showLimitedCnt(int(total_sent)) - state.sent_count = str(total_sent) + state.kivyapp.get_sent_count() else: src_mng_obj.children[0].children[0].text = '0' @@ -1212,11 +1215,11 @@ class Trash(Screen): self.trash_messages = sqlQuery( "SELECT toaddress, fromaddress, subject, message," " folder ||',' || 'sent' as folder, ackdata As" - " id, DATE(senttime) As actionTime FROM sent" + " id, DATE(senttime) As actionTime, senttime as msgtime FROM sent" " WHERE folder = 'trash' and fromaddress = '{0}' UNION" " SELECT toaddress, fromaddress, subject, message," " folder ||',' || 'inbox' as folder, msgid As id," - " DATE(received) As actionTime FROM inbox" + " DATE(received) As actionTime, received as msgtime FROM inbox" " WHERE folder = 'trash' and toaddress = '{0}'" " ORDER BY actionTime DESC limit {1}, {2}".format( state.association, start_indx, end_indx)) @@ -1241,6 +1244,7 @@ class Trash(Screen): item[2][0].upper() if (item[2][0].upper() >= 'A' and item[ 2][0].upper() <= 'Z') else '!') meny.add_widget(AvatarSampleWidget(source=img_latter)) + meny.add_widget(AddTimeWidget(item[7])) carousel = Carousel(direction='right') carousel.height = meny.height carousel.size_hint_y = None @@ -1406,6 +1410,9 @@ class NavigateApp(MDApp): state.searcing_text = '' LoadingPopup().open() self.set_message_count() + for nav_obj in self.root.ids.content_drawer.children[ + 0].children[0].children[0].children: + nav_obj.active = True if nav_obj.text == 'Inbox' else False Clock.schedule_once(self.setCurrentAccountData, 0.5) def setCurrentAccountData(self, dt=0): @@ -1710,7 +1717,7 @@ class NavigateApp(MDApp): f_name = first_name.split() label = f_name[0][:14].capitalize() + '...' if len( f_name[0]) > 15 else f_name[0].capitalize() - address = ' (' + addr + '...)' + address = ' (' + addr + ')' return label + address return '' @@ -1986,6 +1993,8 @@ class MailDetail(Screen): message = StringProperty() status = StringProperty() page_type = StringProperty() + time_tag = StringProperty() + avatarImg = StringProperty() def __init__(self, *args, **kwargs): """Mail Details method""" @@ -1998,14 +2007,14 @@ class MailDetail(Screen): if state.detailPageType == 'sent' or state.detailPageType == 'draft': data = sqlQuery( "select toaddress, fromaddress, subject, message, status," - " ackdata from sent where ackdata = ?;", state.mail_id) + " ackdata, senttime from sent where ackdata = ?;", state.mail_id) state.status = self state.ackdata = data[0][5] self.assign_mail_details(data) state.kivyapp.set_mail_detail_header() elif state.detailPageType == 'inbox': data = sqlQuery( - "select toaddress, fromaddress, subject, message from inbox" + "select toaddress, fromaddress, subject, message, received from inbox" " where msgid = ?;", state.mail_id) self.assign_mail_details(data) state.kivyapp.set_mail_detail_header() @@ -2017,8 +2026,11 @@ class MailDetail(Screen): self.subject = data[0][2].upper( ) if data[0][2].upper() else '(no subject)' self.message = data[0][3] - if len(data[0]) == 6: + if len(data[0]) == 7: self.status = data[0][4] + self.time_tag = ShowTimeHistoy(data[0][4]) if state.detailPageType == 'inbox' else ShowTimeHistoy(data[0][6]) + self.avatarImg = './images/text_images/{0}.png'.format( + 'avatar.png' if state.detailPageType == 'draft' else avatarImageFirstLetter(self.subject.strip())) def delete_mail(self): """Method for mail delete""" @@ -2268,8 +2280,8 @@ class Draft(Screen): 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.children[0].children[0].text = showLimitedCnt(len(self.queryreturn)) + # if state.msg_counter_objs: + # state.msg_counter_objs.draft_cnt.children[0].children[0].text = showLimitedCnt(len(self.queryreturn)) if self.queryreturn: self.ids.identi_tag.children[0].text = 'Draft' self.set_draftCnt(state.draft_count) @@ -2309,7 +2321,7 @@ class Draft(Screen): mail[2]) > 10 else mail[2] + '\n' + " " + ( third_text[:25] + '...!') if len( third_text) > 25 else third_text, - 'ackdata': mail[5]}) + 'ackdata': mail[5], 'senttime': mail[6]}) for item in data: meny = TwoLineAvatarIconListItem( text='Draft', secondary_text=item['text'], @@ -2319,6 +2331,7 @@ class Draft(Screen): source='./images/avatar.png')) meny.bind(on_press=partial( self.draft_detail, item['ackdata'])) + meny.add_widget(AddTimeWidget(item['senttime'])) carousel = Carousel(direction='right') carousel.height = meny.height carousel.size_hint_y = None @@ -2422,7 +2435,7 @@ class Draft(Screen): encoding, BMConfigParser().safeGetInt('bitmessagesettings', 'ttl')) state.msg_counter_objs = src_object.children[2].children[0].ids - state.draft_count = str(int(state.draft_count) + 1) + state.draft_count = str(int(state.draft_count) + 1) if state.association == fromAddress else state.draft_count src_object.ids.sc16.clear_widgets() src_object.ids.sc16.add_widget(Draft()) toast('Save draft') @@ -2489,10 +2502,10 @@ class Allmails(Screen): """Retrieving data from inbox or sent both tables""" self.all_mails = sqlQuery( "SELECT toaddress, fromaddress, subject, message, folder, ackdata" - " As id, DATE(senttime) As actionTime FROM sent WHERE" + " As id, DATE(senttime) As actionTime, senttime as msgtime FROM sent WHERE" " folder = 'sent' and fromaddress = '{0}'" " UNION SELECT toaddress, fromaddress, subject, message, folder," - " msgid As id, DATE(received) As actionTime FROM inbox" + " msgid As id, DATE(received) As actionTime, received as msgtime FROM inbox" " WHERE folder = 'inbox' and toaddress = '{0}'" " ORDER BY actionTime DESC limit {1}, {2}".format( self.account, start_indx, end_indx)) @@ -2519,6 +2532,7 @@ class Allmails(Screen): avatarImageFirstLetter(item[2].strip())))) meny.bind(on_press=partial( self.mail_detail, item[5], item[4])) + meny.add_widget(AddTimeWidget(item[7])) carousel = Carousel(direction='right') carousel.height = meny.height carousel.size_hint_y = None @@ -2678,6 +2692,11 @@ class NavigationItem(OneLineAvatarIconListItem): icon = StringProperty() active = BooleanProperty(False) + def currentlyActive(self): + for nav_obj in self.parent.children: + nav_obj.active = False + self.active = True + class NavigationDrawerDivider(OneLineListItem): """ From 2da3ab9a3a3aca018859a2acf7ebaf2ea4bea098 Mon Sep 17 00:00:00 2001 From: "jai.s" Date: Wed, 5 Feb 2020 19:04:54 +0530 Subject: [PATCH 54/54] Solved message not receiving issue and solved address generation pubkey related issue --- src/bitmessagekivy/mpybit.py | 38 +++++++++++++++++++++++------------- src/class_objectProcessor.py | 25 +++++++++++------------- src/class_singleWorker.py | 12 ++++++------ src/helper_msgcoding.py | 7 +++---- src/messagetypes/message.py | 12 ++++++++---- src/protocol.py | 2 +- 6 files changed, 53 insertions(+), 43 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index 5f6a01d3..c0e90757 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -153,10 +153,12 @@ class Inbox(Screen): self.set_inboxCount(state.inbox_count) for mail in self.queryreturn: # third_text = mail[3].replace('\n', ' ') + subject = mail[3].decode() if isinstance(mail[3],bytes) else mail[3] + body = mail[5].decode() if isinstance(mail[5],bytes) else mail[5] data.append({ 'text': mail[4].strip(), - 'secondary_text': mail[5][:50] + '........' if len( - mail[5]) >= 50 else (mail[5] + ',' + mail[3].replace( + 'secondary_text': body[:50] + '........' if len( + body) >= 50 else (body + ',' + subject.replace( '\n', ''))[0:50] + '........', 'msgid': mail[1], 'received': mail[6]}) self.has_refreshed = True @@ -239,10 +241,12 @@ class Inbox(Screen): self.inboxDataQuery('toaddress', where, what, total_message, 5) for mail in self.queryreturn: # third_text = mail[3].replace('\n', ' ') + subject = mail[3].decode() if isinstance(mail[3],bytes) else mail[3] + body = mail[5].decode() if isinstance(mail[5],bytes) else mail[5] data.append({ 'text': mail[4].strip(), - 'secondary_text': mail[5][:50] + '........' if len( - mail[5]) >= 50 else (mail[5] + ',' + mail[3].replace( + 'secondary_text': body[:50] + '........' if len( + body) >= 50 else (body + ',' +subject.replace( '\n', ''))[0:50] + '........', 'msgid': mail[1]}) self.set_mdList(data) @@ -1233,16 +1237,17 @@ class Trash(Screen): """This method is used to create the mdlist""" total_trash_msg = len(self.ids.ml.children) for item in self.trash_messages: + subject = item[2].decode() if isinstance(item[2],bytes) else item[2] + body = item[3].decode() if isinstance(item[3],bytes) else item[3] meny = TwoLineAvatarIconListItem( text=item[1], secondary_text=item[2][:50] + '........' if len( - item[2]) >= 50 else (item[2] + ',' + item[3].replace( + subject) >= 50 else (subject + ',' + body.replace( '\n', ''))[0:50] + '........', theme_text_color='Custom', text_color=NavigateApp().theme_cls.primary_color) img_latter = './images/text_images/{}.png'.format( - item[2][0].upper() if (item[2][0].upper() >= 'A' and item[ - 2][0].upper() <= 'Z') else '!') + subject[0].upper() if (subject[0].upper() >= 'A' and subject[0].upper() <= 'Z') else '!') meny.add_widget(AvatarSampleWidget(source=img_latter)) meny.add_widget(AddTimeWidget(item[7])) carousel = Carousel(direction='right') @@ -2021,11 +2026,14 @@ class MailDetail(Screen): def assign_mail_details(self, data): """Assigning mail details""" + subject = data[0][2].decode() if isinstance(data[0][2],bytes) else data[0][2] + body = data[0][3].decode() if isinstance(data[0][2],bytes) else data[0][3] self.to_addr = data[0][0] self.from_addr = data[0][1] - self.subject = data[0][2].upper( - ) if data[0][2].upper() else '(no subject)' - self.message = data[0][3] + + self.subject = subject.upper( + ) if subject.upper() else '(no subject)' + self.message = body if len(data[0]) == 7: self.status = data[0][4] self.time_tag = ShowTimeHistoy(data[0][4]) if state.detailPageType == 'inbox' else ShowTimeHistoy(data[0][6]) @@ -2519,17 +2527,19 @@ class Allmails(Screen): """This method is used to create mdList for allmaills""" data_exist = len(self.ids.ml.children) for item in self.all_mails: + body = item[3].decode() if isinstance(item[3],bytes) else item[3] + subject = item[2].decode() if isinstance(item[2],bytes) else item[2] meny = TwoLineAvatarIconListItem( text=item[1], - secondary_text=item[2][:50] + '........' if len( - item[2]) >= 50 else ( - item[2] + ',' + item[3].replace( + secondary_text=body[:50] + '........' if len( + body) >= 50 else ( + body + ',' + subject.replace( '\n', ''))[0:50] + '........', theme_text_color='Custom', text_color=NavigateApp().theme_cls.primary_color) meny.add_widget(AvatarSampleWidget( source='./images/text_images/{}.png'.format( - avatarImageFirstLetter(item[2].strip())))) + avatarImageFirstLetter(body.strip())))) meny.bind(on_press=partial( self.mail_detail, item[5], item[4])) meny.add_widget(AddTimeWidget(item[7])) diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py index 6a832aa7..8dfc96e8 100644 --- a/src/class_objectProcessor.py +++ b/src/class_objectProcessor.py @@ -479,16 +479,15 @@ class objectProcessor(threading.Thread): # This is not an acknowledgement bound for me. See if it is a message # bound for me by trying to decrypt it with my private keys. - for key, cryptorObject in sorted( shared.myECCryptorObjects.items(), key=lambda x: random.random()): try: # continue decryption attempts to avoid timing attacks if initialDecryptionSuccessful: - cryptorObject.decrypt(data[readPosition:]) + cryptorObject.decrypt(bytes(data[readPosition:])) else: - decryptedData = cryptorObject.decrypt(data[readPosition:]) + decryptedData = cryptorObject.decrypt(bytes(data[readPosition:])) # This is the RIPE hash of my pubkeys. We need this # below to compare to the destination_ripe included # in the encrypted data. @@ -536,9 +535,9 @@ class objectProcessor(threading.Thread): return readPosition += sendersStreamNumberLength readPosition += 4 - pubSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64] + pubSigningKey = '\x04'.encode() + decryptedData[readPosition:readPosition + 64] readPosition += 64 - pubEncryptionKey = '\x04' + decryptedData[readPosition:readPosition + 64] + pubEncryptionKey = '\x04'.encode() + decryptedData[readPosition:readPosition + 64] readPosition += 64 if sendersAddressVersionNumber >= 3: requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = \ @@ -589,7 +588,7 @@ class objectProcessor(threading.Thread): readPosition += signatureLengthLength signature = decryptedData[ readPosition:readPosition + signatureLength] - signedData = data[8:20] + encodeVarint(1) + encodeVarint( + signedData = bytes(data[8:20]) + encodeVarint(1) + encodeVarint( streamNumberAsClaimedByMsg ) + decryptedData[:positionOfBottomOfAckData] @@ -635,7 +634,6 @@ class objectProcessor(threading.Thread): # pubkey in order to send a message. If we are, it will do the POW # and send it. self.possibleNewPubkey(fromAddress) - # If this message is bound for one of my version 3 addresses (or # higher), then we must check to make sure it meets our demanded # proof of work requirement. If this is bound for one of my chan @@ -648,10 +646,10 @@ class objectProcessor(threading.Thread): # If I'm not friendly with this person: if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist( fromAddress): - requiredNonceTrialsPerByte = BMConfigParser().getint( - toAddress, 'noncetrialsperbyte') - requiredPayloadLengthExtraBytes = BMConfigParser().getint( - toAddress, 'payloadlengthextrabytes') + requiredNonceTrialsPerByte = int(BMConfigParser().get( + toAddress, 'noncetrialsperbyte')) + requiredPayloadLengthExtraBytes = int(BMConfigParser().get( + toAddress, 'payloadlengthextrabytes')) if not protocol.isProofOfWorkSufficient( data, requiredNonceTrialsPerByte, requiredPayloadLengthExtraBytes): @@ -684,7 +682,6 @@ class objectProcessor(threading.Thread): toLabel = BMConfigParser().get(toAddress, 'label') if toLabel == '': toLabel = toAddress - try: decodedMessage = helper_msgcoding.MsgDecode( messageEncodingType, message) @@ -1121,8 +1118,8 @@ class objectProcessor(threading.Thread): if checksum != hashlib.sha512(payload).digest()[0:4]: logger.info('ackdata checksum wrong. Not sending ackdata.') return False - command = command.rstrip('\x00') - if command != 'object': + command = command.rstrip('\x00'.encode()) + if command != 'object'.encode(): return False return True diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index f6494198..94830990 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -396,7 +396,7 @@ class singleWorker(StoppableThread): TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300)) embeddedTime = int(time.time() + TTL) payload = pack('>Q', (embeddedTime)) - payload += '\x00\x00\x00\x01' # object type: pubkey + payload += '\x00\x00\x00\x01'.encode() # object type: pubkey payload += encodeVarint(addressVersionNumber) # Address version number payload += encodeVarint(streamNumber) dataToEncrypt = protocol.getBitfield(myAddress) @@ -415,10 +415,10 @@ class singleWorker(StoppableThread): dataToEncrypt += pubSigningKey + pubEncryptionKey - dataToEncrypt += encodeVarint(BMConfigParser().getint( - myAddress, 'noncetrialsperbyte')) - dataToEncrypt += encodeVarint(BMConfigParser().getint( - myAddress, 'payloadlengthextrabytes')) + dataToEncrypt += encodeVarint(int(BMConfigParser().get( + myAddress, 'noncetrialsperbyte'))) + dataToEncrypt += encodeVarint(int(BMConfigParser().get( + myAddress, 'payloadlengthextrabytes'))) # When we encrypt, we'll use a hash of the data # contained in an address as a decryption key. This way @@ -449,7 +449,7 @@ class singleWorker(StoppableThread): inventoryHash = calculateInventoryHash(payload) objectType = 1 - Inventory()[inventoryHash] = ( + Inventory()._realInventory[inventoryHash] = ( objectType, streamNumber, payload, embeddedTime, doubleHashOfAddressData[32:] ) diff --git a/src/helper_msgcoding.py b/src/helper_msgcoding.py index ae2bf80b..39df566c 100644 --- a/src/helper_msgcoding.py +++ b/src/helper_msgcoding.py @@ -99,14 +99,14 @@ class MsgDecode(object): def decodeExtended(self, data): """Handle extended encoding""" dc = zlib.decompressobj() - tmp = "" + tmp = bytes() while len(tmp) <= BMConfigParser().safeGetInt("zlib", "maxsize"): try: got = dc.decompress( data, BMConfigParser().safeGetInt("zlib", "maxsize") + 1 - len(tmp)) # EOF - if got == "": + if got == bytes(): break tmp += got data = dc.unconsumed_tail @@ -128,7 +128,6 @@ class MsgDecode(object): except KeyError: logger.error("Message type missing") raise MsgDecodeException("Message type missing") - msgObj = messagetypes.constructObject(tmp) if msgObj is None: raise MsgDecodeException("Malformed message") @@ -142,7 +141,7 @@ class MsgDecode(object): def decodeSimple(self, data): """Handle simple encoding""" - bodyPositionIndex = string.find(data, '\nBody:') + bodyPositionIndex = bytes.find(data, '\nBody:'.encode()) if bodyPositionIndex > 1: subject = data[8:bodyPositionIndex] # Only save and show the first 500 characters of the subject. diff --git a/src/messagetypes/message.py b/src/messagetypes/message.py index 27bba13a..2480df70 100644 --- a/src/messagetypes/message.py +++ b/src/messagetypes/message.py @@ -14,13 +14,17 @@ class Message(MsgBase): """Decode a message""" # UTF-8 and variable type validator if isinstance(data["subject"], str): - self.subject = unicode(data["subject"], 'utf-8', 'replace') + # Unicode is depreciated + self.subject =data["subject"] else: - self.subject = unicode(str(data["subject"]), 'utf-8', 'replace') + # Unicode is depreciated + self.subject = str(data["subject"]) if isinstance(data["body"], str): - self.body = unicode(data["body"], 'utf-8', 'replace') + # Unicode is depreciated + self.body = data["body"] else: - self.body = unicode(str(data["body"]), 'utf-8', 'replace') + # Unicode is depreciated + self.body = str(data["body"]) def encode(self, data): """Encode a message""" diff --git a/src/protocol.py b/src/protocol.py index 029205a9..b0b12208 100644 --- a/src/protocol.py +++ b/src/protocol.py @@ -276,7 +276,7 @@ def isProofOfWorkSufficient( if TTL < 300: TTL = 300 POW, = unpack('>Q', hashlib.sha512(hashlib.sha512( - data[:8] + hashlib.sha512(data[8:]).digest() + bytes(data[:8]) + hashlib.sha512(data[8:]).digest() ).digest()).digest()[0:8]) return POW <= 2 ** 64 / ( nonceTrialsPerByte * (