1 #!/usr/bin/env python 2 3 from os.path import abspath, commonprefix, exists, join, split 4 from os import makedirs 5 from vCalendar import iterwrite 6 7 STORE_DIR = "/var/lib/imip-agent/store" 8 9 def check_dir(base, dir): 10 return commonprefix([base, abspath(dir)]) == base 11 12 def to_stream(out, fragment, objtype, encoding="utf-8"): 13 iterwrite(out, encoding=encoding).write(objtype, {}, fragment) 14 15 class FileStore: 16 17 "A file store of tabular data." 18 19 def __init__(self): 20 self.store_dir = STORE_DIR 21 if not exists(self.store_dir): 22 makedirs(self.store_dir) 23 24 def get_file_object(self, base, *parts): 25 pathname = join(base, *parts) 26 return check_dir(base, pathname) and pathname or None 27 28 def get_event(self, user, uid): 29 30 "Get the event for the given 'user' with the given 'uid'." 31 32 filename = self.get_file_object(self.store_dir, user, uid) 33 if not filename: 34 return None 35 36 return exists(filename) and open(filename) or None 37 38 def set_event(self, user, uid, details): 39 40 "Set an event for 'user' having the given 'uid' and 'details'." 41 42 dir = self.get_file_object(self.store_dir, user) 43 if not dir: 44 return False 45 46 filename = self.get_file_object(dir, uid) 47 if not filename: 48 return False 49 50 if not exists(dir): 51 makedirs(dir) 52 53 f = open(filename, "w") 54 try: 55 to_stream(f, details, "VEVENT") 56 finally: 57 f.close() 58 59 return True 60 61 def get_freebusy(self, user): 62 63 "Get free/busy details for the given 'user'." 64 65 filename = self.get_file_object(self.store_dir, user, "freebusy") 66 if not filename or not exists(filename): 67 return None 68 69 f = open(filename) 70 try: 71 l = [] 72 for line in f.readlines(): 73 l.append(line.strip().split("\t")) 74 return l 75 finally: 76 f.close() 77 78 def set_freebusy(self, user, freebusy): 79 80 "For the given 'user', set 'freebusy' details." 81 82 filename = self.get_file_object(self.store_dir, user, "freebusy") 83 if not filename: 84 return False 85 86 dir = split(filename)[0] 87 88 if not exists(dir): 89 makedirs(dir) 90 91 f = open(filename, "w") 92 try: 93 for item in freebusy: 94 f.write("\t".join(item) + "\n") 95 finally: 96 f.close() 97 98 return True 99 100 # vim: tabstop=4 expandtab shiftwidth=4