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