AmountEdit:get_amount
[electrum-nvc.git] / plugins / labels.py
index 62a9144..83609b0 100644 (file)
 from electrum.util import print_error
-from electrum_gui.i18n import _
+
 import httplib, urllib
+import socket
 import hashlib
 import json
 from urlparse import urlparse, parse_qs
 try:
     import PyQt4
-except:
+except Exception:
     sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
 
 from PyQt4.QtGui import *
 from PyQt4.QtCore import *
 import PyQt4.QtCore as QtCore
 import PyQt4.QtGui as QtGui
+import aes
+import base64
+from electrum.plugins import BasePlugin
+from electrum.i18n import _
 
-target_host = 'labelectrum.herokuapp.com'
-config = {}
-
-def is_available():
-    return True
-
-def auth_token():
-    global config
-    return config.get("plugin_label_api_key")
+from electrum_gui.qt import HelpButton, EnterButton
 
-def init(gui):
-    """If you want to give this a spin create a account at the target_host url and put it in your user dir config
-    file with the label_api_key."""
+class Plugin(BasePlugin):
 
-    global config
-    config = gui.config
+    def fullname(self):
+        return _('Label Sync')
 
-    if config.get('plugin_label_enabled'):
-        gui.set_hook('create_settings_tab', add_settings_tab)
-        gui.set_hook('close_settings_dialog', close_settings_dialog)
+    def description(self):
+        return '%s\n\n%s%s%s' % (_("This plugin can sync your labels across multiple Electrum installs by using a remote database to save your data. Labels, transactions and addresses are all sent and stored encrypted on the remote server. This code might increase the load of your wallet with a few microseconds as it will sync labels on each startup."), _("To get started visit"), " http://labelectrum.herokuapp.com/ ", _(" to sign up for an account."))
 
-        if not auth_token():
-          return 
+    def version(self):
+        return "0.2.1"
 
-        cloud_wallet = CloudWallet(gui.wallet)
-        gui.set_hook('set_label', set_label)
+    def encode(self, message):
+        encrypted = aes.encryptData(self.encode_password, unicode(message))
+        encoded_message = base64.b64encode(encrypted)
 
-        cloud_wallet.full_pull()
+        return encoded_message
 
-def wallet_id():
-    global config
-    return hashlib.sha256(str(config.get("master_public_key"))).digest().encode('hex')
+    def decode(self, message):
+        decoded_message = aes.decryptData(self.encode_password, base64.b64decode(unicode(message)) )
 
-def set_label(gui, item,label, changed):
-    if not changed:
-        return 
+        return decoded_message
 
