Updated label help 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 socket
5 import hashlib
6 import json
7 from urlparse import urlparse, parse_qs
8 try:
9     import PyQt4
10 except:
11     sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
12
13 from PyQt4.QtGui import *
14 from PyQt4.QtCore import *
15 import PyQt4.QtCore as QtCore
16 import PyQt4.QtGui as QtGui
17 import aes
18 import base64
19 from electrum_gui import bmp, pyqrnative, BasePlugin
20 from electrum_gui.i18n import _
21 from electrum_gui.gui_classic import HelpButton
22
23 class Plugin(BasePlugin):
24     def version(self):
25         return "0.2.1"
26
27     def encode(self, message):
28         encrypted = aes.encryptData(self.encode_password, unicode(message))
29         encoded_message = base64.b64encode(encrypted)
30
31         return encoded_message
32
33     def decode(self, message):
34         decoded_message = aes.decryptData(self.encode_password, base64.b64decode(unicode(message)) )
35
36         return decoded_message
37
38     def __init__(self, gui):
39         self.target_host = 'labelectrum.herokuapp.com'
40         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,  \
41 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.\n\n\
42 To get started visit http://labelectrum.herokuapp.com/ to sign up for an account.'))
43
44         self.wallet = gui.wallet
45         self.gui = gui
46         self.config = gui.config
47         self.labels = self.wallet.labels
48         self.transactions = self.wallet.transactions
49         self.encode_password = hashlib.sha1(self.config.get("master_public_key")).digest().encode('hex')[:32]
50
51         self.wallet_id = hashlib.sha256(str(self.config.get("master_public_key"))).digest().encode('hex')
52
53         addresses = [] 
54         for k, account in self.wallet.accounts.items():
55             for address in account[0]:
56                 addresses.append(address)
57
58         self.addresses = addresses
59
60     def auth_token(self):
61         return self.config.get("plugin_label_api_key")
62
63     def init_gui(self):
64         if self.is_enabled() and self.auth_token():
65             # If there is an auth token we can try to actually start syncing
66             self.full_pull()
67
68     def is_available(self):
69         return True
70
71     def requires_settings(self):
72         return True
73
74     def set_label(self, item,label, changed):
75         if not changed:
76             return 
77         try:
78             bundle = {"label": {"external_id": self.encode(item), "text": self.encode(label)}}
79             params = json.dumps(bundle)
80             connection = httplib.HTTPConnection(self.target_host)
81             connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
82
83             response = connection.getresponse()
84             if response.reason == httplib.responses[httplib.NOT_FOUND]:
85                 return
86             response = json.loads(response.read())
87         except socket.gaierror as e:
88             print_error('Error connecting to service: %s ' %  e)
89             return False
90
91     def settings_dialog(self):
92         def check_for_api_key(api_key):
93             if api_key and len(api_key) > 12:
94               self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
95               self.upload.setEnabled(True)
96               self.download.setEnabled(True)
97               self.accept.setEnabled(True)
98             else:
99               self.upload.setEnabled(False)
100               self.download.setEnabled(False)
101               self.accept.setEnabled(False)
102
103         d = QDialog(self.gui)
104         layout = QGridLayout(d)
105         layout.addWidget(QLabel("API Key: "),0,0)
106
107         self.auth_token_edit = QLineEdit(self.auth_token())
108         self.auth_token_edit.textChanged.connect(check_for_api_key)
109
110         layout.addWidget(QLabel("Label sync options: "),2,0)
111         layout.addWidget(self.auth_token_edit, 0,1,1,2)
112
113         decrypt_key_text =  QLineEdit(self.encode_password)
114         decrypt_key_text.setReadOnly(True)
115         layout.addWidget(decrypt_key_text, 1,1)
116         layout.addWidget(QLabel("Decryption key: "),1,0)
117         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)
118
119         self.upload = QPushButton("Force upload")
120         self.upload.clicked.connect(self.full_push)
121         layout.addWidget(self.upload, 2,1)
122
123         self.download = QPushButton("Force download")
124         self.download.clicked.connect(lambda: self.full_pull(True))
125         layout.addWidget(self.download, 2,2)
126
127         c = QPushButton(_("Cancel"))
128         c.clicked.connect(d.reject)
129
130         self.accept = QPushButton(_("Done"))
131         self.accept.clicked.connect(d.accept)
132
133         layout.addWidget(c,3,1)
134         layout.addWidget(self.accept,3,2)
135
136         check_for_api_key(self.auth_token())
137
138         if d.exec_():
139           return True
140         else:
141           return False
142
143     def toggle(self):
144         enabled = not self.is_enabled()
145         self.set_enabled(enabled)
146         self.init_gui()
147
148         if not self.auth_token() and enabled: # First run, throw plugin settings in your face
149             if self.settings_dialog():
150               self.set_enabled(True)
151               return True
152             else:
153               self.set_enabled(False)
154               return False
155         return enabled
156
157     def full_push(self):
158         if self.do_full_push():
159             QMessageBox.information(None, _("Labels uploaded"), _("Your labels have been uploaded."))
160
161     def full_pull(self, force = False):
162         if self.do_full_pull(force) and force:
163             QMessageBox.information(None, _("Labels synchronized"), _("Your labels have been synchronized."))
164             self.gui.update_history_tab()
165             self.gui.update_completions()
166             self.gui.update_receive_tab()
167             self.gui.update_contacts_tab()
168
169     def do_full_push(self):
170         try:
171             bundle = {"labels": {}}
172             for key, value in self.labels.iteritems():
173                 encoded = self.encode(key)
174                 bundle["labels"][encoded] = self.encode(value)
175
176             params = json.dumps(bundle)
177             connection = httplib.HTTPConnection(self.target_host)
178             connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
179
180             response = connection.getresponse()
181             if response.reason == httplib.responses[httplib.NOT_FOUND]:
182                 return
183             try:
184                 response = json.loads(response.read())
185             except ValueError as e:
186                 return False
187
188             if "error" in response:
189                 QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
190                 return False
191
192             return True
193         except socket.gaierror as e:
194             print_error('Error connecting to service: %s ' %  e)
195             return False
196
197     def do_full_pull(self, force = False):
198         try:
199             connection = httplib.HTTPConnection(self.target_host)
200             connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
201             response = connection.getresponse()
202             if response.reason == httplib.responses[httplib.NOT_FOUND]:
203                 return
204             try:
205                 response = json.loads(response.read())
206             except ValueError as e:
207                 return False
208
209             if "error" in response:
210                 QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
211                 return False
212
213             for label in response:
214                  decoded_key = self.decode(label["external_id"]) 
215                  decoded_label = self.decode(label["text"]) 
216                  if force or not self.labels.get(decoded_key):
217                      self.labels[decoded_key] = decoded_label 
218             return True
219         except socket.gaierror as e:
220             print_error('Error connecting to service: %s ' %  e)
221             return False