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 ~ div div#region-%s label.day, 444 input.newevent.selector#%s:checked ~ div div#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 for point, endpoint in intervals: 478 timestr, timeid = self._slot_value_and_identifier(point, endpoint) 479 l.append("""\ 480 input.newevent.selector#%s:checked ~ div div#region-%s label.timepoint""" % (timeid, timeid)) 481 482 page.add(",\n".join(l)) 483 page.add(""" { 484 background-color: #5f4; 485 text-decoration: underline; 486 } 487 """) 488 489 page.style.close() 490 491 def show_calendar_participant_headings(self, group_types, group_sources, group_columns, is_empty): 492 493 """ 494 Show headings for the participants and other scheduling contributors, 495 defined by 'group_types', 'group_sources' and 'group_columns'. 496 """ 497 498 page = self.page 499 500 page.div(class_="tableheading%s" % (is_empty and " empty" or "")) 501 page.div(class_="tablerow") 502 page.div("", class_="tablecell emptyheading") 503 504 for group_type, source, columns in zip(group_types, group_sources, group_columns): 505 page.div(source, 506 class_="tablecell %s" % (group_type == "request" and "requestheading" or "participantheading")) 507 for i in range(1, max(columns, 1)): 508 page.div("", class_="tablecell %s" % (group_type == "request" and "requestheading" or "participantheading")) 509 510 page.div.close() 511 page.div.close() 512 513 def show_calendar_days(self, days, partitioned_groups, partitioned_group_types, partitioned_group_sources, group_columns): 514 515 """ 516 Show calendar days, defined by a collection of 'days', the contributing 517 period information as 'partitioned_groups' (partitioned by day), the 518 'partitioned_group_types' indicating the kind of contribution involved, 519 and the 'group_columns' defining the number of columns in each group. 520 """ 521 522 page = self.page 523 524 # Determine the number of columns required. Where participants provide 525 # no columns for events, one still needs to be provided for the 526 # participant itself. 527 528 all_columns = sum([max(columns, 1) for columns in group_columns]) 529 530 # Determine the days providing time slots. 531 532 all_days = days.items() 533 all_days.sort() 534 535 # Produce a heading and time points for each day. 536 537 for day, intervals in all_days: 538 groups_for_day = [partitioned.get(day) for partitioned in partitioned_groups] 539 is_empty = True 540 541 for slots in groups_for_day: 542 if not slots: 543 continue 544 545 for active in slots.values(): 546 if active: 547 is_empty = False 548 break 549 550 daystr, dayid = self._day_value_and_identifier(day) 551 552 page.div(class_="calendar") 553 554 page.div(class_="dayheading container separator%s" % (is_empty and " empty" or ""), id="region-%s" % dayid) 555 self._day_heading(day) 556 page.div.close() 557 558 self.show_calendar_participant_headings(partitioned_group_types, partitioned_group_sources, group_columns, is_empty) 559 560 page.div(class_="tablebody points%s" % (is_empty and " empty" or ""), id="region-%s" % dayid) 561 self.show_calendar_points(intervals, groups_for_day, partitioned_group_types, group_columns) 562 page.div.close() 563 page.div.close() 564 565 def show_calendar_points(self, intervals, groups, group_types, group_columns): 566 567 """ 568 Show the time 'intervals' along with period information from the given 569 'groups', having the indicated 'group_types', each with the number of 570 columns given by 'group_columns'. 571 """ 572 573 page = self.page 574 575 # Obtain the user's timezone. 576 577 tzid = self.get_tzid() 578 579 # Produce a row for each interval. 580 581 intervals = list(intervals) 582 intervals.sort() 583 584 for point, endpoint in intervals: 585 continuation = point.point == get_start_of_day(point.point, tzid) 586 587 # Some rows contain no period details and are marked as such. 588 589 have_active = False 590 have_active_request = False 591 592 for slots, group_type in zip(groups, group_types): 593 if slots and slots.get(point): 594 if group_type == "request": 595 have_active_request = True 596 else: 597 have_active = True 598 599 # Emit properties of the time interval, where post-instant intervals 600 # are also treated as busy. 601 602 css = " ".join([ 603 "slot", 604 (have_active or point.indicator == Point.REPEATED) and "busy" or \ 605 have_active_request and "suggested" or "empty", 606 continuation and "daystart" or "" 607 ]) 608 609 page.div(class_="tablerow %s" % css) 610 if point.indicator == Point.PRINCIPAL: 611 timestr, timeid = self._slot_value_and_identifier(point, endpoint) 612 page.div(class_="tablecell timeslot", id="region-%s" % timeid) 613 self._time_point(point, endpoint) 614 else: 615 page.div(class_="tablecell") 616 page.div.close() 617 618 # Obtain slots for the time point from each group. 619 620 for columns, slots, group_type in zip(group_columns, groups, group_types): 621 active = slots and slots.get(point) 622 623 # Where no periods exist for the given time interval, generate 624 # an empty cell. Where a participant provides no periods at all, 625 # the colspan is adjusted to be 1, not 0. 626 627 if not active: 628 self._empty_slot(point, endpoint, max(columns, 1)) 629 continue 630 631 slots = slots.items() 632 slots.sort() 633 spans = get_spans(slots) 634 635 empty = 0 636 637 # Show a column for each active period. 638 639 for p in active: 640 641 # The period can be None, meaning an empty column. 642 643 if p: 644 645 # Flush empty slots preceding this one. 646 647 if empty: 648 self._empty_slot(point, endpoint, empty) 649 empty = 0 650 651 key = p.get_key() 652 span = spans[key] 653 654 # Produce a table cell only at the start of the period 655 # or when continued at the start of a day. 656 # Points defining the ends of instant events should 657 # never define the start of new events. 658 659 first_cell_in_group = point.indicator == Point.PRINCIPAL and (point.point == p.get_start() or continuation) 660 661 has_continued = continuation and point.point != p.get_start() 662 will_continue = not endpoint and not ends_on_same_day(point.point, p.get_end(), tzid) 663 is_organiser = p.organiser == self.user 664 665 last_cell = not will_continue and (not endpoint or endpoint.point == p.get_end()) 666 667 css = " ".join([ 668 "event", 669 has_continued and "continued" or "", 670 will_continue and "continues" or "", 671 last_cell and "ends" or "", 672 p.transp == "ORG" and "only-organising" or is_organiser and "organising" or "attending", 673 self._have_request(p.uid, p.recurrenceid, "COUNTER", True) and "counter" or "", 674 ]) 675 676 # Only anchor the first cell of events. 677 # Need to only anchor the first period for a recurring 678 # event. 679 680 html_id = "%s-%s-%s" % (group_type, p.uid, p.recurrenceid or "") 681 682 if point.point == p.get_start() and html_id not in self.html_ids: 683 page.div(class_="tablecell %s" % css, id=html_id) 684 self.html_ids.add(html_id) 685 else: 686 page.div(class_="tablecell %s" % css) 687 688 # Continue event spans using empty cells. 689 690 if not first_cell_in_group: 691 pass 692 693 # Only link to events if they are not being updated 694 # by requests. 695 696 elif 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.div.close() 708 709 else: 710 empty += 1 711 712 # Pad with empty columns. 713 714 empty = columns - len(active) 715 716 if empty: 717 self._empty_slot(point, endpoint, empty) 718 719 page.div.close() 720 721 def _day_heading(self, day): 722 723 """ 724 Generate a heading for 'day' of the following form: 725 726 <label class="day" for="day-20150203">Tuesday, 3 February 2015</label> 727 """ 728 729 page = self.page 730 value, identifier = self._day_value_and_identifier(day) 731 page.label(self.format_date(day, "full"), class_="day", for_=identifier) 732 733 def _time_point(self, point, endpoint): 734 735 """ 736 Generate headings for the 'point' to 'endpoint' period of the following 737 form: 738 739 <label class="timepoint" for="slot-20150203T090000-20150203T100000">09:00:00 CET</label> 740 <span class="endpoint">10:00:00 CET</span> 741 """ 742 743 page = self.page 744 tzid = self.get_tzid() 745 value, identifier = self._slot_value_and_identifier(point, endpoint) 746 page.label(self.format_time(point.point, "long"), class_="timepoint", for_=identifier) 747 page.span(self.format_time(endpoint and endpoint.point or get_end_of_day(point.point, tzid), "long"), class_="endpoint") 748 749 def _slot_selector(self, value, identifier, slots): 750 751 """ 752 Provide a timeslot control having the given 'value', employing the 753 indicated HTML 'identifier', and using the given 'slots' collection 754 to select any control whose 'value' is in this collection, unless the 755 "reset" request parameter has been asserted. 756 """ 757 758 reset = self.env.get_args().has_key("reset") 759 page = self.page 760 if not reset and value in slots: 761 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector", checked="checked") 762 else: 763 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector") 764 765 def _empty_slot(self, point, endpoint, colspan): 766 767 """ 768 Show an empty slot cell for the given 'point' and 'endpoint', with the 769 given 'colspan' configuring the cell's appearance. 770 """ 771 772 page = self.page 773 774 for i in range(0, colspan): 775 page.div(class_="tablecell empty%s" % (point.indicator == Point.PRINCIPAL and " container" or "")) 776 if point.indicator == Point.PRINCIPAL: 777 value, identifier = self._slot_value_and_identifier(point, endpoint) 778 page.label("Select/deselect period", class_="newevent popup", for_=identifier) 779 page.div.close() 780 781 def _day_value_and_identifier(self, day): 782 783 "Return a day value and HTML identifier for the given 'day'." 784 785 value = format_datetime(day) 786 identifier = "day-%s" % value 787 return value, identifier 788 789 def _slot_value_and_identifier(self, point, endpoint): 790 791 """ 792 Return a slot value and HTML identifier for the given 'point' and 793 'endpoint'. 794 """ 795 796 value = "%s-%s" % (format_datetime(point.point), endpoint and format_datetime(endpoint.point) or "") 797 identifier = "slot-%s" % value 798 return value, identifier 799 800 # vim: tabstop=4 expandtab shiftwidth=4