No more arg() call on result of _translate()

This commit is contained in:
Dmitri Bogomolov 2018-02-22 15:09:40 +02:00
parent a83c75e647
commit 512bb41a03
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13
4 changed files with 109 additions and 81 deletions

View File

@ -3,19 +3,16 @@ import threading
import shared import shared
import hashlib import hashlib
import random import random
from struct import unpack, pack from struct import unpack
import sys
import string import string
from subprocess import call # used when the API must execute an outside program # used when the API must execute an outside program
from subprocess import call
import traceback import traceback
from binascii import hexlify from binascii import hexlify
from pyelliptic.openssl import OpenSSL
import highlevelcrypto import highlevelcrypto
from addresses import * from addresses import *
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
import helper_generic
from helper_generic import addDataPadding
import helper_bitcoin import helper_bitcoin
import helper_inbox import helper_inbox
import helper_msgcoding import helper_msgcoding
@ -29,6 +26,7 @@ import tr
from debug import logger from debug import logger
import l10n import l10n
class objectProcessor(threading.Thread): class objectProcessor(threading.Thread):
""" """
The objectProcessor thread, of which there is only one, receives network The objectProcessor thread, of which there is only one, receives network
@ -105,15 +103,20 @@ class objectProcessor(threading.Thread):
if data[readPosition:] in shared.ackdataForWhichImWatching: if data[readPosition:] in shared.ackdataForWhichImWatching:
logger.info('This object is an acknowledgement bound for me.') logger.info('This object is an acknowledgement bound for me.')
del shared.ackdataForWhichImWatching[data[readPosition:]] del shared.ackdataForWhichImWatching[data[readPosition:]]
sqlExecute('UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?', sqlExecute(
'ackreceived', 'UPDATE sent SET status=?, lastactiontime=? WHERE ackdata=?',
int(time.time()), 'ackreceived', int(time.time()), data[readPosition:])
data[readPosition:]) queues.UISignalQueue.put((
queues.UISignalQueue.put(('updateSentItemStatusByAckdata', (data[readPosition:], tr._translate("MainWindow",'Acknowledgement of the message received %1').arg(l10n.formatTimestamp())))) 'updateSentItemStatusByAckdata', (
data[readPosition:], tr._translate(
"MainWindow",
"Acknowledgement of the message received {0}"
).format(l10n.formatTimestamp()))
))
else: else:
logger.debug('This object is not an acknowledgement bound for me.') logger.debug('This object is not an acknowledgement bound for me.')
def processgetpubkey(self, data): def processgetpubkey(self, data):
if len(data) > 200: if len(data) > 200:
logger.info('getpubkey is abnormally long. Sanity check failed. Ignoring object.') logger.info('getpubkey is abnormally long. Sanity check failed. Ignoring object.')

View File

