fix small failures in migrating to Python3 + PyQt6

This commit is contained in:
Kashiko Koibumi 2024-05-18 10:24:00 +09:00
parent 97c9b7eaf6
commit 74bb8763e9
No known key found for this signature in database
GPG Key ID: 8F06E069E37C40C4
13 changed files with 53 additions and 66 deletions

View File

@ -1419,7 +1419,7 @@ class MyForm(settingsmixin.SMainWindow):
self, title, subtitle, category, label=None, icon=QtWidgets.QSystemTrayIcon.MessageIcon.Information): self, title, subtitle, category, label=None, icon=QtWidgets.QSystemTrayIcon.MessageIcon.Information):
self.playSound(category, label) self.playSound(category, label)
self._notifier( self._notifier(
str(title), str(subtitle), category, label, icon) title, subtitle, category, label, icon)
# tree # tree
def treeWidgetKeyPressEvent(self, event): def treeWidgetKeyPressEvent(self, event):
@ -2860,7 +2860,6 @@ class MyForm(settingsmixin.SMainWindow):
lines[i] = '<br><br>' lines[i] = '<br><br>'
content = ' '.join(lines) # To keep the whitespace between lines content = ' '.join(lines) # To keep the whitespace between lines
content = shared.fixPotentiallyInvalidUTF8Data(content) content = shared.fixPotentiallyInvalidUTF8Data(content)
content = content
textEdit.setHtml(content) textEdit.setHtml(content)
def on_action_InboxMarkUnread(self): def on_action_InboxMarkUnread(self):
@ -3786,20 +3785,20 @@ class MyForm(settingsmixin.SMainWindow):
self.setAddressSound(widget.item(widget.currentRow(), 0).text()) self.setAddressSound(widget.item(widget.currentRow(), 0).text())
def setAddressSound(self, addr): def setAddressSound(self, addr):
filters = [str(_translate( filters = [_translate(
"MainWindow", "Sound files (%s)" % "MainWindow", "Sound files (%s)" %
' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions]) ' '.join(['*%s%s' % (os.extsep, ext) for ext in sound.extensions])
))] )]
sourcefile = str(QtWidgets.QFileDialog.getOpenFileName( sourcefile = QtWidgets.QFileDialog.getOpenFileName(
self, _translate("MainWindow", "Set notification sound..."), self, _translate("MainWindow", "Set notification sound..."),
filter=';;'.join(filters) filter=';;'.join(filters)
)) )
if not sourcefile: if not sourcefile:
return return
destdir = os.path.join(state.appdata, 'sounds') destdir = os.path.join(state.appdata, 'sounds')
destfile = str(addr) + os.path.splitext(sourcefile)[-1] destfile = addr + os.path.splitext(sourcefile)[-1]
destination = os.path.join(destdir, destfile) destination = os.path.join(destdir, destfile)
if sourcefile == destination: if sourcefile == destination:
@ -3952,7 +3951,6 @@ class MyForm(settingsmixin.SMainWindow):
def inboxSearchLineEditUpdated(self, text): def inboxSearchLineEditUpdated(self, text):
# dynamic search for too short text is slow # dynamic search for too short text is slow
text = text
if 0 < len(text) < 3: if 0 < len(text) < 3:
return return
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
@ -4080,7 +4078,7 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderMessagelistToLabels() self.rerenderMessagelistToLabels()
completerList = self.ui.lineEditTo.completer().model().stringList() completerList = self.ui.lineEditTo.completer().model().stringList()
for i in range(len(completerList)): for i in range(len(completerList)):
if str(completerList[i]).endswith(" <" + item.address + ">"): if completerList[i].endswith(" <" + item.address + ">"):
completerList[i] = item.label + " <" + item.address + ">" completerList[i] = item.label + " <" + item.address + ">"
self.ui.lineEditTo.completer().model().setStringList(completerList) self.ui.lineEditTo.completer().model().setStringList(completerList)

View File

@ -135,7 +135,6 @@ class AccountMixin(object):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
retval, = row retval, = row
retval = retval
elif self.address is None or self.type == AccountMixin.ALL: elif self.address is None or self.type == AccountMixin.ALL:
return _translate("MainWindow", "All accounts") return _translate("MainWindow", "All accounts")

View File

