1 #!/usr/bin/env python 2 3 """ 4 Interpretation and preparation of iMIP content, together with a content handling 5 mechanism employed by specific recipients. 6 7 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> 8 9 This program is free software; you can redistribute it and/or modify it under 10 the terms of the GNU General Public License as published by the Free Software 11 Foundation; either version 3 of the License, or (at your option) any later 12 version. 13 14 This program is distributed in the hope that it will be useful, but WITHOUT 15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 16 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 17 details. 18 19 You should have received a copy of the GNU General Public License along with 20 this program. If not, see <http://www.gnu.org/licenses/>. 21 """ 22 23 from datetime import datetime, timedelta 24 from email.mime.text import MIMEText 25 from imiptools.config import MANAGER_PATH, MANAGER_URL 26 from imiptools.data import Object, parse_object, \ 27 get_address, get_uri, get_value, \ 28 is_new_object, uri_dict, uri_item 29 from imiptools.dates import format_datetime, to_timezone 30 from imiptools.period import can_schedule, insert_period, remove_period, \ 31 get_periods, remove_from_freebusy, \ 32 remove_from_freebusy_for_other, \ 33 update_freebusy, update_freebusy_for_other 34 from pytz import timezone 35 from socket import gethostname 36 import imip_store 37 38 try: 39 from cStringIO import StringIO 40 except ImportError: 41 from StringIO import StringIO 42 43 # Handler mechanism objects. 44 45 def handle_itip_part(part, handlers): 46 47 """ 48 Handle the given iTIP 'part' using the given 'handlers' dictionary. 49 50 Return a list of responses, each response being a tuple of the form 51 (outgoing-recipients, message-part). 52 """ 53 54 method = part.get_param("method") 55 56 # Decode the data and parse it. 57 58 f = StringIO(part.get_payload(decode=True)) 59 60 itip = parse_object(f, part.get_content_charset(), "VCALENDAR") 61 62 # Ignore the part if not a calendar object. 63 64 if not itip: 65 return 66 67 # Require consistency between declared and employed methods. 68 69 if get_value(itip, "METHOD") == method: 70 71 # Look for different kinds of sections. 72 73 all_results = [] 74 75 for name, items in itip.items(): 76 77 # Get a handler for the given section. 78 79 handler = handlers.get(name) 80 if not handler: 81 continue 82 83 for item in items: 84 85 # Dispatch to a handler and obtain any response. 86 87 handler.set_object(Object({name : item})) 88 methods[method](handler)() 89 90 # References to the Web interface. 91 92 def get_manager_url(): 93 url_base = MANAGER_URL or "http://%s/" % gethostname() 94 return "%s/%s" % (url_base.rstrip("/"), MANAGER_PATH.lstrip("/")) 95 96 def get_object_url(uid): 97 return "%s/%s" % (get_manager_url().rstrip("/"), uid) 98 99 class Handler: 100 101 "General handler support." 102 103 def __init__(self, senders=None, recipient=None, messenger=None): 104 105 """ 106 Initialise the handler with the calendar 'obj' and the 'senders' and 107 'recipient' of the object (if specifically indicated). 108 """ 109 110 self.senders = senders and set(map(get_address, senders)) 111 self.recipient = recipient and get_address(recipient) 112 self.messenger = messenger 113 114 self.results = [] 115 self.outgoing_methods = set() 116 117 self.obj = None 118 self.uid = None 119 self.sequence = None 120 self.dtstamp = None 121 122 self.store = imip_store.FileStore() 123 124 try: 125 self.publisher = imip_store.FilePublisher() 126 except OSError: 127 self.publisher = None 128 129 def set_object(self, obj): 130 self.obj = obj 131 self.uid = self.obj.get_value("UID") 132 self.sequence = self.obj.get_value("SEQUENCE") 133 self.dtstamp = self.obj.get_value("DTSTAMP") 134 135 def wrap(self, text, link=True): 136 137 "Wrap any valid message for passing to the recipient." 138 139 texts = [] 140 texts.append(text) 141 if link: 142 texts.append("If your mail program cannot handle this " 143 "message, you may view the details here:\n\n%s" % 144 get_object_url(self.uid)) 145 146 return self.add_result(None, None, MIMEText("\n".join(texts))) 147 148 # Result registration. 149 150 def add_result(self, method, outgoing_recipients, part): 151 152 """ 153 Record a result having the given 'method', 'outgoing_recipients' and 154 message part. 155 """ 156 157 if outgoing_recipients: 158 self.outgoing_methods.add(method) 159 self.results.append((outgoing_recipients, part)) 160 161 def get_results(self): 162 return self.results 163 164 def get_outgoing_methods(self): 165 return self.outgoing_methods 166 167 # Access to calendar structures and other data. 168 169 def get_periods(self): 170 return get_periods(self.obj) 171 172 def remove_from_freebusy(self, freebusy, attendee): 173 remove_from_freebusy(freebusy, attendee, self.uid, self.store) 174 175 def remove_from_freebusy_for_other(self, freebusy, user, other): 176 remove_from_freebusy_for_other(freebusy, user, other, self.uid, self.store) 177 178 def update_freebusy(self, freebusy, attendee, periods): 179 return update_freebusy(freebusy, attendee, periods, self.obj.get_value("TRANSP"), self.uid, self.store) 180 181 def update_freebusy_for_other(self, freebusy, user, other, periods): 182 return update_freebusy_for_other(freebusy, user, other, periods, self.obj.get_value("TRANSP"), self.uid, self.store) 183 184 def can_schedule(self, freebusy, periods): 185 return can_schedule(freebusy, periods, self.uid) 186 187 def filter_by_senders(self, mapping): 188 189 """ 190 Return a list of items from 'mapping' filtered using sender information. 191 """ 192 193 if self.senders: 194 195 # Get a mapping from senders to identities. 196 197 identities = self.get_sender_identities(mapping) 198 199 # Find the senders that are valid. 200 201 senders = map(get_address, identities) 202 valid = self.senders.intersection(senders) 203 204 # Return the true identities. 205 206 return [identities[get_uri(address)] for address in valid] 207 else: 208 return mapping 209 210 def filter_by_recipient(self, mapping): 211 212 """ 213 Return a list of items from 'mapping' filtered using recipient 214 information. 215 """ 216 217 if self.recipient: 218 addresses = set(map(get_address, mapping)) 219 return map(get_uri, addresses.intersection([self.recipient])) 220 else: 221 return mapping 222 223 def require_organiser_and_attendees(self, from_organiser=True): 224 225 """ 226 Return the organiser and attendees for the current object, filtered for 227 the recipient of interest. Return None if no identities are eligible. 228 229 Organiser and attendee identities are provided as lower case values. 230 """ 231 232 attendee_map = uri_dict(self.obj.get_value_map("ATTENDEE")) 233 organiser_item = uri_item(self.obj.get_item("ORGANIZER")) 234 235 # Only provide details for attendees who sent/receive the message. 236 237 attendee_filter_fn = from_organiser and self.filter_by_recipient or self.filter_by_senders 238 239 attendees = {} 240 for attendee in attendee_filter_fn(attendee_map): 241 attendees[attendee] = attendee_map[attendee] 242 243 if not attendees or not organiser_item: 244 return None 245 246 # Only provide details for an organiser who sent/receives the message. 247 248 organiser_filter_fn = from_organiser and self.filter_by_senders or self.filter_by_recipient 249 250 if not organiser_filter_fn(dict([organiser_item])): 251 return None 252 253 return organiser_item, attendees 254 255 def get_sender_identities(self, mapping): 256 257 """ 258 Return a mapping from actual senders to the identities for which they 259 have provided data, extracting this information from the given 260 'mapping'. 261 """ 262 263 senders = {} 264 265 for value, attr in mapping.items(): 266 sent_by = attr.get("SENT-BY") 267 if sent_by: 268 senders[get_uri(sent_by)] = value 269 else: 270 senders[value] = value 271 272 return senders 273 274 def get_object(self, user): 275 276 """ 277 Return the stored object to which the current object refers for the 278 given 'user' and for the given 'objtype'. 279 """ 280 281 f = self.store.get_event(user, self.uid) 282 fragment = f and parse_object(f, "utf-8") 283 return fragment and Object(fragment) 284 285 def have_new_object(self, attendee, obj=None): 286 287 """ 288 Return whether the current object is new to the 'attendee' (or if the 289 given 'obj' is new). 290 """ 291 292 obj = obj or self.get_object(attendee) 293 294 # If found, compare SEQUENCE and potentially DTSTAMP. 295 296 if obj: 297 sequence = obj.get_value("SEQUENCE") 298 dtstamp = obj.get_value("DTSTAMP") 299 300 # If the request refers to an older version of the object, ignore 301 # it. 302 303 return is_new_object(sequence, self.sequence, dtstamp, self.dtstamp, 304 self.is_partstat_updated(obj)) 305 306 return True 307 308 def is_partstat_updated(self, obj): 309 310 """ 311 Return whether the participant status has been updated in the current 312 object in comparison to the given 'obj'. 313 314 NOTE: Some clients like Claws Mail erase time information from DTSTAMP 315 NOTE: and make it invalid. Thus, such attendance information may also be 316 NOTE: incorporated into any new object assessment. 317 """ 318 319 old_attendees = obj.get_value_map("ATTENDEE") 320 new_attendees = self.obj.get_value_map("ATTENDEE") 321 322 for attendee, attr in old_attendees.items(): 323 old_partstat = attr.get("PARTSTAT") 324 new_attr = new_attendees.get(attendee) 325 new_partstat = new_attr and new_attr.get("PARTSTAT") 326 327 if old_partstat == "NEEDS-ACTION" and new_partstat and \ 328 new_partstat != old_partstat: 329 330 return True 331 332 return False 333 334 def update_dtstamp(self): 335 336 "Update the DTSTAMP in the current object." 337 338 dtstamp = self.obj.get_utc_datetime("DTSTAMP") 339 utcnow = to_timezone(datetime.utcnow(), "UTC") 340 self.obj["DTSTAMP"] = [(format_datetime(dtstamp > utcnow and dtstamp or utcnow), {})] 341 342 # Handler registry. 343 344 methods = { 345 "ADD" : lambda handler: handler.add, 346 "CANCEL" : lambda handler: handler.cancel, 347 "COUNTER" : lambda handler: handler.counter, 348 "DECLINECOUNTER" : lambda handler: handler.declinecounter, 349 "PUBLISH" : lambda handler: handler.publish, 350 "REFRESH" : lambda handler: handler.refresh, 351 "REPLY" : lambda handler: handler.reply, 352 "REQUEST" : lambda handler: handler.request, 353 } 354 355 # vim: tabstop=4 expandtab shiftwidth=4