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@74 | 17 | overlapping = period_overlaps(freebusy, (start, end), get_conflicts) |
paul@74 | 18 | if overlapping: |
paul@72 | 19 | if get_conflicts: |
paul@74 | 20 | conflicts += overlapping |
paul@72 | 21 | else: |
paul@72 | 22 | return True |
paul@74 | 23 | |
paul@72 | 24 | if get_conflicts: |
paul@72 | 25 | return conflicts |
paul@72 | 26 | else: |
paul@72 | 27 | return False |
paul@72 | 28 | |
paul@48 | 29 | def insert_period(freebusy, period): |
paul@48 | 30 | insort_left(freebusy, period) |
paul@48 | 31 | |
paul@48 | 32 | def remove_period(freebusy, uid): |
paul@48 | 33 | i = 0 |
paul@48 | 34 | while i < len(freebusy): |
paul@48 | 35 | t = freebusy[i] |
paul@48 | 36 | if len(t) >= 3 and t[2] == uid: |
paul@48 | 37 | del freebusy[i] |
paul@48 | 38 | else: |
paul@48 | 39 | i += 1 |
paul@48 | 40 | |
paul@74 | 41 | def period_overlaps(freebusy, period, get_periods=False): |
paul@72 | 42 | |
paul@72 | 43 | """ |
paul@74 | 44 | Return whether any period in 'freebusy' overlaps with the given 'period', |
paul@74 | 45 | returning a collection of overlapping periods if 'get_periods' is set to a |
paul@74 | 46 | true value. |
paul@72 | 47 | """ |
paul@72 | 48 | |
paul@48 | 49 | dtstart, dtend = period[:2] |
paul@74 | 50 | found = bisect_left(freebusy, (dtstart, dtend, None)) |
paul@74 | 51 | |
paul@74 | 52 | overlapping = [] |
paul@74 | 53 | |
paul@74 | 54 | # Find earlier overlapping periods. |
paul@74 | 55 | |
paul@74 | 56 | i = found |
paul@74 | 57 | |
paul@74 | 58 | while i > 0 and freebusy[i - 1][1] > dtstart: |
paul@74 | 59 | if get_periods: |
paul@74 | 60 | overlapping.insert(0, freebusy[i - 1]) |
paul@74 | 61 | else: |
paul@74 | 62 | return True |
paul@74 | 63 | i -= 1 |
paul@74 | 64 | |
paul@74 | 65 | # Find later overlapping periods. |
paul@74 | 66 | |
paul@74 | 67 | i = found |
paul@74 | 68 | |
paul@74 | 69 | while i < len(freebusy) and (dtend is None or freebusy[i][0] < dtend): |
paul@74 | 70 | if get_periods: |
paul@74 | 71 | overlapping.append(freebusy[i]) |
paul@74 | 72 | else: |
paul@74 | 73 | return True |
paul@74 | 74 | i += 1 |
paul@74 | 75 | |
paul@74 | 76 | if get_periods: |
paul@74 | 77 | return overlapping |
paul@74 | 78 | else: |
paul@74 | 79 | return False |
paul@48 | 80 | |
paul@48 | 81 | # vim: tabstop=4 expandtab shiftwidth=4 |