91573271207b08ada950529dcdfc7c15cdfbb633
[electrum-nvc.git] / lib / util.py
1 import os, sys, re
2 import platform
3 import shutil
4 from datetime import datetime
5 is_verbose = True
6
7
8
9 def set_verbosity(b):
10     global is_verbose
11     is_verbose = b
12
13 def print_error(*args):
14     if not is_verbose: return
15     args = [str(item) for item in args]
16     sys.stderr.write(" ".join(args) + "\n")
17     sys.stderr.flush()
18
19 def print_msg(*args):
20     # Stringify args
21     args = [str(item) for item in args]
22     sys.stdout.write(" ".join(args) + "\n")
23     sys.stdout.flush()
24
25 def print_json(obj):
26     import json
27     s = json.dumps(obj,sort_keys = True, indent = 4)
28     sys.stdout.write(s + "\n")
29     sys.stdout.flush()
30
31
32 def check_windows_wallet_migration():
33     if platform.release() != "XP":
34         if os.path.exists(os.path.join(os.environ["LOCALAPPDATA"], "Electrum")):
35             if os.path.exists(os.path.join(os.environ["APPDATA"], "Electrum")):
36                 print_msg("Two Electrum folders have been found, the default Electrum location for Windows has changed from %s to %s since Electrum 1.7, please check your wallets and fix the problem manually." % (os.environ["LOCALAPPDATA"], os.environ["APPDATA"]))
37                 sys.exit()
38             try:
39                 shutil.move(os.path.join(os.environ["LOCALAPPDATA"], "Electrum"), os.path.join(os.environ["APPDATA"]))
40                 print_msg("Your wallet has been moved from %s to %s."% (os.environ["LOCALAPPDATA"], os.environ["APPDATA"]))
41             except:
42                 print_msg("Failed to move your wallet.")
43     
44
45 def user_dir():
46     if "HOME" in os.environ:
47         return os.path.join(os.environ["HOME"], ".electrum")
48     elif "APPDATA" in os.environ:
49         return os.path.join(os.environ["APPDATA"], "Electrum")
50     elif "LOCALAPPDATA" in os.environ:
51         return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
52     else:
53         #raise BaseException("No home directory found in environment variables.")
54         return 
55
56 def appdata_dir():
57     """Find the path to the application data directory; add an electrum folder and return path."""
58     if platform.system() == "Windows":
59         return os.path.join(os.environ["APPDATA"], "Electrum")
60     elif platform.system() == "Linux":
61         return os.path.join(sys.prefix, "share", "electrum")
62     elif (platform.system() == "Darwin" or
63           platform.system() == "DragonFly" 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     o = url[8:].split('?')
161     address = o[0]
162     if len(o)>1:
163         params = o[1].split('&')
164     else:
165         params = []
166
167     amount = label = message = signature = identity = ''
168     for p in params:
169         k,v = p.split('=')
170         uv = urldecode(v)
171         if k == 'amount': amount = uv
172         elif k == 'message': message = uv
173         elif k == 'label': label = uv
174         elif k == 'signature':
175             identity, signature = uv.split(':')
176             url = url.replace('&%s=%s'%(k,v),'')
177         else: 
178             print k,v
179
180     return address, amount, label, message, signature, identity, url
181
182
183