eb3571a88e197bdc0db6e8ee88467d38c8dc8107
[electrum-nvc.git] / lib / qrscanner.py
1 from util import print_error
2
3 try:
4     import zbar
5 except ImportError:    
6     print_error("Install zbar package to enable QR scans")
7     zbar = None
8
9 from urlparse import urlparse, parse_qs
10
11 def is_available():
12     if not zbar:
13         return False
14     return True
15
16 def scan_qr():
17     proc = zbar.Processor()
18     proc.init()
19     proc.visible = True
20
21     while True:
22         try:
23             proc.process_one()
24         except:
25             # User closed the preview window
26             return {}
27
28         for r in proc.results:
29             if str(r.type) != 'QRCODE':
30                 continue
31
32             return parse_uri(r.data)
33         
34 def parse_uri(uri):
35     if ':' not in uri:
36         # It's just an address (not BIP21)
37         return {'address': uri}
38
39     if '//' not in uri:
40         # Workaround for urlparse, it don't handle bitcoin: URI properly
41         uri = uri.replace(':', '://')
42         
43     uri = urlparse(uri)
44     result = {'address': uri.netloc} 
45     
46     if uri.path.startswith('?'):
47         params = parse_qs(uri.path[1:])
48     else:
49         params = parse_qs(uri.path)    
50
51     for k,v in params.items():
52         if k in ('amount', 'label', 'message'):
53             result[k] = v[0]
54         
55     return result    
56
57 if __name__ == '__main__':
58     # Run some tests
59     
60     assert(parse_uri('1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
61            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
62
63     assert(parse_uri('bitcoin://1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
64            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
65     
66     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN') ==
67            {'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
68     
69     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10') ==
70            {'amount': '10', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
71     
72     assert(parse_uri('bitcoin:1Marek48fwU7mugmSe186do2QpUkBnpzSN?amount=10&label=slush&message=Small%20tip%20to%20slush') ==
73            {'amount': '10', 'label': 'slush', 'message': 'Small tip to slush', 'address': '1Marek48fwU7mugmSe186do2QpUkBnpzSN'})
74     
75