imip-agent

Annotated imip_manager.py

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