Accept FreeBSD OS
[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 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() == "OpenBSD" or
63           platform.system() == "FreeBSD" or
64           platform.system() == "NetBSD"):
65         return "/Library/Application Support/Electrum"
66     else:
67         raise Exception("Unknown system")
68
69
70 def get_resource_path(*args):
71     return os.path.join(".", *args)
72
73
74 def local_data_dir():
75     """Return path to the data folder."""
76     assert sys.argv
77     prefix_path = os.path.dirname(sys.argv[0])
78     local_data = os.path.join(prefix_path, "data")
79     return local_data
80
81
82 def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
83     from decimal import Decimal
84     s = Decimal(x)
85     sign, digits, exp = s.as_tuple()
86     digits = map(str, digits)
87     while len(digits) < decimal_point + 1:
88         digits.insert(0,'0')
89     digits.insert(-decimal_point,'.')
90     s = ''.join(digits).rstrip('0')
91     if sign: 
92         s = '-' + s
93     elif is_diff:
94         s = "+" + s
95
96     p = s.find('.')
97     s += "0"*( 1 + num_zeros - ( len(s) - p ))
98     if whitespaces:
99         s += " "*( 1 + decimal_point - ( len(s) - p ))
100         s = " "*( 13 - decimal_point - ( p )) + s 
101     return s
102
103
104 # Takes a timestamp and returns a string with the approximation of the age
105 def age(from_date, since_date = None, target_tz=None, include_seconds=False):
106     if from_date is None:
107         return "Unknown"
108
109     from_date = datetime.fromtimestamp(from_date)
110     if since_date is None:
111         since_date = datetime.now(target_tz)
112
113     distance_in_time = since_date - from_date
114     distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
115     distance_in_minutes = int(round(distance_in_seconds/60))
116
117     if distance_in_minutes <= 1:
118         if include_seconds:
119             for remainder in [5, 10, 20]:
120                 if distance_in_seconds < remainder:
121                     return "less than %s seconds ago" % remainder
122             if distance_in_seconds < 40:
123                 return "half a minute ago"
124             elif distance_in_seconds < 60:
125                 return "less than a minute ago"
126             else:
127                 return "1 minute ago"
128         else:
129             if distance_in_minutes == 0:
130                 return "less than a minute ago"
131             else:
132                 return "1 minute ago"
133     elif distance_in_minutes < 45:
134         return "%s minutes ago" % distance_in_minutes
135     elif distance_in_minutes < 90:
136         return "about 1 hour ago"
137     elif distance_in_minutes < 1440:
138         return "about %d hours ago" % (round(distance_in_minutes / 60.0))
139     elif distance_in_minutes < 2880:
140         return "1 day ago"
141     elif distance_in_minutes < 43220:
142         return "%d days ago" % (round(distance_in_minutes / 1440))
143     elif distance_in_minutes < 86400:
144         return "about 1 month ago"
145     elif distance_in_minutes < 525600:
146         return "%d months ago" % (round(distance_in_minutes / 43200))
147     elif distance_in_minutes < 1051200:
148         return "about 1 year ago"
149     else:
150         return "over %d years ago" % (round(distance_in_minutes / 525600))
151
152
153
154
155 # URL decode
156 _ud = re.compile('%([0-9a-hA-H]{2})', re.MULTILINE)
157 urldecode = lambda x: _ud.sub(lambda m: chr(int(m.group(1), 16)), x)
158
159 def parse_url(url):
160     from decimal import Decimal
161     url = str(url)
162     o = url[8:].split('?')
163     address = o[0]
164     if len(o)>1:
165         params = o[1].split('&')
166     else:
167         params = []
168
169     amount = label = message = signature = identity = ''
170     for p in params:
171         k,v = p.split('=')
172         uv = urldecode(v)
173         if k == 'amount': 
174             amount = uv
175             m = re.match('([0-9\.]+)X([0-9])', uv)
176             if m:
177                 k = int(m.group(2)) - 8 
178                 amount = Decimal(m.group(1)) * pow(  Decimal(10) , k)
179             else:
180                 amount = Decimal(uv)
181         elif k == 'message': 
182             message = uv
183         elif k == 'label': 
184             label = uv
185         elif k == 'signature':
186             identity, signature = uv.split(':')
187             url = url.replace('&%s=%s'%(k,v),'')
188         else: 
189             print k,v
190
191     return address, amount, label, message, signature, identity, url
192
193
194 # Python bug (http://bugs.python.org/issue1927) causes raw_input
195 # to be redirected improperly between stdin/stderr on Unix systems
196 def raw_input(prompt=None):
197     if prompt:
198         sys.stdout.write(prompt)
199     return builtin_raw_input()
200 import __builtin__
201 builtin_raw_input = __builtin__.raw_input
202 __builtin__.raw_input = raw_input