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