use standard indendation in age(), and fix the for loop in it
[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
26 def check_windows_wallet_migration():
27     if os.path.exists(os.path.join(os.environ["LOCALAPPDATA"], "Electrum")):
28         if os.path.exists(os.path.join(os.environ["APPDATA"], "Electrum")):
29             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"]))
30             sys.exit()
31         try:
32             shutil.move(os.path.join(os.environ["LOCALAPPDATA"], "Electrum"), os.path.join(os.environ["APPDATA"]))
33             print_msg("Your wallet has been moved from %s to %s."% (os.environ["LOCALAPPDATA"], os.environ["APPDATA"]))
34         except:
35             print_msg("Failed to move your wallet.")
36     
37
38 def user_dir():
39     if "HOME" in os.environ:
40         return os.path.join(os.environ["HOME"], ".electrum")
41     elif "APPDATA" in os.environ:
42         return os.path.join(os.environ["APPDATA"], "Electrum")
43     elif "LOCALAPPDATA" in os.environ:
44         return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
45     else:
46         #raise BaseException("No home directory found in environment variables.")
47         return 
48
49 def appdata_dir():
50     """Find the path to the application data directory; add an electrum folder and return path."""
51     if platform.system() == "Windows":
52         return os.path.join(os.environ["APPDATA"], "Electrum")
53     elif platform.system() == "Linux":
54         return os.path.join(sys.prefix, "share", "electrum")
55     elif (platform.system() == "Darwin" or
56           platform.system() == "DragonFly" or
57           platform.system() == "NetBSD"):
58         return "/Library/Application Support/Electrum"
59     else:
60         raise Exception("Unknown system")
61
62
63 def get_resource_path(*args):
64     return os.path.join(".", *args)
65
66
67 def local_data_dir():
68     """Return path to the data folder."""
69     assert sys.argv
70     prefix_path = os.path.dirname(sys.argv[0])
71     local_data = os.path.join(prefix_path, "data")
72     return local_data
73
74
75 def format_satoshis(x, is_diff=False, num_zeros = 0):
76     from decimal import Decimal
77     s = Decimal(x)
78     sign, digits, exp = s.as_tuple()
79     digits = map(str, digits)
80     while len(digits) < 9:
81         digits.insert(0,'0')
82     digits.insert(-8,'.')
83     s = ''.join(digits).rstrip('0')
84     if sign: 
85         s = '-' + s
86     elif is_diff:
87         s = "+" + s
88
89     p = s.find('.')
90     s += "0"*( 1 + num_zeros - ( len(s) - p ))
91     s += " "*( 9 - ( len(s) - p ))
92     s = " "*( 5 - ( p )) + s
93     return s
94
95
96 # Takes a timestamp and returns a string with the approximation of the age
97 def age(from_date, since_date = None, target_tz=None, include_seconds=False):
98     if from_date is None:
99         return "Unknown"
100
101     from_date = datetime.fromtimestamp(from_date)
102     if since_date is None:
103         since_date = datetime.now(target_tz)
104
105     distance_in_time = since_date - from_date
106     distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
107     distance_in_minutes = int(round(distance_in_seconds/60))
108
109     if distance_in_minutes <= 1:
110         if include_seconds:
111             for remainder in [5, 10, 20]:
112                 if distance_in_seconds < remainder:
113                     return "less than %s seconds ago" % remainder
114             if distance_in_seconds < 40:
115                 return "half a minute ago"
116             elif distance_in_seconds < 60:
117                 return "less than a minute ago"
118             else:
119                 return "1 minute ago"
120         else:
121             if distance_in_minutes == 0:
122                 return "less than a minute ago"
123             else:
124                 return "1 minute ago"
125     elif distance_in_minutes < 45:
126         return "%s minutes ago" % distance_in_minutes
127     elif distance_in_minutes < 90:
128         return "about 1 hour ago"
129     elif distance_in_minutes < 1440:
130         return "about %d hours ago" % (round(distance_in_minutes / 60.0))
131     elif distance_in_minutes < 2880:
132         return "1 day ago"
133     elif distance_in_minutes < 43220:
134         return "%d days ago" % (round(distance_in_minutes / 1440))
135     elif distance_in_minutes < 86400:
136         return "about 1 month ago"
137     elif distance_in_minutes < 525600:
138         return "%d months ago" % (round(distance_in_minutes / 43200))
139     elif distance_in_minutes < 1051200:
140         return "about 1 year ago"
141     else:
142         return "over %d years ago" % (round(distance_in_minutes / 525600))