fix bug with hex_to_int; remove unused function
[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 = True
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 def print_error(*args):
21     if not is_verbose: return
22     args = [str(item) for item in args]
23     sys.stderr.write(" ".join(args) + "\n")
24     sys.stderr.flush()
25
26 def print_msg(*args):
27     # Stringify args
28     args = [str(item) for item in args]
29     sys.stdout.write(" ".join(args) + "\n")
30     sys.stdout.flush()
31
32 def print_json(obj):
33     try:
34         s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
35     except TypeError:
36         s = repr(obj)
37     sys.stdout.write(s + "\n")
38     sys.stdout.flush()
39     
40
41 def user_dir():
42     if "HOME" in os.environ:
43         return os.path.join(os.environ["HOME"], ".electrum")
44     elif "APPDATA" in os.environ:
45         return os.path.join(os.environ["APPDATA"], "Electrum")
46     elif "LOCALAPPDATA" in os.environ:
47         return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
48     elif 'ANDROID_DATA' in os.environ:
49         return "/sdcard/electrum/"
50     else:
51         #raise Exception("No home directory found in environment variables.")
52         return 
53
54 def appdata_dir():
55     """Find the path to the application data directory; add an electrum folder and return path."""
56     if platform.system() == "Windows":
57         return os.path.join(os.environ["APPDATA"], "Electrum")
58     elif platform.system() == "Linux":
59         return os.path.join(sys.prefix, "share", "electrum")
60     elif (platform.system() == "Darwin" or
61           platform.system() == "DragonFly" or
62           platform.system() == "NetBSD"):
63         return "/Library/Application Support/Electrum"
64     else:
65         raise Exception("Unknown system")
66
67
68 def get_resource_path(*args):
69     return os.path.join(".", *args)
70
71
72 def local_data_dir():
73     """Return path to the data folder."""
74     assert sys.argv
75     prefix_path = os.path.dirname(sys.argv[0])
76     local_data = os.path.join(prefix_path, "data")
77     return local_data
78
79
80 def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
81     from decimal import Decimal
82     s = Decimal(x)
83     sign, digits, exp = s.as_tuple()
84     digits = map(str, digits)
85     while len(digits) < decimal_point + 1:
86         digits.insert(0,'0')
87     digits.insert(-decimal_point,'.')
88     s = ''.join(digits).rstrip('0')
89     if sign: 
90         s = '-' + s
91     elif is_diff:
92         s = "+" + s
93
94     p = s.find('.')
95     s += "0"*( 1 + num_zeros - ( len(s) - p ))
96     if whitespaces:
97         s += " "*( 1 + decimal_point - ( len(s) - p ))
98         s = " "*( 13 - decimal_point - ( p )) + s 
99     return s
100
101
102 # Takes a timestamp and returns a string with the approximation of the age
103 def age(from_date, since_date = None, target_tz=None, include_seconds=False):
104     if from_date is None:
105         return "Unknown"
106
107     from_date = datetime.fromtimestamp(from_date)
108     if since_date is None:
109         since_date = datetime.now(target_tz)
110
111     distance_in_time = since_date - from_date
112     distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
113     distance_in_minutes = int(round(distance_in_seconds/60))
114
115     if distance_in_minutes <= 1:
116         if include_seconds:
117             for remainder in [5, 10, 20]:
118                 if distance_in_seconds < remainder:
119                     return "less than %s seconds ago" % remainder
120             if distance_in_seconds < 40:
121                 return "half a minute ago"
122             elif distance_in_seconds < 60:
123                 return "less than a minute ago"
124             else:
125                 return "1 minute ago"
126         else:
127             if distance_in_minutes == 0:
128                 return "less than a minute ago"
129             else:
130                 return "1 minute ago"
131     elif distance_in_minutes < 45:
132         return "%s minutes ago" % distance_in_minutes
133     elif distance_in_minutes < 90:
134         return "about 1 hour ago"
135     elif distance_in_minutes < 1440:
136         return "about %d hours ago" % (round(distance_in_minutes / 60.0))
137     elif distance_in_minutes < 2880:
138         return "1 day ago"
139     elif distance_in_minutes < 43220:
140         return "%d days ago" % (round(distance_in_minutes / 1440))
141     elif distance_in_minutes < 86400:
142         return "about 1 month ago"
143     elif distance_in_minutes < 525600:
144         return "%d months ago" % (round(distance_in_minutes / 43200))
145     elif distance_in_minutes < 1051200:
146         return "about 1 year ago"
147     else:
148         return "over %d years ago" % (round(distance_in_minutes / 525600))
149
150
151
152
153 # URL decode
154 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
155 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
156
157 def parse_url(url):
158     o = url[8:].split('?')
159     address = o[0]
160     if len(o)>1:
161         params = o[1].split('&')
162     else:
163         params = []
164
165     amount = label = message = signature = identity = ''
166     for p in params:
167         k,v = p.split('=')
168         uv = urldecode(v)
169         if k == 'amount': amount = uv
170         elif k == 'message': message = uv
171         elif k == 'label': label = uv
172         elif k == 'signature':
173             identity, signature = uv.split(':')
174             url = url.replace('&%s=%s'%(k,v),'')
175         else: 
176             print k,v
177
178     return address, amount, label, message, signature, identity, url
179
180
181 # Python bug (http://bugs.python.org/issue1927) causes raw_input
182 # to be redirected improperly between stdin/stderr on Unix systems
183 def raw_input(prompt=None):
184     if prompt:
185         sys.stdout.write(prompt)
186     return builtin_raw_input()
187 import __builtin__
188 builtin_raw_input = __builtin__.raw_input
189 __builtin__.raw_input = raw_input