imip-agent

imiptools/handlers/person.py

157:eff00f10d12a
2015-01-22 Paul Boddie Handle "naive" datetimes in to_utc_datetime.
     1 #!/usr/bin/env python     2      3 """     4 Handlers for a person for whom scheduling is performed.     5      6 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk>     7      8 This program is free software; you can redistribute it and/or modify it under     9 the terms of the GNU General Public License as published by the Free Software    10 Foundation; either version 3 of the License, or (at your option) any later    11 version.    12     13 This program is distributed in the hope that it will be useful, but WITHOUT    14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS    15 FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more    16 details.    17     18 You should have received a copy of the GNU General Public License along with    19 this program.  If not, see <http://www.gnu.org/licenses/>.    20 """    21     22 from email.mime.text import MIMEText    23 from imiptools.config import MANAGER_PATH, MANAGER_URL    24 from imiptools.content import Handler, get_address, get_uri, to_part, uri_dict, uri_items    25 from imiptools.handlers.common import CommonFreebusy    26 from socket import gethostname    27 from vCalendar import to_node    28     29 def get_manager_url():    30     url_base = MANAGER_URL or "http://%s/" % gethostname()    31     return "%s/%s" % (url_base.rstrip("/"), MANAGER_PATH.lstrip("/"))    32     33 def get_object_url(uid):    34     return "%s/%s" % (get_manager_url().rstrip("/"), uid)    35     36 class PersonHandler(Handler):    37     38     "Handling mechanisms specific to people."    39     40     def _record_and_deliver(self, objtype, from_organiser=True, queue=False, cancel=False):    41     42         oa = self.require_organiser_and_attendees(from_organiser)    43         if not oa:    44             return False    45     46         (organiser, organiser_attr), attendees = organiser_item, attendees = oa    47     48         # Validate the organiser or attendee, ignoring spoofed requests.    49     50         if not self.validate_identities(from_organiser and [organiser_item] or attendees.items()):    51             return False    52     53         # Handle notifications and invitations.    54     55         if from_organiser:    56     57             # Process each attendee separately.    58     59             for attendee, attendee_attr in attendees.items():    60     61                 if not self.have_new_object(attendee, objtype):    62                     continue    63     64                 # Store the object and queue any request.    65     66                 self.store.set_event(attendee, self.uid, to_node(    67                     {objtype : [(self.details, {})]}    68                     ))    69     70                 if queue:    71                     self.store.queue_request(attendee, self.uid)    72                 elif cancel:    73                     self.store.cancel_event(attendee, self.uid)    74     75         # As organiser, update attendance.    76     77         else:    78             obj = self.get_object(organiser, objtype)    79     80             if obj and self.have_new_object(organiser, objtype, obj):    81     82                 # Get attendee details in a usable form.    83     84                 attendee_map = uri_dict(self.get_value_map("ATTENDEE"))    85     86                 for attendee, attendee_attr in attendees.items():    87     88                     # Update attendance in the loaded object.    89     90                     attendee_map[attendee] = attendee_attr    91     92                 # Set the new details and store the object.    93     94                 obj["ATTENDEE"] = attendee_map.items()    95     96                 self.store.set_event(organiser, self.uid, to_node(    97                     {objtype : [(obj, {})]}    98                     ))    99    100         return True   101    102     def _record_freebusy(self, from_organiser=True):   103    104         "Record free/busy information for the received information."   105    106         freebusy = []   107    108         for value in self.get_values("FREEBUSY") or []:   109             if not isinstance(value, list):   110                 value = [value]   111             for v in value:   112                 try:   113                     start, end = v.split("/", 1)   114                     freebusy.append((start, end))   115                 except ValueError:   116                     pass   117    118         for sender, sender_attr in uri_items(self.get_items(from_organiser and "ORGANIZER" or "ATTENDEE")):   119             for recipient in self.recipients:   120                 self.store.set_freebusy_for_other(get_uri(recipient), freebusy, sender)   121    122     def wrap(self, method, text, from_organiser=True, link=True):   123    124         "Wrap any valid message and pass it on to the recipient."   125    126         texts = []   127         texts.append(text)   128         if link:   129             texts.append("If your mail program cannot handle this "   130                          "message, you may view the details here:\n\n%s" %   131                          get_object_url(self.uid))   132    133         return method, MIMEText("\n".join(texts))   134    135 class Event(PersonHandler):   136    137     "An event handler."   138    139     def add(self):   140    141         # NOTE: Queue a suggested modification to any active event.   142    143         # The message is now wrapped and passed on to the recipient.   144    145         return "ADD", MIMEText("An addition to an event has been received.")   146    147     def cancel(self):   148    149         "Queue a cancellation of any active event."   150    151         self._record_and_deliver("VEVENT", from_organiser=True, queue=False, cancel=True)   152         return self.wrap("CANCEL", "A cancellation has been received.", from_organiser=True, link=True)   153    154     def counter(self):   155    156         # NOTE: Queue a suggested modification to any active event.   157    158         # The message is now wrapped and passed on to the recipient.   159    160         return "COUNTER", MIMEText("A counter proposal has been received.")   161    162     def declinecounter(self):   163    164         # NOTE: Queue a suggested modification to any active event.   165    166         # The message is now wrapped and passed on to the recipient.   167    168         return "DECLINECOUNTER", MIMEText("A declining counter proposal has been received.")   169    170     def publish(self):   171    172         "Register details of any relevant event."   173    174         self._record_and_deliver("VEVENT", from_organiser=True, queue=False)   175         return self.wrap("PUBLISH", "Details of an event have been received.", from_organiser=True, link=True)   176    177     def refresh(self):   178    179         "Update details of any active event."   180    181         self._record_and_deliver("VEVENT", from_organiser=True, queue=False)   182         return self.wrap("REFRESH", "An event update has been received.", from_organiser=True, link=True)   183    184     def reply(self):   185    186         "Record replies and notify the recipient."   187    188         self._record_and_deliver("VEVENT", from_organiser=False, queue=False)   189         return self.wrap("REPLY", "A reply has been received.", from_organiser=False, link=True)   190    191     def request(self):   192    193         "Hold requests and notify the recipient."   194    195         self._record_and_deliver("VEVENT", from_organiser=True, queue=True)   196    197         # The message is now wrapped and passed on to the recipient.   198    199         return "REQUEST", MIMEText("A request has been queued and can be viewed here: %s" % get_object_url(self.uid))   200    201 class Freebusy(PersonHandler, CommonFreebusy):   202    203     "A free/busy handler."   204    205     def publish(self):   206    207         "Register free/busy information."   208    209         # NOTE: This could be configured to not produce a message.   210    211         self._record_freebusy(from_organiser=True)   212         return self.wrap("PUBLISH", "A free/busy update has been received.", from_organiser=True, link=False)   213    214     def reply(self):   215    216         "Record replies and notify the recipient."   217    218         # NOTE: This could be configured to not produce a message.   219    220         self._record_freebusy(from_organiser=False)   221         return self.wrap("REPLY", "A reply has been received.", from_organiser=False, link=False)   222    223     def request(self):   224    225         """   226         Respond to a request by preparing a reply containing free/busy   227         information for each indicated attendee.   228         """   229    230         # NOTE: This should be subject to policy/preferences.   231    232         return CommonFreebusy.request(self)   233    234 class Journal(PersonHandler):   235    236     "A journal entry handler."   237    238     def add(self):   239    240         # NOTE: Queue a suggested modification to any active entry.   241    242         # The message is now wrapped and passed on to the recipient.   243    244         return "ADD", MIMEText("An addition to a journal entry has been received.")   245    246     def cancel(self):   247    248         # NOTE: Queue a suggested modification to any active entry.   249    250         # The message is now wrapped and passed on to the recipient.   251    252         return "CANCEL", MIMEText("A cancellation has been received.")   253    254     def publish(self):   255    256         # NOTE: Register details of any relevant entry.   257    258         # The message is now wrapped and passed on to the recipient.   259    260         self._record_and_deliver("VJOURNAL", from_organiser=True, queue=False)   261         return self.wrap("PUBLISH", "Details of a journal entry have been received.", from_organiser=True, link=False)   262    263 class Todo(PersonHandler):   264    265     "A to-do item handler."   266    267     def add(self):   268    269         # NOTE: Queue a suggested modification to any active item.   270    271         # The message is now wrapped and passed on to the recipient.   272    273         return "ADD", MIMEText("An addition to an item has been received.")   274    275     def cancel(self):   276    277         # NOTE: Queue a suggested modification to any active item.   278    279         # The message is now wrapped and passed on to the recipient.   280    281         return "CANCEL", MIMEText("A cancellation has been received.")   282    283     def counter(self):   284    285         # NOTE: Queue a suggested modification to any active item.   286    287         # The message is now wrapped and passed on to the recipient.   288    289         return "COUNTER", MIMEText("A counter proposal has been received.")   290    291     def declinecounter(self):   292    293         # NOTE: Queue a suggested modification to any active item.   294    295         # The message is now wrapped and passed on to the recipient.   296    297         return "DECLINECOUNTER", MIMEText("A declining counter proposal has been received.")   298    299     def publish(self):   300    301         "Register details of any relevant item."   302    303         self._record_and_deliver("VTODO", from_organiser=True, queue=False)   304         return self.wrap("PUBLISH", "Details of an item have been received.", from_organiser=True, link=True)   305    306     def refresh(self):   307    308         "Update details of any active item."   309    310         self._record_and_deliver("VTODO", from_organiser=True, queue=False)   311         return self.wrap("REFRESH", "An item update has been received.", from_organiser=True, link=True)   312    313     def reply(self):   314    315         "Record replies and notify the recipient."   316    317         self._record_and_deliver("VTODO", from_organiser=False, queue=False)   318         return self.wrap("REPLY", "A reply has been received.", from_organiser=False, link=True)   319    320     def request(self):   321    322         "Hold requests and notify the recipient."   323    324         self._record_and_deliver("VTODO", from_organiser=True, queue=True)   325    326         # The message is now wrapped and passed on to the recipient.   327    328         return "REQUEST", MIMEText("A request has been queued.")   329    330 # Handler registry.   331    332 handlers = [   333     ("VFREEBUSY",   Freebusy),   334     ("VEVENT",      Event),   335     ("VTODO",       Todo),   336     ("VJOURNAL",    Journal),   337     ]   338    339 # vim: tabstop=4 expandtab shiftwidth=4