1.1 --- a/imiptools/freebusy.py Fri May 26 16:52:25 2017 +0200
1.2 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000
1.3 @@ -1,1175 +0,0 @@
1.4 -#!/usr/bin/env python
1.5 -
1.6 -"""
1.7 -Managing free/busy periods.
1.8 -
1.9 -Copyright (C) 2014, 2015, 2016, 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 bisect import bisect_left, bisect_right
1.26 -from imiptools.dates import format_datetime
1.27 -from imiptools.period import get_overlapping, Period, PeriodBase
1.28 -from imiptools.sql import DatabaseOperations
1.29 -
1.30 -try:
1.31 - from cStringIO import StringIO
1.32 -except ImportError:
1.33 - from StringIO import StringIO
1.34 -
1.35 -def from_string(s, encoding):
1.36 -
1.37 - "Interpret 's' using 'encoding', preserving None."
1.38 -
1.39 - if s:
1.40 - return unicode(s, encoding)
1.41 - else:
1.42 - return s
1.43 -
1.44 -def to_string(s, encoding):
1.45 -
1.46 - "Encode 's' using 'encoding', preserving None."
1.47 -
1.48 - if s:
1.49 - return s.encode(encoding)
1.50 - else:
1.51 - return s
1.52 -
1.53 -def to_copy_string(s, encoding):
1.54 -
1.55 - """
1.56 - Encode 's' using 'encoding' as a string suitable for use in tabular data
1.57 - acceptable to the PostgreSQL COPY command with \N as null.
1.58 - """
1.59 -
1.60 - s = to_string(s, encoding)
1.61 - return s is None and "\\N" or s
1.62 -
1.63 -def to_copy_file(records):
1.64 -
1.65 - """
1.66 - Encode the given 'records' and store them in a file-like object for use with
1.67 - a tabular import mechanism. Return the file-like object.
1.68 - """
1.69 -
1.70 - io = StringIO()
1.71 - for values in records:
1.72 - l = []
1.73 - for v in values:
1.74 - l.append(to_copy_string(v, "utf-8"))
1.75 - io.write("\t".join(l))
1.76 - io.write("\n")
1.77 - io.seek(0)
1.78 - return io
1.79 -
1.80 -def quote_column(column):
1.81 -
1.82 - "Quote 'column' using the SQL keyword quoting notation."
1.83 -
1.84 - return '"%s"' % column
1.85 -
1.86 -class FreeBusyPeriod(PeriodBase):
1.87 -
1.88 - "A free/busy record abstraction."
1.89 -
1.90 - def __init__(self, start, end, uid=None, transp=None, recurrenceid=None,
1.91 - summary=None, organiser=None):
1.92 -
1.93 - """
1.94 - Initialise a free/busy period with the given 'start' and 'end' points,
1.95 - plus any 'uid', 'transp', 'recurrenceid', 'summary' and 'organiser'
1.96 - details.
1.97 - """
1.98 -
1.99 - PeriodBase.__init__(self, start, end)
1.100 - self.uid = uid
1.101 - self.transp = transp or None
1.102 - self.recurrenceid = recurrenceid or None
1.103 - self.summary = summary or None
1.104 - self.organiser = organiser or None
1.105 -
1.106 - def as_tuple(self, strings_only=False, string_datetimes=False):
1.107 -
1.108 - """
1.109 - Return the initialisation parameter tuple, converting datetimes and
1.110 - false value parameters to strings if 'strings_only' is set to a true
1.111 - value. Otherwise, if 'string_datetimes' is set to a true value, only the
1.112 - datetime values are converted to strings.
1.113 - """
1.114 -
1.115 - null = lambda x: (strings_only and [""] or [x])[0]
1.116 - return (
1.117 - (strings_only or string_datetimes) and format_datetime(self.get_start_point()) or self.start,
1.118 - (strings_only or string_datetimes) and format_datetime(self.get_end_point()) or self.end,
1.119 - self.uid or null(self.uid),
1.120 - self.transp or strings_only and "OPAQUE" or None,
1.121 - self.recurrenceid or null(self.recurrenceid),
1.122 - self.summary or null(self.summary),
1.123 - self.organiser or null(self.organiser)
1.124 - )
1.125 -
1.126 - def __cmp__(self, other):
1.127 -
1.128 - """
1.129 - Compare this object to 'other', employing the uid if the periods
1.130 - involved are the same.
1.131 - """
1.132 -
1.133 - result = PeriodBase.__cmp__(self, other)
1.134 - if result == 0 and isinstance(other, FreeBusyPeriod):
1.135 - return cmp((self.uid, self.recurrenceid), (other.uid, other.recurrenceid))
1.136 - else:
1.137 - return result
1.138 -
1.139 - def get_key(self):
1.140 - return self.uid, self.recurrenceid, self.get_start()
1.141 -
1.142 - def __repr__(self):
1.143 - return "FreeBusyPeriod%r" % (self.as_tuple(),)
1.144 -
1.145 - def get_tzid(self):
1.146 - return "UTC"
1.147 -
1.148 - # Period and event recurrence logic.
1.149 -
1.150 - def is_replaced(self, recurrences):
1.151 -
1.152 - """
1.153 - Return whether this period refers to one of the 'recurrences'.
1.154 - The 'recurrences' must be UTC datetimes corresponding to the start of
1.155 - the period described by a recurrence.
1.156 - """
1.157 -
1.158 - for recurrence in recurrences:
1.159 - if self.is_affected(recurrence):
1.160 - return True
1.161 - return False
1.162 -
1.163 - def is_affected(self, recurrence):
1.164 -
1.165 - """
1.166 - Return whether this period refers to 'recurrence'. The 'recurrence' must
1.167 - be a UTC datetime corresponding to the start of the period described by
1.168 - a recurrence.
1.169 - """
1.170 -
1.171 - return recurrence and self.get_start_point() == recurrence
1.172 -
1.173 - # Value correction methods.
1.174 -
1.175 - def make_corrected(self, start, end):
1.176 - return self.__class__(start, end)
1.177 -
1.178 -class FreeBusyOfferPeriod(FreeBusyPeriod):
1.179 -
1.180 - "A free/busy record abstraction for an offer period."
1.181 -
1.182 - def __init__(self, start, end, uid=None, transp=None, recurrenceid=None,
1.183 - summary=None, organiser=None, expires=None):
1.184 -
1.185 - """
1.186 - Initialise a free/busy period with the given 'start' and 'end' points,
1.187 - plus any 'uid', 'transp', 'recurrenceid', 'summary' and 'organiser'
1.188 - details.
1.189 -
1.190 - An additional 'expires' parameter can be used to indicate an expiry
1.191 - datetime in conjunction with free/busy offers made when countering
1.192 - event proposals.
1.193 - """
1.194 -
1.195 - FreeBusyPeriod.__init__(self, start, end, uid, transp, recurrenceid,
1.196 - summary, organiser)
1.197 - self.expires = expires or None
1.198 -
1.199 - def as_tuple(self, strings_only=False, string_datetimes=False):
1.200 -
1.201 - """
1.202 - Return the initialisation parameter tuple, converting datetimes and
1.203 - false value parameters to strings if 'strings_only' is set to a true
1.204 - value. Otherwise, if 'string_datetimes' is set to a true value, only the
1.205 - datetime values are converted to strings.
1.206 - """
1.207 -
1.208 - null = lambda x: (strings_only and [""] or [x])[0]
1.209 - return FreeBusyPeriod.as_tuple(self, strings_only, string_datetimes) + (
1.210 - self.expires or null(self.expires),)
1.211 -
1.212 - def __repr__(self):
1.213 - return "FreeBusyOfferPeriod%r" % (self.as_tuple(),)
1.214 -
1.215 -class FreeBusyGroupPeriod(FreeBusyPeriod):
1.216 -
1.217 - "A free/busy record abstraction for a quota group period."
1.218 -
1.219 - def __init__(self, start, end, uid=None, transp=None, recurrenceid=None,
1.220 - summary=None, organiser=None, attendee=None):
1.221 -
1.222 - """
1.223 - Initialise a free/busy period with the given 'start' and 'end' points,
1.224 - plus any 'uid', 'transp', 'recurrenceid', 'summary' and 'organiser'
1.225 - details.
1.226 -
1.227 - An additional 'attendee' parameter can be used to indicate the identity
1.228 - of the attendee recording the period.
1.229 - """
1.230 -
1.231 - FreeBusyPeriod.__init__(self, start, end, uid, transp, recurrenceid,
1.232 - summary, organiser)
1.233 - self.attendee = attendee or None
1.234 -
1.235 - def as_tuple(self, strings_only=False, string_datetimes=False):
1.236 -
1.237 - """
1.238 - Return the initialisation parameter tuple, converting datetimes and
1.239 - false value parameters to strings if 'strings_only' is set to a true
1.240 - value. Otherwise, if 'string_datetimes' is set to a true value, only the
1.241 - datetime values are converted to strings.
1.242 - """
1.243 -
1.244 - null = lambda x: (strings_only and [""] or [x])[0]
1.245 - return FreeBusyPeriod.as_tuple(self, strings_only, string_datetimes) + (
1.246 - self.attendee or null(self.attendee),)
1.247 -
1.248 - def __cmp__(self, other):
1.249 -
1.250 - """
1.251 - Compare this object to 'other', employing the uid if the periods
1.252 - involved are the same.
1.253 - """
1.254 -
1.255 - result = FreeBusyPeriod.__cmp__(self, other)
1.256 - if isinstance(other, FreeBusyGroupPeriod) and result == 0:
1.257 - return cmp(self.attendee, other.attendee)
1.258 - else:
1.259 - return result
1.260 -
1.261 - def __repr__(self):
1.262 - return "FreeBusyGroupPeriod%r" % (self.as_tuple(),)
1.263 -
1.264 -class FreeBusyCollectionBase:
1.265 -
1.266 - "Common operations on free/busy period collections."
1.267 -
1.268 - period_columns = [
1.269 - "start", "end", "object_uid", "transp", "object_recurrenceid",
1.270 - "summary", "organiser"
1.271 - ]
1.272 -
1.273 - period_class = FreeBusyPeriod
1.274 -
1.275 - def __init__(self, mutable=True):
1.276 - self.mutable = mutable
1.277 -
1.278 - def _check_mutable(self):
1.279 - if not self.mutable:
1.280 - raise TypeError, "Cannot mutate this collection."
1.281 -
1.282 - def copy(self):
1.283 -
1.284 - "Make an independent mutable copy of the collection."
1.285 -
1.286 - return FreeBusyCollection(list(self), True)
1.287 -
1.288 - def make_period(self, t):
1.289 -
1.290 - """
1.291 - Make a period using the given tuple of arguments and the collection's
1.292 - column details.
1.293 - """
1.294 -
1.295 - args = []
1.296 - for arg, column in zip(t, self.period_columns):
1.297 - args.append(from_string(arg, "utf-8"))
1.298 - return self.period_class(*args)
1.299 -
1.300 - def make_tuple(self, t):
1.301 -
1.302 - """
1.303 - Return a tuple from the given tuple 't' conforming to the collection's
1.304 - column details.
1.305 - """
1.306 -
1.307 - args = []
1.308 - for arg, column in zip(t, self.period_columns):
1.309 - args.append(arg)
1.310 - return tuple(args)
1.311 -
1.312 - # List emulation methods.
1.313 -
1.314 - def __iadd__(self, periods):
1.315 - self.insert_periods(periods)
1.316 - return self
1.317 -
1.318 - def append(self, period):
1.319 - self.insert_period(period)
1.320 -
1.321 - # Operations.
1.322 -
1.323 - def insert_periods(self, periods):
1.324 -
1.325 - "Insert the given 'periods' into the collection."
1.326 -
1.327 - for p in periods:
1.328 - self.insert_period(p)
1.329 -
1.330 - def can_schedule(self, periods, uid, recurrenceid):
1.331 -
1.332 - """
1.333 - Return whether the collection can accommodate the given 'periods'
1.334 - employing the specified 'uid' and 'recurrenceid'.
1.335 - """
1.336 -
1.337 - for conflict in self.have_conflict(periods, True):
1.338 - if conflict.uid != uid or conflict.recurrenceid != recurrenceid:
1.339 - return False
1.340 -
1.341 - return True
1.342 -
1.343 - def have_conflict(self, periods, get_conflicts=False):
1.344 -
1.345 - """
1.346 - Return whether any period in the collection overlaps with the given
1.347 - 'periods', returning a collection of such overlapping periods if
1.348 - 'get_conflicts' is set to a true value.
1.349 - """
1.350 -
1.351 - conflicts = set()
1.352 - for p in periods:
1.353 - overlapping = self.period_overlaps(p, get_conflicts)
1.354 - if overlapping:
1.355 - if get_conflicts:
1.356 - conflicts.update(overlapping)
1.357 - else:
1.358 - return True
1.359 -
1.360 - if get_conflicts:
1.361 - return conflicts
1.362 - else:
1.363 - return False
1.364 -
1.365 - def period_overlaps(self, period, get_periods=False):
1.366 -
1.367 - """
1.368 - Return whether any period in the collection overlaps with the given
1.369 - 'period', returning a collection of overlapping periods if 'get_periods'
1.370 - is set to a true value.
1.371 - """
1.372 -
1.373 - overlapping = self.get_overlapping([period])
1.374 -
1.375 - if get_periods:
1.376 - return overlapping
1.377 - else:
1.378 - return len(overlapping) != 0
1.379 -
1.380 - def replace_overlapping(self, period, replacements):
1.381 -
1.382 - """
1.383 - Replace existing periods in the collection within the given 'period',
1.384 - using the given 'replacements'.
1.385 - """
1.386 -
1.387 - self._check_mutable()
1.388 -
1.389 - self.remove_overlapping(period)
1.390 - for replacement in replacements:
1.391 - self.insert_period(replacement)
1.392 -
1.393 - def coalesce_freebusy(self):
1.394 -
1.395 - "Coalesce the periods in the collection, returning a new collection."
1.396 -
1.397 - if not self:
1.398 - return FreeBusyCollection()
1.399 -
1.400 - fb = []
1.401 -
1.402 - it = iter(self)
1.403 - period = it.next()
1.404 -
1.405 - start = period.get_start_point()
1.406 - end = period.get_end_point()
1.407 -
1.408 - try:
1.409 - while True:
1.410 - period = it.next()
1.411 - if period.get_start_point() > end:
1.412 - fb.append(self.period_class(start, end))
1.413 - start = period.get_start_point()
1.414 - end = period.get_end_point()
1.415 - else:
1.416 - end = max(end, period.get_end_point())
1.417 - except StopIteration:
1.418 - pass
1.419 -
1.420 - fb.append(self.period_class(start, end))
1.421 - return FreeBusyCollection(fb)
1.422 -
1.423 - def invert_freebusy(self):
1.424 -
1.425 - "Return the free periods from the collection as a new collection."
1.426 -
1.427 - if not self:
1.428 - return FreeBusyCollection([self.period_class(None, None)])
1.429 -
1.430 - # Coalesce periods that overlap or are adjacent.
1.431 -
1.432 - fb = self.coalesce_freebusy()
1.433 - free = []
1.434 -
1.435 - # Add a start-of-time period if appropriate.
1.436 -
1.437 - first = fb[0].get_start_point()
1.438 - if first:
1.439 - free.append(self.period_class(None, first))
1.440 -
1.441 - start = fb[0].get_end_point()
1.442 -
1.443 - for period in fb[1:]:
1.444 - free.append(self.period_class(start, period.get_start_point()))
1.445 - start = period.get_end_point()
1.446 -
1.447 - # Add an end-of-time period if appropriate.
1.448 -
1.449 - if start:
1.450 - free.append(self.period_class(start, None))
1.451 -
1.452 - return FreeBusyCollection(free)
1.453 -
1.454 - def _update_freebusy(self, periods, uid, recurrenceid):
1.455 -
1.456 - """
1.457 - Update the free/busy details with the given 'periods', using the given
1.458 - 'uid' plus 'recurrenceid' to remove existing periods.
1.459 - """
1.460 -
1.461 - self._check_mutable()
1.462 -
1.463 - self.remove_specific_event_periods(uid, recurrenceid)
1.464 -
1.465 - self.insert_periods(periods)
1.466 -
1.467 - def update_freebusy(self, periods, transp, uid, recurrenceid, summary, organiser):
1.468 -
1.469 - """
1.470 - Update the free/busy details with the given 'periods', 'transp' setting,
1.471 - 'uid' plus 'recurrenceid' and 'summary' and 'organiser' details.
1.472 - """
1.473 -
1.474 - new_periods = []
1.475 -
1.476 - for p in periods:
1.477 - new_periods.append(
1.478 - self.period_class(p.get_start_point(), p.get_end_point(), uid, transp, recurrenceid, summary, organiser)
1.479 - )
1.480 -
1.481 - self._update_freebusy(new_periods, uid, recurrenceid)
1.482 -
1.483 -class SupportAttendee:
1.484 -
1.485 - "A mix-in that supports the affected attendee in free/busy periods."
1.486 -
1.487 - period_columns = FreeBusyCollectionBase.period_columns + ["attendee"]
1.488 - period_class = FreeBusyGroupPeriod
1.489 -
1.490 - def _update_freebusy(self, periods, uid, recurrenceid, attendee=None):
1.491 -
1.492 - """
1.493 - Update the free/busy details with the given 'periods', using the given
1.494 - 'uid' plus 'recurrenceid' and 'attendee' to remove existing periods.
1.495 - """
1.496 -
1.497 - self._check_mutable()
1.498 -
1.499 - self.remove_specific_event_periods(uid, recurrenceid, attendee)
1.500 -
1.501 - self.insert_periods(periods)
1.502 -
1.503 - def update_freebusy(self, periods, transp, uid, recurrenceid, summary, organiser, attendee=None):
1.504 -
1.505 - """
1.506 - Update the free/busy details with the given 'periods', 'transp' setting,
1.507 - 'uid' plus 'recurrenceid' and 'summary' and 'organiser' details.
1.508 -
1.509 - An optional 'attendee' indicates the attendee affected by the period.
1.510 - """
1.511 -
1.512 - new_periods = []
1.513 -
1.514 - for p in periods:
1.515 - new_periods.append(
1.516 - self.period_class(p.get_start_point(), p.get_end_point(), uid, transp, recurrenceid, summary, organiser, attendee)
1.517 - )
1.518 -
1.519 - self._update_freebusy(new_periods, uid, recurrenceid, attendee)
1.520 -
1.521 -class SupportExpires:
1.522 -
1.523 - "A mix-in that supports the expiry datetime in free/busy periods."
1.524 -
1.525 - period_columns = FreeBusyCollectionBase.period_columns + ["expires"]
1.526 - period_class = FreeBusyOfferPeriod
1.527 -
1.528 - def update_freebusy(self, periods, transp, uid, recurrenceid, summary, organiser, expires=None):
1.529 -
1.530 - """
1.531 - Update the free/busy details with the given 'periods', 'transp' setting,
1.532 - 'uid' plus 'recurrenceid' and 'summary' and 'organiser' details.
1.533 -
1.534 - An optional 'expires' datetime string indicates the expiry time of any
1.535 - free/busy offer.
1.536 - """
1.537 -
1.538 - new_periods = []
1.539 -
1.540 - for p in periods:
1.541 - new_periods.append(
1.542 - self.period_class(p.get_start_point(), p.get_end_point(), uid, transp, recurrenceid, summary, organiser, expires)
1.543 - )
1.544 -
1.545 - self._update_freebusy(new_periods, uid, recurrenceid)
1.546 -
1.547 -class FreeBusyCollection(FreeBusyCollectionBase):
1.548 -
1.549 - "An abstraction for a collection of free/busy periods."
1.550 -
1.551 - def __init__(self, periods=None, mutable=True):
1.552 -
1.553 - """
1.554 - Initialise the collection with the given list of 'periods', or start an
1.555 - empty collection if no list is given. If 'mutable' is indicated, the
1.556 - collection may be changed; otherwise, an exception will be raised.
1.557 - """
1.558 -
1.559 - FreeBusyCollectionBase.__init__(self, mutable)
1.560 - self.periods = periods or []
1.561 -
1.562 - # List emulation methods.
1.563 -
1.564 - def __nonzero__(self):
1.565 - return bool(self.periods)
1.566 -
1.567 - def __iter__(self):
1.568 - return iter(self.periods)
1.569 -
1.570 - def __len__(self):
1.571 - return len(self.periods)
1.572 -
1.573 - def __getitem__(self, i):
1.574 - return self.periods[i]
1.575 -
1.576 - # Operations.
1.577 -
1.578 - def insert_period(self, period):
1.579 -
1.580 - "Insert the given 'period' into the collection."
1.581 -
1.582 - self._check_mutable()
1.583 -
1.584 - i = bisect_left(self.periods, period)
1.585 - if i == len(self.periods):
1.586 - self.periods.append(period)
1.587 - elif self.periods[i] != period:
1.588 - self.periods.insert(i, period)
1.589 -
1.590 - def remove_periods(self, periods):
1.591 -
1.592 - "Remove the given 'periods' from the collection."
1.593 -
1.594 - self._check_mutable()
1.595 -
1.596 - for period in periods:
1.597 - i = bisect_left(self.periods, period)
1.598 - if i < len(self.periods) and self.periods[i] == period:
1.599 - del self.periods[i]
1.600 -
1.601 - def remove_event_periods(self, uid, recurrenceid=None, participant=None):
1.602 -
1.603 - """
1.604 - Remove from the collection all periods associated with 'uid' and
1.605 - 'recurrenceid' (which if omitted causes the "parent" object's periods to
1.606 - be referenced).
1.607 -
1.608 - If 'participant' is specified, only remove periods for which the
1.609 - participant is given as attending.
1.610 -
1.611 - Return the removed periods.
1.612 - """
1.613 -
1.614 - self._check_mutable()
1.615 -
1.616 - removed = []
1.617 - i = 0
1.618 - while i < len(self.periods):
1.619 - fb = self.periods[i]
1.620 -
1.621 - if fb.uid == uid and fb.recurrenceid == recurrenceid and \
1.622 - (not participant or participant == fb.attendee):
1.623 -
1.624 - removed.append(self.periods[i])
1.625 - del self.periods[i]
1.626 - else:
1.627 - i += 1
1.628 -
1.629 - return removed
1.630 -
1.631 - # Specific period removal when updating event details.
1.632 -
1.633 - remove_specific_event_periods = remove_event_periods
1.634 -
1.635 - def remove_additional_periods(self, uid, recurrenceids=None):
1.636 -
1.637 - """
1.638 - Remove from the collection all periods associated with 'uid' having a
1.639 - recurrence identifier indicating an additional or modified period.
1.640 -
1.641 - If 'recurrenceids' is specified, remove all periods associated with
1.642 - 'uid' that do not have a recurrence identifier in the given list.
1.643 -
1.644 - Return the removed periods.
1.645 - """
1.646 -
1.647 - self._check_mutable()
1.648 -
1.649 - removed = []
1.650 - i = 0
1.651 - while i < len(self.periods):
1.652 - fb = self.periods[i]
1.653 - if fb.uid == uid and fb.recurrenceid and (
1.654 - recurrenceids is None or
1.655 - recurrenceids is not None and fb.recurrenceid not in recurrenceids
1.656 - ):
1.657 - removed.append(self.periods[i])
1.658 - del self.periods[i]
1.659 - else:
1.660 - i += 1
1.661 -
1.662 - return removed
1.663 -
1.664 - def remove_affected_period(self, uid, start, participant=None):
1.665 -
1.666 - """
1.667 - Remove from the collection the period associated with 'uid' that
1.668 - provides an occurrence starting at the given 'start' (provided by a
1.669 - recurrence identifier, converted to a datetime). A recurrence identifier
1.670 - is used to provide an alternative time period whilst also acting as a
1.671 - reference to the originally-defined occurrence.
1.672 -
1.673 - If 'participant' is specified, only remove periods for which the
1.674 - participant is given as attending.
1.675 -
1.676 - Return any removed period in a list.
1.677 - """
1.678 -
1.679 - self._check_mutable()
1.680 -
1.681 - removed = []
1.682 -
1.683 - search = Period(start, start)
1.684 - found = bisect_left(self.periods, search)
1.685 -
1.686 - while found < len(self.periods):
1.687 - fb = self.periods[found]
1.688 -
1.689 - # Stop looking if the start no longer matches the recurrence identifier.
1.690 -
1.691 - if fb.get_start_point() != search.get_start_point():
1.692 - break
1.693 -
1.694 - # If the period belongs to the parent object, remove it and return.
1.695 -
1.696 - if not fb.recurrenceid and uid == fb.uid and \
1.697 - (not participant or participant == fb.attendee):
1.698 -
1.699 - removed.append(self.periods[found])
1.700 - del self.periods[found]
1.701 - break
1.702 -
1.703 - # Otherwise, keep looking for a matching period.
1.704 -
1.705 - found += 1
1.706 -
1.707 - return removed
1.708 -
1.709 - def periods_from(self, period):
1.710 -
1.711 - "Return the entries in the collection at or after 'period'."
1.712 -
1.713 - first = bisect_left(self.periods, period)
1.714 - return self.periods[first:]
1.715 -
1.716 - def periods_until(self, period):
1.717 -
1.718 - "Return the entries in the collection before 'period'."
1.719 -
1.720 - last = bisect_right(self.periods, Period(period.get_end(), period.get_end(), period.get_tzid()))
1.721 - return self.periods[:last]
1.722 -
1.723 - def get_overlapping(self, periods):
1.724 -
1.725 - """
1.726 - Return the entries in the collection providing periods overlapping with
1.727 - the given sorted collection of 'periods'.
1.728 - """
1.729 -
1.730 - return get_overlapping(self.periods, periods)
1.731 -
1.732 - def remove_overlapping(self, period):
1.733 -
1.734 - "Remove all periods overlapping with 'period' from the collection."
1.735 -
1.736 - self._check_mutable()
1.737 -
1.738 - overlapping = self.get_overlapping([period])
1.739 -
1.740 - if overlapping:
1.741 - for fb in overlapping:
1.742 - self.periods.remove(fb)
1.743 -
1.744 -class FreeBusyGroupCollection(SupportAttendee, FreeBusyCollection):
1.745 -
1.746 - "A collection of quota group free/busy objects."
1.747 -
1.748 - def remove_specific_event_periods(self, uid, recurrenceid=None, attendee=None):
1.749 -
1.750 - """
1.751 - Remove from the collection all periods associated with 'uid' and
1.752 - 'recurrenceid' (which if omitted causes the "parent" object's periods to
1.753 - be referenced) and any 'attendee'.
1.754 -
1.755 - Return the removed periods.
1.756 - """
1.757 -
1.758 - self._check_mutable()
1.759 -
1.760 - removed = []
1.761 - i = 0
1.762 - while i < len(self.periods):
1.763 - fb = self.periods[i]
1.764 - if fb.uid == uid and fb.recurrenceid == recurrenceid and fb.attendee == attendee:
1.765 - removed.append(self.periods[i])
1.766 - del self.periods[i]
1.767 - else:
1.768 - i += 1
1.769 -
1.770 - return removed
1.771 -
1.772 -class FreeBusyOffersCollection(SupportExpires, FreeBusyCollection):
1.773 -
1.774 - "A collection of offered free/busy objects."
1.775 -
1.776 - pass
1.777 -
1.778 -class FreeBusyDatabaseCollection(FreeBusyCollectionBase, DatabaseOperations):
1.779 -
1.780 - """
1.781 - An abstraction for a collection of free/busy periods stored in a database
1.782 - system.
1.783 - """
1.784 -
1.785 - def __init__(self, cursor, table_name, column_names=None, filter_values=None,
1.786 - mutable=True, paramstyle=None):
1.787 -
1.788 - """
1.789 - Initialise the collection with the given 'cursor' and with the
1.790 - 'table_name', 'column_names' and 'filter_values' configuring the
1.791 - selection of data. If 'mutable' is indicated, the collection may be
1.792 - changed; otherwise, an exception will be raised.
1.793 - """
1.794 -
1.795 - FreeBusyCollectionBase.__init__(self, mutable)
1.796 - DatabaseOperations.__init__(self, column_names, filter_values, paramstyle)
1.797 - self.cursor = cursor
1.798 - self.table_name = table_name
1.799 -
1.800 - # List emulation methods.
1.801 -
1.802 - def __nonzero__(self):
1.803 - return len(self) and True or False
1.804 -
1.805 - def __iter__(self):
1.806 - query, values = self.get_query(
1.807 - "select %(columns)s from %(table)s :condition" % {
1.808 - "columns" : self.columnlist(self.period_columns),
1.809 - "table" : self.table_name
1.810 - })
1.811 - self.cursor.execute(query, values)
1.812 - return iter(map(lambda t: self.make_period(t), self.cursor.fetchall()))
1.813 -
1.814 - def __len__(self):
1.815 - query, values = self.get_query(
1.816 - "select count(*) from %(table)s :condition" % {
1.817 - "table" : self.table_name
1.818 - })
1.819 - self.cursor.execute(query, values)
1.820 - result = self.cursor.fetchone()
1.821 - return result and int(result[0]) or 0
1.822 -
1.823 - def __getitem__(self, i):
1.824 - return list(iter(self))[i]
1.825 -
1.826 - # Operations.
1.827 -
1.828 - def insert_period(self, period):
1.829 -
1.830 - "Insert the given 'period' into the collection."
1.831 -
1.832 - self._check_mutable()
1.833 -
1.834 - columns, values = self.period_columns, period.as_tuple(string_datetimes=True)
1.835 -
1.836 - query, values = self.get_query(
1.837 - "insert into %(table)s (:columns) values (:values)" % {
1.838 - "table" : self.table_name
1.839 - },
1.840 - columns, [to_string(v, "utf-8") for v in values])
1.841 -
1.842 - self.cursor.execute(query, values)
1.843 -
1.844 - def insert_periods(self, periods):
1.845 -
1.846 - "Insert the given 'periods' into the collection."
1.847 -
1.848 - if not hasattr(self.cursor, "copy_from"):
1.849 - return FreeBusyCollectionBase.insert_periods(self, periods)
1.850 -
1.851 - self._check_mutable()
1.852 -
1.853 - columns = self.merge_default_columns(self.period_columns)
1.854 -
1.855 - all_values = []
1.856 - for period in periods:
1.857 - all_values.append(self.merge_default_values(period.as_tuple(string_datetimes=True)))
1.858 -
1.859 - f = to_copy_file(all_values)
1.860 -
1.861 - # Copy from the file-like object to the table.
1.862 -
1.863 - self.cursor.copy_from(f, self.table_name, columns=map(quote_column, columns))
1.864 -
1.865 - def remove_periods(self, periods):
1.866 -
1.867 - "Remove the given 'periods' from the collection."
1.868 -
1.869 - self._check_mutable()
1.870 -
1.871 - for period in periods:
1.872 - values = period.as_tuple(string_datetimes=True)
1.873 -
1.874 - query, values = self.get_query(
1.875 - "delete from %(table)s :condition" % {
1.876 - "table" : self.table_name
1.877 - },
1.878 - self.period_columns, [to_string(v, "utf-8") for v in values])
1.879 -
1.880 - self.cursor.execute(query, values)
1.881 -
1.882 - def remove_event_periods(self, uid, recurrenceid=None, participant=None):
1.883 -
1.884 - """
1.885 - Remove from the collection all periods associated with 'uid' and
1.886 - 'recurrenceid' (which if omitted causes the "parent" object's periods to
1.887 - be referenced).
1.888 -
1.889 - If 'participant' is specified, only remove periods for which the
1.890 - participant is given as attending.
1.891 -
1.892 - Return the removed periods.
1.893 - """
1.894 -
1.895 - self._check_mutable()
1.896 -
1.897 - columns, values = ["object_uid"], [uid]
1.898 -
1.899 - if recurrenceid:
1.900 - columns.append("object_recurrenceid")
1.901 - values.append(recurrenceid)
1.902 - else:
1.903 - columns.append("object_recurrenceid is null")
1.904 -
1.905 - if participant:
1.906 - columns.append("attendee")
1.907 - values.append(participant)
1.908 -
1.909 - query, _values = self.get_query(
1.910 - "select %(columns)s from %(table)s :condition" % {
1.911 - "columns" : self.columnlist(self.period_columns),
1.912 - "table" : self.table_name
1.913 - },
1.914 - columns, values)
1.915 -
1.916 - self.cursor.execute(query, _values)
1.917 - removed = self.cursor.fetchall()
1.918 -
1.919 - query, values = self.get_query(
1.920 - "delete from %(table)s :condition" % {
1.921 - "table" : self.table_name
1.922 - },
1.923 - columns, values)
1.924 -
1.925 - self.cursor.execute(query, values)
1.926 -
1.927 - return map(lambda t: self.make_period(t), removed)
1.928 -
1.929 - # Specific period removal when updating event details.
1.930 -
1.931 - remove_specific_event_periods = remove_event_periods
1.932 -
1.933 - def remove_additional_periods(self, uid, recurrenceids=None):
1.934 -
1.935 - """
1.936 - Remove from the collection all periods associated with 'uid' having a
1.937 - recurrence identifier indicating an additional or modified period.
1.938 -
1.939 - If 'recurrenceids' is specified, remove all periods associated with
1.940 - 'uid' that do not have a recurrence identifier in the given list.
1.941 -
1.942 - Return the removed periods.
1.943 - """
1.944 -
1.945 - self._check_mutable()
1.946 -
1.947 - if not recurrenceids:
1.948 - columns, values = ["object_uid", "object_recurrenceid is not null"], [uid]
1.949 - else:
1.950 - columns, values = ["object_uid", "object_recurrenceid not in ?", "object_recurrenceid is not null"], [uid, tuple(recurrenceids)]
1.951 -
1.952 - query, _values = self.get_query(
1.953 - "select %(columns)s from %(table)s :condition" % {
1.954 - "columns" : self.columnlist(self.period_columns),
1.955 - "table" : self.table_name
1.956 - },
1.957 - columns, values)
1.958 -
1.959 - self.cursor.execute(query, _values)
1.960 - removed = self.cursor.fetchall()
1.961 -
1.962 - query, values = self.get_query(
1.963 - "delete from %(table)s :condition" % {
1.964 - "table" : self.table_name
1.965 - },
1.966 - columns, values)
1.967 -
1.968 - self.cursor.execute(query, values)
1.969 -
1.970 - return map(lambda t: self.make_period(t), removed)
1.971 -
1.972 - def remove_affected_period(self, uid, start, participant=None):
1.973 -
1.974 - """
1.975 - Remove from the collection the period associated with 'uid' that
1.976 - provides an occurrence starting at the given 'start' (provided by a
1.977 - recurrence identifier, converted to a datetime). A recurrence identifier
1.978 - is used to provide an alternative time period whilst also acting as a
1.979 - reference to the originally-defined occurrence.
1.980 -
1.981 - If 'participant' is specified, only remove periods for which the
1.982 - participant is given as attending.
1.983 -
1.984 - Return any removed period in a list.
1.985 - """
1.986 -
1.987 - self._check_mutable()
1.988 -
1.989 - start = format_datetime(start)
1.990 -
1.991 - columns, values = ["object_uid", "start", "object_recurrenceid is null"], [uid, start]
1.992 -
1.993 - if participant:
1.994 - columns.append("attendee")
1.995 - values.append(participant)
1.996 -
1.997 - query, _values = self.get_query(
1.998 - "select %(columns)s from %(table)s :condition" % {
1.999 - "columns" : self.columnlist(self.period_columns),
1.1000 - "table" : self.table_name
1.1001 - },
1.1002 - columns, values)
1.1003 -
1.1004 - self.cursor.execute(query, _values)
1.1005 - removed = self.cursor.fetchall()
1.1006 -
1.1007 - query, values = self.get_query(
1.1008 - "delete from %(table)s :condition" % {
1.1009 - "table" : self.table_name
1.1010 - },
1.1011 - columns, values)
1.1012 -
1.1013 - self.cursor.execute(query, values)
1.1014 -
1.1015 - return map(lambda t: self.make_period(t), removed)
1.1016 -
1.1017 - def periods_from(self, period):
1.1018 -
1.1019 - "Return the entries in the collection at or after 'period'."
1.1020 -
1.1021 - start = format_datetime(period.get_start_point())
1.1022 -
1.1023 - columns, values = [], []
1.1024 -
1.1025 - if start:
1.1026 - columns.append("start >= ?")
1.1027 - values.append(start)
1.1028 -
1.1029 - query, values = self.get_query(
1.1030 - "select %(columns)s from %(table)s :condition" % {
1.1031 - "columns" : self.columnlist(self.period_columns),
1.1032 - "table" : self.table_name
1.1033 - },
1.1034 - columns, values)
1.1035 -
1.1036 - self.cursor.execute(query, values)
1.1037 -
1.1038 - return map(lambda t: self.make_period(t), self.cursor.fetchall())
1.1039 -
1.1040 - def periods_until(self, period):
1.1041 -
1.1042 - "Return the entries in the collection before 'period'."
1.1043 -
1.1044 - end = format_datetime(period.get_end_point())
1.1045 -
1.1046 - columns, values = [], []
1.1047 -
1.1048 - if end:
1.1049 - columns.append("start < ?")
1.1050 - values.append(end)
1.1051 -
1.1052 - query, values = self.get_query(
1.1053 - "select %(columns)s from %(table)s :condition" % {
1.1054 - "columns" : self.columnlist(self.period_columns),
1.1055 - "table" : self.table_name
1.1056 - },
1.1057 - columns, values)
1.1058 -
1.1059 - self.cursor.execute(query, values)
1.1060 -
1.1061 - return map(lambda t: self.make_period(t), self.cursor.fetchall())
1.1062 -
1.1063 - def get_overlapping(self, periods):
1.1064 -
1.1065 - """
1.1066 - Return the entries in the collection providing periods overlapping with
1.1067 - the given sorted collection of 'periods'.
1.1068 - """
1.1069 -
1.1070 - overlapping = set()
1.1071 -
1.1072 - for period in periods:
1.1073 - columns, values = self._get_period_values(period)
1.1074 -
1.1075 - query, values = self.get_query(
1.1076 - "select %(columns)s from %(table)s :condition" % {
1.1077 - "columns" : self.columnlist(self.period_columns),
1.1078 - "table" : self.table_name
1.1079 - },
1.1080 - columns, values)
1.1081 -
1.1082 - self.cursor.execute(query, values)
1.1083 -
1.1084 - overlapping.update(map(lambda t: self.make_period(t), self.cursor.fetchall()))
1.1085 -
1.1086 - overlapping = list(overlapping)
1.1087 - overlapping.sort()
1.1088 - return overlapping
1.1089 -
1.1090 - def remove_overlapping(self, period):
1.1091 -
1.1092 - "Remove all periods overlapping with 'period' from the collection."
1.1093 -
1.1094 - self._check_mutable()
1.1095 -
1.1096 - columns, values = self._get_period_values(period)
1.1097 -
1.1098 - query, values = self.get_query(
1.1099 - "delete from %(table)s :condition" % {
1.1100 - "table" : self.table_name
1.1101 - },
1.1102 - columns, values)
1.1103 -
1.1104 - self.cursor.execute(query, values)
1.1105 -
1.1106 - def _get_period_values(self, period):
1.1107 -
1.1108 - start = format_datetime(period.get_start_point())
1.1109 - end = format_datetime(period.get_end_point())
1.1110 -
1.1111 - columns, values = [], []
1.1112 -
1.1113 - if end:
1.1114 - columns.append("start < ?")
1.1115 - values.append(end)
1.1116 - if start:
1.1117 - columns.append("end > ?")
1.1118 - values.append(start)
1.1119 -
1.1120 - return columns, values
1.1121 -
1.1122 -class FreeBusyGroupDatabaseCollection(SupportAttendee, FreeBusyDatabaseCollection):
1.1123 -
1.1124 - "A collection of quota group free/busy objects."
1.1125 -
1.1126 - def remove_specific_event_periods(self, uid, recurrenceid=None, attendee=None):
1.1127 -
1.1128 - """
1.1129 - Remove from the collection all periods associated with 'uid' and
1.1130 - 'recurrenceid' (which if omitted causes the "parent" object's periods to
1.1131 - be referenced) and any 'attendee'.
1.1132 -
1.1133 - Return the removed periods.
1.1134 - """
1.1135 -
1.1136 - self._check_mutable()
1.1137 -
1.1138 - columns, values = ["object_uid"], [uid]
1.1139 -
1.1140 - if recurrenceid:
1.1141 - columns.append("object_recurrenceid")
1.1142 - values.append(recurrenceid)
1.1143 - else:
1.1144 - columns.append("object_recurrenceid is null")
1.1145 -
1.1146 - if attendee:
1.1147 - columns.append("attendee")
1.1148 - values.append(attendee)
1.1149 - else:
1.1150 - columns.append("attendee is null")
1.1151 -
1.1152 - query, _values = self.get_query(
1.1153 - "select %(columns)s from %(table)s :condition" % {
1.1154 - "columns" : self.columnlist(self.period_columns),
1.1155 - "table" : self.table_name
1.1156 - },
1.1157 - columns, values)
1.1158 -
1.1159 - self.cursor.execute(query, _values)
1.1160 - removed = self.cursor.fetchall()
1.1161 -
1.1162 - query, values = self.get_query(
1.1163 - "delete from %(table)s :condition" % {
1.1164 - "table" : self.table_name
1.1165 - },
1.1166 - columns, values)
1.1167 -
1.1168 - self.cursor.execute(query, values)
1.1169 -
1.1170 - return map(lambda t: self.make_period(t), removed)
1.1171 -
1.1172 -class FreeBusyOffersDatabaseCollection(SupportExpires, FreeBusyDatabaseCollection):
1.1173 -
1.1174 - "A collection of offered free/busy objects."
1.1175 -
1.1176 - pass
1.1177 -
1.1178 -# vim: tabstop=4 expandtab shiftwidth=4