Merge pull request #28 from cis-navjot-g/codequalitykivy

code fixes for PR#11
This commit is contained in:
lakshyacis 2019-09-18 12:28:57 +05:30 committed by GitHub
commit 6268554b5b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 90 additions and 51 deletions

View File

@ -1,5 +1,7 @@
"""Coding: utf-8.""" """
# pylint: disable=relative-import, too-many-lines src/bitmessagekivy/mpybit.py
=================================
"""
import os import os
import time import time
from functools import partial from functools import partial
@ -53,7 +55,7 @@ import queues
from semaphores import kivyuisignaler from semaphores import kivyuisignaler
import state import state
from uikivysignaler import UIkivySignaler from uikivysignaler import UIkivySignaler
# pylint: disable=unused-argument, too-few-public-methods # pylint: disable=unused-argument, too-few-public-methods, import-error
if platform == 'linux': if platform == 'linux':

View File

@ -1,4 +1,8 @@
#!/usr/bin/python2.7 """
src/bitmessagemain.py
=================================
"""
# !/usr/bin/python2.7
# Copyright (c) 2012-2016 Jonathan Warren # Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2019 The Bitmessage developers # Copyright (c) 2012-2019 The Bitmessage developers
# Distributed under the MIT/X11 software license. See the accompanying # Distributed under the MIT/X11 software license. See the accompanying
@ -11,16 +15,6 @@
import os import os
import sys import sys
app_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(app_dir)
sys.path.insert(0, app_dir)
import depends
depends.check_dependencies()
import ctypes import ctypes
import getopt import getopt
import multiprocessing import multiprocessing
@ -38,6 +32,7 @@ from helper_startup import (
from singleinstance import singleinstance from singleinstance import singleinstance
import defaults import defaults
import depends
import shared import shared
import knownnodes import knownnodes
import state import state
@ -67,8 +62,15 @@ from network.uploadthread import UploadThread
# Helper Functions # Helper Functions
import helper_threading import helper_threading
app_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(app_dir)
sys.path.insert(0, app_dir)
depends.check_dependencies()
def connectToStream(streamNumber): def connectToStream(streamNumber):
"""Connecting to stream"""
state.streamsInWhichIAmParticipating.append(streamNumber) state.streamsInWhichIAmParticipating.append(streamNumber)
if isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections(): if isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections():
@ -109,6 +111,7 @@ def _fixSocket():
addressToString = ctypes.windll.ws2_32.WSAAddressToStringA addressToString = ctypes.windll.ws2_32.WSAAddressToStringA
def inet_ntop(family, host): def inet_ntop(family, host):
"""inet ntop"""
if family == socket.AF_INET: if family == socket.AF_INET:
if len(host) != 4: if len(host) != 4:
raise ValueError("invalid IPv4 host") raise ValueError("invalid IPv4 host")
@ -130,6 +133,7 @@ def _fixSocket():
stringToAddress = ctypes.windll.ws2_32.WSAStringToAddressA stringToAddress = ctypes.windll.ws2_32.WSAStringToAddressA
def inet_pton(family, host): def inet_pton(family, host):
"""inet pton"""
buf = "\0" * 28 buf = "\0" * 28
lengthBuf = pack("I", len(buf)) lengthBuf = pack("I", len(buf))
if stringToAddress(str(host), if stringToAddress(str(host),
@ -175,16 +179,18 @@ def signal_handler(signum, frame):
if shared.thisapp.daemon or not state.enableGUI: if shared.thisapp.daemon or not state.enableGUI:
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
else: else:
print('# Thread: %s(%d)' % (thread.name, thread.ident)) print '# Thread: %s(%d)' % (thread.name, thread.ident)
for filename, lineno, name, line in traceback.extract_stack(frame): for filename, lineno, name, line in traceback.extract_stack(frame):
print('File: "%s", line %d, in %s' % (filename, lineno, name)) print 'File: "%s", line %d, in %s' % (filename, lineno, name)
if line: if line:
print(' %s' % line.strip()) print ' %s' % line.strip()
print('Unfortunately you cannot use Ctrl+C when running the UI' print 'Unfortunately you cannot use Ctrl+C when running the UI \
' because the UI captures the signal.') because the UI captures the signal.'
class Main: class Main: # pylint: disable=no-init, old-style-class
"""Main Method"""
@staticmethod @staticmethod
def start_proxyconfig(config): def start_proxyconfig(config):
"""Check socksproxytype and start any proxy configuration plugin""" """Check socksproxytype and start any proxy configuration plugin"""
@ -206,7 +212,8 @@ class Main:
'Started proxy config plugin %s in %s sec', 'Started proxy config plugin %s in %s sec',
proxy_type, time.time() - proxyconfig_start) proxy_type, time.time() - proxyconfig_start)
def start(self): def start(self): # pylint: disable=too-many-statements, too-many-branches, too-many-locals
"""Start the main method"""
_fixSocket() _fixSocket()
config = BMConfigParser() config = BMConfigParser()
@ -274,7 +281,7 @@ class Main:
if daemon: if daemon:
with shared.printLock: with shared.printLock:
print('Running as a daemon. Send TERM signal to end.') print 'Running as a daemon. Send TERM signal to end.'
self.daemonize() self.daemonize()
self.setSignalHandler() self.setSignalHandler()
@ -397,7 +404,7 @@ class Main:
if state.curses: if state.curses:
if not depends.check_curses(): if not depends.check_curses():
sys.exit() sys.exit()
print('Running with curses') print 'Running with curses'
import bitmessagecurses import bitmessagecurses
bitmessagecurses.runwrapper() bitmessagecurses.runwrapper()
@ -415,8 +422,7 @@ class Main:
if daemon: if daemon:
while state.shutdown == 0: while state.shutdown == 0:
time.sleep(1) time.sleep(1)
if ( if (state.testmode and time.time() - state.last_api_response >= 30):
state.testmode and time.time() - state.last_api_response >= 30):
self.stop() self.stop()
elif not state.enableGUI: elif not state.enableGUI:
from tests import core as test_core # pylint: disable=relative-import from tests import core as test_core # pylint: disable=relative-import
@ -430,7 +436,9 @@ class Main:
else 0 else 0
) )
def daemonize(self): @staticmethod
def daemonize():
"""Daemonize"""
grandfatherPid = os.getpid() grandfatherPid = os.getpid()
parentPid = None parentPid = None
try: try:
@ -440,7 +448,7 @@ class Main:
# wait until grandchild ready # wait until grandchild ready
while True: while True:
time.sleep(1) time.sleep(1)
os._exit(0) os._exit(0) # pylint: disable=protected-access
except AttributeError: except AttributeError:
# fork not implemented # fork not implemented
pass pass
@ -461,7 +469,7 @@ class Main:
# wait until child ready # wait until child ready
while True: while True:
time.sleep(1) time.sleep(1)
os._exit(0) os._exit(0) # pylint: disable=protected-access
except AttributeError: except AttributeError:
# fork not implemented # fork not implemented
pass pass
@ -482,12 +490,15 @@ class Main:
os.kill(parentPid, signal.SIGTERM) os.kill(parentPid, signal.SIGTERM)
os.kill(grandfatherPid, signal.SIGTERM) os.kill(grandfatherPid, signal.SIGTERM)
def setSignalHandler(self): def setSignalHandler(self): # pylint: disable=no-self-use
"""Set Signal Handler"""
signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGTERM, signal_handler)
# signal.signal(signal.SIGINT, signal.SIG_DFL) # signal.signal(signal.SIGINT, signal.SIG_DFL)
def usage(self): @staticmethod
def usage():
"""getting usages"""
print 'Usage: ' + sys.argv[0] + ' [OPTIONS]' print 'Usage: ' + sys.argv[0] + ' [OPTIONS]'
print ''' print '''
Options: Options:
@ -499,13 +510,15 @@ Options:
All parameters are optional. All parameters are optional.
''' '''
def stop(self): def stop(self): # pylint: disable=no-self-use
"""Stopping Bitmessage Deamon"""
with shared.printLock: with shared.printLock:
print('Stopping Bitmessage Deamon.') print 'Stopping Bitmessage Deamon.'
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
# TODO: nice function but no one is using this # ..todo: nice function but no one is using this
def getApiAddress(self): def getApiAddress(self): # pylint: disable=no-self-use
"""Getting Api Addresses"""
if not BMConfigParser().safeGetBoolean( if not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'apienabled'): 'bitmessagesettings', 'apienabled'):
return None return None
@ -515,6 +528,7 @@ All parameters are optional.
def main(): def main():
"""Start of main thread"""
mainprogram = Main() mainprogram = Main()
mainprogram.start() mainprogram.start()

View File

@ -1,9 +1,15 @@
"""
src/identiconGeneration
=================================
"""
import hashlib import hashlib
from PIL import Image from PIL import Image
from kivy.core.image import Image as CoreImage from kivy.core.image import Image as CoreImage
# Core classes for loading images and converting them to a Texture. The raw image data can be keep in memory for further access
from kivy.uix.image import Image as kiImage from kivy.uix.image import Image as kiImage
from io import BytesIO 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 """
# constants # constants
RESOLUTION = 128, 128 RESOLUTION = 128, 128
@ -13,6 +19,7 @@ MODE = "RGB"
def generate(Generate_string=None): def generate(Generate_string=None):
"""Generating string"""
hash_string = generate_hash(Generate_string) hash_string = generate_hash(Generate_string)
color = random_color(hash_string) color = random_color(hash_string)
image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR) image = Image.new(MODE, V_RESOLUTION, BACKGROUND_COLOR)
@ -32,20 +39,22 @@ def generate(Generate_string=None):
def generate_hash(string): def generate_hash(string):
"""Generating hash"""
try: try:
# make input case insensitive # make input case insensitive
string = str.lower(string) string = str.lower(string)
hash_object = hashlib.md5(str.encode(string)) hash_object = hashlib.md5(str.encode(string))
print(hash_object.hexdigest()) print hash_object.hexdigest()
# returned object is a hex string # returned object is a hex string
return hash_object.hexdigest() return hash_object.hexdigest()
except IndexError: except IndexError:
print("Error: Please enter a string as an argument.") print "Error: Please enter a string as an argument."
def random_color(hash_string): def random_color(hash_string):
"""Getting random color"""
# remove first three digits from hex string # remove first three digits from hex string
split = 6 split = 6
rgb = hash_string[:split] rgb = hash_string[:split]
@ -62,6 +71,7 @@ def random_color(hash_string):
def generate_image(image, color, hash_string): def generate_image(image, color, hash_string):
"""Generating images"""
hash_string = hash_string[6:] hash_string = hash_string[6:]
lower_x = 1 lower_x = 1

