Update tests and fix URI parsing
[electrum-nvc.git] / lib / util.py
1 import os, sys, re, json
2 import platform
3 import shutil
4 from datetime import datetime
5 is_verbose = False
6
7
8 class MyEncoder(json.JSONEncoder):
9     def default(self, obj):
10         from transaction import Transaction
11         if isinstance(obj, Transaction):
12             return obj.as_dict()
13         return super(MyEncoder, self).default(obj)
14
15
16 def set_verbosity(b):
17     global is_verbose
18     is_verbose = b
19
20
21 def print_error(*args):
22     if not is_verbose: return
23     print_stderr(*args)
24
25 def print_stderr(*args):
26     args = [str(item) for item in args]
27     sys.stderr.write(" ".join(args) + "\n")
28     sys.stderr.flush()
29
30 def print_msg(*args):
31     # Stringify args
32     args = [str(item) for item in args]
33     sys.stdout.write(" ".join(args) + "\n")
34     sys.stdout.flush()
35
36 def print_json(obj):
37     try:
38         s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
39     except TypeError:
40         s = repr(obj)
41     sys.stdout.write(s + "\n")
42     sys.stdout.flush()
43
44 def user_dir():
45     if "HOME" in os.environ:
46         return os.path.join(os.environ["HOME"], ".electrum")
47     elif "APPDATA" in os.environ:
48         return os.path.join(os.environ["APPDATA"], "Electrum")
49     elif "LOCALAPPDATA" in os.environ:
50         return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
51     elif 'ANDROID_DATA' in os.environ:
52         return "/sdcard/electrum/"
53     else:
54         #raise Exception("No home directory found in environment variables.")
55         return
56
57 def appdata_dir():
58     """Find the path to the application data directory; add an electrum folder and return path."""
59     if platform.system() == "Windows":
60         return os.path.join(os.environ["APPDATA"], "Electrum")
61     elif platform.system() == "Linux":
62         return os.path.join(sys.prefix, "share", "electrum")
63     elif (platform.system() == "Darwin" or
64           platform.system() == "DragonFly" or
65           platform.system() == "OpenBSD" or
66           platform.system() == "FreeBSD" or
67           platform.system() == "NetBSD"):
68         return "/Library/Application Support/Electrum"
69     else:
70         raise Exception("Unknown system")
71
72
73 def get_resource_path(*args):
74     return os.path.join(".", *args)
75
76
77 def local_data_dir():
78     """Return path to the data folder."""
79     assert sys.argv
80     prefix_path = os.path.dirname(sys.argv[0])
81     local_data = os.path.join(prefix_path, "data")
82     return local_data
83
84
85 def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
86     from decimal import Decimal
87     s = Decimal(x)
88     sign, digits, exp = s.as_tuple()
89     digits = map(str, digits)
90     while len(digits) < decimal_point + 1:
91         digits.insert(0,'0')
92     digits.insert(-decimal_point,'.')
93     s = ''.join(digits).rstrip('0')
94     if sign:
95         s = '-' + s
96     elif is_diff:
97         s = "+" + s
98
99     p = s.find('.')
100     s += "0"*( 1 + num_zeros - ( len(s) - p ))
101     if whitespaces:
102         s += " "*( 1 + decimal_point - ( len(s) - p ))
103         s = " "*( 13 - decimal_point - ( p )) + s
104     return s
105
106
107 # Takes a timestamp and returns a string with the approximation of the age
108 def age(from_date, since_date = None, target_tz=None, include_seconds=False):
109     if from_date is None:
110         return "Unknown"
111
112     from_date = datetime.fromtimestamp(from_date)
113     if since_date is None:
114         since_date = datetime.now(target_tz)
115
116     distance_in_time = since_date - from_date
117     distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
118     distance_in_minutes = int(round(distance_in_seconds/60))
119
120     if distance_in_minutes <= 1:
121         if include_seconds:
122             for remainder in [5, 10, 20]:
123                 if distance_in_seconds < remainder:
124                     return "less than %s seconds ago" % remainder
125             if distance_in_seconds < 40:
126                 return "half a minute ago"
127             elif distance_in_seconds < 60:
128                 return "less than a minute ago"
129             else:
130                 return "1 minute ago"
131         else:
132             if distance_in_minutes == 0:
133                 return "less than a minute ago"
134             else:
135                 return "1 minute ago"
136     elif distance_in_minutes < 45:
137         return "%s minutes ago" % distance_in_minutes
138     elif distance_in_minutes < 90:
139         return "about 1 hour ago"
140     elif distance_in_minutes < 1440:
141         return "about %d hours ago" % (round(distance_in_minutes / 60.0))
142     elif distance_in_minutes < 2880:
143         return "1 day ago"
144     elif distance_in_minutes < 43220:
145         return "%d days ago" % (round(distance_in_minutes / 1440))
146     elif distance_in_minutes < 86400:
147         return "about 1 month ago"
148     elif distance_in_minutes < 525600:
149         return "%d months ago" % (round(distance_in_minutes / 43200))
150     elif distance_in_minutes < 1051200:
151         return "about 1 year ago"
152     else:
153         return "over %d years ago" % (round(distance_in_minutes / 525600))
154
155
156 # URL decode
157 #_ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
158 #urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
159
160 def parse_URI(uri):
161     import urlparse
162     import urllib
163     import bitcoin
164     from decimal import Decimal
165
166     if ':' not in uri:
167         assert bitcoin.is_address(uri)
168         return uri, None, None, None, None
169
170     u = urlparse.urlparse(uri)
171     assert u.scheme == 'bitcoin'
172
173     address = u.path
174     valid_address = bitcoin.is_address(address)
175
176     pq = urlparse.parse_qs(u.query)
177     
178     for k, v in pq.items():
179         if len(v)!=1:
180             raise Exception('Duplicate Key', k)
181
182     amount = label = message = request_url = ''
183     if 'amount' in pq:
184         am = pq['amount'][0]
185         m = re.match('([0-9\.]+)X([0-9])', am)
186         if m:
187             k = int(m.group(2)) - 8
188             amount = Decimal(m.group(1)) * pow(  Decimal(10) , k)
189         else:
190             amount = Decimal(am) * 100000000
191     if 'message' in pq:
192         message = pq['message'][0]
193     if 'label' in pq:
194         label = pq['label'][0]
195     if 'r' in pq:
196         request_url = urllib.quote(pq['r'][0], '/:?')
197         
198     if request_url != '':
199         return address, amount, label, message, request_url
200
201     assert valid_address
202
203     return address, amount, label, message, request_url
204
205
206 # Python bug (http://bugs.python.org/issue1927) causes raw_input
207 # to be redirected improperly between stdin/stderr on Unix systems
208 def raw_input(prompt=None):
209     if prompt:
210         sys.stdout.write(prompt)
211     return builtin_raw_input()
212 import __builtin__
213 builtin_raw_input = __builtin__.raw_input
214 __builtin__.raw_input = raw_input