1 #!/usr/bin/env python 2 3 """ 4 A Web interface to an event calendar. 5 6 Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from datetime import datetime 23 from imiptools.data import get_address, get_uri, uri_values 24 from imiptools.dates import format_datetime, get_datetime, \ 25 get_datetime_item, get_end_of_day, get_start_of_day, \ 26 get_start_of_next_day, get_timestamp, ends_on_same_day, \ 27 to_timezone 28 from imiptools.period import add_day_start_points, add_empty_days, add_slots, \ 29 get_scale, get_slots, get_spans, partition_by_day, Point 30 from imipweb.resource import ResourceClient 31 32 class CalendarPage(ResourceClient): 33 34 "A request handler for the calendar page." 35 36 # Request logic methods. 37 38 def handle_newevent(self): 39 40 """ 41 Handle any new event operation, creating a new event and redirecting to 42 the event page for further activity. 43 """ 44 45 # Handle a submitted form. 46 47 args = self.env.get_args() 48 49 if not args.has_key("newevent"): 50 return 51 52 # Create a new event using the available information. 53 54 slots = args.get("slot", []) 55 participants = args.get("participants", []) 56 57 if not slots: 58 return 59 60 # Obtain the user's timezone. 61 62 tzid = self.get_tzid() 63 64 # Coalesce the selected slots. 65 66 slots.sort() 67 coalesced = [] 68 last = None 69 70 for slot in slots: 71 start, end = (slot.split("-", 1) + [None])[:2] 72 start = get_datetime(start, {"TZID" : tzid}) 73 end = end and get_datetime(end, {"TZID" : tzid}) or get_start_of_next_day(start, tzid) 74 75 if last: 76 last_start, last_end = last 77 78 # Merge adjacent dates and datetimes. 79 80 if start == last_end or \ 81 not isinstance(start, datetime) and \ 82 get_start_of_day(last_end, tzid) == get_start_of_day(start, tzid): 83 84 last = last_start, end 85 continue 86 87 # Handle datetimes within dates. 88 # Datetime periods are within single days and are therefore 89 # discarded. 90 91 elif not isinstance(last_start, datetime) and \ 92 get_start_of_day(start, tzid) == get_start_of_day(last_start, tzid): 93 94 continue 95 96 # Add separate dates and datetimes. 97 98 else: 99 coalesced.append(last) 100 101 last = start, end 102 103 if last: 104 coalesced.append(last) 105 106 # Invent a unique identifier. 107 108 utcnow = get_timestamp() 109 uid = "imip-agent-%s-%s" % (utcnow, get_address(self.user)) 110 111 # Create a calendar object and store it as a request. 112 113 record = [] 114 rwrite = record.append 115 116 # Define a single occurrence if only one coalesced slot exists. 117 118 start, end = coalesced[0] 119 start_value, start_attr = get_datetime_item(start, tzid) 120 end_value, end_attr = get_datetime_item(end, tzid) 121 122 rwrite(("UID", {}, uid)) 123 rwrite(("SUMMARY", {}, "New event at %s" % utcnow)) 124 rwrite(("DTSTAMP", {}, utcnow)) 125 rwrite(("DTSTART", start_attr, start_value)) 126 rwrite(("DTEND", end_attr, end_value)) 127 rwrite(("ORGANIZER", {}, self.user)) 128 129 participants = uri_values(filter(None, participants)) 130 131 for participant in participants: 132 rwrite(("ATTENDEE", {"RSVP" : "TRUE", "PARTSTAT" : "NEEDS-ACTION"}, participant)) 133 134 if self.user not in participants: 135 rwrite(("ATTENDEE", {"PARTSTAT" : "ACCEPTED"}, self.user)) 136 137 # Define additional occurrences if many slots are defined. 138 139 rdates = [] 140 141 for start, end in coalesced[1:]: 142 start_value, start_attr = get_datetime_item(start, tzid) 143 end_value, end_attr = get_datetime_item(end, tzid) 144 rdates.append("%s/%s" % (start_value, end_value)) 145 146 if rdates: 147 rwrite(("RDATE", {"VALUE" : "PERIOD", "TZID" : tzid}, rdates)) 148 149 node = ("VEVENT", {}, record) 150 151 self.store.set_event(self.user, uid, None, node=node) 152 self.store.queue_request(self.user, uid) 153 154 # Redirect to the object (or the first of the objects), where instead of 155 # attendee controls, there will be organiser controls. 156 157 self.redirect(self.link_to(uid)) 158 159 # Page fragment methods. 160 161 def show_requests_on_page(self): 162 163 "Show requests for the current user." 164 165 page = self.page 166 167 # NOTE: This list could be more informative, but it is envisaged that 168 # NOTE: the requests would be visited directly anyway. 169 170 requests = self._get_requests() 171 172 page.div(id="pending-requests") 173 174 if requests: 175 page.p("Pending requests:") 176 177 page.ul() 178 179 for uid, recurrenceid, request_type in requests: 180 obj = self._get_object(uid, recurrenceid) 181 if obj: 182 page.li() 183 page.a(obj.get_value("SUMMARY"), href="#request-%s-%s" % (uid, recurrenceid or "")) 184 page.li.close() 185 186 page.ul.close() 187 188 else: 189 page.p("There are no pending requests.") 190 191 page.div.close() 192 193 def show_participants_on_page(self): 194 195 "Show participants for scheduling purposes." 196 197 page = self.page 198 args = self.env.get_args() 199 participants = args.get("participants", []) 200 201 try: 202 for name, value in args.items(): 203 if name.startswith("remove-participant-"): 204 i = int(name[len("remove-participant-"):]) 205 del participants[i] 206 break 207 except ValueError: 208 pass 209 210 # Trim empty participants. 211 212 while participants and not participants[-1].strip(): 213 participants.pop() 214 215 # Show any specified participants together with controls to remove and 216 # add participants. 217 218 page.div(id="participants") 219 220 page.p("Participants for scheduling:") 221 222 for i, participant in enumerate(participants): 223 page.p() 224 page.input(name="participants", type="text", value=participant) 225 page.input(name="remove-participant-%d" % i, type="submit", value="Remove") 226 page.p.close() 227 228 page.p() 229 page.input(name="participants", type="text") 230 page.input(name="add-participant", type="submit", value="Add") 231 page.p.close() 232 233 page.div.close() 234 235 return participants 236 237 # Full page output methods. 238 239 def show(self): 240 241 "Show the calendar for the current user." 242 243 self.new_page(title="Calendar") 244 page = self.page 245 246 handled = self.handle_newevent() 247 freebusy = self.store.get_freebusy(self.user) 248 249 if not freebusy: 250 page.p("No events scheduled.") 251 return 252 253 # Form controls are used in various places on the calendar page. 254 255 page.form(method="POST") 256 257 self.show_requests_on_page() 258 participants = self.show_participants_on_page() 259 260 # Obtain the user's timezone. 261 262 tzid = self.get_tzid() 263 264 # Day view: start at the earliest known day and produce days until the 265 # latest known day, perhaps with expandable sections of empty days. 266 267 # Month view: start at the earliest known month and produce months until 268 # the latest known month, perhaps with expandable sections of empty 269 # months. 270 271 # Details of users to invite to new events could be superimposed on the 272 # calendar. 273 274 # Requests are listed and linked to their tentative positions in the 275 # calendar. Other participants are also shown. 276 277 request_summary = self._get_request_summary() 278 279 period_groups = [request_summary, freebusy] 280 period_group_types = ["request", "freebusy"] 281 period_group_sources = ["Pending requests", "Your schedule"] 282 283 for i, participant in enumerate(participants): 284 period_groups.append(self.store.get_freebusy_for_other(self.user, get_uri(participant))) 285 period_group_types.append("freebusy-part%d" % i) 286 period_group_sources.append(participant) 287 288 groups = [] 289 group_columns = [] 290 group_types = period_group_types 291 group_sources = period_group_sources 292 all_points = set() 293 294 # Obtain time point information for each group of periods. 295 296 for periods in period_groups: 297 298 # Get the time scale with start and end points. 299 300 scale = get_scale(periods, tzid) 301 302 # Get the time slots for the periods. 303 # Time slots are collections of Point objects with lists of active 304 # periods. 305 306 slots = get_slots(scale) 307 308 # Add start of day time points for multi-day periods. 309 310 add_day_start_points(slots, tzid) 311 312 # Record the slots and all time points employed. 313 314 groups.append(slots) 315 all_points.update([point for point, active in slots]) 316 317 # Partition the groups into days. 318 319 days = {} 320 partitioned_groups = [] 321 partitioned_group_types = [] 322 partitioned_group_sources = [] 323 324 for slots, group_type, group_source in zip(groups, group_types, group_sources): 325 326 # Propagate time points to all groups of time slots. 327 328 add_slots(slots, all_points) 329 330 # Count the number of columns employed by the group. 331 332 columns = 0 333 334 # Partition the time slots by day. 335 336 partitioned = {} 337 338 for day, day_slots in partition_by_day(slots).items(): 339 340 # Construct a list of time intervals within the day. 341 342 intervals = [] 343 344 # Convert each partition to a mapping from points to active 345 # periods. 346 347 partitioned[day] = day_points = {} 348 349 last = None 350 351 for point, active in day_slots: 352 columns = max(columns, len(active)) 353 day_points[point] = active 354 355 if last: 356 intervals.append((last, point)) 357 358 last = point 359 360 if last: 361 intervals.append((last, None)) 362 363 if not days.has_key(day): 364 days[day] = set() 365 366 # Record the divisions or intervals within each day. 367 368 days[day].update(intervals) 369 370 # Only include the requests column if it provides objects. 371 372 if group_type != "request" or columns: 373 group_columns.append(columns) 374 partitioned_groups.append(partitioned) 375 partitioned_group_types.append(group_type) 376 partitioned_group_sources.append(group_source) 377 378 # Add empty days. 379 380 add_empty_days(days, tzid) 381 382 # Show the controls permitting day selection as well as the controls 383 # configuring the new event display. 384 385 self.show_calendar_day_controls(days) 386 self.show_calendar_interval_controls(days) 387 388 # Show a button for scheduling a new event. 389 390 page.p(class_="controls") 391 page.input(name="newevent", type="submit", value="New event", id="newevent", class_="newevent-with-periods", accesskey="N") 392 page.span("Select days or periods for a new event.", class_="newevent-no-periods") 393 page.p.close() 394 395 # Show controls for hiding empty days and busy slots. 396 # The positioning of the control, paragraph and table are important here. 397 398 page.input(name="showdays", type="checkbox", value="show", id="showdays", accesskey="D") 399 page.input(name="hidebusy", type="checkbox", value="hide", id="hidebusy", accesskey="B") 400 401 page.p(class_="controls") 402 page.label("Hide busy time periods", for_="hidebusy", class_="hidebusy enable") 403 page.label("Show busy time periods", for_="hidebusy", class_="hidebusy disable") 404 page.label("Show empty days", for_="showdays", class_="showdays disable") 405 page.label("Hide empty days", for_="showdays", class_="showdays enable") 406 page.input(name="reset", type="submit", value="Clear selections", id="reset") 407 page.label("Clear selections", for_="reset", class_="reset newevent-with-periods") 408 page.p.close() 409 410 # Show the calendar itself. 411 412 self.show_calendar_days(days, partitioned_groups, partitioned_group_types, partitioned_group_sources, group_columns) 413 414 # End the form region. 415 416 page.form.close() 417 418 # More page fragment methods. 419 420 def show_calendar_day_controls(self, days): 421 422 "Show controls for the given 'days' in the calendar." 423 424 page = self.page 425 slots = self.env.get_args().get("slot", []) 426 427 for day in days: 428 value, identifier = self._day_value_and_identifier(day) 429 self._slot_selector(value, identifier, slots) 430 431 # Generate a dynamic stylesheet to allow day selections to colour 432 # specific days. 433 # NOTE: The style details need to be coordinated with the static 434 # NOTE: stylesheet. 435 436 page.style(type="text/css") 437 438 l = [] 439 440 for day in days: 441 daystr, dayid = self._day_value_and_identifier(day) 442 l.append("""\ 443 input.newevent.selector#%s:checked ~ table#region-%s label.day, 444 input.newevent.selector#%s:checked ~ table#region-%s label.timepoint""" % (dayid, dayid, dayid, dayid)) 445 446 page.add(",\n".join(l)) 447 page.add(""" { 448 background-color: #5f4; 449 text-decoration: underline; 450 } 451 """) 452 453 page.style.close() 454 455 def show_calendar_interval_controls(self, days): 456 457 "Show controls for the intervals provided by 'days'." 458 459 page = self.page 460 slots = self.env.get_args().get("slot", []) 461 462 for day, intervals in days.items(): 463 for point, endpoint in intervals: 464 value, identifier = self._slot_value_and_identifier(point, endpoint) 465 self._slot_selector(value, identifier, slots) 466 467 # Generate a dynamic stylesheet to allow day selections to colour 468 # specific days. 469 # NOTE: The style details need to be coordinated with the static 470 # NOTE: stylesheet. 471 472 page.style(type="text/css") 473 474 l = [] 475 476 for day, intervals in days.items(): 477 daystr, dayid = self._day_value_and_identifier(day) 478 for point, endpoint in intervals: 479 timestr, timeid = self._slot_value_and_identifier(point, endpoint) 480 l.append("""\ 481 input.newevent.selector#%s:checked ~ table#region-%s th#region-%s""" % (timeid, dayid, timeid)) 482 483 page.add(",\n".join(l)) 484 page.add(""" { 485 background-color: #5f4; 486 text-decoration: underline; 487 } 488 """) 489 490 page.style.close() 491 492 def show_calendar_participant_headings(self, group_types, group_sources, group_columns): 493 494 """ 495 Show headings for the participants and other scheduling contributors, 496 defined by 'group_types', 'group_sources' and 'group_columns'. 497 """ 498 499 page = self.page 500 501 page.colgroup(span=1, id="columns-timeslot") 502 503 for group_type, columns in zip(group_types, group_columns): 504 page.colgroup(span=max(columns, 1), id="columns-%s" % group_type) 505 506 page.thead() 507 page.tr() 508 page.th("", class_="emptyheading") 509 510 for group_type, source, columns in zip(group_types, group_sources, group_columns): 511 page.th(source, 512 class_=(group_type == "request" and "requestheading" or "participantheading"), 513 colspan=max(columns, 1)) 514 515 page.tr.close() 516 page.thead.close() 517 518 def show_calendar_days(self, days, partitioned_groups, partitioned_group_types, 519 partitioned_group_sources, group_columns): 520 521 """ 522 Show calendar days, defined by a collection of 'days', the contributing 523 period information as 'partitioned_groups' (partitioned by day), the 524 'partitioned_group_types' indicating the kind of contribution involved, 525 the 'partitioned_group_sources' indicating the origin of each group, and 526 the 'group_columns' defining the number of columns in each group. 527 """ 528 529 page = self.page 530 531 # Determine the number of columns required. Where participants provide 532 # no columns for events, one still needs to be provided for the 533 # participant itself. 534 535 all_columns = sum([max(columns, 1) for columns in group_columns]) 536 537 # Determine the days providing time slots. 538 539 all_days = days.items() 540 all_days.sort() 541 542 # Produce a heading and time points for each day. 543 544 for day, intervals in all_days: 545 groups_for_day = [partitioned.get(day) for partitioned in partitioned_groups] 546 is_empty = True 547 548 for slots in groups_for_day: 549 if not slots: 550 continue 551 552 for active in slots.values(): 553 if active: 554 is_empty = False 555 break 556 557 daystr, dayid = self._day_value_and_identifier(day) 558 559 page.table(cellspacing=5, cellpadding=5, class_="calendar %s" % (is_empty and " empty" or ""), id="region-%s" % dayid) 560 561 page.caption(class_="dayheading container separator") 562 self._day_heading(day) 563 page.caption.close() 564 565 self.show_calendar_participant_headings(partitioned_group_types, partitioned_group_sources, group_columns) 566 567 page.tbody(class_="points") 568 self.show_calendar_points(intervals, groups_for_day, partitioned_group_types, group_columns) 569 page.tbody.close() 570 571 page.table.close() 572 573 def show_calendar_points(self, intervals, groups, group_types, group_columns): 574 575 """ 576 Show the time 'intervals' along with period information from the given 577 'groups', having the indicated 'group_types', each with the number of 578 columns given by 'group_columns'. 579 """ 580 581 page = self.page 582 583 # Obtain the user's timezone. 584 585 tzid = self.get_tzid() 586 587 # Produce a row for each interval. 588 589 intervals = list(intervals) 590 intervals.sort() 591 592 for point, endpoint in intervals: 593 continuation = point.point == get_start_of_day(point.point, tzid) 594 595 # Some rows contain no period details and are marked as such. 596 597 have_active = False 598 have_active_request = False 599 600 for slots, group_type in zip(groups, group_types): 601 if slots and slots.get(point): 602 if group_type == "request": 603 have_active_request = True 604 else: 605 have_active = True 606 607 # Emit properties of the time interval, where post-instant intervals 608 # are also treated as busy. 609 610 css = " ".join([ 611 "slot", 612 (have_active or point.indicator == Point.REPEATED) and "busy" or \ 613 have_active_request and "suggested" or "empty", 614 continuation and "daystart" or "" 615 ]) 616 617 page.tr(class_=css) 618 if point.indicator == Point.PRINCIPAL: 619 timestr, timeid = self._slot_value_and_identifier(point, endpoint) 620 page.th(class_="timeslot", id="region-%s" % timeid) 621 self._time_point(point, endpoint) 622 else: 623 page.th() 624 page.th.close() 625 626 # Obtain slots for the time point from each group. 627 628 for columns, slots, group_type in zip(group_columns, groups, group_types): 629 active = slots and slots.get(point) 630 631 # Where no periods exist for the given time interval, generate 632 # an empty cell. Where a participant provides no periods at all, 633 # the colspan is adjusted to be 1, not 0. 634 635 if not active: 636 self._empty_slot(point, endpoint, max(columns, 1)) 637 continue 638 639 slots = slots.items() 640 slots.sort() 641 spans = get_spans(slots) 642 643 empty = 0 644 645 # Show a column for each active period. 646 647 for p in active: 648 649 # The period can be None, meaning an empty column. 650 651 if p: 652 653 # Flush empty slots preceding this one. 654 655 if empty: 656 self._empty_slot(point, endpoint, empty) 657 empty = 0 658 659 key = p.get_key() 660 span = spans[key] 661 662 # Produce a table cell only at the start of the period 663 # or when continued at the start of a day. 664 # Points defining the ends of instant events should 665 # never define the start of new events. 666 667 if point.indicator == Point.PRINCIPAL and (point.point == p.get_start() or continuation): 668 669 has_continued = continuation and point.point != p.get_start() 670 will_continue = not ends_on_same_day(point.point, p.get_end(), tzid) 671 is_organiser = p.organiser == self.user 672 673 css = " ".join([ 674 "event", 675 has_continued and "continued" or "", 676 will_continue and "continues" or "", 677 p.transp == "ORG" and "only-organising" or is_organiser and "organising" or "attending", 678 self._have_request(p.uid, p.recurrenceid, "COUNTER", True) and "counter" or "", 679 ]) 680 681 # Only anchor the first cell of events. 682 # Need to only anchor the first period for a recurring 683 # event. 684 685 html_id = "%s-%s-%s" % (group_type, p.uid, p.recurrenceid or "") 686 687 if point.point == p.get_start() and html_id not in self.html_ids: 688 page.td(class_=css, rowspan=span, id=html_id) 689 self.html_ids.add(html_id) 690 else: 691 page.td(class_=css, rowspan=span) 692 693 # Only link to events if they are not being updated 694 # by requests. 695 696 if not p.summary or \ 697 group_type != "request" and self._have_request(p.uid, p.recurrenceid, None, True): 698 699 page.span(p.summary or "(Participant is busy)") 700 701 # Link to requests and events (including ones for 702 # which counter-proposals exist). 703 704 else: 705 page.a(p.summary, href=self.link_to(p.uid, p.recurrenceid)) 706 707 page.td.close() 708 else: 709 empty += 1 710 711 # Pad with empty columns. 712 713 empty = columns - len(active) 714 715 if empty: 716 self._empty_slot(point, endpoint, empty) 717 718 page.tr.close() 719 720 def _day_heading(self, day): 721 722 """ 723 Generate a heading for 'day' of the following form: 724 725 <label class="day" for="day-20150203">Tuesday, 3 February 2015</label> 726 """ 727 728 page = self.page 729 value, identifier = self._day_value_and_identifier(day) 730 page.label(self.format_date(day, "full"), class_="day", for_=identifier) 731 732 def _time_point(self, point, endpoint): 733 734 """ 735 Generate headings for the 'point' to 'endpoint' period of the following 736 form: 737 738 <label class="timepoint" for="slot-20150203T090000-20150203T100000">09:00:00 CET</label> 739 <span class="endpoint">10:00:00 CET</span> 740 """ 741 742 page = self.page 743 tzid = self.get_tzid() 744 value, identifier = self._slot_value_and_identifier(point, endpoint) 745 page.label(self.format_time(point.point, "long"), class_="timepoint", for_=identifier) 746 page.span(self.format_time(endpoint and endpoint.point or get_end_of_day(point.point, tzid), "long"), class_="endpoint") 747 748 def _slot_selector(self, value, identifier, slots): 749 750 """ 751 Provide a timeslot control having the given 'value', employing the 752 indicated HTML 'identifier', and using the given 'slots' collection 753 to select any control whose 'value' is in this collection, unless the 754 "reset" request parameter has been asserted. 755 """ 756 757 reset = self.env.get_args().has_key("reset") 758 page = self.page 759 if not reset and value in slots: 760 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector", checked="checked") 761 else: 762 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector") 763 764 def _empty_slot(self, point, endpoint, colspan): 765 766 """ 767 Show an empty slot cell for the given 'point' and 'endpoint', with the 768 given 'colspan' configuring the cell's appearance. 769 """ 770 771 page = self.page 772 page.td(class_="empty%s" % (point.indicator == Point.PRINCIPAL and " container" or ""), colspan=colspan) 773 if point.indicator == Point.PRINCIPAL: 774 value, identifier = self._slot_value_and_identifier(point, endpoint) 775 page.label("Select/deselect period", class_="newevent popup", for_=identifier) 776 page.td.close() 777 778 def _day_value_and_identifier(self, day): 779 780 "Return a day value and HTML identifier for the given 'day'." 781 782 value = format_datetime(day) 783 identifier = "day-%s" % value 784 return value, identifier 785 786 def _slot_value_and_identifier(self, point, endpoint): 787 788 """ 789 Return a slot value and HTML identifier for the given 'point' and 790 'endpoint'. 791 """ 792 793 value = "%s-%s" % (format_datetime(point.point), endpoint and format_datetime(endpoint.point) or "") 794 identifier = "slot-%s" % value 795 return value, identifier 796 797 # vim: tabstop=4 expandtab shiftwidth=4