imip-agent

imiptools/handlers/person.py

179:ddd660cf1e90
2015-01-27 Paul Boddie Handle recipients individually so that their preferences can be considered when building response messages.
     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 imiptools.profile import Preferences    27 from socket import gethostname    28 from vCalendar import to_node    29     30 def get_manager_url():    31     url_base = MANAGER_URL or "http://%s/" % gethostname()    32     return "%s/%s" % (url_base.rstrip("/"), MANAGER_PATH.lstrip("/"))    33     34 def get_object_url(uid):    35     return "%s/%s" % (get_manager_url().rstrip("/"), uid)    36     37 class PersonHandler(Handler):    38     39     "Handling mechanisms specific to people."    40     41     def _record_and_deliver(self, objtype, from_organiser=True, queue=False, cancel=False):    42     43         oa = self.require_organiser_and_attendees(from_organiser)    44         if not oa:    45             return False    46     47         (organiser, organiser_attr), attendees = organiser_item, attendees = oa    48     49         # Handle notifications and invitations.    50     51         if from_organiser:    52     53             # Process each attendee separately.    54     55             for attendee, attendee_attr in attendees.items():    56     57                 if not self.have_new_object(attendee, objtype):    58                     continue    59     60                 # Record other party free/busy information.    61     62                 if organiser != attendee:    63                     freebusy = self.store.get_freebusy_for_other(attendee, organiser)    64     65                     if organiser_attr.get("PARTSTAT") != "DECLINED":    66                         self.update_freebusy_for_other(freebusy, attendee, organiser, self.get_periods())    67                     else:    68                         self.remove_from_freebusy_for_other(freebusy, attendee, organiser)    69     70                 # Store the object and queue any request.    71     72                 self.store.set_event(attendee, self.uid, to_node(    73                     {objtype : [(self.details, {})]}    74                     ))    75     76                 if queue:    77                     self.store.queue_request(attendee, self.uid)    78                 elif cancel:    79                     self.store.cancel_event(attendee, self.uid)    80     81         # As organiser, update attendance.    82     83         else:    84             obj = self.get_object(organiser, objtype)    85     86             if obj and self.have_new_object(organiser, objtype, obj):    87     88                 # Get attendee details in a usable form.    89     90                 attendee_map = uri_dict(self.get_value_map("ATTENDEE"))    91     92                 for attendee, attendee_attr in attendees.items():    93     94                     # Update attendance in the loaded object.    95     96                     attendee_map[attendee] = attendee_attr    97     98                     # Record other party free/busy information.    99    100                     if organiser != attendee:   101                         freebusy = self.store.get_freebusy_for_other(organiser, attendee)   102    103                         if attendee_attr.get("PARTSTAT") != "DECLINED":   104                             self.update_freebusy_for_other(freebusy, organiser, attendee, self.get_periods())   105                         else:   106                             self.remove_from_freebusy_for_other(freebusy, organiser, attendee)   107    108                 # Set the new details and store the object.   109    110                 obj["ATTENDEE"] = attendee_map.items()   111    112                 self.store.set_event(organiser, self.uid, to_node(   113                     {objtype : [(obj, {})]}   114                     ))   115    116         return True   117    118     def _record_freebusy(self, from_organiser=True):   119    120         "Record free/busy information for the received information."   121    122         freebusy = []   123    124         for value in self.get_values("FREEBUSY") or []:   125             if not isinstance(value, list):   126                 value = [value]   127             for v in value:   128                 try:   129                     start, end = v.split("/", 1)   130                     freebusy.append((start, end))   131                 except ValueError:   132                     pass   133    134         for sender, sender_attr in uri_items(self.get_items(from_organiser and "ORGANIZER" or "ATTENDEE")):   135             self.store.set_freebusy_for_other(get_uri(self.recipient), freebusy, sender)   136    137     def wrap(self, method, text, from_organiser=True, link=True):   138    139         "Wrap any valid message and pass it on to the recipient."   140    141         texts = []   142         texts.append(text)   143         if link:   144             texts.append("If your mail program cannot handle this "   145                          "message, you may view the details here:\n\n%s" %   146                          get_object_url(self.uid))   147    148         return method, MIMEText("\n".join(texts))   149    150 class Event(PersonHandler):   151    152     "An event handler."   153    154     def add(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 "ADD", MIMEText("An addition to an event has been received.")   161    162     def cancel(self):   163    164         "Queue a cancellation of any active event."   165    166         self._record_and_deliver("VEVENT", from_organiser=True, queue=False, cancel=True)   167         return self.wrap("CANCEL", "A cancellation has been received.", from_organiser=True, link=True)   168    169     def counter(self):   170    171         # NOTE: Queue a suggested modification to any active event.   172    173         # The message is now wrapped and passed on to the recipient.   174    175         return "COUNTER", MIMEText("A counter proposal has been received.")   176    177     def declinecounter(self):   178    179         # NOTE: Queue a suggested modification to any active event.   180    181         # The message is now wrapped and passed on to the recipient.   182    183         return "DECLINECOUNTER", MIMEText("A declining counter proposal has been received.")   184    185     def publish(self):   186    187         "Register details of any relevant event."   188    189         self._record_and_deliver("VEVENT", from_organiser=True, queue=False)   190         return self.wrap("PUBLISH", "Details of an event have been received.", from_organiser=True, link=True)   191    192     def refresh(self):   193    194         "Update details of any active event."   195    196         self._record_and_deliver("VEVENT", from_organiser=True, queue=False)   197         return self.wrap("REFRESH", "An event update has been received.", from_organiser=True, link=True)   198    199     def reply(self):   200    201         "Record replies and notify the recipient."   202    203         self._record_and_deliver("VEVENT", from_organiser=False, queue=False)   204         return self.wrap("REPLY", "A reply has been received.", from_organiser=False, link=True)   205    206     def request(self):   207    208         "Hold requests and notify the recipient."   209    210         self._record_and_deliver("VEVENT", from_organiser=True, queue=True)   211    212         # The message is now wrapped and passed on to the recipient.   213    214         return "REQUEST", MIMEText("A request has been queued and can be viewed here: %s" % get_object_url(self.uid))   215    216 class Freebusy(PersonHandler, CommonFreebusy):   217    218     "A free/busy handler."   219    220     def publish(self):   221    222         "Register free/busy information."   223    224         # NOTE: This could be configured to not produce a message.   225    226         self._record_freebusy(from_organiser=True)   227         return self.wrap("PUBLISH", "A free/busy update has been received.", from_organiser=True, link=False)   228    229     def reply(self):   230    231         "Record replies and notify the recipient."   232    233         # NOTE: This could be configured to not produce a message.   234    235         self._record_freebusy(from_organiser=False)   236         return self.wrap("REPLY", "A reply has been received.", from_organiser=False, link=False)   237    238     def request(self):   239    240         """   241         Respond to a request by preparing a reply containing free/busy   242         information for each indicated attendee.   243         """   244    245         # NOTE: This should be subject to policy/preferences.   246    247         return CommonFreebusy.request(self)   248    249 class Journal(PersonHandler):   250    251     "A journal entry handler."   252    253     def add(self):   254    255         # NOTE: Queue a suggested modification to any active entry.   256    257         # The message is now wrapped and passed on to the recipient.   258    259         return "ADD", MIMEText("An addition to a journal entry has been received.")   260    261     def cancel(self):   262    263         # NOTE: Queue a suggested modification to any active entry.   264    265         # The message is now wrapped and passed on to the recipient.   266    267         return "CANCEL", MIMEText("A cancellation has been received.")   268    269     def publish(self):   270    271         # NOTE: Register details of any relevant entry.   272    273         # The message is now wrapped and passed on to the recipient.   274    275         self._record_and_deliver("VJOURNAL", from_organiser=True, queue=False)   276         return self.wrap("PUBLISH", "Details of a journal entry have been received.", from_organiser=True, link=False)   277    278 class Todo(PersonHandler):   279    280     "A to-do item handler."   281    282     def add(self):   283    284         # NOTE: Queue a suggested modification to any active item.   285    286         # The message is now wrapped and passed on to the recipient.   287    288         return "ADD", MIMEText("An addition to an item has been received.")   289    290     def cancel(self):   291    292         # NOTE: Queue a suggested modification to any active item.   293    294         # The message is now wrapped and passed on to the recipient.   295    296         return "CANCEL", MIMEText("A cancellation has been received.")   297    298     def counter(self):   299    300         # NOTE: Queue a suggested modification to any active item.   301    302         # The message is now wrapped and passed on to the recipient.   303    304         return "COUNTER", MIMEText("A counter proposal has been received.")   305    306     def declinecounter(self):   307    308         # NOTE: Queue a suggested modification to any active item.   309    310         # The message is now wrapped and passed on to the recipient.   311    312         return "DECLINECOUNTER", MIMEText("A declining counter proposal has been received.")   313    314     def publish(self):   315    316         "Register details of any relevant item."   317    318         self._record_and_deliver("VTODO", from_organiser=True, queue=False)   319         return self.wrap("PUBLISH", "Details of an item have been received.", from_organiser=True, link=True)   320    321     def refresh(self):   322    323         "Update details of any active item."   324    325         self._record_and_deliver("VTODO", from_organiser=True, queue=False)   326         return self.wrap("REFRESH", "An item update has been received.", from_organiser=True, link=True)   327    328     def reply(self):   329    330         "Record replies and notify the recipient."   331    332         self._record_and_deliver("VTODO", from_organiser=False, queue=False)   333         return self.wrap("REPLY", "A reply has been received.", from_organiser=False, link=True)   334    335     def request(self):   336    337         "Hold requests and notify the recipient."   338    339         self._record_and_deliver("VTODO", from_organiser=True, queue=True)   340    341         # The message is now wrapped and passed on to the recipient.   342    343         return "REQUEST", MIMEText("A request has been queued.")   344    345 # Handler registry.   346    347 handlers = [   348     ("VFREEBUSY",   Freebusy),   349     ("VEVENT",      Event),   350     ("VTODO",       Todo),   351     ("VJOURNAL",    Journal),   352     ]   353    354 # vim: tabstop=4 expandtab shiftwidth=4