Work in progress on Label syncing
[electrum-nvc.git] / plugins / labels.py
1 from electrum.util import print_error
2 import httplib, urllib
3 import hashlib
4 import json
5 from urlparse import urlparse, parse_qs
6 try:
7     import PyQt4
8 except:
9     sys.exit("Error: Could not import PyQt4 on Linux systems, you may try 'sudo apt-get install python-qt4'")
10
11 from PyQt4.QtGui import *
12 from PyQt4.QtCore import *
13 import PyQt4.QtCore as QtCore
14 import PyQt4.QtGui as QtGui
15
16 target_host = 'localhost:3000'
17 auth_token = 'jEnsNBb5fAR5rYSBNYnR'
18
19 def init(gui):
20     cloud_wallet = CloudWallet(gui.wallet)
21     gui.set_hook('create_settings_tab', add_settings_tab)
22     gui.set_hook('label_changed', label_changed)
23     cloud_wallet.full_pull()
24
25 def wallet_id(wallet):
26     return hashlib.sha256(str(wallet.get_master_public_key())).digest().encode('hex')
27
28
29 def label_changed(gui,item,label):
30     print "Label changed! Item: %s Label: %s label" % ( item, label)
31     global auth_token, target_host
32     hashed = hashlib.sha256(item).digest().encode('hex')
33     bundle = {"label": {"external_id": hashed, "text": label}}
34     params = json.dumps(bundle)
35     connection = httplib.HTTPConnection(target_host)
36     connection.request("POST", ("/api/wallets/%s/labels.json?auth_token=%s" % (wallet_id(gui.wallet), auth_token)), params, {'Content-Type': 'application/json'})
37
38     response = connection.getresponse()
39     if response.reason == httplib.responses[httplib.NOT_FOUND]:
40         return
41     response = json.loads(response.read())
42
43 def add_settings_tab(gui, tabs):
44       cloud_tab = QWidget()
45       layout = QGridLayout(cloud_tab)
46       layout.addWidget(QLabel("API Key: "),0,0)
47       layout.addWidget(QLineEdit(), 0,2)
48
49       layout.addWidget(QLabel("Label sync options: "),1,0)
50       layout.addWidget(QPushButton("Force upload"), 1,1)
51       layout.addWidget(QPushButton("Force download"), 1,2)
52
53       tabs.addTab(cloud_tab, "Label cloud")
54
55 def show():
56     print 'showing'
57
58 def get_info():
59     return 'Label sync', "Syncs your labels with LabElectrum. Labels are not encrypted, transactions and addresses are however."
60
61 def is_enabled():
62     return True
63
64 def toggle(gui):
65     return is_enabled()
66
67
68 class CloudWallet():
69     def __init__(self, wallet):
70         self.mpk = hashlib.sha256(str(wallet.get_master_public_key())).digest().encode('hex')
71         self.labels = wallet.labels
72         self.transactions = wallet.transactions
73
74         addresses = [] 
75         for k, account in wallet.accounts.items():
76             for address in account[0]:
77                 addresses.append(address)
78
79         self.addresses = addresses
80
81
82     def full_pull(self):
83         global target_host, auth_token
84         connection = httplib.HTTPConnection(target_host)
85         connection.request("GET", ("/api/wallets/%s/labels.json?auth_token=%s" % (self.mpk, auth_token)),"", {'Content-Type': 'application/json'})
86         response = connection.getresponse()
87         if response.reason == httplib.responses[httplib.NOT_FOUND]:
88             return
89
90         response = json.loads(response.read())
91         for label in response:
92             for key in self.addresses:
93                 target_hashed = hashlib.sha256(key).digest().encode('hex')
94                 if label["external_id"] == target_hashed:
95                    if not self.labels.get(key):
96                        self.labels[key] = label["text"] 
97             for key, value in self.transactions.iteritems():
98                 target_hashed = hashlib.sha256(key).digest().encode('hex')
99                 if label["external_id"] == target_hashed:
100                    if not self.labels.get(key):
101                        self.labels[key] = label["text"] 
102
103     def full_push(self):
104         global target_host, auth_token
105
106         bundle = {"labels": {}}
107         for key, value in self.labels.iteritems():
108             hashed = hashlib.sha256(key).digest().encode('hex')
109             bundle["labels"][hashed] = value
110
111         params = json.dumps(bundle)
112         connection = httplib.HTTPConnection(target_host)
113         connection.request("POST", ("/api/wallets/%s/labels/batch.json?auth_token=%s" % (self.mpk, auth_token)), params, {'Content-Type': 'application/json'})
114
115         response = connection.getresponse()
116         if response.reason == httplib.responses[httplib.NOT_FOUND]:
117             return
118         response = json.loads(response.read())