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, Object, to_part 35 from imiptools.dates import format_datetime, format_time, get_date, get_datetime, \ 36 get_datetime_item, get_default_timezone, \ 37 get_end_of_day, get_start_of_day, get_start_of_next_day, \ 38 get_timestamp, ends_on_same_day, to_timezone 39 from imiptools.mail import Messenger 40 from imiptools.period import add_day_start_points, add_empty_days, add_slots, \ 41 convert_periods, get_freebusy_details, \ 42 get_scale, have_conflict, get_slots, get_spans, \ 43 partition_by_day, remove_from_freebusy, update_freebusy 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 user_attr = self.messenger and self.messenger.sender != get_address(self.user) and \ 161 {"SENT-BY" : get_uri(self.messenger.sender)} or {} 162 163 parts.append(to_part("PUBLISH", [ 164 make_freebusy(freebusy, uid, self.user, user_attr) 165 ])) 166 167 message = self.messenger.make_outgoing_message(parts, recipients, outgoing_bcc=sender) 168 self.messenger.sendmail(recipients, message.as_string(), outgoing_bcc=sender) 169 170 # Action methods. 171 172 def process_received_request(self, update=False): 173 174 """ 175 Process the current request for the given 'user'. Return whether any 176 action was taken. 177 178 If 'update' is given, the sequence number will be incremented in order 179 to override any previous response. 180 """ 181 182 # Reply only on behalf of this user. 183 184 for attendee, attendee_attr in self.obj.get_items("ATTENDEE"): 185 186 if attendee == self.user: 187 if attendee_attr.has_key("RSVP"): 188 del attendee_attr["RSVP"] 189 if self.messenger and self.messenger.sender != get_address(attendee): 190 attendee_attr["SENT-BY"] = get_uri(self.messenger.sender) 191 self.obj["ATTENDEE"] = [(attendee, attendee_attr)] 192 193 self.update_dtstamp() 194 self.set_sequence(update) 195 196 self.send_message("REPLY", get_address(attendee), for_organiser=False) 197 198 return True 199 200 return False 201 202 def process_created_request(self, method, update=False): 203 204 """ 205 Process the current request for the given 'user', sending a created 206 request of the given 'method' to attendees. Return whether any action 207 was taken. 208 209 If 'update' is given, the sequence number will be incremented in order 210 to override any previous message. 211 """ 212 213 organiser, organiser_attr = self.obj.get_item("ORGANIZER") 214 215 if self.messenger and self.messenger.sender != get_address(organiser): 216 organiser_attr["SENT-BY"] = get_uri(self.messenger.sender) 217 218 self.update_dtstamp() 219 self.set_sequence(update) 220 221 self.send_message(method, get_address(self.organiser), for_organiser=True) 222 return True 223 224 class Manager: 225 226 "A simple manager application." 227 228 def __init__(self, messenger=None): 229 self.messenger = messenger or Messenger() 230 231 self.encoding = "utf-8" 232 self.env = CGIEnvironment(self.encoding) 233 234 user = self.env.get_user() 235 self.user = user and get_uri(user) or None 236 self.preferences = None 237 self.locale = None 238 self.requests = None 239 240 self.out = self.env.get_output() 241 self.page = markup.page() 242 243 self.store = imip_store.FileStore() 244 self.objects = {} 245 246 try: 247 self.publisher = imip_store.FilePublisher() 248 except OSError: 249 self.publisher = None 250 251 def _get_uid(self, path_info): 252 return path_info.lstrip("/").split("/", 1)[0] 253 254 def _get_object(self, uid): 255 if self.objects.has_key(uid): 256 return self.objects[uid] 257 258 fragment = uid and self.store.get_event(self.user, uid) or None 259 obj = self.objects[uid] = fragment and Object(fragment) 260 return obj 261 262 def _get_requests(self): 263 if self.requests is None: 264 self.requests = self.store.get_requests(self.user) 265 return self.requests 266 267 def _get_request_summary(self): 268 summary = [] 269 for uid in self._get_requests(): 270 obj = self._get_object(uid) 271 if obj: 272 summary.append(( 273 obj.get_value("DTSTART"), 274 obj.get_value("DTEND"), 275 uid 276 )) 277 return summary 278 279 # Preference methods. 280 281 def get_user_locale(self): 282 if not self.locale: 283 self.locale = self.get_preferences().get("LANG", "C") 284 return self.locale 285 286 def get_preferences(self): 287 if not self.preferences: 288 self.preferences = Preferences(self.user) 289 return self.preferences 290 291 def get_tzid(self): 292 prefs = self.get_preferences() 293 return prefs.get("TZID") or get_default_timezone() 294 295 # Prettyprinting of dates and times. 296 297 def format_date(self, dt, format): 298 return self._format_datetime(babel.dates.format_date, dt, format) 299 300 def format_time(self, dt, format): 301 return self._format_datetime(babel.dates.format_time, dt, format) 302 303 def format_datetime(self, dt, format): 304 return self._format_datetime( 305 isinstance(dt, datetime) and babel.dates.format_datetime or babel.dates.format_date, 306 dt, format) 307 308 def _format_datetime(self, fn, dt, format): 309 return fn(dt, format=format, locale=self.get_user_locale()) 310 311 # Data management methods. 312 313 def remove_request(self, uid): 314 return self.store.dequeue_request(self.user, uid) 315 316 def remove_event(self, uid): 317 return self.store.remove_event(self.user, uid) 318 319 def update_freebusy(self, uid, obj): 320 tzid = self.get_tzid() 321 freebusy = self.store.get_freebusy(self.user) 322 update_freebusy(freebusy, self.user, obj.get_periods_for_freebusy(tzid), 323 obj.get_value("TRANSP"), uid, self.store) 324 325 def remove_from_freebusy(self, uid): 326 freebusy = self.store.get_freebusy(self.user) 327 remove_from_freebusy(freebusy, self.user, uid, self.store) 328 329 # Presentation methods. 330 331 def new_page(self, title): 332 self.page.init(title=title, charset=self.encoding, css=self.env.new_url("styles.css")) 333 334 def status(self, code, message): 335 self.header("Status", "%s %s" % (code, message)) 336 337 def header(self, header, value): 338 print >>self.out, "%s: %s" % (header, value) 339 340 def no_user(self): 341 self.status(403, "Forbidden") 342 self.new_page(title="Forbidden") 343 self.page.p("You are not logged in and thus cannot access scheduling requests.") 344 345 def no_page(self): 346 self.status(404, "Not Found") 347 self.new_page(title="Not Found") 348 self.page.p("No page is provided at the given address.") 349 350 def redirect(self, url): 351 self.status(302, "Redirect") 352 self.header("Location", url) 353 self.new_page(title="Redirect") 354 self.page.p("Redirecting to: %s" % url) 355 356 # Request logic methods. 357 358 def handle_newevent(self): 359 360 """ 361 Handle any new event operation, creating a new event and redirecting to 362 the event page for further activity. 363 """ 364 365 # Handle a submitted form. 366 367 args = self.env.get_args() 368 369 if not args.has_key("newevent"): 370 return 371 372 # Create a new event using the available information. 373 374 slots = args.get("slot", []) 375 participants = args.get("participants", []) 376 377 if not slots: 378 return 379 380 # Obtain the user's timezone. 381 382 tzid = self.get_tzid() 383 384 # Coalesce the selected slots. 385 386 slots.sort() 387 coalesced = [] 388 last = None 389 390 for slot in slots: 391 start, end = slot.split("-") 392 start = get_datetime(start, {"TZID" : tzid}) 393 end = end and get_datetime(end, {"TZID" : tzid}) or get_start_of_next_day(start, tzid) 394 395 if last: 396 last_start, last_end = last 397 398 # Merge adjacent dates and datetimes. 399 400 if start == last_end or get_start_of_day(last_end, tzid) == get_start_of_day(start, tzid): 401 last = last_start, end 402 continue 403 404 # Handle datetimes within dates. 405 # Datetime periods are within single days and are therefore 406 # discarded. 407 408 elif get_start_of_day(start, tzid) == get_start_of_day(last_start, tzid): 409 continue 410 411 # Add separate dates and datetimes. 412 413 else: 414 coalesced.append(last) 415 416 last = start, end 417 418 if last: 419 coalesced.append(last) 420 421 # Invent a unique identifier. 422 423 utcnow = get_timestamp() 424 uid = "imip-agent-%s-%s" % (utcnow, get_address(self.user)) 425 426 # Define a single occurrence if only one coalesced slot exists. 427 # Otherwise, many occurrences are defined. 428 429 for i, (start, end) in enumerate(coalesced): 430 this_uid = "%s-%s" % (uid, i) 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): 464 465 """ 466 Handle actions involving the given 'uid' and 'obj' object, returning an 467 error if one occurred, or None if the request was successfully handled. 468 """ 469 470 # Handle a submitted form. 471 472 args = self.env.get_args() 473 474 # Get the possible actions. 475 476 reply = args.has_key("reply") 477 discard = args.has_key("discard") 478 invite = args.has_key("invite") 479 cancel = args.has_key("cancel") 480 save = args.has_key("save") 481 482 have_action = reply or discard or invite or cancel or save 483 484 if not have_action: 485 return ["action"] 486 487 # Update the object. 488 489 if args.has_key("summary"): 490 obj["SUMMARY"] = [(args["summary"][0], {})] 491 492 if args.has_key("partstat"): 493 organisers = obj.get_value_map("ORGANIZER") 494 attendees = obj.get_value_map("ATTENDEE") 495 for d in attendees, organisers: 496 if d.has_key(self.user): 497 d[self.user]["PARTSTAT"] = args["partstat"][0] 498 if d[self.user].has_key("RSVP"): 499 del d[self.user]["RSVP"] 500 501 is_organiser = obj.get_value("ORGANIZER") == self.user 502 503 # Obtain the user's timezone and process datetime values. 504 505 update = False 506 507 if is_organiser: 508 dtend_enabled = args.get("dtend-control", [None])[0] == "enable" 509 dttimes_enabled = args.get("dttimes-control", [None])[0] == "enable" 510 511 t = self.handle_date_controls("dtstart", dttimes_enabled) 512 if t: 513 dtstart, attr = t 514 update = self.set_datetime_in_object(dtstart, attr.get("TZID"), "DTSTART", obj) or update 515 else: 516 return ["dtstart"] 517 518 # Handle specified end datetimes. 519 520 if dtend_enabled: 521 t = self.handle_date_controls("dtend", dttimes_enabled) 522 if t: 523 dtend, attr = t 524 525 # Convert end dates to iCalendar "next day" dates. 526 527 if not isinstance(dtend, datetime): 528 dtend += timedelta(1) 529 update = self.set_datetime_in_object(dtend, attr.get("TZID"), "DTEND", obj) or update 530 else: 531 return ["dtend"] 532 533 # Otherwise, treat the end date as the start date. Datetimes are 534 # handled by making the event occupy the rest of the day. 535 536 else: 537 dtend = dtstart + timedelta(1) 538 if isinstance(dtstart, datetime): 539 dtend = get_start_of_day(dtend, attr["TZID"]) 540 update = self.set_datetime_in_object(dtend, attr.get("TZID"), "DTEND", obj) or update 541 542 if dtstart >= dtend: 543 return ["dtstart", "dtend"] 544 545 # Process any action. 546 547 handled = True 548 549 if reply or invite or cancel: 550 551 handler = ManagerHandler(obj, self.user, self.messenger) 552 553 # Process the object and remove it from the list of requests. 554 555 if reply and handler.process_received_request(update) or \ 556 (invite or cancel) and handler.process_created_request(invite and "REQUEST" or "CANCEL", update): 557 558 self.remove_request(uid) 559 560 # Save single user events. 561 562 elif save: 563 self.store.set_event(self.user, uid, obj.to_node()) 564 self.update_freebusy(uid, obj) 565 self.remove_request(uid) 566 567 # Remove the request and the object. 568 569 elif discard: 570 self.remove_from_freebusy(uid) 571 self.remove_event(uid) 572 self.remove_request(uid) 573 574 else: 575 handled = False 576 577 # Upon handling an action, redirect to the main page. 578 579 if handled: 580 self.redirect(self.env.get_path()) 581 582 return None 583 584 def handle_date_controls(self, name, with_time=True): 585 586 """ 587 Handle date control information for fields starting with 'name', 588 returning a (datetime, attr) tuple or None if the fields cannot be used 589 to construct a datetime object. 590 """ 591 592 args = self.env.get_args() 593 594 if args.has_key("%s-date" % name): 595 date = args["%s-date" % name][0] 596 597 if with_time: 598 hour = args.get("%s-hour" % name, [None])[0] 599 minute = args.get("%s-minute" % name, [None])[0] 600 second = args.get("%s-second" % name, [None])[0] 601 tzid = args.get("%s-tzid" % name, [self.get_tzid()])[0] 602 603 time = (hour or minute or second) and "T%s%s%s" % (hour, minute, second) or "" 604 value = "%s%s" % (date, time) 605 attr = {"TZID" : tzid, "VALUE" : "DATE-TIME"} 606 dt = get_datetime(value, attr) 607 else: 608 attr = {"VALUE" : "DATE"} 609 dt = get_datetime(date) 610 611 if dt: 612 return dt, attr 613 614 return None 615 616 def set_datetime_in_object(self, dt, tzid, property, obj): 617 618 """ 619 Set 'dt' and 'tzid' for the given 'property' in 'obj', returning whether 620 an update has occurred. 621 """ 622 623 if dt: 624 old_value = obj.get_value(property) 625 obj[property] = [get_datetime_item(dt, tzid)] 626 return format_datetime(dt) != old_value 627 628 return False 629 630 # Page fragment methods. 631 632 def show_request_controls(self, obj): 633 634 "Show form controls for a request concerning 'obj'." 635 636 page = self.page 637 638 is_organiser = obj.get_value("ORGANIZER") == self.user 639 640 attendees = obj.get_value_map("ATTENDEE") 641 is_attendee = attendees.has_key(self.user) 642 attendee_attr = attendees.get(self.user) 643 644 is_request = obj.get_value("UID") in self._get_requests() 645 646 have_other_attendees = len(attendees) > (is_attendee and 1 or 0) 647 648 # Show appropriate options depending on the role of the user. 649 650 if is_attendee and not is_organiser: 651 page.p("An action is required for this request:") 652 653 page.p() 654 page.input(name="reply", type="submit", value="Reply") 655 page.add(" ") 656 page.input(name="discard", type="submit", value="Discard") 657 page.p.close() 658 659 if is_organiser: 660 if have_other_attendees: 661 page.p("As organiser, you can perform the following:") 662 663 page.p() 664 page.input(name="invite", type="submit", value="Invite") 665 page.add(" ") 666 if is_request: 667 page.input(name="discard", type="submit", value="Discard") 668 else: 669 page.input(name="cancel", type="submit", value="Cancel") 670 page.p.close() 671 else: 672 page.p() 673 page.input(name="save", type="submit", value="Save") 674 page.add(" ") 675 page.input(name="discard", type="submit", value="Discard") 676 page.p.close() 677 678 property_items = [ 679 ("SUMMARY", "Summary"), 680 ("DTSTART", "Start"), 681 ("DTEND", "End"), 682 ("ORGANIZER", "Organiser"), 683 ("ATTENDEE", "Attendee"), 684 ] 685 686 partstat_items = [ 687 ("NEEDS-ACTION", "Not confirmed"), 688 ("ACCEPTED", "Attending"), 689 ("TENTATIVE", "Tentatively attending"), 690 ("DECLINED", "Not attending"), 691 ("DELEGATED", "Delegated"), 692 ] 693 694 def show_object_on_page(self, uid, obj, error=None): 695 696 """ 697 Show the calendar object with the given 'uid' and representation 'obj' 698 on the current page. If 'error' is given, show a suitable message. 699 """ 700 701 page = self.page 702 page.form(method="POST") 703 704 # Obtain the user's timezone. 705 706 tzid = self.get_tzid() 707 708 # Provide controls to change the displayed object. 709 710 args = self.env.get_args() 711 dtend_control = args.get("dtend-control", [None])[0] 712 dttimes_control = args.get("dttimes-control", [None])[0] 713 with_time = dttimes_control == "enable" 714 715 t = self.handle_date_controls("dtstart", with_time) 716 if t: 717 dtstart, dtstart_attr = t 718 else: 719 dtstart, dtstart_attr = obj.get_datetime_item("DTSTART") 720 721 if dtend_control == "enable": 722 t = self.handle_date_controls("dtend", with_time) 723 if t: 724 dtend, dtend_attr = t 725 else: 726 dtend, dtend_attr = None, {} 727 elif dtend_control == "disable": 728 dtend, dtend_attr = None, {} 729 else: 730 dtend, dtend_attr = obj.get_datetime_item("DTEND") 731 732 # Change end dates to refer to the actual dates, not the iCalendar 733 # "next day" dates. 734 735 if dtend and not isinstance(dtend, datetime): 736 dtend -= timedelta(1) 737 738 # Show the end datetime controls if already active or if an object needs 739 # them. 740 741 dtend_enabled = dtend_control == "enable" or isinstance(dtend, datetime) or dtstart != dtend 742 dttimes_enabled = dttimes_control == "enable" or isinstance(dtstart, datetime) or isinstance(dtend, datetime) 743 744 if dtend_enabled: 745 page.input(name="dtend-control", type="radio", value="enable", id="dtend-enable", checked="checked") 746 page.input(name="dtend-control", type="radio", value="disable", id="dtend-disable") 747 else: 748 page.input(name="dtend-control", type="radio", value="enable", id="dtend-enable") 749 page.input(name="dtend-control", type="radio", value="disable", id="dtend-disable", checked="checked") 750 751 if dttimes_enabled: 752 page.input(name="dttimes-control", type="radio", value="enable", id="dttimes-enable", checked="checked") 753 page.input(name="dttimes-control", type="radio", value="disable", id="dttimes-disable") 754 else: 755 page.input(name="dttimes-control", type="radio", value="enable", id="dttimes-enable") 756 page.input(name="dttimes-control", type="radio", value="disable", id="dttimes-disable", checked="checked") 757 758 # Provide a summary of the object. 759 760 page.table(class_="object", cellspacing=5, cellpadding=5) 761 page.thead() 762 page.tr() 763 page.th("Event", class_="mainheading", colspan=2) 764 page.tr.close() 765 page.thead.close() 766 page.tbody() 767 768 is_organiser = obj.get_value("ORGANIZER") == self.user 769 770 for name, label in self.property_items: 771 page.tr() 772 773 # Handle datetimes specially. 774 775 if name in ["DTSTART", "DTEND"]: 776 field = name.lower() 777 778 page.th(label, class_="objectheading %s%s" % (field, error and field in error and " error" or "")) 779 780 # Obtain the datetime. 781 782 if name == "DTSTART": 783 dt, attr, event_tzid = dtstart, dtstart_attr, dtstart_attr.get("TZID", tzid) 784 785 # Where no end datetime exists, use the start datetime as the 786 # basis of any potential datetime specified if dt-control is 787 # set. 788 789 else: 790 dt, attr, event_tzid = dtend or dtstart, dtend_attr or dtstart_attr, (dtend_attr or dtstart_attr).get("TZID", tzid) 791 792 # Show controls for editing as organiser. 793 794 if is_organiser: 795 value = format_datetime(dt) 796 797 page.td(class_="objectvalue %s" % field) 798 if name == "DTEND": 799 page.div(class_="dt disabled") 800 page.label("Specify end date", for_="dtend-enable", class_="enable") 801 page.div.close() 802 803 page.div(class_="dt enabled") 804 self._show_date_controls(field, value, attr, tzid) 805 if name == "DTSTART": 806 page.label("Specify times", for_="dttimes-enable", class_="time disabled enable") 807 page.label("Specify dates only", for_="dttimes-disable", class_="time enabled disable") 808 elif name == "DTEND": 809 page.label("End on same day", for_="dtend-disable", class_="disable") 810 page.div.close() 811 812 page.td.close() 813 814 # Show a label as attendee. 815 816 else: 817 page.td(self.format_datetime(dt, "full")) 818 819 page.tr.close() 820 821 # Handle the summary specially. 822 823 elif name == "SUMMARY": 824 value = args.get("summary", [obj.get_value(name)])[0] 825 826 page.th(label, class_="objectheading") 827 page.td() 828 if is_organiser: 829 page.input(name="summary", type="text", value=value, size=80) 830 else: 831 page.add(value) 832 page.td.close() 833 page.tr.close() 834 835 # Handle potentially many values. 836 837 else: 838 items = obj.get_items(name) 839 if not items: 840 continue 841 842 page.th(label, class_="objectheading", rowspan=len(items)) 843 844 first = True 845 846 for value, attr in items: 847 if not first: 848 page.tr() 849 else: 850 first = False 851 852 if name in ("ATTENDEE", "ORGANIZER"): 853 page.td(class_="objectattribute") 854 page.add(value) 855 page.add(" ") 856 857 partstat = attr.get("PARTSTAT") 858 if value == self.user and (not is_organiser or name == "ORGANIZER"): 859 self._show_menu("partstat", partstat, self.partstat_items) 860 else: 861 page.span(dict(self.partstat_items).get(partstat, ""), class_="partstat") 862 else: 863 page.td(class_="objectattribute") 864 page.add(value) 865 866 page.td.close() 867 page.tr.close() 868 869 page.tbody.close() 870 page.table.close() 871 872 dtstart = format_datetime(obj.get_utc_datetime("DTSTART")) 873 dtend = format_datetime(obj.get_utc_datetime("DTEND")) 874 875 # Indicate whether there are conflicting events. 876 877 freebusy = self.store.get_freebusy(self.user) 878 879 if freebusy: 880 881 # Obtain any time zone details from the suggested event. 882 883 _dtstart, attr = obj.get_item("DTSTART") 884 tzid = attr.get("TZID", tzid) 885 886 # Show any conflicts. 887 888 for t in have_conflict(freebusy, [(dtstart, dtend)], True): 889 start, end, found_uid = t[:3] 890 891 # Provide details of any conflicting event. 892 893 if uid != found_uid: 894 start = self.format_datetime(to_timezone(get_datetime(start), tzid), "full") 895 end = self.format_datetime(to_timezone(get_datetime(end), tzid), "full") 896 page.p("Event conflicts with another from %s to %s: " % (start, end)) 897 898 # Show the event summary for the conflicting event. 899 900 found_obj = self._get_object(found_uid) 901 if found_obj: 902 page.a(found_obj.get_value("SUMMARY"), href=self.env.new_url(found_uid)) 903 904 self.show_request_controls(obj) 905 page.form.close() 906 907 def show_requests_on_page(self): 908 909 "Show requests for the current user." 910 911 # NOTE: This list could be more informative, but it is envisaged that 912 # NOTE: the requests would be visited directly anyway. 913 914 requests = self._get_requests() 915 916 self.page.div(id="pending-requests") 917 918 if requests: 919 self.page.p("Pending requests:") 920 921 self.page.ul() 922 923 for request in requests: 924 obj = self._get_object(request) 925 if obj: 926 self.page.li() 927 self.page.a(obj.get_value("SUMMARY"), href="#request-%s" % request) 928 self.page.li.close() 929 930 self.page.ul.close() 931 932 else: 933 self.page.p("There are no pending requests.") 934 935 self.page.div.close() 936 937 def show_participants_on_page(self): 938 939 "Show participants for scheduling purposes." 940 941 args = self.env.get_args() 942 participants = args.get("participants", []) 943 944 try: 945 for name, value in args.items(): 946 if name.startswith("remove-participant-"): 947 i = int(name[len("remove-participant-"):]) 948 del participants[i] 949 break 950 except ValueError: 951 pass 952 953 # Trim empty participants. 954 955 while participants and not participants[-1].strip(): 956 participants.pop() 957 958 # Show any specified participants together with controls to remove and 959 # add participants. 960 961 self.page.div(id="participants") 962 963 self.page.p("Participants for scheduling:") 964 965 for i, participant in enumerate(participants): 966 self.page.p() 967 self.page.input(name="participants", type="text", value=participant) 968 self.page.input(name="remove-participant-%d" % i, type="submit", value="Remove") 969 self.page.p.close() 970 971 self.page.p() 972 self.page.input(name="participants", type="text") 973 self.page.input(name="add-participant", type="submit", value="Add") 974 self.page.p.close() 975 976 self.page.div.close() 977 978 return participants 979 980 # Full page output methods. 981 982 def show_object(self, path_info): 983 984 "Show an object request using the given 'path_info' for the current user." 985 986 uid = self._get_uid(path_info) 987 obj = self._get_object(uid) 988 989 if not obj: 990 return False 991 992 error = self.handle_request(uid, obj) 993 994 if not error: 995 return True 996 997 self.new_page(title="Event") 998 self.show_object_on_page(uid, obj, error) 999 1000 return True 1001 1002 def show_calendar(self): 1003 1004 "Show the calendar for the current user." 1005 1006 handled = self.handle_newevent() 1007 1008 self.new_page(title="Calendar") 1009 page = self.page 1010 1011 # Form controls are used in various places on the calendar page. 1012 1013 page.form(method="POST") 1014 1015 self.show_requests_on_page() 1016 participants = self.show_participants_on_page() 1017 1018 # Show a button for scheduling a new event. 1019 1020 page.p(class_="controls") 1021 page.input(name="newevent", type="submit", value="New event", id="newevent") 1022 page.input(name="reset", type="submit", value="Clear selections", id="reset") 1023 page.p.close() 1024 1025 # Show controls for hiding empty days and busy slots. 1026 # The positioning of the control, paragraph and table are important here. 1027 1028 page.input(name="showdays", type="checkbox", value="show", id="showdays", accesskey="D") 1029 page.input(name="hidebusy", type="checkbox", value="hide", id="hidebusy", accesskey="B") 1030 1031 page.p(class_="controls") 1032 page.label("Hide busy time periods", for_="hidebusy", class_="hidebusy enable") 1033 page.label("Show busy time periods", for_="hidebusy", class_="hidebusy disable") 1034 page.label("Show empty days", for_="showdays", class_="showdays disable") 1035 page.label("Hide empty days", for_="showdays", class_="showdays enable") 1036 page.p.close() 1037 1038 freebusy = self.store.get_freebusy(self.user) 1039 1040 if not freebusy: 1041 page.p("No events scheduled.") 1042 return 1043 1044 # Obtain the user's timezone. 1045 1046 tzid = self.get_tzid() 1047 1048 # Day view: start at the earliest known day and produce days until the 1049 # latest known day, perhaps with expandable sections of empty days. 1050 1051 # Month view: start at the earliest known month and produce months until 1052 # the latest known month, perhaps with expandable sections of empty 1053 # months. 1054 1055 # Details of users to invite to new events could be superimposed on the 1056 # calendar. 1057 1058 # Requests are listed and linked to their tentative positions in the 1059 # calendar. Other participants are also shown. 1060 1061 request_summary = self._get_request_summary() 1062 1063 period_groups = [request_summary, freebusy] 1064 period_group_types = ["request", "freebusy"] 1065 period_group_sources = ["Pending requests", "Your schedule"] 1066 1067 for i, participant in enumerate(participants): 1068 period_groups.append(self.store.get_freebusy_for_other(self.user, get_uri(participant))) 1069 period_group_types.append("freebusy-part%d" % i) 1070 period_group_sources.append(participant) 1071 1072 groups = [] 1073 group_columns = [] 1074 group_types = period_group_types 1075 group_sources = period_group_sources 1076 all_points = set() 1077 1078 # Obtain time point information for each group of periods. 1079 1080 for periods in period_groups: 1081 periods = convert_periods(periods, tzid) 1082 1083 # Get the time scale with start and end points. 1084 1085 scale = get_scale(periods) 1086 1087 # Get the time slots for the periods. 1088 1089 slots = get_slots(scale) 1090 1091 # Add start of day time points for multi-day periods. 1092 1093 add_day_start_points(slots, tzid) 1094 1095 # Record the slots and all time points employed. 1096 1097 groups.append(slots) 1098 all_points.update([point for point, active in slots]) 1099 1100 # Partition the groups into days. 1101 1102 days = {} 1103 partitioned_groups = [] 1104 partitioned_group_types = [] 1105 partitioned_group_sources = [] 1106 1107 for slots, group_type, group_source in zip(groups, group_types, group_sources): 1108 1109 # Propagate time points to all groups of time slots. 1110 1111 add_slots(slots, all_points) 1112 1113 # Count the number of columns employed by the group. 1114 1115 columns = 0 1116 1117 # Partition the time slots by day. 1118 1119 partitioned = {} 1120 1121 for day, day_slots in partition_by_day(slots).items(): 1122 intervals = [] 1123 last = None 1124 1125 for point, active in day_slots: 1126 columns = max(columns, len(active)) 1127 if last: 1128 intervals.append((last, point)) 1129 last = point 1130 1131 if last: 1132 intervals.append((last, None)) 1133 1134 if not days.has_key(day): 1135 days[day] = set() 1136 1137 # Convert each partition to a mapping from points to active 1138 # periods. 1139 1140 partitioned[day] = dict(day_slots) 1141 1142 # Record the divisions or intervals within each day. 1143 1144 days[day].update(intervals) 1145 1146 if group_type != "request" or columns: 1147 group_columns.append(columns) 1148 partitioned_groups.append(partitioned) 1149 partitioned_group_types.append(group_type) 1150 partitioned_group_sources.append(group_source) 1151 1152 # Add empty days. 1153 1154 add_empty_days(days, tzid) 1155 1156 # Show the controls permitting day selection. 1157 1158 self.show_calendar_day_controls(days) 1159 1160 # Show the calendar itself. 1161 1162 page.table(cellspacing=5, cellpadding=5, class_="calendar") 1163 self.show_calendar_participant_headings(partitioned_group_types, partitioned_group_sources, group_columns) 1164 self.show_calendar_days(days, partitioned_groups, partitioned_group_types, group_columns) 1165 page.table.close() 1166 1167 # End the form region. 1168 1169 page.form.close() 1170 1171 # More page fragment methods. 1172 1173 def show_calendar_day_controls(self, days): 1174 1175 "Show controls for the given 'days' in the calendar." 1176 1177 page = self.page 1178 slots = self.env.get_args().get("slot", []) 1179 1180 for day in days: 1181 value, identifier = self._day_value_and_identifier(day) 1182 self._slot_selector(value, identifier, slots) 1183 1184 # Generate a dynamic stylesheet to allow day selections to colour 1185 # specific days. 1186 # NOTE: The style details need to be coordinated with the static 1187 # NOTE: stylesheet. 1188 1189 page.style(type="text/css") 1190 1191 for day in days: 1192 daystr = format_datetime(day) 1193 page.add("""\ 1194 input.newevent.selector#day-%s-:checked ~ table label.day.day-%s, 1195 input.newevent.selector#day-%s-:checked ~ table label.timepoint.day-%s { 1196 background-color: #5f4; 1197 text-decoration: underline; 1198 } 1199 """ % (daystr, daystr, daystr, daystr)) 1200 1201 page.style.close() 1202 1203 def show_calendar_participant_headings(self, group_types, group_sources, group_columns): 1204 1205 """ 1206 Show headings for the participants and other scheduling contributors, 1207 defined by 'group_types', 'group_sources' and 'group_columns'. 1208 """ 1209 1210 page = self.page 1211 1212 page.colgroup(span=1, id="columns-timeslot") 1213 1214 for group_type, columns in zip(group_types, group_columns): 1215 page.colgroup(span=max(columns, 1), id="columns-%s" % group_type) 1216 1217 page.thead() 1218 page.tr() 1219 page.th("", class_="emptyheading") 1220 1221 for group_type, source, columns in zip(group_types, group_sources, group_columns): 1222 page.th(source, 1223 class_=(group_type == "request" and "requestheading" or "participantheading"), 1224 colspan=max(columns, 1)) 1225 1226 page.tr.close() 1227 page.thead.close() 1228 1229 def show_calendar_days(self, days, partitioned_groups, partitioned_group_types, group_columns): 1230 1231 """ 1232 Show calendar days, defined by a collection of 'days', the contributing 1233 period information as 'partitioned_groups' (partitioned by day), the 1234 'partitioned_group_types' indicating the kind of contribution involved, 1235 and the 'group_columns' defining the number of columns in each group. 1236 """ 1237 1238 page = self.page 1239 1240 # Determine the number of columns required. Where participants provide 1241 # no columns for events, one still needs to be provided for the 1242 # participant itself. 1243 1244 all_columns = sum([max(columns, 1) for columns in group_columns]) 1245 1246 # Determine the days providing time slots. 1247 1248 all_days = days.items() 1249 all_days.sort() 1250 1251 # Produce a heading and time points for each day. 1252 1253 for day, intervals in all_days: 1254 groups_for_day = [partitioned.get(day) for partitioned in partitioned_groups] 1255 is_empty = True 1256 1257 for slots in groups_for_day: 1258 if not slots: 1259 continue 1260 1261 for active in slots.values(): 1262 if active: 1263 is_empty = False 1264 break 1265 1266 page.thead(class_="separator%s" % (is_empty and " empty" or "")) 1267 page.tr() 1268 page.th(class_="dayheading container", colspan=all_columns+1) 1269 self._day_heading(day) 1270 page.th.close() 1271 page.tr.close() 1272 page.thead.close() 1273 1274 page.tbody(class_="points%s" % (is_empty and " empty" or "")) 1275 self.show_calendar_points(intervals, groups_for_day, partitioned_group_types, group_columns) 1276 page.tbody.close() 1277 1278 def show_calendar_points(self, intervals, groups, group_types, group_columns): 1279 1280 """ 1281 Show the time 'intervals' along with period information from the given 1282 'groups', having the indicated 'group_types', each with the number of 1283 columns given by 'group_columns'. 1284 """ 1285 1286 page = self.page 1287 1288 # Obtain the user's timezone. 1289 1290 tzid = self.get_tzid() 1291 1292 # Produce a row for each interval. 1293 1294 intervals = list(intervals) 1295 intervals.sort() 1296 1297 for point, endpoint in intervals: 1298 continuation = point == get_start_of_day(point, tzid) 1299 1300 # Some rows contain no period details and are marked as such. 1301 1302 have_active = reduce(lambda x, y: x or y, [slots and slots.get(point) for slots in groups], None) 1303 1304 css = " ".join( 1305 ["slot"] + 1306 (have_active and ["busy"] or ["empty"]) + 1307 (continuation and ["daystart"] or []) 1308 ) 1309 1310 page.tr(class_=css) 1311 page.th(class_="timeslot") 1312 self._time_point(point, endpoint) 1313 page.th.close() 1314 1315 # Obtain slots for the time point from each group. 1316 1317 for columns, slots, group_type in zip(group_columns, groups, group_types): 1318 active = slots and slots.get(point) 1319 1320 # Where no periods exist for the given time interval, generate 1321 # an empty cell. Where a participant provides no periods at all, 1322 # the colspan is adjusted to be 1, not 0. 1323 1324 if not active: 1325 page.td(class_="empty container", colspan=max(columns, 1)) 1326 self._empty_slot(point, endpoint) 1327 page.td.close() 1328 continue 1329 1330 slots = slots.items() 1331 slots.sort() 1332 spans = get_spans(slots) 1333 1334 empty = 0 1335 1336 # Show a column for each active period. 1337 1338 for t in active: 1339 if t and len(t) >= 2: 1340 1341 # Flush empty slots preceding this one. 1342 1343 if empty: 1344 page.td(class_="empty container", colspan=empty) 1345 self._empty_slot(point, endpoint) 1346 page.td.close() 1347 empty = 0 1348 1349 start, end, uid, key = get_freebusy_details(t) 1350 span = spans[key] 1351 1352 # Produce a table cell only at the start of the period 1353 # or when continued at the start of a day. 1354 1355 if point == start or continuation: 1356 1357 obj = self._get_object(uid) 1358 1359 has_continued = continuation and point != start 1360 will_continue = not ends_on_same_day(point, end, tzid) 1361 is_organiser = obj and obj.get_value("ORGANIZER") == self.user 1362 1363 css = " ".join( 1364 ["event"] + 1365 (has_continued and ["continued"] or []) + 1366 (will_continue and ["continues"] or []) + 1367 (is_organiser and ["organising"] or ["attending"]) 1368 ) 1369 1370 # Only anchor the first cell of events. 1371 1372 if point == start: 1373 page.td(class_=css, rowspan=span, id="%s-%s" % (group_type, uid)) 1374 else: 1375 page.td(class_=css, rowspan=span) 1376 1377 if not obj: 1378 page.span("(Participant is busy)") 1379 else: 1380 summary = obj.get_value("SUMMARY") 1381 1382 # Only link to events if they are not being 1383 # updated by requests. 1384 1385 if uid in self._get_requests() and group_type != "request": 1386 page.span(summary) 1387 else: 1388 href = "%s/%s" % (self.env.get_url().rstrip("/"), uid) 1389 page.a(summary, href=href) 1390 1391 page.td.close() 1392 else: 1393 empty += 1 1394 1395 # Pad with empty columns. 1396 1397 empty = columns - len(active) 1398 1399 if empty: 1400 page.td(class_="empty container", colspan=empty) 1401 self._empty_slot(point, endpoint) 1402 page.td.close() 1403 1404 page.tr.close() 1405 1406 def _day_heading(self, day): 1407 1408 """ 1409 Generate a heading for 'day' of the following form: 1410 1411 <label class="day day-20150203" for="day-20150203">Tuesday, 3 February 2015</label> 1412 """ 1413 1414 page = self.page 1415 daystr = format_datetime(day) 1416 value, identifier = self._day_value_and_identifier(day) 1417 page.label(self.format_date(day, "full"), class_="day day-%s" % daystr, for_=identifier) 1418 1419 def _time_point(self, point, endpoint): 1420 1421 """ 1422 Generate headings for the 'point' to 'endpoint' period of the following 1423 form: 1424 1425 <label class="timepoint day-20150203" for="slot-20150203T090000-20150203T100000">09:00:00 CET</label> 1426 <span class="endpoint">10:00:00 CET</span> 1427 """ 1428 1429 page = self.page 1430 tzid = self.get_tzid() 1431 daystr = format_datetime(point.date()) 1432 value, identifier = self._slot_value_and_identifier(point, endpoint) 1433 slots = self.env.get_args().get("slot", []) 1434 self._slot_selector(value, identifier, slots) 1435 page.label(self.format_time(point, "long"), class_="timepoint day-%s" % daystr, for_=identifier) 1436 page.span(self.format_time(endpoint or get_end_of_day(point, tzid), "long"), class_="endpoint") 1437 1438 def _slot_selector(self, value, identifier, slots): 1439 reset = self.env.get_args().has_key("reset") 1440 page = self.page 1441 if not reset and value in slots: 1442 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector", checked="checked") 1443 else: 1444 page.input(name="slot", type="checkbox", value=value, id=identifier, class_="newevent selector") 1445 1446 def _empty_slot(self, point, endpoint): 1447 page = self.page 1448 value, identifier = self._slot_value_and_identifier(point, endpoint) 1449 page.label("Select/deselect period", class_="newevent popup", for_=identifier) 1450 1451 def _day_value_and_identifier(self, day): 1452 value = "%s-" % format_datetime(day) 1453 identifier = "day-%s" % value 1454 return value, identifier 1455 1456 def _slot_value_and_identifier(self, point, endpoint): 1457 value = "%s-%s" % (format_datetime(point), endpoint and format_datetime(endpoint) or "") 1458 identifier = "slot-%s" % value 1459 return value, identifier 1460 1461 def _show_menu(self, name, default, items): 1462 page = self.page 1463 values = self.env.get_args().get(name, [default]) 1464 page.select(name=name) 1465 for v, label in items: 1466 if v in values: 1467 page.option(label, value=v, selected="selected") 1468 else: 1469 page.option(label, value=v) 1470 page.select.close() 1471 1472 def _show_date_controls(self, name, default, attr, tzid): 1473 1474 """ 1475 Show date controls for a field with the given 'name' and 'default' value 1476 and 'attr', with the given 'tzid' being used if no other time regime 1477 information is provided. 1478 """ 1479 1480 page = self.page 1481 args = self.env.get_args() 1482 1483 event_tzid = attr.get("TZID", tzid) 1484 dt = get_datetime(default, attr) 1485 1486 # Show dates for up to one week around the current date. 1487 1488 base = get_date(dt) 1489 items = [] 1490 for i in range(-7, 8): 1491 d = base + timedelta(i) 1492 items.append((format_datetime(d), self.format_date(d, "full"))) 1493 1494 self._show_menu("%s-date" % name, format_datetime(base), items) 1495 1496 # Show time details. 1497 1498 dt_time = isinstance(dt, datetime) and dt or None 1499 hour = args.get("%s-hour" % name, "%02d" % (dt_time and dt_time.hour or 0)) 1500 minute = args.get("%s-minute" % name, "%02d" % (dt_time and dt_time.minute or 0)) 1501 second = args.get("%s-second" % name, "%02d" % (dt_time and dt_time.second or 0)) 1502 1503 page.span(class_="time enabled") 1504 page.input(name="%s-hour" % name, type="text", value=hour, maxlength=2, size=2) 1505 page.add(":") 1506 page.input(name="%s-minute" % name, type="text", value=minute, maxlength=2, size=2) 1507 page.add(":") 1508 page.input(name="%s-second" % name, type="text", value=second, maxlength=2, size=2) 1509 page.add(" ") 1510 self._show_menu("%s-tzid" % name, event_tzid, 1511 [(event_tzid, event_tzid)] + ( 1512 event_tzid != tzid and [(tzid, tzid)] or [] 1513 )) 1514 page.span.close() 1515 1516 # Incoming HTTP request direction. 1517 1518 def select_action(self): 1519 1520 "Select the desired action and show the result." 1521 1522 path_info = self.env.get_path_info().strip("/") 1523 1524 if not path_info: 1525 self.show_calendar() 1526 elif self.show_object(path_info): 1527 pass 1528 else: 1529 self.no_page() 1530 1531 def __call__(self): 1532 1533 "Interpret a request and show an appropriate response." 1534 1535 if not self.user: 1536 self.no_user() 1537 else: 1538 self.select_action() 1539 1540 # Write the headers and actual content. 1541 1542 print >>self.out, "Content-Type: text/html; charset=%s" % self.encoding 1543 print >>self.out 1544 self.out.write(unicode(self.page).encode(self.encoding)) 1545 1546 if __name__ == "__main__": 1547 Manager()() 1548 1549 # vim: tabstop=4 expandtab shiftwidth=4