1 #!/usr/bin/env python 2 3 """ 4 A Web interface to a user's 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 # Edit this path to refer to the location of the imiptools libraries, if 23 # necessary. 24 25 LIBRARY_PATH = "/var/lib/imip-agent" 26 27 from datetime import date, datetime, timedelta 28 import babel.dates 29 import cgi, os, sys 30 31 sys.path.append(LIBRARY_PATH) 32 33 from imiptools.content import Handler 34 from imiptools.data import get_address, get_uri, make_freebusy, parse_object, \ 35 Object, to_part 36 from imiptools.dates import format_datetime, get_datetime, get_datetime_item, \ 37 get_end_of_day, get_start_of_day, get_start_of_next_day, \ 38 get_timestamp, ends_on_same_day, next_date, to_timezone 39 from imiptools.mail import Messenger 40 from imiptools.period import add_day_start_points, add_slots, convert_periods, \ 41 get_freebusy_details, \ 42 get_scale, have_conflict, get_slots, get_spans, \ 43 partition_by_day 44 from imiptools.profile import Preferences 45 import imip_store 46 import markup 47 48 getenv = os.environ.get 49 setenv = os.environ.__setitem__ 50 51 class CGIEnvironment: 52 53 "A CGI-compatible environment." 54 55 def __init__(self, charset=None): 56 self.charset = charset 57 self.args = None 58 self.method = None 59 self.path = None 60 self.path_info = None 61 self.user = None 62 63 def get_args(self): 64 if self.args is None: 65 if self.get_method() != "POST": 66 setenv("QUERY_STRING", "") 67 args = cgi.parse(keep_blank_values=True) 68 69 if not self.charset: 70 self.args = args 71 else: 72 self.args = {} 73 for key, values in args.items(): 74 self.args[key] = [unicode(value, self.charset) for value in values] 75 76 return self.args 77 78 def get_method(self): 79 if self.method is None: 80 self.method = getenv("REQUEST_METHOD") or "GET" 81 return self.method 82 83 def get_path(self): 84 if self.path is None: 85 self.path = getenv("SCRIPT_NAME") or "" 86 return self.path 87 88 def get_path_info(self): 89 if self.path_info is None: 90 self.path_info = getenv("PATH_INFO") or "" 91 return self.path_info 92 93 def get_user(self): 94 if self.user is None: 95 self.user = getenv("REMOTE_USER") or "" 96 return self.user 97 98 def get_output(self): 99 return sys.stdout 100 101 def get_url(self): 102 path = self.get_path() 103 path_info = self.get_path_info() 104 return "%s%s" % (path.rstrip("/"), path_info) 105 106 def new_url(self, path_info): 107 path = self.get_path() 108 return "%s/%s" % (path.rstrip("/"), path_info.lstrip("/")) 109 110 class ManagerHandler(Handler): 111 112 """ 113 A content handler for use by the manager, as opposed to operating within the 114 mail processing pipeline. 115 """ 116 117 def __init__(self, obj, user, messenger): 118 Handler.__init__(self, messenger=messenger) 119 self.set_object(obj) 120 self.user = user 121 122 self.organiser = self.obj.get_value("ORGANIZER") 123 self.attendees = self.obj.get_values("ATTENDEE") 124 125 # Communication methods. 126 127 def send_message(self, method, sender, for_organiser): 128 129 """ 130 Create a full calendar object employing the given 'method', and send it 131 to the appropriate recipients, also sending a copy to the 'sender'. The 132 'for_organiser' value indicates whether the organiser is sending this 133 message. 134 """ 135 136 parts = [self.obj.to_part(method)] 137 138 # As organiser, send an invitation to attendees, excluding oneself if 139 # also attending. The updated event will be saved by the outgoing 140 # handler. 141 142 if for_organiser: 143 recipients = [get_address(attendee) for attendee in self.attendees if attendee != self.user] 144 else: 145 recipients = [get_address(self.organiser)] 146 147 # Bundle free/busy information if appropriate. 148 149 preferences = Preferences(self.user) 150 151 if preferences.get("freebusy_sharing") == "share" and \ 152 preferences.get("freebusy_bundling") == "always": 153 154 # Invent a unique identifier. 155 156 utcnow = get_timestamp() 157 uid = "imip-agent-%s-%s" % (utcnow, get_address(self.user)) 158 159 freebusy = self.store.get_freebusy(self.user) 160 parts.append(to_part("PUBLISH", [make_freebusy(freebusy, uid, self.user)])) 161 162 message = self.messenger.make_outgoing_message(parts, recipients, outgoing_bcc=sender) 163 self.messenger.sendmail(recipients, message.as_string(), outgoing_bcc=sender) 164 165 # Action methods. 166 167 def process_received_request(self, update=False): 168 169 """ 170 Process the current request for the given 'user'. Return whether any 171 action was taken. 172 173 If 'update' is given, the sequence number will be incremented in order 174 to override any previous response. 175 """ 176 177 # Reply only on behalf of this user. 178 179 for attendee, attendee_attr in self.obj.get_items("ATTENDEE"): 180 181 if attendee == self.user: 182 if attendee_attr.has_key("RSVP"): 183 del attendee_attr["RSVP"] 184 if self.messenger and self.messenger.sender != get_address(attendee): 185 attendee_attr["SENT-BY"] = get_uri(self.messenger.sender) 186 self.obj["ATTENDEE"] = [(attendee, attendee_attr)] 187 if update: 188 sequence = self.obj.get_value("SEQUENCE") or "0" 189 self.obj["SEQUENCE"] = [(str(int(sequence) + 1), {})] 190 self.update_dtstamp() 191 192 self.send_message("REPLY", get_address(attendee), for_organiser=False) 193 194 return True 195 196 return False 197 198 def process_created_request(self, method, update=False): 199 200 """ 201 Process the current request for the given 'user', sending a created 202 request of the given 'method' to attendees. Return whether any action 203 was taken. 204 205 If 'update' is given, the sequence number will be incremented in order 206 to override any previous message. 207 """ 208 209 organiser, organiser_attr = self.obj.get_item("ORGANIZER") 210 211 if self.messenger and self.messenger.sender != get_address(organiser): 212 organiser_attr["SENT-BY"] = get_uri(self.messenger.sender) 213 if update: 214 sequence = self.obj.get_value("SEQUENCE") or "0" 215 self.obj["SEQUENCE"] = [(str(int(sequence) + 1), {})] 216 self.update_dtstamp() 217 218 self.send_message(method, get_address(self.organiser), for_organiser=True) 219 return True 220 221 class Manager: 222 223 "A simple manager application." 224 225 def __init__(self, messenger=None): 226 self.messenger = messenger or Messenger() 227 228 self.encoding = "utf-8" 229 self.env = CGIEnvironment(self.encoding) 230 231 user = self.env.get_user() 232 self.user = user and get_uri(user) or None 233 self.preferences = None 234 self.locale = None 235 self.requests = None 236 237 self.out = self.env.get_output() 238 self.page = markup.page() 239 240 self.store = imip_store.FileStore() 241 self.objects = {} 242 243 try: 244 self.publisher = imip_store.FilePublisher() 245 except OSError: 246 self.publisher = None 247 248 def _get_uid(self, path_info): 249 return path_info.lstrip("/").split("/", 1)[0] 250 251 def _get_object(self, uid): 252 if self.objects.has_key(uid): 253 return self.objects[uid] 254 255 f = uid and self.store.get_event(self.user, uid) or None 256 257 if not f: 258 return None 259 260 fragment = parse_object(f, "utf-8") 261 obj = self.objects[uid] = fragment and Object(fragment) 262 263 return obj 264 265 def _get_requests(self): 266 if self.requests is None: 267 self.requests = self.store.get_requests(self.user) 268 return self.requests 269 270 def _get_request_summary(self): 271 summary = [] 272 for uid in self._get_requests(): 273 obj = self._get_object(uid) 274 if obj: 275 summary.append(( 276 obj.get_value("DTSTART"), 277 obj.get_value("DTEND"), 278 uid 279 )) 280 return summary 281 282 # Preference methods. 283 284 def get_user_locale(self): 285 if not self.locale: 286 self.locale = self.get_preferences().get("LANG", "C") 287 return self.locale 288 289 def get_preferences(self): 290 if not self.preferences: 291 self.preferences = Preferences(self.user) 292 return self.preferences 293 294 def get_tzid(self): 295 prefs = self.get_preferences() 296 return prefs.get("TZID", "UTC") 297 298 # Prettyprinting of dates and times. 299 300 def format_date(self, dt, format): 301 return self._format_datetime(babel.dates.format_date, dt, format) 302 303 def format_time(self, dt, format): 304 return self._format_datetime(babel.dates.format_time, dt, format) 305 306 def format_datetime(self, dt, format): 307 return self._format_datetime( 308 isinstance(dt, datetime) and babel.dates.format_datetime or babel.dates.format_date, 309 dt, format) 310 311 def format_end_datetime(self, dt, format): 312 if isinstance(dt, date) and not isinstance(dt, datetime): 313 dt = dt - timedelta(1) 314 return self.format_datetime(dt, format) 315 316 def _format_datetime(self, fn, dt, format): 317 return fn(dt, format=format, locale=self.get_user_locale()) 318 319 # Data management methods. 320 321 def remove_request(self, uid): 322 return self.store.dequeue_request(self.user, uid) 323 324 def remove_event(self, uid): 325 return self.store.remove_event(self.user, uid) 326 327 # Presentation methods. 328 329 def new_page(self, title): 330 self.page.init(title=title, charset=self.encoding, css=self.env.new_url("styles.css")) 331 332 def status(self, code, message): 333 self.header("Status", "%s %s" % (code, message)) 334 335 def header(self, header, value): 336 print >>self.out, "%s: %s" % (header, value) 337 338 def no_user(self): 339 self.status(403, "Forbidden") 340 self.new_page(title="Forbidden") 341 self.page.p("You are not logged in and thus cannot access scheduling requests.") 342 343 def no_page(self): 344 self.status(404, "Not Found") 345 self.new_page(title="Not Found") 346 self.page.p("No page is provided at the given address.") 347 348 def redirect(self, url): 349 self.status(302, "Redirect") 350 self.header("Location", url) 351 self.new_page(title="Redirect") 352 self.page.p("Redirecting to: %s" % url) 353 354 # Request logic methods. 355 356 def handle_newevent(self): 357 358 """ 359 Handle any new event operation, creating a new event and redirecting to 360 the event page for further activity. 361 """ 362 363 # Handle a submitted form. 364 365 args = self.env.get_args() 366 367 if not args.has_key("newevent"): 368 return 369 370 # Create a new event using the available information. 371 372 slots = args.get("slot", []) 373 participants = args.get("participants", []) 374 375 if not slots: 376 return 377 378 # Coalesce the selected slots. 379 380 slots.sort() 381 coalesced = [] 382 last = None 383 384 for slot in slots: 385 start, end = slot.split("-") 386 end = end or next_date(start) 387 388 if last: 389 last_start, last_end = last 390 391 # Merge adjacent dates and datetimes. 392 393 if start == last_end: 394 last = last_start, end 395 continue 396 397 # Handle datetimes within dates. 398 # Datetime periods are within single days and are therefore 399 # discarded. 400 401 elif start.startswith(last_start): 402 continue 403 404 # Add separate dates and datetimes. 405 406 else: 407 coalesced.append(last) 408 409 last = start, end 410 411 if last: 412 coalesced.append(last) 413 414 # Obtain the user's timezone. 415 416 tzid = self.get_tzid() 417 418 # Invent a unique identifier. 419 420 utcnow = get_timestamp() 421 uid = "imip-agent-%s-%s" % (utcnow, get_address(self.user)) 422 423 # Define a single occurrence if only one coalesced slot exists. 424 # Otherwise, many occurrences are defined. 425 426 for i, (start, end) in enumerate(coalesced): 427 this_uid = "%s-%s" % (uid, i) 428 429 start = get_datetime(start, {"TZID" : tzid}) 430 end = end and get_datetime(end, {"TZID" : tzid}) or get_start_of_next_day(start, tzid) 431 432 start_value, start_attr = get_datetime_item(start, tzid) 433 end_value, end_attr = get_datetime_item(end, tzid) 434 435 # Create a calendar object and store it as a request. 436 437 record = [] 438 rwrite = record.append 439 440 rwrite(("UID", {}, this_uid)) 441 rwrite(("SUMMARY", {}, "New event at %s" % utcnow)) 442 rwrite(("DTSTAMP", {}, utcnow)) 443 rwrite(("DTSTART", start_attr, start_value)) 444 rwrite(("DTEND", end_attr, end_value)) 445 rwrite(("ORGANIZER", {}, self.user)) 446 447 for participant in participants: 448 if not participant: 449 continue 450 participant = get_uri(participant) 451 rwrite(("ATTENDEE", {"RSVP" : "TRUE", "PARTSTAT" : "NEEDS-ACTION"}, participant)) 452 453 obj = ("VEVENT", {}, record) 454 455 self.store.set_event(self.user, this_uid, obj) 456 self.store.queue_request(self.user, this_uid) 457 458 # Redirect to the object (or the first of the objects), where instead of 459 # attendee controls, there will be organiser controls. 460 461 self.redirect(self.env.new_url("%s-0" % uid)) 462 463 def handle_request(self, uid, obj, queued): 464 465 """ 466 Handle actions involving the given 'uid' and 'obj' object, where 467 'queued' indicates that the object has not yet been handled. 468 """ 469 470 # Handle a submitted form. 471 472 args = self.env.get_args() 473 handled = True 474 475 # Update the object. 476 477 if args.has_key("summary"): 478 obj["SUMMARY"] = [(args["summary"][0], {})] 479 480 if args.has_key("partstat"): 481 attendees = obj.get_value_map("ATTENDEE") 482 if attendees.has_key(self.user): 483 attendees[self.user]["PARTSTAT"] = args["partstat"][0] 484 485 # Process any action. 486 487 reply = args.has_key("reply") 488 discard = args.has_key("discard") 489 invite = args.has_key("invite") 490 cancel = args.has_key("cancel") 491 save = args.has_key("save") 492 update = not queued and args.has_key("update") 493 494 if reply or invite or cancel: 495 496 handler = ManagerHandler(obj, self.user, self.messenger) 497 498 # Process the object and remove it from the list of requests. 499 500 if reply and handler.process_received_request(update) or \ 501 (invite or cancel) and handler.process_created_request(invite and "REQUEST" or "CANCEL", update): 502 503 self.remove_request(uid) 504 505 # Save single user events. 506 507 elif save: 508 self.store.set_event(self.user, uid, obj.to_node()) 509 freebusy = self.store.get_freebusy(self.user) 510 self.remove_request(uid) 511 512 # Remove the request and the object. 513 514 elif discard: 515 self.remove_event(uid) 516 self.remove_request(uid) 517 518 else: 519 handled = False 520 521 # Upon handling an action, redirect to the main page. 522 523 if handled: 524 self.redirect(self.env.get_path()) 525 526 return handled 527 528 # Page fragment methods. 529 530 def show_request_controls(self, obj, needs_update): 531 532 """ 533 Show form controls for a request concerning 'obj', indicating whether 534 an update will be performed if 'needs_update' is specified as a true 535 value. 536 """ 537 538 page = self.page 539 540 is_organiser = obj.get_value("ORGANIZER") == self.user 541 542 attendees = obj.get_value_map("ATTENDEE") 543 is_attendee = attendees.has_key(self.user) 544 attendee_attr = attendees.get(self.user) 545 546 have_other_attendees = len(attendees) > (is_attendee and 1 or 0) 547 548 # Show appropriate options depending on the role of the user. 549 550 if is_attendee and not is_organiser: 551 partstat = attendee_attr.get("PARTSTAT") 552 if not partstat: 553 page.p("This request has not yet been dealt with.") 554 555 if needs_update: 556 page.p("This request can be updated as follows:") 557 else: 558 page.p("An action is required for this request:") 559 560 page.p() 561 page.input(name="reply", type="submit", value="Reply") 562 page.add(" ") 563 page.input(name="discard", type="submit", value="Discard") 564 page.p.close() 565 566 if is_organiser: 567 if have_other_attendees: 568 if needs_update: 569 page.p("As organiser, you can perform the following:") 570 else: 571 page.p("As organiser, you will need to perform an action:") 572 573 page.p() 574 page.input(name="invite", type="submit", value="Invite") 575 page.add(" ") 576 page.input(name="cancel", type="submit", value="Cancel") 577 page.p.close() 578 else: 579 page.p() 580 page.input(name="save", type="submit", value="Save") 581 page.p.close() 582 583 # Updated objects need to have details updated upon sending. 584 585 if needs_update: 586 page.input(name="update", type="hidden", value="true") 587 588 object_labels = { 589 "SUMMARY" : "Summary", 590 "DTSTART" : "Start", 591 "DTEND" : "End", 592 "ORGANIZER" : "Organiser", 593 "ATTENDEE" : "Attendee", 594 } 595 596 partstat_items = [ 597 ("NEEDS-ACTION", "Not confirmed"), 598 ("ACCEPTED", "Attending"), 599 ("TENTATIVE", "Tentatively attending"), 600 ("DECLINED", "Not attending"), 601 ] 602 603 def show_object_on_page(self, uid, obj, needs_update): 604 605 """ 606 Show the calendar object with the given 'uid' and representation 'obj' 607 on the current page. 608 """ 609 610 page = self.page 611 page.form(method="POST") 612 613 # Obtain the user's timezone. 614 615 tzid = self.get_tzid() 616 617 # Provide a summary of the object. 618 619 page.table(class_="object", cellspacing=5, cellpadding=5) 620 page.thead() 621 page.tr() 622 page.th("Event", class_="mainheading", colspan=3) 623 page.tr.close() 624 page.thead.close() 625 page.tbody() 626 627 for name in ["SUMMARY", "DTSTART", "DTEND", "ORGANIZER", "ATTENDEE"]: 628 page.tr() 629 630 label = self.object_labels.get(name, name) 631 632 # Handle datetimes specially. 633 634 if name in ["DTSTART", "DTEND"]: 635 value, attr = obj.get_item(name) 636 tzid = attr.get("TZID", tzid) 637 value = ( 638 name == "DTSTART" and self.format_datetime or self.format_end_datetime 639 )(to_timezone(get_datetime(value), tzid), "full") 640 page.th(label, class_="objectheading") 641 page.td(value, colspan=2) 642 page.tr.close() 643 644 # Handle the summary specially. 645 646 elif name == "SUMMARY": 647 value = obj.get_value(name) 648 page.th(label, class_="objectheading") 649 page.td(colspan=2) 650 page.input(name="summary", type="text", value=value, size=80) 651 page.td.close() 652 page.tr.close() 653 654 # Handle potentially many values. 655 656 else: 657 items = obj.get_items(name) 658 if not items: 659 continue 660 661 page.th(label, class_="objectheading", rowspan=len(items)) 662 663 first = True 664 665 for value, attr in items: 666 if not first: 667 page.tr() 668 else: 669 first = False 670 671 if name == "ATTENDEE": 672 page.td(class_="objectattribute") 673 page.add(value) 674 page.td.close() 675 page.td(class_="partstat") 676 677 partstat = attr.get("PARTSTAT") 678 if partstat and value == self.user: 679 self._show_menu("partstat", partstat, self.partstat_items) 680 else: 681 page.add(dict(self.partstat_items).get(partstat, "")) 682 else: 683 page.td(class_="objectattribute", colspan=2) 684 page.add(value) 685 686 page.td.close() 687 page.tr.close() 688 689 page.tbody.close() 690 page.table.close() 691 692 dtstart = format_datetime(obj.get_utc_datetime("DTSTART")) 693 dtend = format_datetime(obj.get_utc_datetime("DTEND")) 694 695 # Indicate whether there are conflicting events. 696 697 freebusy = self.store.get_freebusy(self.user) 698 699 if freebusy: 700 701 # Obtain any time zone details from the suggested event. 702 703 _dtstart, attr = obj.get_item("DTSTART") 704 tzid = attr.get("TZID", tzid) 705 706 # Show any conflicts. 707 708 for t in have_conflict(freebusy, [(dtstart, dtend)], True): 709 start, end, found_uid = t[:3] 710 711 # Provide details of any conflicting event. 712 713 if uid != found_uid: 714 start = self.format_datetime(to_timezone(get_datetime(start), tzid), "full") 715 end = self.format_datetime(to_timezone(get_datetime(end), tzid), "full") 716 page.p("Event conflicts with another from %s to %s: " % (start, end)) 717 718 # Show the event summary for the conflicting event. 719 720 found_obj = self._get_object(found_uid) 721 if found_obj: 722 page.a(found_obj.get_value("SUMMARY"), href=self.env.new_url(found_uid)) 723 724 self.show_request_controls(obj, needs_update) 725 page.form.close() 726 727 def show_requests_on_page(self): 728 729 "Show requests for the current user." 730 731 # NOTE: This list could be more informative, but it is envisaged that 732 # NOTE: the requests would be visited directly anyway. 733 734 requests = self._get_requests() 735 736 self.page.div(id="pending-requests") 737 738 if requests: 739 self.page.p("Pending requests:") 740 741 self.page.ul() 742 743 for request in requests: 744 obj = self._get_object(request) 745 if obj: 746 self.page.li() 747 self.page.a(obj.get_value("SUMMARY"), href="#request-%s" % request) 748 self.page.li.close() 749 750 self.page.ul.close() 751 752 else: 753 self.page.p("There are no pending requests.") 754 755 self.page.div.close() 756 757 def show_participants_on_page(self): 758 759 "Show participants for scheduling purposes." 760 761 args = self.env.get_args() 762 participants = args.get("participants", []) 763 764 try: 765 for name, value in args.items(): 766 if name.startswith("remove-participant-"): 767 i = int(name[len("remove-participant-"):]) 768 del participants[i] 769 break 770 except ValueError: 771 pass 772 773 # Trim empty participants. 774 775 while participants and not participants[-1].strip(): 776 participants.pop() 777 778 # Show any specified participants together with controls to remove and 779 # add participants. 780 781 self.page.div(id="participants") 782 783 self.page.p("Participants for scheduling:") 784 785 for i, participant in enumerate(participants): 786 self.page.p() 787 self.page.input(name="participants", type="text", value=participant) 788 self.page.input(name="remove-participant-%d" % i, type="submit", value="Remove") 789 self.page.p.close() 790 791 self.page.p() 792 self.page.input(name="participants", type="text") 793 self.page.input(name="add-participant", type="submit", value="Add") 794 self.page.p.close() 795 796 self.page.div.close() 797 798 return participants 799 800 # Full page output methods. 801 802 def show_object(self, path_info): 803 804 "Show an object request using the given 'path_info' for the current user." 805 806 uid = self._get_uid(path_info) 807 obj = self._get_object(uid) 808 809 if not obj: 810 return False 811 812 is_request = uid in self._get_requests() 813 handled = self.handle_request(uid, obj, is_request) 814 815 if handled: 816 return True 817 818 self.new_page(title="Event") 819 self.show_object_on_page(uid, obj, not is_request) 820 821 return True 822 823 def show_calendar(self): 824 825 "Show the calendar for the current user." 826 827 handled = self.handle_newevent() 828 829 self.new_page(title="Calendar") 830 page = self.page 831 832 # Form controls are used in various places on the calendar page. 833 834 page.form(method="POST") 835 836 self.show_requests_on_page() 837 participants = self.show_participants_on_page() 838 839 # Show a button for scheduling a new event. 840 841 page.p(class_="controls") 842 page.input(name="newevent", type="submit", value="New event", id="newevent") 843 page.input(name="reset", type="submit", value="Clear selections", id="reset") 844 page.p.close() 845 846 # Show controls for hiding empty and busy slots. 847 # The positioning of the control, paragraph and table are important here. 848 849 page.input(name="hideslots", type="checkbox", value="hide", id="hideslots") 850 page.input(name="hidebusy", type="checkbox", value="hide", id="hidebusy") 851 852 page.p(class_="controls") 853 page.label("Hide busy time periods", for_="hidebusy", class_="hidebusy enable") 854 page.label("Show busy time periods", for_="hidebusy", class_="hidebusy disable") 855 page.label("Hide unused time periods", for_="hideslots", class_="hideslots enable") 856 page.label("Show unused time periods", for_="hideslots", class_="hideslots disable") 857 page.p.close() 858 859 freebusy = self.store.get_freebusy(self.user) 860 861 if not freebusy: 862 page.p("No events scheduled.") 863 return 864 865 # Obtain the user's timezone. 866 867 tzid = self.get_tzid() 868 869 # Day view: start at the earliest known day and produce days until the 870 # latest known day, perhaps with expandable sections of empty days. 871 872 # Month view: start at the earliest known month and produce months until 873 # the latest known month, perhaps with expandable sections of empty 874 # months. 875 876 # Details of users to invite to new events could be superimposed on the 877 # calendar. 878 879 # Requests are listed and linked to their tentative positions in the 880 # calendar. Other participants are also shown. 881 882 request_summary = self._get_request_summary() 883 884 period_groups = [request_summary, freebusy] 885 period_group_types = ["request", "freebusy"] 886 period_group_sources = ["Pending requests", "Your schedule"] 887 888 for i, participant in enumerate(participants): 889 period_groups.append(self.store.get_freebusy_for_other(self.user, get_uri(participant))) 890 period_group_types.append("freebusy-part%d" % i) 891 period_group_sources.append(participant) 892 893 groups = [] 894 group_columns = [] 895 group_types = period_group_types 896 group_sources = period_group_sources 897 all_points = set() 898 899 # Obtain time point information for each group of periods. 900 901 for periods in period_groups: 902 periods = convert_periods(periods, tzid) 903 904 # Get the time scale with start and end points. 905 906 scale = get_scale(periods) 907 908 # Get the time slots for the periods. 909 910 slots = get_slots(scale) 911 912 # Add start of day time points for multi-day periods. 913 914 add_day_start_points(slots, tzid) 915 916 # Record the slots and all time points employed. 917 918 groups.append(slots) 919 all_points.update([point for point, active in slots]) 920 921 # Partition the groups into days. 922 923 days = {} 924 partitioned_groups = [] 925 partitioned_group_types = [] 926 partitioned_group_sources = [] 927 928 for slots, group_type, group_source in zip(groups, group_types, group_sources): 929 930 # Propagate time points to all groups of time slots. 931 932 add_slots(slots, all_points) 933 934 # Count the number of columns employed by the group. 935 936 columns = 0 937 938 # Partition the time slots by day. 939 940 partitioned = {} 941 942 for day, day_slots in partition_by_day(slots).items(): 943 intervals = [] 944 last = None 945 946 for point, active in day_slots: 947 columns = max(columns, len(active)) 948 if last: 949 intervals.append((last, point)) 950 last = point 951 952 if last: 953 intervals.append((last, None)) 954 955 if not days.has_key(day): 956 days[day] = set() 957 958 # Convert each partition to a mapping from points to active 959 # periods. 960 961 partitioned[day] = dict(day_slots) 962 963 # Record the divisions or intervals within each day. 964 965 days[day].update(intervals) 966 967 if group_type != "request" or columns: 968 group_columns.append(columns) 969 partitioned_groups.append(partitioned) 970 partitioned_group_types.append(group_type) 971 partitioned_group_sources.append(group_source) 972 973 self.show_calendar_day_controls(days) 974 975 page.table(cellspacing=5, cellpadding=5, class_="calendar") 976 self.show_calendar_participant_headings(partitioned_group_types, partitioned_group_sources, group_columns) 977 self.show_calendar_days(days, partitioned_groups, partitioned_group_types, group_columns) 978 page.table.close() 979 980 # End the form region. 981 982 page.form.close() 983 984 # More page fragment methods. 985 986 def show_calendar_day_controls(self, days): 987 988 "Show controls for the given 'days' in the calendar." 989 990 page = self.page 991 slots = self.env.get_args().get("slot", []) 992 993 for day in days: 994 value, identifier = self._day_value_and_identifier(day) 995 self._slot_selector(value, identifier, slots) 996 997 # Generate a dynamic stylesheet to allow day selections to colour 998 # specific days. 999 # NOTE: The style details need to be coordinated with the static 1000 # NOTE: stylesheet. 1001 1002 page.style(type="text/css") 1003 1004 for day in days: 1005 daystr = format_datetime(day) 1006 page.add("""\ 1007 input.newevent.selector#day-%s-:checked ~ table label.day.day-%s, 1008 input.newevent.selector#day-%s-:checked ~ table label.timepoint.day-%s { 1009 background-color: #5f4; 1010 text-decoration: underline; 1011 } 1012 """ % (daystr, daystr, daystr, daystr)) 1013 1014 page.style.close() 1015 1016 def show_calendar_participant_headings(self, group_types, group_sources, group_columns): 1017 1018 """ 1019 Show headings for the participants and other scheduling contributors, 1020 defined by 'group_types', 'group_sources' and 'group_columns'. 1021 """ 1022 1023 page = self.page 1024 1025 page.colgroup(span=1, id="columns-timeslot") 1026 1027 for group_type, columns in zip(group_types, group_columns): 1028 page.colgroup(span=max(columns, 1), id="columns-%s" % group_type) 1029 1030 page.thead() 1031 page.tr() 1032 page.th("", class_="emptyheading") 1033 1034 for group_type, source, columns in zip(group_types, group_sources, group_columns): 1035 page.th(source, 1036 class_=(group_type == "request" and "requestheading" or "participantheading"), 1037 colspan=max(columns, 1)) 1038 1039 page.tr.close() 1040 page.thead.close() 1041 1042 def show_calendar_days(self, days, partitioned_groups, partitioned_group_types, group_columns): 1043 1044 """ 1045 Show calendar days, defined by a collection of 'days', the contributing 1046 period information as 'partitioned_groups' (partitioned by day), the 1047 'partitioned_group_types' indicating the kind of contribution involved, 1048 and the 'group_columns' defining the number of columns in each group. 1049 """ 1050 1051 page = self.page 1052 1053 # Determine the number of columns required. Where participants provide 1054 # no columns for events, one still needs to be provided for the 1055 # participant itself. 1056 1057 all_columns = sum([max(columns, 1) for columns in group_columns]) 1058 1059 # Determine the days providing time slots. 1060 1061 all_days = days.items() 1062 all_days.sort() 1063 1064 # Produce a heading and time points for each day. 1065 1066 for day, intervals in all_days: 1067 page.thead() 1068 page.tr() 1069 page.th(class_="dayheading container", colspan=all_columns+1) 1070 self._day_heading(day) 1071 page.th.close() 1072 page.tr.close() 1073 page.thead.close() 1074 1075 groups_for_day = [partitioned.get(day) for partitioned in partitioned_groups] 1076 1077 page.tbody() 1078 self.show_calendar_points(intervals, groups_for_day, partitioned_group_types, group_columns) 1079 page.tbody.close() 1080 1081 def show_calendar_points(self, intervals, groups, group_types, group_columns): 1082 1083 """ 1084 Show the time 'intervals' along with period information from the given 1085 'groups', having the indicated 'group_types', each with the number of 1086 columns given by 'group_columns'. 1087 """ 1088 1089 page = self.page 1090 1091 # Obtain the user's timezone. 1092 1093 tzid = self.get_tzid() 1094 1095 # Produce a row for each interval. 1096 1097 intervals = list(intervals) 1098 intervals.sort() 1099 1100 for point, endpoint in intervals: 1101 continuation = point == get_start_of_day(point, tzid) 1102 1103 # Some rows contain no period details and are marked as such. 1104 1105 have_active = reduce(lambda x, y: x or y, [slots.get(point) for slots in groups], None) 1106 1107 css = " ".join( 1108 ["slot"] + 1109 (have_active and ["busy"] or ["empty"]) + 1110 (continuation and ["daystart"] or []) 1111 ) 1112 1113 page.tr(class_=css) 1114 page.th(class_="timeslot") 1115 self._time_point(point, endpoint) 1116 page.th.close() 1117 1118 # Obtain slots for the time point from each group. 1119 1120 for columns, slots, group_type in zip(group_columns, groups, group_types): 1121 active = slots and slots.get(point) 1122 1123 # Where no periods exist for the given time interval, generate 1124 # an empty cell. Where a participant provides no periods at all, 1125 # the colspan is adjusted to be 1, not 0. 1126 1127 if not active: 1128 page.td(class_="empty container", colspan=max(columns, 1)) 1129 self._empty_slot(point, endpoint) 1130 page.td.close() 1131 continue 1132 1133 slots = slots.items() 1134 slots.sort() 1135 spans = get_spans(slots) 1136 1137 # Show a column for each active period. 1138 1139 for t in active: 1140 if t and len(t) >= 2: 1141 start, end, uid, key = get_freebusy_details(t) 1142 span = spans[key] 1143 1144 # Produce a table cell only at the start of the period 1145 # or when continued at the start of a day. 1146 1147 if point == start or continuation: 1148 1149 has_continued = continuation and point != start 1150 will_continue = not ends_on_same_day(point, end, tzid) 1151 css = " ".join( 1152 ["event"] + 1153 (has_continued and ["continued"] or []) + 1154 (will_continue and ["continues"] or []) 1155 ) 1156 1157 # Only anchor the first cell of events. 1158 1159 if point == start: 1160 page.td(class_=css, rowspan=span, id="%s-%s" % (group_type, uid)) 1161 else: 1162 page.td(class_=css, rowspan=span) 1163 1164 obj = self._get_object(uid) 1165 1166 if not obj: 1167 page.span("") 1168 else: 1169 summary = obj.get_value("SUMMARY") 1170 1171 # Only link to events if they are not being 1172 # updated by requests. 1173 1174 if uid in self._get_requests() and group_type != "request": 1175 page.span(summary) 1176 else: 1177 href = "%s/%s" % (self.env.get_url().rstrip("/"), uid) 1178 page.a(summary, href=href) 1179 1180 page.td.close() 1181 else: 1182 page.td(class_="empty container") 1183 self._empty_slot(point, endpoint) 1184 page.td.close() 1185 1186 # Pad with empty columns. 1187 1188 i = columns - len(active) 1189 while i > 0: 1190 i -= 1 1191 page.td(class_="empty container") 1192 self._empty_slot(point, endpoint) 1193 page.td.close() 1194 1195 page.tr.close() 1196 1197 def _day_heading(self, day): 1198 1199 """ 1200 Generate a heading for 'day' of the following form: 1201 1202 <label class="day day-20150203" for="day-20150203">Tuesday, 3 February 2015</label> 1203 """ 1204 1205 page = self.page 1206 daystr = format_datetime(day) 1207 value, identifier = self._day_value_and_identifier(day) 1208 page.label(self.format_date(day, "full"), class_="day day-%s" % daystr, for_=identifier) 1209 1210 def _time_point(self, point, endpoint): 1211 1212 """ 1213 Generate headings for the 'point' to 'endpoint' period of the following 1214 form: 1215 1216 <label class="timepoint day-20150203" for="slot-20150203T090000-20150203T100000">09:00:00 CET</label> 1217 <span class="endpoint">10:00:00 CET</span> 1218 """ 1219 1220 page = self.page 1221 tzid = self.get_tzid() 1222 daystr = format_datetime(point.date()) 1223 value, identifier = self._slot_value_and_identifier(point, endpoint) 1224 slots = self.env.get_args().get("slot", []) 1225 self._slot_selector(value, identifier, slots) 1226 page.label(self.format_time(point, "long"), class_="timepoint day-%s" % daystr, for_=identifier) 1227 page.span(self.format_time(endpoint or get_end_of_day(point, tzid), "long"), class_="endpoint") 1228 1229 def _slot_selector(self, value, identifier, slots): 1230 reset = self.env.get_args().has_key("reset") 1231 page = self.page 1232 if not reset and value in slots: 1233 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector", checked="checked") 1234 else: 1235 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector") 1236 1237 def _empty_slot(self, point, endpoint): 1238 page = self.page 1239 value, identifier = self._slot_value_and_identifier(point, endpoint) 1240 page.label("Select/deselect period", class_="newevent popup", for_=identifier) 1241 1242 def _day_value_and_identifier(self, day): 1243 value = "%s-" % format_datetime(day) 1244 identifier = "day-%s" % value 1245 return value, identifier 1246 1247 def _slot_value_and_identifier(self, point, endpoint): 1248 value = "%s-%s" % (format_datetime(point), endpoint and format_datetime(endpoint) or "") 1249 identifier = "slot-%s" % value 1250 return value, identifier 1251 1252 def _show_menu(self, name, value, items): 1253 page = self.page 1254 values = self.env.get_args().get(name, [value]) 1255 page.select(name=name) 1256 for v, label in items: 1257 if v in values: 1258 page.option(label, value=v, selected="selected") 1259 else: 1260 page.option(label, value=v) 1261 page.select.close() 1262 1263 # Incoming HTTP request direction. 1264 1265 def select_action(self): 1266 1267 "Select the desired action and show the result." 1268 1269 path_info = self.env.get_path_info().strip("/") 1270 1271 if not path_info: 1272 self.show_calendar() 1273 elif self.show_object(path_info): 1274 pass 1275 else: 1276 self.no_page() 1277 1278 def __call__(self): 1279 1280 "Interpret a request and show an appropriate response." 1281 1282 if not self.user: 1283 self.no_user() 1284 else: 1285 self.select_action() 1286 1287 # Write the headers and actual content. 1288 1289 print >>self.out, "Content-Type: text/html; charset=%s" % self.encoding 1290 print >>self.out 1291 self.out.write(unicode(self.page).encode(self.encoding)) 1292 1293 if __name__ == "__main__": 1294 Manager()() 1295 1296 # vim: tabstop=4 expandtab shiftwidth=4