1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/imiptools/editing.py Wed Oct 18 13:24:59 2017 +0200
1.3 @@ -0,0 +1,1484 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +User interface data abstractions.
1.8 +
1.9 +Copyright (C) 2014, 2015, 2017 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +from collections import OrderedDict
1.26 +from copy import copy
1.27 +from datetime import datetime, timedelta
1.28 +from imiptools.client import ClientForObject
1.29 +from imiptools.data import get_main_period
1.30 +from imiptools.dates import end_date_from_calendar, end_date_to_calendar, \
1.31 + format_datetime, get_datetime, \
1.32 + get_datetime_attributes, get_end_of_day, \
1.33 + to_date, to_utc_datetime, to_timezone
1.34 +from imiptools.period import get_overlapping_members, RecurringPeriod
1.35 +from itertools import chain
1.36 +
1.37 +# General editing abstractions.
1.38 +
1.39 +class State:
1.40 +
1.41 + "Manage editing state."
1.42 +
1.43 + def __init__(self, callables):
1.44 +
1.45 + """
1.46 + Define state variable initialisation using the given 'callables', which
1.47 + is a mapping that defines a callable for each variable name that is
1.48 + invoked when the variable is first requested.
1.49 + """
1.50 +
1.51 + self.state = {}
1.52 + self.original = {}
1.53 + self.callables = callables
1.54 +
1.55 + def get_callable(self, key):
1.56 + return self.callables.get(key, lambda: None)
1.57 +
1.58 + def ensure_original(self, key):
1.59 +
1.60 + "Ensure the original state for the given 'key'."
1.61 +
1.62 + if not self.original.has_key(key):
1.63 + self.original[key] = self.get_callable(key)()
1.64 +
1.65 + def get_original(self, key):
1.66 +
1.67 + "Return the original state for the given 'key'."
1.68 +
1.69 + self.ensure_original(key)
1.70 + return copy(self.original[key])
1.71 +
1.72 + def get(self, key, reset=False):
1.73 +
1.74 + """
1.75 + Return state for the given 'key', using the configured callable to
1.76 + compute and set the state if no state is already defined.
1.77 +
1.78 + If 'reset' is set to a true value, compute and return the state using
1.79 + the configured callable regardless of any existing state.
1.80 + """
1.81 +
1.82 + if reset or not self.state.has_key(key):
1.83 + self.state[key] = self.get_original(key)
1.84 +
1.85 + return self.state[key]
1.86 +
1.87 + def set(self, key, value):
1.88 +
1.89 + "Set the state of 'key' to 'value'."
1.90 +
1.91 + self.ensure_original(key)
1.92 + self.state[key] = value
1.93 +
1.94 + def has_changed(self, key):
1.95 +
1.96 + "Return whether 'key' has changed during editing."
1.97 +
1.98 + return self.get_original(key) != self.get(key)
1.99 +
1.100 + # Dictionary emulation methods.
1.101 +
1.102 + def __getitem__(self, key):
1.103 + return self.get(key)
1.104 +
1.105 + def __setitem__(self, key, value):
1.106 + self.set(key, value)
1.107 +
1.108 +
1.109 +
1.110 +# Object editing abstractions.
1.111 +
1.112 +class EditingClient(ClientForObject):
1.113 +
1.114 + "A simple calendar client."
1.115 +
1.116 + def __init__(self, user, messenger, store, journal, preferences_dir):
1.117 + ClientForObject.__init__(self, None, user, messenger, store,
1.118 + journal=journal,
1.119 + preferences_dir=preferences_dir)
1.120 + self.reset()
1.121 +
1.122 + # Editing state.
1.123 +
1.124 + def reset(self):
1.125 +
1.126 + "Reset the editing state."
1.127 +
1.128 + self.state = State({
1.129 + "attendees" : lambda: OrderedDict(self.obj.get_items("ATTENDEE") or []),
1.130 + "organiser" : lambda: self.obj.get_value("ORGANIZER"),
1.131 + "periods" : lambda: form_periods_from_periods(self.get_unedited_periods()),
1.132 + "suggested_attendees" : self.get_suggested_attendees,
1.133 + "suggested_periods" : self.get_suggested_periods,
1.134 + "summary" : lambda: self.obj.get_value("SUMMARY"),
1.135 + })
1.136 +
1.137 + # Access to stored and current information.
1.138 +
1.139 + def get_stored_periods(self):
1.140 +
1.141 + """
1.142 + Return the stored, unrevised, integral periods for the event, excluding
1.143 + revisions from separate recurrence instances.
1.144 + """
1.145 +
1.146 + return event_periods_from_periods(self.get_periods())
1.147 +
1.148 + def get_unedited_periods(self):
1.149 +
1.150 + """
1.151 + Return the original, unedited periods including revisions from separate
1.152 + recurrence instances.
1.153 + """
1.154 +
1.155 + return event_periods_from_updated_periods(self.get_updated_periods())
1.156 +
1.157 + def get_counters(self):
1.158 +
1.159 + "Return a counter-proposal mapping from attendees to objects."
1.160 +
1.161 + d = {}
1.162 +
1.163 + # Get counter-proposals for the specific object.
1.164 +
1.165 + recurrenceids = [self.recurrenceid]
1.166 +
1.167 + # And for all recurrences associated with a parent object.
1.168 +
1.169 + if not self.recurrenceid:
1.170 + recurrenceids += self.store.get_counter_recurrences(self.user, self.uid)
1.171 +
1.172 + # Map attendees to objects.
1.173 +
1.174 + for recurrenceid in recurrenceids:
1.175 + attendees = self.store.get_counters(self.user, self.uid, recurrenceid)
1.176 + for attendee in attendees:
1.177 + if not d.has_key(attendee):
1.178 + d[attendee] = []
1.179 + d[attendee].append(self.get_stored_object(self.uid, recurrenceid, "counters", attendee))
1.180 +
1.181 + return d
1.182 +
1.183 + def get_suggested_attendees(self):
1.184 +
1.185 + "For all counter-proposals, return suggested attendee items."
1.186 +
1.187 + existing = self.state.get("attendees")
1.188 + l = []
1.189 + for attendee, objects in self.get_counters().items():
1.190 + for obj in objects:
1.191 + for suggested, attr in obj.get_items("ATTENDEE"):
1.192 + if suggested not in existing:
1.193 + l.append((attendee, (suggested, attr)))
1.194 + return l
1.195 +
1.196 + def get_suggested_periods(self):
1.197 +
1.198 + "For all counter-proposals, return suggested event periods."
1.199 +
1.200 + existing = self.state.get("periods")
1.201 +
1.202 + # Get active periods for filtering of suggested periods.
1.203 +
1.204 + active = []
1.205 + for p in existing:
1.206 + if not p.cancelled:
1.207 + active.append(p)
1.208 +
1.209 + suggested = []
1.210 +
1.211 + for attendee, objects in self.get_counters().items():
1.212 +
1.213 + # For each object, obtain suggested periods.
1.214 +
1.215 + for obj in objects:
1.216 +
1.217 + # Obtain the current periods for the object providing the
1.218 + # suggested periods.
1.219 +
1.220 + updated = self.get_updated_periods(obj)
1.221 + suggestions = event_periods_from_updated_periods(updated)
1.222 +
1.223 + # Compare current periods with suggested periods.
1.224 +
1.225 + new = set(suggestions).difference(active)
1.226 +
1.227 + # Treat each specific recurrence as affecting only the original
1.228 + # period.
1.229 +
1.230 + if obj.get_recurrenceid():
1.231 + removed = []
1.232 + else:
1.233 + removed = set(active).difference(suggestions)
1.234 +
1.235 + # Associate new and removed periods with the attendee.
1.236 +
1.237 + for period in new:
1.238 + suggested.append((attendee, period, "add"))
1.239 +
1.240 + for period in removed:
1.241 + suggested.append((attendee, period, "remove"))
1.242 +
1.243 + return suggested
1.244 +
1.245 + # Validation methods.
1.246 +
1.247 + def get_checked_periods(self):
1.248 +
1.249 + """
1.250 + Check the edited periods and return objects representing them, setting
1.251 + the "periods" state. If errors occur, raise an exception and set the
1.252 + "errors" state.
1.253 + """
1.254 +
1.255 + self.state["period_errors"] = errors = {}
1.256 +
1.257 + # Basic validation.
1.258 +
1.259 + try:
1.260 + periods = event_periods_from_periods(self.state.get("periods"))
1.261 +
1.262 + except PeriodError, exc:
1.263 +
1.264 + # Obtain error and period index details from the exception,
1.265 + # collecting errors for each index position.
1.266 +
1.267 + for err, index in exc.args:
1.268 + l = errors.get(index)
1.269 + if not l:
1.270 + l = errors[index] = []
1.271 + l.append(err)
1.272 + raise
1.273 +
1.274 + # Check for overlapping periods.
1.275 +
1.276 + overlapping = get_overlapping_members(periods)
1.277 +
1.278 + for period in overlapping:
1.279 + for index, p in enumerate(periods):
1.280 + if period is p:
1.281 + errors[index] = ["overlap"]
1.282 +
1.283 + if overlapping:
1.284 + raise PeriodError
1.285 +
1.286 + self.state["periods"] = form_periods_from_periods(periods)
1.287 + return periods
1.288 +
1.289 + # Update result computation.
1.290 +
1.291 + def classify_attendee_changes(self):
1.292 +
1.293 + "Classify the attendees in the event."
1.294 +
1.295 + original = self.state.get_original("attendees")
1.296 + current = self.state.get("attendees")
1.297 + return classify_attendee_changes(original, current)
1.298 +
1.299 + def classify_attendee_operations(self):
1.300 +
1.301 + "Classify attendee update operations."
1.302 +
1.303 + new, modified, unmodified, removed = self.classify_attendee_changes()
1.304 +
1.305 + if self.is_organiser():
1.306 + to_invite = new
1.307 + to_cancel = removed
1.308 + to_modify = modified
1.309 + else:
1.310 + to_invite = new
1.311 + to_cancel = {}
1.312 + to_modify = modified
1.313 +
1.314 + return to_invite, to_cancel, to_modify
1.315 +
1.316 + def classify_period_changes(self):
1.317 +
1.318 + "Classify changes in the updated periods for the edited event."
1.319 +
1.320 + updated = self.combine_periods_for_comparison()
1.321 + return classify_period_changes(updated)
1.322 +
1.323 + def classify_periods(self):
1.324 +
1.325 + "Classify the updated periods for the edited event."
1.326 +
1.327 + updated = self.combine_periods()
1.328 + return classify_periods(updated)
1.329 +
1.330 + def combine_periods(self):
1.331 +
1.332 + "Combine stored and checked edited periods to make updated periods."
1.333 +
1.334 + stored = self.get_stored_periods()
1.335 + current = self.get_checked_periods()
1.336 + return combine_periods(stored, current)
1.337 +
1.338 + def combine_periods_for_comparison(self):
1.339 +
1.340 + "Combine unedited and checked edited periods to make updated periods."
1.341 +
1.342 + original = self.get_unedited_periods()
1.343 + current = self.get_checked_periods()
1.344 + return combine_periods(original, current)
1.345 +
1.346 + def classify_period_operations(self, is_changed=False):
1.347 +
1.348 + "Classify period update operations."
1.349 +
1.350 + new, replaced, retained, cancelled, obsolete = self.classify_periods()
1.351 +
1.352 + modified, unmodified, removed = self.classify_period_changes()
1.353 +
1.354 + is_organiser = self.is_organiser()
1.355 + is_shared = self.obj.is_shared()
1.356 +
1.357 + return classify_period_operations(new, replaced, retained, cancelled,
1.358 + obsolete, modified, removed,
1.359 + is_organiser, is_shared, is_changed)
1.360 +
1.361 + def properties_changed(self):
1.362 +
1.363 + "Test for changes in event details."
1.364 +
1.365 + is_changed = []
1.366 +
1.367 + for name in ["summary"]:
1.368 + if self.state.has_changed(name):
1.369 + is_changed.append(name)
1.370 +
1.371 + return is_changed
1.372 +
1.373 + def finish(self):
1.374 +
1.375 + "Finish editing, writing edited details to the object."
1.376 +
1.377 + if self.state.get("finished"):
1.378 + return
1.379 +
1.380 + is_changed = self.properties_changed()
1.381 +
1.382 + # Determine attendee modifications.
1.383 +
1.384 + self.state["attendee_operations"] = \
1.385 + to_invite, to_cancel, to_modify = \
1.386 + self.classify_attendee_operations()
1.387 +
1.388 + self.state["attendees_to_cancel"] = to_cancel
1.389 +
1.390 + # Determine period modification operations.
1.391 + # Use property changes and attendee suggestions to affect the result for
1.392 + # attendee responses.
1.393 +
1.394 + is_changed = is_changed or to_invite
1.395 +
1.396 + self.state["period_operations"] = \
1.397 + to_unschedule, to_reschedule, to_add, to_exclude, to_set, \
1.398 + all_unscheduled, all_rescheduled = \
1.399 + self.classify_period_operations(is_changed)
1.400 +
1.401 + # Determine whole event update status.
1.402 +
1.403 + is_changed = is_changed or to_set
1.404 +
1.405 + # Update event details.
1.406 +
1.407 + if self.can_edit_properties():
1.408 + self.obj.set_value("SUMMARY", self.state.get("summary"))
1.409 +
1.410 + self.update_attendees(to_invite, to_cancel, to_modify)
1.411 + self.update_event_from_periods(to_set, to_exclude)
1.412 +
1.413 + # Classify the nature of any update.
1.414 +
1.415 + if is_changed:
1.416 + self.state["changed"] = "complete"
1.417 + elif to_reschedule or to_unschedule or to_add:
1.418 + self.state["changed"] = "incremental"
1.419 +
1.420 + self.state["finished"] = self.update_event_version(is_changed)
1.421 +
1.422 + # Update preparation.
1.423 +
1.424 + def have_update(self):
1.425 +
1.426 + "Return whether an update can be prepared and sent."
1.427 +
1.428 + return not self.is_organiser() or \
1.429 + not self.obj.is_shared() or \
1.430 + self.obj.is_shared() and self.state.get("changed") and \
1.431 + self.have_other_attendees()
1.432 +
1.433 + def have_other_attendees(self):
1.434 +
1.435 + "Return whether any attendees other than the user are present."
1.436 +
1.437 + attendees = self.state.get("attendees")
1.438 + return attendees and (not attendees.has_key(self.user) or len(attendees.keys()) > 1)
1.439 +
1.440 + def prepare_cancel_message(self):
1.441 +
1.442 + "Prepare the cancel message for uninvited attendees."
1.443 +
1.444 + to_cancel = self.state.get("attendees_to_cancel")
1.445 + return self.make_cancel_message(to_cancel)
1.446 +
1.447 + def prepare_publish_message(self):
1.448 +
1.449 + "Prepare the publishing message for the updated event."
1.450 +
1.451 + to_unschedule, to_reschedule, to_add, to_exclude, to_set, \
1.452 + all_unscheduled, all_rescheduled = self.state.get("period_operations")
1.453 +
1.454 + return self.make_self_update_message(all_unscheduled, all_rescheduled, to_add)
1.455 +
1.456 + def prepare_update_message(self):
1.457 +
1.458 + "Prepare the update message for the updated event."
1.459 +
1.460 + if not self.have_update():
1.461 + return None
1.462 +
1.463 + # Obtain operation details.
1.464 +
1.465 + to_unschedule, to_reschedule, to_add, to_exclude, to_set, \
1.466 + all_unscheduled, all_rescheduled = self.state.get("period_operations")
1.467 +
1.468 + # Prepare the message.
1.469 +
1.470 + recipients = self.get_recipients()
1.471 + update_parent = self.state["changed"] == "complete"
1.472 +
1.473 + if self.is_organiser():
1.474 + return self.make_update_message(recipients, update_parent,
1.475 + to_unschedule, to_reschedule,
1.476 + all_unscheduled, all_rescheduled,
1.477 + to_add)
1.478 + else:
1.479 + return self.make_response_message(recipients, update_parent,
1.480 + all_rescheduled, to_reschedule)
1.481 +
1.482 + # Modification methods.
1.483 +
1.484 + def add_attendee(self, uri=None):
1.485 +
1.486 + "Add a blank attendee."
1.487 +
1.488 + attendees = self.state.get("attendees")
1.489 + attendees[uri or ""] = {"PARTSTAT" : "NEEDS-ACTION"}
1.490 +
1.491 + def add_suggested_attendee(self, index):
1.492 +
1.493 + "Add the suggested attendee at 'index' to the event."
1.494 +
1.495 + attendees = self.state.get("attendees")
1.496 + suggested_attendees = self.state.get("suggested_attendees")
1.497 + try:
1.498 + attendee, (suggested, attr) = suggested_attendees[index]
1.499 + self.add_attendee(suggested)
1.500 + except IndexError:
1.501 + pass
1.502 +
1.503 + def add_period(self):
1.504 +
1.505 + "Add a copy of the main period as a new recurrence."
1.506 +
1.507 + current = self.state.get("periods")
1.508 + new = get_main_period(current).copy()
1.509 + new.origin = "RDATE"
1.510 + new.replacement = False
1.511 + new.recurrenceid = False
1.512 + new.cancelled = False
1.513 + current.append(new)
1.514 +
1.515 + def apply_suggested_period(self, index):
1.516 +
1.517 + "Apply the suggested period at 'index' to the event."
1.518 +
1.519 + current = self.state.get("periods")
1.520 + suggested = self.state.get("suggested_periods")
1.521 +
1.522 + try:
1.523 + attendee, period, operation = suggested[index]
1.524 + period = form_period_from_period(period)
1.525 +
1.526 + # Cancel any removed periods.
1.527 +
1.528 + if operation == "remove":
1.529 + for index, p in enumerate(current):
1.530 + if p == period:
1.531 + self.cancel_periods([index])
1.532 + break
1.533 +
1.534 + # Add or replace any other suggestions.
1.535 +
1.536 + elif operation == "add":
1.537 +
1.538 + # Make the status of the period compatible.
1.539 +
1.540 + period.cancelled = False
1.541 + period.origin = "DTSTART-RECUR"
1.542 +
1.543 + # Either replace or add the period.
1.544 +
1.545 + recurrenceid = period.get_recurrenceid()
1.546 +
1.547 + for i, p in enumerate(current):
1.548 + if p.get_recurrenceid() == recurrenceid:
1.549 + current[i] = period
1.550 + break
1.551 +
1.552 + # Add as a new period.
1.553 +
1.554 + else:
1.555 + period.recurrenceid = None
1.556 + current.append(period)
1.557 +
1.558 + except IndexError:
1.559 + pass
1.560 +
1.561 + def cancel_periods(self, indexes, cancelled=True):
1.562 +
1.563 + """
1.564 + Set cancellation state for periods with the given 'indexes', indicating
1.565 + 'cancelled' as a true or false value. New periods will be removed if
1.566 + cancelled.
1.567 + """
1.568 +
1.569 + periods = self.state.get("periods")
1.570 + to_remove = []
1.571 + removed = 0
1.572 +
1.573 + for index in indexes:
1.574 + p = periods[index]
1.575 +
1.576 + # Make replacements from existing periods and cancel them.
1.577 +
1.578 + if p.recurrenceid:
1.579 + p.replacement = True
1.580 + p.cancelled = cancelled
1.581 +
1.582 + # Remove new periods completely.
1.583 +
1.584 + elif cancelled:
1.585 + to_remove.append(index - removed)
1.586 + removed += 1
1.587 +
1.588 + for index in to_remove:
1.589 + del periods[index]
1.590 +
1.591 + def can_edit_attendance(self):
1.592 +
1.593 + "Return whether the organiser's attendance can be edited."
1.594 +
1.595 + return self.state.get("attendees").has_key(self.user)
1.596 +
1.597 + def edit_attendance(self, partstat):
1.598 +
1.599 + "Set the 'partstat' of the current user, if attending."
1.600 +
1.601 + attendees = self.state.get("attendees")
1.602 + attr = attendees.get(self.user)
1.603 +
1.604 + # Set the attendance for the user, if attending.
1.605 +
1.606 + if attr is not None:
1.607 + new_attr = {}
1.608 + new_attr.update(attr)
1.609 + new_attr["PARTSTAT"] = partstat
1.610 + attendees[self.user] = new_attr
1.611 +
1.612 + def can_edit_attendee(self, index):
1.613 +
1.614 + """
1.615 + Return whether the attendee at 'index' can be edited, requiring either
1.616 + the organiser and an unshared event, or a new attendee.
1.617 + """
1.618 +
1.619 + attendees = self.state.get("attendees")
1.620 + attendee = attendees.keys()[index]
1.621 +
1.622 + try:
1.623 + attr = attendees[attendee]
1.624 + if self.is_organiser() and not self.obj.is_shared() or not attr:
1.625 + return (attendee, attr)
1.626 + except IndexError:
1.627 + pass
1.628 +
1.629 + return None
1.630 +
1.631 + def can_remove_attendee(self, index):
1.632 +
1.633 + """
1.634 + Return whether the attendee at 'index' can be removed, requiring either
1.635 + the organiser or a new attendee.
1.636 + """
1.637 +
1.638 + attendees = self.state.get("attendees")
1.639 + attendee = attendees.keys()[index]
1.640 +
1.641 + try:
1.642 + attr = attendees[attendee]
1.643 + if self.is_organiser() or not attr:
1.644 + return (attendee, attr)
1.645 + except IndexError:
1.646 + pass
1.647 +
1.648 + return None
1.649 +
1.650 + def remove_attendees(self, indexes):
1.651 +
1.652 + "Remove attendee at 'index'."
1.653 +
1.654 + attendees = self.state.get("attendees")
1.655 + to_remove = []
1.656 +
1.657 + for index in indexes:
1.658 + attendee_item = self.can_remove_attendee(index)
1.659 + if attendee_item:
1.660 + attendee, attr = attendee_item
1.661 + to_remove.append(attendee)
1.662 +
1.663 + for key in to_remove:
1.664 + del attendees[key]
1.665 +
1.666 + def can_edit_period(self, index):
1.667 +
1.668 + """
1.669 + Return the period at 'index' for editing or None if it cannot be edited.
1.670 + """
1.671 +
1.672 + try:
1.673 + return self.state.get("periods")[index]
1.674 + except IndexError:
1.675 + return None
1.676 +
1.677 + def can_edit_properties(self):
1.678 +
1.679 + "Return whether general event properties can be edited."
1.680 +
1.681 + return True
1.682 +
1.683 +
1.684 +
1.685 +# Period-related abstractions.
1.686 +
1.687 +class PeriodError(Exception):
1.688 + pass
1.689 +
1.690 +class EditablePeriod(RecurringPeriod):
1.691 +
1.692 + "An editable period tracking the identity of any original period."
1.693 +
1.694 + def _get_recurrenceid_item(self):
1.695 +
1.696 + # Convert any stored identifier to the current time zone.
1.697 + # NOTE: This should not be necessary, but is done for consistency with
1.698 + # NOTE: the datetime properties.
1.699 +
1.700 + dt = get_datetime(self.recurrenceid)
1.701 + dt = to_timezone(dt, self.tzid)
1.702 + return dt, get_datetime_attributes(dt)
1.703 +
1.704 + def get_recurrenceid(self):
1.705 +
1.706 + """
1.707 + Return a recurrence identity to be used to associate stored periods with
1.708 + edited periods.
1.709 + """
1.710 +
1.711 + if not self.recurrenceid:
1.712 + return RecurringPeriod.get_recurrenceid(self)
1.713 + return self.recurrenceid
1.714 +
1.715 + def get_recurrenceid_item(self):
1.716 +
1.717 + """
1.718 + Return a recurrence identifier value and datetime properties for use in
1.719 + specifying the RECURRENCE-ID property.
1.720 + """
1.721 +
1.722 + if not self.recurrenceid:
1.723 + return RecurringPeriod.get_recurrenceid_item(self)
1.724 + return self._get_recurrenceid_item()
1.725 +
1.726 +class EventPeriod(EditablePeriod):
1.727 +
1.728 + """
1.729 + A simple period plus attribute details, compatible with RecurringPeriod, and
1.730 + intended to represent information obtained from an iCalendar resource.
1.731 + """
1.732 +
1.733 + def __init__(self, start, end, tzid=None, origin=None, start_attr=None,
1.734 + end_attr=None, form_start=None, form_end=None,
1.735 + replacement=False, cancelled=False, recurrenceid=None):
1.736 +
1.737 + """
1.738 + Initialise a period with the given 'start' and 'end' datetimes.
1.739 +
1.740 + The optional 'tzid' provides time zone information, and the optional
1.741 + 'origin' indicates the kind of period this object describes.
1.742 +
1.743 + The optional 'start_attr' and 'end_attr' provide metadata for the start
1.744 + and end datetimes respectively, and 'form_start' and 'form_end' are
1.745 + values provided as textual input.
1.746 +
1.747 + The 'replacement' flag indicates whether the period is provided by a
1.748 + separate recurrence instance.
1.749 +
1.750 + The 'cancelled' flag indicates whether a separate recurrence is
1.751 + cancelled.
1.752 +
1.753 + The 'recurrenceid' describes the original identity of the period,
1.754 + regardless of whether it is separate or not.
1.755 + """
1.756 +
1.757 + EditablePeriod.__init__(self, start, end, tzid, origin, start_attr, end_attr)
1.758 + self.form_start = form_start
1.759 + self.form_end = form_end
1.760 +
1.761 + # Information about whether a separate recurrence provides this period
1.762 + # and the original period identity.
1.763 +
1.764 + self.replacement = replacement
1.765 + self.cancelled = cancelled
1.766 + self.recurrenceid = recurrenceid
1.767 +
1.768 + # Additional editing state.
1.769 +
1.770 + self.new_replacement = False
1.771 +
1.772 + def as_tuple(self):
1.773 + return self.start, self.end, self.tzid, self.origin, self.start_attr, \
1.774 + self.end_attr, self.form_start, self.form_end, self.replacement, \
1.775 + self.cancelled, self.recurrenceid
1.776 +
1.777 + def __repr__(self):
1.778 + return "EventPeriod%r" % (self.as_tuple(),)
1.779 +
1.780 + def copy(self):
1.781 + return EventPeriod(*self.as_tuple())
1.782 +
1.783 + def as_event_period(self, index=None):
1.784 + return self
1.785 +
1.786 + def get_start_item(self):
1.787 + return self.get_start(), self.get_start_attr()
1.788 +
1.789 + def get_end_item(self):
1.790 + return self.get_end(), self.get_end_attr()
1.791 +
1.792 + # Form data compatibility methods.
1.793 +
1.794 + def get_form_start(self):
1.795 + if not self.form_start:
1.796 + self.form_start = self.get_form_date(self.get_start(), self.start_attr)
1.797 + return self.form_start
1.798 +
1.799 + def get_form_end(self):
1.800 + if not self.form_end:
1.801 + self.form_end = self.get_form_date(end_date_from_calendar(self.get_end()), self.end_attr)
1.802 + return self.form_end
1.803 +
1.804 + def as_form_period(self):
1.805 + return FormPeriod(
1.806 + self.get_form_start(),
1.807 + self.get_form_end(),
1.808 + isinstance(self.end, datetime) or self.get_start() != self.get_end() - timedelta(1),
1.809 + isinstance(self.start, datetime) or isinstance(self.end, datetime),
1.810 + self.tzid,
1.811 + self.origin,
1.812 + self.replacement,
1.813 + self.cancelled,
1.814 + self.recurrenceid
1.815 + )
1.816 +
1.817 + def get_form_date(self, dt, attr=None):
1.818 + return FormDate(
1.819 + format_datetime(to_date(dt)),
1.820 + isinstance(dt, datetime) and str(dt.hour) or None,
1.821 + isinstance(dt, datetime) and str(dt.minute) or None,
1.822 + isinstance(dt, datetime) and str(dt.second) or None,
1.823 + attr and attr.get("TZID") or None,
1.824 + dt, attr
1.825 + )
1.826 +
1.827 +class FormPeriod(EditablePeriod):
1.828 +
1.829 + "A period whose information originates from a form."
1.830 +
1.831 + def __init__(self, start, end, end_enabled=True, times_enabled=True,
1.832 + tzid=None, origin=None, replacement=False, cancelled=False,
1.833 + recurrenceid=None):
1.834 + self.start = start
1.835 + self.end = end
1.836 + self.end_enabled = end_enabled
1.837 + self.times_enabled = times_enabled
1.838 + self.tzid = tzid
1.839 + self.origin = origin
1.840 + self.replacement = replacement
1.841 + self.cancelled = cancelled
1.842 + self.recurrenceid = recurrenceid
1.843 + self.new_replacement = False
1.844 +
1.845 + def as_tuple(self):
1.846 + return self.start, self.end, self.end_enabled, self.times_enabled, \
1.847 + self.tzid, self.origin, self.replacement, self.cancelled, \
1.848 + self.recurrenceid
1.849 +
1.850 + def __repr__(self):
1.851 + return "FormPeriod%r" % (self.as_tuple(),)
1.852 +
1.853 + def copy(self):
1.854 + args = (self.start.copy(), self.end.copy()) + self.as_tuple()[2:]
1.855 + return FormPeriod(*args)
1.856 +
1.857 + def as_event_period(self, index=None):
1.858 +
1.859 + """
1.860 + Return a converted version of this object as an event period suitable
1.861 + for iCalendar usage. If 'index' is indicated, include it in any error
1.862 + raised in the conversion process.
1.863 + """
1.864 +
1.865 + dtstart, dtstart_attr = self.get_start_item()
1.866 + if not dtstart:
1.867 + if index is not None:
1.868 + raise PeriodError(("dtstart", index))
1.869 + else:
1.870 + raise PeriodError("dtstart")
1.871 +
1.872 + dtend, dtend_attr = self.get_end_item()
1.873 + if not dtend:
1.874 + if index is not None:
1.875 + raise PeriodError(("dtend", index))
1.876 + else:
1.877 + raise PeriodError("dtend")
1.878 +
1.879 + if dtstart > dtend:
1.880 + if index is not None:
1.881 + raise PeriodError(("dtstart", index), ("dtend", index))
1.882 + else:
1.883 + raise PeriodError("dtstart", "dtend")
1.884 +
1.885 + return EventPeriod(dtstart, end_date_to_calendar(dtend), self.tzid,
1.886 + self.origin, dtstart_attr, dtend_attr,
1.887 + self.start, self.end, self.replacement,
1.888 + self.cancelled, self.recurrenceid)
1.889 +
1.890 + # Period data methods.
1.891 +
1.892 + def get_start(self):
1.893 + return self.start and self.start.as_datetime(self.times_enabled) or None
1.894 +
1.895 + def get_end(self):
1.896 +
1.897 + # Handle specified end datetimes.
1.898 +
1.899 + if self.end_enabled:
1.900 + dtend = self.end.as_datetime(self.times_enabled)
1.901 + if not dtend:
1.902 + return None
1.903 +
1.904 + # Handle same day times.
1.905 +
1.906 + elif self.times_enabled:
1.907 + formdate = FormDate(self.start.date, self.end.hour, self.end.minute, self.end.second, self.end.tzid)
1.908 + dtend = formdate.as_datetime(self.times_enabled)
1.909 + if not dtend:
1.910 + return None
1.911 +
1.912 + # Otherwise, treat the end date as the start date. Datetimes are
1.913 + # handled by making the event occupy the rest of the day.
1.914 +
1.915 + else:
1.916 + dtstart, dtstart_attr = self.get_start_item()
1.917 + if dtstart:
1.918 + if isinstance(dtstart, datetime):
1.919 + dtend = get_end_of_day(dtstart, dtstart_attr["TZID"])
1.920 + else:
1.921 + dtend = dtstart
1.922 + else:
1.923 + return None
1.924 +
1.925 + return dtend
1.926 +
1.927 + def get_start_attr(self):
1.928 + return self.start and self.start.get_attributes(self.times_enabled) or {}
1.929 +
1.930 + def get_end_attr(self):
1.931 + return self.end and self.end.get_attributes(self.times_enabled) or {}
1.932 +
1.933 + # Form data methods.
1.934 +
1.935 + def get_form_start(self):
1.936 + return self.start
1.937 +
1.938 + def get_form_end(self):
1.939 + return self.end
1.940 +
1.941 + def as_form_period(self):
1.942 + return self
1.943 +
1.944 +class FormDate:
1.945 +
1.946 + "Date information originating from form information."
1.947 +
1.948 + def __init__(self, date=None, hour=None, minute=None, second=None, tzid=None, dt=None, attr=None):
1.949 + self.date = date
1.950 + self.hour = hour
1.951 + self.minute = minute
1.952 + self.second = second
1.953 + self.tzid = tzid
1.954 + self.dt = dt
1.955 + self.attr = attr
1.956 +
1.957 + def as_tuple(self):
1.958 + return self.date, self.hour, self.minute, self.second, self.tzid, self.dt, self.attr
1.959 +
1.960 + def copy(self):
1.961 + return FormDate(*self.as_tuple())
1.962 +
1.963 + def reset(self):
1.964 + self.dt = None
1.965 +
1.966 + def __repr__(self):
1.967 + return "FormDate%r" % (self.as_tuple(),)
1.968 +
1.969 + def get_component(self, value):
1.970 + return (value or "").rjust(2, "0")[:2]
1.971 +
1.972 + def get_hour(self):
1.973 + return self.get_component(self.hour)
1.974 +
1.975 + def get_minute(self):
1.976 + return self.get_component(self.minute)
1.977 +
1.978 + def get_second(self):
1.979 + return self.get_component(self.second)
1.980 +
1.981 + def get_date_string(self):
1.982 + return self.date or ""
1.983 +
1.984 + def get_datetime_string(self):
1.985 + if not self.date:
1.986 + return ""
1.987 +
1.988 + hour = self.hour; minute = self.minute; second = self.second
1.989 +
1.990 + if hour or minute or second:
1.991 + time = "T%s%s%s" % tuple(map(self.get_component, (hour, minute, second)))
1.992 + else:
1.993 + time = ""
1.994 +
1.995 + return "%s%s" % (self.date, time)
1.996 +
1.997 + def get_tzid(self):
1.998 + return self.tzid
1.999 +
1.1000 + def as_datetime(self, with_time=True):
1.1001 +
1.1002 + """
1.1003 + Return a datetime for this object if one is provided or can be produced.
1.1004 + """
1.1005 +
1.1006 + # Return any original datetime details.
1.1007 +
1.1008 + if self.dt:
1.1009 + return self.dt
1.1010 +
1.1011 + # Otherwise, construct a datetime.
1.1012 +
1.1013 + s, attr = self.as_datetime_item(with_time)
1.1014 + if not s:
1.1015 + return None
1.1016 +
1.1017 + # An erroneous datetime will yield None as result.
1.1018 +
1.1019 + try:
1.1020 + return get_datetime(s, attr)
1.1021 + except ValueError:
1.1022 + return None
1.1023 +
1.1024 + def as_datetime_item(self, with_time=True):
1.1025 +
1.1026 + """
1.1027 + Return a (datetime string, attr) tuple for the datetime information
1.1028 + provided by this object, where both tuple elements will be None if no
1.1029 + suitable date or datetime information exists.
1.1030 + """
1.1031 +
1.1032 + s = None
1.1033 + if with_time:
1.1034 + s = self.get_datetime_string()
1.1035 + attr = self.get_attributes(True)
1.1036 + if not s:
1.1037 + s = self.get_date_string()
1.1038 + attr = self.get_attributes(False)
1.1039 + if not s:
1.1040 + return None, None
1.1041 + return s, attr
1.1042 +
1.1043 + def get_attributes(self, with_time=True):
1.1044 +
1.1045 + "Return attributes for the date or datetime represented by this object."
1.1046 +
1.1047 + if with_time:
1.1048 + return {"TZID" : self.get_tzid(), "VALUE" : "DATE-TIME"}
1.1049 + else:
1.1050 + return {"VALUE" : "DATE"}
1.1051 +
1.1052 +def event_period_from_period(period, index=None):
1.1053 +
1.1054 + """
1.1055 + Convert a 'period' to one suitable for use in an iCalendar representation.
1.1056 + In an "event period" representation, the end day of any date-level event is
1.1057 + encoded as the "day after" the last day actually involved in the event.
1.1058 + """
1.1059 +
1.1060 + if isinstance(period, EventPeriod):
1.1061 + return period
1.1062 + elif isinstance(period, FormPeriod):
1.1063 + return period.as_event_period(index)
1.1064 + else:
1.1065 + dtstart, dtstart_attr = period.get_start_item()
1.1066 + dtend, dtend_attr = period.get_end_item()
1.1067 +
1.1068 + if not isinstance(period, RecurringPeriod):
1.1069 + dtend = end_date_to_calendar(dtend)
1.1070 +
1.1071 + return EventPeriod(dtstart, dtend, period.tzid, period.origin,
1.1072 + dtstart_attr, dtend_attr,
1.1073 + recurrenceid=format_datetime(to_utc_datetime(dtstart)))
1.1074 +
1.1075 +def event_periods_from_periods(periods):
1.1076 + return map(event_period_from_period, periods, range(0, len(periods)))
1.1077 +
1.1078 +def form_period_from_period(period):
1.1079 +
1.1080 + """
1.1081 + Convert a 'period' into a representation usable in a user-editable form.
1.1082 + In a "form period" representation, the end day of any date-level event is
1.1083 + presented in a "natural" form, not the iCalendar "day after" form.
1.1084 + """
1.1085 +
1.1086 + if isinstance(period, EventPeriod):
1.1087 + return period.as_form_period()
1.1088 + elif isinstance(period, FormPeriod):
1.1089 + return period
1.1090 + else:
1.1091 + return event_period_from_period(period).as_form_period()
1.1092 +
1.1093 +def form_periods_from_periods(periods):
1.1094 + return map(form_period_from_period, periods)
1.1095 +
1.1096 +
1.1097 +
1.1098 +# Event period processing.
1.1099 +
1.1100 +def periods_from_updated_periods(updated_periods, fn):
1.1101 +
1.1102 + """
1.1103 + Return periods from the given 'updated_periods' created using 'fn', setting
1.1104 + replacement, cancelled and recurrence identifier details.
1.1105 +
1.1106 + This function should be used to produce editing-related periods from the
1.1107 + general updated periods provided by the client abstractions.
1.1108 + """
1.1109 +
1.1110 + periods = []
1.1111 +
1.1112 + for sp, p in updated_periods:
1.1113 +
1.1114 + # Stored periods with corresponding current periods.
1.1115 +
1.1116 + if p:
1.1117 + period = fn(p)
1.1118 +
1.1119 + # Replacements are identified by comparing object identities, since
1.1120 + # a replacement will not be provided by the same object.
1.1121 +
1.1122 + if sp is not p:
1.1123 + period.replacement = True
1.1124 +
1.1125 + # Stored periods without corresponding current periods.
1.1126 +
1.1127 + else:
1.1128 + period = fn(sp)
1.1129 + period.replacement = True
1.1130 + period.cancelled = True
1.1131 +
1.1132 + # Replace the recurrence identifier with that of the original period.
1.1133 +
1.1134 + period.recurrenceid = sp.get_recurrenceid()
1.1135 + periods.append(period)
1.1136 +
1.1137 + return periods
1.1138 +
1.1139 +def event_periods_from_updated_periods(updated_periods):
1.1140 + return periods_from_updated_periods(updated_periods, event_period_from_period)
1.1141 +
1.1142 +def form_periods_from_updated_periods(updated_periods):
1.1143 + return periods_from_updated_periods(updated_periods, form_period_from_period)
1.1144 +
1.1145 +def periods_by_recurrence(periods):
1.1146 +
1.1147 + """
1.1148 + Return a mapping from recurrence identifier to period for 'periods' along
1.1149 + with a collection of unmapped periods.
1.1150 + """
1.1151 +
1.1152 + d = {}
1.1153 + new = []
1.1154 +
1.1155 + for p in periods:
1.1156 + if not p.recurrenceid:
1.1157 + new.append(p)
1.1158 + else:
1.1159 + d[p.recurrenceid] = p
1.1160 +
1.1161 + return d, new
1.1162 +
1.1163 +def combine_periods(old, new):
1.1164 +
1.1165 + """
1.1166 + Combine 'old' and 'new' periods for comparison, making a list of (old, new)
1.1167 + updated period tuples.
1.1168 + """
1.1169 +
1.1170 + old_by_recurrenceid, _new_periods = periods_by_recurrence(old)
1.1171 + new_by_recurrenceid, new_periods = periods_by_recurrence(new)
1.1172 +
1.1173 + combined = []
1.1174 +
1.1175 + for recurrenceid, op in old_by_recurrenceid.items():
1.1176 + np = new_by_recurrenceid.get(recurrenceid)
1.1177 +
1.1178 + # Old period has corresponding new period that is not cancelled.
1.1179 +
1.1180 + if np and not (np.cancelled and not op.cancelled):
1.1181 + combined.append((op, np))
1.1182 +
1.1183 + # No corresponding new, uncancelled period.
1.1184 +
1.1185 + else:
1.1186 + combined.append((op, None))
1.1187 +
1.1188 + # New periods without corresponding old periods are genuinely new.
1.1189 +
1.1190 + for np in new_periods:
1.1191 + combined.append((None, np))
1.1192 +
1.1193 + # Note that new periods should not have recurrence identifiers, and if
1.1194 + # imported from other events, they should have such identifiers removed.
1.1195 +
1.1196 + return combined
1.1197 +
1.1198 +def classify_periods(updated_periods):
1.1199 +
1.1200 + """
1.1201 + Using the 'updated_periods', being a list of (stored, current) periods,
1.1202 + return a tuple containing collections of new, replaced, retained, cancelled
1.1203 + and obsolete periods.
1.1204 +
1.1205 + Note that replaced and retained indicate the presence or absence of
1.1206 + differences between the original event periods and the current periods that
1.1207 + would need to be represented using separate recurrence instances, not
1.1208 + whether any editing operations have changed the periods.
1.1209 +
1.1210 + Obsolete periods are those that have been replaced but not cancelled.
1.1211 + """
1.1212 +
1.1213 + new = []
1.1214 + replaced = []
1.1215 + retained = []
1.1216 + cancelled = []
1.1217 + obsolete = []
1.1218 +
1.1219 + for sp, p in updated_periods:
1.1220 +
1.1221 + # Stored periods...
1.1222 +
1.1223 + if sp:
1.1224 +
1.1225 + # With cancelled or absent current periods.
1.1226 +
1.1227 + if not p or p.cancelled:
1.1228 + cancelled.append(sp)
1.1229 +
1.1230 + # With differing or replacement current periods.
1.1231 +
1.1232 + elif p != sp or p.replacement:
1.1233 + replaced.append(p)
1.1234 + if not p.replacement:
1.1235 + p.new_replacement = True
1.1236 + obsolete.append(sp)
1.1237 +
1.1238 + # With retained, not differing current periods.
1.1239 +
1.1240 + else:
1.1241 + retained.append(p)
1.1242 + if p.new_replacement:
1.1243 + p.new_replacement = False
1.1244 +
1.1245 + # New periods without corresponding stored periods.
1.1246 +
1.1247 + elif p:
1.1248 + new.append(p)
1.1249 +
1.1250 + return new, replaced, retained, cancelled, obsolete
1.1251 +
1.1252 +def classify_period_changes(updated_periods):
1.1253 +
1.1254 + """
1.1255 + Using the 'updated_periods', being a list of (original, current) periods,
1.1256 + return a tuple containing collections of modified, unmodified and removed
1.1257 + periods.
1.1258 + """
1.1259 +
1.1260 + modified = []
1.1261 + unmodified = []
1.1262 + removed = []
1.1263 +
1.1264 + for op, p in updated_periods:
1.1265 +
1.1266 + # Test for periods cancelled, reinstated or changed, or left unmodified
1.1267 + # during editing.
1.1268 +
1.1269 + if op:
1.1270 + if not op.cancelled and (not p or p.cancelled):
1.1271 + removed.append(op)
1.1272 + elif op.cancelled and not p.cancelled or p != op:
1.1273 + modified.append(p)
1.1274 + else:
1.1275 + unmodified.append(p)
1.1276 +
1.1277 + # New periods are always modifications.
1.1278 +
1.1279 + elif p:
1.1280 + modified.append(p)
1.1281 +
1.1282 + return modified, unmodified, removed
1.1283 +
1.1284 +def classify_period_operations(new, replaced, retained, cancelled,
1.1285 + obsolete, modified, removed,
1.1286 + is_organiser, is_shared, is_changed):
1.1287 +
1.1288 + """
1.1289 + Classify the operations for the update of an event. For updates modifying
1.1290 + shared events, return periods for descheduling and rescheduling (where these
1.1291 + operations can modify the event), and periods for exclusion and application
1.1292 + (where these operations redefine the event).
1.1293 +
1.1294 + To define the new state of the event, details of the complete set of
1.1295 + unscheduled and rescheduled periods are also provided.
1.1296 + """
1.1297 +
1.1298 + active_periods = new + replaced + retained
1.1299 +
1.1300 + # Modified replaced and retained recurrences are used for incremental
1.1301 + # updates.
1.1302 +
1.1303 + replaced_modified = select_recurrences(replaced, modified).values()
1.1304 + retained_modified = select_recurrences(retained, modified).values()
1.1305 +
1.1306 + # Unmodified replaced and retained recurrences are used in the complete
1.1307 + # event summary.
1.1308 +
1.1309 + replaced_unmodified = subtract_recurrences(replaced, modified).values()
1.1310 + retained_unmodified = subtract_recurrences(retained, modified).values()
1.1311 +
1.1312 + # Obtain the removed periods in terms of existing periods. These are used in
1.1313 + # incremental updates.
1.1314 +
1.1315 + cancelled_removed = select_recurrences(cancelled, removed).values()
1.1316 +
1.1317 + # Reinstated periods are previously-cancelled periods that are now modified
1.1318 + # periods, and they appear in updates.
1.1319 +
1.1320 + reinstated = select_recurrences(modified, cancelled).values()
1.1321 +
1.1322 + # Get cancelled periods without reinstated periods. These appear in complete
1.1323 + # event summaries.
1.1324 +
1.1325 + cancelled_unmodified = subtract_recurrences(cancelled, modified).values()
1.1326 +
1.1327 + # Cancelled periods originating from rules must be excluded since there are
1.1328 + # no explicit instances to be deleted.
1.1329 +
1.1330 + cancelled_rule = []
1.1331 + for p in cancelled_removed:
1.1332 + if p.origin == "RRULE":
1.1333 + cancelled_rule.append(p)
1.1334 +
1.1335 + # Obsolete periods (replaced by other periods) originating from rules must
1.1336 + # be excluded if no explicit instance will be used to replace them.
1.1337 +
1.1338 + obsolete_rule = []
1.1339 + for p in obsolete:
1.1340 + if p.origin == "RRULE":
1.1341 + obsolete_rule.append(p)
1.1342 +
1.1343 + # As organiser...
1.1344 +
1.1345 + if is_organiser:
1.1346 +
1.1347 + # For unshared events...
1.1348 + # All modifications redefine the event.
1.1349 +
1.1350 + # For shared events...
1.1351 + # New periods should cause the event to be redefined.
1.1352 + # Other changes should also cause event redefinition.
1.1353 + # Event redefinition should only occur if no replacement periods exist.
1.1354 + # Cancelled rule-originating periods must be excluded.
1.1355 +
1.1356 + if not is_shared or new and not replaced:
1.1357 + to_set = active_periods
1.1358 + to_exclude = list(chain(cancelled_rule, obsolete_rule))
1.1359 + to_unschedule = []
1.1360 + to_reschedule = []
1.1361 + to_add = []
1.1362 + all_unscheduled = []
1.1363 + all_rescheduled = []
1.1364 +
1.1365 + # Changed periods should be rescheduled separately.
1.1366 + # Removed periods should be cancelled separately.
1.1367 +
1.1368 + else:
1.1369 + to_set = []
1.1370 + to_exclude = []
1.1371 + to_unschedule = cancelled_removed
1.1372 + to_reschedule = list(chain(replaced_modified, retained_modified, reinstated))
1.1373 + to_add = new
1.1374 + all_unscheduled = cancelled_unmodified
1.1375 + all_rescheduled = list(chain(replaced_unmodified, to_reschedule))
1.1376 +
1.1377 + # As attendee...
1.1378 +
1.1379 + else:
1.1380 + to_unschedule = []
1.1381 + to_add = []
1.1382 +
1.1383 + # Changed periods without new or removed periods are proposed as
1.1384 + # separate changes. Parent event changes cause redefinition of the
1.1385 + # entire event.
1.1386 +
1.1387 + if not new and not removed and not is_changed:
1.1388 + to_set = []
1.1389 + to_exclude = []
1.1390 + to_reschedule = list(chain(replaced_modified, retained_modified, reinstated))
1.1391 + all_unscheduled = list(cancelled_unmodified)
1.1392 + all_rescheduled = list(chain(replaced_unmodified, to_reschedule))
1.1393 +
1.1394 + # Otherwise, the event is defined in terms of new periods and
1.1395 + # exceptions for removed periods or obsolete rule periods.
1.1396 +
1.1397 + else:
1.1398 + to_set = active_periods
1.1399 + to_exclude = list(chain(cancelled, obsolete_rule))
1.1400 + to_reschedule = []
1.1401 + all_unscheduled = []
1.1402 + all_rescheduled = []
1.1403 +
1.1404 + return to_unschedule, to_reschedule, to_add, to_exclude, to_set, all_unscheduled, all_rescheduled
1.1405 +
1.1406 +def get_period_mapping(periods):
1.1407 +
1.1408 + "Return a mapping of recurrence identifiers to the given 'periods."
1.1409 +
1.1410 + d, new = periods_by_recurrence(periods)
1.1411 + return d
1.1412 +
1.1413 +def select_recurrences(source, selected):
1.1414 +
1.1415 + "Restrict 'source' to the recurrences referenced by 'selected'."
1.1416 +
1.1417 + mapping = get_period_mapping(source)
1.1418 +
1.1419 + recurrenceids = get_recurrenceids(selected)
1.1420 + for recurrenceid in mapping.keys():
1.1421 + if not recurrenceid in recurrenceids:
1.1422 + del mapping[recurrenceid]
1.1423 + return mapping
1.1424 +
1.1425 +def subtract_recurrences(source, selected):
1.1426 +
1.1427 + "Remove from 'source' the recurrences referenced by 'selected'."
1.1428 +
1.1429 + mapping = get_period_mapping(source)
1.1430 +
1.1431 + for recurrenceid in get_recurrenceids(selected):
1.1432 + if mapping.has_key(recurrenceid):
1.1433 + del mapping[recurrenceid]
1.1434 + return mapping
1.1435 +
1.1436 +def get_recurrenceids(periods):
1.1437 +
1.1438 + "Return the recurrence identifiers employed by 'periods'."
1.1439 +
1.1440 + return map(lambda p: p.get_recurrenceid(), periods)
1.1441 +
1.1442 +
1.1443 +
1.1444 +# Attendee processing.
1.1445 +
1.1446 +def classify_attendee_changes(original, current):
1.1447 +
1.1448 + """
1.1449 + Return categories of attendees given the 'original' and 'current'
1.1450 + collections of attendees.
1.1451 + """
1.1452 +
1.1453 + new = {}
1.1454 + modified = {}
1.1455 + unmodified = {}
1.1456 +
1.1457 + # Check current attendees against the original ones.
1.1458 +
1.1459 + for attendee, attendee_attr in current.items():
1.1460 + original_attr = original.get(attendee)
1.1461 +
1.1462 + # New attendee if missing original details.
1.1463 +
1.1464 + if not original_attr:
1.1465 + new[attendee] = attendee_attr
1.1466 +
1.1467 + # Details unchanged for existing attendee.
1.1468 +
1.1469 + elif attendee_attr == original_attr:
1.1470 + unmodified[attendee] = attendee_attr
1.1471 +
1.1472 + # Details changed for existing attendee.
1.1473 +
1.1474 + else:
1.1475 + modified[attendee] = attendee_attr
1.1476 +
1.1477 + removed = {}
1.1478 +
1.1479 + # Check for removed attendees.
1.1480 +
1.1481 + for attendee, attendee_attr in original.items():
1.1482 + if not current.has_key(attendee):
1.1483 + removed[attendee] = attendee_attr
1.1484 +
1.1485 + return new, modified, unmodified, removed
1.1486 +
1.1487 +# vim: tabstop=4 expandtab shiftwidth=4