Moved writeKeysFile into configparser

- shared.writeKeysFile -> BMConfigParser().save
- makes it easier to get rid of circular imports
This commit is contained in:
Peter Šurda 2017-01-15 10:50:02 +01:00
parent 5ca8a52662
commit 8cb0953401
Signed by untrusted user: PeterSurda
GPG Key ID: 0C5F50C0B5F37D87
10 changed files with 50 additions and 50 deletions

View File

@ -485,13 +485,13 @@ def handlech(c, stdscr):
label = t label = t
BMConfigParser().set(a, "label", label) BMConfigParser().set(a, "label", label)
# Write config # Write config
shared.writeKeysFile() BMConfigParser().save()
addresses[addrcur][0] = label addresses[addrcur][0] = label
elif t == "4": # Enable address elif t == "4": # Enable address
a = addresses[addrcur][2] a = addresses[addrcur][2]
BMConfigParser().set(a, "enabled", "true") # Set config BMConfigParser().set(a, "enabled", "true") # Set config
# Write config # Write config
shared.writeKeysFile() BMConfigParser().save()
# Change color # Change color
if BMConfigParser().safeGetBoolean(a, 'chan'): if BMConfigParser().safeGetBoolean(a, 'chan'):
addresses[addrcur][3] = 9 # orange addresses[addrcur][3] = 9 # orange
@ -506,14 +506,14 @@ def handlech(c, stdscr):
BMConfigParser().set(a, "enabled", "false") # Set config BMConfigParser().set(a, "enabled", "false") # Set config
addresses[addrcur][3] = 8 # Set color to gray addresses[addrcur][3] = 8 # Set color to gray
# Write config # Write config
shared.writeKeysFile() BMConfigParser().save()
addresses[addrcur][1] = False addresses[addrcur][1] = False
shared.reloadMyAddressHashes() # Reload address hashes shared.reloadMyAddressHashes() # Reload address hashes
elif t == "6": # Delete address elif t == "6": # Delete address
r, t = d.inputbox("Type in \"I want to delete this address\"", width=50) r, t = d.inputbox("Type in \"I want to delete this address\"", width=50)
if r == d.DIALOG_OK and t == "I want to delete this address": if r == d.DIALOG_OK and t == "I want to delete this address":
BMConfigParser().remove_section(addresses[addrcur][2]) BMConfigParser().remove_section(addresses[addrcur][2])
shared.writeKeysFile() BMConfigParser().save()
del addresses[addrcur] del addresses[addrcur]
elif t == "7": # Special address behavior elif t == "7": # Special address behavior
a = addresses[addrcur][2] a = addresses[addrcur][2]
@ -544,7 +544,7 @@ def handlech(c, stdscr):
BMConfigParser().set(a, "mailinglistname", mn) BMConfigParser().set(a, "mailinglistname", mn)
addresses[addrcur][3] = 6 # Set color to magenta addresses[addrcur][3] = 6 # Set color to magenta
# Write config # Write config
shared.writeKeysFile() BMConfigParser().save()
elif menutab == 5: elif menutab == 5:
set_background_title(d, "Subscriptions Dialog Box") set_background_title(d, "Subscriptions Dialog Box")
if len(subscriptions) <= subcur: if len(subscriptions) <= subcur:

View File

