imip-agent

Annotated imip_manager.py

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