Merge branch 'master' of github.com:spesmilo/electrum
[electrum-nvc.git] / lib / util.py
1 import os, sys
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):
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) < 9:
88         digits.insert(0,'0')
89     digits.insert(-8,'.')
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     s += " "*( 9 - ( len(s) - p ))
99     s = " "*( 5 - ( 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))