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
2.1 --- a/imipweb/data.py Wed Oct 18 01:03:42 2017 +0200
2.2 +++ b/imipweb/data.py Wed Oct 18 13:24:59 2017 +0200
2.3 @@ -1,7 +1,7 @@
2.4 #!/usr/bin/env python
2.5
2.6 """
2.7 -User interface data abstractions.
2.8 +Web user interface operations.
2.9
2.10 Copyright (C) 2014, 2015, 2017 Paul Boddie <paul@boddie.org.uk>
2.11
2.12 @@ -19,1424 +19,7 @@
2.13 this program. If not, see <http://www.gnu.org/licenses/>.
2.14 """
2.15
2.16 -from collections import OrderedDict
2.17 -from copy import copy
2.18 -from datetime import datetime, timedelta
2.19 -from imiptools.client import ClientForObject
2.20 -from imiptools.data import get_main_period
2.21 -from imiptools.dates import end_date_from_calendar, end_date_to_calendar, \
2.22 - format_datetime, get_datetime, \
2.23 - get_datetime_attributes, get_end_of_day, \
2.24 - to_date, to_utc_datetime, to_timezone
2.25 -from imiptools.period import get_overlapping_members, RecurringPeriod
2.26 -from itertools import chain
2.27 -
2.28 -# General editing abstractions.
2.29 -
2.30 -class State:
2.31 -
2.32 - "Manage editing state."
2.33 -
2.34 - def __init__(self, callables):
2.35 -
2.36 - """
2.37 - Define state variable initialisation using the given 'callables', which
2.38 - is a mapping that defines a callable for each variable name that is
2.39 - invoked when the variable is first requested.
2.40 - """
2.41 -
2.42 - self.state = {}
2.43 - self.original = {}
2.44 - self.callables = callables
2.45 -
2.46 - def get_callable(self, key):
2.47 - return self.callables.get(key, lambda: None)
2.48 -
2.49 - def ensure_original(self, key):
2.50 -
2.51 - "Ensure the original state for the given 'key'."
2.52 -
2.53 - if not self.original.has_key(key):
2.54 - self.original[key] = self.get_callable(key)()
2.55 -
2.56 - def get_original(self, key):
2.57 -
2.58 - "Return the original state for the given 'key'."
2.59 -
2.60 - self.ensure_original(key)
2.61 - return copy(self.original[key])
2.62 -
2.63 - def get(self, key, reset=False):
2.64 -
2.65 - """
2.66 - Return state for the given 'key', using the configured callable to
2.67 - compute and set the state if no state is already defined.
2.68 -
2.69 - If 'reset' is set to a true value, compute and return the state using
2.70 - the configured callable regardless of any existing state.
2.71 - """
2.72 -
2.73 - if reset or not self.state.has_key(key):
2.74 - self.state[key] = self.get_original(key)
2.75 -
2.76 - return self.state[key]
2.77 -
2.78 - def set(self, key, value):
2.79 -
2.80 - "Set the state of 'key' to 'value'."
2.81 -
2.82 - self.ensure_original(key)
2.83 - self.state[key] = value
2.84 -
2.85 - def has_changed(self, key):
2.86 -
2.87 - "Return whether 'key' has changed during editing."
2.88 -
2.89 - return self.get_original(key) != self.get(key)
2.90 -
2.91 - # Dictionary emulation methods.
2.92 -
2.93 - def __getitem__(self, key):
2.94 - return self.get(key)
2.95 -
2.96 - def __setitem__(self, key, value):
2.97 - self.set(key, value)
2.98 -
2.99 -
2.100 -
2.101 -# Object editing abstractions.
2.102 -
2.103 -class EditingClient(ClientForObject):
2.104 -
2.105 - "A simple calendar client."
2.106 -
2.107 - def __init__(self, user, messenger, store, journal, preferences_dir):
2.108 - ClientForObject.__init__(self, None, user, messenger, store,
2.109 - journal=journal,
2.110 - preferences_dir=preferences_dir)
2.111 - self.reset()
2.112 -
2.113 - # Editing state.
2.114 -
2.115 - def reset(self):
2.116 -
2.117 - "Reset the editing state."
2.118 -
2.119 - self.state = State({
2.120 - "attendees" : lambda: OrderedDict(self.obj.get_items("ATTENDEE") or []),
2.121 - "organiser" : lambda: self.obj.get_value("ORGANIZER"),
2.122 - "periods" : lambda: form_periods_from_periods(self.get_unedited_periods()),
2.123 - "suggested_attendees" : self.get_suggested_attendees,
2.124 - "suggested_periods" : self.get_suggested_periods,
2.125 - "summary" : lambda: self.obj.get_value("SUMMARY"),
2.126 - })
2.127 -
2.128 - # Access to stored and current information.
2.129 -
2.130 - def get_stored_periods(self):
2.131 -
2.132 - """
2.133 - Return the stored, unrevised, integral periods for the event, excluding
2.134 - revisions from separate recurrence instances.
2.135 - """
2.136 -
2.137 - return event_periods_from_periods(self.get_periods())
2.138 -
2.139 - def get_unedited_periods(self):
2.140 -
2.141 - """
2.142 - Return the original, unedited periods including revisions from separate
2.143 - recurrence instances.
2.144 - """
2.145 -
2.146 - return event_periods_from_updated_periods(self.get_updated_periods())
2.147 -
2.148 - def get_counters(self):
2.149 -
2.150 - "Return a counter-proposal mapping from attendees to objects."
2.151 -
2.152 - d = {}
2.153 -
2.154 - # Get counter-proposals for the specific object.
2.155 -
2.156 - recurrenceids = [self.recurrenceid]
2.157 -
2.158 - # And for all recurrences associated with a parent object.
2.159 -
2.160 - if not self.recurrenceid:
2.161 - recurrenceids += self.store.get_counter_recurrences(self.user, self.uid)
2.162 -
2.163 - # Map attendees to objects.
2.164 -
2.165 - for recurrenceid in recurrenceids:
2.166 - attendees = self.store.get_counters(self.user, self.uid, recurrenceid)
2.167 - for attendee in attendees:
2.168 - if not d.has_key(attendee):
2.169 - d[attendee] = []
2.170 - d[attendee].append(self.get_stored_object(self.uid, recurrenceid, "counters", attendee))
2.171 -
2.172 - return d
2.173 -
2.174 - def get_suggested_attendees(self):
2.175 -
2.176 - "For all counter-proposals, return suggested attendee items."
2.177 -
2.178 - existing = self.state.get("attendees")
2.179 - l = []
2.180 - for attendee, objects in self.get_counters().items():
2.181 - for obj in objects:
2.182 - for suggested, attr in obj.get_items("ATTENDEE"):
2.183 - if suggested not in existing:
2.184 - l.append((attendee, (suggested, attr)))
2.185 - return l
2.186 -
2.187 - def get_suggested_periods(self):
2.188 -
2.189 - "For all counter-proposals, return suggested event periods."
2.190 -
2.191 - existing = self.state.get("periods")
2.192 -
2.193 - # Get active periods for filtering of suggested periods.
2.194 -
2.195 - active = []
2.196 - for p in existing:
2.197 - if not p.cancelled:
2.198 - active.append(p)
2.199 -
2.200 - suggested = []
2.201 -
2.202 - for attendee, objects in self.get_counters().items():
2.203 -
2.204 - # For each object, obtain suggested periods.
2.205 -
2.206 - for obj in objects:
2.207 -
2.208 - # Obtain the current periods for the object providing the
2.209 - # suggested periods.
2.210 -
2.211 - updated = self.get_updated_periods(obj)
2.212 - suggestions = event_periods_from_updated_periods(updated)
2.213 -
2.214 - # Compare current periods with suggested periods.
2.215 -
2.216 - new = set(suggestions).difference(active)
2.217 -
2.218 - # Treat each specific recurrence as affecting only the original
2.219 - # period.
2.220 -
2.221 - if obj.get_recurrenceid():
2.222 - removed = []
2.223 - else:
2.224 - removed = set(active).difference(suggestions)
2.225 -
2.226 - # Associate new and removed periods with the attendee.
2.227 -
2.228 - for period in new:
2.229 - suggested.append((attendee, period, "add"))
2.230 -
2.231 - for period in removed:
2.232 - suggested.append((attendee, period, "remove"))
2.233 -
2.234 - return suggested
2.235 -
2.236 - # Validation methods.
2.237 -
2.238 - def get_checked_periods(self):
2.239 -
2.240 - """
2.241 - Check the edited periods and return objects representing them, setting
2.242 - the "periods" state. If errors occur, raise an exception and set the
2.243 - "errors" state.
2.244 - """
2.245 -
2.246 - self.state["period_errors"] = errors = {}
2.247 -
2.248 - # Basic validation.
2.249 -
2.250 - try:
2.251 - periods = event_periods_from_periods(self.state.get("periods"))
2.252 -
2.253 - except PeriodError, exc:
2.254 -
2.255 - # Obtain error and period index details from the exception,
2.256 - # collecting errors for each index position.
2.257 -
2.258 - for err, index in exc.args:
2.259 - l = errors.get(index)
2.260 - if not l:
2.261 - l = errors[index] = []
2.262 - l.append(err)
2.263 - raise
2.264 -
2.265 - # Check for overlapping periods.
2.266 -
2.267 - overlapping = get_overlapping_members(periods)
2.268 -
2.269 - for period in overlapping:
2.270 - for index, p in enumerate(periods):
2.271 - if period is p:
2.272 - errors[index] = ["overlap"]
2.273 -
2.274 - if overlapping:
2.275 - raise PeriodError
2.276 -
2.277 - self.state["periods"] = form_periods_from_periods(periods)
2.278 - return periods
2.279 -
2.280 - # Update result computation.
2.281 -
2.282 - def classify_attendee_changes(self):
2.283 -
2.284 - "Classify the attendees in the event."
2.285 -
2.286 - original = self.state.get_original("attendees")
2.287 - current = self.state.get("attendees")
2.288 - return classify_attendee_changes(original, current)
2.289 -
2.290 - def classify_attendee_operations(self):
2.291 -
2.292 - "Classify attendee update operations."
2.293 -
2.294 - new, modified, unmodified, removed = self.classify_attendee_changes()
2.295 -
2.296 - if self.is_organiser():
2.297 - to_invite = new
2.298 - to_cancel = removed
2.299 - to_modify = modified
2.300 - else:
2.301 - to_invite = new
2.302 - to_cancel = {}
2.303 - to_modify = modified
2.304 -
2.305 - return to_invite, to_cancel, to_modify
2.306 -
2.307 - def classify_period_changes(self):
2.308 -
2.309 - "Classify changes in the updated periods for the edited event."
2.310 -
2.311 - updated = self.combine_periods_for_comparison()
2.312 - return classify_period_changes(updated)
2.313 -
2.314 - def classify_periods(self):
2.315 -
2.316 - "Classify the updated periods for the edited event."
2.317 -
2.318 - updated = self.combine_periods()
2.319 - return classify_periods(updated)
2.320 -
2.321 - def combine_periods(self):
2.322 -
2.323 - "Combine stored and checked edited periods to make updated periods."
2.324 -
2.325 - stored = self.get_stored_periods()
2.326 - current = self.get_checked_periods()
2.327 - return combine_periods(stored, current)
2.328 -
2.329 - def combine_periods_for_comparison(self):
2.330 -
2.331 - "Combine unedited and checked edited periods to make updated periods."
2.332 -
2.333 - original = self.get_unedited_periods()
2.334 - current = self.get_checked_periods()
2.335 - return combine_periods(original, current)
2.336 -
2.337 - def classify_period_operations(self, is_changed=False):
2.338 -
2.339 - "Classify period update operations."
2.340 -
2.341 - new, replaced, retained, cancelled, obsolete = self.classify_periods()
2.342 -
2.343 - modified, unmodified, removed = self.classify_period_changes()
2.344 -
2.345 - is_organiser = self.is_organiser()
2.346 - is_shared = self.obj.is_shared()
2.347 -
2.348 - return classify_period_operations(new, replaced, retained, cancelled,
2.349 - obsolete, modified, removed,
2.350 - is_organiser, is_shared, is_changed)
2.351 -
2.352 - def properties_changed(self):
2.353 -
2.354 - "Test for changes in event details."
2.355 -
2.356 - is_changed = []
2.357 -
2.358 - for name in ["summary"]:
2.359 - if self.state.has_changed(name):
2.360 - is_changed.append(name)
2.361 -
2.362 - return is_changed
2.363 -
2.364 - def finish(self):
2.365 -
2.366 - "Finish editing, writing edited details to the object."
2.367 -
2.368 - if self.state.get("finished"):
2.369 - return
2.370 -
2.371 - is_changed = self.properties_changed()
2.372 -
2.373 - # Determine attendee modifications.
2.374 -
2.375 - self.state["attendee_operations"] = \
2.376 - to_invite, to_cancel, to_modify = \
2.377 - self.classify_attendee_operations()
2.378 -
2.379 - self.state["attendees_to_cancel"] = to_cancel
2.380 -
2.381 - # Determine period modification operations.
2.382 - # Use property changes and attendee suggestions to affect the result for
2.383 - # attendee responses.
2.384 -
2.385 - is_changed = is_changed or to_invite
2.386 -
2.387 - self.state["period_operations"] = \
2.388 - to_unschedule, to_reschedule, to_add, to_exclude, to_set, \
2.389 - all_unscheduled, all_rescheduled = \
2.390 - self.classify_period_operations(is_changed)
2.391 -
2.392 - # Determine whole event update status.
2.393 -
2.394 - is_changed = is_changed or to_set
2.395 -
2.396 - # Update event details.
2.397 -
2.398 - if self.can_edit_properties():
2.399 - self.obj.set_value("SUMMARY", self.state.get("summary"))
2.400 -
2.401 - self.update_attendees(to_invite, to_cancel, to_modify)
2.402 - self.update_event_from_periods(to_set, to_exclude)
2.403 -
2.404 - # Classify the nature of any update.
2.405 -
2.406 - if is_changed:
2.407 - self.state["changed"] = "complete"
2.408 - elif to_reschedule or to_unschedule or to_add:
2.409 - self.state["changed"] = "incremental"
2.410 -
2.411 - self.state["finished"] = self.update_event_version(is_changed)
2.412 -
2.413 - # Update preparation.
2.414 -
2.415 - def have_update(self):
2.416 -
2.417 - "Return whether an update can be prepared and sent."
2.418 -
2.419 - return not self.is_organiser() or \
2.420 - not self.obj.is_shared() or \
2.421 - self.obj.is_shared() and self.state.get("changed") and \
2.422 - self.have_other_attendees()
2.423 -
2.424 - def have_other_attendees(self):
2.425 -
2.426 - "Return whether any attendees other than the user are present."
2.427 -
2.428 - attendees = self.state.get("attendees")
2.429 - return attendees and (not attendees.has_key(self.user) or len(attendees.keys()) > 1)
2.430 -
2.431 - def prepare_cancel_message(self):
2.432 -
2.433 - "Prepare the cancel message for uninvited attendees."
2.434 -
2.435 - to_cancel = self.state.get("attendees_to_cancel")
2.436 - return self.make_cancel_message(to_cancel)
2.437 -
2.438 - def prepare_publish_message(self):
2.439 -
2.440 - "Prepare the publishing message for the updated event."
2.441 -
2.442 - to_unschedule, to_reschedule, to_add, to_exclude, to_set, \
2.443 - all_unscheduled, all_rescheduled = self.state.get("period_operations")
2.444 -
2.445 - return self.make_self_update_message(all_unscheduled, all_rescheduled, to_add)
2.446 -
2.447 - def prepare_update_message(self):
2.448 -
2.449 - "Prepare the update message for the updated event."
2.450 -
2.451 - if not self.have_update():
2.452 - return None
2.453 -
2.454 - # Obtain operation details.
2.455 -
2.456 - to_unschedule, to_reschedule, to_add, to_exclude, to_set, \
2.457 - all_unscheduled, all_rescheduled = self.state.get("period_operations")
2.458 -
2.459 - # Prepare the message.
2.460 -
2.461 - recipients = self.get_recipients()
2.462 - update_parent = self.state["changed"] == "complete"
2.463 -
2.464 - if self.is_organiser():
2.465 - return self.make_update_message(recipients, update_parent,
2.466 - to_unschedule, to_reschedule,
2.467 - all_unscheduled, all_rescheduled,
2.468 - to_add)
2.469 - else:
2.470 - return self.make_response_message(recipients, update_parent,
2.471 - all_rescheduled, to_reschedule)
2.472 -
2.473 - # Modification methods.
2.474 -
2.475 - def add_attendee(self, uri=None):
2.476 -
2.477 - "Add a blank attendee."
2.478 -
2.479 - attendees = self.state.get("attendees")
2.480 - attendees[uri or ""] = {"PARTSTAT" : "NEEDS-ACTION"}
2.481 -
2.482 - def add_suggested_attendee(self, index):
2.483 -
2.484 - "Add the suggested attendee at 'index' to the event."
2.485 -
2.486 - attendees = self.state.get("attendees")
2.487 - suggested_attendees = self.state.get("suggested_attendees")
2.488 - try:
2.489 - attendee, (suggested, attr) = suggested_attendees[index]
2.490 - self.add_attendee(suggested)
2.491 - except IndexError:
2.492 - pass
2.493 -
2.494 - def add_period(self):
2.495 -
2.496 - "Add a copy of the main period as a new recurrence."
2.497 -
2.498 - current = self.state.get("periods")
2.499 - new = get_main_period(current).copy()
2.500 - new.origin = "RDATE"
2.501 - new.replacement = False
2.502 - new.recurrenceid = False
2.503 - new.cancelled = False
2.504 - current.append(new)
2.505 -
2.506 - def apply_suggested_period(self, index):
2.507 -
2.508 - "Apply the suggested period at 'index' to the event."
2.509 -
2.510 - current = self.state.get("periods")
2.511 - suggested = self.state.get("suggested_periods")
2.512 -
2.513 - try:
2.514 - attendee, period, operation = suggested[index]
2.515 - period = form_period_from_period(period)
2.516 -
2.517 - # Cancel any removed periods.
2.518 -
2.519 - if operation == "remove":
2.520 - for index, p in enumerate(current):
2.521 - if p == period:
2.522 - self.cancel_periods([index])
2.523 - break
2.524 -
2.525 - # Add or replace any other suggestions.
2.526 -
2.527 - elif operation == "add":
2.528 -
2.529 - # Make the status of the period compatible.
2.530 -
2.531 - period.cancelled = False
2.532 - period.origin = "DTSTART-RECUR"
2.533 -
2.534 - # Either replace or add the period.
2.535 -
2.536 - recurrenceid = period.get_recurrenceid()
2.537 -
2.538 - for i, p in enumerate(current):
2.539 - if p.get_recurrenceid() == recurrenceid:
2.540 - current[i] = period
2.541 - break
2.542 -
2.543 - # Add as a new period.
2.544 -
2.545 - else:
2.546 - period.recurrenceid = None
2.547 - current.append(period)
2.548 -
2.549 - except IndexError:
2.550 - pass
2.551 -
2.552 - def cancel_periods(self, indexes, cancelled=True):
2.553 -
2.554 - """
2.555 - Set cancellation state for periods with the given 'indexes', indicating
2.556 - 'cancelled' as a true or false value. New periods will be removed if
2.557 - cancelled.
2.558 - """
2.559 -
2.560 - periods = self.state.get("periods")
2.561 - to_remove = []
2.562 - removed = 0
2.563 -
2.564 - for index in indexes:
2.565 - p = periods[index]
2.566 -
2.567 - # Make replacements from existing periods and cancel them.
2.568 -
2.569 - if p.recurrenceid:
2.570 - p.replacement = True
2.571 - p.cancelled = cancelled
2.572 -
2.573 - # Remove new periods completely.
2.574 -
2.575 - elif cancelled:
2.576 - to_remove.append(index - removed)
2.577 - removed += 1
2.578 -
2.579 - for index in to_remove:
2.580 - del periods[index]
2.581 -
2.582 - def can_edit_attendance(self):
2.583 -
2.584 - "Return whether the organiser's attendance can be edited."
2.585 -
2.586 - return self.state.get("attendees").has_key(self.user)
2.587 -
2.588 - def edit_attendance(self, partstat):
2.589 -
2.590 - "Set the 'partstat' of the current user, if attending."
2.591 -
2.592 - attendees = self.state.get("attendees")
2.593 - attr = attendees.get(self.user)
2.594 -
2.595 - # Set the attendance for the user, if attending.
2.596 -
2.597 - if attr is not None:
2.598 - new_attr = {}
2.599 - new_attr.update(attr)
2.600 - new_attr["PARTSTAT"] = partstat
2.601 - attendees[self.user] = new_attr
2.602 -
2.603 - def can_edit_attendee(self, index):
2.604 -
2.605 - """
2.606 - Return whether the attendee at 'index' can be edited, requiring either
2.607 - the organiser and an unshared event, or a new attendee.
2.608 - """
2.609 -
2.610 - attendees = self.state.get("attendees")
2.611 - attendee = attendees.keys()[index]
2.612 -
2.613 - try:
2.614 - attr = attendees[attendee]
2.615 - if self.is_organiser() and not self.obj.is_shared() or not attr:
2.616 - return (attendee, attr)
2.617 - except IndexError:
2.618 - pass
2.619 -
2.620 - return None
2.621 -
2.622 - def can_remove_attendee(self, index):
2.623 -
2.624 - """
2.625 - Return whether the attendee at 'index' can be removed, requiring either
2.626 - the organiser or a new attendee.
2.627 - """
2.628 -
2.629 - attendees = self.state.get("attendees")
2.630 - attendee = attendees.keys()[index]
2.631 -
2.632 - try:
2.633 - attr = attendees[attendee]
2.634 - if self.is_organiser() or not attr:
2.635 - return (attendee, attr)
2.636 - except IndexError:
2.637 - pass
2.638 -
2.639 - return None
2.640 -
2.641 - def remove_attendees(self, indexes):
2.642 -
2.643 - "Remove attendee at 'index'."
2.644 -
2.645 - attendees = self.state.get("attendees")
2.646 - to_remove = []
2.647 -
2.648 - for index in indexes:
2.649 - attendee_item = self.can_remove_attendee(index)
2.650 - if attendee_item:
2.651 - attendee, attr = attendee_item
2.652 - to_remove.append(attendee)
2.653 -
2.654 - for key in to_remove:
2.655 - del attendees[key]
2.656 -
2.657 - def can_edit_period(self, index):
2.658 -
2.659 - """
2.660 - Return the period at 'index' for editing or None if it cannot be edited.
2.661 - """
2.662 -
2.663 - try:
2.664 - return self.state.get("periods")[index]
2.665 - except IndexError:
2.666 - return None
2.667 -
2.668 - def can_edit_properties(self):
2.669 -
2.670 - "Return whether general event properties can be edited."
2.671 -
2.672 - return True
2.673 -
2.674 -
2.675 -
2.676 -# Period-related abstractions.
2.677 -
2.678 -class PeriodError(Exception):
2.679 - pass
2.680 -
2.681 -class EditablePeriod(RecurringPeriod):
2.682 -
2.683 - "An editable period tracking the identity of any original period."
2.684 -
2.685 - def _get_recurrenceid_item(self):
2.686 -
2.687 - # Convert any stored identifier to the current time zone.
2.688 - # NOTE: This should not be necessary, but is done for consistency with
2.689 - # NOTE: the datetime properties.
2.690 -
2.691 - dt = get_datetime(self.recurrenceid)
2.692 - dt = to_timezone(dt, self.tzid)
2.693 - return dt, get_datetime_attributes(dt)
2.694 -
2.695 - def get_recurrenceid(self):
2.696 -
2.697 - """
2.698 - Return a recurrence identity to be used to associate stored periods with
2.699 - edited periods.
2.700 - """
2.701 -
2.702 - if not self.recurrenceid:
2.703 - return RecurringPeriod.get_recurrenceid(self)
2.704 - return self.recurrenceid
2.705 -
2.706 - def get_recurrenceid_item(self):
2.707 -
2.708 - """
2.709 - Return a recurrence identifier value and datetime properties for use in
2.710 - specifying the RECURRENCE-ID property.
2.711 - """
2.712 -
2.713 - if not self.recurrenceid:
2.714 - return RecurringPeriod.get_recurrenceid_item(self)
2.715 - return self._get_recurrenceid_item()
2.716 -
2.717 -class EventPeriod(EditablePeriod):
2.718 -
2.719 - """
2.720 - A simple period plus attribute details, compatible with RecurringPeriod, and
2.721 - intended to represent information obtained from an iCalendar resource.
2.722 - """
2.723 -
2.724 - def __init__(self, start, end, tzid=None, origin=None, start_attr=None,
2.725 - end_attr=None, form_start=None, form_end=None,
2.726 - replacement=False, cancelled=False, recurrenceid=None):
2.727 -
2.728 - """
2.729 - Initialise a period with the given 'start' and 'end' datetimes.
2.730 -
2.731 - The optional 'tzid' provides time zone information, and the optional
2.732 - 'origin' indicates the kind of period this object describes.
2.733 -
2.734 - The optional 'start_attr' and 'end_attr' provide metadata for the start
2.735 - and end datetimes respectively, and 'form_start' and 'form_end' are
2.736 - values provided as textual input.
2.737 -
2.738 - The 'replacement' flag indicates whether the period is provided by a
2.739 - separate recurrence instance.
2.740 -
2.741 - The 'cancelled' flag indicates whether a separate recurrence is
2.742 - cancelled.
2.743 -
2.744 - The 'recurrenceid' describes the original identity of the period,
2.745 - regardless of whether it is separate or not.
2.746 - """
2.747 -
2.748 - EditablePeriod.__init__(self, start, end, tzid, origin, start_attr, end_attr)
2.749 - self.form_start = form_start
2.750 - self.form_end = form_end
2.751 -
2.752 - # Information about whether a separate recurrence provides this period
2.753 - # and the original period identity.
2.754 -
2.755 - self.replacement = replacement
2.756 - self.cancelled = cancelled
2.757 - self.recurrenceid = recurrenceid
2.758 -
2.759 - # Additional editing state.
2.760 -
2.761 - self.new_replacement = False
2.762 -
2.763 - def as_tuple(self):
2.764 - return self.start, self.end, self.tzid, self.origin, self.start_attr, \
2.765 - self.end_attr, self.form_start, self.form_end, self.replacement, \
2.766 - self.cancelled, self.recurrenceid
2.767 -
2.768 - def __repr__(self):
2.769 - return "EventPeriod%r" % (self.as_tuple(),)
2.770 -
2.771 - def copy(self):
2.772 - return EventPeriod(*self.as_tuple())
2.773 -
2.774 - def as_event_period(self, index=None):
2.775 - return self
2.776 -
2.777 - def get_start_item(self):
2.778 - return self.get_start(), self.get_start_attr()
2.779 -
2.780 - def get_end_item(self):
2.781 - return self.get_end(), self.get_end_attr()
2.782 -
2.783 - # Form data compatibility methods.
2.784 -
2.785 - def get_form_start(self):
2.786 - if not self.form_start:
2.787 - self.form_start = self.get_form_date(self.get_start(), self.start_attr)
2.788 - return self.form_start
2.789 -
2.790 - def get_form_end(self):
2.791 - if not self.form_end:
2.792 - self.form_end = self.get_form_date(end_date_from_calendar(self.get_end()), self.end_attr)
2.793 - return self.form_end
2.794 -
2.795 - def as_form_period(self):
2.796 - return FormPeriod(
2.797 - self.get_form_start(),
2.798 - self.get_form_end(),
2.799 - isinstance(self.end, datetime) or self.get_start() != self.get_end() - timedelta(1),
2.800 - isinstance(self.start, datetime) or isinstance(self.end, datetime),
2.801 - self.tzid,
2.802 - self.origin,
2.803 - self.replacement,
2.804 - self.cancelled,
2.805 - self.recurrenceid
2.806 - )
2.807 -
2.808 - def get_form_date(self, dt, attr=None):
2.809 - return FormDate(
2.810 - format_datetime(to_date(dt)),
2.811 - isinstance(dt, datetime) and str(dt.hour) or None,
2.812 - isinstance(dt, datetime) and str(dt.minute) or None,
2.813 - isinstance(dt, datetime) and str(dt.second) or None,
2.814 - attr and attr.get("TZID") or None,
2.815 - dt, attr
2.816 - )
2.817 -
2.818 -class FormPeriod(EditablePeriod):
2.819 -
2.820 - "A period whose information originates from a form."
2.821 -
2.822 - def __init__(self, start, end, end_enabled=True, times_enabled=True,
2.823 - tzid=None, origin=None, replacement=False, cancelled=False,
2.824 - recurrenceid=None):
2.825 - self.start = start
2.826 - self.end = end
2.827 - self.end_enabled = end_enabled
2.828 - self.times_enabled = times_enabled
2.829 - self.tzid = tzid
2.830 - self.origin = origin
2.831 - self.replacement = replacement
2.832 - self.cancelled = cancelled
2.833 - self.recurrenceid = recurrenceid
2.834 - self.new_replacement = False
2.835 -
2.836 - def as_tuple(self):
2.837 - return self.start, self.end, self.end_enabled, self.times_enabled, \
2.838 - self.tzid, self.origin, self.replacement, self.cancelled, \
2.839 - self.recurrenceid
2.840 -
2.841 - def __repr__(self):
2.842 - return "FormPeriod%r" % (self.as_tuple(),)
2.843 -
2.844 - def copy(self):
2.845 - args = (self.start.copy(), self.end.copy()) + self.as_tuple()[2:]
2.846 - return FormPeriod(*args)
2.847 -
2.848 - def as_event_period(self, index=None):
2.849 -
2.850 - """
2.851 - Return a converted version of this object as an event period suitable
2.852 - for iCalendar usage. If 'index' is indicated, include it in any error
2.853 - raised in the conversion process.
2.854 - """
2.855 -
2.856 - dtstart, dtstart_attr = self.get_start_item()
2.857 - if not dtstart:
2.858 - if index is not None:
2.859 - raise PeriodError(("dtstart", index))
2.860 - else:
2.861 - raise PeriodError("dtstart")
2.862 -
2.863 - dtend, dtend_attr = self.get_end_item()
2.864 - if not dtend:
2.865 - if index is not None:
2.866 - raise PeriodError(("dtend", index))
2.867 - else:
2.868 - raise PeriodError("dtend")
2.869 -
2.870 - if dtstart > dtend:
2.871 - if index is not None:
2.872 - raise PeriodError(("dtstart", index), ("dtend", index))
2.873 - else:
2.874 - raise PeriodError("dtstart", "dtend")
2.875 -
2.876 - return EventPeriod(dtstart, end_date_to_calendar(dtend), self.tzid,
2.877 - self.origin, dtstart_attr, dtend_attr,
2.878 - self.start, self.end, self.replacement,
2.879 - self.cancelled, self.recurrenceid)
2.880 -
2.881 - # Period data methods.
2.882 -
2.883 - def get_start(self):
2.884 - return self.start and self.start.as_datetime(self.times_enabled) or None
2.885 -
2.886 - def get_end(self):
2.887 -
2.888 - # Handle specified end datetimes.
2.889 -
2.890 - if self.end_enabled:
2.891 - dtend = self.end.as_datetime(self.times_enabled)
2.892 - if not dtend:
2.893 - return None
2.894 -
2.895 - # Handle same day times.
2.896 -
2.897 - elif self.times_enabled:
2.898 - formdate = FormDate(self.start.date, self.end.hour, self.end.minute, self.end.second, self.end.tzid)
2.899 - dtend = formdate.as_datetime(self.times_enabled)
2.900 - if not dtend:
2.901 - return None
2.902 -
2.903 - # Otherwise, treat the end date as the start date. Datetimes are
2.904 - # handled by making the event occupy the rest of the day.
2.905 -
2.906 - else:
2.907 - dtstart, dtstart_attr = self.get_start_item()
2.908 - if dtstart:
2.909 - if isinstance(dtstart, datetime):
2.910 - dtend = get_end_of_day(dtstart, dtstart_attr["TZID"])
2.911 - else:
2.912 - dtend = dtstart
2.913 - else:
2.914 - return None
2.915 -
2.916 - return dtend
2.917 -
2.918 - def get_start_attr(self):
2.919 - return self.start and self.start.get_attributes(self.times_enabled) or {}
2.920 -
2.921 - def get_end_attr(self):
2.922 - return self.end and self.end.get_attributes(self.times_enabled) or {}
2.923 -
2.924 - # Form data methods.
2.925 -
2.926 - def get_form_start(self):
2.927 - return self.start
2.928 -
2.929 - def get_form_end(self):
2.930 - return self.end
2.931 -
2.932 - def as_form_period(self):
2.933 - return self
2.934 -
2.935 -class FormDate:
2.936 -
2.937 - "Date information originating from form information."
2.938 -
2.939 - def __init__(self, date=None, hour=None, minute=None, second=None, tzid=None, dt=None, attr=None):
2.940 - self.date = date
2.941 - self.hour = hour
2.942 - self.minute = minute
2.943 - self.second = second
2.944 - self.tzid = tzid
2.945 - self.dt = dt
2.946 - self.attr = attr
2.947 -
2.948 - def as_tuple(self):
2.949 - return self.date, self.hour, self.minute, self.second, self.tzid, self.dt, self.attr
2.950 -
2.951 - def copy(self):
2.952 - return FormDate(*self.as_tuple())
2.953 -
2.954 - def reset(self):
2.955 - self.dt = None
2.956 -
2.957 - def __repr__(self):
2.958 - return "FormDate%r" % (self.as_tuple(),)
2.959 -
2.960 - def get_component(self, value):
2.961 - return (value or "").rjust(2, "0")[:2]
2.962 -
2.963 - def get_hour(self):
2.964 - return self.get_component(self.hour)
2.965 -
2.966 - def get_minute(self):
2.967 - return self.get_component(self.minute)
2.968 -
2.969 - def get_second(self):
2.970 - return self.get_component(self.second)
2.971 -
2.972 - def get_date_string(self):
2.973 - return self.date or ""
2.974 -
2.975 - def get_datetime_string(self):
2.976 - if not self.date:
2.977 - return ""
2.978 -
2.979 - hour = self.hour; minute = self.minute; second = self.second
2.980 -
2.981 - if hour or minute or second:
2.982 - time = "T%s%s%s" % tuple(map(self.get_component, (hour, minute, second)))
2.983 - else:
2.984 - time = ""
2.985 -
2.986 - return "%s%s" % (self.date, time)
2.987 -
2.988 - def get_tzid(self):
2.989 - return self.tzid
2.990 -
2.991 - def as_datetime(self, with_time=True):
2.992 -
2.993 - """
2.994 - Return a datetime for this object if one is provided or can be produced.
2.995 - """
2.996 -
2.997 - # Return any original datetime details.
2.998 -
2.999 - if self.dt:
2.1000 - return self.dt
2.1001 -
2.1002 - # Otherwise, construct a datetime.
2.1003 -
2.1004 - s, attr = self.as_datetime_item(with_time)
2.1005 - if not s:
2.1006 - return None
2.1007 -
2.1008 - # An erroneous datetime will yield None as result.
2.1009 -
2.1010 - try:
2.1011 - return get_datetime(s, attr)
2.1012 - except ValueError:
2.1013 - return None
2.1014 -
2.1015 - def as_datetime_item(self, with_time=True):
2.1016 -
2.1017 - """
2.1018 - Return a (datetime string, attr) tuple for the datetime information
2.1019 - provided by this object, where both tuple elements will be None if no
2.1020 - suitable date or datetime information exists.
2.1021 - """
2.1022 -
2.1023 - s = None
2.1024 - if with_time:
2.1025 - s = self.get_datetime_string()
2.1026 - attr = self.get_attributes(True)
2.1027 - if not s:
2.1028 - s = self.get_date_string()
2.1029 - attr = self.get_attributes(False)
2.1030 - if not s:
2.1031 - return None, None
2.1032 - return s, attr
2.1033 -
2.1034 - def get_attributes(self, with_time=True):
2.1035 -
2.1036 - "Return attributes for the date or datetime represented by this object."
2.1037 -
2.1038 - if with_time:
2.1039 - return {"TZID" : self.get_tzid(), "VALUE" : "DATE-TIME"}
2.1040 - else:
2.1041 - return {"VALUE" : "DATE"}
2.1042 -
2.1043 -def event_period_from_period(period, index=None):
2.1044 -
2.1045 - """
2.1046 - Convert a 'period' to one suitable for use in an iCalendar representation.
2.1047 - In an "event period" representation, the end day of any date-level event is
2.1048 - encoded as the "day after" the last day actually involved in the event.
2.1049 - """
2.1050 -
2.1051 - if isinstance(period, EventPeriod):
2.1052 - return period
2.1053 - elif isinstance(period, FormPeriod):
2.1054 - return period.as_event_period(index)
2.1055 - else:
2.1056 - dtstart, dtstart_attr = period.get_start_item()
2.1057 - dtend, dtend_attr = period.get_end_item()
2.1058 -
2.1059 - if not isinstance(period, RecurringPeriod):
2.1060 - dtend = end_date_to_calendar(dtend)
2.1061 -
2.1062 - return EventPeriod(dtstart, dtend, period.tzid, period.origin,
2.1063 - dtstart_attr, dtend_attr,
2.1064 - recurrenceid=format_datetime(to_utc_datetime(dtstart)))
2.1065 -
2.1066 -def event_periods_from_periods(periods):
2.1067 - return map(event_period_from_period, periods, range(0, len(periods)))
2.1068 -
2.1069 -def form_period_from_period(period):
2.1070 -
2.1071 - """
2.1072 - Convert a 'period' into a representation usable in a user-editable form.
2.1073 - In a "form period" representation, the end day of any date-level event is
2.1074 - presented in a "natural" form, not the iCalendar "day after" form.
2.1075 - """
2.1076 -
2.1077 - if isinstance(period, EventPeriod):
2.1078 - return period.as_form_period()
2.1079 - elif isinstance(period, FormPeriod):
2.1080 - return period
2.1081 - else:
2.1082 - return event_period_from_period(period).as_form_period()
2.1083 -
2.1084 -def form_periods_from_periods(periods):
2.1085 - return map(form_period_from_period, periods)
2.1086 -
2.1087 -
2.1088 -
2.1089 -# Event period processing.
2.1090 -
2.1091 -def periods_from_updated_periods(updated_periods, fn):
2.1092 -
2.1093 - """
2.1094 - Return periods from the given 'updated_periods' created using 'fn', setting
2.1095 - replacement, cancelled and recurrence identifier details.
2.1096 -
2.1097 - This function should be used to produce editing-related periods from the
2.1098 - general updated periods provided by the client abstractions.
2.1099 - """
2.1100 -
2.1101 - periods = []
2.1102 -
2.1103 - for sp, p in updated_periods:
2.1104 -
2.1105 - # Stored periods with corresponding current periods.
2.1106 -
2.1107 - if p:
2.1108 - period = fn(p)
2.1109 -
2.1110 - # Replacements are identified by comparing object identities, since
2.1111 - # a replacement will not be provided by the same object.
2.1112 -
2.1113 - if sp is not p:
2.1114 - period.replacement = True
2.1115 -
2.1116 - # Stored periods without corresponding current periods.
2.1117 -
2.1118 - else:
2.1119 - period = fn(sp)
2.1120 - period.replacement = True
2.1121 - period.cancelled = True
2.1122 -
2.1123 - # Replace the recurrence identifier with that of the original period.
2.1124 -
2.1125 - period.recurrenceid = sp.get_recurrenceid()
2.1126 - periods.append(period)
2.1127 -
2.1128 - return periods
2.1129 -
2.1130 -def event_periods_from_updated_periods(updated_periods):
2.1131 - return periods_from_updated_periods(updated_periods, event_period_from_period)
2.1132 -
2.1133 -def form_periods_from_updated_periods(updated_periods):
2.1134 - return periods_from_updated_periods(updated_periods, form_period_from_period)
2.1135 -
2.1136 -def periods_by_recurrence(periods):
2.1137 -
2.1138 - """
2.1139 - Return a mapping from recurrence identifier to period for 'periods' along
2.1140 - with a collection of unmapped periods.
2.1141 - """
2.1142 -
2.1143 - d = {}
2.1144 - new = []
2.1145 -
2.1146 - for p in periods:
2.1147 - if not p.recurrenceid:
2.1148 - new.append(p)
2.1149 - else:
2.1150 - d[p.recurrenceid] = p
2.1151 -
2.1152 - return d, new
2.1153 -
2.1154 -def combine_periods(old, new):
2.1155 -
2.1156 - """
2.1157 - Combine 'old' and 'new' periods for comparison, making a list of (old, new)
2.1158 - updated period tuples.
2.1159 - """
2.1160 -
2.1161 - old_by_recurrenceid, _new_periods = periods_by_recurrence(old)
2.1162 - new_by_recurrenceid, new_periods = periods_by_recurrence(new)
2.1163 -
2.1164 - combined = []
2.1165 -
2.1166 - for recurrenceid, op in old_by_recurrenceid.items():
2.1167 - np = new_by_recurrenceid.get(recurrenceid)
2.1168 -
2.1169 - # Old period has corresponding new period that is not cancelled.
2.1170 -
2.1171 - if np and not (np.cancelled and not op.cancelled):
2.1172 - combined.append((op, np))
2.1173 -
2.1174 - # No corresponding new, uncancelled period.
2.1175 -
2.1176 - else:
2.1177 - combined.append((op, None))
2.1178 -
2.1179 - # New periods without corresponding old periods are genuinely new.
2.1180 -
2.1181 - for np in new_periods:
2.1182 - combined.append((None, np))
2.1183 -
2.1184 - # Note that new periods should not have recurrence identifiers, and if
2.1185 - # imported from other events, they should have such identifiers removed.
2.1186 -
2.1187 - return combined
2.1188 -
2.1189 -def classify_periods(updated_periods):
2.1190 -
2.1191 - """
2.1192 - Using the 'updated_periods', being a list of (stored, current) periods,
2.1193 - return a tuple containing collections of new, replaced, retained, cancelled
2.1194 - and obsolete periods.
2.1195 -
2.1196 - Note that replaced and retained indicate the presence or absence of
2.1197 - differences between the original event periods and the current periods that
2.1198 - would need to be represented using separate recurrence instances, not
2.1199 - whether any editing operations have changed the periods.
2.1200 -
2.1201 - Obsolete periods are those that have been replaced but not cancelled.
2.1202 - """
2.1203 -
2.1204 - new = []
2.1205 - replaced = []
2.1206 - retained = []
2.1207 - cancelled = []
2.1208 - obsolete = []
2.1209 -
2.1210 - for sp, p in updated_periods:
2.1211 -
2.1212 - # Stored periods...
2.1213 -
2.1214 - if sp:
2.1215 -
2.1216 - # With cancelled or absent current periods.
2.1217 -
2.1218 - if not p or p.cancelled:
2.1219 - cancelled.append(sp)
2.1220 -
2.1221 - # With differing or replacement current periods.
2.1222 -
2.1223 - elif p != sp or p.replacement:
2.1224 - replaced.append(p)
2.1225 - if not p.replacement:
2.1226 - p.new_replacement = True
2.1227 - obsolete.append(sp)
2.1228 -
2.1229 - # With retained, not differing current periods.
2.1230 -
2.1231 - else:
2.1232 - retained.append(p)
2.1233 - if p.new_replacement:
2.1234 - p.new_replacement = False
2.1235 -
2.1236 - # New periods without corresponding stored periods.
2.1237 -
2.1238 - elif p:
2.1239 - new.append(p)
2.1240 -
2.1241 - return new, replaced, retained, cancelled, obsolete
2.1242 -
2.1243 -def classify_period_changes(updated_periods):
2.1244 -
2.1245 - """
2.1246 - Using the 'updated_periods', being a list of (original, current) periods,
2.1247 - return a tuple containing collections of modified, unmodified and removed
2.1248 - periods.
2.1249 - """
2.1250 -
2.1251 - modified = []
2.1252 - unmodified = []
2.1253 - removed = []
2.1254 -
2.1255 - for op, p in updated_periods:
2.1256 -
2.1257 - # Test for periods cancelled, reinstated or changed, or left unmodified
2.1258 - # during editing.
2.1259 -
2.1260 - if op:
2.1261 - if not op.cancelled and (not p or p.cancelled):
2.1262 - removed.append(op)
2.1263 - elif op.cancelled and not p.cancelled or p != op:
2.1264 - modified.append(p)
2.1265 - else:
2.1266 - unmodified.append(p)
2.1267 -
2.1268 - # New periods are always modifications.
2.1269 -
2.1270 - elif p:
2.1271 - modified.append(p)
2.1272 -
2.1273 - return modified, unmodified, removed
2.1274 -
2.1275 -def classify_period_operations(new, replaced, retained, cancelled,
2.1276 - obsolete, modified, removed,
2.1277 - is_organiser, is_shared, is_changed):
2.1278 -
2.1279 - """
2.1280 - Classify the operations for the update of an event. For updates modifying
2.1281 - shared events, return periods for descheduling and rescheduling (where these
2.1282 - operations can modify the event), and periods for exclusion and application
2.1283 - (where these operations redefine the event).
2.1284 -
2.1285 - To define the new state of the event, details of the complete set of
2.1286 - unscheduled and rescheduled periods are also provided.
2.1287 - """
2.1288 -
2.1289 - active_periods = new + replaced + retained
2.1290 -
2.1291 - # Modified replaced and retained recurrences are used for incremental
2.1292 - # updates.
2.1293 -
2.1294 - replaced_modified = select_recurrences(replaced, modified).values()
2.1295 - retained_modified = select_recurrences(retained, modified).values()
2.1296 -
2.1297 - # Unmodified replaced and retained recurrences are used in the complete
2.1298 - # event summary.
2.1299 -
2.1300 - replaced_unmodified = subtract_recurrences(replaced, modified).values()
2.1301 - retained_unmodified = subtract_recurrences(retained, modified).values()
2.1302 -
2.1303 - # Obtain the removed periods in terms of existing periods. These are used in
2.1304 - # incremental updates.
2.1305 -
2.1306 - cancelled_removed = select_recurrences(cancelled, removed).values()
2.1307 -
2.1308 - # Reinstated periods are previously-cancelled periods that are now modified
2.1309 - # periods, and they appear in updates.
2.1310 -
2.1311 - reinstated = select_recurrences(modified, cancelled).values()
2.1312 -
2.1313 - # Get cancelled periods without reinstated periods. These appear in complete
2.1314 - # event summaries.
2.1315 -
2.1316 - cancelled_unmodified = subtract_recurrences(cancelled, modified).values()
2.1317 -
2.1318 - # Cancelled periods originating from rules must be excluded since there are
2.1319 - # no explicit instances to be deleted.
2.1320 -
2.1321 - cancelled_rule = []
2.1322 - for p in cancelled_removed:
2.1323 - if p.origin == "RRULE":
2.1324 - cancelled_rule.append(p)
2.1325 -
2.1326 - # Obsolete periods (replaced by other periods) originating from rules must
2.1327 - # be excluded if no explicit instance will be used to replace them.
2.1328 -
2.1329 - obsolete_rule = []
2.1330 - for p in obsolete:
2.1331 - if p.origin == "RRULE":
2.1332 - obsolete_rule.append(p)
2.1333 -
2.1334 - # As organiser...
2.1335 -
2.1336 - if is_organiser:
2.1337 -
2.1338 - # For unshared events...
2.1339 - # All modifications redefine the event.
2.1340 -
2.1341 - # For shared events...
2.1342 - # New periods should cause the event to be redefined.
2.1343 - # Other changes should also cause event redefinition.
2.1344 - # Event redefinition should only occur if no replacement periods exist.
2.1345 - # Cancelled rule-originating periods must be excluded.
2.1346 -
2.1347 - if not is_shared or new and not replaced:
2.1348 - to_set = active_periods
2.1349 - to_exclude = list(chain(cancelled_rule, obsolete_rule))
2.1350 - to_unschedule = []
2.1351 - to_reschedule = []
2.1352 - to_add = []
2.1353 - all_unscheduled = []
2.1354 - all_rescheduled = []
2.1355 -
2.1356 - # Changed periods should be rescheduled separately.
2.1357 - # Removed periods should be cancelled separately.
2.1358 -
2.1359 - else:
2.1360 - to_set = []
2.1361 - to_exclude = []
2.1362 - to_unschedule = cancelled_removed
2.1363 - to_reschedule = list(chain(replaced_modified, retained_modified, reinstated))
2.1364 - to_add = new
2.1365 - all_unscheduled = cancelled_unmodified
2.1366 - all_rescheduled = list(chain(replaced_unmodified, to_reschedule))
2.1367 -
2.1368 - # As attendee...
2.1369 -
2.1370 - else:
2.1371 - to_unschedule = []
2.1372 - to_add = []
2.1373 -
2.1374 - # Changed periods without new or removed periods are proposed as
2.1375 - # separate changes. Parent event changes cause redefinition of the
2.1376 - # entire event.
2.1377 -
2.1378 - if not new and not removed and not is_changed:
2.1379 - to_set = []
2.1380 - to_exclude = []
2.1381 - to_reschedule = list(chain(replaced_modified, retained_modified, reinstated))
2.1382 - all_unscheduled = list(cancelled_unmodified)
2.1383 - all_rescheduled = list(chain(replaced_unmodified, to_reschedule))
2.1384 -
2.1385 - # Otherwise, the event is defined in terms of new periods and
2.1386 - # exceptions for removed periods or obsolete rule periods.
2.1387 -
2.1388 - else:
2.1389 - to_set = active_periods
2.1390 - to_exclude = list(chain(cancelled, obsolete_rule))
2.1391 - to_reschedule = []
2.1392 - all_unscheduled = []
2.1393 - all_rescheduled = []
2.1394 -
2.1395 - return to_unschedule, to_reschedule, to_add, to_exclude, to_set, all_unscheduled, all_rescheduled
2.1396 -
2.1397 -def get_period_mapping(periods):
2.1398 -
2.1399 - "Return a mapping of recurrence identifiers to the given 'periods."
2.1400 -
2.1401 - d, new = periods_by_recurrence(periods)
2.1402 - return d
2.1403 -
2.1404 -def select_recurrences(source, selected):
2.1405 -
2.1406 - "Restrict 'source' to the recurrences referenced by 'selected'."
2.1407 -
2.1408 - mapping = get_period_mapping(source)
2.1409 -
2.1410 - recurrenceids = get_recurrenceids(selected)
2.1411 - for recurrenceid in mapping.keys():
2.1412 - if not recurrenceid in recurrenceids:
2.1413 - del mapping[recurrenceid]
2.1414 - return mapping
2.1415 -
2.1416 -def subtract_recurrences(source, selected):
2.1417 -
2.1418 - "Remove from 'source' the recurrences referenced by 'selected'."
2.1419 -
2.1420 - mapping = get_period_mapping(source)
2.1421 -
2.1422 - for recurrenceid in get_recurrenceids(selected):
2.1423 - if mapping.has_key(recurrenceid):
2.1424 - del mapping[recurrenceid]
2.1425 - return mapping
2.1426 -
2.1427 -def get_recurrenceids(periods):
2.1428 -
2.1429 - "Return the recurrence identifiers employed by 'periods'."
2.1430 -
2.1431 - return map(lambda p: p.get_recurrenceid(), periods)
2.1432 -
2.1433 -
2.1434 +from imiptools.editing import FormPeriod
2.1435
2.1436 # Form field extraction and serialisation.
2.1437
2.1438 @@ -1673,51 +256,6 @@
2.1439
2.1440
2.1441
2.1442 -# Attendee processing.
2.1443 -
2.1444 -def classify_attendee_changes(original, current):
2.1445 -
2.1446 - """
2.1447 - Return categories of attendees given the 'original' and 'current'
2.1448 - collections of attendees.
2.1449 - """
2.1450 -
2.1451 - new = {}
2.1452 - modified = {}
2.1453 - unmodified = {}
2.1454 -
2.1455 - # Check current attendees against the original ones.
2.1456 -
2.1457 - for attendee, attendee_attr in current.items():
2.1458 - original_attr = original.get(attendee)
2.1459 -
2.1460 - # New attendee if missing original details.
2.1461 -
2.1462 - if not original_attr:
2.1463 - new[attendee] = attendee_attr
2.1464 -
2.1465 - # Details unchanged for existing attendee.
2.1466 -
2.1467 - elif attendee_attr == original_attr:
2.1468 - unmodified[attendee] = attendee_attr
2.1469 -
2.1470 - # Details changed for existing attendee.
2.1471 -
2.1472 - else:
2.1473 - modified[attendee] = attendee_attr
2.1474 -
2.1475 - removed = {}
2.1476 -
2.1477 - # Check for removed attendees.
2.1478 -
2.1479 - for attendee, attendee_attr in original.items():
2.1480 - if not current.has_key(attendee):
2.1481 - removed[attendee] = attendee_attr
2.1482 -
2.1483 - return new, modified, unmodified, removed
2.1484 -
2.1485 -
2.1486 -
2.1487 # Utilities.
2.1488
2.1489 def filter_duplicates(l):