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
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/imiptools/freebusy/__init__.py Fri May 26 18:25:23 2017 +0200
2.3 @@ -0,0 +1,30 @@
2.4 +#!/usr/bin/env python
2.5 +
2.6 +"""
2.7 +Managing free/busy periods.
2.8 +
2.9 +Copyright (C) 2017 Paul Boddie <paul@boddie.org.uk>
2.10 +
2.11 +This program is free software; you can redistribute it and/or modify it under
2.12 +the terms of the GNU General Public License as published by the Free Software
2.13 +Foundation; either version 3 of the License, or (at your option) any later
2.14 +version.
2.15 +
2.16 +This program is distributed in the hope that it will be useful, but WITHOUT
2.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
2.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
2.19 +details.
2.20 +
2.21 +You should have received a copy of the GNU General Public License along with
2.22 +this program. If not, see <http://www.gnu.org/licenses/>.
2.23 +"""
2.24 +
2.25 +from imiptools.freebusy.common import FreeBusyPeriod, \
2.26 + FreeBusyGroupPeriod, \
2.27 + FreeBusyOfferPeriod, \
2.28 + FreeBusyCollection, \
2.29 + FreeBusyGroupCollection, \
2.30 + FreeBusyOffersCollection, \
2.31 + SupportAttendee, SupportExpires
2.32 +
2.33 +# vim: tabstop=4 expandtab shiftwidth=4
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/imiptools/freebusy/common.py Fri May 26 18:25:23 2017 +0200
3.3 @@ -0,0 +1,747 @@
3.4 +#!/usr/bin/env python
3.5 +
3.6 +"""
3.7 +Managing free/busy periods.
3.8 +
3.9 +Copyright (C) 2014, 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk>
3.10 +
3.11 +This program is free software; you can redistribute it and/or modify it under
3.12 +the terms of the GNU General Public License as published by the Free Software
3.13 +Foundation; either version 3 of the License, or (at your option) any later
3.14 +version.
3.15 +
3.16 +This program is distributed in the hope that it will be useful, but WITHOUT
3.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
3.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
3.19 +details.
3.20 +
3.21 +You should have received a copy of the GNU General Public License along with
3.22 +this program. If not, see <http://www.gnu.org/licenses/>.
3.23 +"""
3.24 +
3.25 +from bisect import bisect_left, bisect_right
3.26 +from imiptools.dates import format_datetime
3.27 +from imiptools.period import get_overlapping, Period, PeriodBase
3.28 +
3.29 +# Conversion functions.
3.30 +
3.31 +def from_string(s, encoding):
3.32 +
3.33 + "Interpret 's' using 'encoding', preserving None."
3.34 +
3.35 + if s:
3.36 + return unicode(s, encoding)
3.37 + else:
3.38 + return s
3.39 +
3.40 +def to_string(s, encoding):
3.41 +
3.42 + "Encode 's' using 'encoding', preserving None."
3.43 +
3.44 + if s:
3.45 + return s.encode(encoding)
3.46 + else:
3.47 + return s
3.48 +
3.49 +
3.50 +
3.51 +# Period abstractions.
3.52 +
3.53 +class FreeBusyPeriod(PeriodBase):
3.54 +
3.55 + "A free/busy record abstraction."
3.56 +
3.57 + def __init__(self, start, end, uid=None, transp=None, recurrenceid=None,
3.58 + summary=None, organiser=None):
3.59 +
3.60 + """
3.61 + Initialise a free/busy period with the given 'start' and 'end' points,
3.62 + plus any 'uid', 'transp', 'recurrenceid', 'summary' and 'organiser'
3.63 + details.
3.64 + """
3.65 +
3.66 + PeriodBase.__init__(self, start, end)
3.67 + self.uid = uid
3.68 + self.transp = transp or None
3.69 + self.recurrenceid = recurrenceid or None
3.70 + self.summary = summary or None
3.71 + self.organiser = organiser or None
3.72 +
3.73 + def as_tuple(self, strings_only=False, string_datetimes=False):
3.74 +
3.75 + """
3.76 + Return the initialisation parameter tuple, converting datetimes and
3.77 + false value parameters to strings if 'strings_only' is set to a true
3.78 + value. Otherwise, if 'string_datetimes' is set to a true value, only the
3.79 + datetime values are converted to strings.
3.80 + """
3.81 +
3.82 + null = lambda x: (strings_only and [""] or [x])[0]
3.83 + return (
3.84 + (strings_only or string_datetimes) and format_datetime(self.get_start_point()) or self.start,
3.85 + (strings_only or string_datetimes) and format_datetime(self.get_end_point()) or self.end,
3.86 + self.uid or null(self.uid),
3.87 + self.transp or strings_only and "OPAQUE" or None,
3.88 + self.recurrenceid or null(self.recurrenceid),
3.89 + self.summary or null(self.summary),
3.90 + self.organiser or null(self.organiser)
3.91 + )
3.92 +
3.93 + def __cmp__(self, other):
3.94 +
3.95 + """
3.96 + Compare this object to 'other', employing the uid if the periods
3.97 + involved are the same.
3.98 + """
3.99 +
3.100 + result = PeriodBase.__cmp__(self, other)
3.101 + if result == 0 and isinstance(other, FreeBusyPeriod):
3.102 + return cmp((self.uid, self.recurrenceid), (other.uid, other.recurrenceid))
3.103 + else:
3.104 + return result
3.105 +
3.106 + def get_key(self):
3.107 + return self.uid, self.recurrenceid, self.get_start()
3.108 +
3.109 + def __repr__(self):
3.110 + return "FreeBusyPeriod%r" % (self.as_tuple(),)
3.111 +
3.112 + def get_tzid(self):
3.113 + return "UTC"
3.114 +
3.115 + # Period and event recurrence logic.
3.116 +
3.117 + def is_replaced(self, recurrences):
3.118 +
3.119 + """
3.120 + Return whether this period refers to one of the 'recurrences'.
3.121 + The 'recurrences' must be UTC datetimes corresponding to the start of
3.122 + the period described by a recurrence.
3.123 + """
3.124 +
3.125 + for recurrence in recurrences:
3.126 + if self.is_affected(recurrence):
3.127 + return True
3.128 + return False
3.129 +
3.130 + def is_affected(self, recurrence):
3.131 +
3.132 + """
3.133 + Return whether this period refers to 'recurrence'. The 'recurrence' must
3.134 + be a UTC datetime corresponding to the start of the period described by
3.135 + a recurrence.
3.136 + """
3.137 +
3.138 + return recurrence and self.get_start_point() == recurrence
3.139 +
3.140 + # Value correction methods.
3.141 +
3.142 + def make_corrected(self, start, end):
3.143 + return self.__class__(start, end)
3.144 +
3.145 +class FreeBusyOfferPeriod(FreeBusyPeriod):
3.146 +
3.147 + "A free/busy record abstraction for an offer period."
3.148 +
3.149 + def __init__(self, start, end, uid=None, transp=None, recurrenceid=None,
3.150 + summary=None, organiser=None, expires=None):
3.151 +
3.152 + """
3.153 + Initialise a free/busy period with the given 'start' and 'end' points,
3.154 + plus any 'uid', 'transp', 'recurrenceid', 'summary' and 'organiser'
3.155 + details.
3.156 +
3.157 + An additional 'expires' parameter can be used to indicate an expiry
3.158 + datetime in conjunction with free/busy offers made when countering
3.159 + event proposals.
3.160 + """
3.161 +
3.162 + FreeBusyPeriod.__init__(self, start, end, uid, transp, recurrenceid,
3.163 + summary, organiser)
3.164 + self.expires = expires or None
3.165 +
3.166 + def as_tuple(self, strings_only=False, string_datetimes=False):
3.167 +
3.168 + """
3.169 + Return the initialisation parameter tuple, converting datetimes and
3.170 + false value parameters to strings if 'strings_only' is set to a true
3.171 + value. Otherwise, if 'string_datetimes' is set to a true value, only the
3.172 + datetime values are converted to strings.
3.173 + """
3.174 +
3.175 + null = lambda x: (strings_only and [""] or [x])[0]
3.176 + return FreeBusyPeriod.as_tuple(self, strings_only, string_datetimes) + (
3.177 + self.expires or null(self.expires),)
3.178 +
3.179 + def __repr__(self):
3.180 + return "FreeBusyOfferPeriod%r" % (self.as_tuple(),)
3.181 +
3.182 +class FreeBusyGroupPeriod(FreeBusyPeriod):
3.183 +
3.184 + "A free/busy record abstraction for a quota group period."
3.185 +
3.186 + def __init__(self, start, end, uid=None, transp=None, recurrenceid=None,
3.187 + summary=None, organiser=None, attendee=None):
3.188 +
3.189 + """
3.190 + Initialise a free/busy period with the given 'start' and 'end' points,
3.191 + plus any 'uid', 'transp', 'recurrenceid', 'summary' and 'organiser'
3.192 + details.
3.193 +
3.194 + An additional 'attendee' parameter can be used to indicate the identity
3.195 + of the attendee recording the period.
3.196 + """
3.197 +
3.198 + FreeBusyPeriod.__init__(self, start, end, uid, transp, recurrenceid,
3.199 + summary, organiser)
3.200 + self.attendee = attendee or None
3.201 +
3.202 + def as_tuple(self, strings_only=False, string_datetimes=False):
3.203 +
3.204 + """
3.205 + Return the initialisation parameter tuple, converting datetimes and
3.206 + false value parameters to strings if 'strings_only' is set to a true
3.207 + value. Otherwise, if 'string_datetimes' is set to a true value, only the
3.208 + datetime values are converted to strings.
3.209 + """
3.210 +
3.211 + null = lambda x: (strings_only and [""] or [x])[0]
3.212 + return FreeBusyPeriod.as_tuple(self, strings_only, string_datetimes) + (
3.213 + self.attendee or null(self.attendee),)
3.214 +
3.215 + def __cmp__(self, other):
3.216 +
3.217 + """
3.218 + Compare this object to 'other', employing the uid if the periods
3.219 + involved are the same.
3.220 + """
3.221 +
3.222 + result = FreeBusyPeriod.__cmp__(self, other)
3.223 + if isinstance(other, FreeBusyGroupPeriod) and result == 0:
3.224 + return cmp(self.attendee, other.attendee)
3.225 + else:
3.226 + return result
3.227 +
3.228 + def __repr__(self):
3.229 + return "FreeBusyGroupPeriod%r" % (self.as_tuple(),)
3.230 +
3.231 +class FreeBusyCollectionBase:
3.232 +
3.233 + "Common operations on free/busy period collections."
3.234 +
3.235 + period_columns = [
3.236 + "start", "end", "object_uid", "transp", "object_recurrenceid",
3.237 + "summary", "organiser"
3.238 + ]
3.239 +
3.240 + period_class = FreeBusyPeriod
3.241 +
3.242 + def __init__(self, mutable=True):
3.243 + self.mutable = mutable
3.244 +
3.245 + def _check_mutable(self):
3.246 + if not self.mutable:
3.247 + raise TypeError, "Cannot mutate this collection."
3.248 +
3.249 + def copy(self):
3.250 +
3.251 + "Make an independent mutable copy of the collection."
3.252 +
3.253 + return FreeBusyCollection(list(self), True)
3.254 +
3.255 + def make_period(self, t):
3.256 +
3.257 + """
3.258 + Make a period using the given tuple of arguments and the collection's
3.259 + column details.
3.260 + """
3.261 +
3.262 + args = []
3.263 + for arg, column in zip(t, self.period_columns):
3.264 + args.append(from_string(arg, "utf-8"))
3.265 + return self.period_class(*args)
3.266 +
3.267 + def make_tuple(self, t):
3.268 +
3.269 + """
3.270 + Return a tuple from the given tuple 't' conforming to the collection's
3.271 + column details.
3.272 + """
3.273 +
3.274 + args = []
3.275 + for arg, column in zip(t, self.period_columns):
3.276 + args.append(arg)
3.277 + return tuple(args)
3.278 +
3.279 + # List emulation methods.
3.280 +
3.281 + def __iadd__(self, periods):
3.282 + self.insert_periods(periods)
3.283 + return self
3.284 +
3.285 + def append(self, period):
3.286 + self.insert_period(period)
3.287 +
3.288 + # Operations.
3.289 +
3.290 + def insert_periods(self, periods):
3.291 +
3.292 + "Insert the given 'periods' into the collection."
3.293 +
3.294 + for p in periods:
3.295 + self.insert_period(p)
3.296 +
3.297 + def can_schedule(self, periods, uid, recurrenceid):
3.298 +
3.299 + """
3.300 + Return whether the collection can accommodate the given 'periods'
3.301 + employing the specified 'uid' and 'recurrenceid'.
3.302 + """
3.303 +
3.304 + for conflict in self.have_conflict(periods, True):
3.305 + if conflict.uid != uid or conflict.recurrenceid != recurrenceid:
3.306 + return False
3.307 +
3.308 + return True
3.309 +
3.310 + def have_conflict(self, periods, get_conflicts=False):
3.311 +
3.312 + """
3.313 + Return whether any period in the collection overlaps with the given
3.314 + 'periods', returning a collection of such overlapping periods if
3.315 + 'get_conflicts' is set to a true value.
3.316 + """
3.317 +
3.318 + conflicts = set()
3.319 + for p in periods:
3.320 + overlapping = self.period_overlaps(p, get_conflicts)
3.321 + if overlapping:
3.322 + if get_conflicts:
3.323 + conflicts.update(overlapping)
3.324 + else:
3.325 + return True
3.326 +
3.327 + if get_conflicts:
3.328 + return conflicts
3.329 + else:
3.330 + return False
3.331 +
3.332 + def period_overlaps(self, period, get_periods=False):
3.333 +
3.334 + """
3.335 + Return whether any period in the collection overlaps with the given
3.336 + 'period', returning a collection of overlapping periods if 'get_periods'
3.337 + is set to a true value.
3.338 + """
3.339 +
3.340 + overlapping = self.get_overlapping([period])
3.341 +
3.342 + if get_periods:
3.343 + return overlapping
3.344 + else:
3.345 + return len(overlapping) != 0
3.346 +
3.347 + def replace_overlapping(self, period, replacements):
3.348 +
3.349 + """
3.350 + Replace existing periods in the collection within the given 'period',
3.351 + using the given 'replacements'.
3.352 + """
3.353 +
3.354 + self._check_mutable()
3.355 +
3.356 + self.remove_overlapping(period)
3.357 + for replacement in replacements:
3.358 + self.insert_period(replacement)
3.359 +
3.360 + def coalesce_freebusy(self):
3.361 +
3.362 + "Coalesce the periods in the collection, returning a new collection."
3.363 +
3.364 + if not self:
3.365 + return FreeBusyCollection()
3.366 +
3.367 + fb = []
3.368 +
3.369 + it = iter(self)
3.370 + period = it.next()
3.371 +
3.372 + start = period.get_start_point()
3.373 + end = period.get_end_point()
3.374 +
3.375 + try:
3.376 + while True:
3.377 + period = it.next()
3.378 + if period.get_start_point() > end:
3.379 + fb.append(self.period_class(start, end))
3.380 + start = period.get_start_point()
3.381 + end = period.get_end_point()
3.382 + else:
3.383 + end = max(end, period.get_end_point())
3.384 + except StopIteration:
3.385 + pass
3.386 +
3.387 + fb.append(self.period_class(start, end))
3.388 + return FreeBusyCollection(fb)
3.389 +
3.390 + def invert_freebusy(self):
3.391 +
3.392 + "Return the free periods from the collection as a new collection."
3.393 +
3.394 + if not self:
3.395 + return FreeBusyCollection([self.period_class(None, None)])
3.396 +
3.397 + # Coalesce periods that overlap or are adjacent.
3.398 +
3.399 + fb = self.coalesce_freebusy()
3.400 + free = []
3.401 +
3.402 + # Add a start-of-time period if appropriate.
3.403 +
3.404 + first = fb[0].get_start_point()
3.405 + if first:
3.406 + free.append(self.period_class(None, first))
3.407 +
3.408 + start = fb[0].get_end_point()
3.409 +
3.410 + for period in fb[1:]:
3.411 + free.append(self.period_class(start, period.get_start_point()))
3.412 + start = period.get_end_point()
3.413 +
3.414 + # Add an end-of-time period if appropriate.
3.415 +
3.416 + if start:
3.417 + free.append(self.period_class(start, None))
3.418 +
3.419 + return FreeBusyCollection(free)
3.420 +
3.421 + def _update_freebusy(self, periods, uid, recurrenceid):
3.422 +
3.423 + """
3.424 + Update the free/busy details with the given 'periods', using the given
3.425 + 'uid' plus 'recurrenceid' to remove existing periods.
3.426 + """
3.427 +
3.428 + self._check_mutable()
3.429 +
3.430 + self.remove_specific_event_periods(uid, recurrenceid)
3.431 +
3.432 + self.insert_periods(periods)
3.433 +
3.434 + def update_freebusy(self, periods, transp, uid, recurrenceid, summary, organiser):
3.435 +
3.436 + """
3.437 + Update the free/busy details with the given 'periods', 'transp' setting,
3.438 + 'uid' plus 'recurrenceid' and 'summary' and 'organiser' details.
3.439 + """
3.440 +
3.441 + new_periods = []
3.442 +
3.443 + for p in periods:
3.444 + new_periods.append(
3.445 + self.period_class(p.get_start_point(), p.get_end_point(), uid, transp, recurrenceid, summary, organiser)
3.446 + )
3.447 +
3.448 + self._update_freebusy(new_periods, uid, recurrenceid)
3.449 +
3.450 +class SupportAttendee:
3.451 +
3.452 + "A mix-in that supports the affected attendee in free/busy periods."
3.453 +
3.454 + period_columns = FreeBusyCollectionBase.period_columns + ["attendee"]
3.455 + period_class = FreeBusyGroupPeriod
3.456 +
3.457 + def _update_freebusy(self, periods, uid, recurrenceid, attendee=None):
3.458 +
3.459 + """
3.460 + Update the free/busy details with the given 'periods', using the given
3.461 + 'uid' plus 'recurrenceid' and 'attendee' to remove existing periods.
3.462 + """
3.463 +
3.464 + self._check_mutable()
3.465 +
3.466 + self.remove_specific_event_periods(uid, recurrenceid, attendee)
3.467 +
3.468 + self.insert_periods(periods)
3.469 +
3.470 + def update_freebusy(self, periods, transp, uid, recurrenceid, summary, organiser, attendee=None):
3.471 +
3.472 + """
3.473 + Update the free/busy details with the given 'periods', 'transp' setting,
3.474 + 'uid' plus 'recurrenceid' and 'summary' and 'organiser' details.
3.475 +
3.476 + An optional 'attendee' indicates the attendee affected by the period.
3.477 + """
3.478 +
3.479 + new_periods = []
3.480 +
3.481 + for p in periods:
3.482 + new_periods.append(
3.483 + self.period_class(p.get_start_point(), p.get_end_point(), uid, transp, recurrenceid, summary, organiser, attendee)
3.484 + )
3.485 +
3.486 + self._update_freebusy(new_periods, uid, recurrenceid, attendee)
3.487 +
3.488 +class SupportExpires:
3.489 +
3.490 + "A mix-in that supports the expiry datetime in free/busy periods."
3.491 +
3.492 + period_columns = FreeBusyCollectionBase.period_columns + ["expires"]
3.493 + period_class = FreeBusyOfferPeriod
3.494 +
3.495 + def update_freebusy(self, periods, transp, uid, recurrenceid, summary, organiser, expires=None):
3.496 +
3.497 + """
3.498 + Update the free/busy details with the given 'periods', 'transp' setting,
3.499 + 'uid' plus 'recurrenceid' and 'summary' and 'organiser' details.
3.500 +
3.501 + An optional 'expires' datetime string indicates the expiry time of any
3.502 + free/busy offer.
3.503 + """
3.504 +
3.505 + new_periods = []
3.506 +
3.507 + for p in periods:
3.508 + new_periods.append(
3.509 + self.period_class(p.get_start_point(), p.get_end_point(), uid, transp, recurrenceid, summary, organiser, expires)
3.510 + )
3.511 +
3.512 + self._update_freebusy(new_periods, uid, recurrenceid)
3.513 +
3.514 +
3.515 +
3.516 +# Simple abstractions suitable for use with file-based representations and as
3.517 +# general copies of collections.
3.518 +
3.519 +class FreeBusyCollection(FreeBusyCollectionBase):
3.520 +
3.521 + "An abstraction for a collection of free/busy periods."
3.522 +
3.523 + def __init__(self, periods=None, mutable=True):
3.524 +
3.525 + """
3.526 + Initialise the collection with the given list of 'periods', or start an
3.527 + empty collection if no list is given. If 'mutable' is indicated, the
3.528 + collection may be changed; otherwise, an exception will be raised.
3.529 + """
3.530 +
3.531 + FreeBusyCollectionBase.__init__(self, mutable)
3.532 + self.periods = periods or []
3.533 +
3.534 + # List emulation methods.
3.535 +
3.536 + def __nonzero__(self):
3.537 + return bool(self.periods)
3.538 +
3.539 + def __iter__(self):
3.540 + return iter(self.periods)
3.541 +
3.542 + def __len__(self):
3.543 + return len(self.periods)
3.544 +
3.545 + def __getitem__(self, i):
3.546 + return self.periods[i]
3.547 +
3.548 + # Operations.
3.549 +
3.550 + def insert_period(self, period):
3.551 +
3.552 + "Insert the given 'period' into the collection."
3.553 +
3.554 + self._check_mutable()
3.555 +
3.556 + i = bisect_left(self.periods, period)
3.557 + if i == len(self.periods):
3.558 + self.periods.append(period)
3.559 + elif self.periods[i] != period:
3.560 + self.periods.insert(i, period)
3.561 +
3.562 + def remove_periods(self, periods):
3.563 +
3.564 + "Remove the given 'periods' from the collection."
3.565 +
3.566 + self._check_mutable()
3.567 +
3.568 + for period in periods:
3.569 + i = bisect_left(self.periods, period)
3.570 + if i < len(self.periods) and self.periods[i] == period:
3.571 + del self.periods[i]
3.572 +
3.573 + def remove_event_periods(self, uid, recurrenceid=None, participant=None):
3.574 +
3.575 + """
3.576 + Remove from the collection all periods associated with 'uid' and
3.577 + 'recurrenceid' (which if omitted causes the "parent" object's periods to
3.578 + be referenced).
3.579 +
3.580 + If 'participant' is specified, only remove periods for which the
3.581 + participant is given as attending.
3.582 +
3.583 + Return the removed periods.
3.584 + """
3.585 +
3.586 + self._check_mutable()
3.587 +
3.588 + removed = []
3.589 + i = 0
3.590 + while i < len(self.periods):
3.591 + fb = self.periods[i]
3.592 +
3.593 + if fb.uid == uid and fb.recurrenceid == recurrenceid and \
3.594 + (not participant or participant == fb.attendee):
3.595 +
3.596 + removed.append(self.periods[i])
3.597 + del self.periods[i]
3.598 + else:
3.599 + i += 1
3.600 +
3.601 + return removed
3.602 +
3.603 + # Specific period removal when updating event details.
3.604 +
3.605 + remove_specific_event_periods = remove_event_periods
3.606 +
3.607 + def remove_additional_periods(self, uid, recurrenceids=None):
3.608 +
3.609 + """
3.610 + Remove from the collection all periods associated with 'uid' having a
3.611 + recurrence identifier indicating an additional or modified period.
3.612 +
3.613 + If 'recurrenceids' is specified, remove all periods associated with
3.614 + 'uid' that do not have a recurrence identifier in the given list.
3.615 +
3.616 + Return the removed periods.
3.617 + """
3.618 +
3.619 + self._check_mutable()
3.620 +
3.621 + removed = []
3.622 + i = 0
3.623 + while i < len(self.periods):
3.624 + fb = self.periods[i]
3.625 + if fb.uid == uid and fb.recurrenceid and (
3.626 + recurrenceids is None or
3.627 + recurrenceids is not None and fb.recurrenceid not in recurrenceids
3.628 + ):
3.629 + removed.append(self.periods[i])
3.630 + del self.periods[i]
3.631 + else:
3.632 + i += 1
3.633 +
3.634 + return removed
3.635 +
3.636 + def remove_affected_period(self, uid, start, participant=None):
3.637 +
3.638 + """
3.639 + Remove from the collection the period associated with 'uid' that
3.640 + provides an occurrence starting at the given 'start' (provided by a
3.641 + recurrence identifier, converted to a datetime). A recurrence identifier
3.642 + is used to provide an alternative time period whilst also acting as a
3.643 + reference to the originally-defined occurrence.
3.644 +
3.645 + If 'participant' is specified, only remove periods for which the
3.646 + participant is given as attending.
3.647 +
3.648 + Return any removed period in a list.
3.649 + """
3.650 +
3.651 + self._check_mutable()
3.652 +
3.653 + removed = []
3.654 +
3.655 + search = Period(start, start)
3.656 + found = bisect_left(self.periods, search)
3.657 +
3.658 + while found < len(self.periods):
3.659 + fb = self.periods[found]
3.660 +
3.661 + # Stop looking if the start no longer matches the recurrence identifier.
3.662 +
3.663 + if fb.get_start_point() != search.get_start_point():
3.664 + break
3.665 +
3.666 + # If the period belongs to the parent object, remove it and return.
3.667 +
3.668 + if not fb.recurrenceid and uid == fb.uid and \
3.669 + (not participant or participant == fb.attendee):
3.670 +
3.671 + removed.append(self.periods[found])
3.672 + del self.periods[found]
3.673 + break
3.674 +
3.675 + # Otherwise, keep looking for a matching period.
3.676 +
3.677 + found += 1
3.678 +
3.679 + return removed
3.680 +
3.681 + def periods_from(self, period):
3.682 +
3.683 + "Return the entries in the collection at or after 'period'."
3.684 +
3.685 + first = bisect_left(self.periods, period)
3.686 + return self.periods[first:]
3.687 +
3.688 + def periods_until(self, period):
3.689 +
3.690 + "Return the entries in the collection before 'period'."
3.691 +
3.692 + last = bisect_right(self.periods, Period(period.get_end(), period.get_end(), period.get_tzid()))
3.693 + return self.periods[:last]
3.694 +
3.695 + def get_overlapping(self, periods):
3.696 +
3.697 + """
3.698 + Return the entries in the collection providing periods overlapping with
3.699 + the given sorted collection of 'periods'.
3.700 + """
3.701 +
3.702 + return get_overlapping(self.periods, periods)
3.703 +
3.704 + def remove_overlapping(self, period):
3.705 +
3.706 + "Remove all periods overlapping with 'period' from the collection."
3.707 +
3.708 + self._check_mutable()
3.709 +
3.710 + overlapping = self.get_overlapping([period])
3.711 +
3.712 + if overlapping:
3.713 + for fb in overlapping:
3.714 + self.periods.remove(fb)
3.715 +
3.716 +class FreeBusyGroupCollection(SupportAttendee, FreeBusyCollection):
3.717 +
3.718 + "A collection of quota group free/busy objects."
3.719 +
3.720 + def remove_specific_event_periods(self, uid, recurrenceid=None, attendee=None):
3.721 +
3.722 + """
3.723 + Remove from the collection all periods associated with 'uid' and
3.724 + 'recurrenceid' (which if omitted causes the "parent" object's periods to
3.725 + be referenced) and any 'attendee'.
3.726 +
3.727 + Return the removed periods.
3.728 + """
3.729 +
3.730 + self._check_mutable()
3.731 +
3.732 + removed = []
3.733 + i = 0
3.734 + while i < len(self.periods):
3.735 + fb = self.periods[i]
3.736 + if fb.uid == uid and fb.recurrenceid == recurrenceid and fb.attendee == attendee:
3.737 + removed.append(self.periods[i])
3.738 + del self.periods[i]
3.739 + else:
3.740 + i += 1
3.741 +
3.742 + return removed
3.743 +
3.744 +class FreeBusyOffersCollection(SupportExpires, FreeBusyCollection):
3.745 +
3.746 + "A collection of offered free/busy objects."
3.747 +
3.748 + pass
3.749 +
3.750 +# vim: tabstop=4 expandtab shiftwidth=4
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/imiptools/freebusy/database.py Fri May 26 18:25:23 2017 +0200
4.3 @@ -0,0 +1,471 @@
4.4 +#!/usr/bin/env python
4.5 +
4.6 +"""
4.7 +Managing free/busy period collections using database representations.
4.8 +
4.9 +Copyright (C) 2014, 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk>
4.10 +
4.11 +This program is free software; you can redistribute it and/or modify it under
4.12 +the terms of the GNU General Public License as published by the Free Software
4.13 +Foundation; either version 3 of the License, or (at your option) any later
4.14 +version.
4.15 +
4.16 +This program is distributed in the hope that it will be useful, but WITHOUT
4.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
4.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
4.19 +details.
4.20 +
4.21 +You should have received a copy of the GNU General Public License along with
4.22 +this program. If not, see <http://www.gnu.org/licenses/>.
4.23 +"""
4.24 +
4.25 +from imiptools.dates import format_datetime
4.26 +from imiptools.freebusy.common import FreeBusyCollectionBase, SupportAttendee, \
4.27 + SupportExpires, from_string, to_string
4.28 +from imiptools.sql import DatabaseOperations
4.29 +
4.30 +try:
4.31 + from cStringIO import StringIO
4.32 +except ImportError:
4.33 + from StringIO import StringIO
4.34 +
4.35 +# Conversion functions.
4.36 +
4.37 +def to_copy_string(s, encoding):
4.38 +
4.39 + """
4.40 + Encode 's' using 'encoding' as a string suitable for use in tabular data
4.41 + acceptable to the PostgreSQL COPY command with \N as null.
4.42 + """
4.43 +
4.44 + s = to_string(s, encoding)
4.45 + return s is None and "\\N" or s
4.46 +
4.47 +def to_copy_file(records):
4.48 +
4.49 + """
4.50 + Encode the given 'records' and store them in a file-like object for use with
4.51 + a tabular import mechanism. Return the file-like object.
4.52 + """
4.53 +
4.54 + io = StringIO()
4.55 + for values in records:
4.56 + l = []
4.57 + for v in values:
4.58 + l.append(to_copy_string(v, "utf-8"))
4.59 + io.write("\t".join(l))
4.60 + io.write("\n")
4.61 + io.seek(0)
4.62 + return io
4.63 +
4.64 +def quote_column(column):
4.65 +
4.66 + "Quote 'column' using the SQL keyword quoting notation."
4.67 +
4.68 + return '"%s"' % column
4.69 +
4.70 +
4.71 +
4.72 +# Collection abstractions.
4.73 +
4.74 +class FreeBusyDatabaseCollection(FreeBusyCollectionBase, DatabaseOperations):
4.75 +
4.76 + """
4.77 + An abstraction for a collection of free/busy periods stored in a database
4.78 + system.
4.79 + """
4.80 +
4.81 + def __init__(self, cursor, table_name, column_names=None, filter_values=None,
4.82 + mutable=True, paramstyle=None):
4.83 +
4.84 + """
4.85 + Initialise the collection with the given 'cursor' and with the
4.86 + 'table_name', 'column_names' and 'filter_values' configuring the
4.87 + selection of data. If 'mutable' is indicated, the collection may be
4.88 + changed; otherwise, an exception will be raised.
4.89 + """
4.90 +
4.91 + FreeBusyCollectionBase.__init__(self, mutable)
4.92 + DatabaseOperations.__init__(self, column_names, filter_values, paramstyle)
4.93 + self.cursor = cursor
4.94 + self.table_name = table_name
4.95 +
4.96 + # List emulation methods.
4.97 +
4.98 + def __nonzero__(self):
4.99 + return len(self) and True or False
4.100 +
4.101 + def __iter__(self):
4.102 + query, values = self.get_query(
4.103 + "select %(columns)s from %(table)s :condition" % {
4.104 + "columns" : self.columnlist(self.period_columns),
4.105 + "table" : self.table_name
4.106 + })
4.107 + self.cursor.execute(query, values)
4.108 + return iter(map(lambda t: self.make_period(t), self.cursor.fetchall()))
4.109 +
4.110 + def __len__(self):
4.111 + query, values = self.get_query(
4.112 + "select count(*) from %(table)s :condition" % {
4.113 + "table" : self.table_name
4.114 + })
4.115 + self.cursor.execute(query, values)
4.116 + result = self.cursor.fetchone()
4.117 + return result and int(result[0]) or 0
4.118 +
4.119 + def __getitem__(self, i):
4.120 + return list(iter(self))[i]
4.121 +
4.122 + # Operations.
4.123 +
4.124 + def insert_period(self, period):
4.125 +
4.126 + "Insert the given 'period' into the collection."
4.127 +
4.128 + self._check_mutable()
4.129 +
4.130 + columns, values = self.period_columns, period.as_tuple(string_datetimes=True)
4.131 +
4.132 + query, values = self.get_query(
4.133 + "insert into %(table)s (:columns) values (:values)" % {
4.134 + "table" : self.table_name
4.135 + },
4.136 + columns, [to_string(v, "utf-8") for v in values])
4.137 +
4.138 + self.cursor.execute(query, values)
4.139 +
4.140 + def insert_periods(self, periods):
4.141 +
4.142 + "Insert the given 'periods' into the collection."
4.143 +
4.144 + if not hasattr(self.cursor, "copy_from"):
4.145 + return FreeBusyCollectionBase.insert_periods(self, periods)
4.146 +
4.147 + self._check_mutable()
4.148 +
4.149 + columns = self.merge_default_columns(self.period_columns)
4.150 +
4.151 + all_values = []
4.152 + for period in periods:
4.153 + all_values.append(self.merge_default_values(period.as_tuple(string_datetimes=True)))
4.154 +
4.155 + f = to_copy_file(all_values)
4.156 +
4.157 + # Copy from the file-like object to the table.
4.158 +
4.159 + self.cursor.copy_from(f, self.table_name, columns=map(quote_column, columns))
4.160 +
4.161 + def remove_periods(self, periods):
4.162 +
4.163 + "Remove the given 'periods' from the collection."
4.164 +
4.165 + self._check_mutable()
4.166 +
4.167 + for period in periods:
4.168 + values = period.as_tuple(string_datetimes=True)
4.169 +
4.170 + query, values = self.get_query(
4.171 + "delete from %(table)s :condition" % {
4.172 + "table" : self.table_name
4.173 + },
4.174 + self.period_columns, [to_string(v, "utf-8") for v in values])
4.175 +
4.176 + self.cursor.execute(query, values)
4.177 +
4.178 + def remove_event_periods(self, uid, recurrenceid=None, participant=None):
4.179 +
4.180 + """
4.181 + Remove from the collection all periods associated with 'uid' and
4.182 + 'recurrenceid' (which if omitted causes the "parent" object's periods to
4.183 + be referenced).
4.184 +
4.185 + If 'participant' is specified, only remove periods for which the
4.186 + participant is given as attending.
4.187 +
4.188 + Return the removed periods.
4.189 + """
4.190 +
4.191 + self._check_mutable()
4.192 +
4.193 + columns, values = ["object_uid"], [uid]
4.194 +
4.195 + if recurrenceid:
4.196 + columns.append("object_recurrenceid")
4.197 + values.append(recurrenceid)
4.198 + else:
4.199 + columns.append("object_recurrenceid is null")
4.200 +
4.201 + if participant:
4.202 + columns.append("attendee")
4.203 + values.append(participant)
4.204 +
4.205 + query, _values = self.get_query(
4.206 + "select %(columns)s from %(table)s :condition" % {
4.207 + "columns" : self.columnlist(self.period_columns),
4.208 + "table" : self.table_name
4.209 + },
4.210 + columns, values)
4.211 +
4.212 + self.cursor.execute(query, _values)
4.213 + removed = self.cursor.fetchall()
4.214 +
4.215 + query, values = self.get_query(
4.216 + "delete from %(table)s :condition" % {
4.217 + "table" : self.table_name
4.218 + },
4.219 + columns, values)
4.220 +
4.221 + self.cursor.execute(query, values)
4.222 +
4.223 + return map(lambda t: self.make_period(t), removed)
4.224 +
4.225 + # Specific period removal when updating event details.
4.226 +
4.227 + remove_specific_event_periods = remove_event_periods
4.228 +
4.229 + def remove_additional_periods(self, uid, recurrenceids=None):
4.230 +
4.231 + """
4.232 + Remove from the collection all periods associated with 'uid' having a
4.233 + recurrence identifier indicating an additional or modified period.
4.234 +
4.235 + If 'recurrenceids' is specified, remove all periods associated with
4.236 + 'uid' that do not have a recurrence identifier in the given list.
4.237 +
4.238 + Return the removed periods.
4.239 + """
4.240 +
4.241 + self._check_mutable()
4.242 +
4.243 + if not recurrenceids:
4.244 + columns, values = ["object_uid", "object_recurrenceid is not null"], [uid]
4.245 + else:
4.246 + columns, values = ["object_uid", "object_recurrenceid not in ?", "object_recurrenceid is not null"], [uid, tuple(recurrenceids)]
4.247 +
4.248 + query, _values = self.get_query(
4.249 + "select %(columns)s from %(table)s :condition" % {
4.250 + "columns" : self.columnlist(self.period_columns),
4.251 + "table" : self.table_name
4.252 + },
4.253 + columns, values)
4.254 +
4.255 + self.cursor.execute(query, _values)
4.256 + removed = self.cursor.fetchall()
4.257 +
4.258 + query, values = self.get_query(
4.259 + "delete from %(table)s :condition" % {
4.260 + "table" : self.table_name
4.261 + },
4.262 + columns, values)
4.263 +
4.264 + self.cursor.execute(query, values)
4.265 +
4.266 + return map(lambda t: self.make_period(t), removed)
4.267 +
4.268 + def remove_affected_period(self, uid, start, participant=None):
4.269 +
4.270 + """
4.271 + Remove from the collection the period associated with 'uid' that
4.272 + provides an occurrence starting at the given 'start' (provided by a
4.273 + recurrence identifier, converted to a datetime). A recurrence identifier
4.274 + is used to provide an alternative time period whilst also acting as a
4.275 + reference to the originally-defined occurrence.
4.276 +
4.277 + If 'participant' is specified, only remove periods for which the
4.278 + participant is given as attending.
4.279 +
4.280 + Return any removed period in a list.
4.281 + """
4.282 +
4.283 + self._check_mutable()
4.284 +
4.285 + start = format_datetime(start)
4.286 +
4.287 + columns, values = ["object_uid", "start", "object_recurrenceid is null"], [uid, start]
4.288 +
4.289 + if participant:
4.290 + columns.append("attendee")
4.291 + values.append(participant)
4.292 +
4.293 + query, _values = self.get_query(
4.294 + "select %(columns)s from %(table)s :condition" % {
4.295 + "columns" : self.columnlist(self.period_columns),
4.296 + "table" : self.table_name
4.297 + },
4.298 + columns, values)
4.299 +
4.300 + self.cursor.execute(query, _values)
4.301 + removed = self.cursor.fetchall()
4.302 +
4.303 + query, values = self.get_query(
4.304 + "delete from %(table)s :condition" % {
4.305 + "table" : self.table_name
4.306 + },
4.307 + columns, values)
4.308 +
4.309 + self.cursor.execute(query, values)
4.310 +
4.311 + return map(lambda t: self.make_period(t), removed)
4.312 +
4.313 + def periods_from(self, period):
4.314 +
4.315 + "Return the entries in the collection at or after 'period'."
4.316 +
4.317 + start = format_datetime(period.get_start_point())
4.318 +
4.319 + columns, values = [], []
4.320 +
4.321 + if start:
4.322 + columns.append("start >= ?")
4.323 + values.append(start)
4.324 +
4.325 + query, values = self.get_query(
4.326 + "select %(columns)s from %(table)s :condition" % {
4.327 + "columns" : self.columnlist(self.period_columns),
4.328 + "table" : self.table_name
4.329 + },
4.330 + columns, values)
4.331 +
4.332 + self.cursor.execute(query, values)
4.333 +
4.334 + return map(lambda t: self.make_period(t), self.cursor.fetchall())
4.335 +
4.336 + def periods_until(self, period):
4.337 +
4.338 + "Return the entries in the collection before 'period'."
4.339 +
4.340 + end = format_datetime(period.get_end_point())
4.341 +
4.342 + columns, values = [], []
4.343 +
4.344 + if end:
4.345 + columns.append("start < ?")
4.346 + values.append(end)
4.347 +
4.348 + query, values = self.get_query(
4.349 + "select %(columns)s from %(table)s :condition" % {
4.350 + "columns" : self.columnlist(self.period_columns),
4.351 + "table" : self.table_name
4.352 + },
4.353 + columns, values)
4.354 +
4.355 + self.cursor.execute(query, values)
4.356 +
4.357 + return map(lambda t: self.make_period(t), self.cursor.fetchall())
4.358 +
4.359 + def get_overlapping(self, periods):
4.360 +
4.361 + """
4.362 + Return the entries in the collection providing periods overlapping with
4.363 + the given sorted collection of 'periods'.
4.364 + """
4.365 +
4.366 + overlapping = set()
4.367 +
4.368 + for period in periods:
4.369 + columns, values = self._get_period_values(period)
4.370 +
4.371 + query, values = self.get_query(
4.372 + "select %(columns)s from %(table)s :condition" % {
4.373 + "columns" : self.columnlist(self.period_columns),
4.374 + "table" : self.table_name
4.375 + },
4.376 + columns, values)
4.377 +
4.378 + self.cursor.execute(query, values)
4.379 +
4.380 + overlapping.update(map(lambda t: self.make_period(t), self.cursor.fetchall()))
4.381 +
4.382 + overlapping = list(overlapping)
4.383 + overlapping.sort()
4.384 + return overlapping
4.385 +
4.386 + def remove_overlapping(self, period):
4.387 +
4.388 + "Remove all periods overlapping with 'period' from the collection."
4.389 +
4.390 + self._check_mutable()
4.391 +
4.392 + columns, values = self._get_period_values(period)
4.393 +
4.394 + query, values = self.get_query(
4.395 + "delete from %(table)s :condition" % {
4.396 + "table" : self.table_name
4.397 + },
4.398 + columns, values)
4.399 +
4.400 + self.cursor.execute(query, values)
4.401 +
4.402 + def _get_period_values(self, period):
4.403 +
4.404 + start = format_datetime(period.get_start_point())
4.405 + end = format_datetime(period.get_end_point())
4.406 +
4.407 + columns, values = [], []
4.408 +
4.409 + if end:
4.410 + columns.append("start < ?")
4.411 + values.append(end)
4.412 + if start:
4.413 + columns.append("end > ?")
4.414 + values.append(start)
4.415 +
4.416 + return columns, values
4.417 +
4.418 +class FreeBusyGroupDatabaseCollection(SupportAttendee, FreeBusyDatabaseCollection):
4.419 +
4.420 + "A collection of quota group free/busy objects."
4.421 +
4.422 + def remove_specific_event_periods(self, uid, recurrenceid=None, attendee=None):
4.423 +
4.424 + """
4.425 + Remove from the collection all periods associated with 'uid' and
4.426 + 'recurrenceid' (which if omitted causes the "parent" object's periods to
4.427 + be referenced) and any 'attendee'.
4.428 +
4.429 + Return the removed periods.
4.430 + """
4.431 +
4.432 + self._check_mutable()
4.433 +
4.434 + columns, values = ["object_uid"], [uid]
4.435 +
4.436 + if recurrenceid:
4.437 + columns.append("object_recurrenceid")
4.438 + values.append(recurrenceid)
4.439 + else:
4.440 + columns.append("object_recurrenceid is null")
4.441 +
4.442 + if attendee:
4.443 + columns.append("attendee")
4.444 + values.append(attendee)
4.445 + else:
4.446 + columns.append("attendee is null")
4.447 +
4.448 + query, _values = self.get_query(
4.449 + "select %(columns)s from %(table)s :condition" % {
4.450 + "columns" : self.columnlist(self.period_columns),
4.451 + "table" : self.table_name
4.452 + },
4.453 + columns, values)
4.454 +
4.455 + self.cursor.execute(query, _values)
4.456 + removed = self.cursor.fetchall()
4.457 +
4.458 + query, values = self.get_query(
4.459 + "delete from %(table)s :condition" % {
4.460 + "table" : self.table_name
4.461 + },
4.462 + columns, values)
4.463 +
4.464 + self.cursor.execute(query, values)
4.465 +
4.466 + return map(lambda t: self.make_period(t), removed)
4.467 +
4.468 +class FreeBusyOffersDatabaseCollection(SupportExpires, FreeBusyDatabaseCollection):
4.469 +
4.470 + "A collection of offered free/busy objects."
4.471 +
4.472 + pass
4.473 +
4.474 +# vim: tabstop=4 expandtab shiftwidth=4
5.1 --- a/imiptools/stores/database/common.py Fri May 26 16:52:25 2017 +0200
5.2 +++ b/imiptools/stores/database/common.py Fri May 26 18:25:23 2017 +0200
5.3 @@ -24,9 +24,9 @@
5.4 from datetime import datetime
5.5 from imiptools.data import Object, parse_string, to_string
5.6 from imiptools.dates import format_datetime, get_datetime, to_timezone
5.7 -from imiptools.freebusy import FreeBusyDatabaseCollection, \
5.8 - FreeBusyGroupDatabaseCollection, \
5.9 - FreeBusyOffersDatabaseCollection
5.10 +from imiptools.freebusy.database import FreeBusyDatabaseCollection, \
5.11 + FreeBusyGroupDatabaseCollection, \
5.12 + FreeBusyOffersDatabaseCollection
5.13 from imiptools.sql import DatabaseOperations
5.14
5.15 def first(l): return l[0]
6.1 --- a/imiptools/stores/file.py Fri May 26 16:52:25 2017 +0200
6.2 +++ b/imiptools/stores/file.py Fri May 26 18:25:23 2017 +0200
6.3 @@ -27,8 +27,10 @@
6.4 from imiptools.dates import format_datetime, get_datetime, to_timezone
6.5 from imiptools.filesys import fix_permissions, FileBase
6.6 from imiptools.freebusy import FreeBusyPeriod, FreeBusyGroupPeriod, \
6.7 - FreeBusyOfferPeriod, FreeBusyCollection, \
6.8 - FreeBusyGroupCollection, FreeBusyOffersCollection
6.9 + FreeBusyOfferPeriod, \
6.10 + FreeBusyCollection, \
6.11 + FreeBusyGroupCollection, \
6.12 + FreeBusyOffersCollection
6.13 from imiptools.text import get_table, set_defaults
6.14 from os.path import isdir, isfile, join
6.15 from os import listdir, remove, rmdir
7.1 --- a/tools/install.sh Fri May 26 16:52:25 2017 +0200
7.2 +++ b/tools/install.sh Fri May 26 18:25:23 2017 +0200
7.3 @@ -47,6 +47,7 @@
7.4 # Package modules.
7.5
7.6 for DIR in "$INSTALL_DIR/imiptools" \
7.7 + "$INSTALL_DIR/imiptools/freebusy" \
7.8 "$INSTALL_DIR/imiptools/stores" \
7.9 "$INSTALL_DIR/imiptools/stores/database" \
7.10 "$INSTALL_DIR/imiptools/handlers" \
7.11 @@ -66,6 +67,7 @@
7.12 # Copy modules into the installation directory.
7.13
7.14 cp imiptools/*.py "$INSTALL_DIR/imiptools/"
7.15 +cp imiptools/freebusy/*.py "$INSTALL_DIR/imiptools/freebusy/"
7.16 cp imiptools/stores/*.py "$INSTALL_DIR/imiptools/stores/"
7.17 cp imiptools/stores/database/*.py "$INSTALL_DIR/imiptools/stores/database/"
7.18 cp imiptools/handlers/*.py "$INSTALL_DIR/imiptools/handlers/"
7.19 @@ -77,6 +79,10 @@
7.20 rm "$INSTALL_DIR/imiptools/handlers/scheduling.py"*
7.21 fi
7.22
7.23 +if [ -e "$INSTALL_DIR/imiptools/freebusy.py" ]; then
7.24 + rm "$INSTALL_DIR/imiptools/freebusy.py"*
7.25 +fi
7.26 +
7.27 if [ -e "$INSTALL_DIR/imip_store.py" ]; then
7.28 rm "$INSTALL_DIR/imip_store.py"*
7.29 fi
8.1 --- a/tools/make_freebusy.py Fri May 26 16:52:25 2017 +0200
8.2 +++ b/tools/make_freebusy.py Fri May 26 18:25:23 2017 +0200
8.3 @@ -36,7 +36,7 @@
8.4 from codecs import getwriter
8.5 from imiptools.config import settings
8.6 from imiptools.client import Client
8.7 -from imiptools.data import get_window_end, Object
8.8 +from imiptools.data import get_window_end
8.9 from imiptools.dates import get_default_timezone, to_utc_datetime
8.10 from imiptools.freebusy import FreeBusyCollection, FreeBusyGroupCollection, \
8.11 FreeBusyGroupPeriod