1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/imip_agent.py Sun Sep 21 23:37:24 2014 +0200
1.3 @@ -0,0 +1,102 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +from email import message_from_file
1.7 +from vCalendar import parse
1.8 +import sys
1.9 +
1.10 +try:
1.11 + from cStringIO import StringIO
1.12 +except ImportError:
1.13 + from StringIO import StringIO
1.14 +
1.15 +# Postfix exit codes.
1.16 +
1.17 +EX_USAGE = 64
1.18 +EX_DATAERR = 65
1.19 +EX_NOINPUT = 66
1.20 +EX_NOUSER = 67
1.21 +EX_NOHOST = 68
1.22 +EX_UNAVAILABLE = 69
1.23 +EX_SOFTWARE = 70
1.24 +EX_OSERR = 71
1.25 +EX_OSFILE = 72
1.26 +EX_CANTCREAT = 73
1.27 +EX_IOERR = 74
1.28 +EX_TEMPFAIL = 75
1.29 +EX_PROTOCOL = 76
1.30 +EX_NOPERM = 77
1.31 +EX_CONFIG = 78
1.32 +
1.33 +# Permitted iTIP content types.
1.34 +
1.35 +itip_content_types = [
1.36 + "text/calendar", # from RFC 6047
1.37 + "text/x-vcalendar", "application/ics", # other possibilities
1.38 + ]
1.39 +
1.40 +def process(f):
1.41 + msg = message_from_file(f)
1.42 +
1.43 + # Handle messages with iTIP parts.
1.44 +
1.45 + for part in msg.walk():
1.46 + if part.get_content_type() in itip_content_types and \
1.47 + part.get_param("method"):
1.48 +
1.49 + handle_itip_part(part)
1.50 +
1.51 +def get_itip_elements(elements):
1.52 + d = {}
1.53 + for name, attr, value in elements:
1.54 + if isinstance(value, list):
1.55 + d[name] = attr, get_itip_elements(value)
1.56 + else:
1.57 + d[name] = attr, value
1.58 + return d
1.59 +
1.60 +def get_value(d, name):
1.61 + if d.has_key(name):
1.62 + attr, value = d[name]
1.63 + return value
1.64 + else:
1.65 + return None
1.66 +
1.67 +def handle_itip_part(part):
1.68 + method = part.get_param("method")
1.69 +
1.70 + f = StringIO(part.get_payload(decode=True))
1.71 + doctype, attrs, elements = parse(f, encoding=part.get_content_charset())
1.72 +
1.73 + if doctype == "VCALENDAR":
1.74 + itip = get_itip_elements(elements)
1.75 +
1.76 + if get_value(itip, "METHOD") == method:
1.77 + for name, handler in [
1.78 + ("VFREEBUSY", handle_itip_freebusy),
1.79 + ("VEVENT", handle_itip_event),
1.80 + ("VTODO", handle_itip_todo),
1.81 + ("VJOURNAL", handle_itip_journal),
1.82 + ]:
1.83 +
1.84 + obj = get_value(itip, name)
1.85 + if obj:
1.86 + uid = get_value(obj, "UID")
1.87 + if uid:
1.88 + handler(obj, method)
1.89 +
1.90 +def handle_itip_freebusy(freebusy, method):
1.91 + print >>open("/tmp/imip.txt", "a"), freebusy
1.92 +
1.93 +def handle_itip_event(event, method):
1.94 + print >>open("/tmp/imip.txt", "a"), event
1.95 +
1.96 +def handle_itip_todo(todo, method):
1.97 + print >>open("/tmp/imip.txt", "a"), todo
1.98 +
1.99 +def handle_itip_journal(journal, method):
1.100 + print >>open("/tmp/imip.txt", "a"), journal
1.101 +
1.102 +if __name__ == "__main__":
1.103 + process(sys.stdin)
1.104 +
1.105 +# vim: tabstop=4 expandtab shiftwidth=4