ctdo-trac/TracBooking/tracbooking/utils.py

103 lines
3.0 KiB
Python
Raw Permalink Normal View History

2012-03-31 15:55:42 +00:00
# -*- coding: utf-8 -*-
from sys import maxint
from datetime import datetime, date, time
from trac.util.datefmt import utc, to_timestamp, localtz, format_time, get_timezone, timezone
from re import match, compile as re_compile
class ValidationError(ValueError):
def __str__(self):
return "ValidationError: value out of bounds!"
def validate_id(value):
if (0 > value > maxint):
raise ValidationError("invalid argument")
def make_hash():
from random import sample
population = '123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
return "".join(sample(population, 4))
def date_parse(foo):
groups = match("^(\d{1,2}).(\d{1,2}).(\d{4})$", foo).groups()
return date(int(groups[2]),int(groups[1]),int(groups[0]))
def time_parse(foo):
timeM = re_compile("^(\d{1,2}):?(\d{2})$")
res = timeM.match(foo)
if not res:
raise ValueError("not valid time format")
h,m = res.groups()
return time(int(h),int(m))
def validate_email(addr):
rfc822_specials = '()<>@,;:\\"[]'
# First we validate the name portion (name@domain)
c = 0
while c < len(addr):
if addr[c] == '"' and (not c or addr[c - 1] == '.' or addr[c - 1] == '"'):
c = c + 1
while c < len(addr):
if addr[c] == '"':
break
if addr[c] == '\\' and addr[c + 1] == ' ':
c = c + 2
continue
if ord(addr[c]) < 32 or ord(addr[c]) >= 127:
return 0
c = c + 1
else:
return False
if addr[c] == '@':
break
if addr[c] != '.':
return False
c = c + 1
continue
if addr[c] == '@':
break
if ord(addr[c]) <= 32 or ord(addr[c]) >= 127:
return False
if addr[c] in rfc822_specials:
return False
c = c + 1
if not c or addr[c - 1] == '.':
return False
# Next we validate the domain portion (name@domain)
domain = c = c + 1
if domain >= len(addr):
return False
count = 0
while c < len(addr):
if addr[c] == '.':
if c == domain or addr[c - 1] == '.':
return False
count = count + 1
if ord(addr[c]) <= 32 or ord(addr[c]) >= 127:
return False
if addr[c] in rfc822_specials:
return False
c = c + 1
return count >= 1
def get_tz(session_tzname):
if session_tzname == 'UTC':
selected_tz = utc
else:
try:
selected_tz = timezone(session_tzname)
except Exception, e:
print e
selected_tz = utc
return session_tzname, selected_tz
def get_option_count(a, aopt):
aopt.count = 0
print a, a.options
for i in a.options:
if i.ao_id == aopt.ao_id:
i.name = aopt.name
aopt.count = i.count
return