@ -34,6 +34,7 @@ from helper_sql import sqlQuery, sqlExecute
# This thread, of which there is only one, does the heavy lifting: # This thread, of which there is only one, does the heavy lifting:
# calculating POWs. # calculating POWs.
def sizeof_fmt(num, suffix='h/s'): def sizeof_fmt(num, suffix='h/s'):
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']: for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1000.0: if abs(num) < 1000.0:
@ -610,11 +611,9 @@ class singleWorker(threading.Thread, StoppableThread):
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', ( 'updateSentItemStatusByAckdata', (
ackdata, ackdata, tr._translate(
tr._translate( "MainWindow", "Broadcast sent on {0}"
"MainWindow", ).format(l10n.formatTimestamp()))
"Broadcast sent on %1"
).arg(l10n.formatTimestamp()))
)) ))
# Update the status of the message in the 'sent' table to have # Update the status of the message in the 'sent' table to have
@ -881,8 +880,8 @@ class singleWorker(threading.Thread, StoppableThread):
" device who requests that the" " device who requests that the"
" destination be included in the" " destination be included in the"
" message but this is disallowed in" " message but this is disallowed in"
" your settings. %1" " your settings. {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
# if the human changes their setting and then # if the human changes their setting and then
# sends another message or restarts their client, # sends another message or restarts their client,
@ -940,19 +939,16 @@ class singleWorker(threading.Thread, StoppableThread):
) )
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', ( 'updateSentItemStatusByAckdata', (
ackdata, ackdata, tr._translate(
tr._translate(
"MainWindow", "MainWindow",
"Doing work necessary to send message.\n" "Doing work necessary to send message.\n"
"Receiver\'s required difficulty: %1" "Receiver\'s required difficulty: {0} and {1}"
" and %2" ).format(
).arg(str(float( float(requiredAverageProofOfWorkNonceTrialsPerByte)
requiredAverageProofOfWorkNonceTrialsPerByte) / / defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
defaults.networkDefaultProofOfWorkNonceTrialsPerByte float(requiredPayloadLengthExtraBytes)
)).arg(str(float( / defaults.networkDefaultPayloadLengthExtraBytes))
requiredPayloadLengthExtraBytes) / ))
defaults.networkDefaultPayloadLengthExtraBytes
)))))
if status != 'forcepow': if status != 'forcepow':
if (requiredAverageProofOfWorkNonceTrialsPerByte if (requiredAverageProofOfWorkNonceTrialsPerByte
> BMConfigParser().getint( > BMConfigParser().getint(
@ -980,20 +976,18 @@ class singleWorker(threading.Thread, StoppableThread):
ackdata) ackdata)
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', ( 'updateSentItemStatusByAckdata', (
ackdata, ackdata, tr._translate(
tr._translate(
"MainWindow", "MainWindow",
"Problem: The work demanded by" "Problem: The work demanded by the"
" the recipient (%1 and %2) is" " recipient ({0} and {1}) is more"
" more difficult than you are" " difficult than you are willing"
" willing to do. %3" " to do. {2}"
).arg(str(float( ).format(
requiredAverageProofOfWorkNonceTrialsPerByte) float(requiredAverageProofOfWorkNonceTrialsPerByte)
/ defaults.networkDefaultProofOfWorkNonceTrialsPerByte / defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
)).arg(str(float( float(requiredPayloadLengthExtraBytes)
requiredPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes,
/ defaults.networkDefaultPayloadLengthExtraBytes l10n.formatTimestamp()))
)).arg(l10n.formatTimestamp()))
)) ))
continue continue
else: # if we are sending a message to ourselves or a chan.. else: # if we are sending a message to ourselves or a chan..
@ -1015,8 +1009,8 @@ class singleWorker(threading.Thread, StoppableThread):
" message to yourself or a chan but your" " message to yourself or a chan but your"
" encryption key could not be found in" " encryption key could not be found in"
" the keys.dat file. Could not encrypt" " the keys.dat file. Could not encrypt"
" message. %1" " message. {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
logger.error( logger.error(
'Error within sendMsg. Could not read the keys' 'Error within sendMsg. Could not read the keys'
@ -1123,8 +1117,7 @@ class singleWorker(threading.Thread, StoppableThread):
# We have assembled the data that will be encrypted. # We have assembled the data that will be encrypted.
try: try:
encrypted = highlevelcrypto.encrypt( encrypted = highlevelcrypto.encrypt(
payload, "04" + hexlify(pubEncryptionKeyBase256) payload, "04" + hexlify(pubEncryptionKeyBase256))
)
except: except:
sqlExecute( sqlExecute(
'''UPDATE sent SET status='badkey' WHERE ackdata=?''', '''UPDATE sent SET status='badkey' WHERE ackdata=?''',
@ -1132,12 +1125,11 @@ class singleWorker(threading.Thread, StoppableThread):
) )
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', ( 'updateSentItemStatusByAckdata', (
ackdata, ackdata, tr._translate(
tr._translate(
"MainWindow", "MainWindow",
"Problem: The recipient\'s encryption key is" "Problem: The recipient\'s encryption key is"
" no good. Could not encrypt message. %1" " no good. Could not encrypt message. {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
continue continue
@ -1202,22 +1194,19 @@ class singleWorker(threading.Thread, StoppableThread):
behaviorBitfield, protocol.BITFIELD_DOESACK): behaviorBitfield, protocol.BITFIELD_DOESACK):
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', ( 'updateSentItemStatusByAckdata', (
ackdata, ackdata, tr._translate(
tr._translate( "MainWindow", "Message sent. Sent at {0}"
"MainWindow", ).format(l10n.formatTimestamp()))
"Message sent. Sent at %1"
).arg(l10n.formatTimestamp()))
)) ))
else: else:
# not sending to a chan or one of my addresses # not sending to a chan or one of my addresses
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByAckdata', ( 'updateSentItemStatusByAckdata', (
ackdata, ackdata, tr._translate(
tr._translate(
"MainWindow", "MainWindow",
"Message sent. Waiting for acknowledgement." "Message sent. Waiting for acknowledgement."
" Sent on %1" " Sent on {0}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
logger.info( logger.info(
'Broadcasting inv for my msg(within sendmsg function): %s', 'Broadcasting inv for my msg(within sendmsg function): %s',
@ -1372,23 +1361,22 @@ class singleWorker(threading.Thread, StoppableThread):
int(time.time()), retryNumber + 1, sleeptill, toAddress) int(time.time()), retryNumber + 1, sleeptill, toAddress)
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateStatusBar', 'updateStatusBar', tr._translate(
tr._translate(
"MainWindow", "MainWindow",
"Broadcasting the public key request. This program will" "Broadcasting the public key request. This program will"
" auto-retry if they are offline.") " auto-retry if they are offline.")
)) ))
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateSentItemStatusByToAddress', ( 'updateSentItemStatusByToAddress', (
toAddress, toAddress, 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}"
).arg(l10n.formatTimestamp())) ).format(l10n.formatTimestamp()))
)) ))
def generateFullAckMessage(self, ackdata, toStreamNumber, TTL): def generateFullAckMessage(self, ackdata, toStreamNumber, TTL):
# It might be perfectly fine to just use the same TTL for # It might be perfectly fine to just use the same TTL for
# the ackdata that we use for the message. But I would rather # the ackdata that we use for the message. But I would rather
# it be more difficult for attackers to associate ackData with # it be more difficult for attackers to associate ackData with