-    print "Label changed! Item: %s Label: %s label" % ( item, label)
-    global target_host
-    hashed = hashlib.sha256(item).digest().encode('hex')
-    bundle = {"label": {"external_id": hashed, "text": label}}
-    params = json.dumps(bundle)
-    connection = httplib.HTTPConnection(target_host)
-    connection.request("POST", ("/api/wallets/%s/labels.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
-    response = json.loads(response.read())
+    def init(self):
+        self.target_host = 'labelectrum.herokuapp.com'
+        self.window = self.gui.main_window
 
-def close_settings_dialog(gui):
-    global config
-
-    # When you enable the plugin for the first time this won't exist.
-    if is_enabled():
-        if hasattr(gui, 'auth_token_edit'):
-            config.set_key("plugin_label_api_key", str(gui.auth_token_edit.text()))
-        else:
-            QMessageBox.information(None, _("Cloud plugin loaded"), _("Please open the settings again to configure the label-cloud plugin."))
-
-def add_settings_tab(gui, tabs):
-    def check_for_api_key(api_key):
-        global config
-        if api_key and len(api_key) > 12:
-          config.set_key("plugin_label_api_key", str(gui.auth_token_edit.text()))
-          upload.setEnabled(True)
-          download.setEnabled(True)
+    def load_wallet(self, wallet):
+        self.wallet = wallet
+        if self.wallet.get_master_public_key():
+            mpk = self.wallet.get_master_public_key()
         else:
-          upload.setEnabled(False)
-          download.setEnabled(False)
-
-    cloud_tab = QWidget()
-    layout = QGridLayout(cloud_tab)
-    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?
-    gui.auth_token_edit = QLineEdit(auth_token())
-    gui.auth_token_edit.textChanged.connect(check_for_api_key)
-
-    layout.addWidget(gui.auth_token_edit, 0,1,1,2)
-    layout.addWidget(QLabel("Label cloud options: "),1,0)
-
-    upload = QPushButton("Force upload")
-    upload.clicked.connect(lambda: full_push(gui.wallet))
-    layout.addWidget(upload, 1,1)
+            mpk = self.wallet.master_public_keys["m/0'/"][1]
+        self.encode_password = hashlib.sha1(mpk).digest().encode('hex')[:32]
+        self.wallet_id = hashlib.sha256(mpk).digest().encode('hex')
 
-    download = QPushButton("Force download")
-    download.clicked.connect(lambda: full_pull(gui.wallet))
-    layout.addWidget(download, 1,2)
-
-    gui.cloud_tab = cloud_tab
-    check_for_api_key(auth_token())
-
-    tabs.addTab(cloud_tab, "Label cloud")
-
-def full_push(wallet):
-    cloud_wallet = CloudWallet(wallet)
-    cloud_wallet.full_push()
-    QMessageBox.information(None, _("Labels synced"), _("Your labels have been uploaded."))
-
-def full_pull(wallet):
-    cloud_wallet = CloudWallet(wallet)
-    cloud_wallet.full_pull(True)
-    QMessageBox.information(None, _("Labels synced"), _("Your labels have been synced, please restart Electrum for the changes to take effect."))
-
-def show():
-    print 'showing'
-
-def get_info():
-    return 'Label sync', "Syncs your labels with 'the cloud'. 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."
-
-def is_enabled():
-    return config.get('plugin_label_enabled') is True
+        addresses = [] 
+        for account in self.wallet.accounts.values():
+            for address in account.get_addresses(0):
+                addresses.append(address)
 
-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)
+        self.addresses = addresses
 
-    if enabled:
-        init(gui)
-    return enabled
+        if self.auth_token():
+            # If there is an auth token we can try to actually start syncing
+            self.full_pull()
 
-# This can probably be refactored into plain top level methods instead of a class
-class CloudWallet():
-    def __init__(self, wallet):
-        self.labels = wallet.labels
-        self.transactions = wallet.transactions
+    def auth_token(self):
+        return self.config.get("plugin_label_api_key")
 
-        addresses = [] 
-        for k, account in wallet.accounts.items():
-            for address in account[0]:
-                addresses.append(address)
+    def is_available(self):
+        return True
 
-        self.addresses = addresses
+    def requires_settings(self):
+        return True
 
-    def full_pull(self, force = False):
-        global target_host
-        connection = httplib.HTTPConnection(target_host)
-        connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (wallet_id(), auth_token())),"", {'Content-Type': 'application/json'})
-        response = connection.getresponse()
-        if response.reason == httplib.responses[httplib.NOT_FOUND]:
-            return
+    def set_label(self, item,label, changed):
+        if not changed:
+            return 
         try:
+            bundle = {"label": {"external_id": self.encode(item), "text": self.encode(label)}}
+            params = json.dumps(bundle)
+            connection = httplib.HTTPConnection(self.target_host)
+            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()
+            if response.reason == httplib.responses[httplib.NOT_FOUND]:
+                return
             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 