@ -611,7 +611,7 @@ class MyForm(settingsmixin.SMainWindow):
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:
BMConfigParser().remove_section(addressInKeysFile) BMConfigParser().remove_section(addressInKeysFile)
shared.writeKeysFile() BMConfigParser().save()
# 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
@ -822,7 +822,7 @@ class MyForm(settingsmixin.SMainWindow):
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))
shared.writeKeysFile() BMConfigParser().save()
def updateHumanFriendlyTTLDescription(self, TTL): def updateHumanFriendlyTTLDescription(self, TTL):
numberOfHours = int(round(TTL / (60*60))) numberOfHours = int(round(TTL / (60*60)))
@ -1596,7 +1596,7 @@ class MyForm(settingsmixin.SMainWindow):
if self.connectDialogInstance.exec_(): if self.connectDialogInstance.exec_():
if self.connectDialogInstance.ui.radioButtonConnectNow.isChecked(): if self.connectDialogInstance.ui.radioButtonConnectNow.isChecked():
BMConfigParser().remove_option('bitmessagesettings', 'dontconnect') BMConfigParser().remove_option('bitmessagesettings', 'dontconnect')
shared.writeKeysFile() BMConfigParser().save()
else: else:
self.click_actionSettings() self.click_actionSettings()
@ -1953,7 +1953,7 @@ class MyForm(settingsmixin.SMainWindow):
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')
shared.writeKeysFile() BMConfigParser().save()
self.statusBar().showMessage(_translate( self.statusBar().showMessage(_translate(
"MainWindow", "Error: Your account wasn't registered at an email gateway. Sending registration now as %1, please wait for the registration to be processed before retrying sending.").arg(email), 10000) "MainWindow", "Error: Your account wasn't registered at an email gateway. Sending registration now as %1, please wait for the registration to be processed before retrying sending.").arg(email), 10000)
return return
@ -2236,7 +2236,7 @@ class MyForm(settingsmixin.SMainWindow):
acct.register(email) acct.register(email)
BMConfigParser().set(acct.fromAddress, 'label', email) BMConfigParser().set(acct.fromAddress, 'label', email)
BMConfigParser().set(acct.fromAddress, 'gateway', 'mailchuck') BMConfigParser().set(acct.fromAddress, 'gateway', 'mailchuck')
shared.writeKeysFile() BMConfigParser().save()
self.statusBar().showMessage(_translate( self.statusBar().showMessage(_translate(
"MainWindow", "Sending email gateway registration request"), 10000) "MainWindow", "Sending email gateway registration request"), 10000)
@ -2476,7 +2476,7 @@ class MyForm(settingsmixin.SMainWindow):
BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', str(float( BMConfigParser().set('bitmessagesettings', 'stopresendingafterxmonths', str(float(
self.settingsDialogInstance.ui.lineEditMonths.text()))) self.settingsDialogInstance.ui.lineEditMonths.text())))
shared.writeKeysFile() 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
@ -2521,7 +2521,7 @@ class MyForm(settingsmixin.SMainWindow):
os.makedirs(state.appdata) os.makedirs(state.appdata)
sqlStoredProcedure('movemessagstoappdata') sqlStoredProcedure('movemessagstoappdata')
# Write the keys.dat file to disk in the new location # Write the keys.dat file to disk in the new location
shared.writeKeysFile() BMConfigParser().save()
# Write the knownnodes.dat file to disk in the new location # Write the knownnodes.dat file to disk in the new location
shared.knownNodesLock.acquire() shared.knownNodesLock.acquire()
output = open(state.appdata + 'knownnodes.dat', 'wb') output = open(state.appdata + 'knownnodes.dat', 'wb')
@ -2561,7 +2561,7 @@ class MyForm(settingsmixin.SMainWindow):
self.setCurrentItemColor(QtGui.QColor(137, 04, 177)) #magenta self.setCurrentItemColor(QtGui.QColor(137, 04, 177)) #magenta
self.rerenderComboBoxSendFrom() self.rerenderComboBoxSendFrom()
self.rerenderComboBoxSendFromBroadcast() self.rerenderComboBoxSendFromBroadcast()
shared.writeKeysFile() BMConfigParser().save()
self.rerenderMessagelistToLabels() self.rerenderMessagelistToLabels()
def on_action_EmailGatewayDialog(self): def on_action_EmailGatewayDialog(self):
@ -2576,7 +2576,7 @@ class MyForm(settingsmixin.SMainWindow):
if self.dialog.ui.radioButtonUnregister.isChecked() and isinstance(acct, GatewayAccount): if self.dialog.ui.radioButtonUnregister.isChecked() and isinstance(acct, GatewayAccount):
acct.unregister() acct.unregister()
BMConfigParser().remove_option(addressAtCurrentRow, 'gateway') BMConfigParser().remove_option(addressAtCurrentRow, 'gateway')
shared.writeKeysFile() BMConfigParser().save()
self.statusBar().showMessage(_translate( self.statusBar().showMessage(_translate(
"MainWindow", "Sending email gateway unregistration request"), 10000) "MainWindow", "Sending email gateway unregistration request"), 10000)
elif self.dialog.ui.radioButtonStatus.isChecked() and isinstance(acct, GatewayAccount): elif self.dialog.ui.radioButtonStatus.isChecked() and isinstance(acct, GatewayAccount):
@ -2603,7 +2603,7 @@ class MyForm(settingsmixin.SMainWindow):
acct.register(email) acct.register(email)
BMConfigParser().set(addressAtCurrentRow, 'label', email) BMConfigParser().set(addressAtCurrentRow, 'label', email)
BMConfigParser().set(addressAtCurrentRow, 'gateway', 'mailchuck') BMConfigParser().set(addressAtCurrentRow, 'gateway', 'mailchuck')
shared.writeKeysFile() BMConfigParser().save()
self.statusBar().showMessage(_translate( self.statusBar().showMessage(_translate(
"MainWindow", "Sending email gateway registration request"), 10000) "MainWindow", "Sending email gateway registration request"), 10000)
else: else:
@ -3540,7 +3540,7 @@ class MyForm(settingsmixin.SMainWindow):
return return
else: else:
return return
shared.writeKeysFile() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
if account.type == AccountMixin.NORMAL: if account.type == AccountMixin.NORMAL:
@ -3556,7 +3556,7 @@ class MyForm(settingsmixin.SMainWindow):
def enableIdentity(self, address): def enableIdentity(self, address):
BMConfigParser().set(address, 'enabled', 'true') BMConfigParser().set(address, 'enabled', 'true')
shared.writeKeysFile() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()
@ -3568,7 +3568,7 @@ class MyForm(settingsmixin.SMainWindow):
def disableIdentity(self, address): def disableIdentity(self, address):
BMConfigParser().set(str(address), 'enabled', 'false') BMConfigParser().set(str(address), 'enabled', 'false')
shared.writeKeysFile() BMConfigParser().save()
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
self.rerenderAddressBook() self.rerenderAddressBook()

View File

@ -1,5 +1,4 @@
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
import shared
from tr import _translate from tr import _translate
import l10n import l10n
import widgets import widgets
@ -41,7 +40,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
def click_radioButtonBlacklist(self): def click_radioButtonBlacklist(self):
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'white': if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'white':
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black') BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'black')
shared.writeKeysFile() BMConfigParser().save()
# self.tableWidgetBlacklist.clearContents() # self.tableWidgetBlacklist.clearContents()
self.tableWidgetBlacklist.setRowCount(0) self.tableWidgetBlacklist.setRowCount(0)
self.rerenderBlackWhiteList() self.rerenderBlackWhiteList()
@ -49,7 +48,7 @@ class Blacklist(QtGui.QWidget, RetranslateMixin):
def click_radioButtonWhitelist(self): def click_radioButtonWhitelist(self):
if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black': if BMConfigParser().get('bitmessagesettings', 'blackwhitelist') == 'black':
BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'white') BMConfigParser().set('bitmessagesettings', 'blackwhitelist', 'white')
shared.writeKeysFile() BMConfigParser().save()
# self.tableWidgetBlacklist.clearContents() # self.tableWidgetBlacklist.clearContents()
self.tableWidgetBlacklist.setRowCount(0) self.tableWidgetBlacklist.setRowCount(0)
self.rerenderBlackWhiteList() self.rerenderBlackWhiteList()

View File

