imip-agent

Annotated imip_manager.py

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