View File

@ -28,7 +28,7 @@ import os
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
import defaults import defaults
import tr # translate import tr
# FIXME: from debug import logger crashes PyBitmessage due to a circular # FIXME: from debug import logger crashes PyBitmessage due to a circular
# dependency. The debug module will also override/disable logging.getLogger() # dependency. The debug module will also override/disable logging.getLogger()
@ -37,6 +37,7 @@ import logging as logger
configSection = "bitmessagesettings" configSection = "bitmessagesettings"
# Error thrown when the RPC call returns an error. # Error thrown when the RPC call returns an error.
class RPCError (Exception): class RPCError (Exception):
error = None error = None
@ -85,20 +86,25 @@ class namecoinConnection (object):
# string. If it doesn't contain a slash, id/ is prepended. We return # string. If it doesn't contain a slash, id/ is prepended. We return
# the result as (Error, Address) pair, where the Error is an error # the result as (Error, Address) pair, where the Error is an error
# message to display or None in case of success. # message to display or None in case of success.
def query (self, string): def query(self, string):
slashPos = string.find ("/") slashPos = string.find("/")
if slashPos < 0: if slashPos < 0:
string = "id/" + string string = "id/" + string
try: try:
if self.nmctype == "namecoind": if self.nmctype == "namecoind":
res = self.callRPC ("name_show", [string]) res = self.callRPC("name_show", [string])
res = res["value"] res = res["value"]
elif self.nmctype == "nmcontrol": elif self.nmctype == "nmcontrol":
res = self.callRPC ("data", ["getValue", string]) res = self.callRPC("data", ["getValue", string])
res = res["reply"] res = res["reply"]
if res == False: if res is False:
return (tr._translate("MainWindow",'The name %1 was not found.').arg(unicode(string)), None) return (
tr._translate(
"MainWindow", "The name {0} was not found."
).format(string),
None
)
else: else:
assert False assert False
except RPCError as exc: except RPCError as exc:
@ -107,16 +113,29 @@ class namecoinConnection (object):
errmsg = exc.error["message"] errmsg = exc.error["message"]
else: else:
errmsg = exc.error errmsg = exc.error
return (tr._translate("MainWindow",'The namecoin query failed (%1)').arg(unicode(errmsg)), None) return (
tr._translate(
"MainWindow", "The namecoin query failed ({0})"
).format(errmsg),
None
)
except Exception as exc: except Exception as exc:
logger.exception("Namecoin query exception") logger.exception("Namecoin query exception")
return (tr._translate("MainWindow",'The namecoin query failed.'), None) return (
tr._translate("MainWindow", "The namecoin query failed."),
None
)
try: try:
val = json.loads (res) val = json.loads(res)
except: except:
logger.exception("Namecoin query json exception") logger.exception("Namecoin query json exception")
return (tr._translate("MainWindow",'The name %1 has no valid JSON data.').arg(unicode(string)), None) return (
tr._translate(
"MainWindow", "The name {0} has no valid JSON data."
).format(string),
None
)
if "bitmessage" in val: if "bitmessage" in val:
if "name" in val: if "name" in val:
@ -124,7 +143,13 @@ class namecoinConnection (object):
else: else:
ret = val["bitmessage"] ret = val["bitmessage"]
return (None, ret) return (None, ret)
return (tr._translate("MainWindow",'The name %1 has no associated Bitmessage address.').arg(unicode(string)), None) return (
tr._translate(
"MainWindow",
"The name {0} has no associated Bitmessage address."
).format(string),
None
)
# Test the connection settings. This routine tries to query a "getinfo" # Test the connection settings. This routine tries to query a "getinfo"
# command, and builds either an error message or a success message with # command, and builds either an error message or a success message with
@ -146,7 +171,13 @@ class namecoinConnection (object):
versStr = "0.%d.%d" % (v1, v2) versStr = "0.%d.%d" % (v1, v2)
else: else:
versStr = "0.%d.%d.%d" % (v1, v2, v3) versStr = "0.%d.%d.%d" % (v1, v2, v3)
return ('success', tr._translate("MainWindow",'Success! Namecoind version %1 running.').arg(unicode(versStr)) ) return (
'success',
tr._translate(
"MainWindow",
"Success! Namecoind version {0} running."
).format(versStr)
)
elif self.nmctype == "nmcontrol": elif self.nmctype == "nmcontrol":
res = self.callRPC ("data", ["status"]) res = self.callRPC ("data", ["status"])

