Merge pull request #25 from jaicis/py3porting

Py3porting
This commit is contained in:
surbhi 2020-03-18 20:10:17 +05:30 committed by GitHub
commit 6da6912e25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 329 additions and 281 deletions

View File

@ -6,11 +6,10 @@ idna==2.8
isort==4.3.21 isort==4.3.21
Kivy==1.11.1 Kivy==1.11.1
Kivy-Garden==0.1.4 Kivy-Garden==0.1.4
git+https://github.com/HeaTTheatR/KivyMD.git -e git+https://github.com/surbhicis/KivyMD-1#egg=kivymd
lazy-object-proxy==1.4.3 lazy-object-proxy==1.4.3
mccabe==0.6.1 mccabe==0.6.1
Pillow==6.1.0 Pillow==6.1.0
pkg-resources==0.0.0
pydenticon==0.3.1 pydenticon==0.3.1
Pygments==2.4.2 Pygments==2.4.2
pylint==2.4.4 pylint==2.4.4

View File

@ -3,16 +3,9 @@ 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/API ) and optionally enable daemon mode
( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py.
""" """
<<<<<<< HEAD
# Copyright (c) 2012-2016 Jonathan Warren # Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2020 The Bitmessage developers # Copyright (c) 2012-2020 The Bitmessage developers
# pylint: disable=too-many-lines,no-self-use,unused-variable,unused-argument # pylint: disable=too-many-lines,no-self-use,unused-variable,unused-argument
=======
# 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
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
import base64 import base64
import errno import errno
import hashlib import hashlib
@ -34,7 +27,6 @@ import queues
import shared import shared
import shutdown import shutdown
import state import state
<<<<<<< HEAD
from addresses import ( from addresses import (
addBMIfNotPresent, addBMIfNotPresent,
calculateInventoryHash, calculateInventoryHash,
@ -42,21 +34,13 @@ from addresses import (
decodeVarint, decodeVarint,
varintDecodeError varintDecodeError
) )
=======
from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure from helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
from inventory import Inventory from inventory import Inventory
from network.threads import StoppableThread from network.threads import StoppableThread
<<<<<<< HEAD
from version import softwareVersion from version import softwareVersion
=======
# pylint: disable=unused-variable
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
str_chan = '[chan]' str_chan = '[chan]'
@ -275,13 +259,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(9, 'Invalid characters in address: ' + address) raise APIError(9, 'Invalid characters in address: ' + address)
if status == 'versiontoohigh': if status == 'versiontoohigh':
raise APIError( raise APIError(
<<<<<<< HEAD
10, 10,
'Address version number too high (or zero) in address: ' + 'Address version number too high (or zero) in address: ' +
address) address)
=======
10, 'Address version number too high (or zero) in address: ' + address)
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
if status == 'varintmalformed': if status == 'varintmalformed':
raise APIError(26, 'Malformed varint in address: ' + address) raise APIError(26, 'Malformed varint in address: ' + address)
raise APIError( raise APIError(
@ -645,13 +625,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
label = str_chan + ' ' + passphrase label = str_chan + ' ' + passphrase
except BaseException: except BaseException:
label = str_chan + ' ' + repr(passphrase) label = str_chan + ' ' + repr(passphrase)
<<<<<<< HEAD
status, addressVersionNumber, streamNumber, toRipe = ( status, addressVersionNumber, streamNumber, toRipe = (
self._verifyAddress(suppliedAddress)) self._verifyAddress(suppliedAddress))
=======
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(
suppliedAddress)
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
suppliedAddress = addBMIfNotPresent(suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress)
queues.apiAddressGeneratorReturnQueue.queue.clear() queues.apiAddressGeneratorReturnQueue.queue.clear()
queues.addressGeneratorQueue.put(( queues.addressGeneratorQueue.put((
@ -674,13 +649,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.') raise APIError(0, 'I need parameters.')
elif len(params) == 1: elif len(params) == 1:
address, = params address, = params
<<<<<<< HEAD
status, addressVersionNumber, streamNumber, toRipe = ( status, addressVersionNumber, streamNumber, toRipe = (
self._verifyAddress(address)) self._verifyAddress(address))
=======
status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(address)
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
raise APIError( raise APIError(
@ -701,13 +671,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.') raise APIError(0, 'I need parameters.')
elif len(params) == 1: elif len(params) == 1:
address, = params address, = params
<<<<<<< HEAD
status, addressVersionNumber, streamNumber, toRipe = ( status, addressVersionNumber, streamNumber, toRipe = (
self._verifyAddress(address)) self._verifyAddress(address))
=======
status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(address)
>>>>>>> 86df28c260eb1dd4acae506c1366f3cf136c5840
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
raise APIError( raise APIError(

View File

@ -53,6 +53,7 @@
<CustomTwoLineAvatarIconListItem>: <CustomTwoLineAvatarIconListItem>:
canvas: canvas:
Color: Color:
id: set_clr
# rgba: 0.5, 0.5, 0.5, 0.5 # rgba: 0.5, 0.5, 0.5, 0.5
rgba: 0,0,0,0 rgba: 0,0,0,0
Rectangle: #woohoo!!! Rectangle: #woohoo!!!

View File

@ -13,7 +13,7 @@
hint_text: 'type or select sender address' hint_text: 'type or select sender address'
size_hint_y: None size_hint_y: None
height: 100 height: 100
font_size: '13sp' font_size: '15sp'
multiline: False multiline: False
required: True required: True
helper_text_mode: "on_error" helper_text_mode: "on_error"
@ -26,34 +26,41 @@
background_color: app.theme_cls.primary_dark background_color: app.theme_cls.primary_dark
values: app.variable_1 values: app.variable_1
on_text: root.auto_fill_fromaddr() if self.text != 'Select' else '' on_text: root.auto_fill_fromaddr() if self.text != 'Select' else ''
option_cls: Factory.get("MySpinnerOption") option_cls: Factory.get("ComposerSpinnerOption")
#background_color: color_button if self.state == 'normal' else color_button_pressed #background_color: color_button if self.state == 'normal' else color_button_pressed
#background_down: 'atlas://data/images/defaulttheme/spinner' #background_down: 'atlas://data/images/defaulttheme/spinner'
background_normal: '' background_normal: ''
background_color: app.theme_cls.primary_color background_color: app.theme_cls.primary_color
color: color_font color: color_font
font_size: '12.5sp' font_size: '13.5sp'
ArrowImg: ArrowImg:
BoxLayout: BoxLayout:
orientation: 'vertical' orientation: 'horizontal'
txt_input: txt_input BoxLayout:
rv: rv orientation: 'vertical'
size : (890, 60) txt_input: txt_input
MyTextInput: rv: rv
id: txt_input size : (890, 60)
size_hint_y: None MyTextInput:
font_size: '13sp' id: txt_input
height: self.parent.height/2 size_hint_y: None
hint_text: 'type, select or scan QR code for recipients address' font_size: '15sp'
RV: height: self.parent.height/2
id: rv hint_text: 'type, select or scan QR code for recipients address'
RV:
id: rv
MDIconButton:
icon: 'qrcode-scan'
pos_hint: {'center_x': 0, 'center_y': .8}
on_press: root.qrScanner()
MyMDTextField: MyMDTextField:
id: subject id: subject
hint_text: 'subject' hint_text: 'subject'
required: True required: True
height: 100 height: 100
font_size: '13sp' font_size: '15sp'
size_hint_y: None size_hint_y: None
multiline: False multiline: False
helper_text_mode: "on_error" helper_text_mode: "on_error"
@ -63,7 +70,7 @@
multiline: True multiline: True
hint_text: 'body' hint_text: 'body'
size_hint_y: None size_hint_y: None
font_size: '13sp' font_size: '15sp'
required: True required: True
helper_text_mode: "on_error" helper_text_mode: "on_error"
BoxLayout: BoxLayout:
@ -106,4 +113,13 @@
<MyMDTextField@MDTextField>: <MyMDTextField@MDTextField>:
canvas.before: canvas.before:
Color: Color:
rgba: (0,0,0,1) rgba: (0,0,0,1)
<ComposerSpinnerOption@SpinnerOption>:
font_size: '13.5sp'
#background_color: color_button if self.state == 'down' else color_button_pressed
#background_down: 'atlas://data/images/defaulttheme/button'
background_normal: 'atlas://data/images/defaulttheme/textinput_active'
background_color: app.theme_cls.primary_color
color: color_font

View File

@ -87,7 +87,6 @@
text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged" text: "Here you may generate as many addresses as you like, Indeed creating and abandoning addresses is encouraged"
halign: 'center' halign: 'center'
color:app.theme_cls.primary_dark color:app.theme_cls.primary_dark
MDTextField: MDTextField:
id: label id: label
multiline: False multiline: False

View File

@ -15,16 +15,16 @@
OneLineListItem: OneLineListItem:
text: "Total Connections" text: "Total Connections"
BoxLayout: BoxLayout:
AnchorLayout: orientation: 'vertical'
MDRaisedButton: size_hint_y: None
size_hint: .6, .3 height: dp(58)
height: dp(40) MDRaisedButton:
MDLabel: size_hint: .5, 0
font_style: 'H6' height: dp(40)
text: root.text_variable_1 text: root.text_variable_1
font_size: '13sp' elevation_normal: 2
color: (1,1,1,1) opposite_colors: True
halign: 'center' pos_hint: {'center_x': .5}
Tab: Tab:
text: 'Processes' text: 'Processes'
ScrollView: ScrollView:
@ -36,52 +36,52 @@
OneLineListItem: OneLineListItem:
text: "person-to-person" text: "person-to-person"
BoxLayout: BoxLayout:
AnchorLayout: orientation: 'vertical'
MDRaisedButton: size_hint_y: None
size_hint: .7, .55 height: dp(58)
height: dp(40) MDRaisedButton:
MDLabel: size_hint: .5, 0
font_style: 'H6' height: dp(40)
text: root.text_variable_2 text: root.text_variable_2
font_size: '13sp' elevation_normal: 2
color: (1,1,1,1) opposite_colors: True
halign: 'center' pos_hint: {'center_x': .5}
OneLineListItem: OneLineListItem:
text: "Brodcast" text: "Brodcast"
BoxLayout: BoxLayout:
AnchorLayout: orientation: 'vertical'
MDRaisedButton: size_hint_y: None
size_hint: .7, .55 height: dp(58)
height: dp(40) MDRaisedButton:
MDLabel: size_hint: .5, 0
font_style: 'H6' height: dp(40)
text: root.text_variable_3 text: root.text_variable_3
font_size: '13sp' elevation_normal: 2
color: (1,1,1,1) opposite_colors: True
halign: 'center' pos_hint: {'center_x': .5}
OneLineListItem: OneLineListItem:
text: "publickeys" text: "publickeys"
BoxLayout: BoxLayout:
AnchorLayout: orientation: 'vertical'
MDRaisedButton: size_hint_y: None
size_hint: .7, .55 height: dp(58)
height: dp(40) MDRaisedButton:
MDLabel: size_hint: .5, 0
font_style: 'H6' height: dp(40)
text: root.text_variable_4 text: root.text_variable_4
font_size: '13sp' elevation_normal: 2
color: (1,1,1,1) opposite_colors: True
halign: 'center' pos_hint: {'center_x': .5}
OneLineListItem: OneLineListItem:
text: "objects" text: "objects"
BoxLayout: BoxLayout:
AnchorLayout: orientation: 'vertical'
MDRaisedButton: size_hint_y: None
size_hint: .7, .55 height: dp(58)
height: dp(40) MDRaisedButton:
MDLabel: size_hint: .5, 0
font_style: 'H6' height: dp(40)
text: root.text_variable_5 text: root.text_variable_5
font_size: '13sp' elevation_normal: 2
color: (1,1,1,1) opposite_colors: True
halign: 'center' pos_hint: {'center_x': .5}

View File

@ -47,7 +47,7 @@
size: self.size size: self.size
size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1 size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1
height: dp(40) height: dp(40)
on_press: root.get_available_credits(self) on_press: root.get_free_credits(self)
MDLabel: MDLabel:
font_style: 'H6' font_style: 'H6'
text: 'Get Free Credits' text: 'Get Free Credits'
@ -78,6 +78,7 @@
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
id: py2
font_style: 'H5' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: '€ 100.0' text: '€ 100.0'
@ -92,6 +93,7 @@
size: self.size size: self.size
size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1 size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1
height: dp(40) height: dp(40)
on_press: root.move_to_pay_option(py2.text)
MDLabel: MDLabel:
font_style: 'H6' font_style: 'H6'
text: 'Get Monthly Credits' text: 'Get Monthly Credits'
@ -122,6 +124,7 @@
halign: 'center' halign: 'center'
color: 1,1,1,1 color: 1,1,1,1
MDLabel: MDLabel:
id: py3
font_style: 'H5' font_style: 'H5'
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: '€ 500.0' text: '€ 500.0'
@ -136,6 +139,7 @@
size: self.size size: self.size
size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1 size: dp(app.window_size[0] - 2*self.parent.parent.padding[0]) - 10 , 1
height: dp(40) height: dp(40)
on_press: root.move_to_pay_option(py3.text)
MDLabel: MDLabel:
font_style: 'H6' font_style: 'H6'
text: 'Get Yearly Credits' text: 'Get Yearly Credits'

View File

@ -43,6 +43,7 @@
id: dropdown_item id: dropdown_item
text: 'italiano' text: 'italiano'
dropdown_max_height: 150 dropdown_max_height: 150
dropdown_bg: [1, 1, 1, 1]
pos_hint: {'center_x': 0.8, 'center_y': 0} pos_hint: {'center_x': 0.8, 'center_y': 0}
items: [f"{i}" for i in ['System Setting','U.S. English','italiano','Esperanto','dansk','Deutsch','Pirate English','francais','Nederlands','norsk bokmal','polski','portugues europeu']] items: [f"{i}" for i in ['System Setting','U.S. English','italiano','Esperanto','dansk','Deutsch','Pirate English','francais','Nederlands','norsk bokmal','polski','portugues europeu']]
BoxLayout: BoxLayout:
@ -284,26 +285,25 @@
halign: 'left' halign: 'left'
bold: True bold: True
BoxLayout: GridLayout:
orientation: 'horizontal' cols: 2
padding: [10, 0, 0, 0] padding: [10, 0, 0, 0]
BoxLayout: MDLabel:
orientation: 'horizontal' size_hint_x: None
MDLabel: font_style: 'Body1'
font_style: 'Body1' theme_text_color: 'Primary'
theme_text_color: 'Primary' text: "Type:"
text: "Type:" halign: 'left'
halign: 'left' MDDropDownItem:
BoxLayout: id: dropdown_item
orientation: 'horizontal' dropdown_bg: [1, 1, 1, 1]
MDDropDownItem: text: 'none'
id: dropdown_item pos_hint: {'x': 0.9, 'y': 0}
dropdown_bg: [1, 1, 1, 1] items: [f"{i}" for i in ['System Setting','U.S. English']]
text: 'none'
items: [f"{i}" for i in ['System Setting','U.S. English']]
BoxLayout: BoxLayout:
orientation: 'horizontal' orientation: 'horizontal'
padding: [30, 0, 0, 0] padding: [30, 0, 0, 0]
spacing: 10
BoxLayout: BoxLayout:
orientation: 'horizontal' orientation: 'horizontal'
MDLabel: MDLabel:
@ -323,6 +323,14 @@
theme_text_color: 'Primary' theme_text_color: 'Primary'
text: "Port:" text: "Port:"
halign: 'left' halign: 'left'
# TextInput:
# size_hint: None, None
# hint_text: '9050'
# size: dp(app.window_size[0]/4), dp(30)
# input_filter: "int"
# readonly: False
# multiline: False
# font_size: '15sp'
MDTextFieldRect: MDTextFieldRect:
size_hint: None, None size_hint: None, None
size: dp(app.window_size[0]/4), dp(30) size: dp(app.window_size[0]/4), dp(30)
@ -332,6 +340,7 @@
BoxLayout: BoxLayout:
orientation: 'horizontal' orientation: 'horizontal'
padding: [30, 0, 0, 0] padding: [30, 0, 0, 0]
spacing: 10
BoxLayout: BoxLayout:
orientation: 'horizontal' orientation: 'horizontal'
MDLabel: MDLabel:

View File

@ -27,7 +27,8 @@
#background_color: color_button if self.state == 'down' else color_button_pressed #background_color: color_button if self.state == 'down' else color_button_pressed
#background_down: 'atlas://data/images/defaulttheme/button' #background_down: 'atlas://data/images/defaulttheme/button'
background_normal: 'atlas://data/images/defaulttheme/textinput_active' background_normal: 'atlas://data/images/defaulttheme/textinput_active'
background_color: app.theme_cls.primary_color background_color: app.theme_cls.primary_color
# text_autoupdate: True
color: color_font color: color_font
<NavigationItem> <NavigationItem>
@ -101,7 +102,7 @@
id: btn id: btn
pos_hint:{"x":0,"y":0} pos_hint:{"x":0,"y":0}
option_cls: Factory.get("MySpinnerOption") option_cls: Factory.get("MySpinnerOption")
font_size: '10.9sp' font_size: '12.5sp'
text: app.getDefaultAccData() text: app.getDefaultAccData()
#background_color: color_button if self.state == 'normal' else color_button_pressed #background_color: color_button if self.state == 'normal' else color_button_pressed
#background_down: 'atlas://data/images/defaulttheme/spinner' #background_down: 'atlas://data/images/defaulttheme/spinner'
@ -111,11 +112,11 @@
#background_color: (0.62,0.67,0.72,1) #background_color: (0.62,0.67,0.72,1)
values: app.variable_1 values: app.variable_1
on_text:app.getCurrentAccountData(self.text) on_text:app.getCurrentAccountData(self.text)
Image: # Image:
source: app.get_default_image() # source: app.get_default_image()
x: self.width/6 # x: self.width/6
y: self.parent.y + self.parent.height/4 # y: self.parent.y + self.parent.height/4
size: self.parent.height/2, self.parent.height/2 # size: self.parent.height/2, self.parent.height/2
ArrowImg: ArrowImg:
NavigationItem: NavigationItem:
id: inbox_cnt id: inbox_cnt

View File

@ -95,33 +95,35 @@ def ShowTimeHistoy(act_time):
action_time = datetime.fromtimestamp(int(act_time)) action_time = datetime.fromtimestamp(int(act_time))
crnt_date = datetime.now() crnt_date = datetime.now()
duration = crnt_date - action_time duration = crnt_date - action_time
display_data = (action_time.strftime('%d/%m/%Y') display_data = (
action_time.strftime('%d/%m/%Y')
if duration.days >= 365 else action_time.strftime('%I:%M %p').lstrip('0') 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') if duration.days == 0 and crnt_date.strftime('%d/%m/%Y') == action_time.strftime('%d/%m/%Y')
else action_time.strftime("%d %b")) else action_time.strftime("%d %b")
)
return display_data return display_data
def AddTimeWidget(time): def AddTimeWidget(time): # pylint: disable=redefined-outer-name
"""This method is used to create TimeWidget""" """This method is used to create TimeWidget"""
action_time = BadgeText( action_time = BadgeText(
size_hint= (None, None), size_hint=(None, None),
text= f"{ShowTimeHistoy(time)}", text=str(ShowTimeHistoy(time)),
halign='right', halign='right',
font_style='Caption', font_style='Caption',
size= [65,70]) size=[65, 70])
return action_time return action_time
def chipTag(text): def chipTag(text):
"""This method is used for showing chip tag""" """This method is used for showing chip tag"""
obj = MDChip() obj = MDChip()
obj.size_hint= (None, None) obj.size_hint = (None, None)
obj.label= text obj.label = text
obj.icon= '' obj.icon = ''
obj.pos_hint= {'center_x': .96, 'center_y': .2} obj.pos_hint = {'center_x': .96, 'center_y': .2}
obj.height= dp(18) obj.height = dp(18)
obj.radius= 8 obj.radius = 8
return obj return obj
@ -167,12 +169,13 @@ class Inbox(Screen):
self.set_inboxCount(state.inbox_count) self.set_inboxCount(state.inbox_count)
for mail in self.queryreturn: for mail in self.queryreturn:
# third_text = mail[3].replace('\n', ' ') # third_text = mail[3].replace('\n', ' ')
body = mail[3].decode() if isinstance(mail[3],bytes) else mail[3] body = mail[3].decode() if isinstance(mail[3], bytes) else mail[3]
subject = mail[5].decode() if isinstance(mail[5],bytes) else mail[5] subject = mail[5].decode() if isinstance(mail[5], bytes) else mail[5]
data.append({ data.append({
'text': mail[4].strip(), 'text': mail[4].strip(),
'secondary_text': (subject[:50] + '........' if len( 'secondary_text': (subject[:50] + '........' if len(
subject) >= 50 else (subject + ',' + body)[0:50] + '........').replace('\t', '').replace(' ', ''), subject) >= 50 else (subject + ',' + body)[0:50] + '........').replace(
'\t', '').replace(' ', ''),
'msgid': mail[1], 'received': mail[6]}) 'msgid': mail[1], 'received': mail[6]})
self.has_refreshed = True self.has_refreshed = True
@ -255,12 +258,12 @@ class Inbox(Screen):
self.inboxDataQuery('toaddress', where, what, total_message, 5) self.inboxDataQuery('toaddress', where, what, total_message, 5)
for mail in self.queryreturn: for mail in self.queryreturn:
# third_text = mail[3].replace('\n', ' ') # third_text = mail[3].replace('\n', ' ')
subject = mail[3].decode() if isinstance(mail[3],bytes) else mail[3] subject = mail[3].decode() if isinstance(mail[3], bytes) else mail[3]
body = mail[5].decode() if isinstance(mail[5],bytes) else mail[5] body = mail[5].decode() if isinstance(mail[5], bytes) else mail[5]
data.append({ data.append({
'text': mail[4].strip(), 'text': mail[4].strip(),
'secondary_text': body[:50] + '........' if len( 'secondary_text': body[:50] + '........' if len(
body) >= 50 else (body + ',' +subject.replace( body) >= 50 else (body + ',' + subject.replace(
'\n', ''))[0:50] + '........', '\n', ''))[0:50] + '........',
'msgid': mail[1]}) 'msgid': mail[1]})
self.set_mdList(data) self.set_mdList(data)
@ -331,6 +334,7 @@ class Inbox(Screen):
class CustomTwoLineAvatarIconListItem(TwoLineAvatarIconListItem): class CustomTwoLineAvatarIconListItem(TwoLineAvatarIconListItem):
"""Custom Two Line Avatar Icon List"""
pass pass
@ -393,22 +397,26 @@ class MyAddress(Screen):
meny = CustomTwoLineAvatarIconListItem( meny = CustomTwoLineAvatarIconListItem(
text=item['text'], secondary_text=item['secondary_text'], text=item['text'], secondary_text=item['secondary_text'],
theme_text_color='Custom' if is_enable == 'true' else 'Primary', theme_text_color='Custom' if is_enable == 'true' else 'Primary',
text_color=NavigateApp().theme_cls.primary_color, text_color=NavigateApp().theme_cls.primary_color,)
) try:
meny.canvas.children[6].rgba = [0, 0, 0, 0] if is_enable == 'true' else [0.5, 0.5, 0.5, 0.5] meny.canvas.children[6].rgba = [0, 0, 0, 0] if is_enable == 'true' else [0.5, 0.5, 0.5, 0.5]
except Exception:
meny.canvas.children[9].rgba = [0, 0, 0, 0] if is_enable == 'true' else [0.5, 0.5, 0.5, 0.5]
meny.add_widget(AvatarSampleWidget( meny.add_widget(AvatarSampleWidget(
source='./images/text_images/{}.png'.format( source='./images/text_images/{}.png'.format(
avatarImageFirstLetter(item['text'].strip())))) avatarImageFirstLetter(item['text'].strip()))))
meny.bind(on_press=partial( meny.bind(on_press=partial(
self.myadd_detail, item['secondary_text'], item['text'])) self.myadd_detail, item['secondary_text'], item['text']))
if state.association == item['secondary_text']: if state.association == item['secondary_text']:
meny.add_widget(BadgeText(size_hint= (None, None), meny.add_widget(
text='Active', halign='right', BadgeText(
font_style='Body1', size= [50,60], size_hint=(None, None),
theme_text_color='Custom', text='Active', halign='right',
text_color=NavigateApp().theme_cls.primary_color)) font_style='Body1', size=[50, 60],
theme_text_color='Custom',
text_color=NavigateApp().theme_cls.primary_color))
else: else:
meny.add_widget(ToggleBtn(active = True if is_enable == 'true' else False)) meny.add_widget(ToggleBtn(active=True if is_enable == 'true' else False))
# carousel = Carousel(direction='right') # carousel = Carousel(direction='right')
# carousel.height = meny.height # carousel.height = meny.height
# carousel.size_hint_y = None # carousel.size_hint_y = None
@ -491,13 +499,15 @@ class MyAddress(Screen):
return True return True
return False return False
def disableAddress(self, address, instance): def disableAddress(self, address, instance):
"""This method is use for disabling address""" """This method is use for disabling address"""
BMConfigParser().set(str(address), 'enabled', 'false') BMConfigParser().set(str(address), 'enabled', 'false')
BMConfigParser().save() BMConfigParser().save()
instance.parent.parent.theme_text_color = 'Primary' instance.parent.parent.theme_text_color = 'Primary'
instance.parent.parent.canvas.children[6].rgba = [0.5, 0.5, 0.5, 0.5] try:
instance.parent.parent.canvas.children[6].rgba = [0.5, 0.5, 0.5, 0.5]
except Exception:
instance.parent.parent.canvas.children[9].rgba = [0.5, 0.5, 0.5, 0.5]
toast('Address disabled') toast('Address disabled')
Clock.schedule_once(self.address_permision_callback, 0) Clock.schedule_once(self.address_permision_callback, 0)
@ -506,7 +516,10 @@ class MyAddress(Screen):
BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().save() BMConfigParser().save()
instance.parent.parent.theme_text_color = 'Custom' instance.parent.parent.theme_text_color = 'Custom'
instance.parent.parent.canvas.children[6].rgba = [0, 0, 0, 0] try:
instance.parent.parent.canvas.children[6].rgba = [0, 0, 0, 0]
except Exception:
instance.parent.parent.canvas.children[9].rgba = [0, 0, 0, 0]
toast('Address Enabled') toast('Address Enabled')
Clock.schedule_once(self.address_permision_callback, 0) Clock.schedule_once(self.address_permision_callback, 0)
@ -818,6 +831,10 @@ class DropDownWidget(BoxLayout):
self.ids.ti.text = self.ids.btn.text self.ids.ti.text = self.ids.btn.text
self.ids.ti.focus = True self.ids.ti.focus = True
def qrScanner(self):
"""This method is used for scanning Qr code"""
pass
class MyTextInput(TextInput): class MyTextInput(TextInput):
"""Takes the text input in the field""" """Takes the text input in the field"""
@ -831,18 +848,18 @@ class MyTextInput(TextInput):
def __init__(self, **kwargs): def __init__(self, **kwargs):
"""Getting Text Input.""" """Getting Text Input."""
super(MyTextInput, self).__init__(**kwargs) super(MyTextInput, self).__init__(**kwargs)
self.__lineBreak__=0 self.__lineBreak__ = 0
def on_text(self, instance, value): def on_text(self, instance, value):
"""Find all the occurrence of the word""" """Find all the occurrence of the word"""
self.parent.parent.parent.parent.ids.rv.data = [] self.parent.parent.parent.parent.parent.ids.rv.data = []
matches = [self.word_list[i] for i in range( matches = [self.word_list[i] for i in range(
len(self.word_list)) if self.word_list[ len(self.word_list)) if self.word_list[
i][:self.starting_no] == value[:self.starting_no]] i][:self.starting_no] == value[:self.starting_no]]
display_data = [] display_data = []
for i in matches: for i in matches:
display_data.append({'text': i}) display_data.append({'text': i})
self.parent.parent.parent.parent.ids.rv.data = display_data self.parent.parent.parent.parent.parent.ids.rv.data = display_data
if len(matches) <= 10: if len(matches) <= 10:
self.parent.height = (250 + (len(matches) * 20)) self.parent.height = (250 + (len(matches) * 20))
else: else:
@ -860,7 +877,7 @@ class MyTextInput(TextInput):
class Payment(Screen): class Payment(Screen):
"""Payment module""" """Payment module"""
def get_available_credits(self, instance): def get_free_credits(self, instance):
"""Get the available credits""" """Get the available credits"""
# pylint: disable=no-self-use # pylint: disable=no-self-use
state.availabe_credit = instance.parent.children[1].text state.availabe_credit = instance.parent.children[1].text
@ -874,21 +891,25 @@ class Payment(Screen):
state.kivyapp.root.ids.sc18.ids.cred.text = '{0}'.format( state.kivyapp.root.ids.sc18.ids.cred.text = '{0}'.format(
state.availabe_credit) state.availabe_credit)
def move_to_pay_option(self, amount): # pylint: disable=no-self-use
"""Option move to pay"""
pass
class Credits(Screen): class Credits(Screen):
"""Credits Method""" """Credits Method"""
available_credits = StringProperty( available_credits = StringProperty('{0}'.format('€ 0'))
'{0}'.format('€ 0'))
class Login(Screen): class Login(Screen):
"""Login Screeen""" """Login Screeen"""
log_text1 = ('You may generate addresses by using either random numbers' log_text1 = (
' or by using a passphrase If you use a passphrase, the address' 'You may generate addresses by using either random numbers'
' is called a deterministic; address The Random Number option is' ' or by using a passphrase If you use a passphrase, the address'
' selected by default but deterministic addresses have several pros' ' is called a deterministic; address The Random Number option is'
' and cons:') ' selected by default but deterministic addresses have several pros'
' and cons:')
log_text2 = ('If talk about pros You can recreate your addresses on any computer' log_text2 = ('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' ' 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' ' as long as you can remember your passphrase and aside talk about cons'
@ -897,6 +918,7 @@ class Login(Screen):
' choose a weak passphrase and someone on the Internet can brute-force it,' ' choose a weak passphrase and someone on the Internet can brute-force it,'
' they can read your messages and send messages as you') ' they can read your messages and send messages as you')
class NetworkStat(Screen): class NetworkStat(Screen):
"""Method used to show network stat""" """Method used to show network stat"""
@ -1040,7 +1062,8 @@ class Sent(Screen):
data.append({ data.append({
'text': mail[1].strip(), 'text': mail[1].strip(),
'secondary_text': (mail[2][:50] + '........' if len( 'secondary_text': (mail[2][:50] + '........' if len(
mail[2]) >= 50 else (mail[2] + ',' + mail[3])[0:50] + '........').replace('\t', '').replace(' ', ''), mail[2]) >= 50 else (mail[2] + ',' + mail[3])[0:50] + '........').replace(
'\t', '').replace(' ', ''),
'ackdata': mail[5], 'senttime': mail[6]},) 'ackdata': mail[5], 'senttime': mail[6]},)
self.set_mdlist(data, 0) self.set_mdlist(data, 0)
self.has_refreshed = True self.has_refreshed = True
@ -1076,8 +1099,7 @@ class Sent(Screen):
meny = TwoLineAvatarIconListItem( meny = TwoLineAvatarIconListItem(
text=item['text'], secondary_text=item['secondary_text'], text=item['text'], secondary_text=item['secondary_text'],
theme_text_color='Custom', theme_text_color='Custom',
text_color=NavigateApp().theme_cls.primary_color text_color=NavigateApp().theme_cls.primary_color)
)
meny.add_widget(AvatarSampleWidget( meny.add_widget(AvatarSampleWidget(
source='./images/text_images/{}.png'.format( source='./images/text_images/{}.png'.format(
avatarImageFirstLetter(item['secondary_text'].strip())))) avatarImageFirstLetter(item['secondary_text'].strip()))))
@ -1110,20 +1132,27 @@ class Sent(Screen):
if len(self.ids.ml.children) < 3: if len(self.ids.ml.children) < 3:
self.ids.ml.clear_widgets() self.ids.ml.clear_widgets()
self.loadSent() self.loadSent()
total_sent = int(state.sent_count) + 1 if state.association == state.check_sent_acc:
state.sent_count = str(int(state.sent_count) +1) total_sent = int(state.sent_count) + 1
self.set_sentCount(total_sent) state.sent_count = str(int(state.sent_count) + 1)
self.set_sentCount(total_sent)
else:
total_sent = int(state.sent_count)
else: else:
data = [] data = []
self.sentDataQuery('fromaddress', '', '', 0, 1) self.sentDataQuery('fromaddress', '', '', 0, 1)
total_sent = int(state.sent_count) + 1 if state.association == state.check_sent_acc:
state.sent_count = str(int(state.sent_count) +1) total_sent = int(state.sent_count) + 1
self.set_sentCount(total_sent) state.sent_count = str(int(state.sent_count) + 1)
self.set_sentCount(total_sent)
else:
total_sent = int(state.sent_count)
for mail in self.queryreturn: for mail in self.queryreturn:
data.append({ data.append({
'text': mail[1].strip(), 'text': mail[1].strip(),
'secondary_text': (mail[2][:50] + '........' if len( 'secondary_text': (mail[2][:50] + '........' if len(
mail[2]) >= 50 else (mail[2] + ',' + mail[3])[0:50] + '........').replace('\t', '').replace(' ', ''), mail[2]) >= 50 else (mail[2] + ',' + mail[3])[0:50] + '........').replace(
'\t', '').replace(' ', ''),
'ackdata': mail[5], 'senttime': mail[6]}) 'ackdata': mail[5], 'senttime': mail[6]})
self.set_mdlist(data, total_sent - 1) self.set_mdlist(data, total_sent - 1)
if state.msg_counter_objs and state.association == ( if state.msg_counter_objs and state.association == (
@ -1281,8 +1310,8 @@ class Trash(Screen):
"""This method is used to create the mdlist""" """This method is used to create the mdlist"""
total_trash_msg = len(self.ids.ml.children) total_trash_msg = len(self.ids.ml.children)
for item in self.trash_messages: for item in self.trash_messages:
subject = item[2].decode() if isinstance(item[2],bytes) else item[2] subject = item[2].decode() if isinstance(item[2], bytes) else item[2]
body = item[3].decode() if isinstance(item[3],bytes) else item[3] body = item[3].decode() if isinstance(item[3], bytes) else item[3]
meny = TwoLineAvatarIconListItem( meny = TwoLineAvatarIconListItem(
text=item[1], text=item[1],
secondary_text=(item[2][:50] + '........' if len( secondary_text=(item[2][:50] + '........' if len(
@ -1400,8 +1429,9 @@ class Setting(Screen):
"""Setting the Screen components""" """Setting the Screen components"""
exp_text = "By default, if you send a message to someone and he is offline for more than two days, Bitmessage will\ exp_text = "By default, if you send a message to someone and he is offline for more than two days, Bitmessage will\
send the message again after an additional two days. This will be continued with exponential backoff\ send the message again after an additional two days. This will be continued with exponential backoff\
forever; messages will be resent after 5, 10, 20 days ect. until the receiver acknowledges them. Here you\ forever; messages will be resent after 5, 10, 20 days ect. until the receiver acknowledges them.\
may change that behavior by having Bitmessage give up after a certain number of days or months." Here you may change that behavior by having Bitmessage give up after a certain number of days \
or months."
class NavigateApp(MDApp): class NavigateApp(MDApp):
@ -1466,7 +1496,7 @@ class NavigateApp(MDApp):
LoadingPopup().open() LoadingPopup().open()
self.set_message_count() self.set_message_count()
for nav_obj in self.root.ids.content_drawer.children[ for nav_obj in self.root.ids.content_drawer.children[
0].children[0].children[0].children: 0].children[0].children[0].children:
nav_obj.active = True if nav_obj.text == 'Inbox' else False nav_obj.active = True if nav_obj.text == 'Inbox' else False
Clock.schedule_once(self.setCurrentAccountData, 0.5) Clock.schedule_once(self.setCurrentAccountData, 0.5)
@ -1520,7 +1550,7 @@ class NavigateApp(MDApp):
BMConfigParser().addresses()[0], android_path)) BMConfigParser().addresses()[0], android_path))
else: else:
if not os.path.exists('./images/default_identicon/{}.png'.format( if not os.path.exists('./images/default_identicon/{}.png'.format(
BMConfigParser().addresses()[0])): BMConfigParser().addresses()[0])):
img.texture.save('./images/default_identicon/{}.png'.format( img.texture.save('./images/default_identicon/{}.png'.format(
BMConfigParser().addresses()[0])) BMConfigParser().addresses()[0]))
return BMConfigParser().addresses()[0] return BMConfigParser().addresses()[0]
@ -1559,7 +1589,7 @@ class NavigateApp(MDApp):
return False return False
def on_key(self, window, key, *args): def on_key(self, window, key, *args):
# pylint: disable=inconsistent-return-statements # pylint: disable=inconsistent-return-statements, too-many-branches
"""Method is used for going on previous screen""" """Method is used for going on previous screen"""
if key == 27: if key == 27:
if state.in_search_mode and self.root.ids.scr_mngr.current != ( if state.in_search_mode and self.root.ids.scr_mngr.current != (
@ -1579,6 +1609,9 @@ class NavigateApp(MDApp):
self.root.ids.scr_mngr.current = 'myaddress' self.root.ids.scr_mngr.current = 'myaddress'
elif self.root.ids.scr_mngr.current == "random": elif self.root.ids.scr_mngr.current == "random":
self.root.ids.scr_mngr.current = 'login' self.root.ids.scr_mngr.current = 'login'
elif self.root.ids.scr_mngr.current == 'pay-options':
self.set_common_header()
self.root.ids.scr_mngr.current = 'payment'
else: else:
if state.kivyapp.variable_1: if state.kivyapp.variable_1:
self.root.ids.scr_mngr.current = 'inbox' self.root.ids.scr_mngr.current = 'inbox'
@ -1660,7 +1693,6 @@ class NavigateApp(MDApp):
state.in_composer = True state.in_composer = True
state.in_sent_method = False state.in_sent_method = False
def set_navbar_for_composer(self): def set_navbar_for_composer(self):
"""Clearing toolbar data when composer open""" """Clearing toolbar data when composer open"""
self.root.ids.toolbar.left_action_items = [ self.root.ids.toolbar.left_action_items = [
@ -1704,7 +1736,8 @@ class NavigateApp(MDApp):
if state.in_composer else 'allmails'\ if state.in_composer else 'allmails'\
if state.is_allmail else state.detailPageType\ if state.is_allmail else state.detailPageType\
if state.detailPageType else 'myaddress'\ if state.detailPageType else 'myaddress'\
if self.root.ids.scr_mngr.current == 'showqrcode' else 'inbox' if self.root.ids.scr_mngr.current == 'showqrcode' else 'payment'\
if self.root.ids.scr_mngr.current == 'pay-options' else 'inbox'
self.root.ids.scr_mngr.transition.direction = 'right' self.root.ids.scr_mngr.transition.direction = 'right'
self.root.ids.scr_mngr.transition.bind(on_complete=self.reset) self.root.ids.scr_mngr.transition.bind(on_complete=self.reset)
if state.is_allmail or state.detailPageType == 'draft': if state.is_allmail or state.detailPageType == 'draft':
@ -1728,12 +1761,13 @@ class NavigateApp(MDApp):
def set_message_count(self): def set_message_count(self):
"""Setting message count""" """Setting message count"""
try: msg_counter_objs = state.kivyapp.root.children[0].children[0].ids
msg_counter_objs = ( # try:
self.root_window.children[0].children[2].children[0].ids) # msg_counter_objs = (
except Exception: # self.root_window.children[0].children[2].children[0].ids)
msg_counter_objs = ( # except Exception:
self.root_window.children[2].children[2].children[0].ids) # msg_counter_objs = (
# self.root_window.children[2].children[2].children[0].ids)
self.get_inbox_count() self.get_inbox_count()
self.get_sent_count() self.get_sent_count()
state.trash_count = str(sqlQuery( state.trash_count = str(sqlQuery(
@ -1842,7 +1876,7 @@ class NavigateApp(MDApp):
def set_identicon(self, text): def set_identicon(self, text):
"""Show identicon in address spinner""" """Show identicon in address spinner"""
img = identiconGeneration.generate(text) img = identiconGeneration.generate(text)
self.root.children[0].children[0].ids.btn.children[1].texture = (img.texture) # 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) self.root.ids.content_drawer.ids.top_box.children[0].texture = (img.texture)
@ -1907,7 +1941,6 @@ class NavigateApp(MDApp):
def file_manager_open(self): def file_manager_open(self):
"""This method open the file manager of local system""" """This method open the file manager of local system"""
from kivymd.uix.filemanager import MDFileManager from kivymd.uix.filemanager import MDFileManager
from kivymd.uix.dialog import MDDialog
self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False) self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
self.file_manager = MDFileManager( self.file_manager = MDFileManager(
@ -1926,7 +1959,7 @@ class NavigateApp(MDApp):
from PIL import Image as PilImage from PIL import Image as PilImage
if not os.path.exists('./images/default_identicon/'): if not os.path.exists('./images/default_identicon/'):
os.makedirs('./images/default_identicon/') os.makedirs('./images/default_identicon/')
newImg = PilImage.open(path).resize((300,300)) newImg = PilImage.open(path).resize((300, 300))
newImg.save('./images/default_identicon/{0}.png'.format(state.association)) newImg.save('./images/default_identicon/{0}.png'.format(state.association))
self.load_selected_Image(state.association) self.load_selected_Image(state.association)
self.exit_manager() self.exit_manager()
@ -1941,12 +1974,13 @@ class NavigateApp(MDApp):
def load_selected_Image(self, curerentAddr): def load_selected_Image(self, curerentAddr):
"""This method load the selected image on screen""" """This method load the selected image on screen"""
top_box_obj = self.root.ids.content_drawer.ids.top_box.children[0] top_box_obj = self.root.ids.content_drawer.ids.top_box.children[0]
spinner_img_obj = self.root.ids.content_drawer.ids.btn.children[1] # spinner_img_obj = self.root.ids.content_drawer.ids.btn.children[1]
spinner_img_obj.source = top_box_obj.source ='./images/default_identicon/{0}.png'.format(curerentAddr) # spinner_img_obj.source = top_box_obj.source ='./images/default_identicon/{0}.png'.format(curerentAddr)
top_box_obj.source = './images/default_identicon/{0}.png'.format(curerentAddr)
top_box_obj.reload() top_box_obj.reload()
spinner_img_obj.reload() # spinner_img_obj.reload()
def copy_composer_text(self, text): def copy_composer_text(self, text): # pylint: disable=no-self-use
"""Copy the data from mail detail page""" """Copy the data from mail detail page"""
Clipboard.copy(text) Clipboard.copy(text)
toast('Copied') toast('Copied')
@ -2085,18 +2119,18 @@ class IconRightSampleWidget(IRightBodyTouch, MDIconButton):
pass pass
class IconRightSampleWidget(IRightBodyTouch, MDCheckbox):
"""Right icon sample widget"""
pass
class ToggleBtn(IRightBodyTouch, MDSwitch): class ToggleBtn(IRightBodyTouch, MDSwitch):
"""Right toggle button widget""" """Right toggle button widget"""
pass pass
class MailDetail(Screen): class CheckboxLeftSampleWidget(ILeftBodyTouch, MDCheckbox):
"""Left icon sample widget"""
pass
class MailDetail(Screen): # pylint: disable=too-many-instance-attributes
"""MailDetail Screen uses to show the detail of mails""" """MailDetail Screen uses to show the detail of mails"""
to_addr = StringProperty() to_addr = StringProperty()
@ -2133,8 +2167,8 @@ class MailDetail(Screen):
def assign_mail_details(self, data): def assign_mail_details(self, data):
"""Assigning mail details""" """Assigning mail details"""
subject = data[0][2].decode() if isinstance(data[0][2],bytes) else data[0][2] 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] body = data[0][3].decode() if isinstance(data[0][2], bytes) else data[0][3]
self.to_addr = data[0][0] if len(data[0][0]) > 4 else ' ' self.to_addr = data[0][0] if len(data[0][0]) > 4 else ' '
self.from_addr = data[0][1] self.from_addr = data[0][1]
@ -2144,7 +2178,7 @@ class MailDetail(Screen):
if len(data[0]) == 7: if len(data[0]) == 7:
self.status = data[0][4] self.status = data[0][4]
self.time_tag = ShowTimeHistoy(data[0][4]) if state.detailPageType == 'inbox' else ShowTimeHistoy(data[0][6]) self.time_tag = ShowTimeHistoy(data[0][4]) if state.detailPageType == 'inbox' else ShowTimeHistoy(data[0][6])
self.avatarImg= './images/avatar.png' if state.detailPageType == 'draft' else ( self.avatarImg = './images/avatar.png' if state.detailPageType == 'draft' else (
'./images/text_images/{0}.png'.format(avatarImageFirstLetter(self.subject.strip()))) './images/text_images/{0}.png'.format(avatarImageFirstLetter(self.subject.strip())))
self.timeinseconds = data[0][4] if state.detailPageType == 'inbox' else data[0][6] self.timeinseconds = data[0][4] if state.detailPageType == 'inbox' else data[0][6]
@ -2211,14 +2245,22 @@ class MailDetail(Screen):
def inbox_reply(self): def inbox_reply(self):
"""Reply inbox messages""" """Reply inbox messages"""
data = sqlQuery( data = sqlQuery(
"select toaddress, fromaddress, subject, message from inbox where" "select toaddress, fromaddress, subject, message, received from inbox where"
" msgid = ?;", state.mail_id) " msgid = ?;", state.mail_id)
composer_obj = self.parent.screens[2].children[1].ids composer_obj = self.parent.screens[2].children[1].ids
composer_obj.ti.text = data[0][0] composer_obj.ti.text = data[0][0]
composer_obj.btn.text = data[0][0] composer_obj.btn.text = data[0][0]
composer_obj.txt_input.text = data[0][1] composer_obj.txt_input.text = data[0][1]
composer_obj.subject.text = data[0][2] split_subject = data[0][2].split('Re:', 1)
composer_obj.body.text = '' composer_obj.subject.text = 'Re: ' + (split_subject[1] if len(split_subject) > 1 else split_subject[0])
time_obj = datetime.fromtimestamp(int(data[0][4]))
time_tag = time_obj.strftime("%d %b %Y, %I:%M %p")
sender_name = BMConfigParser().get(data[0][1], 'label')
composer_obj.body.text = (
'\n\n ------------------------On ' + time_tag + ', '
+ sender_name + ' wrote:-----------------------\n' + data[0][3])
composer_obj.body.focus = True
composer_obj.body.cursor = (0, 0)
state.kivyapp.root.ids.sc3.children[1].ids.rv.data = '' state.kivyapp.root.ids.sc3.children[1].ids.rv.data = ''
self.parent.current = 'create' self.parent.current = 'create'
state.kivyapp.set_navbar_for_composer() state.kivyapp.set_navbar_for_composer()
@ -2240,6 +2282,7 @@ class MailDetail(Screen):
navApp.set_navbar_for_composer() navApp.set_navbar_for_composer()
def detailedPopup(self): def detailedPopup(self):
"""Detailed popup"""
obj = SenderDetailPopup() obj = SenderDetailPopup()
obj.open() obj.open()
arg = (self.to_addr, self.from_addr, self.timeinseconds) arg = (self.to_addr, self.from_addr, self.timeinseconds)
@ -2271,7 +2314,7 @@ class MyaddDetailPopup(Popup):
state.kivyapp.set_navbar_for_composer() state.kivyapp.set_navbar_for_composer()
try: try:
window_obj = self.parent.children[2].ids window_obj = self.parent.children[2].ids
except Exception as e: except Exception:
window_obj = self.parent.children[1].ids window_obj = self.parent.children[1].ids
window_obj.sc3.children[1].ids.ti.text = self.address 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.btn.text = self.address
@ -2315,8 +2358,8 @@ class AddbookDetailPopup(Popup):
"UPDATE addressbook SET label = '{}' WHERE" "UPDATE addressbook SET label = '{}' WHERE"
" address = '{}';".format( " address = '{}';".format(
str(self.ids.add_label.text), address)) str(self.ids.add_label.text), address))
self.parent.children[1].ids.sc11.ids.ml.clear_widgets() state.kivyapp.root.ids.sc11.ids.ml.clear_widgets()
self.parent.children[1].ids.sc11.loadAddresslist(None, 'All', '') state.kivyapp.root.ids.sc11.loadAddresslist(None, 'All', '')
self.dismiss() self.dismiss()
toast('Saved') toast('Saved')
@ -2325,7 +2368,7 @@ class AddbookDetailPopup(Popup):
state.kivyapp.set_navbar_for_composer() state.kivyapp.set_navbar_for_composer()
try: try:
window_obj = self.parent.children[2].ids window_obj = self.parent.children[2].ids
except Exception as e: except Exception:
window_obj = self.parent.children[1].ids window_obj = self.parent.children[1].ids
window_obj.sc3.children[1].ids.txt_input.text = self.address 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.ti.text = ''
@ -2562,7 +2605,8 @@ class Draft(Screen):
encoding, encoding,
BMConfigParser().safeGetInt('bitmessagesettings', 'ttl')) BMConfigParser().safeGetInt('bitmessagesettings', 'ttl'))
state.msg_counter_objs = src_object.children[2].children[0].ids state.msg_counter_objs = src_object.children[2].children[0].ids
state.draft_count = str(int(state.draft_count) + 1) if state.association == fromAddress else state.draft_count 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.clear_widgets()
src_object.ids.sc16.add_widget(Draft()) src_object.ids.sc16.add_widget(Draft())
toast('Save draft') toast('Save draft')
@ -2646,12 +2690,12 @@ class Allmails(Screen):
"""This method is used to create mdList for allmaills""" """This method is used to create mdList for allmaills"""
data_exist = len(self.ids.ml.children) data_exist = len(self.ids.ml.children)
for item in self.all_mails: for item in self.all_mails:
body = item[3].decode() if isinstance(item[3],bytes) else item[3] body = item[3].decode() if isinstance(item[3], bytes) else item[3]
subject = item[2].decode() if isinstance(item[2],bytes) else item[2] subject = item[2].decode() if isinstance(item[2], bytes) else item[2]
meny = TwoLineAvatarIconListItem( meny = TwoLineAvatarIconListItem(
text=item[1], text=item[1],
secondary_text=(subject[:50] + '........' if len( secondary_text=(subject[:50] + '........' if len(
subject) >= 50 else ( subject) >= 50 else (
subject + ',' + body)[0:50] + '........').replace('\t', '').replace(' ', ''), subject + ',' + body)[0:50] + '........').replace('\t', '').replace(' ', ''),
theme_text_color='Custom', theme_text_color='Custom',
text_color=NavigateApp().theme_cls.primary_color) text_color=NavigateApp().theme_cls.primary_color)
@ -2822,6 +2866,7 @@ class NavigationItem(OneLineAvatarIconListItem):
active = BooleanProperty(False) active = BooleanProperty(False)
def currentlyActive(self): def currentlyActive(self):
"""Currenly active"""
for nav_obj in self.parent.children: for nav_obj in self.parent.children:
nav_obj.active = False nav_obj.active = False
self.active = True self.active = True
@ -2885,22 +2930,23 @@ class SenderDetailPopup(Popup):
super(SenderDetailPopup, self).__init__(**kwargs) super(SenderDetailPopup, self).__init__(**kwargs)
def assignDetail(self, to_addr, from_addr, timeinseconds): def assignDetail(self, to_addr, from_addr, timeinseconds):
"""Detailes assigned"""
self.to_addr = to_addr self.to_addr = to_addr
self.from_addr = from_addr self.from_addr = from_addr
time_obj = datetime.fromtimestamp(int(timeinseconds)) time_obj = datetime.fromtimestamp(int(timeinseconds))
self.time_tag = time_obj.strftime("%d %b %Y, %I:%M %p") self.time_tag = time_obj.strftime("%d %b %Y, %I:%M %p")
pop_height = 1.2*(self.ids.sd_label.height+self.ids.sd_btn.children[0].height) pop_height = 1.2 * (self.ids.sd_label.height + self.ids.sd_btn.children[0].height)
if len(to_addr) > 3: if len(to_addr) > 3:
self.height = 0 self.height = 0
self.height = pop_height self.height = pop_height
self.ids.to_addId.size_hint_y = None self.ids.to_addId.size_hint_y = None
self.ids.to_addId.height= 50 self.ids.to_addId.height = 50
frmaddbox = ToAddrBoxlayout() frmaddbox = ToAddrBoxlayout()
frmaddbox.set_toAddress(to_addr) frmaddbox.set_toAddress(to_addr)
self.ids.to_addId.add_widget(frmaddbox) self.ids.to_addId.add_widget(frmaddbox)
else: else:
self.height = 0 self.height = 0
self.height = pop_height/1.5 self.height = pop_height / 1.5
class OneLineListTitle(OneLineListItem): class OneLineListTitle(OneLineListItem):
@ -2909,6 +2955,7 @@ class OneLineListTitle(OneLineListItem):
long_press_time = NumericProperty(1) long_press_time = NumericProperty(1)
def on_state(self, instance, value): def on_state(self, instance, value):
"""On state"""
if value == 'down': if value == 'down':
lpt = self.long_press_time lpt = self.long_press_time
self._clockev = Clock.schedule_once(self._do_long_press, lpt) self._clockev = Clock.schedule_once(self._do_long_press, lpt)
@ -2916,9 +2963,11 @@ class OneLineListTitle(OneLineListItem):
self._clockev.cancel() self._clockev.cancel()
def _do_long_press(self, dt): def _do_long_press(self, dt):
"""Do long press"""
self.dispatch('on_long_press') self.dispatch('on_long_press')
def on_long_press(self, *largs): def on_long_press(self, *largs):
"""On long press"""
self.copymessageTitle(self.text) self.copymessageTitle(self.text)
def copymessageTitle(self, text): def copymessageTitle(self, text):
@ -2945,5 +2994,5 @@ class ToAddrBoxlayout(BoxLayout):
to_addr = StringProperty() to_addr = StringProperty()
def set_toAddress(self, to_addr): def set_toAddress(self, to_addr):
"""This method is use to set to address"""
self.to_addr = to_addr self.to_addr = to_addr
pass

View File

@ -3,7 +3,6 @@ BMConfigParser class definition and default configuration settings
""" """
# pylint: disable=no-self-use, arguments-differ # pylint: disable=no-self-use, arguments-differ
import configparser import configparser
import shutil
import os import os
import shutil import shutil
from datetime import datetime from datetime import datetime

View File

@ -439,8 +439,8 @@ class objectProcessor(threading.Thread):
return return
# Let us try to decrypt the pubkey # Let us try to decrypt the pubkey
toAddress, _ = state.neededPubkeys[bytes(tag)] #check with py2 toAddress, _ = state.neededPubkeys[bytes(tag)] # check with py2
if protocol.decryptAndCheckPubkeyPayload(bytes(data), toAddress) == \ if protocol.decryptAndCheckPubkeyPayload(bytes(data), toAddress) == \
'successful': 'successful':
# At this point we know that we have been waiting on this # At this point we know that we have been waiting on this
# pubkey. This function will command the workerThread # pubkey. This function will command the workerThread

View File

@ -1,7 +1,7 @@
""" """
Thread for performing PoW Thread for performing PoW
""" """
# pylint: disable=protected-access,too-many-branches,too-many-statements # pylint: disable=protected-access,too-many-branches,too-many-statements,unused-variable
# pylint: disable=no-self-use,too-many-lines,too-many-locals,relative-import # pylint: disable=no-self-use,too-many-lines,too-many-locals,relative-import
@ -455,7 +455,7 @@ class singleWorker(StoppableThread):
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 1 objectType = 1
Inventory()._realInventory[inventoryHash] = ( Inventory()[inventoryHash] = (
objectType, streamNumber, payload, embeddedTime, objectType, streamNumber, payload, embeddedTime,
doubleHashOfAddressData[32:] doubleHashOfAddressData[32:]
) )
@ -477,6 +477,7 @@ class singleWorker(StoppableThread):
def sendOnionPeerObj(self, peer=None): def sendOnionPeerObj(self, peer=None):
"""Send onionpeer object representing peer""" """Send onionpeer object representing peer"""
# pylint: disable=redefined-argument-from-local
if not peer: # find own onionhostname if not peer: # find own onionhostname
for peer in state.ownAddresses: for peer in state.ownAddresses:
if peer.host.endswith('.onion'): if peer.host.endswith('.onion'):
@ -684,7 +685,7 @@ class singleWorker(StoppableThread):
def sendMsg(self): def sendMsg(self):
"""Send a message-type object (assemble the object, perform PoW and put it to the inv announcement queue)""" """Send a message-type object (assemble the object, perform PoW and put it to the inv announcement queue)"""
# pylint: disable=too-many-nested-blocks # pylint: disable=too-many-nested-blocks,logging-format-interpolation,unused-variable
# Reset just in case # Reset just in case
sqlExecute( sqlExecute(
'''UPDATE sent SET status='msgqueued' ''' '''UPDATE sent SET status='msgqueued' '''
@ -873,7 +874,7 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Looking up the receiver\'s public key")) "Looking up the receiver\'s public key"))
)) ))
self.logger.info('Sending a message.') self.logger.info('Sending a message.')
# self.logger.debug( # self.logger.debug(
# 'First 150 characters of message: %s', # 'First 150 characters of message: %s',
@ -883,13 +884,13 @@ class singleWorker(StoppableThread):
# Let us fetch the recipient's public key out of # Let us fetch the recipient's public key out of
# our database. If the required proof of work difficulty # our database. If the required proof of work difficulty
# is too hard then we'll abort. # is too hard then we'll abort.
queryreturn = sqlQuery( queryreturn = sqlQuery(
'SELECT transmitdata FROM pubkeys WHERE address=?', 'SELECT transmitdata FROM pubkeys WHERE address=?',
toaddress) toaddress)
for row in queryreturn: # pylint: disable=redefined-outer-name for row in queryreturn: # pylint: disable=redefined-outer-name
pubkeyPayload, = row pubkeyPayload, = row
# The pubkey message is stored with the following items # The pubkey message is stored with the following items
# all appended: # all appended:
# -address version # -address version
@ -913,7 +914,7 @@ class singleWorker(StoppableThread):
# if receiver is a mobile device who expects that their # if receiver is a mobile device who expects that their
# address RIPE is included unencrypted on the front of # address RIPE is included unencrypted on the front of
# the message.. # the message..
if protocol.isBitSetWithinBitfield(behaviorBitfield, 30): if protocol.isBitSetWithinBitfield(behaviorBitfield, 30):
# if we are Not willing to include the receiver's # if we are Not willing to include the receiver's
# RIPE hash on the message.. # RIPE hash on the message..
@ -951,7 +952,7 @@ class singleWorker(StoppableThread):
readPosition:readPosition + 64] readPosition:readPosition + 64]
readPosition += 64 readPosition += 64
# Let us fetch the amount of work required by the recipient. # Let us fetch the amount of work required by the recipient.
if toAddressVersionNumber == 2: if toAddressVersionNumber == 2:
requiredAverageProofOfWorkNonceTrialsPerByte = \ requiredAverageProofOfWorkNonceTrialsPerByte = \
defaults.networkDefaultProofOfWorkNonceTrialsPerByte defaults.networkDefaultProofOfWorkNonceTrialsPerByte
requiredPayloadLengthExtraBytes = \ requiredPayloadLengthExtraBytes = \
@ -965,7 +966,7 @@ class singleWorker(StoppableThread):
"There is no required difficulty for" "There is no required difficulty for"
" version 2 addresses like this.")) " version 2 addresses like this."))
)) ))
elif toAddressVersionNumber >= 3: elif toAddressVersionNumber >= 3:
requiredAverageProofOfWorkNonceTrialsPerByte, \ requiredAverageProofOfWorkNonceTrialsPerByte, \
varintLength = decodeVarint( varintLength = decodeVarint(
@ -1158,7 +1159,7 @@ class singleWorker(StoppableThread):
fullAckPayload = self.generateFullAckMessage( fullAckPayload = self.generateFullAckMessage(
ackdata, toStreamNumber, TTL) ackdata, toStreamNumber, TTL)
payload += encodeVarint(len(fullAckPayload)) payload += encodeVarint(len(fullAckPayload))
payload += fullAckPayload if isinstance(fullAckPayload,bytes) else fullAckPayload.encode() payload += fullAckPayload if isinstance(fullAckPayload, bytes) else fullAckPayload.encode()
dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02'.encode() + \ dataToSign = pack('>Q', embeddedTime) + '\x00\x00\x00\x02'.encode() + \
encodeVarint(1) + encodeVarint(toStreamNumber) + payload encodeVarint(1) + encodeVarint(toStreamNumber) + payload
signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex) signature = highlevelcrypto.sign(dataToSign, privSigningKeyHex)
@ -1201,11 +1202,11 @@ class singleWorker(StoppableThread):
self.logger.info( self.logger.info(
'(For msg message) Doing proof of work. Total required' '(For msg message) Doing proof of work. Total required'
' difficulty: {}. Required small message difficulty: {}.'.format ' difficulty: {}. Required small message difficulty: {}.'.format
(float(requiredAverageProofOfWorkNonceTrialsPerByte) / (
defaults.networkDefaultProofOfWorkNonceTrialsPerByte, float(requiredAverageProofOfWorkNonceTrialsPerByte) /
float(requiredPayloadLengthExtraBytes) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
defaults.networkDefaultPayloadLengthExtraBytes) float(requiredPayloadLengthExtraBytes) /
) defaults.networkDefaultPayloadLengthExtraBytes))
powStartTime = time.time() powStartTime = time.time()
initialHash = hashlib.sha512(encryptedPayload).digest() initialHash = hashlib.sha512(encryptedPayload).digest()
@ -1238,8 +1239,8 @@ class singleWorker(StoppableThread):
inventoryHash = calculateInventoryHash(encryptedPayload) inventoryHash = calculateInventoryHash(encryptedPayload)
objectType = 2 objectType = 2
inventoryHashlist = ( inventoryHashlist = (
objectType, toStreamNumber,encryptedPayload, embeddedTime, '') objectType, toStreamNumber, encryptedPayload, embeddedTime, '')
Inventory()._realInventory[inventoryHash] = ( Inventory()[inventoryHash] = (
objectType, toStreamNumber, encryptedPayload, embeddedTime, '') objectType, toStreamNumber, encryptedPayload, embeddedTime, '')
if BMConfigParser().has_section(toaddress) or \ if BMConfigParser().has_section(toaddress) or \
not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK): not protocol.checkBitfield(behaviorBitfield, protocol.BITFIELD_DOESACK):
@ -1332,9 +1333,9 @@ class singleWorker(StoppableThread):
) )
return return
retryNumber = queryReturn[0][0] retryNumber = queryReturn[0][0]
if addressVersionNumber <= 3: if addressVersionNumber <= 3:
state.neededPubkeys[toAddress] = 0 state.neededPubkeys[toAddress] = 0
elif addressVersionNumber >= 4: elif addressVersionNumber >= 4:
# If the user just clicked 'send' then the tag # If the user just clicked 'send' then the tag
# (and other information) will already be in the # (and other information) will already be in the
# neededPubkeys dictionary. But if we are recovering # neededPubkeys dictionary. But if we are recovering
@ -1393,9 +1394,8 @@ class singleWorker(StoppableThread):
payload = self._doPOWDefaults(payload, TTL) payload = self._doPOWDefaults(payload, TTL)
inventoryHash = calculateInventoryHash(payload) inventoryHash = calculateInventoryHash(payload)
objectType = 1 objectType = 1
Inventory()._realInventory[inventoryHash] = ( Inventory()[inventoryHash] = (
objectType, streamNumber, payload, embeddedTime, '') objectType, streamNumber, payload, embeddedTime, '')
# Inventory()._realInventory[inventoryHashlist]
self.logger.info('sending inv (for the getpubkey message)') self.logger.info('sending inv (for the getpubkey message)')
queues.invQueue.put((streamNumber, inventoryHash)) queues.invQueue.put((streamNumber, inventoryHash))
# wait 10% past expiration # wait 10% past expiration

View File

@ -2,7 +2,6 @@
Message encoding end decoding functions Message encoding end decoding functions
""" """
import string
import zlib import zlib
import messagetypes import messagetypes

BIN
src/images/paymode/111.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

View File

@ -8,7 +8,7 @@ from singleton import Singleton
@Singleton @Singleton
class Inventory(): class Inventory(object):
""" """
Inventory singleton class which uses storage backends Inventory singleton class which uses storage backends
to manage the inventory. to manage the inventory.
@ -24,8 +24,8 @@ class Inventory():
# cheap inheritance copied from asyncore # cheap inheritance copied from asyncore
def __getattr__(self, attr): def __getattr__(self, attr):
if attr == "__contains__": # if attr == "__contains__":
self.numberOfInventoryLookupsPerformed += 1 # self.numberOfInventoryLookupsPerformed += 1
try: try:
realRet = getattr(self._realInventory, attr) realRet = getattr(self._realInventory, attr)
except AttributeError: except AttributeError:
@ -36,6 +36,15 @@ class Inventory():
else: else:
return realRet return realRet
# on python3 we have separately added __contains__ method
def __contains__(self, attr):
self.numberOfInventoryLookupsPerformed += 1
return getattr(self._realInventory, '__contains__')(attr)
# on python3 we have separately added __setitem__ method
def __setitem__(self, hash_, value):
return getattr(self._realInventory, '__setitem__')(hash_, value)
# hint for pylint: this is dictionary like object # hint for pylint: this is dictionary like object
def __getitem__(self, key): def __getitem__(self, key):
return self._realInventory[key] return self._realInventory[key]

View File

@ -15,7 +15,7 @@ class Message(MsgBase):
# UTF-8 and variable type validator # UTF-8 and variable type validator
if isinstance(data["subject"], str): if isinstance(data["subject"], str):
# Unicode is depreciated # Unicode is depreciated
self.subject =data["subject"] self.subject = data["subject"]
else: else:
# Unicode is depreciated # Unicode is depreciated
self.subject = str(data["subject"]) self.subject = str(data["subject"])

View File

@ -114,9 +114,10 @@ class BMObject(object): # pylint: disable=too-many-instance-attributes
or advertise it unnecessarily) or advertise it unnecessarily)
""" """
# if it's a stem duplicate, pretend we don't have it # if it's a stem duplicate, pretend we don't have it
# pylint: disable=protected-access
if Dandelion().hasHash(self.inventoryHash): if Dandelion().hasHash(self.inventoryHash):
return return
if self.inventoryHash in Inventory()._realInventory: if self.inventoryHash in Inventory():
raise BMObjectAlreadyHaveError() raise BMObjectAlreadyHaveError()
def checkObjectByType(self): def checkObjectByType(self):

View File

@ -1,7 +1,7 @@
""" """
Bitmessage Protocol Bitmessage Protocol
""" """
# pylint: disable=attribute-defined-outside-init, too-few-public-methods, logging-format-interpolation # pylint: disable=attribute-defined-outside-init,too-few-public-methods,logging-format-interpolation,protected-access
import base64 import base64
import hashlib import hashlib
import logging import logging
@ -31,7 +31,7 @@ from network.dandelion import Dandelion
from network.proxy import ProxyError from network.proxy import ProxyError
from network.objectracker import missingObjects, ObjectTracker from network.objectracker import missingObjects, ObjectTracker
from network.node import Node, Peer from network.node import Node, Peer
from queues import objectProcessorQueue, portCheckerQueue, invQueue, addrQueue from queues import objectProcessorQueue, portCheckerQueue, invQueue
from network.randomtrackingdict import RandomTrackingDict from network.randomtrackingdict import RandomTrackingDict
logger = logging.getLogger('default') logger = logging.getLogger('default')
@ -355,9 +355,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
# ignore dinv if dandelion turned off # ignore dinv if dandelion turned off
if dandelion and not state.dandelion: if dandelion and not state.dandelion:
return True return True
for i in map(bytes, items): for i in map(bytes, items):
if i in Inventory()._realInventory and not Dandelion().hasHash(i): if i in Inventory() and not Dandelion().hasHash(i):
continue continue
if dandelion and not Dandelion().hasHash(i): if dandelion and not Dandelion().hasHash(i):
Dandelion().addHash(i, self) Dandelion().addHash(i, self)
@ -409,7 +409,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
try: try:
self.object.checkObjectByType() self.object.checkObjectByType()
objectProcessorQueue.put(( objectProcessorQueue.put((
self.object.objectType, memoryview(self.object.data))) self.object.objectType, memoryview(self.object.data)))
except BMObjectInvalidError: except BMObjectInvalidError:
BMProto.stopDownloadingObject(self.object.inventoryHash, True) BMProto.stopDownloadingObject(self.object.inventoryHash, True)
else: else:
@ -417,10 +417,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
del missingObjects[self.object.inventoryHash] del missingObjects[self.object.inventoryHash]
except KeyError: except KeyError:
pass 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") Dandelion().removeHash(self.object.inventoryHash, "cycle detection")
Inventory()._realInventory[self.object.inventoryHash] = ( Inventory()[self.object.inventoryHash] = (
self.object.objectType, self.object.streamNumber, self.object.objectType, self.object.streamNumber,
memoryview(self.payload[objectOffset:]), self.object.expiresTime, memoryview(self.payload[objectOffset:]), self.object.expiresTime,
memoryview(self.object.tag) memoryview(self.object.tag)
@ -700,4 +699,4 @@ class BMStringParser(BMProto):
except Exception as e: except Exception as e:
logger.debug( logger.debug(
'Exception of type %s while sending ACK', 'Exception of type %s while sending ACK',
type(e), exc_info=True) type(e), exc_info=True)

View File

@ -40,7 +40,7 @@ class DownloadThread(StoppableThread):
del missingObjects[i] del missingObjects[i]
self.lastCleaned = time.time() self.lastCleaned = time.time()
def run(self): def run(self): # pylint: disable=protected-access
while not self._stopped: while not self._stopped:
requested = 0 requested = 0
connections = BMConnectionPool().establishedConnections() connections = BMConnectionPool().establishedConnections()
@ -61,7 +61,7 @@ class DownloadThread(StoppableThread):
payload = bytearray() payload = bytearray()
chunkCount = 0 chunkCount = 0
for chunk in request: for chunk in request:
if chunk in Inventory()._realInventory and not Dandelion().hasHash(chunk): if chunk in Inventory() and not Dandelion().hasHash(chunk):
try: try:
del i.objectsNewToMe[chunk] del i.objectsNewToMe[chunk]
except KeyError: except KeyError:

View File

@ -92,13 +92,13 @@ class InvThread(StoppableThread):
connection.append_write_buf(protocol.CreatePacket( connection.append_write_buf(protocol.CreatePacket(
'inv', 'inv',
addresses.encodeVarint( addresses.encodeVarint(
len(fluffs)) + ('').encode().join([x for x in fluffs]))) #compare result with python2 len(fluffs)) + ('').encode().join([x for x in fluffs]))) # compare result with python2
if stems: if stems:
random.shuffle(stems) random.shuffle(stems)
connection.append_write_buf(protocol.CreatePacket( connection.append_write_buf(protocol.CreatePacket(
'dinv', 'dinv',
addresses.encodeVarint( addresses.encodeVarint(
len(stems)) + ('').encode().join([x for x in stems]))) #compare result with python2 len(stems)) + ('').encode().join([x for x in stems]))) # compare result with python2
invQueue.iterate() invQueue.iterate()
for _ in range(len(chunk)): for _ in range(len(chunk)):

View File

@ -1,7 +1,7 @@
""" """
TCP protocol handler TCP protocol handler
""" """
# pylint: disable=too-many-ancestors # pylint: disable=too-many-ancestors, protected-access
import logging import logging
import math import math
import random import random
@ -211,7 +211,7 @@ class TCPConnection(BMProto, TLSDispatcher):
# may lock for a long time, but I think it's better than # may lock for a long time, but I think it's better than
# thousands of small locks # thousands of small locks
with self.objectsNewToThemLock: with self.objectsNewToThemLock:
for objHash in Inventory()._realInventory.unexpired_hashes_by_stream(stream): for objHash in Inventory().unexpired_hashes_by_stream(stream):
# don't advertise stem objects on bigInv # don't advertise stem objects on bigInv
if Dandelion().hasHash(objHash): if Dandelion().hasHash(objHash):
continue continue
@ -428,4 +428,4 @@ class TCPServer(AdvancedDispatcher):
connectionpool.BMConnectionPool().addConnection( connectionpool.BMConnectionPool().addConnection(
TCPConnection(sock=sock)) TCPConnection(sock=sock))
except socket.error: except socket.error:
pass pass

View File

@ -108,7 +108,6 @@ def _doFastPoW(target, initialHash):
logger.debug("Fast PoW done") logger.debug("Fast PoW done")
return result[0], result[1] return result[0], result[1]
time.sleep(0.2) time.sleep(0.2)
def _doCPoW(target, initialHash): def _doCPoW(target, initialHash):

View File

@ -289,7 +289,7 @@ def isProofOfWorkSufficient(
def CreatePacket(command, payload=''): def CreatePacket(command, payload=''):
"""Construct and return a number of bytes from a payload""" """Construct and return a number of bytes from a payload"""
payload = payload if type(payload) in [bytes, bytearray,memoryview] else payload.encode() payload = payload if type(payload) in [bytes, bytearray, memoryview] else payload.encode()
payload_length = len(payload) payload_length = len(payload)
checksum = hashlib.sha512(payload).digest()[0:4] checksum = hashlib.sha512(payload).digest()[0:4]
byte = bytearray(Header.size + payload_length) byte = bytearray(Header.size + payload_length)

View File

@ -25,7 +25,6 @@ from addresses import decodeAddress, encodeVarint
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger
from helper_sql import sqlQuery from helper_sql import sqlQuery
from pyelliptic import arithmetic
# pylint: disable=logging-format-interpolation # pylint: disable=logging-format-interpolation
verbose = 1 verbose = 1

View File

@ -39,11 +39,11 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors
return False return False
self._objects[hash_] = rows[0][0] self._objects[hash_] = rows[0][0]
return True return True
def __getitem__(self, hash_): def __getitem__(self, hash_):
with self.lock: with self.lock:
if isinstance(hash_,memoryview) and bytes(hash_) in self._inventory : if isinstance(hash_, memoryview) and bytes(hash_) in self._inventory:
return self._inventory[bytes(hash_)] return self._inventory[bytes(hash_)]
else: else:
if hash_ in self._inventory: if hash_ in self._inventory:
return self._inventory[hash_] return self._inventory[hash_]
@ -52,7 +52,7 @@ class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors
' FROM inventory WHERE hash=?', sqlite3.Binary(hash_)) ' FROM inventory WHERE hash=?', sqlite3.Binary(hash_))
if not rows: if not rows:
raise KeyError(hash_) raise KeyError(hash_)
return InventoryItem(*rows[0]) return InventoryItem(*rows[0])
def __setitem__(self, hash_, value): def __setitem__(self, hash_, value):
with self.lock: with self.lock: