Browse Source

Rewrote plugin to new format

283
Maran 12 years ago
parent
commit
bafac9dc83
  1. 4
      gui/gui_classic.py
  2. 205
      plugins/labels.py

4
gui/gui_classic.py

@ -2015,7 +2015,7 @@ class ElectrumWindow(QMainWindow):
traceback.print_exc(file=sys.stdout) traceback.print_exc(file=sys.stdout)
grid_plugins.setRowStretch(i+1,1) grid_plugins.setRowStretch(i+1,1)
self.run_hook('create_settings_tab', (tabs,)) self.run_hook('create_settings_tab', tabs)
vbox.addLayout(ok_cancel_buttons(d)) vbox.addLayout(ok_cancel_buttons(d))
d.setLayout(vbox) d.setLayout(vbox)
@ -2079,7 +2079,7 @@ class ElectrumWindow(QMainWindow):
self.config.set_key('currency', cur_request, True) self.config.set_key('currency', cur_request, True)
self.update_wallet() self.update_wallet()
self.run_hook('close_settings_dialog', ()) self.run_hook('close_settings_dialog')
if need_restart: if need_restart:
QMessageBox.warning(self, _('Success'), _('Please restart Electrum to activate the new GUI settings'), _('OK')) QMessageBox.warning(self, _('Success'), _('Please restart Electrum to activate the new GUI settings'), _('OK'))

205
plugins/labels.py

@ -13,163 +13,151 @@ from PyQt4.QtGui import *
from PyQt4.QtCore import * from PyQt4.QtCore import *
import PyQt4.QtCore as QtCore import PyQt4.QtCore as QtCore
import PyQt4.QtGui as QtGui import PyQt4.QtGui as QtGui
from electrum_gui import bmp, pyqrnative, BasePlugin
from electrum_gui.i18n import _
target_host = 'labelectrum.herokuapp.com' class Plugin(BasePlugin):
config = {}
def is_available(): def __init__(self, gui):
return True self.target_host = 'labelectrum.herokuapp.com'
#self.target_host = 'localhost:3000'
BasePlugin.__init__(self, gui, 'labels', _('Label Sync'),_('This plugin can sync your labels accross multiple Electrum installs by using a remote database to save your data. Labels are not encrypted, \
transactions and addresses are however. This code might increase the load of your wallet with a few micoseconds as it will sync labels on each startup.\n\n\
To get started visit http://labelectrum.herokuapp.com/ to sign up for an account.'))
def auth_token(): self.wallet = gui.wallet
global config self.gui = gui
return config.get("plugin_label_api_key") self.config = gui.config
self.labels = self.wallet.labels
self.transactions = self.wallet.transactions
def init(gui): self.wallet_id = hashlib.sha256(str(self.config.get("master_public_key"))).digest().encode('hex')
global config
config = gui.config
if config.get('plugin_label_enabled'): addresses = []
gui.set_hook('create_settings_tab', add_settings_tab) for k, account in self.wallet.accounts.items():
gui.set_hook('close_settings_dialog', close_settings_dialog) for address in account[0]:
addresses.append(address)
if not auth_token(): self.addresses = addresses
return
cloud_wallet = CloudWallet(gui.wallet)
gui.set_hook('set_label', set_label)
cloud_wallet.full_pull() def auth_token(self):
return self.config.get("plugin_label_api_key")
def wallet_id(): def init_gui(self):
global config if self.is_enabled() and self.auth_token():
return hashlib.sha256(str(config.get("master_public_key"))).digest().encode('hex') self.enabled = True
# If there is an auth token we can try to actually start syncing
self.full_pull()
def set_label(gui, item,label, changed): def is_available(self):
return True
def set_label(self, item,label, changed):
if not changed: if not changed:
return return
print "Label changed! Item: %s Label: %s label" % ( item, label) print "Label changed! Item: %s Label: %s label" % ( item, label)
global target_host
hashed = hashlib.sha256(item).digest().encode('hex') hashed = hashlib.sha256(item).digest().encode('hex')
bundle = {"label": {"external_id": hashed, "text": label}} bundle = {"label": {"external_id": hashed, "text": label}}
params = json.dumps(bundle) params = json.dumps(bundle)
connection = httplib.HTTPConnection(target_host) connection = httplib.HTTPConnection(self.target_host)
connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (wallet_id(), auth_token())), params, {'Content-Type': 'application/json'}) connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
response = connection.getresponse() response = connection.getresponse()
if response.reason == httplib.responses[httplib.NOT_FOUND]: if response.reason == httplib.responses[httplib.NOT_FOUND]:
return return
response = json.loads(response.read()) response = json.loads(response.read())
def close_settings_dialog(gui): def close_settings_dialog(self):
global config
# When you enable the plugin for the first time this won't exist. # When you enable the plugin for the first time this won't exist.
if is_enabled(): if self.is_enabled():
if hasattr(gui, 'auth_token_edit'): if hasattr(self, 'auth_token_edit'):
config.set_key("plugin_label_api_key", str(gui.auth_token_edit.text())) self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
else: else:
QMessageBox.information(None, _("Cloud plugin loaded"), _("Please open the settings again to configure the label-cloud plugin.")) QMessageBox.information(None, _("Cloud plugin loaded"), _("Please open the settings again to configure the label-cloud plugin."))
def add_settings_tab(gui, tabs): def create_settings_tab(self, tabs):
def check_for_api_key(api_key): def check_for_api_key(api_key):
global config
if api_key and len(api_key) > 12: if api_key and len(api_key) > 12:
config.set_key("plugin_label_api_key", str(gui.auth_token_edit.text())) self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
upload.setEnabled(True) self.upload.setEnabled(True)
download.setEnabled(True) self.download.setEnabled(True)
else: else:
upload.setEnabled(False) self.upload.setEnabled(False)
download.setEnabled(False) self.download.setEnabled(False)
cloud_tab = QWidget() cloud_tab = QWidget()
layout = QGridLayout(cloud_tab) layout = QGridLayout(cloud_tab)
layout.addWidget(QLabel("API Key: "),0,0) layout.addWidget(QLabel("API Key: "),0,0)
# TODO: I need to add it to the Electrum GUI here so I can retrieve it later when the settings dialog is closed, is there a better way to do this? self.auth_token_edit = QLineEdit(self.auth_token())
gui.auth_token_edit = QLineEdit(auth_token()) self.auth_token_edit.textChanged.connect(check_for_api_key)
gui.auth_token_edit.textChanged.connect(check_for_api_key)
layout.addWidget(gui.auth_token_edit, 0,1,1,2) layout.addWidget(self.auth_token_edit, 0,1,1,2)
layout.addWidget(QLabel("Label cloud options: "),1,0) layout.addWidget(QLabel("Label sync options: "),1,0)
upload = QPushButton("Force upload") self.upload = QPushButton("Force upload")
upload.clicked.connect(lambda: full_push(gui.wallet)) self.upload.clicked.connect(self.full_push)
layout.addWidget(upload, 1,1) layout.addWidget(self.upload, 1,1)
download = QPushButton("Force download") self.download = QPushButton("Force download")
download.clicked.connect(lambda: full_pull(gui.wallet)) self.download.clicked.connect(lambda: self.full_pull(True))
layout.addWidget(download, 1,2) layout.addWidget(self.download, 1,2)
gui.cloud_tab = cloud_tab check_for_api_key(self.auth_token())
check_for_api_key(auth_token())
tabs.addTab(cloud_tab, "Label cloud") tabs.addTab(cloud_tab, "Label cloud")
def full_push(wallet): def full_push(self):
cloud_wallet = CloudWallet(wallet) if self.do_full_push():
cloud_wallet.full_push()
QMessageBox.information(None, _("Labels synced"), _("Your labels have been uploaded.")) QMessageBox.information(None, _("Labels synced"), _("Your labels have been uploaded."))
def full_pull(wallet): def full_pull(self, force = False):
cloud_wallet = CloudWallet(wallet) if self.do_full_pull(force) and force:
cloud_wallet.full_pull(True)
QMessageBox.information(None, _("Labels synced"), _("Your labels have been synced, please restart Electrum for the changes to take effect.")) QMessageBox.information(None, _("Labels synced"), _("Your labels have been synced, please restart Electrum for the changes to take effect."))
def show(): def do_full_push(self):
print 'showing' bundle = {"labels": {}}
for key, value in self.labels.iteritems():
def get_info(): hashed = hashlib.sha256(key).digest().encode('hex')
return 'Label cloud', "This plugin can sync your labels accross multiple Electrum instances by using a remote database to save your data. Labels are not encrypted, \ bundle["labels"][hashed] = value
transactions and addresses are however. This code might increase the load of your wallet with a few micoseconds as it will sync labels on each startup.\n\n\
To get started visit http://labelectrum.herokuapp.com/ to sign up for an account."
def is_enabled():
return config.get('plugin_label_enabled') is True
def toggle(gui):
if not is_enabled():
enabled = True
else:
enabled = False
gui.unset_hook('create_settings_tab', add_settings_tab)
gui.unset_hook('close_settings_dialog', close_settings_dialog)
config.set_key('plugin_label_enabled', enabled, True)
if enabled: params = json.dumps(bundle)
init(gui) connection = httplib.HTTPConnection(self.target_host)
return enabled connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
# This can probably be refactored into plain top level methods instead of a class response = connection.getresponse()
class CloudWallet(): if response.reason == httplib.responses[httplib.NOT_FOUND]:
def __init__(self, wallet): return
self.labels = wallet.labels try:
self.transactions = wallet.transactions response = json.loads(response.read())
except ValueError as e:
return False
addresses = [] if "error" in response:
for k, account in wallet.accounts.items(): QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
for address in account[0]: return False
addresses.append(address)
self.addresses = addresses return True
def full_pull(self, force = False): def do_full_pull(self, force = False):
global target_host print "Pulling info, force: %s" % force
connection = httplib.HTTPConnection(target_host) connection = httplib.HTTPConnection(self.target_host)
connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (wallet_id(), auth_token())),"", {'Content-Type': 'application/json'}) connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
response = connection.getresponse() response = connection.getresponse()
if response.reason == httplib.responses[httplib.NOT_FOUND]: if response.reason == httplib.responses[httplib.NOT_FOUND]:
return return
try: try:
response = json.loads(response.read()) response = json.loads(response.read())
except ValueError as e: except ValueError as e:
return return False
if "error" in response: if "error" in response:
QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"])) QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
return return False
print response
for label in response: for label in response:
for key in self.addresses: for key in self.addresses:
target_hashed = hashlib.sha256(key).digest().encode('hex') target_hashed = hashlib.sha256(key).digest().encode('hex')
@ -181,27 +169,4 @@ class CloudWallet():
if label["external_id"] == target_hashed: if label["external_id"] == target_hashed:
if force or not self.labels.get(key): if force or not self.labels.get(key):
self.labels[key] = label["text"] self.labels[key] = label["text"]
return True
def full_push(self):
global target_host
bundle = {"labels": {}}
for key, value in self.labels.iteritems():
hashed = hashlib.sha256(key).digest().encode('hex')
bundle["labels"][hashed] = value
params = json.dumps(bundle)
connection = httplib.HTTPConnection(target_host)
connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (wallet_id(), auth_token())), params, {'Content-Type': 'application/json'})
response = connection.getresponse()
if response.reason == httplib.responses[httplib.NOT_FOUND]:
return
try:
response = json.loads(response.read())
except ValueError as e:
return
if "error" in response:
QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
return

Loading…
Cancel
Save