View File

@ -3,7 +3,7 @@
import httplib import httplib
from random import randint from random import randint
import socket import socket
from struct import unpack, pack from struct import unpack
import threading import threading
import time import time
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
@ -14,6 +14,7 @@ import shared
import state import state
import tr import tr
def createRequestXML(service, action, arguments=None): def createRequestXML(service, action, arguments=None):
from xml.dom.minidom import Document from xml.dom.minidom import Document
@ -230,7 +231,12 @@ class uPnPThread(threading.Thread, StoppableThread):
logger.debug("Found UPnP router at %s", ip) logger.debug("Found UPnP router at %s", ip)
self.routers.append(newRouter) self.routers.append(newRouter)
self.createPortMapping(newRouter) self.createPortMapping(newRouter)
queues.UISignalQueue.put(('updateStatusBar', tr._translate("MainWindow",'UPnP port mapping established on port %1').arg(str(self.extPort)))) queues.UISignalQueue.put((
'updateStatusBar', tr._translate(
"MainWindow",
"UPnP port mapping established on port {0}"
).format(self.extPort)
))
# retry connections so that the submitted port is refreshed # retry connections so that the submitted port is refreshed
with shared.alreadyAttemptedConnectionsListLock: with shared.alreadyAttemptedConnectionsListLock:
shared.alreadyAttemptedConnectionsList.clear() shared.alreadyAttemptedConnectionsList.clear()