Merge branch 'v0.6' into codeQ-2805

This commit is contained in:
coffeedogs 2018-06-12 00:24:48 +01:00 committed by GitHub
commit 6f5c261fb4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 1918 additions and 1030 deletions

View File

@ -1,4 +1,13 @@
"""Check dependendies and give recommendations about how to satisfy them""" """
Check dependendies and give recommendations about how to satisfy them
Limitations:
* Does not detect whether packages are already installed. Solving this requires writing more of a configuration
management system. Or we could switch to an existing one.
* Not fully PEP508 compliant. Not slightly. It makes bold assumptions about the simplicity of the contents of
EXTRAS_REQUIRE. This is fine because most developers do, too.
"""
from distutils.errors import CompileError from distutils.errors import CompileError
try: try:
@ -12,6 +21,29 @@ from importlib import import_module
import os import os
import sys import sys
from setup import EXTRAS_REQUIRE
PROJECT_ROOT = os.path.abspath('..')
sys.path.insert(0, PROJECT_ROOT)
# OS-specific dependencies for optional components listed in EXTRAS_REQUIRE
EXTRAS_REQUIRE_DEPS = {
# The values from setup.EXTRAS_REQUIRE
'python_prctl': {
# The packages needed for this requirement, by OS
"OpenBSD": [""],
"FreeBSD": [""],
"Debian": ["libcap-dev"],
"Ubuntu": [""],
"Ubuntu 12": [""],
"openSUSE": [""],
"Fedora": [""],
"Guix": [""],
"Gentoo": [""],
},
}
PACKAGE_MANAGER = { PACKAGE_MANAGER = {
"OpenBSD": "pkg_add", "OpenBSD": "pkg_add",
"FreeBSD": "pkg install", "FreeBSD": "pkg install",
@ -199,6 +231,7 @@ if not compiler:
if prereqs: if prereqs:
mandatory = list(x for x in prereqs if "optional" not in PACKAGES[x] or not PACKAGES[x]["optional"]) mandatory = list(x for x in prereqs if "optional" not in PACKAGES[x] or not PACKAGES[x]["optional"])
optional = list(x for x in prereqs if "optional" in PACKAGES[x] and PACKAGES[x]["optional"]) optional = list(x for x in prereqs if "optional" in PACKAGES[x] and PACKAGES[x]["optional"])
if mandatory: if mandatory:
print "Missing mandatory dependencies: %s" % (" ".join(mandatory)) print "Missing mandatory dependencies: %s" % (" ".join(mandatory))
if optional: if optional:
@ -206,6 +239,28 @@ if prereqs:
for package in optional: for package in optional:
print PACKAGES[package].get('description') print PACKAGES[package].get('description')
# Install the system dependencies of optional extras_require components
OPSYS = detectOS()
CMD = PACKAGE_MANAGER[OPSYS] if OPSYS in PACKAGE_MANAGER else 'UNKNOWN_INSTALLER'
for lhs, rhs in EXTRAS_REQUIRE.items():
if rhs and any([
EXTRAS_REQUIRE_DEPS[x][OPSYS]
for x in rhs
if x in EXTRAS_REQUIRE_DEPS
]):
rhs_cmd = ''.join([
CMD,
' ',
' '.join([
''. join([
xx for xx in EXTRAS_REQUIRE_DEPS[x][OPSYS]
])
for x in rhs
if x in EXTRAS_REQUIRE_DEPS
]),
])
print "Optional dependency `pip install .[{}]` would require `{}` to be run as root".format(lhs, rhs_cmd)
if (not compiler or prereqs) and detectOS() in PACKAGE_MANAGER: if (not compiler or prereqs) and detectOS() in PACKAGE_MANAGER:
print "You can install the missing dependencies by running, as root:" print "You can install the missing dependencies by running, as root:"
if not compiler: if not compiler:

View File

@ -1 +0,0 @@
python_prctl

View File

@ -1,10 +1,17 @@
# Since there is overlap in the violations that the different tools check for, it makes sense to quiesce some warnings
# in some tools if those warnings in other tools are preferred. This avoids the need to add duplicate lint warnings.
[pycodestyle] [pycodestyle]
max-line-length = 119 max-line-length = 119
[flake8] [flake8]
max-line-length = 119 max-line-length = 119
ignore = E722 ignore = E722,F841
# E722: pylint is preferred for bare-except
# F841: pylint is preferred for unused-variable
# pylint # pylint honours the [MESSAGES CONTROL] section
[MESSAGES CONTROL] [MESSAGES CONTROL]
disable=invalid-name,bare-except disable=invalid-name,bare-except,broad-except
# invalid-name: needs fixing during a large, project-wide refactor
# bare-except,broad-except: Need fixing once thorough testing is easier

View File

@ -1,13 +1,24 @@
#!/usr/bin/env python2.7 #!/usr/bin/env python2.7
import os import os
import sys
import shutil import shutil
from setuptools import setup, Extension from setuptools import setup, Extension
from setuptools.command.install import install from setuptools.command.install import install
from src.version import softwareVersion from src.version import softwareVersion
EXTRAS_REQUIRE = {
'gir': ['pygobject'],
'notify2': ['notify2'],
'pyopencl': ['pyopencl'],
'prctl': ['python_prctl'], # Named threads
'qrcode': ['qrcode'],
'sound;platform_system=="Windows"': ['winsound']
}
class InstallCmd(install): class InstallCmd(install):
def run(self): def run(self):
# prepare icons directories # prepare icons directories
@ -78,13 +89,7 @@ if __name__ == "__main__":
# TODO: add keywords # TODO: add keywords
#keywords='', #keywords='',
install_requires=installRequires, install_requires=installRequires,
extras_require={ extras_require=EXTRAS_REQUIRE,
'gir': ['pygobject'],
'qrcode': ['qrcode'],
'pyopencl': ['pyopencl'],
'notify2': ['notify2'],
'sound;platform_system=="Windows"': ['winsound']
},
classifiers=[ classifiers=[
"License :: OSI Approved :: MIT License" "License :: OSI Approved :: MIT License"
"Operating System :: OS Independent", "Operating System :: OS Independent",

View File

@ -263,7 +263,7 @@ class Main:
'bitmessagesettings', 'sendoutgoingconnections'): 'bitmessagesettings', 'sendoutgoingconnections'):
state.dandelion = 0 state.dandelion = 0
helper_bootstrap.knownNodes() knownnodes.readKnownNodes()
# Not needed if objproc is disabled # Not needed if objproc is disabled
if state.enableObjProc: if state.enableObjProc:

View File

@ -1,63 +1,78 @@
from debug import logger # pylint: disable=too-many-lines,broad-except,too-many-instance-attributes,global-statement,too-few-public-methods
# pylint: disable=too-many-statements,too-many-branches,attribute-defined-outside-init,too-many-arguments,no-member
# pylint: disable=unused-argument,no-self-use,too-many-locals,unused-variable,too-many-nested-blocks
# pylint: disable=too-many-return-statements,protected-access,super-init-not-called,non-parent-init-called
"""
Initialise the QT interface
"""
import hashlib
import locale
import os
import random
import string
import sys import sys
import textwrap
import time
from datetime import datetime, timedelta
import debug
from debug import logger
try: try:
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from PyQt4.QtNetwork import QLocalSocket, QLocalServer from PyQt4.QtNetwork import QLocalSocket, QLocalServer
except Exception as err: except ImportError:
logmsg = 'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can download it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for \'PyQt Download\' (without quotes).' logmsg = (
'PyBitmessage requires PyQt unless you want to run it as a daemon and interact with it using the API. You can'
' download it from http://www.riverbankcomputing.com/software/pyqt/download or by searching Google for '
'\'PyQt Download\' (without quotes).'
)
logger.critical(logmsg, exc_info=True) logger.critical(logmsg, exc_info=True)
sys.exit() sys.exit()
from tr import _translate
from addresses import decodeAddress, addBMIfNotPresent from sqlite3 import register_adapter # pylint: disable=wrong-import-order
import shared
from bitmessageui import Ui_MainWindow
from bmconfigparser import BMConfigParser
import defaults import defaults
from namecoin import namecoinConnection
from messageview import MessageView
from migrationwizard import Ui_MigrationWizard
from foldertree import (
AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget,
MessageList_AddressWidget, MessageList_SubjectWidget,
Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress)
from settings import Ui_settingsDialog
import settingsmixin
import support
import locale
import time
import os
import hashlib
from pyelliptic.openssl import OpenSSL
import textwrap
import debug
import random
from sqlite3 import register_adapter
import string
from datetime import datetime, timedelta
from helper_ackPayload import genAckPayload
from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
import helper_search import helper_search
import knownnodes
import l10n import l10n
import openclpow import openclpow
from utils import str_broadcast_subscribers, avatarize
from account import (
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount,
GatewayAccount, MailchuckAccount, AccountColor)
import dialogs
from helper_generic import powQueueSize
from network.stats import pendingDownload, pendingUpload
from uisignaler import UISignaler
import knownnodes
import paths import paths
from proofofwork import getPowType
import queues import queues
import shared
import shutdown import shutdown
import state import state
from statusbar import BMStatusBar import upnp
from bitmessageqt import sound, support, dialogs
from bitmessageqt.foldertree import (
AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget, MessageList_AddressWidget,
MessageList_SubjectWidget, Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress,
)
from bitmessageqt.account import (
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount, GatewayAccount, MailchuckAccount, AccountColor,
)
from bitmessageqt.bitmessageui import Ui_MainWindow, settingsmixin
from bitmessageqt.messageview import MessageView
from bitmessageqt.migrationwizard import Ui_MigrationWizard
from bitmessageqt.settings import Ui_settingsDialog
from bitmessageqt.utils import str_broadcast_subscribers, avatarize
from bitmessageqt.uisignaler import UISignaler
from bitmessageqt.statusbar import BMStatusBar
from addresses import decodeAddress, addBMIfNotPresent
from bmconfigparser import BMConfigParser
from namecoin import namecoinConnection
from helper_ackPayload import genAckPayload
from helper_generic import powQueueSize
from helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
from network.stats import pendingDownload, pendingUpload
from network.asyncore_pollchoose import set_rates from network.asyncore_pollchoose import set_rates
import sound from proofofwork import getPowType
from tr import _translate
try: try:
@ -66,8 +81,15 @@ except ImportError:
get_plugins = False get_plugins = False
qmytranslator = None
qsystranslator = None
def change_translation(newlocale): def change_translation(newlocale):
"""Change a translation to a new locale"""
global qmytranslator, qsystranslator global qmytranslator, qsystranslator
try: try:
if not qmytranslator.isEmpty(): if not qmytranslator.isEmpty():
QtGui.QApplication.removeTranslator(qmytranslator) QtGui.QApplication.removeTranslator(qmytranslator)
@ -80,15 +102,16 @@ def change_translation(newlocale):
pass pass
qmytranslator = QtCore.QTranslator() qmytranslator = QtCore.QTranslator()
translationpath = os.path.join (paths.codePath(), 'translations', 'bitmessage_' + newlocale) translationpath = os.path.join(paths.codePath(), 'translations', 'bitmessage_' + newlocale)
qmytranslator.load(translationpath) qmytranslator.load(translationpath)
QtGui.QApplication.installTranslator(qmytranslator) QtGui.QApplication.installTranslator(qmytranslator)
qsystranslator = QtCore.QTranslator() qsystranslator = QtCore.QTranslator()
if paths.frozen: if paths.frozen:
translationpath = os.path.join (paths.codePath(), 'translations', 'qt_' + newlocale) translationpath = os.path.join(paths.codePath(), 'translations', 'qt_' + newlocale)
else: else:
translationpath = os.path.join (str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale) translationpath = os.path.join(str(QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)), 'qt_' + newlocale)
qsystranslator.load(translationpath) qsystranslator.load(translationpath)
QtGui.QApplication.installTranslator(qsystranslator) QtGui.QApplication.installTranslator(qsystranslator)
@ -109,7 +132,8 @@ def change_translation(newlocale):
logger.error("Failed to set locale to %s", lang, exc_info=True) logger.error("Failed to set locale to %s", lang, exc_info=True)
class MyForm(settingsmixin.SMainWindow): class MyForm(settingsmixin.SMainWindow): # pylint: disable=too-many-public-methods
"""TBC"""
# the last time that a message arrival sound was played # the last time that a message arrival sound was played
lastSoundTime = datetime.now() - timedelta(days=1) lastSoundTime = datetime.now() - timedelta(days=1)
@ -121,6 +145,8 @@ class MyForm(settingsmixin.SMainWindow):
REPLY_TYPE_CHAN = 1 REPLY_TYPE_CHAN = 1
def init_file_menu(self): def init_file_menu(self):
"""Initialise the file menu"""
QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL(
"triggered()"), self.quit) "triggered()"), self.quit)
QtCore.QObject.connect(self.ui.actionNetworkSwitch, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.actionNetworkSwitch, QtCore.SIGNAL(
@ -135,9 +161,10 @@ class MyForm(settingsmixin.SMainWindow):
QtCore.SIGNAL( QtCore.SIGNAL(
"triggered()"), "triggered()"),
self.click_actionRegenerateDeterministicAddresses) self.click_actionRegenerateDeterministicAddresses)
QtCore.QObject.connect(self.ui.pushButtonAddChan, QtCore.SIGNAL( QtCore.QObject.connect(
"clicked()"), self.ui.pushButtonAddChan,
self.click_actionJoinChan) # also used for creating chans. QtCore.SIGNAL("clicked()"),
self.click_actionJoinChan) # also used for creating chans.
QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.pushButtonNewAddress, QtCore.SIGNAL(
"clicked()"), self.click_NewAddressDialog) "clicked()"), self.click_NewAddressDialog)
QtCore.QObject.connect(self.ui.pushButtonAddAddressBook, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.pushButtonAddAddressBook, QtCore.SIGNAL(
@ -162,7 +189,8 @@ class MyForm(settingsmixin.SMainWindow):
"triggered()"), self.click_actionHelp) "triggered()"), self.click_actionHelp)
def init_inbox_popup_menu(self, connectSignal=True): def init_inbox_popup_menu(self, connectSignal=True):
# Popup menu for the Inbox tab """Popup menu for the Inbox tab"""
self.ui.inboxContextMenuToolbar = QtGui.QToolBar() self.ui.inboxContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionReply = self.ui.inboxContextMenuToolbar.addAction(_translate( self.actionReply = self.ui.inboxContextMenuToolbar.addAction(_translate(
@ -199,24 +227,28 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tableWidgetInbox.setContextMenuPolicy( self.ui.tableWidgetInbox.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetInbox, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.tableWidgetInbox,
self.on_context_menuInbox) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox)
self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy( self.ui.tableWidgetInboxSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetInboxSubscriptions, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.tableWidgetInboxSubscriptions,
self.on_context_menuInbox) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox)
self.ui.tableWidgetInboxChans.setContextMenuPolicy( self.ui.tableWidgetInboxChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetInboxChans, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.tableWidgetInboxChans,
self.on_context_menuInbox) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuInbox)
def init_identities_popup_menu(self, connectSignal=True): def init_identities_popup_menu(self, connectSignal=True):
# Popup menu for the Your Identities tab """Popup menu for the Your Identities tab"""
self.ui.addressContextMenuToolbarYourIdentities = QtGui.QToolBar() self.ui.addressContextMenuToolbarYourIdentities = QtGui.QToolBar()
# Actions # Actions
self.actionNewYourIdentities = self.ui.addressContextMenuToolbarYourIdentities.addAction(_translate( self.actionNewYourIdentities = self.ui.addressContextMenuToolbarYourIdentities.addAction(_translate(
@ -251,9 +283,10 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetYourIdentities.setContextMenuPolicy( self.ui.treeWidgetYourIdentities.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.treeWidgetYourIdentities, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.treeWidgetYourIdentities,
self.on_context_menuYourIdentities) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuYourIdentities)
# load all gui.menu plugins with prefix 'address' # load all gui.menu plugins with prefix 'address'
self.menu_plugins = {'address': []} self.menu_plugins = {'address': []}
@ -268,7 +301,8 @@ class MyForm(settingsmixin.SMainWindow):
)) ))
def init_chan_popup_menu(self, connectSignal=True): def init_chan_popup_menu(self, connectSignal=True):
# Popup menu for the Channels tab """Popup menu for the Channels tab"""
self.ui.addressContextMenuToolbar = QtGui.QToolBar() self.ui.addressContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionNew = self.ui.addressContextMenuToolbar.addAction(_translate( self.actionNew = self.ui.addressContextMenuToolbar.addAction(_translate(
@ -298,12 +332,14 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetChans.setContextMenuPolicy( self.ui.treeWidgetChans.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.treeWidgetChans, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.treeWidgetChans,
self.on_context_menuChan) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuChan)
def init_addressbook_popup_menu(self, connectSignal=True): def init_addressbook_popup_menu(self, connectSignal=True):
# Popup menu for the Address Book page """Popup menu for the Address Book page"""
self.ui.addressBookContextMenuToolbar = QtGui.QToolBar() self.ui.addressBookContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionAddressBookSend = self.ui.addressBookContextMenuToolbar.addAction( self.actionAddressBookSend = self.ui.addressBookContextMenuToolbar.addAction(
@ -335,12 +371,14 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tableWidgetAddressBook.setContextMenuPolicy( self.ui.tableWidgetAddressBook.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.tableWidgetAddressBook, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.tableWidgetAddressBook,
self.on_context_menuAddressBook) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuAddressBook)
def init_subscriptions_popup_menu(self, connectSignal=True): def init_subscriptions_popup_menu(self, connectSignal=True):
# Popup menu for the Subscriptions page """Popup menu for the Subscriptions page"""
self.ui.subscriptionsContextMenuToolbar = QtGui.QToolBar() self.ui.subscriptionsContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionsubscriptionsNew = self.ui.subscriptionsContextMenuToolbar.addAction( self.actionsubscriptionsNew = self.ui.subscriptionsContextMenuToolbar.addAction(
@ -363,12 +401,14 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetSubscriptions.setContextMenuPolicy( self.ui.treeWidgetSubscriptions.setContextMenuPolicy(
QtCore.Qt.CustomContextMenu) QtCore.Qt.CustomContextMenu)
if connectSignal: if connectSignal:
self.connect(self.ui.treeWidgetSubscriptions, QtCore.SIGNAL( self.connect(
'customContextMenuRequested(const QPoint&)'), self.ui.treeWidgetSubscriptions,
self.on_context_menuSubscriptions) QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'),
self.on_context_menuSubscriptions)
def init_sent_popup_menu(self, connectSignal=True): def init_sent_popup_menu(self, connectSignal=True):
# Popup menu for the Sent page """Popup menu for the Sent page"""
self.ui.sentContextMenuToolbar = QtGui.QToolBar() self.ui.sentContextMenuToolbar = QtGui.QToolBar()
# Actions # Actions
self.actionTrashSentMessage = self.ui.sentContextMenuToolbar.addAction( self.actionTrashSentMessage = self.ui.sentContextMenuToolbar.addAction(
@ -381,11 +421,10 @@ class MyForm(settingsmixin.SMainWindow):
self.actionForceSend = self.ui.sentContextMenuToolbar.addAction( self.actionForceSend = self.ui.sentContextMenuToolbar.addAction(
_translate( _translate(
"MainWindow", "Force send"), self.on_action_ForceSend) "MainWindow", "Force send"), self.on_action_ForceSend)
# self.popMenuSent = QtGui.QMenu( self )
# self.popMenuSent.addAction( self.actionSentClipboard )
# self.popMenuSent.addAction( self.actionTrashSentMessage )
def rerenderTabTreeSubscriptions(self): def rerenderTabTreeSubscriptions(self):
"""TBC"""
treeWidget = self.ui.treeWidgetSubscriptions treeWidget = self.ui.treeWidgetSubscriptions
folders = Ui_FolderWidget.folderWeight.keys() folders = Ui_FolderWidget.folderWeight.keys()
folders.remove("new") folders.remove("new")
@ -399,13 +438,12 @@ class MyForm(settingsmixin.SMainWindow):
db = getSortedSubscriptions(True) db = getSortedSubscriptions(True)
for address in db: for address in db:
for folder in folders: for folder in folders:
if not folder in db[address]: if folder not in db[address]:
db[address][folder] = {} db[address][folder] = {}
if treeWidget.isSortingEnabled(): if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False) treeWidget.setSortingEnabled(False)
widgets = {}
i = 0 i = 0
while i < treeWidget.topLevelItemCount(): while i < treeWidget.topLevelItemCount():
widget = treeWidget.topLevelItem(i) widget = treeWidget.topLevelItem(i)
@ -414,7 +452,7 @@ class MyForm(settingsmixin.SMainWindow):
else: else:
toAddress = None toAddress = None
if not toAddress in db: if toAddress not in db:
treeWidget.takeTopLevelItem(i) treeWidget.takeTopLevelItem(i)
# no increment # no increment
continue continue
@ -433,7 +471,7 @@ class MyForm(settingsmixin.SMainWindow):
j += 1 j += 1
# add missing folders # add missing folders
if len(db[toAddress]) > 0: if db[toAddress]:
j = 0 j = 0
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].iteritems():
try: try:
@ -447,7 +485,11 @@ class MyForm(settingsmixin.SMainWindow):
i = 0 i = 0
for toAddress in db: for toAddress in db:
widget = Ui_SubscriptionWidget(treeWidget, i, toAddress, db[toAddress]["inbox"]['count'], db[toAddress]["inbox"]['label'], db[toAddress]["inbox"]['enabled']) widget = Ui_SubscriptionWidget(
treeWidget, i, toAddress,
db[toAddress]["inbox"]['count'],
db[toAddress]["inbox"]['label'],
db[toAddress]["inbox"]['enabled'])
j = 0 j = 0
unread = 0 unread = 0
for folder in folders: for folder in folders:
@ -462,14 +504,19 @@ class MyForm(settingsmixin.SMainWindow):
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
def rerenderTabTreeMessages(self): def rerenderTabTreeMessages(self):
"""TBC"""
self.rerenderTabTree('messages') self.rerenderTabTree('messages')
def rerenderTabTreeChans(self): def rerenderTabTreeChans(self):
"""TBC"""
self.rerenderTabTree('chan') self.rerenderTabTree('chan')
def rerenderTabTree(self, tab): def rerenderTabTree(self, tab):
"""TBC"""
if tab == 'messages': if tab == 'messages':
treeWidget = self.ui.treeWidgetYourIdentities treeWidget = self.ui.treeWidgetYourIdentities
elif tab == 'chan': elif tab == 'chan':
@ -489,8 +536,6 @@ class MyForm(settingsmixin.SMainWindow):
toAddress, 'enabled') toAddress, 'enabled')
isChan = BMConfigParser().safeGetBoolean( isChan = BMConfigParser().safeGetBoolean(
toAddress, 'chan') toAddress, 'chan')
isMaillinglist = BMConfigParser().safeGetBoolean(
toAddress, 'mailinglist')
if treeWidget == self.ui.treeWidgetYourIdentities: if treeWidget == self.ui.treeWidgetYourIdentities:
if isChan: if isChan:
@ -507,7 +552,8 @@ class MyForm(settingsmixin.SMainWindow):
# get number of (unread) messages # get number of (unread) messages
total = 0 total = 0
queryreturn = sqlQuery('SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder') queryreturn = sqlQuery(
'SELECT toaddress, folder, count(msgid) as cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder')
for row in queryreturn: for row in queryreturn:
toaddress, folder, cnt = row toaddress, folder, cnt = row
total += cnt total += cnt
@ -524,7 +570,6 @@ class MyForm(settingsmixin.SMainWindow):
if treeWidget.isSortingEnabled(): if treeWidget.isSortingEnabled():
treeWidget.setSortingEnabled(False) treeWidget.setSortingEnabled(False)
widgets = {}
i = 0 i = 0
while i < treeWidget.topLevelItemCount(): while i < treeWidget.topLevelItemCount():
widget = treeWidget.topLevelItem(i) widget = treeWidget.topLevelItem(i)
@ -533,7 +578,7 @@ class MyForm(settingsmixin.SMainWindow):
else: else:
toAddress = None toAddress = None
if not toAddress in db: if toAddress not in db:
treeWidget.takeTopLevelItem(i) treeWidget.takeTopLevelItem(i)
# no increment # no increment
continue continue
@ -553,7 +598,7 @@ class MyForm(settingsmixin.SMainWindow):
j += 1 j += 1
# add missing folders # add missing folders
if len(db[toAddress]) > 0: if db[toAddress]:
j = 0 j = 0
for f, c in db[toAddress].iteritems(): for f, c in db[toAddress].iteritems():
if toAddress is not None and tab == 'messages' and folder == "new": if toAddress is not None and tab == 'messages' and folder == "new":
@ -584,6 +629,8 @@ class MyForm(settingsmixin.SMainWindow):
treeWidget.setSortingEnabled(True) treeWidget.setSortingEnabled(True)
def __init__(self, parent=None): def __init__(self, parent=None):
"""TBC"""
QtGui.QWidget.__init__(self, parent) QtGui.QWidget.__init__(self, parent)
self.ui = Ui_MainWindow() self.ui = Ui_MainWindow()
self.ui.setupUi(self) self.ui.setupUi(self)
@ -591,12 +638,14 @@ class MyForm(settingsmixin.SMainWindow):
# Ask the user if we may delete their old version 1 addresses if they # Ask the user if we may delete their old version 1 addresses if they
# have any. # have any.
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
status, addressVersionNumber, streamNumber, hash = decodeAddress( status, addressVersionNumber, streamNumber, addressHash = decodeAddress(
addressInKeysFile) addressInKeysFile)
if addressVersionNumber == 1: if addressVersionNumber == 1:
displayMsg = _translate( displayMsg = _translate(
"MainWindow", "One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer supported. " "MainWindow",
+ "May we delete it now?").arg(addressInKeysFile) 'One of your addresses, %1, is an old version 1 address. Version 1 addresses are no longer '
'supported. May we delete it now?'
).arg(addressInKeysFile)
reply = QtGui.QMessageBox.question( reply = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
@ -606,11 +655,13 @@ class MyForm(settingsmixin.SMainWindow):
# Configure Bitmessage to start on startup (or remove the # Configure Bitmessage to start on startup (or remove the
# configuration) based on the setting in the keys.dat file # configuration) based on the setting in the keys.dat file
if 'win32' in sys.platform or 'win64' in sys.platform: if 'win32' in sys.platform or 'win64' in sys.platform:
# Auto-startup for Windows # Auto-startup for Windows
RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat) self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat)
self.settings.remove( # In case the user moves the program and the registry entry is no longer
"PyBitmessage") # In case the user moves the program and the registry entry is no longer valid, this will delete the old registry entry. # valid, this will delete the old registry entry.
self.settings.remove("PyBitmessage")
if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'): if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'):
self.settings.setValue("PyBitmessage", sys.argv[0]) self.settings.setValue("PyBitmessage", sys.argv[0])
elif 'darwin' in sys.platform: elif 'darwin' in sys.platform:
@ -724,7 +775,7 @@ class MyForm(settingsmixin.SMainWindow):
self.unreadCount = 0 self.unreadCount = 0
# Set the icon sizes for the identicons # Set the icon sizes for the identicons
identicon_size = 3*7 identicon_size = 3 * 7
self.ui.tableWidgetInbox.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.tableWidgetInbox.setIconSize(QtCore.QSize(identicon_size, identicon_size))
self.ui.treeWidgetChans.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.treeWidgetChans.setIconSize(QtCore.QSize(identicon_size, identicon_size))
self.ui.treeWidgetYourIdentities.setIconSize(QtCore.QSize(identicon_size, identicon_size)) self.ui.treeWidgetYourIdentities.setIconSize(QtCore.QSize(identicon_size, identicon_size))
@ -740,10 +791,15 @@ class MyForm(settingsmixin.SMainWindow):
"updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByToAddress) "updateSentItemStatusByToAddress(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByToAddress)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByAckdata) "updateSentItemStatusByAckdata(PyQt_PyObject,PyQt_PyObject)"), self.updateSentItemStatusByAckdata)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(
"displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewInboxMessage) self.UISignalThread, QtCore.SIGNAL(
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( "displayNewInboxMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"),
"displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)"), self.displayNewSentMessage) self.displayNewInboxMessage)
QtCore.QObject.connect(
self.UISignalThread, QtCore.SIGNAL(
("displayNewSentMessage(PyQt_PyObject,PyQt_PyObject,PyQt_PyObject,"
"PyQt_PyObject,PyQt_PyObject,PyQt_PyObject)")),
self.displayNewSentMessage)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
"setStatusIcon(PyQt_PyObject)"), self.setStatusIcon) "setStatusIcon(PyQt_PyObject)"), self.setStatusIcon)
QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL( QtCore.QObject.connect(self.UISignalThread, QtCore.SIGNAL(
@ -787,11 +843,11 @@ class MyForm(settingsmixin.SMainWindow):
# Put the TTL slider in the correct spot # Put the TTL slider in the correct spot
TTL = BMConfigParser().getint('bitmessagesettings', 'ttl') TTL = BMConfigParser().getint('bitmessagesettings', 'ttl')
if TTL < 3600: # an hour if TTL < 3600: # an hour
TTL = 3600 TTL = 3600
elif TTL > 28*24*60*60: # 28 days elif TTL > 28 * 24 * 60 * 60: # 28 days
TTL = 28*24*60*60 TTL = 28 * 24 * 60 * 60
self.ui.horizontalSliderTTL.setSliderPosition((TTL - 3600) ** (1/3.199)) self.ui.horizontalSliderTTL.setSliderPosition((TTL - 3600) ** (1 / 3.199))
self.updateHumanFriendlyTTLDescription(TTL) self.updateHumanFriendlyTTLDescription(TTL)
QtCore.QObject.connect(self.ui.horizontalSliderTTL, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.horizontalSliderTTL, QtCore.SIGNAL(
@ -805,20 +861,24 @@ class MyForm(settingsmixin.SMainWindow):
# Hide the 'Fetch Namecoin ID' button if we can't. # Hide the 'Fetch Namecoin ID' button if we can't.
if BMConfigParser().safeGetBoolean( if BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect' 'bitmessagesettings', 'dontconnect'
) or self.namecoin.test()[0] == 'failed': ) or self.namecoin.test()[0] == 'failed':
logger.warning( logger.warning(
'There was a problem testing for a Namecoin daemon. Hiding the' 'There was a problem testing for a Namecoin daemon. Hiding the'
' Fetch Namecoin ID button') ' Fetch Namecoin ID button')
self.ui.pushButtonFetchNamecoinID.hide() self.ui.pushButtonFetchNamecoinID.hide()
def updateTTL(self, sliderPosition): def updateTTL(self, sliderPosition):
"""TBC"""
TTL = int(sliderPosition ** 3.199 + 3600) TTL = int(sliderPosition ** 3.199 + 3600)
self.updateHumanFriendlyTTLDescription(TTL) self.updateHumanFriendlyTTLDescription(TTL)
BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL)) BMConfigParser().set('bitmessagesettings', 'ttl', str(TTL))
BMConfigParser().save() BMConfigParser().save()
def updateHumanFriendlyTTLDescription(self, TTL): def updateHumanFriendlyTTLDescription(self, TTL):
numberOfHours = int(round(TTL / (60*60))) """TBC"""
numberOfHours = int(round(TTL / (60 * 60)))
font = QtGui.QFont() font = QtGui.QFont()
stylesheet = "" stylesheet = ""
@ -827,19 +887,28 @@ class MyForm(settingsmixin.SMainWindow):
_translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfHours) + _translate("MainWindow", "%n hour(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfHours) +
", " + ", " +
_translate("MainWindow", "not recommended for chans", None, QtCore.QCoreApplication.CodecForTr) _translate("MainWindow", "not recommended for chans", None, QtCore.QCoreApplication.CodecForTr)
) )
stylesheet = "QLabel { color : red; }" stylesheet = "QLabel { color : red; }"
font.setBold(True) font.setBold(True)
else: else:
numberOfDays = int(round(TTL / (24*60*60))) numberOfDays = int(round(TTL / (24 * 60 * 60)))
self.ui.labelHumanFriendlyTTLDescription.setText(_translate("MainWindow", "%n day(s)", None, QtCore.QCoreApplication.CodecForTr, numberOfDays)) self.ui.labelHumanFriendlyTTLDescription.setText(
_translate(
"MainWindow",
"%n day(s)",
None,
QtCore.QCoreApplication.CodecForTr,
numberOfDays))
font.setBold(False) font.setBold(False)
self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet) self.ui.labelHumanFriendlyTTLDescription.setStyleSheet(stylesheet)
self.ui.labelHumanFriendlyTTLDescription.setFont(font) self.ui.labelHumanFriendlyTTLDescription.setFont(font)
# Show or hide the application window after clicking an item within the
# tray icon or, on Windows, the try icon itself.
def appIndicatorShowOrHideWindow(self): def appIndicatorShowOrHideWindow(self):
"""
Show or hide the application window after clicking an item within the tray icon or, on Windows,
the try icon itself.
"""
if not self.actionShow.isChecked(): if not self.actionShow.isChecked():
self.hide() self.hide()
else: else:
@ -849,16 +918,18 @@ class MyForm(settingsmixin.SMainWindow):
self.raise_() self.raise_()
self.activateWindow() self.activateWindow()
# show the application window
def appIndicatorShow(self): def appIndicatorShow(self):
"""show the application window"""
if self.actionShow is None: if self.actionShow is None:
return return
if not self.actionShow.isChecked(): if not self.actionShow.isChecked():
self.actionShow.setChecked(True) self.actionShow.setChecked(True)
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
# unchecks the show item on the application indicator
def appIndicatorHide(self): def appIndicatorHide(self):
"""unchecks the show item on the application indicator"""
if self.actionShow is None: if self.actionShow is None:
return return
if self.actionShow.isChecked(): if self.actionShow.isChecked():
@ -866,25 +937,16 @@ class MyForm(settingsmixin.SMainWindow):
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
def appIndicatorSwitchQuietMode(self): def appIndicatorSwitchQuietMode(self):
"""TBC"""
BMConfigParser().set( BMConfigParser().set(
'bitmessagesettings', 'showtraynotifications', 'bitmessagesettings', 'showtraynotifications',
str(not self.actionQuiet.isChecked()) str(not self.actionQuiet.isChecked())
) )
# application indicator show or hide
"""# application indicator show or hide
def appIndicatorShowBitmessage(self):
#if self.actionShow == None:
# return
print self.actionShow.isChecked()
if not self.actionShow.isChecked():
self.hide()
#self.setWindowState(self.windowState() & QtCore.Qt.WindowMinimized)
else:
self.appIndicatorShowOrHideWindow()"""
# Show the program window and select inbox tab
def appIndicatorInbox(self, item=None): def appIndicatorInbox(self, item=None):
"""Show the program window and select inbox tab"""
self.appIndicatorShow() self.appIndicatorShow()
# select inbox # select inbox
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
@ -900,22 +962,24 @@ class MyForm(settingsmixin.SMainWindow):
else: else:
self.ui.tableWidgetInbox.setCurrentCell(0, 0) self.ui.tableWidgetInbox.setCurrentCell(0, 0)
# Show the program window and select send tab
def appIndicatorSend(self): def appIndicatorSend(self):
"""Show the program window and select send tab"""
self.appIndicatorShow() self.appIndicatorShow()
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.send) self.ui.tabWidget.indexOf(self.ui.send)
) )
# Show the program window and select subscriptions tab
def appIndicatorSubscribe(self): def appIndicatorSubscribe(self):
"""Show the program window and select subscriptions tab"""
self.appIndicatorShow() self.appIndicatorShow()
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.subscriptions) self.ui.tabWidget.indexOf(self.ui.subscriptions)
) )
# Show the program window and select channels tab
def appIndicatorChannel(self): def appIndicatorChannel(self):
"""Show the program window and select channels tab"""
self.appIndicatorShow() self.appIndicatorShow()
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.chans) self.ui.tabWidget.indexOf(self.ui.chans)
@ -961,9 +1025,12 @@ class MyForm(settingsmixin.SMainWindow):
for col in (0, 1, 2): for col in (0, 1, 2):
related.item(rrow, col).setUnread(not status) related.item(rrow, col).setUnread(not status)
def propagateUnreadCount(self, address = None, folder = "inbox", widget = None, type = 1): def propagateUnreadCount(self, address=None, folder="inbox", widget=None, type_arg=1):
"""TBC"""
widgets = [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] widgets = [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans]
queryReturn = sqlQuery("SELECT toaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder") queryReturn = sqlQuery(
"SELECT toaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 GROUP BY toaddress, folder")
totalUnread = {} totalUnread = {}
normalUnread = {} normalUnread = {}
for row in queryReturn: for row in queryReturn:
@ -975,7 +1042,10 @@ class MyForm(settingsmixin.SMainWindow):
totalUnread[row[1]] += row[2] totalUnread[row[1]] += row[2]
else: else:
totalUnread[row[1]] = row[2] totalUnread[row[1]] = row[2]
queryReturn = sqlQuery("SELECT fromaddress, folder, COUNT(msgid) AS cnt FROM inbox WHERE read = 0 AND toaddress = ? GROUP BY fromaddress, folder", str_broadcast_subscribers) queryReturn = sqlQuery(
"SELECT fromaddress, folder, COUNT(msgid) AS cnt FROM inbox "
"WHERE read = 0 AND toaddress = ? GROUP BY fromaddress, folder",
str_broadcast_subscribers)
broadcastsUnread = {} broadcastsUnread = {}
for row in queryReturn: for row in queryReturn:
broadcastsUnread[row[0]] = {} broadcastsUnread[row[0]] = {}
@ -1007,7 +1077,8 @@ class MyForm(settingsmixin.SMainWindow):
if addressItem.type == AccountMixin.ALL and folderName in totalUnread: if addressItem.type == AccountMixin.ALL and folderName in totalUnread:
newCount = totalUnread[folderName] newCount = totalUnread[folderName]
elif addressItem.type == AccountMixin.SUBSCRIPTION: elif addressItem.type == AccountMixin.SUBSCRIPTION:
if addressItem.address in broadcastsUnread and folderName in broadcastsUnread[addressItem.address]: if addressItem.address in broadcastsUnread and folderName in broadcastsUnread[
addressItem.address]:
newCount = broadcastsUnread[addressItem.address][folderName] newCount = broadcastsUnread[addressItem.address][folderName]
elif addressItem.address in normalUnread and folderName in normalUnread[addressItem.address]: elif addressItem.address in normalUnread and folderName in normalUnread[addressItem.address]:
newCount = normalUnread[addressItem.address][folderName] newCount = normalUnread[addressItem.address][folderName]
@ -1015,16 +1086,20 @@ class MyForm(settingsmixin.SMainWindow):
folderItem.setUnreadCount(newCount) folderItem.setUnreadCount(newCount)
def addMessageListItem(self, tableWidget, items): def addMessageListItem(self, tableWidget, items):
"""TBC"""
sortingEnabled = tableWidget.isSortingEnabled() sortingEnabled = tableWidget.isSortingEnabled()
if sortingEnabled: if sortingEnabled:
tableWidget.setSortingEnabled(False) tableWidget.setSortingEnabled(False)
tableWidget.insertRow(0) tableWidget.insertRow(0)
for i in range(len(items)): for i, _ in enumerate(items):
tableWidget.setItem(0, i, items[i]) tableWidget.setItem(0, i, items[i])
if sortingEnabled: if sortingEnabled:
tableWidget.setSortingEnabled(True) tableWidget.setSortingEnabled(True)
def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime): def addMessageListItemSent(self, tableWidget, toAddress, fromAddress, subject, status, ackdata, lastactiontime):
"""TBC"""
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
if acct is None: if acct is None:
acct = BMAccount(fromAddress) acct = BMAccount(fromAddress)
@ -1063,14 +1138,19 @@ class MyForm(settingsmixin.SMainWindow):
statusText = _translate( statusText = _translate(
"MainWindow", "Doing work necessary to send broadcast.") "MainWindow", "Doing work necessary to send broadcast.")
elif status == 'broadcastsent': elif status == 'broadcastsent':
statusText = _translate("MainWindow", "Broadcast on %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow", "Broadcast on %1").arg(
l10n.formatTimestamp(lastactiontime))
elif status == 'toodifficult': elif status == 'toodifficult':
statusText = _translate("MainWindow", "Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow",
"Problem: The work demanded by the recipient is more difficult than you are willing to do. %1").arg(
l10n.formatTimestamp(lastactiontime))
elif status == 'badkey': elif status == 'badkey':
statusText = _translate("MainWindow", "Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg( statusText = _translate(
l10n.formatTimestamp(lastactiontime)) "MainWindow",
"Problem: The recipient\'s encryption key is no good. Could not encrypt message. %1").arg(
l10n.formatTimestamp(lastactiontime))
elif status == 'forcepow': elif status == 'forcepow':
statusText = _translate( statusText = _translate(
"MainWindow", "Forced difficulty override. Send should start soon.") "MainWindow", "Forced difficulty override. Send should start soon.")
@ -1088,6 +1168,8 @@ class MyForm(settingsmixin.SMainWindow):
return acct return acct
def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read): def addMessageListItemInbox(self, tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read):
"""TBC"""
font = QtGui.QFont() font = QtGui.QFont()
font.setBold(True) font.setBold(True)
if toAddress == str_broadcast_subscribers: if toAddress == str_broadcast_subscribers:
@ -1101,7 +1183,7 @@ class MyForm(settingsmixin.SMainWindow):
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
items = [] items = []
#to # to
MessageList_AddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read) MessageList_AddressWidget(items, toAddress, unicode(acct.toLabel, 'utf-8'), not read)
# from # from
MessageList_AddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read) MessageList_AddressWidget(items, fromAddress, unicode(acct.fromLabel, 'utf-8'), not read)
@ -1120,8 +1202,9 @@ class MyForm(settingsmixin.SMainWindow):
self.addMessageListItem(tableWidget, items) self.addMessageListItem(tableWidget, items)
return acct return acct
# Load Sent items from database
def loadSent(self, tableWidget, account, where="", what=""): def loadSent(self, tableWidget, account, where="", what=""):
"""Load Sent items from database"""
if tableWidget == self.ui.tableWidgetInboxSubscriptions: if tableWidget == self.ui.tableWidgetInboxSubscriptions:
tableWidget.setColumnHidden(0, True) tableWidget.setColumnHidden(0, True)
tableWidget.setColumnHidden(1, False) tableWidget.setColumnHidden(1, False)
@ -1153,8 +1236,9 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None)) tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Sent", None))
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
# Load messages from database file def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly=False):
def loadMessagelist(self, tableWidget, account, folder="inbox", where="", what="", unreadOnly = False): """Load messages from database file"""
if folder == 'sent': if folder == 'sent':
self.loadSent(tableWidget, account, where, what) self.loadSent(tableWidget, account, where, what)
return return
@ -1178,7 +1262,8 @@ class MyForm(settingsmixin.SMainWindow):
for row in queryreturn: for row in queryreturn:
msgfolder, msgid, toAddress, fromAddress, subject, received, read = row msgfolder, msgid, toAddress, fromAddress, subject, received, read = row
self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress, fromAddress, subject, received, read) self.addMessageListItemInbox(tableWidget, msgfolder, msgid, toAddress,
fromAddress, subject, received, read)
tableWidget.horizontalHeader().setSortIndicator( tableWidget.horizontalHeader().setSortIndicator(
3, QtCore.Qt.DescendingOrder) 3, QtCore.Qt.DescendingOrder)
@ -1187,9 +1272,10 @@ class MyForm(settingsmixin.SMainWindow):
tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None)) tableWidget.horizontalHeaderItem(3).setText(_translate("MainWindow", "Received", None))
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
# create application indicator def appIndicatorInit(self, this_app):
def appIndicatorInit(self, app): """create application indicator"""
self.initTrayIcon("can-icon-24px-red.png", app)
self.initTrayIcon("can-icon-24px-red.png", this_app)
traySignal = "activated(QSystemTrayIcon::ActivationReason)" traySignal = "activated(QSystemTrayIcon::ActivationReason)"
QtCore.QObject.connect(self.tray, QtCore.SIGNAL( QtCore.QObject.connect(self.tray, QtCore.SIGNAL(
traySignal), self.__icon_activated) traySignal), self.__icon_activated)
@ -1211,7 +1297,7 @@ class MyForm(settingsmixin.SMainWindow):
self.actionShow.setChecked(not BMConfigParser().getboolean( self.actionShow.setChecked(not BMConfigParser().getboolean(
'bitmessagesettings', 'startintray')) 'bitmessagesettings', 'startintray'))
self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow) self.actionShow.triggered.connect(self.appIndicatorShowOrHideWindow)
if not sys.platform[0:3] == 'win': if sys.platform[0:3] != 'win':
m.addAction(self.actionShow) m.addAction(self.actionShow)
# quiet mode # quiet mode
@ -1252,8 +1338,9 @@ class MyForm(settingsmixin.SMainWindow):
self.tray.setContextMenu(m) self.tray.setContextMenu(m)
self.tray.show() self.tray.show()
# returns the number of unread messages and subscriptions
def getUnread(self): def getUnread(self):
"""returns the number of unread messages and subscriptions"""
counters = [0, 0] counters = [0, 0]
queryreturn = sqlQuery(''' queryreturn = sqlQuery('''
@ -1268,12 +1355,15 @@ class MyForm(settingsmixin.SMainWindow):
return counters return counters
# play a sound def playSound(self, category, label): # pylint: disable=inconsistent-return-statements
def playSound(self, category, label): """play a sound"""
# filename of the sound to be played # filename of the sound to be played
soundFilename = None soundFilename = None
def _choose_ext(basename): def _choose_ext(basename): # pylint: disable=inconsistent-return-statements
"""TBC"""
for ext in sound.extensions: for ext in sound.extensions:
if os.path.isfile(os.extsep.join([basename, ext])): if os.path.isfile(os.extsep.join([basename, ext])):
return os.extsep + ext return os.extsep + ext
@ -1295,24 +1385,23 @@ class MyForm(settingsmixin.SMainWindow):
# elapsed time since the last sound was played # elapsed time since the last sound was played
dt = datetime.now() - self.lastSoundTime dt = datetime.now() - self.lastSoundTime
# suppress sounds which are more frequent than the threshold # suppress sounds which are more frequent than the threshold
if dt.total_seconds() < self.maxSoundFrequencySec: if not dt.total_seconds() < self.maxSoundFrequencySec:
return
# the sound is for an address which exists in the address book # the sound is for an address which exists in the address book
if category is sound.SOUND_KNOWN: if category is sound.SOUND_KNOWN:
soundFilename = state.appdata + 'sounds/known' soundFilename = state.appdata + 'sounds/known'
# the sound is for an unknown address # the sound is for an unknown address
elif category is sound.SOUND_UNKNOWN: elif category is sound.SOUND_UNKNOWN:
soundFilename = state.appdata + 'sounds/unknown' soundFilename = state.appdata + 'sounds/unknown'
# initial connection sound # initial connection sound
elif category is sound.SOUND_CONNECTED: elif category is sound.SOUND_CONNECTED:
soundFilename = state.appdata + 'sounds/connected' soundFilename = state.appdata + 'sounds/connected'
# disconnected sound # disconnected sound
elif category is sound.SOUND_DISCONNECTED: elif category is sound.SOUND_DISCONNECTED:
soundFilename = state.appdata + 'sounds/disconnected' soundFilename = state.appdata + 'sounds/disconnected'
# sound when the connection status becomes green # sound when the connection status becomes green
elif category is sound.SOUND_CONNECTION_GREEN: elif category is sound.SOUND_CONNECTION_GREEN:
soundFilename = state.appdata + 'sounds/green' soundFilename = state.appdata + 'sounds/green'
if soundFilename is None: if soundFilename is None:
logger.warning("Probably wrong category number in playSound()") logger.warning("Probably wrong category number in playSound()")
@ -1336,13 +1425,14 @@ class MyForm(settingsmixin.SMainWindow):
self._player(soundFilename) self._player(soundFilename)
# Adapters and converters for QT <-> sqlite
def sqlInit(self): def sqlInit(self):
"""Adapters and converters for QT <-> sqlite"""
register_adapter(QtCore.QByteArray, str) register_adapter(QtCore.QByteArray, str)
# Try init the distro specific appindicator,
# for example the Ubuntu MessagingMenu
def indicatorInit(self): def indicatorInit(self):
""" Try init the distro specific appindicator, for example the Ubuntu MessagingMenu"""
def _noop_update(*args, **kwargs): def _noop_update(*args, **kwargs):
pass pass
@ -1352,8 +1442,9 @@ class MyForm(settingsmixin.SMainWindow):
logger.warning("No indicator plugin found") logger.warning("No indicator plugin found")
self.indicatorUpdate = _noop_update self.indicatorUpdate = _noop_update
# initialise the message notifier
def notifierInit(self): def notifierInit(self):
"""initialise the message notifier"""
def _simple_notify( def _simple_notify(
title, subtitle, category, label=None, icon=None): title, subtitle, category, label=None, icon=None):
self.tray.showMessage(title, subtitle, 1, 2000) self.tray.showMessage(title, subtitle, 1, 2000)
@ -1383,27 +1474,34 @@ class MyForm(settingsmixin.SMainWindow):
def notifierShow( def notifierShow(
self, title, subtitle, category, label=None, icon=None): self, title, subtitle, category, label=None, icon=None):
"""TBC"""
self.playSound(category, label) self.playSound(category, label)
self._notifier( self._notifier(
unicode(title), unicode(subtitle), category, label, icon) unicode(title), unicode(subtitle), category, label, icon)
# tree
def treeWidgetKeyPressEvent(self, event): def treeWidgetKeyPressEvent(self, event):
"""tree"""
return self.handleKeyPress(event, self.getCurrentTreeWidget()) return self.handleKeyPress(event, self.getCurrentTreeWidget())
# inbox / sent
def tableWidgetKeyPressEvent(self, event): def tableWidgetKeyPressEvent(self, event):
"""inbox / sent"""
return self.handleKeyPress(event, self.getCurrentMessagelist()) return self.handleKeyPress(event, self.getCurrentMessagelist())
# messageview
def textEditKeyPressEvent(self, event): def textEditKeyPressEvent(self, event):
"""messageview"""
return self.handleKeyPress(event, self.getCurrentMessageTextedit()) return self.handleKeyPress(event, self.getCurrentMessageTextedit())
def handleKeyPress(self, event, focus = None): def handleKeyPress(self, event, focus=None): # pylint: disable=inconsistent-return-statements
"""TBC"""
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
if event.key() == QtCore.Qt.Key_Delete: if event.key() == QtCore.Qt.Key_Delete:
if isinstance (focus, MessageView) or isinstance(focus, QtGui.QTableWidget): if isinstance(focus, (MessageView, QtGui.QTableWidget)):
if folder == "sent": if folder == "sent":
self.on_action_SentTrash() self.on_action_SentTrash()
else: else:
@ -1439,60 +1537,116 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.lineEditTo.setFocus() self.ui.lineEditTo.setFocus()
event.ignore() event.ignore()
elif event.key() == QtCore.Qt.Key_F: elif event.key() == QtCore.Qt.Key_F:
searchline = self.getCurrentSearchLine(retObj = True) searchline = self.getCurrentSearchLine(retObj=True)
if searchline: if searchline:
searchline.setFocus() searchline.setFocus()
event.ignore() event.ignore()
if not event.isAccepted(): if not event.isAccepted():
return return
if isinstance (focus, MessageView): if isinstance(focus, MessageView):
return MessageView.keyPressEvent(focus, event) return MessageView.keyPressEvent(focus, event)
elif isinstance (focus, QtGui.QTableWidget): elif isinstance(focus, QtGui.QTableWidget):
return QtGui.QTableWidget.keyPressEvent(focus, event) return QtGui.QTableWidget.keyPressEvent(focus, event)
elif isinstance (focus, QtGui.QTreeWidget): elif isinstance(focus, QtGui.QTreeWidget):
return QtGui.QTreeWidget.keyPressEvent(focus, event) return QtGui.QTreeWidget.keyPressEvent(focus, event)
# menu button 'manage keys'
def click_actionManageKeys(self): def click_actionManageKeys(self):
"""menu button 'manage keys'"""
if 'darwin' in sys.platform or 'linux' in sys.platform: if 'darwin' in sys.platform or 'linux' in sys.platform:
if state.appdata == '': if state.appdata == '':
# reply = QtGui.QMessageBox.information(self, 'keys.dat?','You # reply = QtGui.QMessageBox.information(self, 'keys.dat?','You
# may manage your keys by editing the keys.dat file stored in # may manage your keys by editing the keys.dat file stored in
# the same directory as this program. It is important that you # the same directory as this program. It is important that you
# back up this file.', QMessageBox.Ok) # back up this file.', QMessageBox.Ok)
reply = QtGui.QMessageBox.information(self, 'keys.dat?', _translate( reply = QtGui.QMessageBox.information(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file."), QtGui.QMessageBox.Ok) self,
'keys.dat?',
_translate(
"MainWindow",
("You may manage your keys by editing the keys.dat file stored in the same directory as this "
"program. It is important that you back up this file.")),
QtGui.QMessageBox.Ok)
else: else:
QtGui.QMessageBox.information(self, 'keys.dat?', _translate( QtGui.QMessageBox.information(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file.").arg(state.appdata), QtGui.QMessageBox.Ok) self,
'keys.dat?',
_translate(
"MainWindow",
("You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important "
"that you back up this file.")).arg(
state.appdata),
QtGui.QMessageBox.Ok)
elif sys.platform == 'win32' or sys.platform == 'win64': elif sys.platform == 'win32' or sys.platform == 'win64':
if state.appdata == '': if state.appdata == '':
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( reply = QtGui.QMessageBox.question(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in the same directory as this program. It is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self,
_translate(
"MainWindow",
"Open keys.dat?"),
_translate(
"MainWindow",
("You may manage your keys by editing the keys.dat file stored in the same directory as this "
"program. It is important that you back up this file. Would you like to open the file now? "
"(Be sure to close Bitmessage before making any changes.)")),
QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
else: else:
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Open keys.dat?"), _translate( reply = QtGui.QMessageBox.question(
"MainWindow", "You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important that you back up this file. Would you like to open the file now? (Be sure to close Bitmessage before making any changes.)").arg(state.appdata), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self,
_translate(
"MainWindow",
"Open keys.dat?"),
_translate(
"MainWindow",
("You may manage your keys by editing the keys.dat file stored in\n %1 \nIt is important "
"that you back up this file. Would you like to open the file now? (Be sure to close "
"Bitmessage before making any changes.)")).arg(
state.appdata),
QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
shared.openKeysFile() shared.openKeysFile()
# menu button 'delete all treshed messages'
def click_actionDeleteAllTrashedMessages(self): def click_actionDeleteAllTrashedMessages(self):
if QtGui.QMessageBox.question(self, _translate("MainWindow", "Delete trash?"), _translate("MainWindow", "Are you sure you want to delete all trashed messages?"), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) == QtGui.QMessageBox.No: """menu button 'delete all treshed messages'"""
if QtGui.QMessageBox.question(
self,
_translate(
"MainWindow",
"Delete trash?"),
_translate(
"MainWindow",
"Are you sure you want to delete all trashed messages?"),
QtGui.QMessageBox.Yes,
QtGui.QMessageBox.No) == QtGui.QMessageBox.No:
return return
sqlStoredProcedure('deleteandvacuume') sqlStoredProcedure('deleteandvacuume')
self.rerenderTabTreeMessages() self.rerenderTabTreeMessages()
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
if self.getCurrentFolder(self.ui.treeWidgetYourIdentities) == "trash": if self.getCurrentFolder(self.ui.treeWidgetYourIdentities) == "trash":
self.loadMessagelist(self.ui.tableWidgetInbox, self.getCurrentAccount(self.ui.treeWidgetYourIdentities), "trash") self.loadMessagelist(
self.ui.tableWidgetInbox, self.getCurrentAccount(
self.ui.treeWidgetYourIdentities), "trash")
elif self.getCurrentFolder(self.ui.treeWidgetSubscriptions) == "trash": elif self.getCurrentFolder(self.ui.treeWidgetSubscriptions) == "trash":
self.loadMessagelist(self.ui.tableWidgetInboxSubscriptions, self.getCurrentAccount(self.ui.treeWidgetSubscriptions), "trash") self.loadMessagelist(
self.ui.tableWidgetInboxSubscriptions,
self.getCurrentAccount(
self.ui.treeWidgetSubscriptions),
"trash")
elif self.getCurrentFolder(self.ui.treeWidgetChans) == "trash": elif self.getCurrentFolder(self.ui.treeWidgetChans) == "trash":
self.loadMessagelist(self.ui.tableWidgetInboxChans, self.getCurrentAccount(self.ui.treeWidgetChans), "trash") self.loadMessagelist(
self.ui.tableWidgetInboxChans,
self.getCurrentAccount(
self.ui.treeWidgetChans),
"trash")
# menu button 'regenerate deterministic addresses'
def click_actionRegenerateDeterministicAddresses(self): def click_actionRegenerateDeterministicAddresses(self):
"""menu button 'regenerate deterministic addresses'"""
dialog = dialogs.RegenerateAddressesDialog(self) dialog = dialogs.RegenerateAddressesDialog(self)
if dialog.exec_(): if dialog.exec_():
if dialog.lineEditPassphrase.text() == "": if dialog.lineEditPassphrase.text() == "":
@ -1539,11 +1693,14 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tabWidget.indexOf(self.ui.chans) self.ui.tabWidget.indexOf(self.ui.chans)
) )
# opens 'join chan' dialog
def click_actionJoinChan(self): def click_actionJoinChan(self):
"""opens 'join chan' dialog"""
dialogs.NewChanDialog(self) dialogs.NewChanDialog(self)
def showConnectDialog(self): def showConnectDialog(self):
"""TBC"""
dialog = dialogs.ConnectDialog(self) dialog = dialogs.ConnectDialog(self)
if dialog.exec_(): if dialog.exec_():
if dialog.radioButtonConnectNow.isChecked(): if dialog.radioButtonConnectNow.isChecked():
@ -1556,6 +1713,8 @@ class MyForm(settingsmixin.SMainWindow):
self._firstrun = False self._firstrun = False
def showMigrationWizard(self, level): def showMigrationWizard(self, level):
"""TBC"""
self.migrationWizardInstance = Ui_MigrationWizard(["a"]) self.migrationWizardInstance = Ui_MigrationWizard(["a"])
if self.migrationWizardInstance.exec_(): if self.migrationWizardInstance.exec_():
pass pass
@ -1563,6 +1722,8 @@ class MyForm(settingsmixin.SMainWindow):
pass pass
def changeEvent(self, event): def changeEvent(self, event):
"""TBC"""
if event.type() == QtCore.QEvent.LanguageChange: if event.type() == QtCore.QEvent.LanguageChange:
self.ui.retranslateUi(self) self.ui.retranslateUi(self)
self.init_inbox_popup_menu(False) self.init_inbox_popup_menu(False)
@ -1574,15 +1735,17 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.blackwhitelist.init_blacklist_popup_menu(False) self.ui.blackwhitelist.init_blacklist_popup_menu(False)
if event.type() == QtCore.QEvent.WindowStateChange: if event.type() == QtCore.QEvent.WindowStateChange:
if self.windowState() & QtCore.Qt.WindowMinimized: if self.windowState() & QtCore.Qt.WindowMinimized:
if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray') and not 'darwin' in sys.platform: if BMConfigParser().getboolean('bitmessagesettings', 'minimizetotray'):
QtCore.QTimer.singleShot(0, self.appIndicatorHide) if 'darwin' not in sys.platform:
QtCore.QTimer.singleShot(0, self.appIndicatorHide)
elif event.oldState() & QtCore.Qt.WindowMinimized: elif event.oldState() & QtCore.Qt.WindowMinimized:
# The window state has just been changed to # The window state has just been changed to
# Normal/Maximised/FullScreen # Normal/Maximised/FullScreen
pass pass
# QtGui.QWidget.changeEvent(self, event)
def __icon_activated(self, reason): def __icon_activated(self, reason):
"""TBC"""
if reason == QtGui.QSystemTrayIcon.Trigger: if reason == QtGui.QSystemTrayIcon.Trigger:
self.actionShow.setChecked(not self.actionShow.isChecked()) self.actionShow.setChecked(not self.actionShow.isChecked())
self.appIndicatorShowOrHideWindow() self.appIndicatorShowOrHideWindow()
@ -1591,7 +1754,8 @@ class MyForm(settingsmixin.SMainWindow):
connected = False connected = False
def setStatusIcon(self, color): def setStatusIcon(self, color):
# print 'setting status icon color' """Set the status icon"""
_notifications_enabled = not BMConfigParser().getboolean( _notifications_enabled = not BMConfigParser().getboolean(
'bitmessagesettings', 'hidetrayconnectionnotifications') 'bitmessagesettings', 'hidetrayconnectionnotifications')
if color == 'red': if color == 'red':
@ -1605,7 +1769,7 @@ class MyForm(settingsmixin.SMainWindow):
_translate("MainWindow", "Connection lost"), _translate("MainWindow", "Connection lost"),
sound.SOUND_DISCONNECTED) sound.SOUND_DISCONNECTED)
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and \ if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and \
BMConfigParser().get('bitmessagesettings', 'socksproxytype') == "none": BMConfigParser().get('bitmessagesettings', 'socksproxytype') == "none":
self.updateStatusBar( self.updateStatusBar(
_translate( _translate(
"MainWindow", "MainWindow",
@ -1619,7 +1783,9 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Not Connected")) "MainWindow", "Not Connected"))
self.setTrayIconFile("can-icon-24px-red.png") self.setTrayIconFile("can-icon-24px-red.png")
if color == 'yellow': if color == 'yellow':
if self.statusbar.currentMessage() == 'Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.': if self.statusbar.currentMessage() == ('Warning: You are currently not connected. Bitmessage will do '
'the work necessary to send the message but it won\'t send until '
'you connect.'):
self.statusbar.clearMessage() self.statusbar.clearMessage()
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/yellowicon.png")) QtGui.QIcon(":/newPrefix/images/yellowicon.png"))
@ -1637,7 +1803,9 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Connected")) "MainWindow", "Connected"))
self.setTrayIconFile("can-icon-24px-yellow.png") self.setTrayIconFile("can-icon-24px-yellow.png")
if color == 'green': if color == 'green':
if self.statusbar.currentMessage() == 'Warning: You are currently not connected. Bitmessage will do the work necessary to send the message but it won\'t send until you connect.': if self.statusbar.currentMessage() == ('Warning: You are currently not connected. Bitmessage will do the '
'work necessary to send the message but it won\'t send until you '
'connect.'):
self.statusbar.clearMessage() self.statusbar.clearMessage()
self.pushButtonStatusIcon.setIcon( self.pushButtonStatusIcon.setIcon(
QtGui.QIcon(":/newPrefix/images/greenicon.png")) QtGui.QIcon(":/newPrefix/images/greenicon.png"))
@ -1654,17 +1822,23 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Connected")) "MainWindow", "Connected"))
self.setTrayIconFile("can-icon-24px-green.png") self.setTrayIconFile("can-icon-24px-green.png")
def initTrayIcon(self, iconFileName, app): def initTrayIcon(self, iconFileName, this_app):
"""TBC"""
self.currentTrayIconFileName = iconFileName self.currentTrayIconFileName = iconFileName
self.tray = QtGui.QSystemTrayIcon( self.tray = QtGui.QSystemTrayIcon(
self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), app) self.calcTrayIcon(iconFileName, self.findInboxUnreadCount()), this_app)
def setTrayIconFile(self, iconFileName): def setTrayIconFile(self, iconFileName):
"""TBC"""
self.currentTrayIconFileName = iconFileName self.currentTrayIconFileName = iconFileName
self.drawTrayIcon(iconFileName, self.findInboxUnreadCount()) self.drawTrayIcon(iconFileName, self.findInboxUnreadCount())
def calcTrayIcon(self, iconFileName, inboxUnreadCount): def calcTrayIcon(self, iconFileName, inboxUnreadCount):
pixmap = QtGui.QPixmap(":/newPrefix/images/"+iconFileName) """TBC"""
pixmap = QtGui.QPixmap(":/newPrefix/images/" + iconFileName)
if inboxUnreadCount > 0: if inboxUnreadCount > 0:
# choose font and calculate font parameters # choose font and calculate font parameters
fontName = "Lucida" fontName = "Lucida"
@ -1676,7 +1850,7 @@ class MyForm(settingsmixin.SMainWindow):
rect = fontMetrics.boundingRect(txt) rect = fontMetrics.boundingRect(txt)
# margins that we add in the top-right corner # margins that we add in the top-right corner
marginX = 2 marginX = 2
marginY = 0 # it looks like -2 is also ok due to the error of metric marginY = 0 # it looks like -2 is also ok due to the error of metric
# if it renders too wide we need to change it to a plus symbol # if it renders too wide we need to change it to a plus symbol
if rect.width() > 20: if rect.width() > 20:
txt = "+" txt = "+"
@ -1690,14 +1864,18 @@ class MyForm(settingsmixin.SMainWindow):
painter.setPen( painter.setPen(
QtGui.QPen(QtGui.QColor(255, 0, 0), QtCore.Qt.SolidPattern)) QtGui.QPen(QtGui.QColor(255, 0, 0), QtCore.Qt.SolidPattern))
painter.setFont(font) painter.setFont(font)
painter.drawText(24-rect.right()-marginX, -rect.top()+marginY, txt) painter.drawText(24 - rect.right() - marginX, -rect.top() + marginY, txt)
painter.end() painter.end()
return QtGui.QIcon(pixmap) return QtGui.QIcon(pixmap)
def drawTrayIcon(self, iconFileName, inboxUnreadCount): def drawTrayIcon(self, iconFileName, inboxUnreadCount):
"""TBC"""
self.tray.setIcon(self.calcTrayIcon(iconFileName, inboxUnreadCount)) self.tray.setIcon(self.calcTrayIcon(iconFileName, inboxUnreadCount))
def changedInboxUnread(self, row=None): def changedInboxUnread(self, row=None):
"""TBC"""
self.drawTrayIcon( self.drawTrayIcon(
self.currentTrayIconFileName, self.findInboxUnreadCount()) self.currentTrayIconFileName, self.findInboxUnreadCount())
self.rerenderTabTreeMessages() self.rerenderTabTreeMessages()
@ -1705,6 +1883,8 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
def findInboxUnreadCount(self, count=None): def findInboxUnreadCount(self, count=None):
"""TBC"""
if count is None: if count is None:
queryreturn = sqlQuery('''SELECT count(*) from inbox WHERE folder='inbox' and read=0''') queryreturn = sqlQuery('''SELECT count(*) from inbox WHERE folder='inbox' and read=0''')
cnt = 0 cnt = 0
@ -1716,11 +1896,14 @@ class MyForm(settingsmixin.SMainWindow):
return self.unreadCount return self.unreadCount
def updateSentItemStatusByToAddress(self, toAddress, textToDisplay): def updateSentItemStatusByToAddress(self, toAddress, textToDisplay):
"""TBC"""
for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]:
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue continue
if treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress: if treeWidget in [self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress:
continue continue
for i in range(sent.rowCount()): for i in range(sent.rowCount()):
@ -1729,7 +1912,7 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setToolTip(textToDisplay) sent.item(i, 3).setToolTip(textToDisplay)
try: try:
newlinePosition = textToDisplay.indexOf('\n') newlinePosition = textToDisplay.indexOf('\n')
except: # If someone misses adding a "_translate" to a string before passing it to this function, this function won't receive a qstring which will cause an exception. except: # If no "_translate" appended to string before passing in, there's no qstring
newlinePosition = 0 newlinePosition = 0
if newlinePosition > 1: if newlinePosition > 1:
sent.item(i, 3).setText( sent.item(i, 3).setText(
@ -1738,7 +1921,9 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setText(textToDisplay) sent.item(i, 3).setText(textToDisplay)
def updateSentItemStatusByAckdata(self, ackdata, textToDisplay): def updateSentItemStatusByAckdata(self, ackdata, textToDisplay):
if type(ackdata) is str: """TBC"""
if isinstance(ackdata, str):
ackdata = QtCore.QByteArray(ackdata) ackdata = QtCore.QByteArray(ackdata)
for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]: for sent in [self.ui.tableWidgetInbox, self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxChans]:
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
@ -1755,7 +1940,7 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setToolTip(textToDisplay) sent.item(i, 3).setToolTip(textToDisplay)
try: try:
newlinePosition = textToDisplay.indexOf('\n') newlinePosition = textToDisplay.indexOf('\n')
except: # If someone misses adding a "_translate" to a string before passing it to this function, this function won't receive a qstring which will cause an exception. except: # If no "_translate" appended to string before passing in, there's no qstring
newlinePosition = 0 newlinePosition = 0
if newlinePosition > 1: if newlinePosition > 1:
sent.item(i, 3).setText( sent.item(i, 3).setText(
@ -1764,50 +1949,80 @@ class MyForm(settingsmixin.SMainWindow):
sent.item(i, 3).setText(textToDisplay) sent.item(i, 3).setText(textToDisplay)
def removeInboxRowByMsgid(self, msgid): # msgid and inventoryHash are the same thing def removeInboxRowByMsgid(self, msgid): # msgid and inventoryHash are the same thing
"""TBC"""
for inbox in ([ for inbox in ([
self.ui.tableWidgetInbox, self.ui.tableWidgetInbox,
self.ui.tableWidgetInboxSubscriptions, self.ui.tableWidgetInboxSubscriptions,
self.ui.tableWidgetInboxChans]): self.ui.tableWidgetInboxChans]):
for i in range(inbox.rowCount()): for i in range(inbox.rowCount()):
if msgid == str(inbox.item(i, 3).data(QtCore.Qt.UserRole).toPyObject()): if msgid == str(inbox.item(i, 3).data(QtCore.Qt.UserRole).toPyObject()):
self.updateStatusBar( self.updateStatusBar(
_translate("MainWindow", "Message trashed")) _translate("MainWindow", "Message trashed"))
treeWidget = self.widgetConvert(inbox) treeWidget = self.widgetConvert(inbox)
self.propagateUnreadCount(inbox.item(i, 1 if inbox.item(i, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder(treeWidget), treeWidget, 0) self.propagateUnreadCount(
inbox.item(
i,
1 if inbox.item(
i,
1).type == AccountMixin.SUBSCRIPTION else 0).data(
QtCore.Qt.UserRole),
self.getCurrentFolder(treeWidget),
treeWidget,
0)
inbox.removeRow(i) inbox.removeRow(i)
break break
def newVersionAvailable(self, version): def newVersionAvailable(self, version):
"""TBC"""
self.notifiedNewVersion = ".".join(str(n) for n in version) self.notifiedNewVersion = ".".join(str(n) for n in version)
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", _translate(
"New version of PyBitmessage is available: %1. Download it" "MainWindow",
" from https://github.com/Bitmessage/PyBitmessage/releases/latest" "New version of PyBitmessage is available: %1. Download it"
" from https://github.com/Bitmessage/PyBitmessage/releases/latest"
).arg(self.notifiedNewVersion) ).arg(self.notifiedNewVersion)
) )
def displayAlert(self, title, text, exitAfterUserClicksOk): def displayAlert(self, title, text, exitAfterUserClicksOk):
"""TBC"""
self.updateStatusBar(text) self.updateStatusBar(text)
QtGui.QMessageBox.critical(self, title, text, QtGui.QMessageBox.Ok) QtGui.QMessageBox.critical(self, title, text, QtGui.QMessageBox.Ok)
if exitAfterUserClicksOk: if exitAfterUserClicksOk:
os._exit(0) sys.exit(0)
def rerenderMessagelistFromLabels(self): def rerenderMessagelistFromLabels(self):
for messagelist in (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions): """TBC"""
for messagelist in (
self.ui.tableWidgetInbox,
self.ui.tableWidgetInboxChans,
self.ui.tableWidgetInboxSubscriptions):
for i in range(messagelist.rowCount()): for i in range(messagelist.rowCount()):
messagelist.item(i, 1).setLabel() messagelist.item(i, 1).setLabel()
def rerenderMessagelistToLabels(self): def rerenderMessagelistToLabels(self):
for messagelist in (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions): """TBC"""
for messagelist in (
self.ui.tableWidgetInbox,
self.ui.tableWidgetInboxChans,
self.ui.tableWidgetInboxSubscriptions):
for i in range(messagelist.rowCount()): for i in range(messagelist.rowCount()):
messagelist.item(i, 0).setLabel() messagelist.item(i, 0).setLabel()
def rerenderAddressBook(self): def rerenderAddressBook(self):
def addRow (address, label, type): """TBC"""
def addRow(address, label, arg_type):
"""TBC"""
self.ui.tableWidgetAddressBook.insertRow(0) self.ui.tableWidgetAddressBook.insertRow(0)
newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), type) newItem = Ui_AddressBookWidgetItemLabel(address, unicode(label, 'utf-8'), arg_type)
self.ui.tableWidgetAddressBook.setItem(0, 0, newItem) self.ui.tableWidgetAddressBook.setItem(0, 0, newItem)
newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), type) newItem = Ui_AddressBookWidgetItemAddress(address, unicode(label, 'utf-8'), arg_type)
self.ui.tableWidgetAddressBook.setItem(0, 1, newItem) self.ui.tableWidgetAddressBook.setItem(0, 1, newItem)
oldRows = {} oldRows = {}
@ -1839,7 +2054,7 @@ class MyForm(settingsmixin.SMainWindow):
newRows[address] = [label, AccountMixin.NORMAL] newRows[address] = [label, AccountMixin.NORMAL]
completerList = [] completerList = []
for address in sorted(oldRows, key = lambda x: oldRows[x][2], reverse = True): for address in sorted(oldRows, key=lambda x: oldRows[x][2], reverse=True):
if address in newRows: if address in newRows:
completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">") completerList.append(unicode(newRows[address][0], encoding="UTF-8") + " <" + address + ">")
newRows.pop(address) newRows.pop(address)
@ -1856,22 +2071,42 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.lineEditTo.completer().model().setStringList(completerList) self.ui.lineEditTo.completer().model().setStringList(completerList)
def rerenderSubscriptions(self): def rerenderSubscriptions(self):
"""TBC"""
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
def click_pushButtonTTL(self): def click_pushButtonTTL(self):
"""TBC"""
QtGui.QMessageBox.information(self, 'Time To Live', _translate( QtGui.QMessageBox.information(self, 'Time To Live', _translate(
"MainWindow", """The TTL, or Time-To-Live is the length of time that the network will hold the message. "MainWindow",
The recipient must get it during this time. If your Bitmessage client does not hear an acknowledgement, it ("The TTL, or Time-To-Live is the length of time that the network will hold the message."
will resend the message automatically. The longer the Time-To-Live, the "The recipient must get it during this time. If your Bitmessage client does not hear an "
more work your computer must do to send the message. A Time-To-Live of four or five days is often appropriate."""), QtGui.QMessageBox.Ok) "acknowledgement, it will resend the message automatically. The longer the Time-To-Live, "
"the more work your computer must do to send the message. A Time-To-Live of four or five "
"days is often appropriate.")), QtGui.QMessageBox.Ok)
def click_pushButtonClear(self): def click_pushButtonClear(self):
"""TBC"""
self.ui.lineEditSubject.setText("") self.ui.lineEditSubject.setText("")
self.ui.lineEditTo.setText("") self.ui.lineEditTo.setText("")
self.ui.textEditMessage.setText("") self.ui.textEditMessage.setText("")
self.ui.comboBoxSendFrom.setCurrentIndex(0) self.ui.comboBoxSendFrom.setCurrentIndex(0)
def click_pushButtonSend(self): def click_pushButtonSend(self):
"""
TBC
Regarding the line below `if len(message) > (2 ** 18 - 500):`:
The whole network message must fit in 2^18 bytes.
Let's assume 500 bytes of overhead. If someone wants to get that
too an exact number you are welcome to but I think that it would
be a better use of time to support message continuation so that
users can send messages of any length.
"""
encoding = 3 if QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2 encoding = 3 if QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier else 2
self.statusbar.clearMessage() self.statusbar.clearMessage()
@ -1896,13 +2131,6 @@ class MyForm(settingsmixin.SMainWindow):
subject = str(self.ui.lineEditSubjectBroadcast.text().toUtf8()) subject = str(self.ui.lineEditSubjectBroadcast.text().toUtf8())
message = str( message = str(
self.ui.textEditMessageBroadcast.document().toPlainText().toUtf8()) self.ui.textEditMessageBroadcast.document().toPlainText().toUtf8())
"""
The whole network message must fit in 2^18 bytes.
Let's assume 500 bytes of overhead. If someone wants to get that
too an exact number you are welcome to but I think that it would
be a better use of time to support message continuation so that
users can send messages of any length.
"""
if len(message) > (2 ** 18 - 500): if len(message) > (2 ** 18 - 500):
QtGui.QMessageBox.about( QtGui.QMessageBox.about(
self, _translate("MainWindow", "Message too long"), self, _translate("MainWindow", "Message too long"),
@ -1916,11 +2144,13 @@ class MyForm(settingsmixin.SMainWindow):
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
if sendMessageToPeople: # To send a message to specific people (rather than broadcast) if sendMessageToPeople: # To send a message to specific people (rather than broadcast)
toAddressesList = [s.strip() toAddressesList = [s.strip()
for s in toAddresses.replace(',', ';').split(';')] for s in toAddresses.replace(',', ';').split(';')]
toAddressesList = list(set( # remove duplicate addresses. If the user has one address with a BM- and
toAddressesList)) # remove duplicate addresses. If the user has one address with a BM- and the same address without the BM-, this will not catch it. They'll send the message to the person twice. # the same address without the BM-, this will not catch it. They'll send
# the message to the person twice.
toAddressesList = list(set(toAddressesList))
for toAddress in toAddressesList: for toAddress in toAddressesList:
if toAddress != '': if toAddress != '':
# label plus address # label plus address
@ -1933,25 +2163,30 @@ class MyForm(settingsmixin.SMainWindow):
subject = acct.subject subject = acct.subject
toAddress = acct.toAddress toAddress = acct.toAddress
else: else:
if QtGui.QMessageBox.question(self, "Sending an email?", _translate("MainWindow", if QtGui.QMessageBox.question(
"You are trying to send an email instead of a bitmessage. This requires registering with a gateway. Attempt to register?"), self, "Sending an email?",
QtGui.QMessageBox.Yes|QtGui.QMessageBox.No) != QtGui.QMessageBox.Yes: _translate(
"MainWindow",
("You are trying to send an email instead of a bitmessage. This requires "
"registering with a gateway. Attempt to register?")),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) != QtGui.QMessageBox.Yes:
continue continue
email = acct.getLabel() email = acct.getLabel()
if email[-14:] != "@mailchuck.com": #attempt register if email[-14:] != "@mailchuck.com": # attempt register
# 12 character random email address # 12 character random email address
email = ''.join(random.SystemRandom().choice(string.ascii_lowercase) for _ in range(12)) + "@mailchuck.com" email = ''.join(random.SystemRandom().choice(string.ascii_lowercase)
for _ in range(12)) + "@mailchuck.com"
acct = MailchuckAccount(fromAddress) acct = MailchuckAccount(fromAddress)
acct.register(email) acct.register(email)
BMConfigParser().set(fromAddress, 'label', email) BMConfigParser().set(fromAddress, 'label', email)
BMConfigParser().set(fromAddress, 'gateway', 'mailchuck') BMConfigParser().set(fromAddress, 'gateway', 'mailchuck')
BMConfigParser().save() BMConfigParser().save()
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", _translate(
"Error: Your account wasn't registered at" "MainWindow",
" an email gateway. Sending registration" ("Error: Your account wasn't registered at an email gateway. Sending registration"
" now as %1, please wait for the registration" " now as %1, please wait for the registration to be processed before retrying "
" to be processed before retrying sending." "sending.")
).arg(email) ).arg(email)
) )
return return
@ -1969,19 +2204,19 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "MainWindow",
"Error: Bitmessage addresses start with" "Error: Bitmessage addresses start with"
" BM- Please check the recipient address %1" " BM- Please check the recipient address %1"
).arg(toAddress)) ).arg(toAddress))
elif status == 'checksumfailed': elif status == 'checksumfailed':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Error: The recipient address %1 is not" "Error: The recipient address %1 is not"
" typed or copied correctly. Please check it." " typed or copied correctly. Please check it."
).arg(toAddress)) ).arg(toAddress))
elif status == 'invalidcharacters': elif status == 'invalidcharacters':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Error: The recipient address %1 contains" "Error: The recipient address %1 contains"
" invalid characters. Please check it." " invalid characters. Please check it."
).arg(toAddress)) ).arg(toAddress))
elif status == 'versiontoohigh': elif status == 'versiontoohigh':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
@ -1989,7 +2224,7 @@ class MyForm(settingsmixin.SMainWindow):
" %1 is too high. Either you need to upgrade" " %1 is too high. Either you need to upgrade"
" your Bitmessage software or your" " your Bitmessage software or your"
" acquaintance is being clever." " acquaintance is being clever."
).arg(toAddress)) ).arg(toAddress))
elif status == 'ripetooshort': elif status == 'ripetooshort':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
@ -1997,7 +2232,7 @@ class MyForm(settingsmixin.SMainWindow):
" address %1 is too short. There might be" " address %1 is too short. There might be"
" something wrong with the software of" " something wrong with the software of"
" your acquaintance." " your acquaintance."
).arg(toAddress)) ).arg(toAddress))
elif status == 'ripetoolong': elif status == 'ripetoolong':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
@ -2005,7 +2240,7 @@ class MyForm(settingsmixin.SMainWindow):
" address %1 is too long. There might be" " address %1 is too long. There might be"
" something wrong with the software of" " something wrong with the software of"
" your acquaintance." " your acquaintance."
).arg(toAddress)) ).arg(toAddress))
elif status == 'varintmalformed': elif status == 'varintmalformed':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
@ -2013,39 +2248,55 @@ class MyForm(settingsmixin.SMainWindow):
" address %1 is malformed. There might be" " address %1 is malformed. There might be"
" something wrong with the software of" " something wrong with the software of"
" your acquaintance." " your acquaintance."
).arg(toAddress)) ).arg(toAddress))
else: else:
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Error: Something is wrong with the" "Error: Something is wrong with the"
" recipient address %1." " recipient address %1."
).arg(toAddress)) ).arg(toAddress))
elif fromAddress == '': elif fromAddress == '':
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "MainWindow",
"Error: You must specify a From address. If you" ("Error: You must specify a From address. If you don\'t have one, go to the"
" don\'t have one, go to the" " \'Your Identities\' tab.")))
" \'Your Identities\' tab.")
)
else: else:
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
if addressVersionNumber > 4 or addressVersionNumber <= 1: if addressVersionNumber > 4 or addressVersionNumber <= 1:
QtGui.QMessageBox.about(self, _translate("MainWindow", "Address version number"), _translate( QtGui.QMessageBox.about(
"MainWindow", "Concerning the address %1, Bitmessage cannot understand address version numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(addressVersionNumber))) self,
_translate(
"MainWindow",
"Address version number"),
_translate(
"MainWindow",
("Concerning the address %1, Bitmessage cannot understand address version "
"numbers of %2. Perhaps upgrade Bitmessage to the latest version.")
).arg(toAddress).arg(
str(addressVersionNumber)))
continue continue
if streamNumber > 1 or streamNumber == 0: if streamNumber > 1 or streamNumber == 0:
QtGui.QMessageBox.about(self, _translate("MainWindow", "Stream number"), _translate( QtGui.QMessageBox.about(
"MainWindow", "Concerning the address %1, Bitmessage cannot handle stream numbers of %2. Perhaps upgrade Bitmessage to the latest version.").arg(toAddress).arg(str(streamNumber))) self,
_translate(
"MainWindow",
"Stream number"),
_translate(
"MainWindow",
("Concerning the address %1, Bitmessage cannot handle stream numbers of %2. "
"Perhaps upgrade Bitmessage to the latest version.")
).arg(toAddress).arg(
str(streamNumber)))
continue continue
self.statusbar.clearMessage() self.statusbar.clearMessage()
if shared.statusIconColor == 'red': if shared.statusIconColor == 'red':
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", _translate(
"Warning: You are currently not connected." "MainWindow",
" Bitmessage will do the work necessary to" ("Warning: You are currently not connected. Bitmessage will do the work necessary"
" send the message but it won\'t send until" " to send the message but it won\'t send until you connect.")
" you connect.") )
) )
stealthLevel = BMConfigParser().safeGetInt( stealthLevel = BMConfigParser().safeGetInt(
'bitmessagesettings', 'ackstealthlevel') 'bitmessagesettings', 'ackstealthlevel')
@ -2060,15 +2311,15 @@ class MyForm(settingsmixin.SMainWindow):
subject, subject,
message, message,
ackdata, ackdata,
int(time.time()), # sentTime (this will never change) int(time.time()), # sentTime (this will never change)
int(time.time()), # lastActionTime int(time.time()), # lastActionTime
0, # sleepTill time. This will get set when the POW gets done. 0, # sleepTill time. This will get set when the POW gets done.
'msgqueued', 'msgqueued',
0, # retryNumber 0, # retryNumber
'sent', # folder 'sent', # folder
encoding, # encodingtype encoding, # encodingtype
BMConfigParser().getint('bitmessagesettings', 'ttl') BMConfigParser().getint('bitmessagesettings', 'ttl')
) )
toLabel = '' toLabel = ''
queryreturn = sqlQuery('''select label from addressbook where address=?''', queryreturn = sqlQuery('''select label from addressbook where address=?''',
@ -2110,22 +2361,23 @@ class MyForm(settingsmixin.SMainWindow):
ackdata = genAckPayload(streamNumber, 0) ackdata = genAckPayload(streamNumber, 0)
toAddress = str_broadcast_subscribers toAddress = str_broadcast_subscribers
ripe = '' ripe = ''
t = ('', # msgid. We don't know what this will be until the POW is done. t = (
toAddress, '', # msgid. We don't know what this will be until the POW is done.
ripe, toAddress,
fromAddress, ripe,
subject, fromAddress,
message, subject,
ackdata, message,
int(time.time()), # sentTime (this will never change) ackdata,
int(time.time()), # lastActionTime int(time.time()), # sentTime (this will never change)
0, # sleepTill time. This will get set when the POW gets done. int(time.time()), # lastActionTime
'broadcastqueued', 0, # sleepTill time. This will get set when the POW gets done.
0, # retryNumber 'broadcastqueued',
'sent', # folder 0, # retryNumber
encoding, # encoding type 'sent', # folder
BMConfigParser().getint('bitmessagesettings', 'ttl') encoding, # encoding type
) BMConfigParser().getint('bitmessagesettings', 'ttl')
)
sqlExecute( sqlExecute(
'''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t) '''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
@ -2147,6 +2399,8 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Broadcast queued.")) "MainWindow", "Broadcast queued."))
def click_pushButtonLoadFromAddressBook(self): def click_pushButtonLoadFromAddressBook(self):
"""TBC"""
self.ui.tabWidget.setCurrentIndex(5) self.ui.tabWidget.setCurrentIndex(5)
for i in range(4): for i in range(4):
time.sleep(0.1) time.sleep(0.1)
@ -2159,6 +2413,8 @@ class MyForm(settingsmixin.SMainWindow):
)) ))
def click_pushButtonFetchNamecoinID(self): def click_pushButtonFetchNamecoinID(self):
"""TBC"""
nc = namecoinConnection() nc = namecoinConnection()
identities = str(self.ui.lineEditTo.text().toUtf8()).split(";") identities = str(self.ui.lineEditTo.text().toUtf8()).split(";")
err, addr = nc.query(identities[-1].strip()) err, addr = nc.query(identities[-1].strip())
@ -2172,8 +2428,8 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Fetched address from namecoin identity.")) "MainWindow", "Fetched address from namecoin identity."))
def setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(self, address): def setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(self, address):
# If this is a chan then don't let people broadcast because no one """If this is a chan then don't let people broadcast because no one should subscribe to chan addresses."""
# should subscribe to chan addresses.
self.ui.tabWidgetSend.setCurrentIndex( self.ui.tabWidgetSend.setCurrentIndex(
self.ui.tabWidgetSend.indexOf( self.ui.tabWidgetSend.indexOf(
self.ui.sendBroadcast self.ui.sendBroadcast
@ -2182,17 +2438,20 @@ class MyForm(settingsmixin.SMainWindow):
)) ))
def rerenderComboBoxSendFrom(self): def rerenderComboBoxSendFrom(self):
"""TBC"""
self.ui.comboBoxSendFrom.clear() self.ui.comboBoxSendFrom.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean(
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist') isMaillinglist = BMConfigParser().safeGetBoolean(addressInKeysFile, 'mailinglist')
if isEnabled and not isMaillinglist: if isEnabled and not isMaillinglist:
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
if label == "": if label == "":
label = addressInKeysFile label = addressInKeysFile
self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) self.ui.comboBoxSendFrom.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
# self.ui.comboBoxSendFrom.model().sort(1, Qt.AscendingOrder)
for i in range(self.ui.comboBoxSendFrom.count()): for i in range(self.ui.comboBoxSendFrom.count()):
address = str(self.ui.comboBoxSendFrom.itemData( address = str(self.ui.comboBoxSendFrom.itemData(
i, QtCore.Qt.UserRole).toString()) i, QtCore.Qt.UserRole).toString())
@ -2200,22 +2459,26 @@ class MyForm(settingsmixin.SMainWindow):
i, AccountColor(address).accountColor(), i, AccountColor(address).accountColor(),
QtCore.Qt.ForegroundRole) QtCore.Qt.ForegroundRole)
self.ui.comboBoxSendFrom.insertItem(0, '', '') self.ui.comboBoxSendFrom.insertItem(0, '', '')
if(self.ui.comboBoxSendFrom.count() == 2): if self.ui.comboBoxSendFrom.count() == 2:
self.ui.comboBoxSendFrom.setCurrentIndex(1) self.ui.comboBoxSendFrom.setCurrentIndex(1)
else: else:
self.ui.comboBoxSendFrom.setCurrentIndex(0) self.ui.comboBoxSendFrom.setCurrentIndex(0)
def rerenderComboBoxSendFromBroadcast(self): def rerenderComboBoxSendFromBroadcast(self):
"""TBC"""
self.ui.comboBoxSendFromBroadcast.clear() self.ui.comboBoxSendFromBroadcast.clear()
for addressInKeysFile in getSortedAccounts(): for addressInKeysFile in getSortedAccounts():
isEnabled = BMConfigParser().getboolean(
addressInKeysFile, 'enabled') # I realize that this is poor programming practice but I don't care. It's easier for others to read. # I realize that this is poor programming practice but I don't care. It's easier for others to read.
isEnabled = BMConfigParser().getboolean(addressInKeysFile, 'enabled')
isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan') isChan = BMConfigParser().safeGetBoolean(addressInKeysFile, 'chan')
if isEnabled and not isChan: if isEnabled and not isChan:
label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip() label = unicode(BMConfigParser().get(addressInKeysFile, 'label'), 'utf-8', 'ignore').strip()
if label == "": if label == "":
label = addressInKeysFile label = addressInKeysFile
self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile) self.ui.comboBoxSendFromBroadcast.addItem(avatarize(addressInKeysFile), label, addressInKeysFile)
for i in range(self.ui.comboBoxSendFromBroadcast.count()): for i in range(self.ui.comboBoxSendFromBroadcast.count()):
address = str(self.ui.comboBoxSendFromBroadcast.itemData( address = str(self.ui.comboBoxSendFromBroadcast.itemData(
i, QtCore.Qt.UserRole).toString()) i, QtCore.Qt.UserRole).toString())
@ -2223,16 +2486,19 @@ class MyForm(settingsmixin.SMainWindow):
i, AccountColor(address).accountColor(), i, AccountColor(address).accountColor(),
QtCore.Qt.ForegroundRole) QtCore.Qt.ForegroundRole)
self.ui.comboBoxSendFromBroadcast.insertItem(0, '', '') self.ui.comboBoxSendFromBroadcast.insertItem(0, '', '')
if(self.ui.comboBoxSendFromBroadcast.count() == 2): if self.ui.comboBoxSendFromBroadcast.count() == 2:
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(1) self.ui.comboBoxSendFromBroadcast.setCurrentIndex(1)
else: else:
self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0) self.ui.comboBoxSendFromBroadcast.setCurrentIndex(0)
# This function is called by the processmsg function when that function
# receives a message to an address that is acting as a
# pseudo-mailing-list. The message will be broadcast out. This function
# puts the message on the 'Sent' tab.
def displayNewSentMessage(self, toAddress, toLabel, fromAddress, subject, message, ackdata): def displayNewSentMessage(self, toAddress, toLabel, fromAddress, subject, message, ackdata):
"""
This function is called by the processmsg function when that function
receives a message to an address that is acting as a
pseudo-mailing-list. The message will be broadcast out. This function
puts the message on the 'Sent' tab.
"""
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
acct.parseMessage(toAddress, fromAddress, subject, message) acct.parseMessage(toAddress, fromAddress, subject, message)
tab = -1 tab = -1
@ -2243,11 +2509,28 @@ class MyForm(settingsmixin.SMainWindow):
treeWidget = self.widgetConvert(sent) treeWidget = self.widgetConvert(sent)
if self.getCurrentFolder(treeWidget) != "sent": if self.getCurrentFolder(treeWidget) != "sent":
continue continue
if treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) not in (fromAddress, None, False): if all(
[
treeWidget == self.ui.treeWidgetYourIdentities,
self.getCurrentAccount(treeWidget) not in (fromAddress, None, False),
]
):
continue continue
elif treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans] and self.getCurrentAccount(treeWidget) != toAddress: elif all(
[
treeWidget in [self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans],
self.getCurrentAccount(treeWidget) != toAddress,
]
):
continue continue
elif not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)): elif not helper_search.check_match(
toAddress,
fromAddress,
subject,
message,
self.getCurrentSearchOption(tab),
self.getCurrentSearchLine(tab),
):
continue continue
self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time()) self.addMessageListItemSent(sent, toAddress, fromAddress, subject, "msgqueued", ackdata, time.time())
@ -2255,6 +2538,8 @@ class MyForm(settingsmixin.SMainWindow):
sent.setCurrentCell(0, 0) sent.setCurrentCell(0, 0)
def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message): def displayNewInboxMessage(self, inventoryHash, toAddress, fromAddress, subject, message):
"""TBC"""
if toAddress == str_broadcast_subscribers: if toAddress == str_broadcast_subscribers:
acct = accountClass(fromAddress) acct = accountClass(fromAddress)
else: else:
@ -2262,17 +2547,58 @@ class MyForm(settingsmixin.SMainWindow):
inbox = self.getAccountMessagelist(acct) inbox = self.getAccountMessagelist(acct)
ret = None ret = None
tab = -1 tab = -1
for treeWidget in [self.ui.treeWidgetYourIdentities, self.ui.treeWidgetSubscriptions, self.ui.treeWidgetChans]: for treeWidget in [
self.ui.treeWidgetYourIdentities,
self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans,
]:
tab += 1 tab += 1
if tab == 1: if tab == 1:
tab = 2 tab = 2
tableWidget = self.widgetConvert(treeWidget) tableWidget = self.widgetConvert(treeWidget)
if not helper_search.check_match(toAddress, fromAddress, subject, message, self.getCurrentSearchOption(tab), self.getCurrentSearchLine(tab)): if not helper_search.check_match(
toAddress,
fromAddress,
subject,
message,
self.getCurrentSearchOption(tab),
self.getCurrentSearchLine(tab),
):
continue continue
if tableWidget == inbox and self.getCurrentAccount(treeWidget) == acct.address and self.getCurrentFolder(treeWidget) in ["inbox", None]: if all(
ret = self.addMessageListItemInbox(inbox, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) [
elif treeWidget == self.ui.treeWidgetYourIdentities and self.getCurrentAccount(treeWidget) is None and self.getCurrentFolder(treeWidget) in ["inbox", "new", None]: tableWidget == inbox,
ret = self.addMessageListItemInbox(tableWidget, "inbox", inventoryHash, toAddress, fromAddress, subject, time.time(), 0) self.getCurrentAccount(treeWidget) == acct.address,
self.getCurrentFolder(treeWidget) in ["inbox", None],
]
):
ret = self.addMessageListItemInbox(
inbox,
"inbox",
inventoryHash,
toAddress,
fromAddress,
subject,
time.time(),
0,
)
elif treeWidget == all(
[
self.ui.treeWidgetYourIdentities,
self.getCurrentAccount(treeWidget) is None,
self.getCurrentFolder(treeWidget) in ["inbox", "new", None]
]
):
ret = self.addMessageListItemInbox(
tableWidget,
"inbox",
inventoryHash,
toAddress,
fromAddress,
subject,
time.time(),
0,
)
if ret is None: if ret is None:
acct.parseMessage(toAddress, fromAddress, subject, "") acct.parseMessage(toAddress, fromAddress, subject, "")
else: else:
@ -2286,18 +2612,30 @@ class MyForm(settingsmixin.SMainWindow):
unicode(acct.fromLabel, 'utf-8')), unicode(acct.fromLabel, 'utf-8')),
sound.SOUND_UNKNOWN sound.SOUND_UNKNOWN
) )
if self.getCurrentAccount() is not None and ((self.getCurrentFolder(treeWidget) != "inbox" and self.getCurrentFolder(treeWidget) is not None) or self.getCurrentAccount(treeWidget) != acct.address): if any(
[
all(
[
self.getCurrentAccount() is not None,
self.getCurrentFolder(treeWidget) != "inbox", # pylint: disable=undefined-loop-variable
self.getCurrentFolder(treeWidget) is not None, # pylint: disable=undefined-loop-variable
]
),
self.getCurrentAccount(treeWidget) != acct.address # pylint: disable=undefined-loop-variable
]
):
# Ubuntu should notify of new message irespective of # Ubuntu should notify of new message irespective of
# whether it's in current message list or not # whether it's in current message list or not
self.indicatorUpdate(True, to_label=acct.toLabel) self.indicatorUpdate(True, to_label=acct.toLabel)
# cannot find item to pass here ): # cannot find item to pass here ):
if hasattr(acct, "feedback") \ if hasattr(acct, "feedback") and acct.feedback != GatewayAccount.ALL_OK:
and acct.feedback != GatewayAccount.ALL_OK:
if acct.feedback == GatewayAccount.REGISTRATION_DENIED: if acct.feedback == GatewayAccount.REGISTRATION_DENIED:
dialogs.EmailGatewayDialog( dialogs.EmailGatewayDialog(
self, BMConfigParser(), acct).exec_() self, BMConfigParser(), acct).exec_()
def click_pushButtonAddAddressBook(self, dialog=None): def click_pushButtonAddAddressBook(self, dialog=None):
"""TBC"""
if not dialog: if not dialog:
dialog = dialogs.AddAddressDialog(self) dialog = dialogs.AddAddressDialog(self)
dialog.exec_() dialog.exec_()
@ -2321,6 +2659,8 @@ class MyForm(settingsmixin.SMainWindow):
self.addEntryToAddressBook(address, label) self.addEntryToAddressBook(address, label)
def addEntryToAddressBook(self, address, label): def addEntryToAddressBook(self, address, label):
"""TBC"""
if shared.isAddressInMyAddressBook(address): if shared.isAddressInMyAddressBook(address):
return return
sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', label, address) sqlExecute('''INSERT INTO addressbook VALUES (?,?)''', label, address)
@ -2329,6 +2669,8 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderAddressBook() self.rerenderAddressBook()
def addSubscription(self, address, label): def addSubscription(self, address, label):
"""TBC"""
# This should be handled outside of this function, for error displaying # This should be handled outside of this function, for error displaying
# and such, but it must also be checked here. # and such, but it must also be checked here.
if shared.isAddressInMySubscriptionsList(address): if shared.isAddressInMySubscriptionsList(address):
@ -2344,6 +2686,8 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
def click_pushButtonAddSubscription(self): def click_pushButtonAddSubscription(self):
"""TBC"""
dialog = dialogs.NewSubscriptionDialog(self) dialog = dialogs.NewSubscriptionDialog(self)
dialog.exec_() dialog.exec_()
try: try:
@ -2374,18 +2718,28 @@ class MyForm(settingsmixin.SMainWindow):
)) ))
def click_pushButtonStatusIcon(self): def click_pushButtonStatusIcon(self):
"""TBC"""
dialogs.IconGlossaryDialog(self, config=BMConfigParser()).exec_() dialogs.IconGlossaryDialog(self, config=BMConfigParser()).exec_()
def click_actionHelp(self): def click_actionHelp(self):
"""TBC"""
dialogs.HelpDialog(self).exec_() dialogs.HelpDialog(self).exec_()
def click_actionSupport(self): def click_actionSupport(self):
"""TBC"""
support.createSupportMessage(self) support.createSupportMessage(self)
def click_actionAbout(self): def click_actionAbout(self):
"""TBC"""
dialogs.AboutDialog(self).exec_() dialogs.AboutDialog(self).exec_()
def click_actionSettings(self): def click_actionSettings(self):
"""TBC"""
self.settingsDialogInstance = settingsDialog(self) self.settingsDialogInstance = settingsDialog(self)
if self._firstrun: if self._firstrun:
self.settingsDialogInstance.ui.tabWidgetSettings.setCurrentIndex(1) self.settingsDialogInstance.ui.tabWidgetSettings.setCurrentIndex(1)
@ -2412,31 +2766,56 @@ class MyForm(settingsmixin.SMainWindow):
BMConfigParser().set('bitmessagesettings', 'replybelow', str( BMConfigParser().set('bitmessagesettings', 'replybelow', str(
self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked())) self.settingsDialogInstance.ui.checkBoxReplyBelow.isChecked()))
lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData(self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString()) lang = str(self.settingsDialogInstance.ui.languageComboBox.itemData(
self.settingsDialogInstance.ui.languageComboBox.currentIndex()).toString())
BMConfigParser().set('bitmessagesettings', 'userlocale', lang) BMConfigParser().set('bitmessagesettings', 'userlocale', lang)
change_translation(l10n.getTranslationLanguage()) change_translation(l10n.getTranslationLanguage())
if int(BMConfigParser().get('bitmessagesettings', 'port')) != int(self.settingsDialogInstance.ui.lineEditTCPPort.text()): if int(BMConfigParser().get('bitmessagesettings', 'port')) != int(
self.settingsDialogInstance.ui.lineEditTCPPort.text()):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'): if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'dontconnect'):
QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate(
"MainWindow", "You must restart Bitmessage for the port number change to take effect.")) "MainWindow", "You must restart Bitmessage for the port number change to take effect."))
BMConfigParser().set('bitmessagesettings', 'port', str( BMConfigParser().set('bitmessagesettings', 'port', str(
self.settingsDialogInstance.ui.lineEditTCPPort.text())) self.settingsDialogInstance.ui.lineEditTCPPort.text()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp'): if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked() != BMConfigParser().safeGetBoolean(
BMConfigParser().set('bitmessagesettings', 'upnp', str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked())) 'bitmessagesettings', 'upnp'
):
BMConfigParser().set(
'bitmessagesettings', 'upnp',
str(self.settingsDialogInstance.ui.checkBoxUPnP.isChecked()))
if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked(): if self.settingsDialogInstance.ui.checkBoxUPnP.isChecked():
import upnp
upnpThread = upnp.uPnPThread() upnpThread = upnp.uPnPThread()
upnpThread.start() upnpThread.start()
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText()', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()
#print 'self.settingsDialogInstance.ui.comboBoxProxyType.currentText())[0:5]', self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] if all(
if BMConfigParser().get('bitmessagesettings', 'socksproxytype') == 'none' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS': [
BMConfigParser().get(
'bitmessagesettings',
'socksproxytype') == 'none',
self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS',
]
):
if shared.statusIconColor != 'red': if shared.statusIconColor != 'red':
QtGui.QMessageBox.about(self, _translate("MainWindow", "Restart"), _translate( QtGui.QMessageBox.about(
"MainWindow", "Bitmessage will use your proxy from now on but you may want to manually restart Bitmessage now to close existing connections (if any).")) self,
if BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS' and self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS': _translate(
"MainWindow",
"Restart"),
_translate(
"MainWindow",
("Bitmessage will use your proxy from now on but you may want to manually restart "
"Bitmessage now to close existing connections (if any).")))
if all(
[
BMConfigParser().get('bitmessagesettings', 'socksproxytype')[0:5] == 'SOCKS',
self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] != 'SOCKS',
]
):
self.statusbar.clearMessage() self.statusbar.clearMessage()
state.resetNetworkProtocolAvailability() # just in case we changed something in the network connectivity state.resetNetworkProtocolAvailability() # just in case we changed something in the network connectivity
if self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS': if self.settingsDialogInstance.ui.comboBoxProxyType.currentText()[0:5] == 'SOCKS':
BMConfigParser().set('bitmessagesettings', 'socksproxytype', str( BMConfigParser().set('bitmessagesettings', 'socksproxytype', str(
self.settingsDialogInstance.ui.comboBoxProxyType.currentText())) self.settingsDialogInstance.ui.comboBoxProxyType.currentText()))
@ -2465,13 +2844,13 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Your maximum download and upload rate must be numbers. Ignoring what you typed.")) "MainWindow", "Your maximum download and upload rate must be numbers. Ignoring what you typed."))
else: else:
set_rates(BMConfigParser().safeGetInt("bitmessagesettings", "maxdownloadrate"), set_rates(BMConfigParser().safeGetInt("bitmessagesettings", "maxdownloadrate"),
BMConfigParser().safeGetInt("bitmessagesettings", "maxuploadrate")) BMConfigParser().safeGetInt("bitmessagesettings", "maxuploadrate"))
BMConfigParser().set('bitmessagesettings', 'maxoutboundconnections', str( BMConfigParser().set('bitmessagesettings', 'maxoutboundconnections', str(
int(float(self.settingsDialogInstance.ui.lineEditMaxOutboundConnections.text())))) int(float(self.settingsDialogInstance.ui.lineEditMaxOutboundConnections.text()))))
BMConfigParser().set('bitmessagesettings', 'namecoinrpctype', BMConfigParser().set('bitmessagesettings', 'namecoinrpctype',
self.settingsDialogInstance.getNamecoinType()) self.settingsDialogInstance.getNamecoinType())
BMConfigParser().set('bitmessagesettings', 'namecoinrpchost', str( BMConfigParser().set('bitmessagesettings', 'namecoinrpchost', str(
self.settingsDialogInstance.ui.lineEditNamecoinHost.text())) self.settingsDialogInstance.ui.lineEditNamecoinHost.text()))
BMConfigParser().set('bitmessagesettings', 'namecoinrpcport', str( BMConfigParser().set('bitmessagesettings', 'namecoinrpcport', str(
@ -2484,31 +2863,65 @@ class MyForm(settingsmixin.SMainWindow):
# Demanded difficulty tab # Demanded difficulty tab
if float(self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) >= 1: if float(self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) >= 1:
BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float( BMConfigParser().set('bitmessagesettings', 'defaultnoncetrialsperbyte', str(int(float(
self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) self.settingsDialogInstance.ui.lineEditTotalDifficulty.text()
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
if float(self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) >= 1: if float(self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) >= 1:
BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float( BMConfigParser().set('bitmessagesettings', 'defaultpayloadlengthextrabytes', str(int(float(
self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes))) self.settingsDialogInstance.ui.lineEditSmallMessageDifficulty.text()
) * defaults.networkDefaultPayloadLengthExtraBytes)))
if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8() != BMConfigParser().safeGet("bitmessagesettings", "opencl"): if self.settingsDialogInstance.ui.comboBoxOpenCL.currentText().toUtf8(
BMConfigParser().set('bitmessagesettings', 'opencl', str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText())) ) != BMConfigParser().safeGet("bitmessagesettings", "opencl"):
BMConfigParser().set(
'bitmessagesettings', 'opencl',
str(self.settingsDialogInstance.ui.comboBoxOpenCL.currentText()))
queues.workerQueue.put(('resetPoW', '')) queues.workerQueue.put(('resetPoW', ''))
acceptableDifficultyChanged = False acceptableDifficultyChanged = False
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0: if any(
if BMConfigParser().get('bitmessagesettings','maxacceptablenoncetrialsperbyte') != str(int(float( [
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)): float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) >= 1,
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) == 0,
]
):
if BMConfigParser().get(
'bitmessagesettings',
'maxacceptablenoncetrialsperbyte',
) != str(
int(
float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte
)
):
# the user changed the max acceptable total difficulty # the user changed the max acceptable total difficulty
acceptableDifficultyChanged = True acceptableDifficultyChanged = True
BMConfigParser().set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float( BMConfigParser().set('bitmessagesettings', 'maxacceptablenoncetrialsperbyte', str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) self.settingsDialogInstance.ui.lineEditMaxAcceptableTotalDifficulty.text()
if float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 or float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0: ) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)))
if BMConfigParser().get('bitmessagesettings','maxacceptablepayloadlengthextrabytes') != str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes)): if any(
[
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1,
float(self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0,
]
):
if BMConfigParser().get(
'bitmessagesettings',
'maxacceptablepayloadlengthextrabytes',
) != str(
int(
float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()
) * defaults.networkDefaultPayloadLengthExtraBytes
)
):
# the user changed the max acceptable small message difficulty # the user changed the max acceptable small message difficulty
acceptableDifficultyChanged = True acceptableDifficultyChanged = True
BMConfigParser().set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float( BMConfigParser().set('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', str(int(float(
self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()) * defaults.networkDefaultPayloadLengthExtraBytes))) self.settingsDialogInstance.ui.lineEditMaxAcceptableSmallMessageDifficulty.text()
) * defaults.networkDefaultPayloadLengthExtraBytes)))
if acceptableDifficultyChanged: if acceptableDifficultyChanged:
# It might now be possible to send msgs which were previously marked as toodifficult. # It might now be possible to send msgs which were previously marked as toodifficult.
# Let us change them to 'msgqueued'. The singleWorker will try to send them and will again # Let us change them to 'msgqueued'. The singleWorker will try to send them and will again
@ -2517,9 +2930,14 @@ class MyForm(settingsmixin.SMainWindow):
sqlExecute('''UPDATE sent SET status='msgqueued' WHERE status='toodifficult' ''') sqlExecute('''UPDATE sent SET status='msgqueued' WHERE status='toodifficult' ''')
queues.workerQueue.put(('sendmessage', '')) queues.workerQueue.put(('sendmessage', ''))
#start:UI setting to stop trying to send messages after X days/months # start:UI setting to stop trying to send messages after X days/months
# I'm open to changing this UI to something else if someone has a better idea. # I'm open to changing this UI to something else if someone has a better idea.
if ((self.settingsDialogInstance.ui.lineEditDays.text()=='') and (self.settingsDialogInstance.ui.lineEditMonths.text()=='')):#We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank if all(
[
self.settingsDialogInstance.ui.lineEditDays.text() == '',
self.settingsDialogInstance.ui.lineEditMonths.text() == '',
]
): # We need to handle this special case. Bitmessage has its default behavior. The input is blank/blank
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '')
shared.maximumLengthOfTimeToBotherResendingMessages = float('inf') shared.maximumLengthOfTimeToBotherResendingMessages = float('inf')
@ -2538,24 +2956,41 @@ class MyForm(settingsmixin.SMainWindow):
if lineEditMonthsIsValidFloat and not lineEditDaysIsValidFloat: if lineEditMonthsIsValidFloat and not lineEditDaysIsValidFloat:
self.settingsDialogInstance.ui.lineEditDays.setText("0") self.settingsDialogInstance.ui.lineEditDays.setText("0")
if lineEditDaysIsValidFloat or lineEditMonthsIsValidFloat: if lineEditDaysIsValidFloat or lineEditMonthsIsValidFloat:
if (float(self.settingsDialogInstance.ui.lineEditDays.text()) >=0 and float(self.settingsDialogInstance.ui.lineEditMonths.text()) >=0): if all(
shared.maximumLengthOfTimeToBotherResendingMessages = (float(str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60) + (float(str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 *365)/12) [
if shared.maximumLengthOfTimeToBotherResendingMessages < 432000: # If the time period is less than 5 hours, we give zero values to all fields. No message will be sent again. float(self.settingsDialogInstance.ui.lineEditDays.text()) >= 0,
QtGui.QMessageBox.about(self, _translate("MainWindow", "Will not resend ever"), _translate( float(self.settingsDialogInstance.ui.lineEditMonths.text()) >= 0,
"MainWindow", "Note that the time limit you entered is less than the amount of time Bitmessage waits for the first resend attempt therefore your messages will never be resent.")) ]
):
shared.maximumLengthOfTimeToBotherResendingMessages = sum(
float(str(self.settingsDialogInstance.ui.lineEditDays.text())) * 24 * 60 * 60,
float(str(self.settingsDialogInstance.ui.lineEditMonths.text())) * (60 * 60 * 24 * 365) / 12,
)
# If the time period is less than 5 hours, we give zero values to all
# fields. No message will be sent again.
if shared.maximumLengthOfTimeToBotherResendingMessages < 432000:
QtGui.QMessageBox.about(
self,
_translate(
"MainWindow",
"Will not resend ever"),
_translate(
"MainWindow",
("Note that the time limit you entered is less than the amount of time Bitmessage "
"waits for the first resend attempt therefore your messages will never be resent.")))
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '0') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', '0')
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '0') BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', '0')
shared.maximumLengthOfTimeToBotherResendingMessages = 0 shared.maximumLengthOfTimeToBotherResendingMessages = 0
else: else:
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', str(float( BMConfigParser().set('bitmessagesettings', 'stopresendingafterxdays', str(float(
self.settingsDialogInstance.ui.lineEditDays.text()))) self.settingsDialogInstance.ui.lineEditDays.text())))
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', str(float( BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', str(float(
self.settingsDialogInstance.ui.lineEditMonths.text()))) self.settingsDialogInstance.ui.lineEditMonths.text())))
BMConfigParser().save() BMConfigParser().save()
if 'win32' in sys.platform or 'win64' in sys.platform: if 'win32' in sys.platform or 'win64' in sys.platform:
# Auto-startup for Windows # Auto-startup for Windows
RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" RUN_PATH = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat) self.settings = QtCore.QSettings(RUN_PATH, QtCore.QSettings.NativeFormat)
if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'): if BMConfigParser().getboolean('bitmessagesettings', 'startonlogon'):
@ -2569,46 +3004,56 @@ class MyForm(settingsmixin.SMainWindow):
# startup for linux # startup for linux
pass pass
if state.appdata != paths.lookupExeFolder() and self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): # If we are NOT using portable mode now but the user selected that we should... # If we are NOT using portable mode now but the user selected that we should...
# Write the keys.dat file to disk in the new location if state.appdata != paths.lookupExeFolder():
sqlStoredProcedure('movemessagstoprog') if self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked():
with open(paths.lookupExeFolder() + 'keys.dat', 'wb') as configfile:
BMConfigParser().write(configfile)
# Write the knownnodes.dat file to disk in the new location
knownnodes.saveKnownNodes(paths.lookupExeFolder())
os.remove(state.appdata + 'keys.dat')
os.remove(state.appdata + 'knownnodes.dat')
previousAppdataLocation = state.appdata
state.appdata = paths.lookupExeFolder()
debug.restartLoggingInUpdatedAppdataLocation()
try:
os.remove(previousAppdataLocation + 'debug.log')
os.remove(previousAppdataLocation + 'debug.log.1')
except:
pass
if state.appdata == paths.lookupExeFolder() and not self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked(): # If we ARE using portable mode now but the user selected that we shouldn't... # Write the keys.dat file to disk in the new location
state.appdata = paths.lookupAppdataFolder() sqlStoredProcedure('movemessagstoprog')
if not os.path.exists(state.appdata): with open(paths.lookupExeFolder() + 'keys.dat', 'wb') as configfile:
os.makedirs(state.appdata) BMConfigParser().write(configfile)
sqlStoredProcedure('movemessagstoappdata') # Write the knownnodes.dat file to disk in the new location
# Write the keys.dat file to disk in the new location knownnodes.saveKnownNodes(paths.lookupExeFolder())
BMConfigParser().save() os.remove(state.appdata + 'keys.dat')
# Write the knownnodes.dat file to disk in the new location os.remove(state.appdata + 'knownnodes.dat')
knownnodes.saveKnownNodes(state.appdata) previousAppdataLocation = state.appdata
os.remove(paths.lookupExeFolder() + 'keys.dat') state.appdata = paths.lookupExeFolder()
os.remove(paths.lookupExeFolder() + 'knownnodes.dat') debug.restartLoggingInUpdatedAppdataLocation()
debug.restartLoggingInUpdatedAppdataLocation() try:
try: os.remove(previousAppdataLocation + 'debug.log')
os.remove(paths.lookupExeFolder() + 'debug.log') os.remove(previousAppdataLocation + 'debug.log.1')
os.remove(paths.lookupExeFolder() + 'debug.log.1') except:
except: pass
pass
# If we ARE using portable mode now but the user selected that we shouldn't...
if state.appdata == paths.lookupExeFolder():
if not self.settingsDialogInstance.ui.checkBoxPortableMode.isChecked():
state.appdata = paths.lookupAppdataFolder()
if not os.path.exists(state.appdata):
os.makedirs(state.appdata)
sqlStoredProcedure('movemessagstoappdata')
# Write the keys.dat file to disk in the new location
BMConfigParser().save()
# Write the knownnodes.dat file to disk in the new location
knownnodes.saveKnownNodes(state.appdata)
os.remove(paths.lookupExeFolder() + 'keys.dat')
os.remove(paths.lookupExeFolder() + 'knownnodes.dat')
debug.restartLoggingInUpdatedAppdataLocation()
try:
os.remove(paths.lookupExeFolder() + 'debug.log')
os.remove(paths.lookupExeFolder() + 'debug.log.1')
except:
pass
def on_action_SpecialAddressBehaviorDialog(self): def on_action_SpecialAddressBehaviorDialog(self):
"""TBC"""
dialogs.SpecialAddressBehaviorDialog(self, BMConfigParser()) dialogs.SpecialAddressBehaviorDialog(self, BMConfigParser())
def on_action_EmailGatewayDialog(self): def on_action_EmailGatewayDialog(self):
"""TBC"""
dialog = dialogs.EmailGatewayDialog(self, config=BMConfigParser()) dialog = dialogs.EmailGatewayDialog(self, config=BMConfigParser())
# For Modal dialogs # For Modal dialogs
dialog.exec_() dialog.exec_()
@ -2639,6 +3084,8 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.textEditMessage.setFocus() self.ui.textEditMessage.setFocus()
def on_action_MarkAllRead(self): def on_action_MarkAllRead(self):
"""TBC"""
if QtGui.QMessageBox.question( if QtGui.QMessageBox.question(
self, "Marking all messages as read?", self, "Marking all messages as read?",
_translate( _translate(
@ -2675,12 +3122,16 @@ class MyForm(settingsmixin.SMainWindow):
if markread > 0: if markread > 0:
self.propagateUnreadCount() self.propagateUnreadCount()
# addressAtCurrentRow, self.getCurrentFolder(), None, 0) # addressAtCurrentRow, self.getCurrentFolder(), None, 0)
def click_NewAddressDialog(self): def click_NewAddressDialog(self):
"""TBC"""
dialogs.NewAddressDialog(self) dialogs.NewAddressDialog(self)
def network_switch(self): def network_switch(self):
"""TBC"""
dontconnect_option = not BMConfigParser().safeGetBoolean( dontconnect_option = not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect') 'bitmessagesettings', 'dontconnect')
BMConfigParser().set( BMConfigParser().set(
@ -2692,15 +3143,8 @@ class MyForm(settingsmixin.SMainWindow):
dontconnect_option or self.namecoin.test()[0] == 'failed' dontconnect_option or self.namecoin.test()[0] == 'failed'
) )
# Quit selected from menu or application indicator
def quit(self): def quit(self):
'''quit_msg = "Are you sure you want to exit Bitmessage?" """Quit selected from menu or application indicator"""
reply = QtGui.QMessageBox.question(self, 'Message',
quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply is QtGui.QMessageBox.No:
return
'''
if self.quitAccepted: if self.quitAccepted:
return return
@ -2715,20 +3159,50 @@ class MyForm(settingsmixin.SMainWindow):
# C PoW currently doesn't support interrupting and OpenCL is untested # C PoW currently doesn't support interrupting and OpenCL is untested
if getPowType() == "python" and (powQueueSize() > 0 or pendingUpload() > 0): if getPowType() == "python" and (powQueueSize() > 0 or pendingUpload() > 0):
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Proof of work pending"), reply = QtGui.QMessageBox.question(
_translate("MainWindow", "%n object(s) pending proof of work", None, QtCore.QCoreApplication.CodecForTr, powQueueSize()) + ", " + self,
_translate("MainWindow", "%n object(s) waiting to be distributed", None, QtCore.QCoreApplication.CodecForTr, pendingUpload()) + "\n\n" + _translate(
_translate("MainWindow", "Wait until these tasks finish?"), "MainWindow",
QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) "Proof of work pending"),
_translate(
"MainWindow",
"%n object(s) pending proof of work",
None,
QtCore.QCoreApplication.CodecForTr,
powQueueSize()) +
", " +
_translate(
"MainWindow",
"%n object(s) waiting to be distributed",
None,
QtCore.QCoreApplication.CodecForTr,
pendingUpload()) +
"\n\n" +
_translate(
"MainWindow",
"Wait until these tasks finish?"),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.No: if reply == QtGui.QMessageBox.No:
waitForPow = False waitForPow = False
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
return return
if pendingDownload() > 0: if pendingDownload() > 0:
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Synchronisation pending"), reply = QtGui.QMessageBox.question(
_translate("MainWindow", "Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit now, it may cause delivery delays. Wait until the synchronisation finishes?", None, QtCore.QCoreApplication.CodecForTr, pendingDownload()), self,
QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) _translate(
"MainWindow",
"Synchronisation pending"),
_translate(
"MainWindow",
("Bitmessage hasn't synchronised with the network, %n object(s) to be downloaded. If you quit "
"now, it may cause delivery delays. Wait until the synchronisation finishes?"),
None,
QtCore.QCoreApplication.CodecForTr,
pendingDownload()),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
waitForSync = True waitForSync = True
elif reply == QtGui.QMessageBox.Cancel: elif reply == QtGui.QMessageBox.Cancel:
@ -2736,9 +3210,17 @@ class MyForm(settingsmixin.SMainWindow):
if shared.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean( if shared.statusIconColor == 'red' and not BMConfigParser().safeGetBoolean(
'bitmessagesettings', 'dontconnect'): 'bitmessagesettings', 'dontconnect'):
reply = QtGui.QMessageBox.question(self, _translate("MainWindow", "Not connected"), reply = QtGui.QMessageBox.question(
_translate("MainWindow", "Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. Wait until connected and the synchronisation finishes?"), self,
QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Cancel) _translate(
"MainWindow",
"Not connected"),
_translate(
"MainWindow",
("Bitmessage isn't connected to the network. If you quit now, it may cause delivery delays. "
"Wait until connected and the synchronisation finishes?")),
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No | QtGui.QMessageBox.Cancel,
QtGui.QMessageBox.Cancel)
if reply == QtGui.QMessageBox.Yes: if reply == QtGui.QMessageBox.Yes:
waitForConnection = True waitForConnection = True
waitForSync = True waitForSync = True
@ -2759,7 +3241,9 @@ class MyForm(settingsmixin.SMainWindow):
QtCore.QEventLoop.AllEvents, 1000 QtCore.QEventLoop.AllEvents, 1000
) )
# this probably will not work correctly, because there is a delay between the status icon turning red and inventory exchange, but it's better than nothing. # this probably will not work correctly, because there is a delay between
# the status icon turning red and inventory exchange, but it's better than
# nothing.
if waitForSync: if waitForSync:
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
"MainWindow", "Waiting for finishing synchronisation...")) "MainWindow", "Waiting for finishing synchronisation..."))
@ -2779,10 +3263,11 @@ class MyForm(settingsmixin.SMainWindow):
if curWorkerQueue > maxWorkerQueue: if curWorkerQueue > maxWorkerQueue:
maxWorkerQueue = curWorkerQueue maxWorkerQueue = curWorkerQueue
if curWorkerQueue > 0: if curWorkerQueue > 0:
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", "Waiting for PoW to finish... %1%" _translate(
).arg(50 * (maxWorkerQueue - curWorkerQueue) "MainWindow",
/ maxWorkerQueue) "Waiting for PoW to finish... %1%",
).arg(50 * (maxWorkerQueue - curWorkerQueue) / maxWorkerQueue)
) )
time.sleep(0.5) time.sleep(0.5)
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
@ -2808,10 +3293,11 @@ class MyForm(settingsmixin.SMainWindow):
maxPendingUpload = max(1, pendingUpload()) maxPendingUpload = max(1, pendingUpload())
while pendingUpload() > 1: while pendingUpload() > 1:
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", _translate(
"Waiting for objects to be sent... %1%" "MainWindow",
).arg(int(50 + 20 * (pendingUpload()/maxPendingUpload))) "Waiting for objects to be sent... %1%"
).arg(int(50 + 20 * (pendingUpload() / maxPendingUpload)))
) )
time.sleep(0.5) time.sleep(0.5)
QtCore.QCoreApplication.processEvents( QtCore.QCoreApplication.processEvents(
@ -2854,11 +3340,11 @@ class MyForm(settingsmixin.SMainWindow):
shared.thisapp.cleanup() shared.thisapp.cleanup()
logger.info("Shutdown complete") logger.info("Shutdown complete")
super(MyForm, myapp).close() super(MyForm, myapp).close()
# return sys.exit(0)
os._exit(0)
# window close event
def closeEvent(self, event): def closeEvent(self, event):
"""window close event"""
self.appIndicatorHide() self.appIndicatorHide()
trayonclose = False trayonclose = False
@ -2879,6 +3365,8 @@ class MyForm(settingsmixin.SMainWindow):
self.quit() self.quit()
def on_action_InboxMessageForceHtml(self): def on_action_InboxMessageForceHtml(self):
"""TBC"""
msgid = self.getCurrentMessageId() msgid = self.getCurrentMessageId()
textEdit = self.getCurrentMessageTextedit() textEdit = self.getCurrentMessageTextedit()
if not msgid: if not msgid:
@ -2897,60 +3385,54 @@ class MyForm(settingsmixin.SMainWindow):
lines[i]) lines[i])
elif lines[i] == '------------------------------------------------------': elif lines[i] == '------------------------------------------------------':
lines[i] = '<hr>' lines[i] = '<hr>'
elif lines[i] == '' and (i+1) < totalLines and \ elif lines[i] == '' and (i + 1) < totalLines and \
lines[i+1] != '------------------------------------------------------': lines[i + 1] != '------------------------------------------------------':
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 = unicode(content, 'utf-8)') content = unicode(content, 'utf-8)')
textEdit.setHtml(QtCore.QString(content)) textEdit.setHtml(QtCore.QString(content))
def on_action_InboxMarkUnread(self): def on_action_InboxMarkUnread(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
msgids = set() msgids = set()
# modified = 0
for row in tableWidget.selectedIndexes(): for row in tableWidget.selectedIndexes():
currentRow = row.row() currentRow = row.row()
msgid = str(tableWidget.item( msgid = str(tableWidget.item(
currentRow, 3).data(QtCore.Qt.UserRole).toPyObject()) currentRow, 3).data(QtCore.Qt.UserRole).toPyObject())
msgids.add(msgid) msgids.add(msgid)
# if not tableWidget.item(currentRow, 0).unread:
# modified += 1
self.updateUnreadStatus(tableWidget, currentRow, msgid, False) self.updateUnreadStatus(tableWidget, currentRow, msgid, False)
# for 1081
idCount = len(msgids) idCount = len(msgids)
# rowcount =
sqlExecuteChunked( sqlExecuteChunked(
'''UPDATE inbox SET read=0 WHERE msgid IN ({0}) AND read=1''', '''UPDATE inbox SET read=0 WHERE msgid IN ({0}) AND read=1''',
idCount, *msgids idCount, *msgids
) )
self.propagateUnreadCount() self.propagateUnreadCount()
# if rowcount == 1:
# # performance optimisation
# self.propagateUnreadCount(tableWidget.item(currentRow, 1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder())
# else:
# self.propagateUnreadCount(tableWidget.item(currentRow, 1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), self.getCurrentFolder(), self.getCurrentTreeWidget(), 0)
# tableWidget.selectRow(currentRow + 1)
# This doesn't de-select the last message if you try to mark it unread, but that doesn't interfere. Might not be necessary.
# We could also select upwards, but then our problem would be with the topmost message.
# tableWidget.clearSelection() manages to mark the message as read again.
# Format predefined text on message reply.
def quoted_text(self, message): def quoted_text(self, message):
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'): """Format predefined text on message reply."""
return '\n\n------------------------------------------------------\n' + message
if not BMConfigParser().safeGetBoolean('bitmessagesettings', 'replybelow'):
return '\n\n------------------------------------------------------\n' + message
quoteWrapper = textwrap.TextWrapper(
replace_whitespace=False,
initial_indent='> ',
subsequent_indent='> ',
break_long_words=False,
break_on_hyphens=False,
)
quoteWrapper = textwrap.TextWrapper(replace_whitespace = False,
initial_indent = '> ',
subsequent_indent = '> ',
break_long_words = False,
break_on_hyphens = False)
def quote_line(line): def quote_line(line):
"""TBC"""
# Do quote empty lines. # Do quote empty lines.
if line == '' or line.isspace(): if line == '' or line.isspace():
return '> ' return '> '
@ -2958,11 +3440,13 @@ class MyForm(settingsmixin.SMainWindow):
elif line[0:2] == '> ': elif line[0:2] == '> ':
return '> ' + line return '> ' + line
# Wrap and quote lines/paragraphs new to this message. # Wrap and quote lines/paragraphs new to this message.
else: return quoteWrapper.fill(line)
return quoteWrapper.fill(line)
return '\n'.join([quote_line(l) for l in message.splitlines()]) + '\n\n' return '\n'.join([quote_line(l) for l in message.splitlines()]) + '\n\n'
def setSendFromComboBox(self, address = None): def setSendFromComboBox(self, address=None):
"""TBC"""
if address is None: if address is None:
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
if messagelist: if messagelist:
@ -2978,9 +3462,13 @@ class MyForm(settingsmixin.SMainWindow):
box.setCurrentIndex(0) box.setCurrentIndex(0)
def on_action_InboxReplyChan(self): def on_action_InboxReplyChan(self):
"""TBC"""
self.on_action_InboxReply(self.REPLY_TYPE_CHAN) self.on_action_InboxReply(self.REPLY_TYPE_CHAN)
def on_action_InboxReply(self, replyType = None): def on_action_InboxReply(self, replyType=None):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3004,7 +3492,13 @@ class MyForm(settingsmixin.SMainWindow):
if queryreturn != []: if queryreturn != []:
for row in queryreturn: for row in queryreturn:
messageAtCurrentInboxRow, = row messageAtCurrentInboxRow, = row
acct.parseMessage(toAddressAtCurrentInboxRow, fromAddressAtCurrentInboxRow, tableWidget.item(currentInboxRow, 2).subject, messageAtCurrentInboxRow) acct.parseMessage(
toAddressAtCurrentInboxRow,
fromAddressAtCurrentInboxRow,
tableWidget.item(
currentInboxRow,
2).subject,
messageAtCurrentInboxRow)
widget = { widget = {
'subject': self.ui.lineEditSubject, 'subject': self.ui.lineEditSubject,
'from': self.ui.comboBoxSendFrom, 'from': self.ui.comboBoxSendFrom,
@ -3014,13 +3508,23 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tabWidgetSend.setCurrentIndex( self.ui.tabWidgetSend.setCurrentIndex(
self.ui.tabWidgetSend.indexOf(self.ui.sendDirect) self.ui.tabWidgetSend.indexOf(self.ui.sendDirect)
) )
# toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow
elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow): elif not BMConfigParser().has_section(toAddressAtCurrentInboxRow):
QtGui.QMessageBox.information(self, _translate("MainWindow", "Address is gone"), _translate( QtGui.QMessageBox.information(
"MainWindow", "Bitmessage cannot find your address %1. Perhaps you removed it?").arg(toAddressAtCurrentInboxRow), QtGui.QMessageBox.Ok) self, _translate("MainWindow", "Address is gone"),
_translate("MainWindow", "Bitmessage cannot find your address %1. Perhaps you removed it?").arg(
toAddressAtCurrentInboxRow),
QtGui.QMessageBox.Ok)
elif not BMConfigParser().getboolean(toAddressAtCurrentInboxRow, 'enabled'): elif not BMConfigParser().getboolean(toAddressAtCurrentInboxRow, 'enabled'):
QtGui.QMessageBox.information(self, _translate("MainWindow", "Address disabled"), _translate( QtGui.QMessageBox.information(
"MainWindow", "Error: The address from which you are trying to send is disabled. You\'ll have to enable it on the \'Your Identities\' tab before using it."), QtGui.QMessageBox.Ok) self,
_translate(
"MainWindow",
"Address disabled"),
_translate(
"MainWindow",
("Error: The address from which you are trying to send is disabled. You\'ll have to enable it on "
"the \'Your Identities\' tab before using it.")),
QtGui.QMessageBox.Ok)
else: else:
self.setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(toAddressAtCurrentInboxRow) self.setBroadcastEnablementDependingOnWhetherThisIsAMailingListAddress(toAddressAtCurrentInboxRow)
broadcast_tab_index = self.ui.tabWidgetSend.indexOf( broadcast_tab_index = self.ui.tabWidgetSend.indexOf(
@ -3035,18 +3539,28 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.tabWidgetSend.setCurrentIndex(broadcast_tab_index) self.ui.tabWidgetSend.setCurrentIndex(broadcast_tab_index)
toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow toAddressAtCurrentInboxRow = fromAddressAtCurrentInboxRow
if fromAddressAtCurrentInboxRow == tableWidget.item(currentInboxRow, 1).label or ( if fromAddressAtCurrentInboxRow == tableWidget.item(currentInboxRow, 1).label or (
isinstance(acct, GatewayAccount) and fromAddressAtCurrentInboxRow == acct.relayAddress): isinstance(acct, GatewayAccount) and fromAddressAtCurrentInboxRow == acct.relayAddress):
self.ui.lineEditTo.setText(str(acct.fromAddress)) self.ui.lineEditTo.setText(str(acct.fromAddress))
else: else:
self.ui.lineEditTo.setText(tableWidget.item(currentInboxRow, 1).label + " <" + str(acct.fromAddress) + ">") self.ui.lineEditTo.setText(
''.join(
[
tableWidget.item(currentInboxRow, 1).label,
" <",
str(acct.fromAddress) + ">",
]
)
)
# If the previous message was to a chan then we should send our reply to the chan rather than to the particular person who sent the message. # If the previous message was to a chan then we should send our reply to
# the chan rather than to the particular person who sent the message.
if acct.type == AccountMixin.CHAN and replyType == self.REPLY_TYPE_CHAN: if acct.type == AccountMixin.CHAN and replyType == self.REPLY_TYPE_CHAN:
logger.debug('original sent to a chan. Setting the to address in the reply to the chan address.') logger.debug('original sent to a chan. Setting the to address in the reply to the chan address.')
if toAddressAtCurrentInboxRow == tableWidget.item(currentInboxRow, 0).label: if toAddressAtCurrentInboxRow == tableWidget.item(currentInboxRow, 0).label:
self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow)) self.ui.lineEditTo.setText(str(toAddressAtCurrentInboxRow))
else: else:
self.ui.lineEditTo.setText(tableWidget.item(currentInboxRow, 0).label + " <" + str(acct.toAddress) + ">") self.ui.lineEditTo.setText(tableWidget.item(
currentInboxRow, 0).label + " <" + str(acct.toAddress) + ">")
self.setSendFromComboBox(toAddressAtCurrentInboxRow) self.setSendFromComboBox(toAddressAtCurrentInboxRow)
@ -3062,6 +3576,8 @@ class MyForm(settingsmixin.SMainWindow):
widget['message'].setFocus() widget['message'].setFocus()
def on_action_InboxAddSenderToAddressBook(self): def on_action_InboxAddSenderToAddressBook(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3076,6 +3592,8 @@ class MyForm(settingsmixin.SMainWindow):
dialogs.AddAddressDialog(self, addressAtCurrentInboxRow)) dialogs.AddAddressDialog(self, addressAtCurrentInboxRow))
def on_action_InboxAddSenderToBlackList(self): def on_action_InboxAddSenderToBlackList(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3089,25 +3607,37 @@ class MyForm(settingsmixin.SMainWindow):
queryreturn = sqlQuery('''select * from blacklist where address=?''', queryreturn = sqlQuery('''select * from blacklist where address=?''',
addressAtCurrentInboxRow) addressAtCurrentInboxRow)
if queryreturn == []: if queryreturn == []:
label = "\"" + tableWidget.item(currentInboxRow, 2).subject + "\" in " + BMConfigParser().get(recipientAddress, "label") label = "\"" + tableWidget.item(currentInboxRow,
2).subject + "\" in " + BMConfigParser().get(recipientAddress,
"label")
sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''', sqlExecute('''INSERT INTO blacklist VALUES (?,?, ?)''',
label, label,
addressAtCurrentInboxRow, True) addressAtCurrentInboxRow, True)
self.ui.blackwhitelist.rerenderBlackWhiteList() self.ui.blackwhitelist.rerenderBlackWhiteList()
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", _translate(
"Entry added to the blacklist. Edit the label to your liking.") "MainWindow",
"Entry added to the blacklist. Edit the label to your liking."
)
) )
else: else:
self.updateStatusBar(_translate( self.updateStatusBar(
"MainWindow", _translate(
"Error: You cannot add the same address to your blacklist" "MainWindow",
" twice. Try renaming the existing one if you want.")) ("Error: You cannot add the same address to your blacklist"
" twice. Try renaming the existing one if you want.")
)
)
def deleteRowFromMessagelist(self, row=None, inventoryHash=None, ackData=None, messageLists=None):
"""TBC"""
def deleteRowFromMessagelist(self, row = None, inventoryHash = None, ackData = None, messageLists = None):
if messageLists is None: if messageLists is None:
messageLists = (self.ui.tableWidgetInbox, self.ui.tableWidgetInboxChans, self.ui.tableWidgetInboxSubscriptions) messageLists = (
elif type(messageLists) not in (list, tuple): self.ui.tableWidgetInbox,
self.ui.tableWidgetInboxChans,
self.ui.tableWidgetInboxSubscriptions)
elif not isinstance(messageLists, (list, tuple)):
messageLists = (messageLists) messageLists = (messageLists)
for messageList in messageLists: for messageList in messageLists:
if row is not None: if row is not None:
@ -3123,34 +3653,35 @@ class MyForm(settingsmixin.SMainWindow):
if messageList.item(i, 3).data(QtCore.Qt.UserRole).toPyObject() == ackData: if messageList.item(i, 3).data(QtCore.Qt.UserRole).toPyObject() == ackData:
messageList.removeRow(i) messageList.removeRow(i)
# Send item on the Inbox tab to trash
def on_action_InboxTrash(self): def on_action_InboxTrash(self):
"""Send item on the Inbox tab to trash"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
currentRow = 0 currentRow = 0
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier shifted = QtGui.QApplication.queryKeyboardModifiers() & QtCore.Qt.ShiftModifier
tableWidget.setUpdatesEnabled(False); tableWidget.setUpdatesEnabled(False)
inventoryHashesToTrash = [] inventoryHashesToTrash = []
# ranges in reversed order # ranges in reversed order
for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]: for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]:
for i in range(r.bottomRow()-r.topRow()+1): for i in range(r.bottomRow() - r.topRow() + 1):
inventoryHashToTrash = str(tableWidget.item( inventoryHashToTrash = str(tableWidget.item(
r.topRow()+i, 3).data(QtCore.Qt.UserRole).toPyObject()) r.topRow() + i, 3).data(QtCore.Qt.UserRole).toPyObject())
if inventoryHashToTrash in inventoryHashesToTrash: if inventoryHashToTrash in inventoryHashesToTrash:
continue continue
inventoryHashesToTrash.append(inventoryHashToTrash) inventoryHashesToTrash.append(inventoryHashToTrash)
currentRow = r.topRow() currentRow = r.topRow()
self.getCurrentMessageTextedit().setText("") self.getCurrentMessageTextedit().setText("")
tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1) tableWidget.model().removeRows(r.topRow(), r.bottomRow() - r.topRow() + 1)
idCount = len(inventoryHashesToTrash) idCount = len(inventoryHashesToTrash)
if folder == "trash" or shifted: if folder == "trash" or shifted:
sqlExecuteChunked('''DELETE FROM inbox WHERE msgid IN ({0})''', sqlExecuteChunked('''DELETE FROM inbox WHERE msgid IN ({0})''',
idCount, *inventoryHashesToTrash) idCount, *inventoryHashesToTrash)
else: else:
sqlExecuteChunked('''UPDATE inbox SET folder='trash' WHERE msgid IN ({0})''', sqlExecuteChunked('''UPDATE inbox SET folder='trash' WHERE msgid IN ({0})''',
idCount, *inventoryHashesToTrash) idCount, *inventoryHashesToTrash)
tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1) tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
self.propagateUnreadCount(self.getCurrentAccount, folder) self.propagateUnreadCount(self.getCurrentAccount, folder)
@ -3158,6 +3689,8 @@ class MyForm(settingsmixin.SMainWindow):
"MainWindow", "Moved items to trash.")) "MainWindow", "Moved items to trash."))
def on_action_TrashUndelete(self): def on_action_TrashUndelete(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3166,28 +3699,30 @@ class MyForm(settingsmixin.SMainWindow):
inventoryHashesToTrash = [] inventoryHashesToTrash = []
# ranges in reversed order # ranges in reversed order
for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]: for r in sorted(tableWidget.selectedRanges(), key=lambda r: r.topRow())[::-1]:
for i in range(r.bottomRow()-r.topRow()+1): for i in range(r.bottomRow() - r.topRow() + 1):
inventoryHashToTrash = str(tableWidget.item( inventoryHashToTrash = str(tableWidget.item(
r.topRow()+i, 3).data(QtCore.Qt.UserRole).toPyObject()) r.topRow() + i, 3).data(QtCore.Qt.UserRole).toPyObject())
if inventoryHashToTrash in inventoryHashesToTrash: if inventoryHashToTrash in inventoryHashesToTrash:
continue continue
inventoryHashesToTrash.append(inventoryHashToTrash) inventoryHashesToTrash.append(inventoryHashToTrash)
currentRow = r.topRow() currentRow = r.topRow()
self.getCurrentMessageTextedit().setText("") self.getCurrentMessageTextedit().setText("")
tableWidget.model().removeRows(r.topRow(), r.bottomRow()-r.topRow()+1) tableWidget.model().removeRows(r.topRow(), r.bottomRow() - r.topRow() + 1)
if currentRow == 0: if currentRow == 0:
tableWidget.selectRow(currentRow) tableWidget.selectRow(currentRow)
else: else:
tableWidget.selectRow(currentRow - 1) tableWidget.selectRow(currentRow - 1)
idCount = len(inventoryHashesToTrash) idCount = len(inventoryHashesToTrash)
sqlExecuteChunked('''UPDATE inbox SET folder='inbox' WHERE msgid IN({0})''', sqlExecuteChunked('''UPDATE inbox SET folder='inbox' WHERE msgid IN({0})''',
idCount, *inventoryHashesToTrash) idCount, *inventoryHashesToTrash)
tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1) tableWidget.selectRow(0 if currentRow == 0 else currentRow - 1)
tableWidget.setUpdatesEnabled(True) tableWidget.setUpdatesEnabled(True)
self.propagateUnreadCount(self.getCurrentAccount) self.propagateUnreadCount(self.getCurrentAccount)
self.updateStatusBar(_translate("MainWindow", "Undeleted item.")) self.updateStatusBar(_translate("MainWindow", "Undeleted item."))
def on_action_InboxSaveMessageAs(self): def on_action_InboxSaveMessageAs(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3208,7 +3743,9 @@ class MyForm(settingsmixin.SMainWindow):
message, = row message, = row
defaultFilename = "".join(x for x in subjectAtCurrentInboxRow if x.isalnum()) + '.txt' defaultFilename = "".join(x for x in subjectAtCurrentInboxRow if x.isalnum()) + '.txt'
filename = QtGui.QFileDialog.getSaveFileName(self, _translate("MainWindow","Save As..."), defaultFilename, "Text files (*.txt);;All files (*.*)") filename = QtGui.QFileDialog.getSaveFileName(
self, _translate("MainWindow", "Save As..."),
defaultFilename, "Text files (*.txt);;All files (*.*)")
if filename == '': if filename == '':
return return
try: try:
@ -3219,10 +3756,10 @@ class MyForm(settingsmixin.SMainWindow):
logger.exception('Message not saved', exc_info=True) logger.exception('Message not saved', exc_info=True)
self.updateStatusBar(_translate("MainWindow", "Write error.")) self.updateStatusBar(_translate("MainWindow", "Write error."))
# Send item on the Sent tab to trash
def on_action_SentTrash(self): def on_action_SentTrash(self):
"""Send item on the Sent tab to trash"""
currentRow = 0 currentRow = 0
unread = False
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if not tableWidget: if not tableWidget:
return return
@ -3237,7 +3774,15 @@ class MyForm(settingsmixin.SMainWindow):
else: else:
sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''', ackdataToTrash) sqlExecute('''UPDATE sent SET folder='trash' WHERE ackdata=?''', ackdataToTrash)
if tableWidget.item(currentRow, 0).unread: if tableWidget.item(currentRow, 0).unread:
self.propagateUnreadCount(tableWidget.item(currentRow, 1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0).data(QtCore.Qt.UserRole), folder, self.getCurrentTreeWidget(), -1) self.propagateUnreadCount(
tableWidget.item(
currentRow,
1 if tableWidget.item(currentRow, 1).type == AccountMixin.SUBSCRIPTION else 0
).data(QtCore.Qt.UserRole),
folder,
self.getCurrentTreeWidget(),
-1,
)
self.getCurrentMessageTextedit().setPlainText("") self.getCurrentMessageTextedit().setPlainText("")
tableWidget.removeRow(currentRow) tableWidget.removeRow(currentRow)
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
@ -3247,6 +3792,8 @@ class MyForm(settingsmixin.SMainWindow):
currentRow if currentRow == 0 else currentRow - 1) currentRow if currentRow == 0 else currentRow - 1)
def on_action_ForceSend(self): def on_action_ForceSend(self):
"""TBC"""
currentRow = self.ui.tableWidgetInbox.currentRow() currentRow = self.ui.tableWidgetInbox.currentRow()
addressAtCurrentRow = self.ui.tableWidgetInbox.item( addressAtCurrentRow = self.ui.tableWidgetInbox.item(
currentRow, 0).data(QtCore.Qt.UserRole) currentRow, 0).data(QtCore.Qt.UserRole)
@ -3262,17 +3809,22 @@ class MyForm(settingsmixin.SMainWindow):
queues.workerQueue.put(('sendmessage', '')) queues.workerQueue.put(('sendmessage', ''))
def on_action_SentClipboard(self): def on_action_SentClipboard(self):
"""TBC"""
currentRow = self.ui.tableWidgetInbox.currentRow() currentRow = self.ui.tableWidgetInbox.currentRow()
addressAtCurrentRow = self.ui.tableWidgetInbox.item( addressAtCurrentRow = self.ui.tableWidgetInbox.item(
currentRow, 0).data(QtCore.Qt.UserRole) currentRow, 0).data(QtCore.Qt.UserRole)
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(addressAtCurrentRow)) clipboard.setText(str(addressAtCurrentRow))
# Group of functions for the Address Book dialog box
def on_action_AddressBookNew(self): def on_action_AddressBookNew(self):
"""Group of functions for the Address Book dialog box"""
self.click_pushButtonAddAddressBook() self.click_pushButtonAddAddressBook()
def on_action_AddressBookDelete(self): def on_action_AddressBookDelete(self):
"""TBC"""
while self.ui.tableWidgetAddressBook.selectedIndexes() != []: while self.ui.tableWidgetAddressBook.selectedIndexes() != []:
currentRow = self.ui.tableWidgetAddressBook.selectedIndexes()[ currentRow = self.ui.tableWidgetAddressBook.selectedIndexes()[
0].row() 0].row()
@ -3287,6 +3839,8 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderMessagelistToLabels() self.rerenderMessagelistToLabels()
def on_action_AddressBookClipboard(self): def on_action_AddressBookClipboard(self):
"""TBC"""
fullStringOfAddresses = '' fullStringOfAddresses = ''
listOfSelectedRows = {} listOfSelectedRows = {}
for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())): for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())):
@ -3303,6 +3857,8 @@ class MyForm(settingsmixin.SMainWindow):
clipboard.setText(fullStringOfAddresses) clipboard.setText(fullStringOfAddresses)
def on_action_AddressBookSend(self): def on_action_AddressBookSend(self):
"""TBC"""
listOfSelectedRows = {} listOfSelectedRows = {}
for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())): for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())):
listOfSelectedRows[ listOfSelectedRows[
@ -3328,11 +3884,13 @@ class MyForm(settingsmixin.SMainWindow):
) )
def on_action_AddressBookSubscribe(self): def on_action_AddressBookSubscribe(self):
"""TBC"""
listOfSelectedRows = {} listOfSelectedRows = {}
for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())): for i in range(len(self.ui.tableWidgetAddressBook.selectedIndexes())):
listOfSelectedRows[self.ui.tableWidgetAddressBook.selectedIndexes()[i].row()] = 0 listOfSelectedRows[self.ui.tableWidgetAddressBook.selectedIndexes()[i].row()] = 0
for currentRow in listOfSelectedRows: for currentRow in listOfSelectedRows:
addressAtCurrentRow = str(self.ui.tableWidgetAddressBook.item(currentRow,1).text()) addressAtCurrentRow = str(self.ui.tableWidgetAddressBook.item(currentRow, 1).text())
# Then subscribe to it... provided it's not already in the address book # Then subscribe to it... provided it's not already in the address book
if shared.isAddressInMySubscriptionsList(addressAtCurrentRow): if shared.isAddressInMySubscriptionsList(addressAtCurrentRow):
self.updateStatusBar(_translate( self.updateStatusBar(_translate(
@ -3341,13 +3899,15 @@ class MyForm(settingsmixin.SMainWindow):
" subscriptions twice. Perhaps rename the existing" " subscriptions twice. Perhaps rename the existing"
" one if you want.")) " one if you want."))
continue continue
labelAtCurrentRow = self.ui.tableWidgetAddressBook.item(currentRow,0).text().toUtf8() labelAtCurrentRow = self.ui.tableWidgetAddressBook.item(currentRow, 0).text().toUtf8()
self.addSubscription(addressAtCurrentRow, labelAtCurrentRow) self.addSubscription(addressAtCurrentRow, labelAtCurrentRow)
self.ui.tabWidget.setCurrentIndex( self.ui.tabWidget.setCurrentIndex(
self.ui.tabWidget.indexOf(self.ui.subscriptions) self.ui.tabWidget.indexOf(self.ui.subscriptions)
) )
def on_context_menuAddressBook(self, point): def on_context_menuAddressBook(self, point):
"""TBC"""
self.popMenuAddressBook = QtGui.QMenu(self) self.popMenuAddressBook = QtGui.QMenu(self)
self.popMenuAddressBook.addAction(self.actionAddressBookSend) self.popMenuAddressBook.addAction(self.actionAddressBookSend)
self.popMenuAddressBook.addAction(self.actionAddressBookClipboard) self.popMenuAddressBook.addAction(self.actionAddressBookClipboard)
@ -3359,9 +3919,9 @@ class MyForm(settingsmixin.SMainWindow):
normal = True normal = True
for row in self.ui.tableWidgetAddressBook.selectedIndexes(): for row in self.ui.tableWidgetAddressBook.selectedIndexes():
currentRow = row.row() currentRow = row.row()
type = self.ui.tableWidgetAddressBook.item( row_type = self.ui.tableWidgetAddressBook.item(
currentRow, 0).type currentRow, 0).type
if type != AccountMixin.NORMAL: if row_type != AccountMixin.NORMAL:
normal = False normal = False
if normal: if normal:
# only if all selected addressbook items are normal, allow delete # only if all selected addressbook items are normal, allow delete
@ -3369,11 +3929,14 @@ class MyForm(settingsmixin.SMainWindow):
self.popMenuAddressBook.exec_( self.popMenuAddressBook.exec_(
self.ui.tableWidgetAddressBook.mapToGlobal(point)) self.ui.tableWidgetAddressBook.mapToGlobal(point))
# Group of functions for the Subscriptions dialog box
def on_action_SubscriptionsNew(self): def on_action_SubscriptionsNew(self):
"""Group of functions for the Subscriptions dialog box"""
self.click_pushButtonAddSubscription() self.click_pushButtonAddSubscription()
def on_action_SubscriptionsDelete(self): def on_action_SubscriptionsDelete(self):
"""TBC"""
if QtGui.QMessageBox.question( if QtGui.QMessageBox.question(
self, "Delete subscription?", self, "Delete subscription?",
_translate( _translate(
@ -3397,11 +3960,15 @@ class MyForm(settingsmixin.SMainWindow):
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_action_SubscriptionsClipboard(self): def on_action_SubscriptionsClipboard(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(address)) clipboard.setText(str(address))
def on_action_SubscriptionsEnable(self): def on_action_SubscriptionsEnable(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
sqlExecute( sqlExecute(
'''update subscriptions set enabled=1 WHERE address=?''', '''update subscriptions set enabled=1 WHERE address=?''',
@ -3412,6 +3979,8 @@ class MyForm(settingsmixin.SMainWindow):
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_action_SubscriptionsDisable(self): def on_action_SubscriptionsDisable(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
sqlExecute( sqlExecute(
'''update subscriptions set enabled=0 WHERE address=?''', '''update subscriptions set enabled=0 WHERE address=?''',
@ -3422,6 +3991,8 @@ class MyForm(settingsmixin.SMainWindow):
shared.reloadBroadcastSendersForWhichImWatching() shared.reloadBroadcastSendersForWhichImWatching()
def on_context_menuSubscriptions(self, point): def on_context_menuSubscriptions(self, point):
"""TBC"""
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenuSubscriptions = QtGui.QMenu(self) self.popMenuSubscriptions = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, Ui_AddressWidget):
@ -3444,7 +4015,9 @@ class MyForm(settingsmixin.SMainWindow):
self.popMenuSubscriptions.exec_( self.popMenuSubscriptions.exec_(
self.ui.treeWidgetSubscriptions.mapToGlobal(point)) self.ui.treeWidgetSubscriptions.mapToGlobal(point))
def widgetConvert (self, widget): def widgetConvert(self, widget): # pylint: disable=inconsistent-return-statements
"""TBC"""
if widget == self.ui.tableWidgetInbox: if widget == self.ui.tableWidgetInbox:
return self.ui.treeWidgetYourIdentities return self.ui.treeWidgetYourIdentities
elif widget == self.ui.tableWidgetInboxSubscriptions: elif widget == self.ui.tableWidgetInboxSubscriptions:
@ -3457,35 +4030,35 @@ class MyForm(settingsmixin.SMainWindow):
return self.ui.tableWidgetInboxSubscriptions return self.ui.tableWidgetInboxSubscriptions
elif widget == self.ui.treeWidgetChans: elif widget == self.ui.treeWidgetChans:
return self.ui.tableWidgetInboxChans return self.ui.tableWidgetInboxChans
else:
return None
def getCurrentTreeWidget(self): def getCurrentTreeWidget(self):
currentIndex = self.ui.tabWidget.currentIndex(); """TBC"""
currentIndex = self.ui.tabWidget.currentIndex()
treeWidgetList = [ treeWidgetList = [
self.ui.treeWidgetYourIdentities, self.ui.treeWidgetYourIdentities,
False, False,
self.ui.treeWidgetSubscriptions, self.ui.treeWidgetSubscriptions,
self.ui.treeWidgetChans self.ui.treeWidgetChans
] ]
if currentIndex >= 0 and currentIndex < len(treeWidgetList): return treeWidgetList[currentIndex] if currentIndex >= 0 and currentIndex < len(treeWidgetList) else False
return treeWidgetList[currentIndex]
else:
return False
def getAccountTreeWidget(self, account): def getAccountTreeWidget(self, account):
"""TBC"""
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
return self.ui.treeWidgetChans return self.ui.treeWidgetChans
elif account.type == AccountMixin.SUBSCRIPTION: elif account.type == AccountMixin.SUBSCRIPTION:
return self.ui.treeWidgetSubscriptions return self.ui.treeWidgetSubscriptions
else: return self.ui.treeWidgetYourIdentities
return self.ui.treeWidgetYourIdentities
except: except:
return self.ui.treeWidgetYourIdentities return self.ui.treeWidgetYourIdentities
def getCurrentMessagelist(self): def getCurrentMessagelist(self):
currentIndex = self.ui.tabWidget.currentIndex(); """TBC"""
currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
self.ui.tableWidgetInbox, self.ui.tableWidgetInbox,
False, False,
@ -3494,21 +4067,23 @@ class MyForm(settingsmixin.SMainWindow):
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex] return messagelistList[currentIndex]
else: return False
return False
def getAccountMessagelist(self, account): def getAccountMessagelist(self, account):
"""TBC"""
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
return self.ui.tableWidgetInboxChans return self.ui.tableWidgetInboxChans
elif account.type == AccountMixin.SUBSCRIPTION: elif account.type == AccountMixin.SUBSCRIPTION:
return self.ui.tableWidgetInboxSubscriptions return self.ui.tableWidgetInboxSubscriptions
else: return self.ui.tableWidgetInbox
return self.ui.tableWidgetInbox
except: except:
return self.ui.tableWidgetInbox return self.ui.tableWidgetInbox
def getCurrentMessageId(self): def getCurrentMessageId(self):
"""TBC"""
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
if messagelist: if messagelist:
currentRow = messagelist.currentRow() currentRow = messagelist.currentRow()
@ -3520,6 +4095,8 @@ class MyForm(settingsmixin.SMainWindow):
return False return False
def getCurrentMessageTextedit(self): def getCurrentMessageTextedit(self):
"""TBC"""
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
self.ui.textEditInboxMessage, self.ui.textEditInboxMessage,
@ -3529,38 +4106,41 @@ class MyForm(settingsmixin.SMainWindow):
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex] return messagelistList[currentIndex]
else: return False
return False
def getAccountTextedit(self, account): def getAccountTextedit(self, account):
"""TBC"""
try: try:
if account.type == AccountMixin.CHAN: if account.type == AccountMixin.CHAN:
return self.ui.textEditInboxMessageChans return self.ui.textEditInboxMessageChans
elif account.type == AccountMixin.SUBSCRIPTION: elif account.type == AccountMixin.SUBSCRIPTION:
return self.ui.textEditInboxSubscriptions return self.ui.textEditInboxSubscriptions
else: return self.ui.textEditInboxMessage
return self.ui.textEditInboxMessage
except: except:
return self.ui.textEditInboxMessage return self.ui.textEditInboxMessage
def getCurrentSearchLine(self, currentIndex=None, retObj=False): def getCurrentSearchLine(self, currentIndex=None, retObj=False): # pylint: disable=inconsistent-return-statements
"""TBC"""
if currentIndex is None: if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
self.ui.inboxSearchLineEdit, self.ui.inboxSearchLineEdit,
False, False,
self.ui.inboxSearchLineEditSubscriptions, self.ui.inboxSearchLineEditSubscriptions,
self.ui.inboxSearchLineEditChans, self.ui.inboxSearchLineEditChans,
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
if retObj: if retObj:
return messagelistList[currentIndex] return messagelistList[currentIndex]
else: return messagelistList[currentIndex].text().toUtf8().data()
return messagelistList[currentIndex].text().toUtf8().data()
else: def getCurrentSearchOption(self, currentIndex=None): # pylint: disable=inconsistent-return-statements
return None """TBC"""
def getCurrentSearchOption(self, currentIndex=None):
if currentIndex is None: if currentIndex is None:
currentIndex = self.ui.tabWidget.currentIndex() currentIndex = self.ui.tabWidget.currentIndex()
messagelistList = [ messagelistList = [
@ -3571,11 +4151,10 @@ class MyForm(settingsmixin.SMainWindow):
] ]
if currentIndex >= 0 and currentIndex < len(messagelistList): if currentIndex >= 0 and currentIndex < len(messagelistList):
return messagelistList[currentIndex].currentText().toUtf8().data() return messagelistList[currentIndex].currentText().toUtf8().data()
else:
return None
# Group of functions for the Your Identities dialog box
def getCurrentItem(self, treeWidget=None): def getCurrentItem(self, treeWidget=None):
"""Group of functions for the Your Identities dialog box"""
if treeWidget is None: if treeWidget is None:
treeWidget = self.getCurrentTreeWidget() treeWidget = self.getCurrentTreeWidget()
if treeWidget: if treeWidget:
@ -3585,26 +4164,27 @@ class MyForm(settingsmixin.SMainWindow):
return False return False
def getCurrentAccount(self, treeWidget=None): def getCurrentAccount(self, treeWidget=None):
"""TODO: debug msg in else?"""
currentItem = self.getCurrentItem(treeWidget) currentItem = self.getCurrentItem(treeWidget)
if currentItem: if currentItem:
account = currentItem.address account = currentItem.address
return account return account
else: return False
# TODO need debug msg?
return False def getCurrentFolder(self, treeWidget=None): # pylint: disable=inconsistent-return-statements
"""TBC"""
def getCurrentFolder(self, treeWidget=None):
if treeWidget is None: if treeWidget is None:
treeWidget = self.getCurrentTreeWidget() treeWidget = self.getCurrentTreeWidget()
#treeWidget = self.ui.treeWidgetYourIdentities
if treeWidget: if treeWidget:
currentItem = treeWidget.currentItem() currentItem = treeWidget.currentItem()
if currentItem and hasattr(currentItem, 'folderName'): if currentItem and hasattr(currentItem, 'folderName'):
return currentItem.folderName return currentItem.folderName
else:
return None
def setCurrentItemColor(self, color): def setCurrentItemColor(self, color):
"""TBC"""
treeWidget = self.getCurrentTreeWidget() treeWidget = self.getCurrentTreeWidget()
if treeWidget: if treeWidget:
brush = QtGui.QBrush() brush = QtGui.QBrush()
@ -3614,9 +4194,13 @@ class MyForm(settingsmixin.SMainWindow):
currentItem.setForeground(0, brush) currentItem.setForeground(0, brush)
def on_action_YourIdentitiesNew(self): def on_action_YourIdentitiesNew(self):
"""TBC"""
self.click_NewAddressDialog() self.click_NewAddressDialog()
def on_action_YourIdentitiesDelete(self): def on_action_YourIdentitiesDelete(self):
"""TBC"""
account = self.getCurrentItem() account = self.getCurrentItem()
if account.type == AccountMixin.NORMAL: if account.type == AccountMixin.NORMAL:
return # maybe in the future return # maybe in the future
@ -3649,39 +4233,51 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
def on_action_Enable(self): def on_action_Enable(self):
"""TBC"""
addressAtCurrentRow = self.getCurrentAccount() addressAtCurrentRow = self.getCurrentAccount()
self.enableIdentity(addressAtCurrentRow) self.enableIdentity(addressAtCurrentRow)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(True) account.setEnabled(True)
def enableIdentity(self, address): def enableIdentity(self, address):
"""TBC"""
BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'enabled', 'true')
BMConfigParser().save() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
def on_action_Disable(self): def on_action_Disable(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
self.disableIdentity(address) self.disableIdentity(address)
account = self.getCurrentItem() account = self.getCurrentItem()
account.setEnabled(False) account.setEnabled(False)
def disableIdentity(self, address): def disableIdentity(self, address):
"""TBC"""
BMConfigParser().set(str(address), 'enabled', 'false') BMConfigParser().set(str(address), 'enabled', 'false')
BMConfigParser().save() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
def on_action_Clipboard(self): def on_action_Clipboard(self):
"""TBC"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(str(address)) clipboard.setText(str(address))
def on_action_ClipboardMessagelist(self): def on_action_ClipboardMessagelist(self):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
currentColumn = tableWidget.currentColumn() currentColumn = tableWidget.currentColumn()
currentRow = tableWidget.currentRow() currentRow = tableWidget.currentRow()
if currentColumn not in [0, 1, 2]: # to, from, subject if currentColumn not in [0, 1, 2]: # to, from, subject
if self.getCurrentFolder() == "sent": if self.getCurrentFolder() == "sent":
currentColumn = 0 currentColumn = 0
else: else:
@ -3693,9 +4289,19 @@ class MyForm(settingsmixin.SMainWindow):
myAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole) myAddress = tableWidget.item(currentRow, 0).data(QtCore.Qt.UserRole)
otherAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole) otherAddress = tableWidget.item(currentRow, 1).data(QtCore.Qt.UserRole)
account = accountClass(myAddress) account = accountClass(myAddress)
if isinstance(account, GatewayAccount) and otherAddress == account.relayAddress and ( if all(
(currentColumn in [0, 2] and self.getCurrentFolder() == "sent") or [
(currentColumn in [1, 2] and self.getCurrentFolder() != "sent")): isinstance(account, GatewayAccount),
otherAddress == account.relayAddress,
any(
[
currentColumn in [0, 2] and self.getCurrentFolder() == "sent",
currentColumn in [1, 2] and self.getCurrentFolder() != "sent",
]
),
]
):
text = str(tableWidget.item(currentRow, currentColumn).label) text = str(tableWidget.item(currentRow, currentColumn).label)
else: else:
text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole) text = tableWidget.item(currentRow, currentColumn).data(QtCore.Qt.UserRole)
@ -3703,15 +4309,20 @@ class MyForm(settingsmixin.SMainWindow):
clipboard = QtGui.QApplication.clipboard() clipboard = QtGui.QApplication.clipboard()
clipboard.setText(text) clipboard.setText(text)
#set avatar functions
def on_action_TreeWidgetSetAvatar(self): def on_action_TreeWidgetSetAvatar(self):
"""set avatar functions"""
address = self.getCurrentAccount() address = self.getCurrentAccount()
self.setAvatar(address) self.setAvatar(address)
def on_action_AddressBookSetAvatar(self): def on_action_AddressBookSetAvatar(self):
"""TBC"""
self.on_action_SetAvatar(self.ui.tableWidgetAddressBook) self.on_action_SetAvatar(self.ui.tableWidgetAddressBook)
def on_action_SetAvatar(self, thisTableWidget): def on_action_SetAvatar(self, thisTableWidget):
"""TBC"""
currentRow = thisTableWidget.currentRow() currentRow = thisTableWidget.currentRow()
addressAtCurrentRow = thisTableWidget.item( addressAtCurrentRow = thisTableWidget.item(
currentRow, 1).text() currentRow, 1).text()
@ -3721,20 +4332,50 @@ class MyForm(settingsmixin.SMainWindow):
currentRow, 0).setIcon(avatarize(addressAtCurrentRow)) currentRow, 0).setIcon(avatarize(addressAtCurrentRow))
def setAvatar(self, addressAtCurrentRow): def setAvatar(self, addressAtCurrentRow):
"""TBC"""
if not os.path.exists(state.appdata + 'avatars/'): if not os.path.exists(state.appdata + 'avatars/'):
os.makedirs(state.appdata + 'avatars/') os.makedirs(state.appdata + 'avatars/')
hash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest() addressHash = hashlib.md5(addBMIfNotPresent(addressAtCurrentRow)).hexdigest()
extensions = ['PNG', 'GIF', 'JPG', 'JPEG', 'SVG', 'BMP', 'MNG', 'PBM', 'PGM', 'PPM', 'TIFF', 'XBM', 'XPM', 'TGA'] extensions = [
'PNG',
'GIF',
'JPG',
'JPEG',
'SVG',
'BMP',
'MNG',
'PBM',
'PGM',
'PPM',
'TIFF',
'XBM',
'XPM',
'TGA']
# http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats # http://pyqt.sourceforge.net/Docs/PyQt4/qimagereader.html#supportedImageFormats
names = {'BMP':'Windows Bitmap', 'GIF':'Graphic Interchange Format', 'JPG':'Joint Photographic Experts Group', 'JPEG':'Joint Photographic Experts Group', 'MNG':'Multiple-image Network Graphics', 'PNG':'Portable Network Graphics', 'PBM':'Portable Bitmap', 'PGM':'Portable Graymap', 'PPM':'Portable Pixmap', 'TIFF':'Tagged Image File Format', 'XBM':'X11 Bitmap', 'XPM':'X11 Pixmap', 'SVG':'Scalable Vector Graphics', 'TGA':'Targa Image Format'} names = {
'BMP': 'Windows Bitmap',
'GIF': 'Graphic Interchange Format',
'JPG': 'Joint Photographic Experts Group',
'JPEG': 'Joint Photographic Experts Group',
'MNG': 'Multiple-image Network Graphics',
'PNG': 'Portable Network Graphics',
'PBM': 'Portable Bitmap',
'PGM': 'Portable Graymap',
'PPM': 'Portable Pixmap',
'TIFF': 'Tagged Image File Format',
'XBM': 'X11 Bitmap',
'XPM': 'X11 Pixmap',
'SVG': 'Scalable Vector Graphics',
'TGA': 'Targa Image Format'}
filters = [] filters = []
all_images_filter = [] all_images_filter = []
current_files = [] current_files = []
for ext in extensions: for ext in extensions:
filters += [ names[ext] + ' (*.' + ext.lower() + ')' ] filters += [names[ext] + ' (*.' + ext.lower() + ')']
all_images_filter += [ '*.' + ext.lower() ] all_images_filter += ['*.' + ext.lower()]
upper = state.appdata + 'avatars/' + hash + '.' + ext.upper() upper = state.appdata + 'avatars/' + addressHash + '.' + ext.upper()
lower = state.appdata + 'avatars/' + hash + '.' + ext.lower() lower = state.appdata + 'avatars/' + addressHash + '.' + ext.lower()
if os.path.isfile(lower): if os.path.isfile(lower):
current_files += [lower] current_files += [lower]
elif os.path.isfile(upper): elif os.path.isfile(upper):
@ -3743,33 +4384,35 @@ class MyForm(settingsmixin.SMainWindow):
filters[1:1] = ['All files (*.*)'] filters[1:1] = ['All files (*.*)']
sourcefile = QtGui.QFileDialog.getOpenFileName( sourcefile = QtGui.QFileDialog.getOpenFileName(
self, _translate("MainWindow", "Set avatar..."), self, _translate("MainWindow", "Set avatar..."),
filter = ';;'.join(filters) filter=';;'.join(filters)
) )
# determine the correct filename (note that avatars don't use the suffix) # determine the correct filename (note that avatars don't use the suffix)
destination = state.appdata + 'avatars/' + hash + '.' + sourcefile.split('.')[-1] destination = state.appdata + 'avatars/' + addressHash + '.' + sourcefile.split('.')[-1]
exists = QtCore.QFile.exists(destination) exists = QtCore.QFile.exists(destination)
if sourcefile == '': if sourcefile == '':
# ask for removal of avatar # ask for removal of avatar
if exists | (len(current_files)>0): if exists | current_files:
displayMsg = _translate("MainWindow", "Do you really want to remove this avatar?") displayMsg = _translate("MainWindow", "Do you really want to remove this avatar?")
overwrite = QtGui.QMessageBox.question( overwrite = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
else: else:
# ask whether to overwrite old avatar # ask whether to overwrite old avatar
if exists | (len(current_files)>0): if exists | current_files:
displayMsg = _translate("MainWindow", "You have already set an avatar for this address. Do you really want to overwrite it?") displayMsg = _translate(
"MainWindow",
"You have already set an avatar for this address. Do you really want to overwrite it?")
overwrite = QtGui.QMessageBox.question( overwrite = QtGui.QMessageBox.question(
self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) self, 'Message', displayMsg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
else: else:
overwrite = QtGui.QMessageBox.No overwrite = QtGui.QMessageBox.No
# copy the image file to the appdata folder # copy the image file to the appdata folder
if (not exists) | (overwrite == QtGui.QMessageBox.Yes): if not exists | overwrite == QtGui.QMessageBox.Yes:
if overwrite == QtGui.QMessageBox.Yes: if overwrite == QtGui.QMessageBox.Yes:
for file in current_files: for file_name in current_files:
QtCore.QFile.remove(file) QtCore.QFile.remove(file_name)
QtCore.QFile.remove(destination) QtCore.QFile.remove(destination)
# copy it # copy it
if sourcefile != '': if sourcefile != '':
@ -3791,10 +4434,14 @@ class MyForm(settingsmixin.SMainWindow):
return True return True
def on_action_AddressBookSetSound(self): def on_action_AddressBookSetSound(self):
"""TBC"""
widget = self.ui.tableWidgetAddressBook widget = self.ui.tableWidgetAddressBook
self.setAddressSound(widget.item(widget.currentRow(), 0).text()) self.setAddressSound(widget.item(widget.currentRow(), 0).text())
def setAddressSound(self, addr): def setAddressSound(self, addr):
"""TBC"""
filters = [unicode(_translate( filters = [unicode(_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])
@ -3835,6 +4482,8 @@ class MyForm(settingsmixin.SMainWindow):
'couldn\'t copy %s to %s', sourcefile, destination) 'couldn\'t copy %s to %s', sourcefile, destination)
def on_context_menuYourIdentities(self, point): def on_context_menuYourIdentities(self, point):
"""TBC"""
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenuYourIdentities = QtGui.QMenu(self) self.popMenuYourIdentities = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, Ui_AddressWidget):
@ -3860,8 +4509,9 @@ class MyForm(settingsmixin.SMainWindow):
self.popMenuYourIdentities.exec_( self.popMenuYourIdentities.exec_(
self.ui.treeWidgetYourIdentities.mapToGlobal(point)) self.ui.treeWidgetYourIdentities.mapToGlobal(point))
# TODO make one popMenu
def on_context_menuChan(self, point): def on_context_menuChan(self, point):
"""TODO: make one popMenu"""
currentItem = self.getCurrentItem() currentItem = self.getCurrentItem()
self.popMenu = QtGui.QMenu(self) self.popMenu = QtGui.QMenu(self)
if isinstance(currentItem, Ui_AddressWidget): if isinstance(currentItem, Ui_AddressWidget):
@ -3885,6 +4535,8 @@ class MyForm(settingsmixin.SMainWindow):
self.ui.treeWidgetChans.mapToGlobal(point)) self.ui.treeWidgetChans.mapToGlobal(point))
def on_context_menuInbox(self, point): def on_context_menuInbox(self, point):
"""TBC"""
tableWidget = self.getCurrentMessagelist() tableWidget = self.getCurrentMessagelist()
if tableWidget: if tableWidget:
currentFolder = self.getCurrentFolder() currentFolder = self.getCurrentFolder()
@ -3905,9 +4557,9 @@ class MyForm(settingsmixin.SMainWindow):
self.popMenuInbox.addAction(self.actionReply) self.popMenuInbox.addAction(self.actionReply)
self.popMenuInbox.addAction(self.actionAddSenderToAddressBook) self.popMenuInbox.addAction(self.actionAddSenderToAddressBook)
self.actionClipboardMessagelist = self.ui.inboxContextMenuToolbar.addAction( self.actionClipboardMessagelist = self.ui.inboxContextMenuToolbar.addAction(
_translate("MainWindow", _translate(
"Copy subject to clipboard" if tableWidget.currentColumn() == 2 else "Copy address to clipboard" "MainWindow", "Copy subject to clipboard"
), if tableWidget.currentColumn() == 2 else "Copy address to clipboard"),
self.on_action_ClipboardMessagelist) self.on_action_ClipboardMessagelist)
self.popMenuInbox.addAction(self.actionClipboardMessagelist) self.popMenuInbox.addAction(self.actionClipboardMessagelist)
self.popMenuInbox.addSeparator() self.popMenuInbox.addSeparator()
@ -3921,6 +4573,8 @@ class MyForm(settingsmixin.SMainWindow):
self.popMenuInbox.exec_(tableWidget.mapToGlobal(point)) self.popMenuInbox.exec_(tableWidget.mapToGlobal(point))
def on_context_menuSent(self, point): def on_context_menuSent(self, point):
"""TBC"""
self.popMenuSent = QtGui.QMenu(self) self.popMenuSent = QtGui.QMenu(self)
self.popMenuSent.addAction(self.actionSentClipboard) self.popMenuSent.addAction(self.actionSentClipboard)
self.popMenuSent.addAction(self.actionTrashSentMessage) self.popMenuSent.addAction(self.actionTrashSentMessage)
@ -3940,6 +4594,8 @@ class MyForm(settingsmixin.SMainWindow):
self.popMenuSent.exec_(self.ui.tableWidgetInbox.mapToGlobal(point)) self.popMenuSent.exec_(self.ui.tableWidgetInbox.mapToGlobal(point))
def inboxSearchLineEditUpdated(self, text): def inboxSearchLineEditUpdated(self, text):
"""TBC"""
# dynamic search for too short text is slow # dynamic search for too short text is slow
if len(str(text)) < 3: if len(str(text)) < 3:
return return
@ -3951,6 +4607,8 @@ class MyForm(settingsmixin.SMainWindow):
self.loadMessagelist(messagelist, account, folder, searchOption, str(text)) self.loadMessagelist(messagelist, account, folder, searchOption, str(text))
def inboxSearchLineEditReturnPressed(self): def inboxSearchLineEditReturnPressed(self):
"""TBC"""
logger.debug("Search return pressed") logger.debug("Search return pressed")
searchLine = self.getCurrentSearchLine() searchLine = self.getCurrentSearchLine()
messagelist = self.getCurrentMessagelist() messagelist = self.getCurrentMessagelist()
@ -3963,6 +4621,8 @@ class MyForm(settingsmixin.SMainWindow):
messagelist.setFocus() messagelist.setFocus()
def treeWidgetItemClicked(self): def treeWidgetItemClicked(self):
"""TBC"""
searchLine = self.getCurrentSearchLine() searchLine = self.getCurrentSearchLine()
searchOption = self.getCurrentSearchOption() searchOption = self.getCurrentSearchOption()
messageTextedit = self.getCurrentMessageTextedit() messageTextedit = self.getCurrentMessageTextedit()
@ -3978,14 +4638,23 @@ class MyForm(settingsmixin.SMainWindow):
self.loadMessagelist(messagelist, account, folder, searchOption, searchLine) self.loadMessagelist(messagelist, account, folder, searchOption, searchLine)
def treeWidgetItemChanged(self, item, column): def treeWidgetItemChanged(self, item, column):
"""TBC"""
# only for manual edits. automatic edits (setText) are ignored # only for manual edits. automatic edits (setText) are ignored
if column != 0: if column != 0:
return return
# only account names of normal addresses (no chans/mailinglists) # only account names of normal addresses (no chans/mailinglists)
if (not isinstance(item, Ui_AddressWidget)) or (not self.getCurrentTreeWidget()) or self.getCurrentTreeWidget().currentItem() is None: if any(
[
not isinstance(item, Ui_AddressWidget),
not self.getCurrentTreeWidget(),
self.getCurrentTreeWidget().currentItem() is None,
]
):
return return
# not visible # not visible
if (not self.getCurrentItem()) or (not isinstance (self.getCurrentItem(), Ui_AddressWidget)): if (not self.getCurrentItem()) or (not isinstance(self.getCurrentItem(), Ui_AddressWidget)):
return return
# only currently selected item # only currently selected item
if item.address != self.getCurrentAccount(): if item.address != self.getCurrentAccount():
@ -4018,6 +4687,8 @@ class MyForm(settingsmixin.SMainWindow):
self.recurDepth -= 1 self.recurDepth -= 1
def tableWidgetInboxItemClicked(self): def tableWidgetInboxItemClicked(self):
"""TBC"""
folder = self.getCurrentFolder() folder = self.getCurrentFolder()
messageTextedit = self.getCurrentMessageTextedit() messageTextedit = self.getCurrentMessageTextedit()
if not messageTextedit: if not messageTextedit:
@ -4048,10 +4719,12 @@ class MyForm(settingsmixin.SMainWindow):
if tableWidget.item(currentRow, 0).unread is True: if tableWidget.item(currentRow, 0).unread is True:
self.updateUnreadStatus(tableWidget, currentRow, msgid) self.updateUnreadStatus(tableWidget, currentRow, msgid)
# propagate # propagate
if folder != 'sent' and sqlExecute( if all(
'''UPDATE inbox SET read=1 WHERE msgid=? AND read=0''', [
msgid folder != 'sent',
) > 0: sqlExecute('''UPDATE inbox SET read=1 WHERE msgid=? AND read=0''', msgid) > 0,
]
):
self.propagateUnreadCount() self.propagateUnreadCount()
messageTextedit.setCurrentFont(QtGui.QFont()) messageTextedit.setCurrentFont(QtGui.QFont())
@ -4059,23 +4732,29 @@ class MyForm(settingsmixin.SMainWindow):
messageTextedit.setContent(message) messageTextedit.setContent(message)
def tableWidgetAddressBookItemChanged(self, item): def tableWidgetAddressBookItemChanged(self, item):
"""TBC"""
if item.type == AccountMixin.CHAN: if item.type == AccountMixin.CHAN:
self.rerenderComboBoxSendFrom() self.rerenderComboBoxSendFrom()
self.rerenderMessagelistFromLabels() self.rerenderMessagelistFromLabels()
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, this_item in enumerate(completerList):
if unicode(completerList[i]).endswith(" <" + item.address + ">"): if unicode(this_item).endswith(" <" + item.address + ">"):
completerList[i] = item.label + " <" + item.address + ">" this_item = item.label + " <" + item.address + ">"
self.ui.lineEditTo.completer().model().setStringList(completerList) self.ui.lineEditTo.completer().model().setStringList(completerList)
def tabWidgetCurrentChanged(self, n): def tabWidgetCurrentChanged(self, n):
"""TBC"""
if n == self.ui.tabWidget.indexOf(self.ui.networkstatus): if n == self.ui.tabWidget.indexOf(self.ui.networkstatus):
self.ui.networkstatus.startUpdate() self.ui.networkstatus.startUpdate()
else: else:
self.ui.networkstatus.stopUpdate() self.ui.networkstatus.stopUpdate()
def writeNewAddressToTable(self, label, address, streamNumber): def writeNewAddressToTable(self, label, address, streamNumber):
"""TBC"""
self.rerenderTabTreeMessages() self.rerenderTabTreeMessages()
self.rerenderTabTreeSubscriptions() self.rerenderTabTreeSubscriptions()
self.rerenderTabTreeChans() self.rerenderTabTreeChans()
@ -4084,14 +4763,16 @@ class MyForm(settingsmixin.SMainWindow):
self.rerenderAddressBook() self.rerenderAddressBook()
def updateStatusBar(self, data): def updateStatusBar(self, data):
if type(data) is tuple or type(data) is list: """TBC"""
if isinstance(data, (tuple, list)):
option = data[1] option = data[1]
message = data[0] message = data[0]
else: else:
option = 0 option = 0
message = data message = data
if message != "": if message != "":
logger.info('Status bar: ' + message) logger.info('Status bar: %s', message)
if option == 1: if option == 1:
self.statusbar.addImportant(message) self.statusbar.addImportant(message)
@ -4099,6 +4780,8 @@ class MyForm(settingsmixin.SMainWindow):
self.statusbar.showMessage(message, 10000) self.statusbar.showMessage(message, 10000)
def initSettings(self): def initSettings(self):
"""TBC"""
QtCore.QCoreApplication.setOrganizationName("PyBitmessage") QtCore.QCoreApplication.setOrganizationName("PyBitmessage")
QtCore.QCoreApplication.setOrganizationDomain("bitmessage.org") QtCore.QCoreApplication.setOrganizationDomain("bitmessage.org")
QtCore.QCoreApplication.setApplicationName("pybitmessageqt") QtCore.QCoreApplication.setApplicationName("pybitmessageqt")
@ -4112,8 +4795,11 @@ class MyForm(settingsmixin.SMainWindow):
class settingsDialog(QtGui.QDialog): class settingsDialog(QtGui.QDialog):
"""TBC"""
def __init__(self, parent): def __init__(self, parent):
"""TBC"""
QtGui.QWidget.__init__(self, parent) QtGui.QWidget.__init__(self, parent)
self.ui = Ui_settingsDialog() self.ui = Ui_settingsDialog()
self.ui.setupUi(self) self.ui.setupUi(self)
@ -4202,16 +4888,36 @@ class settingsDialog(QtGui.QDialog):
BMConfigParser().get('bitmessagesettings', 'maxoutboundconnections'))) BMConfigParser().get('bitmessagesettings', 'maxoutboundconnections')))
# Demanded difficulty tab # Demanded difficulty tab
self.ui.lineEditTotalDifficulty.setText(str((float(BMConfigParser().getint( self.ui.lineEditTotalDifficulty.setText(
'bitmessagesettings', 'defaultnoncetrialsperbyte')) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) str(
self.ui.lineEditSmallMessageDifficulty.setText(str((float(BMConfigParser().getint( float(
'bitmessagesettings', 'defaultpayloadlengthextrabytes')) / defaults.networkDefaultPayloadLengthExtraBytes))) BMConfigParser().getint('bitmessagesettings', 'defaultnoncetrialsperbyte')
) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte
)
)
self.ui.lineEditSmallMessageDifficulty.setText(
str(
float(
BMConfigParser().getint('bitmessagesettings', 'defaultpayloadlengthextrabytes')
) / defaults.networkDefaultPayloadLengthExtraBytes
)
)
# Max acceptable difficulty tab # Max acceptable difficulty tab
self.ui.lineEditMaxAcceptableTotalDifficulty.setText(str((float(BMConfigParser().getint( self.ui.lineEditMaxAcceptableTotalDifficulty.setText(
'bitmessagesettings', 'maxacceptablenoncetrialsperbyte')) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte))) str(
self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(str((float(BMConfigParser().getint( float(
'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')) / defaults.networkDefaultPayloadLengthExtraBytes))) BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte')
) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte
)
)
self.ui.lineEditMaxAcceptableSmallMessageDifficulty.setText(
str(
float(
BMConfigParser().getint('bitmessagesettings', 'maxacceptablepayloadlengthextrabytes')
) / defaults.networkDefaultPayloadLengthExtraBytes
)
)
# OpenCL # OpenCL
if openclpow.openclAvailable(): if openclpow.openclAvailable():
@ -4256,34 +4962,17 @@ class settingsDialog(QtGui.QDialog):
QtCore.QObject.connect(self.ui.pushButtonNamecoinTest, QtCore.SIGNAL( QtCore.QObject.connect(self.ui.pushButtonNamecoinTest, QtCore.SIGNAL(
"clicked()"), self.click_pushButtonNamecoinTest) "clicked()"), self.click_pushButtonNamecoinTest)
#Message Resend tab # Message Resend tab
self.ui.lineEditDays.setText(str( self.ui.lineEditDays.setText(str(
BMConfigParser().get('bitmessagesettings', 'stopresendingafterxdays'))) BMConfigParser().get('bitmessagesettings', 'stopresendingafterxdays')))
self.ui.lineEditMonths.setText(str( self.ui.lineEditMonths.setText(str(
BMConfigParser().get('bitmessagesettings', 'stopresendingafterxmonths'))) BMConfigParser().get('bitmessagesettings', 'stopresendingafterxmonths')))
#'System' tab removed for now.
"""try:
maxCores = BMConfigParser().getint('bitmessagesettings', 'maxcores')
except:
maxCores = 99999
if maxCores <= 1:
self.ui.comboBoxMaxCores.setCurrentIndex(0)
elif maxCores == 2:
self.ui.comboBoxMaxCores.setCurrentIndex(1)
elif maxCores <= 4:
self.ui.comboBoxMaxCores.setCurrentIndex(2)
elif maxCores <= 8:
self.ui.comboBoxMaxCores.setCurrentIndex(3)
elif maxCores <= 16:
self.ui.comboBoxMaxCores.setCurrentIndex(4)
else:
self.ui.comboBoxMaxCores.setCurrentIndex(5)"""
QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self)) QtGui.QWidget.resize(self, QtGui.QWidget.sizeHint(self))
def comboBoxProxyTypeChanged(self, comboBoxIndex): def comboBoxProxyTypeChanged(self, comboBoxIndex):
"""TBC"""
if comboBoxIndex == 0: if comboBoxIndex == 0:
self.ui.lineEditSocksHostname.setEnabled(False) self.ui.lineEditSocksHostname.setEnabled(False)
self.ui.lineEditSocksPort.setEnabled(False) self.ui.lineEditSocksPort.setEnabled(False)
@ -4300,17 +4989,19 @@ class settingsDialog(QtGui.QDialog):
self.ui.lineEditSocksUsername.setEnabled(True) self.ui.lineEditSocksUsername.setEnabled(True)
self.ui.lineEditSocksPassword.setEnabled(True) self.ui.lineEditSocksPassword.setEnabled(True)
# Check status of namecoin integration radio buttons and translate
# it to a string as in the options.
def getNamecoinType(self): def getNamecoinType(self):
"""Check status of namecoin integration radio buttons and translate it to a string as in the options."""
if self.ui.radioButtonNamecoinNamecoind.isChecked(): if self.ui.radioButtonNamecoinNamecoind.isChecked():
return "namecoind" return "namecoind"
if self.ui.radioButtonNamecoinNmcontrol.isChecked(): elif self.ui.radioButtonNamecoinNmcontrol.isChecked():
return "nmcontrol" return "nmcontrol"
assert False logger.info("Neither namecoind nor nmcontrol were checked. This is a fatal error")
sys.exit(1)
# Namecoin connection type was changed.
def namecoinTypeChanged(self, checked): def namecoinTypeChanged(self, checked):
"""Namecoin connection type was changed."""
nmctype = self.getNamecoinType() nmctype = self.getNamecoinType()
assert nmctype == "namecoind" or nmctype == "nmcontrol" assert nmctype == "namecoind" or nmctype == "nmcontrol"
@ -4325,10 +5016,11 @@ class settingsDialog(QtGui.QDialog):
else: else:
self.ui.lineEditNamecoinPort.setText("9000") self.ui.lineEditNamecoinPort.setText("9000")
# Test the namecoin settings specified in the settings dialog.
def click_pushButtonNamecoinTest(self): def click_pushButtonNamecoinTest(self):
"""Test the namecoin settings specified in the settings dialog."""
self.ui.labelNamecoinTestResult.setText(_translate( self.ui.labelNamecoinTestResult.setText(_translate(
"MainWindow", "Testing...")) "MainWindow", "Testing..."))
options = {} options = {}
options["type"] = self.getNamecoinType() options["type"] = self.getNamecoinType()
options["host"] = str(self.ui.lineEditNamecoinHost.text().toUtf8()) options["host"] = str(self.ui.lineEditNamecoinHost.text().toUtf8())
@ -4340,14 +5032,15 @@ class settingsDialog(QtGui.QDialog):
responseStatus = response[0] responseStatus = response[0]
responseText = response[1] responseText = response[1]
self.ui.labelNamecoinTestResult.setText(responseText) self.ui.labelNamecoinTestResult.setText(responseText)
if responseStatus== 'success': if responseStatus == 'success':
self.parent.ui.pushButtonFetchNamecoinID.show() self.parent.ui.pushButtonFetchNamecoinID.show()
# In order for the time columns on the Inbox and Sent tabs to be sorted
# correctly (rather than alphabetically), we need to overload the <
# operator and use this class instead of QTableWidgetItem.
class myTableWidgetItem(QtGui.QTableWidgetItem): class myTableWidgetItem(QtGui.QTableWidgetItem):
"""
In order for the time columns on the Inbox and Sent tabs to be sorted correctly (rather than alphabetically),
we need to overload the < operator and use this class instead of QTableWidgetItem.
"""
def __lt__(self, other): def __lt__(self, other):
return int(self.data(33).toPyObject()) < int(other.data(33).toPyObject()) return int(self.data(33).toPyObject()) < int(other.data(33).toPyObject())
@ -4370,21 +5063,23 @@ class MySingleApplication(QtGui.QApplication):
uuid = '6ec0149b-96e1-4be1-93ab-1465fb3ebf7c' uuid = '6ec0149b-96e1-4be1-93ab-1465fb3ebf7c'
def __init__(self, *argv): def __init__(self, *argv):
"""TBC"""
super(MySingleApplication, self).__init__(*argv) super(MySingleApplication, self).__init__(*argv)
id = MySingleApplication.uuid _id = MySingleApplication.uuid
self.server = None self.server = None
self.is_running = False self.is_running = False
socket = QLocalSocket() socket = QLocalSocket()
socket.connectToServer(id) socket.connectToServer(_id)
self.is_running = socket.waitForConnected() self.is_running = socket.waitForConnected()
# Cleanup past crashed servers # Cleanup past crashed servers
if not self.is_running: if not self.is_running:
if socket.error() == QLocalSocket.ConnectionRefusedError: if socket.error() == QLocalSocket.ConnectionRefusedError:
socket.disconnectFromServer() socket.disconnectFromServer()
QLocalServer.removeServer(id) QLocalServer.removeServer(_id)
socket.abort() socket.abort()
@ -4396,34 +5091,44 @@ class MySingleApplication(QtGui.QApplication):
# Nope, create a local server with this id and assign on_new_connection # Nope, create a local server with this id and assign on_new_connection
# for whenever a second instance tries to run focus the application. # for whenever a second instance tries to run focus the application.
self.server = QLocalServer() self.server = QLocalServer()
self.server.listen(id) self.server.listen(_id)
self.server.newConnection.connect(self.on_new_connection) self.server.newConnection.connect(self.on_new_connection)
def __del__(self): def __del__(self):
"""TBC"""
if self.server: if self.server:
self.server.close() self.server.close()
def on_new_connection(self): def on_new_connection(self):
"""TBC"""
if myapp: if myapp:
myapp.appIndicatorShow() myapp.appIndicatorShow()
def init(): def init():
"""TBC"""
global app global app
if not app: if not app:
app = MySingleApplication(sys.argv) app = MySingleApplication(sys.argv)
return app return app
def run(): def run():
"""Run the gui"""
global myapp global myapp
app = init()
running_app = init()
change_translation(l10n.getTranslationLanguage()) change_translation(l10n.getTranslationLanguage())
app.setStyleSheet("QStatusBar::item { border: 0px solid black }") app.setStyleSheet("QStatusBar::item { border: 0px solid black }")
myapp = MyForm() myapp = MyForm()
myapp.sqlInit() myapp.sqlInit()
myapp.appIndicatorInit(app) myapp.appIndicatorInit(running_app)
myapp.indicatorInit() myapp.indicatorInit()
myapp.notifierInit() myapp.notifierInit()
myapp._firstrun = BMConfigParser().safeGetBoolean( myapp._firstrun = BMConfigParser().safeGetBoolean(
@ -4432,12 +5137,6 @@ def run():
myapp.showConnectDialog() # ask the user if we may connect myapp.showConnectDialog() # ask the user if we may connect
myapp.ui.updateNetworkSwitchMenuLabel() myapp.ui.updateNetworkSwitchMenuLabel()
# try:
# if BMConfigParser().get('bitmessagesettings', 'mailchuck') < 1:
# myapp.showMigrationWizard(BMConfigParser().get('bitmessagesettings', 'mailchuck'))
# except:
# myapp.showMigrationWizard(0)
# only show after wizards and connect dialogs have completed # only show after wizards and connect dialogs have completed
if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'): if not BMConfigParser().getboolean('bitmessagesettings', 'startintray'):
myapp.show() myapp.show()

View File

@ -1,82 +0,0 @@
import pickle
import socket
from struct import *
import time
import random
import sys
from time import strftime, localtime
import state
def createDefaultKnownNodes(appdata):
############## Stream 1 ################
stream1 = {}
#stream1[state.Peer('2604:2000:1380:9f:82e:148b:2746:d0c7', 8080)] = int(time.time())
stream1[state.Peer('5.45.99.75', 8444)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('75.167.159.54', 8444)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('95.165.168.168', 8444)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('85.180.139.241', 8444)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('158.222.217.190', 8080)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('178.62.12.187', 8448)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('24.188.198.204', 8111)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('109.147.204.113', 1195)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
stream1[state.Peer('178.11.46.221', 8444)] = {"lastseen": int(time.time()), "rating": 0, "self": False}
############# Stream 2 #################
stream2 = {}
# None yet
############# Stream 3 #################
stream3 = {}
# None yet
allKnownNodes = {}
allKnownNodes[1] = stream1
allKnownNodes[2] = stream2
allKnownNodes[3] = stream3
#print stream1
#print allKnownNodes
with open(appdata + 'knownnodes.dat', 'wb') as output:
# Pickle dictionary using protocol 0.
pickle.dump(allKnownNodes, output)
return allKnownNodes
def readDefaultKnownNodes(appdata):
pickleFile = open(appdata + 'knownnodes.dat', 'rb')
knownNodes = pickle.load(pickleFile)
pickleFile.close()
for stream, storedValue in knownNodes.items():
for host,value in storedValue.items():
try:
# Old knownNodes format.
port, storedtime = value
except:
# New knownNodes format.
host, port = host
storedtime = value
print host, '\t', port, '\t', unicode(strftime('%a, %d %b %Y %I:%M %p',localtime(storedtime)),'utf-8')
if __name__ == "__main__":
APPNAME = "PyBitmessage"
from os import path, environ
if sys.platform == 'darwin':
from AppKit import NSSearchPathForDirectoriesInDomains # @UnresolvedImport
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
# NSApplicationSupportDirectory = 14
# NSUserDomainMask = 1
# True for expanding the tilde into a fully qualified path
appdata = path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME) + '/'
elif 'win' in sys.platform:
appdata = path.join(environ['APPDATA'], APPNAME) + '\\'
else:
appdata = path.expanduser(path.join("~", "." + APPNAME + "/"))
print 'New list of all known nodes:', createDefaultKnownNodes(appdata)
readDefaultKnownNodes(appdata)

View File

@ -1,52 +1,21 @@
import socket import socket
import defaultKnownNodes
import pickle # nosec
import time
from bmconfigparser import BMConfigParser
from debug import logger
import knownnodes import knownnodes
import socks import socks
import state import state
from bmconfigparser import BMConfigParser
from debug import logger
def addKnownNode(stream, peer, lastseen=None, self=False):
if lastseen is None:
lastseen = time.time()
knownnodes.knownNodes[stream][peer] = {
"lastseen": lastseen,
"rating": 0,
"self": self,
}
def knownNodes():
try:
with open(state.appdata + 'knownnodes.dat', 'rb') as pickleFile:
with knownnodes.knownNodesLock:
knownnodes.knownNodes = pickle.load(pickleFile) # nosec
# the old format was {Peer:lastseen, ...}
# the new format is {Peer:{"lastseen":i, "rating":f}}
for stream in knownnodes.knownNodes.keys():
for node, params in knownnodes.knownNodes[stream].items():
if isinstance(params, (float, int)):
addKnownNode(stream, node, params)
except:
knownnodes.knownNodes = defaultKnownNodes.createDefaultKnownNodes(state.appdata)
# your own onion address, if setup
if BMConfigParser().has_option('bitmessagesettings', 'onionhostname') and ".onion" in BMConfigParser().get('bitmessagesettings', 'onionhostname'):
addKnownNode(1, state.Peer(BMConfigParser().get('bitmessagesettings', 'onionhostname'), BMConfigParser().getint('bitmessagesettings', 'onionport')), self=True)
if BMConfigParser().getint('bitmessagesettings', 'settingsversion') > 10:
logger.error('Bitmessage cannot read future versions of the keys file (keys.dat). Run the newer version of Bitmessage.')
raise SystemExit
def dns(): def dns():
# DNS bootstrap. This could be programmed to use the SOCKS proxy to do the """
# DNS lookup some day but for now we will just rely on the entries in DNS bootstrap. This could be programmed to use the SOCKS proxy to do the
# defaultKnownNodes.py. Hopefully either they are up to date or the user DNS lookup some day but for now we will just rely on the entries in
# has run Bitmessage recently without SOCKS turned on and received good defaultKnownNodes.py. Hopefully either they are up to date or the user
# bootstrap nodes using that method. has run Bitmessage recently without SOCKS turned on and received good
bootstrap nodes using that method.
"""
def try_add_known_node(stream, addr, port, method=''): def try_add_known_node(stream, addr, port, method=''):
try: try:
socket.inet_aton(addr) socket.inet_aton(addr)
@ -55,7 +24,7 @@ def dns():
logger.info( logger.info(
'Adding %s to knownNodes based on %s DNS bootstrap method', 'Adding %s to knownNodes based on %s DNS bootstrap method',
addr, method) addr, method)
addKnownNode(stream, state.Peer(addr, port)) knownnodes.addKnownNode(stream, state.Peer(addr, port))
proxy_type = BMConfigParser().get('bitmessagesettings', 'socksproxytype') proxy_type = BMConfigParser().get('bitmessagesettings', 'socksproxytype')
@ -71,7 +40,7 @@ def dns():
port, exc_info=True port, exc_info=True
) )
elif proxy_type == 'SOCKS5': elif proxy_type == 'SOCKS5':
addKnownNode(1, state.Peer('quzwelsuziwqgpt2.onion', 8444)) knownnodes.addKnownNode(1, state.Peer('quzwelsuziwqgpt2.onion', 8444))
logger.debug("Adding quzwelsuziwqgpt2.onion:8444 to knownNodes.") logger.debug("Adding quzwelsuziwqgpt2.onion:8444 to knownNodes.")
for port in [8080, 8444]: for port in [8080, 8444]:
logger.debug("Resolving %i through SOCKS...", port) logger.debug("Resolving %i through SOCKS...", port)
@ -84,14 +53,19 @@ def dns():
'bitmessagesettings', 'sockshostname') 'bitmessagesettings', 'sockshostname')
socksport = BMConfigParser().getint( socksport = BMConfigParser().getint(
'bitmessagesettings', 'socksport') 'bitmessagesettings', 'socksport')
rdns = True # Do domain name lookups through the proxy; though this setting doesn't really matter since we won't be doing any domain name lookups anyway. # Do domain name lookups through the proxy;
if BMConfigParser().getboolean('bitmessagesettings', 'socksauthentication'): # though this setting doesn't really matter since we won't
# be doing any domain name lookups anyway.
rdns = True
if BMConfigParser().getboolean(
'bitmessagesettings', 'socksauthentication'):
socksusername = BMConfigParser().get( socksusername = BMConfigParser().get(
'bitmessagesettings', 'socksusername') 'bitmessagesettings', 'socksusername')
sockspassword = BMConfigParser().get( sockspassword = BMConfigParser().get(
'bitmessagesettings', 'sockspassword') 'bitmessagesettings', 'sockspassword')
sock.setproxy( sock.setproxy(
proxytype, sockshostname, socksport, rdns, socksusername, sockspassword) proxytype, sockshostname, socksport, rdns,
socksusername, sockspassword)
else: else:
sock.setproxy( sock.setproxy(
proxytype, sockshostname, socksport, rdns) proxytype, sockshostname, socksport, rdns)

View File

@ -1,24 +1,120 @@
import pickle import json
import os import os
import pickle
# import sys
import threading import threading
import time
from bmconfigparser import BMConfigParser
import state import state
from bmconfigparser import BMConfigParser
from debug import logger
knownNodesLock = threading.Lock() knownNodesLock = threading.Lock()
knownNodes = {} knownNodes = {stream: {} for stream in range(1, 4)}
knownNodesTrimAmount = 2000 knownNodesTrimAmount = 2000
# forget a node after rating is this low # forget a node after rating is this low
knownNodesForgetRating = -0.5 knownNodesForgetRating = -0.5
def saveKnownNodes(dirName = None): DEFAULT_NODES = (
state.Peer('5.45.99.75', 8444),
state.Peer('75.167.159.54', 8444),
state.Peer('95.165.168.168', 8444),
state.Peer('85.180.139.241', 8444),
state.Peer('158.222.217.190', 8080),
state.Peer('178.62.12.187', 8448),
state.Peer('24.188.198.204', 8111),
state.Peer('109.147.204.113', 1195),
state.Peer('178.11.46.221', 8444)
)
def json_serialize_knownnodes(output):
"""
Reorganize knownnodes dict and write it as JSON to output
"""
_serialized = []
for stream, peers in knownNodes.iteritems():
for peer, info in peers.iteritems():
_serialized.append({
'stream': stream, 'peer': peer._asdict(), 'info': info
})
json.dump(_serialized, output, indent=4)
def json_deserialize_knownnodes(source):
"""
Read JSON from source and make knownnodes dict
"""
for node in json.load(source):
peer = node['peer']
peer['host'] = str(peer['host'])
knownNodes[node['stream']][state.Peer(**peer)] = node['info']
def pickle_deserialize_old_knownnodes(source):
"""
Unpickle source and reorganize knownnodes dict if it's in old format
the old format was {Peer:lastseen, ...}
the new format is {Peer:{"lastseen":i, "rating":f}}
"""
knownNodes = pickle.load(source)
for stream in knownNodes.keys():
for node, params in knownNodes[stream].items():
if isinstance(params, (float, int)):
addKnownNode(stream, node, params)
def saveKnownNodes(dirName=None):
if dirName is None: if dirName is None:
dirName = state.appdata dirName = state.appdata
with knownNodesLock: with knownNodesLock:
with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output: with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output:
pickle.dump(knownNodes, output) json_serialize_knownnodes(output)
def addKnownNode(stream, peer, lastseen=None, is_self=False):
knownNodes[stream][peer] = {
"lastseen": lastseen or time.time(),
"rating": 0,
"self": is_self,
}
def createDefaultKnownNodes():
for peer in DEFAULT_NODES:
addKnownNode(1, peer)
saveKnownNodes()
def readKnownNodes():
try:
with open(state.appdata + 'knownnodes.dat', 'rb') as source:
with knownNodesLock:
try:
json_deserialize_knownnodes(source)
except ValueError:
source.seek(0)
pickle_deserialize_old_knownnodes(source)
except (IOError, OSError, KeyError):
logger.debug(
'Failed to read nodes from knownnodes.dat', exc_info=True)
createDefaultKnownNodes()
config = BMConfigParser()
# if config.safeGetInt('bitmessagesettings', 'settingsversion') > 10:
# sys.exit(
# 'Bitmessage cannot read future versions of the keys file'
# ' (keys.dat). Run the newer version of Bitmessage.')
# your own onion address, if setup
onionhostname = config.safeGet('bitmessagesettings', 'onionhostname')
if onionhostname and ".onion" in onionhostname:
onionport = config.safeGetInt('bitmessagesettings', 'onionport')
if onionport:
addKnownNode(1, state.Peer(onionhostname, onionport), is_self=True)
def increaseRating(peer): def increaseRating(peer):
increaseAmount = 0.1 increaseAmount = 0.1
@ -26,24 +122,36 @@ def increaseRating(peer):
with knownNodesLock: with knownNodesLock:
for stream in knownNodes.keys(): for stream in knownNodes.keys():
try: try:
knownNodes[stream][peer]["rating"] = min(knownNodes[stream][peer]["rating"] + increaseAmount, maxRating) knownNodes[stream][peer]["rating"] = min(
knownNodes[stream][peer]["rating"] + increaseAmount,
maxRating
)
except KeyError: except KeyError:
pass pass
def decreaseRating(peer): def decreaseRating(peer):
decreaseAmount = 0.1 decreaseAmount = 0.1
minRating = -1 minRating = -1
with knownNodesLock: with knownNodesLock:
for stream in knownNodes.keys(): for stream in knownNodes.keys():
try: try:
knownNodes[stream][peer]["rating"] = max(knownNodes[stream][peer]["rating"] - decreaseAmount, minRating) knownNodes[stream][peer]["rating"] = max(
knownNodes[stream][peer]["rating"] - decreaseAmount,
minRating
)
except KeyError: except KeyError:
pass pass
def trimKnownNodes(recAddrStream = 1):
if len(knownNodes[recAddrStream]) < int(BMConfigParser().get("knownnodes", "maxnodes")): def trimKnownNodes(recAddrStream=1):
if len(knownNodes[recAddrStream]) < \
BMConfigParser().safeGetInt("knownnodes", "maxnodes"):
return return
with knownNodesLock: with knownNodesLock:
oldestList = sorted(knownNodes[recAddrStream], key=lambda x: x['lastseen'])[:knownNodesTrimAmount] oldestList = sorted(
knownNodes[recAddrStream],
key=lambda x: x['lastseen']
)[:knownNodesTrimAmount]
for oldest in oldestList: for oldest in oldestList:
del knownNodes[recAddrStream][oldest] del knownNodes[recAddrStream][oldest]

View File

@ -1,6 +1,17 @@
# pylint: disable=too-many-boolean-expressions,too-many-return-statements,too-many-locals,too-many-statements
"""
protocol.py
===========
Low-level protocol-related functions.
"""
from __future__ import absolute_import
import base64 import base64
from binascii import hexlify from binascii import hexlify
import hashlib import hashlib
import os
import random import random
import socket import socket
import ssl import ssl
@ -9,31 +20,32 @@ import sys
import time import time
import traceback import traceback
import defaults
import highlevelcrypto
import state
from addresses import calculateInventoryHash, encodeVarint, decodeVarint, decodeAddress, varintDecodeError from addresses import calculateInventoryHash, encodeVarint, decodeVarint, decodeAddress, varintDecodeError
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger
import defaults
from helper_sql import sqlExecute from helper_sql import sqlExecute
import highlevelcrypto
from inventory import Inventory from inventory import Inventory
from queues import objectProcessorQueue from queues import objectProcessorQueue
import state
from version import softwareVersion from version import softwareVersion
#Service flags
# Service flags
NODE_NETWORK = 1 NODE_NETWORK = 1
NODE_SSL = 2 NODE_SSL = 2
NODE_DANDELION = 8 NODE_DANDELION = 8
#Bitfield flags # Bitfield flags
BITFIELD_DOESACK = 1 BITFIELD_DOESACK = 1
#Error types # Error types
STATUS_WARNING = 0 STATUS_WARNING = 0
STATUS_ERROR = 1 STATUS_ERROR = 1
STATUS_FATAL = 2 STATUS_FATAL = 2
#Object types # Object types
OBJECT_GETPUBKEY = 0 OBJECT_GETPUBKEY = 0
OBJECT_PUBKEY = 1 OBJECT_PUBKEY = 1
OBJECT_MSG = 2 OBJECT_MSG = 2
@ -44,15 +56,17 @@ OBJECT_ADDR = 0x61646472
eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack( eightBytesOfRandomDataUsedToDetectConnectionsToSelf = pack(
'>Q', random.randrange(1, 18446744073709551615)) '>Q', random.randrange(1, 18446744073709551615))
#Compiled struct for packing/unpacking headers # Compiled struct for packing/unpacking headers
#New code should use CreatePacket instead of Header.pack # New code should use CreatePacket instead of Header.pack
Header = Struct('!L12sL4s') Header = Struct('!L12sL4s')
VersionPacket = Struct('>LqQ20s4s36sH') VersionPacket = Struct('>LqQ20s4s36sH')
# Bitfield # Bitfield
def getBitfield(address): def getBitfield(address):
"""Get a bitfield from an address"""
# bitfield of features supported by me (see the wiki). # bitfield of features supported by me (see the wiki).
bitfield = 0 bitfield = 0
# send ack # send ack
@ -60,36 +74,45 @@ def getBitfield(address):
bitfield |= BITFIELD_DOESACK bitfield |= BITFIELD_DOESACK
return pack('>I', bitfield) return pack('>I', bitfield)
def checkBitfield(bitfieldBinary, flags): def checkBitfield(bitfieldBinary, flags):
"""Check if a bitfield matches the given flags"""
bitfield, = unpack('>I', bitfieldBinary) bitfield, = unpack('>I', bitfieldBinary)
return (bitfield & flags) == flags return (bitfield & flags) == flags
def isBitSetWithinBitfield(fourByteString, n): def isBitSetWithinBitfield(fourByteString, n):
"""Check if a particular bit is set in a bitfeld"""
# Uses MSB 0 bit numbering across 4 bytes of data # Uses MSB 0 bit numbering across 4 bytes of data
n = 31 - n n = 31 - n
x, = unpack('>L', fourByteString) x, = unpack('>L', fourByteString)
return x & 2**n != 0 return x & 2**n != 0
# ip addresses # ip addresses
def encodeHost(host): def encodeHost(host):
"""Encode a given host to be used in low-level socket operations"""
if host.find('.onion') > -1: if host.find('.onion') > -1:
return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True) return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(host.split(".")[0], True)
elif host.find(':') == -1: elif host.find(':') == -1:
return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \ return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
socket.inet_aton(host) socket.inet_aton(host)
else: return socket.inet_pton(socket.AF_INET6, host)
return socket.inet_pton(socket.AF_INET6, host)
def networkType(host): def networkType(host):
"""Determine if a host is IPv4, IPv6 or an onion address"""
if host.find('.onion') > -1: if host.find('.onion') > -1:
return 'onion' return 'onion'
elif host.find(':') == -1: elif host.find(':') == -1:
return 'IPv4' return 'IPv4'
else: return 'IPv6'
return 'IPv6'
def checkIPAddress(host, private=False): def checkIPAddress(host, private=False):
"""Returns hostStandardFormat if it is a valid IP address, otherwise returns False"""
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF': if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
hostStandardFormat = socket.inet_ntop(socket.AF_INET, host[12:]) hostStandardFormat = socket.inet_ntop(socket.AF_INET, host[12:])
return checkIPv4Address(host[12:], hostStandardFormat, private) return checkIPv4Address(host[12:], hostStandardFormat, private)
@ -110,51 +133,61 @@ def checkIPAddress(host, private=False):
return False return False
return checkIPv6Address(host, hostStandardFormat, private) return checkIPv6Address(host, hostStandardFormat, private)
def checkIPv4Address(host, hostStandardFormat, private=False): def checkIPv4Address(host, hostStandardFormat, private=False):
if host[0] == '\x7F': # 127/8 """Returns hostStandardFormat if it is an IPv4 address, otherwise returns False"""
if host[0] == '\x7F': # 127/8
if not private: if not private:
logger.debug('Ignoring IP address in loopback range: ' + hostStandardFormat) logger.debug('Ignoring IP address in loopback range: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
if host[0] == '\x0A': # 10/8 if host[0] == '\x0A': # 10/8
if not private: if not private:
logger.debug('Ignoring IP address in private range: ' + hostStandardFormat) logger.debug('Ignoring IP address in private range: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
if host[0:2] == '\xC0\xA8': # 192.168/16 if host[0:2] == '\xC0\xA8': # 192.168/16
if not private: if not private:
logger.debug('Ignoring IP address in private range: ' + hostStandardFormat) logger.debug('Ignoring IP address in private range: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
if host[0:2] >= '\xAC\x10' and host[0:2] < '\xAC\x20': # 172.16/12 if host[0:2] >= '\xAC\x10' and host[0:2] < '\xAC\x20': # 172.16/12
if not private: if not private:
logger.debug('Ignoring IP address in private range:' + hostStandardFormat) logger.debug('Ignoring IP address in private range: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
return False if private else hostStandardFormat return False if private else hostStandardFormat
def checkIPv6Address(host, hostStandardFormat, private=False): def checkIPv6Address(host, hostStandardFormat, private=False):
"""Returns hostStandardFormat if it is an IPv6 address, otherwise returns False"""
if host == ('\x00' * 15) + '\x01': if host == ('\x00' * 15) + '\x01':
if not private: if not private:
logger.debug('Ignoring loopback address: ' + hostStandardFormat) logger.debug('Ignoring loopback address: %s', hostStandardFormat)
return False return False
if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80: if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80:
if not private: if not private:
logger.debug ('Ignoring local address: ' + hostStandardFormat) logger.debug('Ignoring local address: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
if (ord(host[0]) & 0xfe) == 0xfc: if (ord(host[0]) & 0xfe) == 0xfc:
if not private: if not private:
logger.debug ('Ignoring unique local address: ' + hostStandardFormat) logger.debug('Ignoring unique local address: %s', hostStandardFormat)
return hostStandardFormat if private else False return hostStandardFormat if private else False
return False if private else hostStandardFormat return False if private else hostStandardFormat
# checks
def haveSSL(server = False): def haveSSL(server=False):
# python < 2.7.9's ssl library does not support ECDSA server due to missing initialisation of available curves, but client works ok """
if server == False: Predicate to check if ECDSA server support is required and available
python < 2.7.9's ssl library does not support ECDSA server due to
missing initialisation of available curves, but client works ok
"""
if not server:
return True return True
elif sys.version_info >= (2,7,9): elif sys.version_info >= (2, 7, 9):
return True return True
return False return False
def checkSocksIP(host): def checkSocksIP(host):
"""Predicate to check if we're using a SOCKS proxy"""
try: try:
if state.socksIP is None or not state.socksIP: if state.socksIP is None or not state.socksIP:
state.socksIP = socket.gethostbyname(BMConfigParser().get("bitmessagesettings", "sockshostname")) state.socksIP = socket.gethostbyname(BMConfigParser().get("bitmessagesettings", "sockshostname"))
@ -166,24 +199,42 @@ def checkSocksIP(host):
state.socksIP = BMConfigParser().get("bitmessagesettings", "sockshostname") state.socksIP = BMConfigParser().get("bitmessagesettings", "sockshostname")
return state.socksIP == host return state.socksIP == host
def isProofOfWorkSufficient(data, def isProofOfWorkSufficient(data,
nonceTrialsPerByte=0, nonceTrialsPerByte=0,
payloadLengthExtraBytes=0): payloadLengthExtraBytes=0,
recvTime=0):
"""
Validate an object's Proof of Work using method described in:
https://bitmessage.org/wiki/Proof_of_work
Arguments:
int nonceTrialsPerByte (default: from default.py)
int payloadLengthExtraBytes (default: from default.py)
float recvTime (optional) UNIX epoch time when object was
received from the network (default: current system time)
Returns:
True if PoW valid and sufficient, False in all other cases
"""
if nonceTrialsPerByte < defaults.networkDefaultProofOfWorkNonceTrialsPerByte: if nonceTrialsPerByte < defaults.networkDefaultProofOfWorkNonceTrialsPerByte:
nonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte nonceTrialsPerByte = defaults.networkDefaultProofOfWorkNonceTrialsPerByte
if payloadLengthExtraBytes < defaults.networkDefaultPayloadLengthExtraBytes: if payloadLengthExtraBytes < defaults.networkDefaultPayloadLengthExtraBytes:
payloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes payloadLengthExtraBytes = defaults.networkDefaultPayloadLengthExtraBytes
endOfLifeTime, = unpack('>Q', data[8:16]) endOfLifeTime, = unpack('>Q', data[8:16])
TTL = endOfLifeTime - int(time.time()) TTL = endOfLifeTime - (int(recvTime) if recvTime else int(time.time()))
if TTL < 300: if TTL < 300:
TTL = 300 TTL = 300
POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[ POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
:8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8]) :8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
return POW <= 2 ** 64 / (nonceTrialsPerByte*(len(data) + payloadLengthExtraBytes + ((TTL*(len(data)+payloadLengthExtraBytes))/(2 ** 16)))) return POW <= 2 ** 64 / (nonceTrialsPerByte *
(len(data) + payloadLengthExtraBytes +
((TTL * (len(data) + payloadLengthExtraBytes)) / (2 ** 16))))
# Packet creation # Packet creation
def CreatePacket(command, payload=''): def CreatePacket(command, payload=''):
"""Construct and return a number of bytes from a payload"""
payload_length = len(payload) payload_length = len(payload)
checksum = hashlib.sha512(payload).digest()[0:4] checksum = hashlib.sha512(payload).digest()[0:4]
@ -192,20 +243,23 @@ def CreatePacket(command, payload=''):
b[Header.size:] = payload b[Header.size:] = payload
return bytes(b) return bytes(b)
def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server = False, nodeid = None):
def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server=False, nodeid=None):
"""Construct the payload of a version message, return the resultng bytes of running CreatePacket() on it"""
payload = '' payload = ''
payload += pack('>L', 3) # protocol version. payload += pack('>L', 3) # protocol version.
# bitflags of the services I offer. # bitflags of the services I offer.
payload += pack('>q', payload += pack(
NODE_NETWORK | '>q',
(NODE_SSL if haveSSL(server) else 0) | NODE_NETWORK |
(NODE_DANDELION if state.dandelion else 0) (NODE_SSL if haveSSL(server) else 0) |
) (NODE_DANDELION if state.dandelion else 0)
)
payload += pack('>q', int(time.time())) payload += pack('>q', int(time.time()))
payload += pack( payload += pack(
'>q', 1) # boolservices of remote connection; ignored by the remote host. '>q', 1) # boolservices of remote connection; ignored by the remote host.
if checkSocksIP(remoteHost) and server: # prevent leaking of tor outbound IP if checkSocksIP(remoteHost) and server: # prevent leaking of tor outbound IP
payload += encodeHost('127.0.0.1') payload += encodeHost('127.0.0.1')
payload += pack('>H', 8444) payload += pack('>H', 8444)
else: else:
@ -213,23 +267,22 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server
payload += pack('>H', remotePort) # remote IPv6 and port payload += pack('>H', remotePort) # remote IPv6 and port
# bitflags of the services I offer. # bitflags of the services I offer.
payload += pack('>q', payload += pack(
NODE_NETWORK | '>q',
(NODE_SSL if haveSSL(server) else 0) | NODE_NETWORK |
(NODE_DANDELION if state.dandelion else 0) (NODE_SSL if haveSSL(server) else 0) |
) (NODE_DANDELION if state.dandelion else 0)
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack( )
'>L', 2130706433) # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used. # = 127.0.0.1. This will be ignored by the remote host. The actual remote connected IP will be used.
# we have a separate extPort and payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack('>L', 2130706433)
# incoming over clearnet or # we have a separate extPort and incoming over clearnet or outgoing through clearnet
# outgoing through clearnet
if BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and state.extPort \ if BMConfigParser().safeGetBoolean('bitmessagesettings', 'upnp') and state.extPort \
and ((server and not checkSocksIP(remoteHost)) or \ and ((server and not checkSocksIP(remoteHost)) or
(BMConfigParser().get("bitmessagesettings", "socksproxytype") == "none" and not server)): (BMConfigParser().get("bitmessagesettings", "socksproxytype") == "none" and not server)):
payload += pack('>H', state.extPort) payload += pack('>H', state.extPort)
elif checkSocksIP(remoteHost) and server: # incoming connection over Tor elif checkSocksIP(remoteHost) and server: # incoming connection over Tor
payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'onionport')) payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'onionport'))
else: # no extPort and not incoming over Tor else: # no extPort and not incoming over Tor
payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'port')) payload += pack('>H', BMConfigParser().getint('bitmessagesettings', 'port'))
random.seed() random.seed()
@ -253,7 +306,9 @@ def assembleVersionMessage(remoteHost, remotePort, participatingStreams, server
return CreatePacket('version', payload) return CreatePacket('version', payload)
def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''): def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''):
"""Construct the payload of an error message, return the resultng bytes of running CreatePacket() on it"""
payload = encodeVarint(fatal) payload = encodeVarint(fatal)
payload += encodeVarint(banTime) payload += encodeVarint(banTime)
payload += encodeVarint(len(inventoryVector)) payload += encodeVarint(len(inventoryVector))
@ -262,8 +317,10 @@ def assembleErrorMessage(fatal=0, banTime=0, inventoryVector='', errorText=''):
payload += errorText payload += errorText
return CreatePacket('error', payload) return CreatePacket('error', payload)
# Packet decoding # Packet decoding
def decryptAndCheckPubkeyPayload(data, address): def decryptAndCheckPubkeyPayload(data, address):
""" """
Version 4 pubkeys are encrypted. This function is run when we already have the Version 4 pubkeys are encrypted. This function is run when we already have the
@ -271,6 +328,7 @@ def decryptAndCheckPubkeyPayload(data, address):
off of the wire or we might have had it already in our inventory when we tried off of the wire or we might have had it already in our inventory when we tried
to send a msg to this particular address. to send a msg to this particular address.
""" """
# pylint: disable=unused-variable
try: try:
status, addressVersion, streamNumber, ripe = decodeAddress(address) status, addressVersion, streamNumber, ripe = decodeAddress(address)
@ -279,7 +337,8 @@ def decryptAndCheckPubkeyPayload(data, address):
readPosition += varintLength readPosition += varintLength
embeddedStreamNumber, varintLength = decodeVarint(data[readPosition:readPosition + 10]) embeddedStreamNumber, varintLength = decodeVarint(data[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
storedData = data[20:readPosition] # We'll store the address version and stream number (and some more) in the pubkeys table. # We'll store the address version and stream number (and some more) in the pubkeys table.
storedData = data[20:readPosition]
if addressVersion != embeddedAddressVersion: if addressVersion != embeddedAddressVersion:
logger.info('Pubkey decryption was UNsuccessful due to address version mismatch.') logger.info('Pubkey decryption was UNsuccessful due to address version mismatch.')
@ -290,15 +349,21 @@ def decryptAndCheckPubkeyPayload(data, address):
tag = data[readPosition:readPosition + 32] tag = data[readPosition:readPosition + 32]
readPosition += 32 readPosition += 32
signedData = data[8:readPosition] # the time through the tag. More data is appended onto signedData below after the decryption. # the time through the tag. More data is appended onto signedData below after the decryption.
signedData = data[8:readPosition]
encryptedData = data[readPosition:] encryptedData = data[readPosition:]
# Let us try to decrypt the pubkey # Let us try to decrypt the pubkey
toAddress, cryptorObject = state.neededPubkeys[tag] toAddress, cryptorObject = state.neededPubkeys[tag]
if toAddress != address: if toAddress != address:
logger.critical('decryptAndCheckPubkeyPayload failed due to toAddress mismatch. This is very peculiar. toAddress: %s, address %s', toAddress, address) logger.critical(
# the only way I can think that this could happen is if someone encodes their address data two different ways. 'decryptAndCheckPubkeyPayload failed due to toAddress mismatch.'
# That sort of address-malleability should have been caught by the UI or API and an error given to the user. ' This is very peculiar. toAddress: %s, address %s',
toAddress,
address)
# the only way I can think that this could happen is if someone encodes their address data two different
# ways. That sort of address-malleability should have been caught by the UI or API and an error given to
# the user.
return 'failed' return 'failed'
try: try:
decryptedData = cryptorObject.decrypt(encryptedData) decryptedData = cryptorObject.decrypt(encryptedData)
@ -349,26 +414,29 @@ def decryptAndCheckPubkeyPayload(data, address):
# Everything checked out. Insert it into the pubkeys table. # Everything checked out. Insert it into the pubkeys table.
logger.info('within decryptAndCheckPubkeyPayload, addressVersion: %s, streamNumber: %s \n\ logger.info(
ripe %s\n\ os.linesep.join([
publicSigningKey in hex: %s\n\ 'within decryptAndCheckPubkeyPayload,'
publicEncryptionKey in hex: %s', addressVersion, ' addressVersion: %s, streamNumber: %s' % addressVersion, streamNumber,
streamNumber, 'ripe %s' % hexlify(ripe),
hexlify(ripe), 'publicSigningKey in hex: %s' % hexlify(publicSigningKey),
hexlify(publicSigningKey), 'publicEncryptionKey in hex: %s' % hexlify(publicEncryptionKey),
hexlify(publicEncryptionKey) ])
) )
t = (address, addressVersion, storedData, int(time.time()), 'yes') t = (address, addressVersion, storedData, int(time.time()), 'yes')
sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t) sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
return 'successful' return 'successful'
except varintDecodeError as e: except varintDecodeError:
logger.info('Pubkey decryption was UNsuccessful due to a malformed varint.') logger.info('Pubkey decryption was UNsuccessful due to a malformed varint.')
return 'failed' return 'failed'
except Exception as e: except Exception:
logger.critical('Pubkey decryption was UNsuccessful because of an unhandled exception! This is definitely a bug! \n%s', traceback.format_exc()) logger.critical(
'Pubkey decryption was UNsuccessful because of an unhandled exception! This is definitely a bug! \n%s',
traceback.format_exc())
return 'failed' return 'failed'
def checkAndShareObjectWithPeers(data): def checkAndShareObjectWithPeers(data):
""" """
This function is called after either receiving an object off of the wire This function is called after either receiving an object off of the wire
@ -385,11 +453,14 @@ def checkAndShareObjectWithPeers(data):
return 0 return 0
endOfLifeTime, = unpack('>Q', data[8:16]) endOfLifeTime, = unpack('>Q', data[8:16])
if endOfLifeTime - int(time.time()) > 28 * 24 * 60 * 60 + 10800: # The TTL may not be larger than 28 days + 3 hours of wiggle room # The TTL may not be larger than 28 days + 3 hours of wiggle room
if endOfLifeTime - int(time.time()) > 28 * 24 * 60 * 60 + 10800:
logger.info('This object\'s End of Life time is too far in the future. Ignoring it. Time is %s', endOfLifeTime) logger.info('This object\'s End of Life time is too far in the future. Ignoring it. Time is %s', endOfLifeTime)
return 0 return 0
if endOfLifeTime - int(time.time()) < - 3600: # The EOL time was more than an hour ago. That's too much. if endOfLifeTime - int(time.time()) < - 3600: # The EOL time was more than an hour ago. That's too much.
logger.info('This object\'s End of Life time was more than an hour ago. Ignoring the object. Time is %s', endOfLifeTime) logger.info(
'This object\'s End of Life time was more than an hour ago. Ignoring the object. Time is %s',
endOfLifeTime)
return 0 return 0
intObjectType, = unpack('>I', data[16:20]) intObjectType, = unpack('>I', data[16:20])
try: try:
@ -405,25 +476,31 @@ def checkAndShareObjectWithPeers(data):
elif intObjectType == 3: elif intObjectType == 3:
_checkAndShareBroadcastWithPeers(data) _checkAndShareBroadcastWithPeers(data)
return 0.6 return 0.6
else: _checkAndShareUndefinedObjectWithPeers(data)
_checkAndShareUndefinedObjectWithPeers(data) return 0.6
return 0.6 except varintDecodeError as err:
except varintDecodeError as e: logger.debug(
logger.debug("There was a problem with a varint while checking to see whether it was appropriate to share an object with peers. Some details: %s", e) "There was a problem with a varint while checking to see whether it was appropriate to share an object"
except Exception as e: " with peers. Some details: %s", err
logger.critical('There was a problem while checking to see whether it was appropriate to share an object with peers. This is definitely a bug! \n%s', traceback.format_exc()) )
except Exception:
logger.critical(
'There was a problem while checking to see whether it was appropriate to share an object with peers.'
' This is definitely a bug! %s%s' % os.linesep, traceback.format_exc()
)
return 0 return 0
def _checkAndShareUndefinedObjectWithPeers(data): def _checkAndShareUndefinedObjectWithPeers(data):
# pylint: disable=unused-variable
embeddedTime, = unpack('>Q', data[8:16]) embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass nonce, time, and object type readPosition = 20 # bypass nonce, time, and object type
objectVersion, objectVersionLength = decodeVarint( objectVersion, objectVersionLength = decodeVarint(
data[readPosition:readPosition + 9]) data[readPosition:readPosition + 9])
readPosition += objectVersionLength readPosition += objectVersionLength
streamNumber, streamNumberLength = decodeVarint( streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 9]) data[readPosition:readPosition + 9])
if not streamNumber in state.streamsInWhichIAmParticipating: if streamNumber not in state.streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber) logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber)
return return
@ -433,20 +510,20 @@ def _checkAndShareUndefinedObjectWithPeers(data):
return return
objectType, = unpack('>I', data[16:20]) objectType, = unpack('>I', data[16:20])
Inventory()[inventoryHash] = ( Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'') objectType, streamNumber, data, embeddedTime, '')
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash)) logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash)) broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
def _checkAndShareMsgWithPeers(data): def _checkAndShareMsgWithPeers(data):
embeddedTime, = unpack('>Q', data[8:16]) embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass nonce, time, and object type readPosition = 20 # bypass nonce, time, and object type
objectVersion, objectVersionLength = decodeVarint( objectVersion, objectVersionLength = decodeVarint( # pylint: disable=unused-variable
data[readPosition:readPosition + 9]) data[readPosition:readPosition + 9])
readPosition += objectVersionLength readPosition += objectVersionLength
streamNumber, streamNumberLength = decodeVarint( streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 9]) data[readPosition:readPosition + 9])
if not streamNumber in state.streamsInWhichIAmParticipating: if streamNumber not in state.streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber) logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber)
return return
readPosition += streamNumberLength readPosition += streamNumberLength
@ -457,14 +534,16 @@ def _checkAndShareMsgWithPeers(data):
# This msg message is valid. Let's let our peers know about it. # This msg message is valid. Let's let our peers know about it.
objectType = 2 objectType = 2
Inventory()[inventoryHash] = ( Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'') objectType, streamNumber, data, embeddedTime, '')
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash)) logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash)) broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's enqueue it to be processed ourselves. # Now let's enqueue it to be processed ourselves.
objectProcessorQueue.put((objectType,data)) objectProcessorQueue.put((objectType, data))
def _checkAndShareGetpubkeyWithPeers(data): def _checkAndShareGetpubkeyWithPeers(data):
# pylint: disable=unused-variable
if len(data) < 42: if len(data) < 42:
logger.info('getpubkey message doesn\'t contain enough data. Ignoring.') logger.info('getpubkey message doesn\'t contain enough data. Ignoring.')
return return
@ -477,7 +556,7 @@ def _checkAndShareGetpubkeyWithPeers(data):
readPosition += addressVersionLength readPosition += addressVersionLength
streamNumber, streamNumberLength = decodeVarint( streamNumber, streamNumberLength = decodeVarint(
data[readPosition:readPosition + 10]) data[readPosition:readPosition + 10])
if not streamNumber in state.streamsInWhichIAmParticipating: if streamNumber not in state.streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber) logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber)
return return
readPosition += streamNumberLength readPosition += streamNumberLength
@ -489,13 +568,14 @@ def _checkAndShareGetpubkeyWithPeers(data):
objectType = 0 objectType = 0
Inventory()[inventoryHash] = ( Inventory()[inventoryHash] = (
objectType, streamNumber, data, embeddedTime,'') objectType, streamNumber, data, embeddedTime, '')
# This getpubkey request is valid. Forward to peers. # This getpubkey request is valid. Forward to peers.
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash)) logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash)) broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves. # Now let's queue it to be processed ourselves.
objectProcessorQueue.put((objectType,data)) objectProcessorQueue.put((objectType, data))
def _checkAndSharePubkeyWithPeers(data): def _checkAndSharePubkeyWithPeers(data):
if len(data) < 146 or len(data) > 440: # sanity check if len(data) < 146 or len(data) > 440: # sanity check
@ -508,7 +588,7 @@ def _checkAndSharePubkeyWithPeers(data):
streamNumber, varintLength = decodeVarint( streamNumber, varintLength = decodeVarint(
data[readPosition:readPosition + 10]) data[readPosition:readPosition + 10])
readPosition += varintLength readPosition += varintLength
if not streamNumber in state.streamsInWhichIAmParticipating: if streamNumber not in state.streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber) logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber)
return return
if addressVersion >= 4: if addressVersion >= 4:
@ -528,14 +608,15 @@ def _checkAndSharePubkeyWithPeers(data):
logger.debug('advertising inv with hash: %s', hexlify(inventoryHash)) logger.debug('advertising inv with hash: %s', hexlify(inventoryHash))
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash)) broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves. # Now let's queue it to be processed ourselves.
objectProcessorQueue.put((objectType,data)) objectProcessorQueue.put((objectType, data))
def _checkAndShareBroadcastWithPeers(data): def _checkAndShareBroadcastWithPeers(data):
if len(data) < 180: if len(data) < 180:
logger.debug('The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.') logger.debug(
'The payload length of this broadcast packet is unreasonably low. '
'Someone is probably trying funny business. Ignoring message.')
return return
embeddedTime, = unpack('>Q', data[8:16]) embeddedTime, = unpack('>Q', data[8:16])
readPosition = 20 # bypass the nonce, time, and object type readPosition = 20 # bypass the nonce, time, and object type
@ -545,11 +626,11 @@ def _checkAndShareBroadcastWithPeers(data):
if broadcastVersion >= 2: if broadcastVersion >= 2:
streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition + 10]) streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition + 10])
readPosition += streamNumberLength readPosition += streamNumberLength
if not streamNumber in state.streamsInWhichIAmParticipating: if streamNumber not in state.streamsInWhichIAmParticipating:
logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber) logger.debug('The streamNumber %s isn\'t one we are interested in.', streamNumber)
return return
if broadcastVersion >= 3: if broadcastVersion >= 3:
tag = data[readPosition:readPosition+32] tag = data[readPosition:readPosition + 32]
else: else:
tag = '' tag = ''
inventoryHash = calculateInventoryHash(data) inventoryHash = calculateInventoryHash(data)
@ -565,23 +646,26 @@ def _checkAndShareBroadcastWithPeers(data):
broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash)) broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
# Now let's queue it to be processed ourselves. # Now let's queue it to be processed ourselves.
objectProcessorQueue.put((objectType,data)) objectProcessorQueue.put((objectType, data))
# If you want to command all of the sendDataThreads to do something, like shutdown or send some data, this
# function puts your data into the queues for each of the sendDataThreads. The sendDataThreads are
# responsible for putting their queue into (and out of) the sendDataQueues list.
def broadcastToSendDataQueues(data): def broadcastToSendDataQueues(data):
# logger.debug('running broadcastToSendDataQueues') """
If you want to command all of the sendDataThreads to do something, like shutdown or send some data, this
function puts your data into the queues for each of the sendDataThreads. The sendDataThreads are
responsible for putting their queue into (and out of) the sendDataQueues list.
"""
for q in state.sendDataQueues: for q in state.sendDataQueues:
q.put(data) q.put(data)
# sslProtocolVersion # sslProtocolVersion
if sys.version_info >= (2,7,13): if sys.version_info >= (2, 7, 13):
# this means TLSv1 or higher # this means TLSv1 or higher
# in the future change to # in the future change to
# ssl.PROTOCOL_TLS1.2 # ssl.PROTOCOL_TLS1.2
sslProtocolVersion = ssl.PROTOCOL_TLS sslProtocolVersion = ssl.PROTOCOL_TLS # pylint: disable=no-member
elif sys.version_info >= (2,7,9): elif sys.version_info >= (2, 7, 9):
# this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created # this means any SSL/TLS. SSLv2 and 3 are excluded with an option after context is created
sslProtocolVersion = ssl.PROTOCOL_SSLv23 sslProtocolVersion = ssl.PROTOCOL_SSLv23
else: else:
@ -589,6 +673,7 @@ else:
# "TLSv1.2" in < 2.7.9 # "TLSv1.2" in < 2.7.9
sslProtocolVersion = ssl.PROTOCOL_TLSv1 sslProtocolVersion = ssl.PROTOCOL_TLSv1
# ciphers # ciphers
if ssl.OPENSSL_VERSION_NUMBER >= 0x10100000 and not ssl.OPENSSL_VERSION.startswith("LibreSSL"): if ssl.OPENSSL_VERSION_NUMBER >= 0x10100000 and not ssl.OPENSSL_VERSION.startswith("LibreSSL"):
sslProtocolCiphers = "AECDH-AES256-SHA@SECLEVEL=0" sslProtocolCiphers = "AECDH-AES256-SHA@SECLEVEL=0"

View File

@ -1,106 +1,144 @@
import hashlib, re # pylint: disable=missing-docstring,too-many-function-args
P = 2**256-2**32-2**9-2**8-2**7-2**6-2**4-1 import hashlib
import re
P = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1
A = 0 A = 0
Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240 Gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240
Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424 Gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424
G = (Gx,Gy) G = (Gx, Gy)
def inv(a, n):
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high / low
nm, new = hm - lm * r, high - low * r
lm, low, hm, high = nm, new, lm, low
return lm % n
def inv(a,n):
lm, hm = 1,0
low, high = a%n,n
while low > 1:
r = high/low
nm, new = hm-lm*r, high-low*r
lm, low, hm, high = nm, new, lm, low
return lm % n
def get_code_string(base): def get_code_string(base):
if base == 2: return '01' if base == 2:
elif base == 10: return '0123456789' return '01'
elif base == 16: return "0123456789abcdef" elif base == 10:
elif base == 58: return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" return '0123456789'
elif base == 256: return ''.join([chr(x) for x in range(256)]) elif base == 16:
else: raise ValueError("Invalid base!") return "0123456789abcdef"
elif base == 58:
return "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
elif base == 256:
return ''.join([chr(x) for x in range(256)])
else:
raise ValueError("Invalid base!")
def encode(val,base,minlen=0):
code_string = get_code_string(base)
result = ""
while val > 0:
result = code_string[val % base] + result
val /= base
if len(result) < minlen:
result = code_string[0]*(minlen-len(result))+result
return result
def decode(string,base): def encode(val, base, minlen=0):
code_string = get_code_string(base) code_string = get_code_string(base)
result = 0 result = ""
if base == 16: string = string.lower() while val > 0:
while len(string) > 0: result = code_string[val % base] + result
result *= base val /= base
result += code_string.find(string[0]) if len(result) < minlen:
string = string[1:] result = code_string[0] * (minlen - len(result)) + result
return result return result
def changebase(string,frm,to,minlen=0):
return encode(decode(string,frm),to,minlen)
def base10_add(a,b): def decode(string, base):
if a == None: return b[0],b[1] code_string = get_code_string(base)
if b == None: return a[0],a[1] result = 0
if a[0] == b[0]: if base == 16:
if a[1] == b[1]: return base10_double(a[0],a[1]) string = string.lower()
else: return None while string:
m = ((b[1]-a[1]) * inv(b[0]-a[0],P)) % P result *= base
x = (m*m-a[0]-b[0]) % P result += code_string.find(string[0])
y = (m*(a[0]-x)-a[1]) % P string = string[1:]
return (x,y) return result
def changebase(string, frm, to, minlen=0):
return encode(decode(string, frm), to, minlen)
def base10_add(a, b):
if a is None:
return b[0], b[1]
if b is None:
return a[0], a[1]
if a[0] == b[0]:
if a[1] == b[1]:
return base10_double(a[0], a[1])
return None
m = ((b[1] - a[1]) * inv(b[0] - a[0], P)) % P
x = (m * m - a[0] - b[0]) % P
y = (m * (a[0] - x) - a[1]) % P
return (x, y)
def base10_double(a): def base10_double(a):
if a == None: return None if a is None:
m = ((3*a[0]*a[0]+A)*inv(2*a[1],P)) % P return None
x = (m*m-2*a[0]) % P m = ((3 * a[0] * a[0] + A) * inv(2 * a[1], P)) % P
y = (m*(a[0]-x)-a[1]) % P x = (m * m - 2 * a[0]) % P
return (x,y) y = (m * (a[0] - x) - a[1]) % P
return (x, y)
def base10_multiply(a,n):
if n == 0: return G
if n == 1: return a
if (n%2) == 0: return base10_double(base10_multiply(a,n/2))
if (n%2) == 1: return base10_add(base10_double(base10_multiply(a,n/2)),a)
def hex_to_point(h): return (decode(h[2:66],16),decode(h[66:],16)) def base10_multiply(a, n):
if n == 0:
return G
if n == 1:
return a
if (n % 2) == 0:
return base10_double(base10_multiply(a, n / 2))
if (n % 2) == 1:
return base10_add(base10_double(base10_multiply(a, n / 2)), a)
return None
def point_to_hex(p): return '04'+encode(p[0],16,64)+encode(p[1],16,64)
def multiply(privkey,pubkey): def hex_to_point(h):
return point_to_hex(base10_multiply(hex_to_point(pubkey),decode(privkey,16))) return (decode(h[2:66], 16), decode(h[66:], 16))
def point_to_hex(p):
return '04' + encode(p[0], 16, 64) + encode(p[1], 16, 64)
def multiply(privkey, pubkey):
return point_to_hex(base10_multiply(hex_to_point(pubkey), decode(privkey, 16)))
def privtopub(privkey): def privtopub(privkey):
return point_to_hex(base10_multiply(G,decode(privkey,16))) return point_to_hex(base10_multiply(G, decode(privkey, 16)))
def add(p1, p2):
if len(p1) == 32:
return encode(decode(p1, 16) + decode(p2, 16) % P, 16, 32)
return point_to_hex(base10_add(hex_to_point(p1), hex_to_point(p2)))
def add(p1,p2):
if (len(p1)==32):
return encode(decode(p1,16) + decode(p2,16) % P,16,32)
else:
return point_to_hex(base10_add(hex_to_point(p1),hex_to_point(p2)))
def hash_160(string): def hash_160(string):
intermed = hashlib.sha256(string).digest() intermed = hashlib.sha256(string).digest()
ripemd160 = hashlib.new('ripemd160') ripemd160 = hashlib.new('ripemd160')
ripemd160.update(intermed) ripemd160.update(intermed)
return ripemd160.digest() return ripemd160.digest()
def dbl_sha256(string): def dbl_sha256(string):
return hashlib.sha256(hashlib.sha256(string).digest()).digest() return hashlib.sha256(hashlib.sha256(string).digest()).digest()
def bin_to_b58check(inp): def bin_to_b58check(inp):
inp_fmtd = '\x00' + inp inp_fmtd = '\x00' + inp
leadingzbytes = len(re.match('^\x00*',inp_fmtd).group(0)) leadingzbytes = len(re.match('^\x00*', inp_fmtd).group(0))
checksum = dbl_sha256(inp_fmtd)[:4] checksum = dbl_sha256(inp_fmtd)[:4]
return '1' * leadingzbytes + changebase(inp_fmtd+checksum,256,58) return '1' * leadingzbytes + changebase(inp_fmtd + checksum, 256, 58)
# Convert a public key (in hex) to a Bitcoin address
#Convert a public key (in hex) to a Bitcoin address
def pubkey_to_address(pubkey): def pubkey_to_address(pubkey):
return bin_to_b58check(hash_160(changebase(pubkey,16,256))) return bin_to_b58check(hash_160(changebase(pubkey, 16, 256)))