@ -4,7 +4,6 @@ from string import find, rfind, rstrip, lstrip
from configparser import BMConfigParser from configparser import BMConfigParser
from helper_sql import * from helper_sql import *
from utils import * from utils import *
import shared
from settingsmixin import SettingsMixin from settingsmixin import SettingsMixin
class AccountMixin (object): class AccountMixin (object):
@ -215,7 +214,7 @@ class Ui_AddressWidget(QtGui.QTreeWidgetItem, AccountMixin, SettingsMixin):
BMConfigParser().set(str(self.address), 'label', str(value.toString().toUtf8())) BMConfigParser().set(str(self.address), 'label', str(value.toString().toUtf8()))
else: else:
BMConfigParser().set(str(self.address), 'label', str(value)) BMConfigParser().set(str(self.address), 'label', str(value))
shared.writeKeysFile() BMConfigParser().save()
return super(Ui_AddressWidget, self).setData(column, role, value) return super(Ui_AddressWidget, self).setData(column, role, value)
def setAddress(self, address): def setAddress(self, address):

View File

@ -143,7 +143,7 @@ class addressGenerator(threading.Thread, StoppableThread):
address, 'privSigningKey', privSigningKeyWIF) address, 'privSigningKey', privSigningKeyWIF)
BMConfigParser().set( BMConfigParser().set(
address, 'privEncryptionKey', privEncryptionKeyWIF) address, 'privEncryptionKey', privEncryptionKeyWIF)
shared.writeKeysFile() BMConfigParser().save()
# The API and the join and create Chan functionality # The API and the join and create Chan functionality
# both need information back from the address generator. # both need information back from the address generator.
@ -260,7 +260,7 @@ class addressGenerator(threading.Thread, StoppableThread):
address, 'privSigningKey', privSigningKeyWIF) address, 'privSigningKey', privSigningKeyWIF)
BMConfigParser().set( BMConfigParser().set(
address, 'privEncryptionKey', privEncryptionKeyWIF) address, 'privEncryptionKey', privEncryptionKeyWIF)
shared.writeKeysFile() BMConfigParser().save()
shared.UISignalQueue.put(('writeNewAddressToTable', ( shared.UISignalQueue.put(('writeNewAddressToTable', (
label, address, str(streamNumber)))) label, address, str(streamNumber))))

View File

@ -185,7 +185,7 @@ class singleWorker(threading.Thread, StoppableThread):
try: try:
BMConfigParser().set( BMConfigParser().set(
myAddress, 'lastpubkeysendtime', str(int(time.time()))) myAddress, 'lastpubkeysendtime', str(int(time.time())))
shared.writeKeysFile() BMConfigParser().save()
except: except:
# The user deleted the address out of the keys.dat file before this # The user deleted the address out of the keys.dat file before this
# finished. # finished.
@ -275,7 +275,7 @@ class singleWorker(threading.Thread, StoppableThread):
try: try:
BMConfigParser().set( BMConfigParser().set(
myAddress, 'lastpubkeysendtime', str(int(time.time()))) myAddress, 'lastpubkeysendtime', str(int(time.time())))
shared.writeKeysFile() BMConfigParser().save()
except: except:
# The user deleted the address out of the keys.dat file before this # The user deleted the address out of the keys.dat file before this
# finished. # finished.
@ -365,7 +365,7 @@ class singleWorker(threading.Thread, StoppableThread):
try: try:
BMConfigParser().set( BMConfigParser().set(
myAddress, 'lastpubkeysendtime', str(int(time.time()))) myAddress, 'lastpubkeysendtime', str(int(time.time())))
shared.writeKeysFile() BMConfigParser().save()
except Exception as err: except Exception as err:
logger.error('Error: Couldn\'t add the lastpubkeysendtime to the keys.dat file. Error message: %s' % err) logger.error('Error: Couldn\'t add the lastpubkeysendtime to the keys.dat file. Error message: %s' % err)

View File

