]> jfr.im git - irc/rizon/acid.git/blob - pyva/src/main/python/utils.py
.gitignore: Ignore all pyva logs
[irc/rizon/acid.git] / pyva / src / main / python / utils.py
1 import re
2 import time
3 from datetime import datetime
4 from htmlentitydefs import name2codepoint
5
6 def unix_time(datetime):
7 return int(time.mktime(datetime.timetuple()))
8
9 def parse_timespan(text):
10 buffer = ''
11 duration = 0
12
13 for char in text:
14 if char == 'd':
15 duration += int(buffer) * 24 * 60 * 60
16 buffer = ''
17 elif char == 'h':
18 duration += int(buffer) * 60 * 60
19 buffer = ''
20 elif char == 'm':
21 duration += int(buffer) * 60
22 buffer = ''
23 elif char == 's':
24 duration += int(buffer)
25 buffer = ''
26 else:
27 buffer += char
28
29 return duration
30
31 def get_timespan(date):
32 td = datetime.now() - date
33 if td.days > 365:
34 y = int(td.days/365)
35 return '%d year%s' % (y, 's' if y > 1 else '')
36 elif td.days > 0:
37 d = td.days
38 return '%d day%s' % (d, 's' if d > 1 else '')
39 elif td.seconds > 3600:
40 h = int(td.seconds/3600)
41 return '%d hour%s' % (h, 's' if h > 1 else '')
42 elif td.seconds > 60:
43 m = int(td.seconds/60)
44 return '%d minute%s' % (m, 's' if m > 1 else '')
45 else:
46 s = td.seconds
47 return '%d second%s' % (s, 's' if s > 1 else '')
48
49 def format_name(name):
50 if name.endswith('s'):
51 return "%s'" % name
52 else:
53 return "%s's" % name
54
55 def format_thousand(number, add_prefix = False):
56 if not isinstance(number, int):
57 return str(number)
58
59 text = str(abs(number))
60
61 length = len(text)
62 count = (length - 1) / 3
63
64 for i in xrange(1, count + 1):
65 text = text[:length - (i * 3)] + ',' + text[length - (i * 3):]
66
67 if number < 0:
68 text = '-' + text
69 elif add_prefix:
70 text = '+' + text
71
72 return text
73
74 def format_hms(seconds):
75 hours = seconds / 3600
76 seconds -= 3600*hours
77 minutes = seconds / 60
78 seconds -= 60*minutes
79 if hours == 0:
80 return "%02d:%02d" % (minutes, seconds)
81 return "%02d:%02d:%02d" % (hours, minutes, seconds)
82
83 def format_ascii_irc(message):
84 return message.replace('@errsep', '@b@c4::@o').replace('@nsep', '@b@c7::@o').replace('@sep', '@b@c3::@o').replace('@b', chr(2)).replace('@c', chr(3)).replace('@o', chr(15)).replace('@u', chr(31))
85
86 def strip_ascii_irc(message):
87 stripped = ''
88
89 for char in message:
90 if char not in [chr(2), chr(15), chr(22), chr(31)]: #Not actually stripping color codes, but we don't need that (yet)
91 stripped += char
92
93 return stripped
94
95 def unescape(s):
96 "unescape HTML code refs; c.f. http://wiki.python.org/moin/EscapingHtml"
97
98 # XXX: There must be a better way than hardcoding these
99 name2codepoint['#39'] = 39
100 name2codepoint['#215'] = 215
101 name2codepoint['#8260'] = 8260
102
103 return re.sub('&(%s);' % '|'.join(name2codepoint),
104 lambda m: unichr(name2codepoint[m.group(1)]), s)