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