From ace05e151ceb20e9a4b95563782e70096af029f5 Mon Sep 17 00:00:00 2001 From: Navjot Date: Tue, 24 Sep 2019 20:51:34 +0530 Subject: [PATCH 1/3] worked on android application popup responsive functionality --- src/bitmessagekivy/main.kv | 23 +++++--- src/bitmessagekivy/mpybit.py | 51 +++--------------- .../BM-2cXQpSjUCAf8fvAQCvsrLDVkLnDAkSjRGN.png | Bin 461 -> 0 bytes .../BM-2cXewfSjCgGMPB5qYwUSCD2Q57bGLWgD3C.png | Bin 475 -> 0 bytes 4 files changed, 23 insertions(+), 51 deletions(-) delete mode 100644 src/images/default_identicon/BM-2cXQpSjUCAf8fvAQCvsrLDVkLnDAkSjRGN.png delete mode 100644 src/images/default_identicon/BM-2cXewfSjCgGMPB5qYwUSCD2Q57bGLWgD3C.png diff --git a/src/bitmessagekivy/main.kv b/src/bitmessagekivy/main.kv index 1fdb29f0..920ca2ef 100644 --- a/src/bitmessagekivy/main.kv +++ b/src/bitmessagekivy/main.kv @@ -72,9 +72,9 @@ on_text:app.getCurrentAccountData(self.text) Image: source: app.get_default_image() - x: self.width/4-2 - y: self.parent.y + self.parent.height/2 - self.height + 14 - size: 28, 28 + x: self.width/6 + y: self.parent.y + self.parent.height/4 + size: self.parent.height/2, self.parent.height/2 ArrowImg: NavigationDrawerIconButton: id: inbox_cnt @@ -821,11 +821,13 @@ 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' background: './images/popup.jpeg' title_size: sp(20) title_color: 0.4, 0.3765, 0.3451, 1 - size_hint: 1, 1 auto_dismiss: False separator_color: 0.3529, 0.3922, 0.102, 0.7 BoxLayout: @@ -1050,19 +1052,23 @@ 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' - separator_height: 0 auto_dismiss: False + separator_height: 0 BoxLayout: + id: myadd_popup_box size_hint_y: None spacing:dp(70) - id: myadd_popup_box orientation: 'vertical' BoxLayout: size_hint_y: None orientation: 'vertical' spacing:dp(25) MDLabel: + id: myaddr_label font_style: 'Title' theme_text_color: 'Primary' text: "Label" @@ -1087,6 +1093,7 @@ NavigationLayout: font_size: '15sp' halign: 'left' BoxLayout: + id: my_add_btn spacing:5 orientation: 'horizontal' MDRaisedButton: @@ -1125,6 +1132,9 @@ 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' separator_height: 0 auto_dismiss: False @@ -1165,6 +1175,7 @@ NavigationLayout: font_size: '15sp' halign: 'left' BoxLayout: + id: addbook_btn spacing:5 orientation: 'horizontal' MDRaisedButton: diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index ae69a133..0eb2c1e3 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -1036,14 +1036,6 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods state.association = text self.root.ids.sc1.clear_widgets() self.root.ids.sc1.add_widget(Inbox()) - # self.root.ids.sc4.clear_widgets() - # self.root.ids.sc5.clear_widgets() - # self.root.ids.sc16.clear_widgets() - # self.root.ids.sc17.clear_widgets() - # self.root.ids.sc4.add_widget(Sent()) - # self.root.ids.sc5.add_widget(Trash()) - # self.root.ids.sc16.add_widget(Draft()) - # self.root.ids.sc17.add_widget(Allmails()) self.root.ids.scr_mngr.current = 'inbox' msg_counter_objs = \ @@ -1091,7 +1083,12 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods if BMConfigParser().addresses(): img = identiconGeneration.generate(BMConfigParser().addresses()[0]) self.createFolder('./images/default_identicon/') - img.texture.save('./images/default_identicon/{}.png'.format(BMConfigParser().addresses()[0])) + 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/') + 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])) return BMConfigParser().addresses()[0] return 'Select Address' @@ -1125,8 +1122,6 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods self.root.ids.scr_mngr.current = 'sent'\ if state.detailPageType == 'sent' else 'inbox' \ if state.detailPageType == 'inbox' else 'draft' - # if state.detailPageType in ['sent', 'inbox']: - # self.add_search_bar() self.back_press() elif self.root.ids.scr_mngr.current == "create": composer_objs = self.root @@ -1309,13 +1304,6 @@ class GrashofPopup(Popup): def __init__(self, **kwargs): """Grash of pop screen settings.""" super(GrashofPopup, self).__init__(**kwargs) - print("sssssssssssssssssssiiiiiiiiiiiiiiizzzzzzzzzzeeeeee...............", state.screen_density) - if state.screen_density[0] <= 720: - self.size_hint_y = 0.4 - self.size_hint_x = 0.9 - else: - self.size_hint_y = 0.42 - self.size_hint_x = 0.7 def savecontact(self): """Method is used for Saving Contacts.""" @@ -1497,9 +1485,6 @@ class MailDetail(Screen): sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE \ received = {};".format(state.sentMailTime)) - # 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].clear_widgets() self.parent.screens[0].add_widget(Inbox()) elif state.detailPageType == 'draft': @@ -1574,12 +1559,6 @@ class MyaddDetailPopup(Popup): def __init__(self, **kwargs): """My Address Details screen setting.""" super(MyaddDetailPopup, self).__init__(**kwargs) - if state.screen_density[0] <= 720: - self.size_hint_y = 0.32 - self.size_hint_x = 0.9 - else: - self.size_hint_y = 0.32 - self.size_hint_x = 0.7 def set_address(self, address, label): """Getting address for displaying details on popup.""" @@ -1612,12 +1591,6 @@ class AddbookDetailPopup(Popup): def __init__(self, **kwargs): """Method used set screen of address detail page.""" super(AddbookDetailPopup, self).__init__(**kwargs) - if state.screen_density[0] <= 720: - self.size_hint_y = 0.35 - self.size_hint_x = 0.95 - else: - self.size_hint_y = 0.35 - self.size_hint_x = 0.7 def set_addbook_data(self, address, label): """Getting address book data for detial dipaly.""" @@ -1694,10 +1667,6 @@ class Draft(Screen): xAddress, account, "draft", where, what, False) if state.msg_counter_objs: state.msg_counter_objs.draft_cnt.badge_text = str(len(queryreturn)) - # state.all_count = str(int(state.all_count) + 1) - # state.msg_counter_objs.allmail_cnt.badge_text = state.all_count - # state.msg_counter_objs = None - if queryreturn: src_mng_obj = state.kivyapp.root.children[2].children[0].ids src_mng_obj.draft_cnt.badge_text = str(len(queryreturn)) @@ -1772,13 +1741,7 @@ class Draft(Screen): if int(state.draft_count) > 0: msg_count_objs.draft_cnt.badge_text = str( int(state.draft_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) state.draft_count = str(int(state.draft_count) - 1) - # state.all_count = str(int(state.all_count) - 1) - # state.trash_count = str(int(state.trash_count) + 1) self.ids.ml.remove_widget(instance.parent.parent) toast('Deleted') @@ -1840,8 +1803,6 @@ class CustomSpinner(Spinner): def __init__(self, *args, **kwargs): """Method used for setting size of spinner.""" super(CustomSpinner, self).__init__(*args, **kwargs) - # max_value = 2.8 - # self.dropdown_cls.max_height = self.height / 2 * max_value + max_value * 4 self.dropdown_cls.max_height = Window.size[1] / 3 diff --git a/src/images/default_identicon/BM-2cXQpSjUCAf8fvAQCvsrLDVkLnDAkSjRGN.png b/src/images/default_identicon/BM-2cXQpSjUCAf8fvAQCvsrLDVkLnDAkSjRGN.png deleted file mode 100644 index 22def0cd17aa71234a0ab0ad8237d8795055e7e1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 461 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrV4ULV;uumf=k1-1yiATf3Z%_+g}Yo_3`3Vh(#~4LV0gIt_b?d2K{=@9ASpvIdCKIWUk%% zP43a<{r?Wk{I$^JBpV@*Ky^y*7BuFk|yI+#2Mtc{jm*(GOW^ fqJoW6;T`WBd$}JI#g{z=MiYaltDnm{r-UW|*9?{7 diff --git a/src/images/default_identicon/BM-2cXewfSjCgGMPB5qYwUSCD2Q57bGLWgD3C.png b/src/images/default_identicon/BM-2cXewfSjCgGMPB5qYwUSCD2Q57bGLWgD3C.png deleted file mode 100644 index c886f8fc069f541c653bb2c07092ae61037b5a95..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 475 zcmeAS@N?(olHy`uVBq!ia0vp^4Is?H1|$#LC7xzrU|i(s;uuoF`1aODUseYmR>xTj za)r3sg!BqOyq!B$uYQvHp7r)ifBy=$VtB+Tz~4~8aD-Vwj^QIi2fKp}r9#UY|J42O z*>jqa;lN#n3U&sDa^?rJ3=DU88_F3N3d|Yq;gfj&HM4y;4`)MbwHkB6!+9qeB6g%3 zF^IjJ$wQIQXVsjS50^19H0);lz{kMwj_rUo1H%q!hW88%5AqoHFyoeBm`c5nK?>zP Z^(S8Q{r0V21PmDl22WQ%mvv4FO#s!zm}&q3 From 8f09140513a6fb86ee12165e36bf1353dce3ac21 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Fri, 20 Sep 2019 16:49:04 +0530 Subject: [PATCH 2/3] Code fixes 3 regarding PR#11 --- .../recipes/kivymd/__init__.py | 19 ++++--- src/bitmessagekivy/identiconGeneration.py | 4 +- src/bitmessagekivy/kivy_helper_search.py | 16 ++++-- src/bitmessagekivy/mpybit.py | 12 +++-- src/class_singleCleaner.py | 18 ++++--- src/class_singleWorker.py | 9 ++-- src/messagetypes/__init__.py | 13 ++++- src/messagetypes/message.py | 13 ++++- src/messagetypes/vote.py | 13 ++++- src/paths.py | 47 ++++++++++++----- src/pyelliptic/openssl.py | 4 +- src/state.py | 28 +++++----- src/tr.py | 51 +++++++++++++------ 13 files changed, 171 insertions(+), 76 deletions(-) diff --git a/src/bitmessagekivy/android/python-for-android/recipes/kivymd/__init__.py b/src/bitmessagekivy/android/python-for-android/recipes/kivymd/__init__.py index d7e91a90..5a29bba7 100644 --- a/src/bitmessagekivy/android/python-for-android/recipes/kivymd/__init__.py +++ b/src/bitmessagekivy/android/python-for-android/recipes/kivymd/__init__.py @@ -1,24 +1,28 @@ -from os import environ -from os.path import exists, join +""" +src/bitmessagekivy/android/python-for-android/recipes/kivymd/__init__.py +================================= +""" +# pylint: disable=import-error +from os.path import join -import sh -from pythonforandroid.logger import shprint, info_main, info from pythonforandroid.recipe import PythonRecipe # from pythonforandroid.util import ensure_dir class KivyMDRecipe(PythonRecipe): - # This recipe installs KivyMD into the android dist from source + """This recipe installs KivyMD into the android dist from source""" version = 'master' url = 'https://github.com/surbhicis/kivymd/archive/master.zip' depends = ['kivy'] site_packages_name = 'kivymd' call_hostpython_via_targetpython = False - def should_build(self, arch): + def should_build(self, arch): # pylint: disable=no-self-use, unused-argument + """Method helps to build the application""" return True def get_recipe_env(self, arch): + """Method is used for getting all the env paths""" env = super(KivyMDRecipe, self).get_recipe_env(arch) env['PYTHON_ROOT'] = self.ctx.get_python_install_dir() env['CFLAGS'] += ' -I' + env['PYTHON_ROOT'] + '/include/python2.7' @@ -30,8 +34,7 @@ class KivyMDRecipe(PythonRecipe): join(self.ctx.bootstrap.build_dir, 'jni', 'SDL', 'include'), join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_image'), join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_mixer'), - join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_ttf'), - ]) + join(self.ctx.bootstrap.build_dir, 'jni', 'SDL2_ttf'), ]) return env diff --git a/src/bitmessagekivy/identiconGeneration.py b/src/bitmessagekivy/identiconGeneration.py index 43e0dbc5..a5dcf3d0 100644 --- a/src/bitmessagekivy/identiconGeneration.py +++ b/src/bitmessagekivy/identiconGeneration.py @@ -2,11 +2,13 @@ src/identiconGeneration.py ================================= """ +# pylint: disable=import-error import hashlib +from io import BytesIO + from PIL import Image from kivy.core.image import Image as CoreImage from kivy.uix.image import Image as kiImage -from io import BytesIO """ Core classes for loading images and converting them to a Texture. The raw image data can be keep in memory for further access """ diff --git a/src/bitmessagekivy/kivy_helper_search.py b/src/bitmessagekivy/kivy_helper_search.py index e2e962c0..a1fe4a99 100644 --- a/src/bitmessagekivy/kivy_helper_search.py +++ b/src/bitmessagekivy/kivy_helper_search.py @@ -1,7 +1,13 @@ -from helper_sql import * +""" +src/bitmessagekivy/kivy_helper_search.py +================================= +""" +from helper_sql import sqlQuery def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, what=None, unreadOnly=False): + """Method helping for searching mails""" + # pylint: disable=too-many-arguments, too-many-branches if what is not None and what != "": what = "%" + what + "%" else: @@ -9,7 +15,7 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w if folder == "sent" or folder == "draft": sqlStatementBase = ''' - SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime + SELECT toaddress, fromaddress, subject, message, status, ackdata, lastactiontime FROM sent ''' elif folder == "addressbook": sqlStatementBase = '''SELECT label, address From addressbook ''' @@ -27,7 +33,7 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w else: sqlStatementParts.append(xAddress + " = ? ") sqlArguments.append(account) - if folder is not "addressbook": + if folder != "addressbook": if folder is not None: if folder == "new": folder = "inbox" @@ -50,10 +56,10 @@ def search_sql(xAddress="toaddress", account=None, folder="inbox", where=None, w sqlStatementParts.append(filter_col) if unreadOnly: sqlStatementParts.append("read = 0") - if len(sqlStatementParts) > 0: + if sqlStatementParts: sqlStatementBase += "WHERE " + " AND ".join(sqlStatementParts) if folder == "sent": sqlStatementBase += " ORDER BY lastactiontime DESC" elif folder == "inbox": sqlStatementBase += " ORDER BY received DESC" - 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 0eb2c1e3..cb4c4fda 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -2,6 +2,7 @@ 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 @@ -55,11 +56,8 @@ import queues from semaphores import kivyuisignaler import state from uikivysignaler import UIkivySignaler -# pylint: disable=unused-argument, too-few-public-methods, import-error -import identiconGeneration -import os -from kivy.core.clipboard import Clipboard +import identiconGeneration # pylint: disable=unused-argument, too-few-public-methods @@ -1485,6 +1483,9 @@ class MailDetail(Screen): sqlExecute( "UPDATE inbox SET folder = 'trash' WHERE \ received = {};".format(state.sentMailTime)) + # 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].clear_widgets() self.parent.screens[0].add_widget(Inbox()) elif state.detailPageType == 'draft': @@ -1987,7 +1988,8 @@ class Archieve(Screen): pass + class Spam(Screen): """Spam Screen show widgets of page.""" - pass \ No newline at end of file + pass diff --git a/src/class_singleCleaner.py b/src/class_singleCleaner.py index eb67fcef..9a2916c7 100644 --- a/src/class_singleCleaner.py +++ b/src/class_singleCleaner.py @@ -17,11 +17,11 @@ resends getpubkey messages in 5 days (then 10 days, then 20 days, etc...) resends msg messages in 5 days (then 10 days, then 20 days, etc...) """ - +# pylint: disable=relative-import, protected-access import gc import os -import shared import time +import shared import tr from bmconfigparser import BMConfigParser @@ -36,11 +36,12 @@ import state class singleCleaner(StoppableThread): + """Base method that Cleanup knownnodes and handle possible severe exception""" name = "singleCleaner" cycleLength = 300 expireDiscoveredPeers = 300 - def run(self): + def run(self): # pylint: disable=too-many-branches gc.disable() timeWeLastClearedInventoryAndPubkeysTables = 0 try: @@ -73,7 +74,7 @@ class singleCleaner(StoppableThread): # If we are running as a daemon then we are going to fill up the UI # queue which will never be handled by a UI. We should clear it to # save memory. - # FIXME redundant? + # ..FIXME redundant? if shared.thisapp.daemon or not state.enableGUI: queues.UISignalQueue.queue.clear() if timeWeLastClearedInventoryAndPubkeysTables < \ @@ -128,9 +129,10 @@ class singleCleaner(StoppableThread): "MainWindow", 'Alert: Your disk or data storage volume' ' is full. Bitmessage will now exit.'), - True) + True) )) - # FIXME redundant? + # ..FIXME redundant? + # pylint: disable=no-member if shared.daemon or not state.enableGUI: os._exit(1) @@ -153,7 +155,7 @@ class singleCleaner(StoppableThread): del state.discoveredPeers[k] except KeyError: pass - # TODO: cleanup pending upload / download + # ..TODO: cleanup pending upload / download gc.collect() @@ -162,6 +164,7 @@ class singleCleaner(StoppableThread): def resendPubkeyRequest(address): + """After a long time, method send getpubkey request""" logger.debug( 'It has been a long time and we haven\'t heard a response to our' ' getpubkey request. Sending again.' @@ -186,6 +189,7 @@ def resendPubkeyRequest(address): def resendMsg(ackdata): + """After a long time, method send acknowledgement msg""" logger.debug( 'It has been a long time and we haven\'t heard an acknowledgement' ' to our msg. Sending again.' diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index ca8c0b95..74343459 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -2,8 +2,8 @@ src/class_singleWorker.py ========================= """ -# pylint: disable=protected-access,too-many-branches,too-many-statements,no-self-use,too-many-lines,too-many-locals - +# pylint: disable=protected-access,too-many-branches,too-many-statements +# pylint: disable=no-self-use,too-many-lines,too-many-locals,relative-import from __future__ import division import hashlib @@ -34,6 +34,7 @@ from inventory import Inventory # This thread, of which there is only one, does the heavy lifting: # calculating POWs. + def sizeof_fmt(num, suffix='h/s'): """Format hashes per seconds nicely (SI prefix)""" @@ -469,7 +470,7 @@ class singleWorker(StoppableThread): def sendOnionPeerObj(self, peer=None): """Send onionpeer object representing peer""" if not peer: # find own onionhostname - for peer in state.ownAddresses: + for peer in state.ownAddresses: # pylint: disable=redefined-argument-from-local if peer.host.endswith('.onion'): break else: @@ -478,7 +479,7 @@ class singleWorker(StoppableThread): embeddedTime = int(time.time() + TTL) streamNumber = 1 # Don't know yet what should be here objectType = protocol.OBJECT_ONIONPEER - # FIXME: ideally the objectPayload should be signed + # ..FIXME: ideally the objectPayload should be signed objectPayload = encodeVarint(peer.port) + protocol.encodeHost(peer.host) tag = calculateInventoryHash(objectPayload) diff --git a/src/messagetypes/__init__.py b/src/messagetypes/__init__.py index ad1aee9c..95eee595 100644 --- a/src/messagetypes/__init__.py +++ b/src/messagetypes/__init__.py @@ -1,3 +1,8 @@ +""" +src/messagetypes/__init__.py +============================ +""" +# pylint: disable=import-error from importlib import import_module from os import path, listdir from string import lower @@ -9,12 +14,15 @@ from debug import logger import messagetypes import paths -class MsgBase(object): - def encode(self): + +class MsgBase(object): # pylint: disable=too-few-public-methods + """Base class for message types""" + def __init__(self): self.data = {"": lower(type(self).__name__)} def constructObject(data): + """Construct an object""" whitelist = ["message"] if data[""] not in whitelist: return None @@ -35,6 +43,7 @@ def constructObject(data): else: return returnObj + if paths.frozen is not None or platform == "android": import messagetypes.message import messagetypes.vote diff --git a/src/messagetypes/message.py b/src/messagetypes/message.py index f52c6b35..263a2e4a 100644 --- a/src/messagetypes/message.py +++ b/src/messagetypes/message.py @@ -1,13 +1,21 @@ +""" +src/messagetypes/message.py +================================= +""" from debug import logger from messagetypes import MsgBase +# pylint: disable=attribute-defined-outside-init class Message(MsgBase): - def __init__(self): + """Base method, helps to decode, encode and process the message""" + def __init__(self): # pylint: disable=super-init-not-called return def decode(self, data): + """Method used for decoding the message""" # UTF-8 and variable type validator + # pylint: disable=unidiomatic-typecheck if type(data["subject"]) is str: self.subject = unicode(data["subject"], 'utf-8', 'replace') else: @@ -18,6 +26,8 @@ class Message(MsgBase): self.body = unicode(str(data["body"]), 'utf-8', 'replace') def encode(self, data): + """Method used for encoding the message""" + # pylint: disable=no-member super(Message, self).encode() try: self.data["subject"] = data["subject"] @@ -27,5 +37,6 @@ class Message(MsgBase): return self.data def process(self): + """Method used for process the message""" logger.debug("Subject: %i bytes", len(self.subject)) logger.debug("Body: %i bytes", len(self.body)) diff --git a/src/messagetypes/vote.py b/src/messagetypes/vote.py index df8d267f..a77e1cc7 100644 --- a/src/messagetypes/vote.py +++ b/src/messagetypes/vote.py @@ -1,15 +1,25 @@ +""" +src/messagetypes/vote.py +================================= +""" from debug import logger from messagetypes import MsgBase +# pylint: disable=attribute-defined-outside-init + class Vote(MsgBase): - def __init__(self): + """Base method, helps to decode, encode and process the message""" + def __init__(self): # pylint: disable=super-init-not-called return def decode(self, data): + """Method used for decoding the message""" self.msgid = data["msgid"] self.vote = data["vote"] def encode(self, data): + """Method used for encoding the message""" + # pylint: disable=no-member super(Vote, self).encode() try: self.data["msgid"] = data["msgid"] @@ -19,5 +29,6 @@ class Vote(MsgBase): return self.data def process(self): + """Method used for process the message""" logger.debug("msgid: %s", self.msgid) logger.debug("vote: %s", self.vote) diff --git a/src/paths.py b/src/paths.py index c4c62950..78ae2804 100644 --- a/src/paths.py +++ b/src/paths.py @@ -1,3 +1,8 @@ +""" +src/paths.py +============ +""" +# pylint: disable=import-error from os import environ, path import sys import re @@ -7,9 +12,14 @@ from kivy.utils import platform # When using py2exe or py2app, the variable frozen is added to the sys # namespace. This can be used to setup a different code path for # binary distributions vs source distributions. -frozen = getattr(sys,'frozen', None) +frozen = getattr(sys, 'frozen', None) + def lookupExeFolder(): + """ + Folder with PyBitmessage binary (.exe, .app, ...). If it is run from source, it returns the source root + directory + """ if frozen: if frozen == "macosx_app": # targetdir/Bitmessage.app/Contents/MacOS/Bitmessage @@ -22,10 +32,12 @@ def lookupExeFolder(): exeFolder = '' return exeFolder -def lookupAppdataFolder(): +def lookupAppdataFolder(): # pylint: disable=too-many-branches + """Folder with runtime data (like configuration, database, ...)""" + # flake8: noqa=F821 import traceback - print(traceback.print_tb) + print traceback.print_tb APPNAME = "PyBitmessage" if "BITMESSAGE_HOME" in environ: dataFolder = environ["BITMESSAGE_HOME"] @@ -35,9 +47,11 @@ def lookupAppdataFolder(): if "HOME" in environ: dataFolder = path.join(environ["HOME"], "Library/Application Support/", APPNAME) + '/' else: - stringToLog = 'Could not find home folder, please report this message and your OS X version to the BitMessage Github.' + stringToLog = ( + 'Could not find home folder, please report this message' + ' and your OS X version to the BitMessage Github.') if 'logger' in globals(): - logger.critical(stringToLog) + logger.critical(stringToLog) # pylint: disable=undefined-variable else: print stringToLog sys.exit() @@ -58,7 +72,7 @@ def lookupAppdataFolder(): move(path.join(environ["HOME"], ".%s" % APPNAME), dataFolder) stringToLog = "Moving data folder to %s" % (dataFolder) if 'logger' in globals(): - logger.info(stringToLog) + logger.info(stringToLog) # pylint: disable=undefined-variable else: print stringToLog except IOError: @@ -67,16 +81,21 @@ def lookupAppdataFolder(): dataFolder = dataFolder + '/' return dataFolder + def codePath(): + """Return the code path of the running instance""" + # pylint: disable=redefined-outer-name if frozen == "macosx_app": codePath = environ.get("RESOURCEPATH") - elif frozen: # windows - codePath = sys._MEIPASS + elif frozen: # windows + codePath = sys._MEIPASS # pylint: disable=no-member,protected-access else: codePath = path.dirname(__file__) return codePath + def tail(f, lines=20): + """Read last lines of a file. Like tail(1)""" total_lines_wanted = lines BLOCK_SIZE = 1024 @@ -84,12 +103,13 @@ def tail(f, lines=20): block_end_byte = f.tell() lines_to_go = total_lines_wanted block_number = -1 - blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting - # from the end of the file + blocks = [] + # blocks of size BLOCK_SIZE, in reverse order starting + # from the end of the file while lines_to_go > 0 and block_end_byte > 0: - if (block_end_byte - BLOCK_SIZE > 0): + if block_end_byte - BLOCK_SIZE > 0: # read the last block we haven't yet read - f.seek(block_number*BLOCK_SIZE, 2) + f.seek(block_number * BLOCK_SIZE, 2) blocks.append(f.read(BLOCK_SIZE)) else: # file too small, start from begining @@ -105,6 +125,7 @@ def tail(f, lines=20): def lastCommit(): + """Git commitish of the currently checked out repository""" githeadfile = path.join(codePath(), '..', '.git', 'logs', 'HEAD') result = {} if path.isfile(githeadfile): @@ -117,4 +138,4 @@ def lastCommit(): ) except (IOError, AttributeError, TypeError): pass - return result \ No newline at end of file + return result diff --git a/src/pyelliptic/openssl.py b/src/pyelliptic/openssl.py index 0fc445e6..2d5ea04a 100644 --- a/src/pyelliptic/openssl.py +++ b/src/pyelliptic/openssl.py @@ -2,6 +2,7 @@ src/pyelliptic/openssl.py ================================= """ +# pylint: disable=import-error import sys import ctypes from kivy.utils import platform @@ -646,7 +647,8 @@ class _OpenSSL: # pylint: disable=too-many-instance-attributes, old-style-cl def loadOpenSSL(): """Method find and load the OpenSSL library""" - # pylint: disable=global-statement, protected-access, too-many-branches + # pylint: disable=global-statement, protected-access, too-many-branches, no-member + global OpenSSL from os import path, environ from ctypes.util import find_library diff --git a/src/state.py b/src/state.py index 63fa82e4..07cb687a 100644 --- a/src/state.py +++ b/src/state.py @@ -1,20 +1,21 @@ +""" +src/state.py +================================= +""" import collections neededPubkeys = {} streamsInWhichIAmParticipating = [] - # For UPnP extPort = None - # for Tor hidden service socksIP = None - +# 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 - # 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 @@ -23,18 +24,13 @@ 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 sqlTread when ready for processing - maximumNumberOfHalfOpenConnections = 0 - invThread = None addrThread = None downloadThread = None uploadThread = None - ownAddresses = {} - # If the trustedpeer option is specified in keys.dat then this will # contain a Peer which will be connected to instead of using the # addresses advertised by other peers. The client will only connect to @@ -46,11 +42,19 @@ ownAddresses = {} # it will sync with the network a lot faster without compromising # security. trustedPeer = None - discoveredPeers = {} - Peer = collections.namedtuple('Peer', ['host', 'port']) + +def resetNetworkProtocolAvailability(): + """This method helps to reset the availability of network protocol""" + # pylint: disable=global-statement + global networkProtocolAvailability + networkProtocolAvailability = {'IPv4': None, 'IPv6': None, 'onion': None} + + +resetNetworkProtocolAvailability() + dandelion = 0 testmode = False diff --git a/src/tr.py b/src/tr.py index af42145e..5ce623cd 100644 --- a/src/tr.py +++ b/src/tr.py @@ -1,25 +1,43 @@ +""" +src/tr.py +================================= +""" +# pylint: disable=relative-import import os import state -# This is used so that the translateText function can be used when we are in daemon mode and not using any QT functions. -class translateClass: +"""This is used so that the translateText function can be used """ +"""when we are in daemon mode and not using any QT functions.""" + + +class translateClass: # pylint: disable=old-style-class, too-few-public-methods + """ + This is used so that the translateText function can be used when we are + in daemon mode and not using any QT functions. + """ def __init__(self, context, text): self.context = context self.text = text - def arg(self,argument): - if '%' in self.text: - return translateClass(self.context, self.text.replace('%','',1)) # This doesn't actually do anything with the arguments because we don't have a UI in which to display this information anyway. - else: - return self.text -def _translate(context, text, disambiguation = None, encoding = None, n = None): + def arg(self, argument): # pylint: disable=unused-argument + """Replace argument placeholders""" + if '%' in self.text: + return translateClass(self.context, self.text.replace('%', '', 1)) + # This doesn't actually do anything with the arguments + # because we don't have a UI in which to display this information anyway. + return self.text + + +def _translate(context, text, disambiguation=None, encoding=None, n=None): # pylint: disable=unused-argument return translateText(context, text, n) # def _translate(context, text, disambiguation = None, encoding = None, n = None): # return translateClass(context, text.replace('%','',1)) -def translateText(context, text, n = None): + +def translateText(context, text, n=None): + """Translate text in context""" try: enableGUI = state.enableGUI except AttributeError: # inside the plugin @@ -28,15 +46,16 @@ 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. 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 '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) + os._exit(0) # pylint: disable=protected-access if n is None: return QtGui.QApplication.translate(context, text) - else: - return QtGui.QApplication.translate(context, text, None, QtCore.QCoreApplication.CodecForTr, n) + return QtGui.QApplication.translate(context, text, None, QtCore.QCoreApplication.CodecForTr, n) else: if '%' in text: - return translateClass(context, text.replace('%','',1)) - else: - return text + return translateClass(context, text.replace('%', '', 1)) + return text From 5a6611219cc2343f9fc8c9e55a2e8c059659cdb1 Mon Sep 17 00:00:00 2001 From: lakshyacis Date: Wed, 25 Sep 2019 17:15:45 +0530 Subject: [PATCH 3/3] mpybit fixes --- src/bitmessagekivy/mpybit.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/bitmessagekivy/mpybit.py b/src/bitmessagekivy/mpybit.py index cb4c4fda..1b4db996 100644 --- a/src/bitmessagekivy/mpybit.py +++ b/src/bitmessagekivy/mpybit.py @@ -43,7 +43,6 @@ from kivymd.list import ( ILeftBody, ILeftBodyTouch, IRightBodyTouch, - ThreeLineAvatarIconListItem, TwoLineAvatarIconListItem, TwoLineListItem) from kivymd.navigationdrawer import ( @@ -1084,7 +1083,8 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods 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/') - img.texture.save('{1}/images/default_identicon/{0}.png'.format(BMConfigParser().addresses()[0], android_path)) + 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])) return BMConfigParser().addresses()[0] @@ -1299,7 +1299,7 @@ class NavigateApp(App): # pylint: disable=too-many-public-methods class GrashofPopup(Popup): """Methods for saving contacts, error messages.""" - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """Grash of pop screen settings.""" super(GrashofPopup, self).__init__(**kwargs) @@ -1557,7 +1557,7 @@ class MyaddDetailPopup(Popup): address_label = StringProperty() address = StringProperty() - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """My Address Details screen setting.""" super(MyaddDetailPopup, self).__init__(**kwargs) @@ -1589,7 +1589,7 @@ class AddbookDetailPopup(Popup): address_label = StringProperty() address = StringProperty() - def __init__(self, **kwargs): + def __init__(self, **kwargs): # pylint: disable=useless-super-delegation """Method used set screen of address detail page.""" super(AddbookDetailPopup, self).__init__(**kwargs)