summaryrefslogtreecommitdiff
path: root/exchange/commands.py
blob: f9623423caf62865b5629e7cc9420143955c2f47 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# vim: set filencoding=utf8
"""
Exchange Commands

@author: Mike Crute (mcrute@gmail.com)
@organization: American Greetings Interactive
@date: November 10, 2008

This is a set of classes that starts to define a set of classes for
fetching data using Exchange's WebDAV API. This is still pretty
development code but it does the trick. Watch out, it doesn't consider
many corner cases.
"""

import dateutil.parser as date_parser
import xml.etree.cElementTree as ElementTree

from string import Template
from httplib import HTTPSConnection
from datetime import datetime, timedelta
from exchange import ExchangeException, EST
from icalendar import Calendar, Event as _Event


class Event(_Event):

    def _get_element_text(self, element, key):
        value = element.find(key)

        if hasattr(value, 'text'):
            return value.text

    def add_text(self, element, key, add_as=None):
        value = self._get_element_text(element, key)

        add_as = key if not add_as else add_as
        self.add(add_as, value)

    def add_date(self, element, key, add_as=None):
        value = date_parser.parse(self._get_element_text(element, key))

        add_as = key if not add_as else add_as
        self.add(add_as, value)


class ExchangeRequest(object):

    def __init__(self, session, service, method='GET'):
        self.session = session
        self.service = service
        self.method = method
        self.server = session.server
        self.username = session.username
        self._headers = { 'Content-Type': 'text/xml',
                         'Depth': '0', 'Translate': 'f' }

    @property
    def headers(self):
        self._headers['Cookie'] = self.session.token
        return self._headers

    @property
    def request_url(self):
        path = '/'.join(['exchange', self.username, self.service])
        return '/{0}'.format(path)

    def get_response(self, query=None):
        connection = HTTPSConnection(self.server)
        connection.request(self.method, self.request_url, query,
                            headers=self.headers)
        resp = connection.getresponse()

        if int(resp.status) > 299 or int(resp.status) < 200:
            raise ExchangeException("%s %s" % (resp.status, resp.reason))

        return resp.read()


class ExchangeCommand(object):
    """
    Base class for Exchange commands. This really shouldn't be constructed
    directly but should be subclassed to do useful things.
    """

    def __init__(self, session):
        self.session = session

    def _get_xml(self, **kwargs):
        """
        Try to get an XML response from the server.
        @return: ElementTree response
        """
        kwargs["username"] = self.session.username
        xml = self._get_query(**kwargs)

        req = ExchangeRequest(self.session, self.exchange_method,
                                    self.dav_method)
        resp = req.get_response(Template(xml).substitute(kwargs))

        return ElementTree.fromstring(resp)

    def _get_query(self, **kwargs):
        """
        Build up the XML query for the server. Mostly just does a lot
        of template substitutions, also does a little bit of elementtree
        magic to to build the XML query.
        """
        declaration = ElementTree.ProcessingInstruction("xml", 'version="1.0"')

        request = ElementTree.Element("g:searchrequest", { "xmlns:g": "DAV:" })
        query = ElementTree.SubElement(request, "g:sql")
        query.text = Template(self.sql).substitute(kwargs)

        output = ElementTree.tostring(declaration)
        output += ElementTree.tostring(request)

        return output


class FetchCalendar(ExchangeCommand):

    exchange_method = "calendar"
    dav_method = "SEARCH"

    sql = """
        SELECT
            PidLidAllAttendeesString                 AS attendees,
            "urn:schemas:calendar:location"          AS location,
            "urn:schemas:calendar:organizer"         AS organizer,
            "urn:schemas:calendar:meetingstatus"     AS status,
            "urn:schemas:httpmail:normalizedsubject" AS subject,
            "urn:schemas:calendar:dtstart"           AS start_date,
            "urn:schemas:calendar:dtend"             AS end_date,
            "urn:schemas:calendar:timezone"          AS timezone_info,
            "urn:schemas:httpmail:textdescription"   AS description
        FROM
            Scope('SHALLOW TRAVERSAL OF "/exchange/${username}/calendar/"')
        WHERE
            NOT "urn:schemas:calendar:instancetype" = 1
            AND "DAV:contentclass" = 'urn:content-classes:appointment'
        ORDER BY
            "urn:schemas:calendar:dtstart" ASC
        """

    def execute(self, alarms=True, alarm_offset=15, **kwargs):
        exchange_xml = self._get_xml(**kwargs)
        calendar = Calendar()

        for item in exchange_xml.getchildren():
            item = item.find("{DAV:}propstat").find("{DAV:}prop")

            event = Event()
            event.add_text(item, 'subject', add_as='summary')
            event.add_text(item, 'location')
            event.add_text(item, 'description')
            event.add_date(item, 'start_date', add_as='dtstart')
            event.add_date(item, 'end_date', add_as='dtend')

            calendar.add_component(event)

        return calendar