@ -142,7 +142,7 @@ class addressGenerator(StoppableThread):
): ):
break break
self.logger.info( self.logger.info(
'Generated address with ripe digest: %s', hexlify(ripe)) 'Generated address with ripe digest: %s', hexlify(ripe).decode())
try: try:
self.logger.info( self.logger.info(
'Address generator calculated %s addresses at %s' 'Address generator calculated %s addresses at %s'
@ -255,7 +255,7 @@ class addressGenerator(StoppableThread):
break break
self.logger.info( self.logger.info(
'Generated address with ripe digest: %s', hexlify(ripe)) 'Generated address with ripe digest: %s', hexlify(ripe).decode())
try: try:
self.logger.info( self.logger.info(
'Address generator calculated %s addresses' 'Address generator calculated %s addresses'

View File

@ -153,7 +153,7 @@ class objectProcessor(threading.Thread):
data[readPosition:], data[readPosition:],
_translate( _translate(
"MainWindow", "MainWindow",
"Acknowledgement of the message received {}" "Acknowledgement of the message received {0}"
).format(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
else: else:
@ -326,8 +326,8 @@ class objectProcessor(threading.Thread):
'within recpubkey, addressVersion: %s, streamNumber: %s' 'within recpubkey, addressVersion: %s, streamNumber: %s'
'\nripe %s\npublicSigningKey in hex: %s' '\nripe %s\npublicSigningKey in hex: %s'
'\npublicEncryptionKey in hex: %s', '\npublicEncryptionKey in hex: %s',
addressVersion, streamNumber, hexlify(ripe), addressVersion, streamNumber, hexlify(ripe).decode(),
hexlify(publicSigningKey), hexlify(publicEncryptionKey) hexlify(publicSigningKey).decode(), hexlify(publicEncryptionKey).decode()
) )
address = encodeAddress(addressVersion, streamNumber, ripe) address = encodeAddress(addressVersion, streamNumber, ripe)
@ -391,8 +391,8 @@ class objectProcessor(threading.Thread):
'within recpubkey, addressVersion: %s, streamNumber: %s' 'within recpubkey, addressVersion: %s, streamNumber: %s'
'\nripe %s\npublicSigningKey in hex: %s' '\nripe %s\npublicSigningKey in hex: %s'
'\npublicEncryptionKey in hex: %s', '\npublicEncryptionKey in hex: %s',
addressVersion, streamNumber, hexlify(ripe), addressVersion, streamNumber, hexlify(ripe).decode(),
hexlify(publicSigningKey), hexlify(publicEncryptionKey) hexlify(publicSigningKey).decode(), hexlify(publicEncryptionKey).decode()
) )
address = encodeAddress(addressVersion, streamNumber, ripe) address = encodeAddress(addressVersion, streamNumber, ripe)
@ -481,7 +481,7 @@ class objectProcessor(threading.Thread):
initialDecryptionSuccessful = True initialDecryptionSuccessful = True
logger.info( logger.info(
'EC decryption successful using key associated' 'EC decryption successful using key associated'
' with ripe hash: %s.', hexlify(key)) ' with ripe hash: %s.', hexlify(key).decode())
except Exception: # nosec B110 except Exception: # nosec B110
pass pass
if not initialDecryptionSuccessful: if not initialDecryptionSuccessful:
@ -544,8 +544,8 @@ class objectProcessor(threading.Thread):
' Attack.\nSee: ' ' Attack.\nSee: '
'http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html' 'http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
'\nyour toRipe: %s\nembedded destination toRipe: %s', '\nyour toRipe: %s\nembedded destination toRipe: %s',
hexlify(toRipe), hexlify(toRipe).decode(),
hexlify(decryptedData[readPosition:readPosition + 20]) hexlify(decryptedData[readPosition:readPosition + 20]).decode()
) )
readPosition += 20 readPosition += 20
messageEncodingType, messageEncodingTypeLength = decodeVarint( messageEncodingType, messageEncodingTypeLength = decodeVarint(
@ -808,9 +808,9 @@ class objectProcessor(threading.Thread):
logger.info( logger.info(
'EC decryption successful using key associated' 'EC decryption successful using key associated'
' with ripe hash: %s', hexlify(key).decode()) ' with ripe hash: %s', hexlify(key).decode())
except Exception as ex: except Exception:
logger.debug( logger.debug(
'cryptorObject.decrypt Exception: {}'.format(ex)) 'cryptorObject.decrypt Exception:', exc_info=True)
if not initialDecryptionSuccessful: if not initialDecryptionSuccessful:
# This is not a broadcast I am interested in. # This is not a broadcast I am interested in.
return logger.debug( return logger.debug(

View File

@ -146,38 +146,38 @@ class singleWorker(StoppableThread):
if command == 'sendmessage': if command == 'sendmessage':
try: try:
self.sendMsg() self.sendMsg()
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("sendMsg didn't work: {}".format(ex)) self.logger.warning("sendMsg didn't work")
elif command == 'sendbroadcast': elif command == 'sendbroadcast':
try: try:
self.sendBroadcast() self.sendBroadcast()
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("sendBroadcast didn't work: {}".format(ex)) self.logger.warning("sendBroadcast didn't work")
elif command == 'doPOWForMyV2Pubkey': elif command == 'doPOWForMyV2Pubkey':
try: try:
self.doPOWForMyV2Pubkey(data) self.doPOWForMyV2Pubkey(data)
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("doPOWForMyV2Pubkey didn't work: {}".format(ex)) self.logger.warning("doPOWForMyV2Pubkey didn't work")
elif command == 'sendOutOrStoreMyV3Pubkey': elif command == 'sendOutOrStoreMyV3Pubkey':
try: try:
self.sendOutOrStoreMyV3Pubkey(data) self.sendOutOrStoreMyV3Pubkey(data)
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("sendOutOrStoreMyV3Pubkey didn't work: {}".format(ex)) self.logger.warning("sendOutOrStoreMyV3Pubkey didn't work")
elif command == 'sendOutOrStoreMyV4Pubkey': elif command == 'sendOutOrStoreMyV4Pubkey':
try: try:
self.sendOutOrStoreMyV4Pubkey(data) self.sendOutOrStoreMyV4Pubkey(data)
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("sendOutOrStoreMyV4Pubkey didn't work: {}".format(ex)) self.logger.warning("sendOutOrStoreMyV4Pubkey didn't work")
elif command == 'sendOnionPeerObj': elif command == 'sendOnionPeerObj':
try: try:
self.sendOnionPeerObj(data) self.sendOnionPeerObj(data)
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("sendOnionPeerObj didn't work: {}".format(ex)) self.logger.warning("sendOnionPeerObj didn't work")
elif command == 'resetPoW': elif command == 'resetPoW':
try: try:
proofofwork.resetPoW() proofofwork.resetPoW()
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("proofofwork.resetPoW didn't work: {}".format(ex)) self.logger.warning("proofofwork.resetPoW didn't work")
elif command == 'stopThread': elif command == 'stopThread':
self.busy = 0 self.busy = 0
return return
@ -1230,8 +1230,8 @@ class singleWorker(StoppableThread):
encrypted = highlevelcrypto.encrypt( encrypted = highlevelcrypto.encrypt(
payload, b"04" + hexlify(pubEncryptionKeyBase256) payload, b"04" + hexlify(pubEncryptionKeyBase256)
) )
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("highlevelcrypto.encrypt didn't work: {}".format(ex)) self.logger.warning("highlevelcrypto.encrypt didn't work")
sqlExecute( sqlExecute(
'''UPDATE sent SET status='badkey' WHERE ackdata=? AND folder='sent' ''', '''UPDATE sent SET status='badkey' WHERE ackdata=? AND folder='sent' ''',
ackdata ackdata
@ -1282,8 +1282,8 @@ class singleWorker(StoppableThread):
time.time() - powStartTime, time.time() - powStartTime,
sizeof_fmt(nonce / (time.time() - powStartTime)) sizeof_fmt(nonce / (time.time() - powStartTime))
) )
except Exception as ex: # noqa:E722 except: # noqa:E722
self.logger.warning("Proof of Work exception: {}".format(ex)) self.logger.warning("Proof of Work exception")
encryptedPayload = pack('>Q', nonce) + encryptedPayload encryptedPayload = pack('>Q', nonce) + encryptedPayload
@ -1485,7 +1485,7 @@ class singleWorker(StoppableThread):
tr._translate( tr._translate(
"MainWindow", "MainWindow",
"Sending public key request. Waiting for reply." "Sending public key request. Waiting for reply."
" Requested at %1" " Requested at {0}"
).format(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))

View File

@ -435,8 +435,8 @@ def check_dependencies(verbose=False, optional=False):
logger.info('Python version: %s', sys.version) logger.info('Python version: %s', sys.version)
if sys.hexversion < 0x3000000: if sys.hexversion < 0x3000000:
logger.error( logger.error(
'PyBitmessage requires Python 3 or greater') 'PyBitmessage does not support Python 2.7-. Python 3'
#has_all_dependencies = False ' or greater is required.')
sys.exit() sys.exit()
# FIXME: This needs to be uncommented when more of the code is python3 compatible # FIXME: This needs to be uncommented when more of the code is python3 compatible

View File

@ -71,16 +71,12 @@ class MsgEncode(object):
def encodeSimple(self, message): def encodeSimple(self, message):
"""Handle simple encoding""" """Handle simple encoding"""
data = 'Subject:%(subject)s\nBody:%(body)s' % message self.data = ('Subject:%(subject)s\nBody:%(body)s' % message).encode()
self.data = data.encode('utf-8', 'backslashreplace')
self.length = len(self.data) self.length = len(self.data)
def encodeTrivial(self, message): def encodeTrivial(self, message):
"""Handle trivial encoding""" """Handle trivial encoding"""
data = message['body'] self.data = message['body'].encode()
if isinstance(data, str):
data = data.encode('utf-8', 'backslashreplace')
self.data = data
self.length = len(self.data) self.length = len(self.data)
@ -146,7 +142,7 @@ class MsgDecode(object):
def decodeSimple(self, data): def decodeSimple(self, data):
"""Handle simple encoding""" """Handle simple encoding"""
data = data.decode('utf-8', 'backslashreplace') data = data.decode('utf-8', 'replace')
bodyPositionIndex = data.find('\nBody:') bodyPositionIndex = data.find('\nBody:')
if bodyPositionIndex > 1: if bodyPositionIndex > 1:
subject = data[8:bodyPositionIndex] subject = data[8:bodyPositionIndex]

View File

@ -723,9 +723,9 @@ class dispatcher(object):
if why.args[0] not in (ENOTCONN, EBADF): if why.args[0] not in (ENOTCONN, EBADF):
raise raise
# XXX unresolved
# cheap inheritance, used to pass all other attribute # cheap inheritance, used to pass all other attribute
# references to the underlying socket object. # references to the underlying socket object.
# XXX unresolved: is this can be removed safely or not?
#def __getattr__(self, attr): #def __getattr__(self, attr):
# try: # try:
# retattr = getattr(self.socket, attr) # retattr = getattr(self.socket, attr)

View File

@ -110,16 +110,15 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
b"error", b"version", b"verack"): b"error", b"version", b"verack"):
logger.error( logger.error(
'Received command %s before connection was fully' 'Received command %s before connection was fully'
' established, ignoring', self.command.decode('utf-8', 'replace')) ' established, ignoring', self.command)
self.invalid = True self.invalid = True
if not self.invalid: if not self.invalid:
try: try:
retval = getattr( retval = getattr(
self, "bm_command_" + self.command.decode('utf-8', 'replace').lower())() self, "bm_command_" + self.command.decode('utf-8', 'replace').lower())()
except AttributeError as err: except AttributeError:
logger.debug('command = {}, err = {}'.format(self.command.decode('utf-8', 'replace'), err))
# unimplemented command # unimplemented command
logger.debug('unimplemented command %s', self.command.decode('utf-8', 'replace')) logger.debug('unimplemented command %s', self.command)
except BMProtoInsufficientDataError: except BMProtoInsufficientDataError:
logger.debug('packet length too short, skipping') logger.debug('packet length too short, skipping')
except BMProtoExcessiveDataError: except BMProtoExcessiveDataError:
@ -142,8 +141,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
# broken read, ignore # broken read, ignore
pass pass
else: else:
logger.debug('Closing due to invalid command %s', self.command.decode('utf-8', 'replace')) logger.debug('Closing due to invalid command %s', self.command)
self.close_reason = "Invalid command %s" % self.command.decode('utf-8', 'replace') self.close_reason = "Invalid command %s" % self.command
self.set_state("close") self.set_state("close")
return False return False
if retval: if retval:

View File

@ -184,10 +184,7 @@ class TCPConnection(BMProto, TLSDispatcher):
try: try:
return s.endswith(tail) return s.endswith(tail)
except: except:
try: return s.decode('utf-8', 'replace').endswith(tail)
return s.decode('ascii').endswith(tail)
except UnicodeDecodeError:
return False
templist = [] templist = []
addrs = {} addrs = {}

View File

@ -92,6 +92,7 @@ class TLSDispatcher(AdvancedDispatcher):
ciphers=self.ciphers, do_handshake_on_connect=False) ciphers=self.ciphers, do_handshake_on_connect=False)
self.sslSocket.setblocking(0) self.sslSocket.setblocking(0)
self.want_read = self.want_write = True self.want_read = self.want_write = True
self.tlsPrepared = True
return False return False
@staticmethod @staticmethod
@ -139,7 +140,6 @@ class TLSDispatcher(AdvancedDispatcher):
if self.tlsStarted and not self.tlsDone and not self.write_buf: if self.tlsStarted and not self.tlsDone and not self.write_buf:
if not self.tlsPrepared: if not self.tlsPrepared:
self.do_tls_init() self.do_tls_init()
self.tlsPrepared = True
else: else:
self.tls_handshake() self.tls_handshake()
else: else:
@ -165,7 +165,6 @@ class TLSDispatcher(AdvancedDispatcher):
if self.tlsStarted and not self.tlsDone and not self.write_buf: if self.tlsStarted and not self.tlsDone and not self.write_buf:
if not self.tlsPrepared: if not self.tlsPrepared:
self.do_tls_init() self.do_tls_init()
self.tlsPrepared = True
else: else:
self.tls_handshake() self.tls_handshake()
else: else:

View File

@ -3,7 +3,6 @@ Track randomize ordered dict
""" """
from threading import RLock from threading import RLock
from time import time from time import time
from binascii import hexlify
try: try:
import helper_random import helper_random