xinclude: added pic and latests plugins
[treecutter.git] / xinclude / events.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 from getpass import getpass
5 from dateutil.tz import *
6 from datetime import datetime
7 from dateutil.parser import parse
8 import vobject
9 import httplib
10 from urlparse import urlparse
11 from lxml import etree
12 from lxml.builder import ElementMaker
13 import sys
14 import re
15
16 from address import Address
17 from contact import Organization
18 from treecutter import constants as const
19
20
21 class Events(object):
22     def __init__(self, uri):
23         self.uri = uri
24         self.events = []
25         self.data = None
26         if uri.scheme == 'file':
27             with open(self.uri.path, 'r') as f:
28                 self.data = f.read()
29             f.closed
30         if uri.scheme == 'http':
31             pw = getpass()
32             print "http not yet implemented"
33         if uri.scheme == 'https':
34             pw = getpass()
35             headers = {"User-Agent": "Mozilla/5.0",
36                        "Content-Type": "text/xml",
37                        "Accept": "text/xml"}
38
39             headers['authorization'] = "Basic %s" % (("%s:%s" % (self.uri.username, pw)).encode('base64')[:-1])
40             handle = httplib.HTTPSConnection(self.uri.hostname,self.uri.port)
41             res = handle.request('GET', self.uri.path, "", headers)
42             r = handle.getresponse()
43             if r.status != 200:
44                 print "Failed to connect! Wrong Password ?"
45                 sys.exit(5)
46             self.data = r.read()
47             handle.close()
48         headers = ['dtstart','summary','location','description']
49         for cal in vobject.readComponents(self.data):
50             for ev in cal.vevent_list:
51                 details = {}
52                 for k in headers:
53                     details[k] = ""
54                 for p in ev.getChildren():
55                     details[p.name.lower()] = p.value
56                 self.events.append(Event(details))
57
58     def filter(self,query):
59         (key, name) = query.split(':')
60         fev = []
61         if key == 'year':
62             for ev in self.events:
63                 if ev.start.year == int(name):
64                     fev.append(ev)
65         self.events = fev
66
67     def geocode(self):
68         for ev in self.events:
69             ev.geocode()
70
71     def sorted(self,order):
72         if order == 'start':
73             self.events.sort(key=lambda x: x.start, reverse=True)
74
75
76     def db_xml(self):
77         db = ElementMaker(namespace=const.DB_NS, nsmap=const.NSMAP)
78         evlist = db.variablelist(db.title(u'Stammtisch träffar'),
79                                  role=u'calendar')
80         for ev in self.events:
81             evlist.append(ev.db_xml())
82         return evlist
83
84
85 class Event(object):
86     def __init__(self,ev):
87         self.start = ev['dtstart']
88         self.end = ev['dtend']
89         self.summary = ev['summary']
90         self.location = ev['location']
91         self.org = None
92         self.description = ev['description']
93
94     def geocode(self):
95         addrlist = self.location.split(',')
96         addrfmt = "org,street,postcode,city"
97         adict = addrfmt.split(',')
98         argdict = dict(zip(adict,addrlist))
99         self.org = Organization(argdict['org'])
100         del argdict['org']
101         addr = Address(**argdict)
102         self.org.add_address(addr)
103         addr.geocode()
104
105
106     def db_xml(self):
107         db = ElementMaker(namespace=const.DB_NS, nsmap=const.NSMAP)
108         # Build paragraphs from the description
109         paras = db.listitem(role="description")
110         for p in re.split('\n\n',unicode(self.description)):
111             paras.append(db.para(p,role="desc"))
112
113         lst = db.varlistentry(
114             db.term(db.date(self.start.strftime('%Y %b %d'),role='calendar')),
115             db.listitem(db.para(self.summary),db.variablelist(
116                     db.varlistentry(
117                         db.term("Tid"),
118                         db.listitem(db.para(self.start.strftime('%H:%M')))
119                         ),
120                     db.varlistentry(
121                         db.term("Plats"),
122                         db.listitem(db.para(self.org.db_xml()))
123                         ),
124                     db.varlistentry(
125                         db.term("Beskrivning"),
126                         paras
127                 )
128                     )
129                         )
130             )
131         return lst
132
133 # ln = db.link("Text",**{XLINK+"href": "https://"})
134
135 if __name__ == "__main__":
136     for arg in sys.argv[1:]:
137         al = arg.split("=")
138         if al[0] == "lang":
139             lang = al[1]
140         if al[0] == "xptr":
141             argument = al[1]
142
143     (uristr,query) = argument.split('|')
144     uri = urlparse(uristr)
145     events = Events(uri)
146     events.filter(query)
147     events.geocode()
148     events.sorted('start')
149     exml = events.db_xml()
150     #clean_db(exml)
151
152     #print(etree.tostring(cxml, pretty_print=True))
153     #sys.stdout.write(out.encode('utf-8'))
154     sys.stdout.write(etree.tostring(exml,encoding='UTF-8',pretty_print=False))