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