paul@48 | 1 | #!/usr/bin/env python |
paul@48 | 2 | |
paul@48 | 3 | from bisect import bisect_left, insort_left |
paul@48 | 4 | |
paul@48 | 5 | # Time management. |
paul@48 | 6 | |
paul@72 | 7 | def have_conflict(freebusy, periods, get_conflicts=False): |
paul@72 | 8 | |
paul@72 | 9 | """ |
paul@72 | 10 | Return whether any period in 'freebusy' overlaps with the given 'periods', |
paul@72 | 11 | returning a collection of such overlapping periods if 'get_conflicts' is |
paul@72 | 12 | set to a true value. |
paul@72 | 13 | """ |
paul@72 | 14 | |
paul@72 | 15 | conflicts = [] |
paul@72 | 16 | for start, end in periods: |
paul@72 | 17 | period = period_overlaps(freebusy, (start, end)) |
paul@72 | 18 | if period: |
paul@72 | 19 | if get_conflicts: |
paul@72 | 20 | conflicts.append(period) |
paul@72 | 21 | else: |
paul@72 | 22 | return True |
paul@72 | 23 | if get_conflicts: |
paul@72 | 24 | return conflicts |
paul@72 | 25 | else: |
paul@72 | 26 | return False |
paul@72 | 27 | |
paul@48 | 28 | def insert_period(freebusy, period): |
paul@48 | 29 | insort_left(freebusy, period) |
paul@48 | 30 | |
paul@48 | 31 | def remove_period(freebusy, uid): |
paul@48 | 32 | i = 0 |
paul@48 | 33 | while i < len(freebusy): |
paul@48 | 34 | t = freebusy[i] |
paul@48 | 35 | if len(t) >= 3 and t[2] == uid: |
paul@48 | 36 | del freebusy[i] |
paul@48 | 37 | else: |
paul@48 | 38 | i += 1 |
paul@48 | 39 | |
paul@48 | 40 | def period_overlaps(freebusy, period): |
paul@72 | 41 | |
paul@72 | 42 | """ |
paul@72 | 43 | Return from 'freebusy' any period overlapping with the given 'period', or |
paul@72 | 44 | None if no overlap occurs. |
paul@72 | 45 | """ |
paul@72 | 46 | |
paul@48 | 47 | dtstart, dtend = period[:2] |
paul@48 | 48 | i = bisect_left(freebusy, (dtstart, dtend, None)) |
paul@48 | 49 | return ( |
paul@72 | 50 | i < len(freebusy) and (dtend is None or freebusy[i][0] < dtend) and freebusy[i] |
paul@48 | 51 | or |
paul@72 | 52 | i > 0 and freebusy[i - 1][1] > dtstart and freebusy[i - 1] |
paul@72 | 53 | or |
paul@72 | 54 | None |
paul@48 | 55 | ) |
paul@48 | 56 | |
paul@48 | 57 | # vim: tabstop=4 expandtab shiftwidth=4 |