1 import os, sys, re, json
4 from datetime import datetime
9 class MyEncoder(json.JSONEncoder):
10 def default(self, obj):
11 from transaction import Transaction
12 if isinstance(obj, Transaction):
14 return super(MyEncoder, self).default(obj)
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")
29 args = [str(item) for item in args]
30 sys.stdout.write(" ".join(args) + "\n")
35 s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
38 sys.stdout.write(s + "\n")
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"]))
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"]))
52 print_msg("Failed to move your wallet.")
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")
63 #raise BaseException("No home directory found in environment variables.")
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"
77 raise Exception("Unknown system")
80 def get_resource_path(*args):
81 return os.path.join(".", *args)
85 """Return path to the data folder."""
87 prefix_path = os.path.dirname(sys.argv[0])
88 local_data = os.path.join(prefix_path, "data")
92 def format_satoshis(x, is_diff=False, num_zeros = 0, decimal_point = 8, whitespaces=False):
93 from decimal import Decimal
95 sign, digits, exp = s.as_tuple()
96 digits = map(str, digits)
97 while len(digits) < decimal_point + 1:
99 digits.insert(-decimal_point,'.')
100 s = ''.join(digits).rstrip('0')
107 s += "0"*( 1 + num_zeros - ( len(s) - p ))
109 s += " "*( 1 + decimal_point - ( len(s) - p ))
110 s = " "*( 13 - decimal_point - ( p )) + s
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:
119 from_date = datetime.fromtimestamp(from_date)
120 if since_date is None:
121 since_date = datetime.now(target_tz)
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))
127 if distance_in_minutes <= 1:
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"
137 return "1 minute ago"
139 if distance_in_minutes == 0:
140 return "less than a minute ago"
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:
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"
160 return "over %d years ago" % (round(distance_in_minutes / 525600))
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)
170 o = url[8:].split('?')
173 params = o[1].split('&')
177 amount = label = message = signature = identity = ''
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),'')
190 return address, amount, label, message, signature, identity, url