imip-agent

Annotated imip_manager.py

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