View File

@ -1,4 +1,15 @@
#!/usr/bin/env python """
src/pyelliptic/openssl.py
=================================
"""
import sys
import ctypes
from kivy.utils import platform
OpenSSL = None
# !/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com> # Copyright (C) 2011 Yann GUIBET <yannguibet@gmail.com>
@ -6,13 +17,9 @@
# #
# Software slightly changed by Jonathan Warren <bitmessage at-symbol jonwarren.org> # Software slightly changed by Jonathan Warren <bitmessage at-symbol jonwarren.org>
import sys
import ctypes
OpenSSL = None class CipherName: # pylint: disable=old-style-class
from kivy.utils import platform """Getting CipherName"""
class CipherName:
def __init__(self, name, pointer, blocksize): def __init__(self, name, pointer, blocksize):
self._name = name self._name = name
self._pointer = pointer self._pointer = pointer
@ -24,16 +31,20 @@ class CipherName:
" | Function pointer : " + str(self._pointer) " | Function pointer : " + str(self._pointer)
def get_pointer(self): def get_pointer(self):
"""Getting pointer"""
return self._pointer() return self._pointer()
def get_name(self): def get_name(self):
"""Getting Name"""
return self._name return self._name
def get_blocksize(self): def get_blocksize(self):
"""Getting blocksize"""
return self._blocksize return self._blocksize
def get_version(library): def get_version(library):
"""Getting versions"""
version = None version = None
hexversion = None hexversion = None
cflags = None cflags = None
@ -64,14 +75,11 @@ def get_version(library):
return (version, hexversion, cflags) return (version, hexversion, cflags)
class _OpenSSL: class _OpenSSL: # pylint: disable=too-many-instance-attributes, old-style-class, too-many-statements
""" """Wrapper for OpenSSL using ctypes"""
Wrapper for OpenSSL using ctypes
"""
def __init__(self, library): def __init__(self, library):
""" """Build the wrapper"""
Build the wrapper
"""
self._lib = ctypes.CDLL(library) self._lib = ctypes.CDLL(library)
self._version, self._hexversion, self._cflags = get_version(self._lib) self._version, self._hexversion, self._cflags = get_version(self._lib)
self._libreSSL = self._version.startswith("LibreSSL") self._libreSSL = self._version.startswith("LibreSSL")
@ -594,6 +602,7 @@ class _OpenSSL:
""" """
returns the name of a elliptic curve with his id returns the name of a elliptic curve with his id
""" """
# pylint: disable=redefined-builtin
res = None res = None
for i in self.curves: for i in self.curves:
if self.curves[i] == id: if self.curves[i] == id:
@ -607,6 +616,7 @@ class _OpenSSL:
""" """
OpenSSL random function OpenSSL random function
""" """
# pylint: disable=redefined-builtin
buffer = self.malloc(0, size) buffer = self.malloc(0, size)
# This pyelliptic library, by default, didn't check the return value of RAND_bytes. It is # This pyelliptic library, by default, didn't check the return value of RAND_bytes. It is
# evidently possible that it returned an error and not-actually-random data. However, in # evidently possible that it returned an error and not-actually-random data. However, in
@ -623,6 +633,7 @@ class _OpenSSL:
""" """
returns a create_string_buffer (ctypes) returns a create_string_buffer (ctypes)
""" """
# pylint: disable=redefined-builtin
buffer = None buffer = None
if data != 0: if data != 0:
if sys.version_info.major == 3 and isinstance(data, type('')): if sys.version_info.major == 3 and isinstance(data, type('')):
@ -634,6 +645,8 @@ class _OpenSSL:
def loadOpenSSL(): def loadOpenSSL():
"""Loading OpenSSL"""
# pylint: disable=global-statement, protected-access, too-many-branches
global OpenSSL global OpenSSL
from os import path, environ from os import path, environ
from ctypes.util import find_library from ctypes.util import find_library