-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathschedule
executable file
·334 lines (257 loc) · 9.87 KB
/
schedule
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
#!/usr/bin/env python3
"Schedule a bunch of desired meetings."
import json
from datetime import datetime, time, timedelta
import pendulum
from apiclient.discovery import build
from httplib2 import Http
from credentials import creds
class Interval:
"Represent a time interval as start (inclusive) and end (exlcusive)."
def __init__(self, start, end):
self.start = start
self.end = end
def __eq__(self, other):
return self.start == other.start and self.end == other.end
def __hash__(self):
return hash((self.start, self.end))
def __repr__(self):
return "{} to {}".format(self.start.isoformat(), self.end.isoformat())
def before(self, other):
return self.end <= other.start
def after(self, other):
return self.start >= other.end
def overlaps(self, other):
return not (self.before(other) or self.after(other))
def from_calendar(cal):
return Interval(pendulum.parse(cal["start"]), pendulum.parse(cal["end"]))
class Meeting:
"Meeting to be scheduled. Attendees and slots are filled in by the scheduling process."
def __init__(self, summary, minutes, invitees, attendees=None, slots=None):
self.summary = summary
self.minutes = minutes
self.invitees = invitees # Who's on the invite, may includes groups
self.attendees = attendees # Actual people after expanding groups
self.slots = slots
def __repr__(self):
return json.dumps(
{
"summary": self.summary,
"minutes": self.minutes,
"invitees": list(self.invitees),
"attendees": list(self.attendees),
"slots": ["{}".format(s) for s in self.slots],
}
)
def scheduled(self):
return len(self.slots) == 1
def copy(self):
return Meeting(
self.summary, self.minutes, self.invitees, self.attendees, set(self.slots)
)
def busy(emails, start_day, start_time, end_time, days):
"Map of intervals each person is busy according to their calendar."
service = build("calendar", "v3", http=creds.authorize(Http()))
data = (
service.freebusy()
.query(
body={
"timeMin": datetime.combine(start_day, start_time).isoformat(),
"timeMax": datetime.combine(
start_day + timedelta(days=days), end_time
).isoformat(),
"items": [{"id": e} for e in emails],
}
)
.execute()
)
busy_times = {
name: [Interval.from_calendar(x) for x in x["busy"]]
for name, x in data["calendars"].items()
}
groups = (
{g: x["calendars"] for g, x in data["groups"].items()}
if "groups" in data
else {}
)
return busy_times, groups
def schedule_meeting(meeting, calendar, location=None, description=None):
"Schedule a meeting on the given calendar with the given location and description."
service = build("calendar", "v3", http=creds.authorize(Http()))
body = {
"summary": meeting.summary,
"location": location or "",
"description": description or "",
"start": {"dateTime": item(meeting.slots).start.isoformat()},
"end": {"dateTime": item(meeting.slots).end.isoformat()},
"attendees": [{"email": e} for e in meeting.invitees if e != calendar],
}
return service.events().insert(calendarId=calendar, body=body).execute()
def working_slots(
start_day,
start_time,
end_time,
now,
days=1,
minutes=30,
increment=15,
daysofweek={0, 1, 2, 3, 4},
):
"Get all slots during working hours in a given time range."
ss = []
for d in range(days):
day = start_day + timedelta(days=d)
if day.weekday() in daysofweek:
start = datetime.combine(day, start_time)
end = datetime.combine(day, end_time)
length = timedelta(minutes=minutes)
incr = timedelta(minutes=increment)
s = start
while (s + length) <= end:
e = s + length
if s > now:
ss.append(Interval(s, e))
s += incr
return ss
def schedules(meetings):
"Generator of all possible schedules."
if meetings is None:
return None
elif all(m.scheduled() for m in meetings.values()):
yield meetings
else:
unscheduled = [m for m in meetings if len(meetings[m].slots) > 1]
for m in sorted(unscheduled, key=lambda m: len(meetings[m].slots)):
for s in sorted(meetings[m].slots, key=lambda s: s.start):
copied = {m: meeting.copy() for m, meeting in meetings.items()}
yield from schedules(assign(copied, m, s))
def assign(meetings, m, s):
"Assign slot s to meeting m, propagating consequences."
return meetings if eliminate(meetings, m, lambda x: x != s) else None
def eliminate(meetings, m, fn):
"Eliminate slots from meeting m and propagate consequences."
to_eliminate = {s for s in meetings[m].slots if fn(s)}
if to_eliminate:
meetings[m].slots -= to_eliminate
left = len(meetings[m].slots)
if left == 0:
return None
elif left == 1:
s = item(meetings[m].slots)
attendees = meetings[m].attendees
other_meetings = {
m for m in meetings if attendees & meetings[m].attendees
} - {m}
if not all(
eliminate(meetings, m2, lambda x: x.overlaps(s))
for m2 in other_meetings
):
return None
return meetings
def item(s):
return next(iter(s))
def schedule(meetings, start_day, start_time, end_time, days, now):
"Find the first possible schedule for the set of meetings."
emails = set(a for m in meetings.values() for a in m.invitees)
busy_times, groups = busy(emails, start_day, start_time, end_time, days)
# First fill in the basic slots for the desired length of meeting
# and expand the attendees list.
for m, meeting in meetings.items():
meeting.slots = set(
working_slots(start_day, start_time, end_time, now, days, meeting.minutes)
)
meeting.attendees = expand(meeting.invitees, groups)
# Now that every meeting is set up we can eliminate busy times and
# potentially take advantage of contstraint propagation.
for m, meeting in meetings.items():
if not (eliminate_busy(meetings, m, busy_times)):
return None
return next(schedules(meetings), None)
def eliminate_busy(meetings, m, busy):
"Eliminate the slots where one of the attendees is busy."
meeting = meetings[m]
for a in meeting.attendees:
to_eliminate = busy_slots(sorted(meeting.slots, key=lambda x: x.start), busy[a])
if not eliminate(meetings, m, lambda x: x in to_eliminate):
return None
return meetings
def expand(invitees, groups):
"Expand the invitees (which may include groups) into actual people."
expansion = set()
for i in invitees:
expansion |= set(groups[i]) if i in groups else {i}
return expansion
def busy_slots(slots, busy):
"Find intervals in slots that overlap busy intervals."
def walk(slots, busy):
while slots and busy:
s = slots[0]
b = busy[0]
if s.before(b):
slots.pop(0)
elif s.after(b):
busy.pop(0)
else:
yield slots.pop(0)
return list(walk(slots[:], busy[:]))
def print_schedule(meetings):
"Print a human readable schedule."
for m in sorted(meetings.values(), key=lambda m: item(m.slots).start):
s = item(m.slots)
print(
"{:30} {} to {}".format(
m.summary,
s.start.strftime("%a, %b %d %I:%M %p"),
s.end.strftime("%I:%M %p (%Z)"),
)
)
def schedule_meetings(meetings, calendar, location=None, description=None):
"Actually schedule the meetings on the given calendar at the given location."
for m in sorted(meetings.values(), key=lambda m: item(m.slots).start):
r = schedule_meeting(m, calendar, location, description)
print(json.dumps(r, indent=2))
if __name__ == "__main__":
import argparse
import re
pacific = pendulum.timezone("US/Pacific")
start_time = time(9, 0, tzinfo=pacific)
end_time = time(14, 0, tzinfo=pacific)
days = 60
now = datetime.now(tz=pacific)
pat = re.compile(r"^\[(\d+)\] *(.*?): *(.*)$")
p = argparse.ArgumentParser(description=__doc__)
p.add_argument(
"meetings",
help="File containing meeting specs, one per line.",
type=argparse.FileType(),
)
p.add_argument(
"--calendar",
dest="calendar",
help="Email address of the calendar to create the meetings on. If not provided, just print times meetings would be scheduled.",
)
p.add_argument(
"--description",
dest="description",
help="Description for meeting.",
default="")
p.add_argument(
"--start",
dest="start",
help="First possible day.")
args = p.parse_args()
start_day = pendulum.parse(args.start, tz=pacific) if args.start else pendulum.today()
def to_meeting(line):
m = pat.match(line)
return Meeting(
m.group(2), int(m.group(1)), frozenset(re.split(r", *", m.group(3)))
)
meetings = {id: to_meeting(line[:-1]) for id, line in enumerate(args.meetings)}
meetings = schedule(meetings, start_day, start_time, end_time, days, now)
if meetings is None:
print("No way to schedule all meetings. Maybe time to become a goat farmer.")
else:
if not args.calendar:
print_schedule(meetings)
else:
schedule_meetings(meetings, args.calendar, description=args.description)