From 77dc092f91ad0437b29c810f856f742a9a4e4684 Mon Sep 17 00:00:00 2001 From: Fredrik Unger Date: Fri, 9 Nov 2012 12:59:58 +0100 Subject: [PATCH] Creating objects, switching to lxml, made main callable Rewrote to use objects for Events and Event. db_xml generation with lxml. commandline callable using the __main__ setup --- xinclude/events.py | 187 ++++++++++++++++++++++++++++----------------- 1 file changed, 119 insertions(+), 68 deletions(-) diff --git a/xinclude/events.py b/xinclude/events.py index a956ba0..35c79e0 100755 --- a/xinclude/events.py +++ b/xinclude/events.py @@ -1,79 +1,130 @@ #!/usr/bin/python # -*- coding: utf-8 -*- -import getpass -from dateutil.tz import *; from datetime import * +from getpass import getpass +from dateutil.tz import * +from datetime import datetime +from dateutil.parser import parse import vobject import httplib -import urlparse +from urlparse import urlparse from lxml import etree +from lxml.builder import ElementMaker import sys import re +from treecutter import constants as const -pw = getpass.getpass() -urlstr = "CALDAV ULR" -url = urlparse.urlparse(urlstr) -headers = {"User-Agent": "Mozilla/5.0", - "Content-Type": "text/xml", - "Accept": "text/xml"} -headers['authorization'] = "Basic %s" % (("%s:%s" % (username, pw)).encode('base64')[:-1]) -handle = httplib.HTTPSConnection('tree.se','8443') -res = handle.request('GET', 'CALENDAR PATH', "", headers) -r = handle.getresponse() -if r.status != 200: - print "Failed to connect! Wrong Password ?" - sys.exit(5) -s = r.read() -events = [] -headers = ['dtstart','summary','location','description'] -for cal in vobject.readComponents(s): - for ev in cal.vevent_list: - details = {} - for k in headers: - details[k] = "" - for p in ev.getChildren(): - details[p.name.lower()] = p.value - events.append(details) -handle.close() +class Events(object): + def __init__(self, uri): + self.uri = uri + self.events = [] + self.data = None + if uri.scheme == 'file': + with open(self.uri.path, 'r') as f: + self.data = f.read() + f.closed + if uri.scheme == 'http': + pw = getpass() + print "http not yet implemented" + if uri.scheme == 'https': + pw = getpass() + headers = {"User-Agent": "Mozilla/5.0", + "Content-Type": "text/xml", + "Accept": "text/xml"} -sortedevents = sorted(events, key=lambda k: k['dtstart'], reverse=True) -output = u''' - -%s''' % (u'Stammtisch träffar') -for ev in sortedevents: - loc = ev['location'].split('[')[0] - if ev['location'].find('['): - lat = ev['location'].split('[')[1].split(',')[0] - lon = ev['location'].split('[')[1].split(',')[1].replace(']','') - loc = ' %s' % (lat,lon,loc) - output += u''' - -%s %s %s - - -%s - - - Tid - %s - - - Plats - %s - - - Beskrivning - %s - - - -''' % (ev['dtstart'].strftime('%Y'), - ev['dtstart'].strftime('%b'), - ev['dtstart'].strftime('%d'), - ev['summary'], - ev['dtstart'].strftime('%H:%M'), - loc, - ''.join(re.split('\n\n',unicode(ev['description'])))) -output += u'' -print output.encode("utf-8") + headers['authorization'] = "Basic %s" % (("%s:%s" % (self.uri.username, pw)).encode('base64')[:-1]) + handle = httplib.HTTPSConnection(self.uri.hostname,self.uri.port) + res = handle.request('GET', self.uri.path, "", headers) + r = handle.getresponse() + if r.status != 200: + print "Failed to connect! Wrong Password ?" + sys.exit(5) + self.data = r.read() + handle.close() + headers = ['dtstart','summary','location','description'] + for cal in vobject.readComponents(self.data): + for ev in cal.vevent_list: + details = {} + for k in headers: + details[k] = "" + for p in ev.getChildren(): + details[p.name.lower()] = p.value + self.events.append(Event(details)) + + def filter(self,query): + (key, name) = query.split(':') + fev = [] + if key == 'year': + for ev in self.events: + if ev.start.year == int(name): + fev.append(ev) + self.events = fev + + def sort(self,order): + sortedevents = sorted(events, key=lambda k: k['dtstart'], reverse=True) + + def db_xml(self): + db = ElementMaker(namespace=const.DB_NS, nsmap=const.NSMAP) + evlist = db.variablelist(db.title(u'Stammtisch träffar'), + role=u'calendar') + for ev in self.events: + evlist.append(ev.db_xml()) + return evlist + + +class Event(object): + def __init__(self,ev): + self.start = ev['dtstart'] + self.end = ev['dtend'] + self.summary = ev['summary'] + self.location = ev['location'] + self.description = ev['description'] + + def db_xml(self): + db = ElementMaker(namespace=const.DB_NS, nsmap=const.NSMAP) + # Build paragraphs from the description + paras = db.listitem(role="description") + for p in re.split('\n\n',unicode(self.description)): + paras.append(db.para(p,role="desc")) + + lst = db.varlistentry( + db.term(db.date(self.start.strftime('%Y %b %d'),role='calendar')), + db.listitem(db.para(self.summary),db.variablelist( + db.varlistentry( + db.term("Tid"), + db.listitem(db.para(self.start.strftime('%H:%M'))) + ), + db.varlistentry( + db.term("Plats"), + db.listitem(db.para(self.location)) + ), + db.varlistentry( + db.term("Beskrivning"), + paras + ) + ) + ) + ) + return lst + +# ln = db.link("Text",**{XLINK+"href": "https://"}) + +if __name__ == "__main__": + for arg in sys.argv[1:]: + al = arg.split("=") + if al[0] == "lang": + lang = al[1] + if al[0] == "xptr": + argument = al[1] + + (uristr,query) = argument.split('|') + uri = urlparse(uristr) + events = Events(uri) + events.filter(query) + exml = events.db_xml() + #clean_db(exml) + + #print(etree.tostring(cxml, pretty_print=True)) + #sys.stdout.write(out.encode('utf-8')) + sys.stdout.write(etree.tostring(exml,encoding='UTF-8',pretty_print=True)) -- 2.30.2