+        except socket.gaierror as e:
+            print_error('Error connecting to service: %s ' %  e)
+            return False
+
+    def settings_widget(self, window):
+        return EnterButton(_('Settings'), self.settings_dialog)
+
+    def settings_dialog(self):
+        def check_for_api_key(api_key):
+            if api_key and len(api_key) > 12:
+              self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
+              self.upload.setEnabled(True)
+              self.download.setEnabled(True)
+              self.accept.setEnabled(True)
+            else:
+              self.upload.setEnabled(False)
+              self.download.setEnabled(False)
+              self.accept.setEnabled(False)
+
+        d = QDialog()
+        layout = QGridLayout(d)
+        layout.addWidget(QLabel("API Key: "),0,0)
+
+        self.auth_token_edit = QLineEdit(self.auth_token())
+        self.auth_token_edit.textChanged.connect(check_for_api_key)
+
+        layout.addWidget(QLabel("Label sync options: "),2,0)
+        layout.addWidget(self.auth_token_edit, 0,1,1,2)
+
+        decrypt_key_text =  QLineEdit(self.encode_password)
+        decrypt_key_text.setReadOnly(True)
+        layout.addWidget(decrypt_key_text, 1,1)
+        layout.addWidget(QLabel("Decryption key: "),1,0)
+        layout.addWidget(HelpButton("This key can be used on the LabElectrum website to decrypt your data in case you want to review it online."),1,2)
+
+        self.upload = QPushButton("Force upload")
+        self.upload.clicked.connect(self.full_push)
+        layout.addWidget(self.upload, 2,1)
+
+        self.download = QPushButton("Force download")
+        self.download.clicked.connect(lambda: self.full_pull(True))
+        layout.addWidget(self.download, 2,2)
+
+        c = QPushButton(_("Cancel"))
+        c.clicked.connect(d.reject)
+
+        self.accept = QPushButton(_("Done"))
+        self.accept.clicked.connect(d.accept)
+
+        layout.addWidget(c,3,1)
+        layout.addWidget(self.accept,3,2)
+
+        check_for_api_key(self.auth_token())
+
+        if d.exec_():
+          return True
+        else:
+          return False
 
-        for label in response:
-            for key in self.addresses:
-                target_hashed = hashlib.sha256(key).digest().encode('hex')
-                if label["external_id"] == target_hashed:
-                   if force or not self.labels.get(key):
-                       self.labels[key] = label["text"] 
-            for key, value in self.transactions.iteritems():
-                target_hashed = hashlib.sha256(key).digest().encode('hex')
-                if label["external_id"] == target_hashed:
-                   if force or not self.labels.get(key):
-                       self.labels[key] = label["text"] 
+    def enable(self):
+        if not self.auth_token(): # First run, throw plugin settings in your face
+            self.init()
+            self.load_wallet(self.gui.main_window.wallet)
+            if self.settings_dialog():
+                self.set_enabled(True)
+                return True
+            else:
+                self.set_enabled(False)
+                return False
 
-    def full_push(self):
-        global target_host
+        self.set_enabled(True)
+        return True
 
-        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'})
+    def full_push(self):
+        if self.do_full_push():
+            QMessageBox.information(None, _("Labels uploaded"), _("Your labels have been uploaded."))
 
-        response = connection.getresponse()
-        if response.reason == httplib.responses[httplib.NOT_FOUND]:
-            return
+    def full_pull(self, force = False):
+        if self.do_full_pull(force) and force:
+            QMessageBox.information(None, _("Labels synchronized"), _("Your labels have been synchronized."))
+            self.window.update_history_tab()
+            self.window.update_completions()
+            self.window.update_receive_tab()
+            self.window.update_contacts_tab()
+
+    def do_full_push(self):
         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 
+            bundle = {"labels": {}}
+            for key, value in self.wallet.labels.iteritems():
+                encoded = self.encode(key)
+                bundle["labels"][encoded] = self.encode(value)
+
+            params = json.dumps(bundle)
+            connection = httplib.HTTPConnection(self.target_host)
+            connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.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 False
+
+            if "error" in response:
+                QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
+                return False
+
+            return True
+        except socket.gaierror as e:
+            print_error('Error connecting to service: %s ' %  e)
+            return False
+
+    def do_full_pull(self, force = False):
+        try:
+            connection = httplib.HTTPConnection(self.target_host)
+            connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'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 False
+
+            if "error" in response:
+                QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
+                return False
+
+            for label in response:
+                 decoded_key = self.decode(label["external_id"]) 
+                 decoded_label = self.decode(label["text"]) 
+                 if force or not self.wallet.labels.get(decoded_key):
+                     self.wallet.labels[decoded_key] = decoded_label 
+            return True
+        except socket.gaierror as e:
+            print_error('Error connecting to service: %s ' %  e)
+            return False