@ -330,7 +330,7 @@ class sqlThread(threading.Thread):
BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0') BMConfigParser().set('bitmessagesettings', 'maxdownloadrate', '0')
BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0') BMConfigParser().set('bitmessagesettings', 'maxuploadrate', '0')
BMConfigParser().set('bitmessagesettings', 'settingsversion', '10') BMConfigParser().set('bitmessagesettings', 'settingsversion', '10')
shared.writeKeysFile() BMConfigParser().save()
# sanity check # sanity check
if BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') == 0: if BMConfigParser().getint('bitmessagesettings', 'maxacceptablenoncetrialsperbyte') == 0:
@ -433,7 +433,7 @@ class sqlThread(threading.Thread):
BMConfigParser().set('bitmessagesettings', 'smtpdeliver', '') BMConfigParser().set('bitmessagesettings', 'smtpdeliver', '')
if not BMConfigParser().has_option('bitmessagesettings', 'hidetrayconnectionnotifications'): if not BMConfigParser().has_option('bitmessagesettings', 'hidetrayconnectionnotifications'):
BMConfigParser().set('bitmessagesettings', 'hidetrayconnectionnotifications', 'false') BMConfigParser().set('bitmessagesettings', 'hidetrayconnectionnotifications', 'false')
shared.writeKeysFile() BMConfigParser().save()
# Are you hoping to add a new option to the keys.dat file of existing # Are you hoping to add a new option to the keys.dat file of existing
# Bitmessage users or modify the SQLite database? Add it right above this line! # Bitmessage users or modify the SQLite database? Add it right above this line!

View File

@ -1,6 +1,10 @@
import ConfigParser import ConfigParser
import datetime
import shutil
import os
from singleton import Singleton from singleton import Singleton
import state
@Singleton @Singleton
@ -44,3 +48,20 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
def items(self, section, raw=False, vars=None): def items(self, section, raw=False, vars=None):
return ConfigParser.ConfigParser.items(self, section, True, vars) return ConfigParser.ConfigParser.items(self, section, True, vars)
def save(self):
fileName = os.path.join(state.appdata, 'keys.dat')
fileNameBak = fileName + "." + datetime.datetime.now().strftime("%Y%j%H%M%S%f") + '.bak'
# create a backup copy to prevent the accidental loss due to the disk write failure
try:
shutil.copyfile(fileName, fileNameBak)
# The backup succeeded.
fileNameExisted = True
except:
# The backup failed. This can happen if the file didn't exist before.
fileNameExisted = False
# write the file
with open(fileName, 'wb') as configfile:
self.write(configfile)
# delete the backup
if fileNameExisted:
os.remove(fileNameBak)

View File

@ -1,5 +1,4 @@
import ConfigParser import ConfigParser
import shared
from configparser import BMConfigParser from configparser import BMConfigParser
import sys import sys
import os import os
@ -138,7 +137,7 @@ def loadConfig():
os.makedirs(state.appdata) os.makedirs(state.appdata)
if not sys.platform.startswith('win'): if not sys.platform.startswith('win'):
os.umask(0o077) os.umask(0o077)
shared.writeKeysFile() BMConfigParser().save()
_loadTrustedPeer() _loadTrustedPeer()

View File

@ -623,22 +623,4 @@ def openKeysFile():
else: else:
os.startfile(state.appdata + 'keys.dat') os.startfile(state.appdata + 'keys.dat')
def writeKeysFile():
fileName = state.appdata + 'keys.dat'
fileNameBak = fileName + "." + datetime.datetime.now().strftime("%Y%j%H%M%S%f") + '.bak'
# create a backup copy to prevent the accidental loss due to the disk write failure
try:
shutil.copyfile(fileName, fileNameBak)
# The backup succeeded.
fileNameExisted = True
except:
# The backup failed. This can happen if the file didn't exist before.
fileNameExisted = False
# write the file
with open(fileName, 'wb') as configfile:
BMConfigParser().write(configfile)
# delete the backup
if fileNameExisted:
os.remove(fileNameBak)
from debug import logger from debug import logger