Consistant text
[electrum-nvc.git] / plugins / labels.py
1 from electrum.util import print_error
2 from electrum_gui.i18n import _
3 import httplib, urllib
4 import hashlib
5 import json
6 from urlparse import urlparse, parse_qs
7 try:
8     import PyQt4
9 except:
10     sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
11
12 from PyQt4.QtGui import *
13 from PyQt4.QtCore import *
14 import PyQt4.QtCore as QtCore
15 import PyQt4.QtGui as QtGui
16 from electrum_gui import bmp, pyqrnative, BasePlugin
17 from electrum_gui.i18n import _
18
19 class Plugin(BasePlugin):
20
21     def __init__(self, gui):
22         self.target_host = 'labelectrum.herokuapp.com'
23         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, \
24 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\
25 To get started visit http://labelectrum.herokuapp.com/ to sign up for an account.'))
26
27         self.wallet = gui.wallet
28         self.gui = gui
29         self.config = gui.config
30         self.labels = self.wallet.labels
31         self.transactions = self.wallet.transactions
32
33         self.wallet_id = hashlib.sha256(str(self.config.get("master_public_key"))).digest().encode('hex')
34
35         addresses = [] 
36         for k, account in self.wallet.accounts.items():
37             for address in account[0]:
38                 addresses.append(address)
39
40         self.addresses = addresses
41
42     def auth_token(self):
43         return self.config.get("plugin_label_api_key")
44
45     def init_gui(self):
46         if self.is_enabled() and self.auth_token():
47             # If there is an auth token we can try to actually start syncing
48             self.full_pull()
49
50     def is_available(self):
51         return True
52
53     def set_label(self, item,label, changed):
54         if not changed:
55             return 
56
57         hashed = hashlib.sha256(item).digest().encode('hex')
58         bundle = {"label": {"external_id": hashed, "text": label}}
59         params = json.dumps(bundle)
60         connection = httplib.HTTPConnection(self.target_host)
61         connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
62
63         response = connection.getresponse()
64         if response.reason == httplib.responses[httplib.NOT_FOUND]:
65             return
66         response = json.loads(response.read())
67
68     def close_settings_dialog(self):
69         # When you enable the plugin for the first time this won't exist.
70         if self.is_enabled():
71             if hasattr(self, 'auth_token_edit'):
72                 self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
73             else:
74                 QMessageBox.information(None, _("Label sync loaded"), _("Please open the settings again to configure the label sync plugin."))
75
76     def create_settings_tab(self, tabs):
77         def check_for_api_key(api_key):
78             if api_key and len(api_key) > 12:
79               self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
80               self.upload.setEnabled(True)
81               self.download.setEnabled(True)
82             else:
83               self.upload.setEnabled(False)
84               self.download.setEnabled(False)
85
86         cloud_tab = QWidget()
87         layout = QGridLayout(cloud_tab)
88         layout.addWidget(QLabel("API Key: "),0,0)
89
90         self.auth_token_edit = QLineEdit(self.auth_token())
91         self.auth_token_edit.textChanged.connect(check_for_api_key)
92
93         layout.addWidget(self.auth_token_edit, 0,1,1,2)
94         layout.addWidget(QLabel("Label sync options: "),1,0)
95
96         self.upload = QPushButton("Force upload")
97         self.upload.clicked.connect(self.full_push)
98         layout.addWidget(self.upload, 1,1)
99
100         self.download = QPushButton("Force download")
101         self.download.clicked.connect(lambda: self.full_pull(True))
102         layout.addWidget(self.download, 1,2)
103
104         check_for_api_key(self.auth_token())
105
106         tabs.addTab(cloud_tab, "Label sync")
107
108     def full_push(self):
109         if self.do_full_push():
110             QMessageBox.information(None, _("Labels synced"), _("Your labels have been uploaded."))
111
112     def full_pull(self, force = False):
113         if self.do_full_pull(force) and force:
114             QMessageBox.information(None, _("Labels synced"), _("Your labels have been synced, please restart Electrum for the changes to take effect."))
115
116     def do_full_push(self):
117         bundle = {"labels": {}}
118         for key, value in self.labels.iteritems():
119             hashed = hashlib.sha256(key).digest().encode('hex')
120             bundle["labels"][hashed] = value
121
122         params = json.dumps(bundle)
123         connection = httplib.HTTPConnection(self.target_host)
124         connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
125
126         response = connection.getresponse()
127         if response.reason == httplib.responses[httplib.NOT_FOUND]:
128             return
129         try:
130             response = json.loads(response.read())
131         except ValueError as e:
132             return False
133
134         if "error" in response:
135             QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
136             return False
137
138         return True
139
140     def do_full_pull(self, force = False):
141         connection = httplib.HTTPConnection(self.target_host)
142         connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
143         response = connection.getresponse()
144         if response.reason == httplib.responses[httplib.NOT_FOUND]:
145             return
146         try:
147             response = json.loads(response.read())
148         except ValueError as e:
149             return False
150
151         if "error" in response:
152             QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
153             return False
154
155         for label in response:
156             for key in self.addresses:
157                 target_hashed = hashlib.sha256(key).digest().encode('hex')
158                 if label["external_id"] == target_hashed:
159                    if force or not self.labels.get(key):
160                        self.labels[key] = label["text"] 
161             for key, value in self.transactions.iteritems():
162                 target_hashed = hashlib.sha256(key).digest().encode('hex')
163                 if label["external_id"] == target_hashed:
164                    if force or not self.labels.get(key):
165                        self.labels[key] = label["text"] 
166         return True