imip-agent

Annotated imip_manager.py

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