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