restore infobox
[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 requires_settings(self):
54         return True
55
56     def set_label(self, item,label, changed):
57         if not changed:
58             return 
59
60         hashed = hashlib.sha256(item).digest().encode('hex')
61         bundle = {"label": {"external_id": hashed, "text": label}}
62         params = json.dumps(bundle)
63         connection = httplib.HTTPConnection(self.target_host)
64         connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
65
66         response = connection.getresponse()
67         if response.reason == httplib.responses[httplib.NOT_FOUND]:
68             return
69         response = json.loads(response.read())
70
71     def settings_dialog(self):
72         def check_for_api_key(api_key):
73             if api_key and len(api_key) > 12:
74               self.config.set_key("plugin_label_api_key", str(self.auth_token_edit.text()))
75               self.upload.setEnabled(True)
76               self.download.setEnabled(True)
77               self.accept.setEnabled(True)
78             else:
79               self.upload.setEnabled(False)
80               self.download.setEnabled(False)
81               self.accept.setEnabled(False)
82
83         d = QDialog(self.gui)
84         layout = QGridLayout(d)
85         layout.addWidget(QLabel("API Key: "),0,0)
86
87         self.auth_token_edit = QLineEdit(self.auth_token())
88         self.auth_token_edit.textChanged.connect(check_for_api_key)
89
90         layout.addWidget(self.auth_token_edit, 0,1,1,2)
91         layout.addWidget(QLabel("Label sync options: "),1,0)
92
93         self.upload = QPushButton("Force upload")
94         self.upload.clicked.connect(self.full_push)
95         layout.addWidget(self.upload, 1,1)
96
97         self.download = QPushButton("Force download")
98         self.download.clicked.connect(lambda: self.full_pull(True))
99         layout.addWidget(self.download, 1,2)
100
101         c = QPushButton(_("Cancel"))
102         c.clicked.connect(d.reject)
103
104         self.accept = QPushButton(_("Done"))
105         self.accept.clicked.connect(d.accept)
106
107         layout.addWidget(c,2,1)
108         layout.addWidget(self.accept,2,2)
109
110         check_for_api_key(self.auth_token())
111
112         if d.exec_():
113           return True
114         else:
115           return False
116
117     def toggle(self):
118         enabled = not self.is_enabled()
119         self.set_enabled(enabled)
120         self.init_gui()
121
122         if not self.auth_token() and enabled: # First run, throw plugin settings in your face
123             if self.settings_dialog():
124               self.set_enabled(True)
125               return True
126             else:
127               self.set_enabled(False)
128               return False
129         return enabled
130
131     def full_push(self):
132         if self.do_full_push():
133             QMessageBox.information(None, _("Labels uploaded"), _("Your labels have been uploaded."))
134
135     def full_pull(self, force = False):
136         if self.do_full_pull(force) and force:
137             QMessageBox.information(None, _("Labels synchronized"), _("Your labels have been synchronized."))
138             self.gui.update_history_tab()
139             self.gui.update_completions()
140             self.gui.update_receive_tab()
141             self.gui.update_contacts_tab()
142
143     def do_full_push(self):
144         bundle = {"labels": {}}
145         for key, value in self.labels.iteritems():
146             hashed = hashlib.sha256(key).digest().encode('hex')
147             bundle["labels"][hashed] = value
148
149         params = json.dumps(bundle)
150         connection = httplib.HTTPConnection(self.target_host)
151         connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.wallet_id, self.auth_token())), params, {'Content-Type': 'application/json'})
152
153         response = connection.getresponse()
154         if response.reason == httplib.responses[httplib.NOT_FOUND]:
155             return
156         try:
157             response = json.loads(response.read())
158         except ValueError as e:
159             return False
160
161         if "error" in response:
162             QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
163             return False
164
165         return True
166
167     def do_full_pull(self, force = False):
168         connection = httplib.HTTPConnection(self.target_host)
169         connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.wallet_id, self.auth_token())),"", {'Content-Type': 'application/json'})
170         response = connection.getresponse()
171         if response.reason == httplib.responses[httplib.NOT_FOUND]:
172             return
173         try:
174             response = json.loads(response.read())
175         except ValueError as e:
176             return False
177
178         if "error" in response:
179             QMessageBox.warning(None, _("Error"),_("Could not sync labels: %s" % response["error"]))
180             return False
181
182         for label in response:
183             for key in self.addresses:
184                 target_hashed = hashlib.sha256(key).digest().encode('hex')
185                 if label["external_id"] == target_hashed:
186                    if force or not self.labels.get(key):
187                        self.labels[key] = label["text"] 
188             for key, value in self.transactions.iteritems():
189                 target_hashed = hashlib.sha256(key).digest().encode('hex')
190                 if label["external_id"] == target_hashed:
191                    if force or not self.labels.get(key):
192                        self.labels[key] = label["text"] 
193         return True