更新 README
[gaetalk.git] / utils.py
blobd82290bda3541b768c376895f15d5f607b227109
1 #!/usr/bin/env python2
2 # vim:fileencoding=utf-8
4 import re
5 import unicodedata
6 import time
7 import config
9 from google.appengine.api import memcache
11 timeParser = re.compile(r'^(\d+)([smhd])?$')
12 linkre = re.compile(r' <https?://(?!i.imgur.com/)[^>]+>')
13 linkjsre = re.compile(r' <javascript:[^>]+>')
14 timeUnitMap = {
15 '': 1,
16 's': 1,
17 'm': 60,
18 'h': 3600,
19 'd': 86400,
22 def filesize(size):
23 '''将 数字 转化为 xxKiB 的形式'''
24 units = 'KMGT'
25 left = abs(size)
26 unit = -1
27 while left > 1100 and unit < 3:
28 left = left / 1024
29 unit += 1
30 if unit == -1:
31 return '%dB' % size
32 else:
33 if size < 0:
34 left = -left
35 return '%.1f%siB' % (left, units[unit])
37 def strftime(time, timezone, show_date=False):
38 '''将时间转换为字符串,考虑时区,可能带日期'''
39 if not show_date:
40 format = '%H:%M:%S'
41 else:
42 format = '%m-%d %H:%M:%S'
43 return (time + timezone).strftime(format)
45 def parseTime(s):
46 '''将 3s,5d,1h,6m 等转换成秒数'''
47 m = timeParser.match(s)
48 if m is None:
49 raise ValueError('not a time')
50 n = int(m.group(1))
51 u = m.group(2)
52 if u is None:
53 return n
54 else:
55 return n * timeUnitMap[u]
57 def checkNick(nick):
58 '''判断一个昵称是否合法'''
59 if len(nick.encode('utf-8')) > config.nick_maxlen:
60 return False
61 for i in nick:
62 if not unicodedata.category(i).startswith('L') and i not in config.allowedSymbolInNick:
63 return False
64 return True
66 def removelinks(msg):
67 '''清除多余的链接文本'''
68 links = linkre.findall(msg)
69 if len(links) != 1:
70 msg = linkre.sub('', msg)
71 msg = linkjsre.sub('', msg)
72 return msg
74 class MemLock:
75 def __init__(self, name):
76 self.name = name
78 def require(self):
79 while memcache.get(self.name):
80 time.sleep(0.001)
81 memcache.set(self.name, True)
83 def release(self):
84 memcache.set(self.name, False)