imip-agent

Annotated imip_manager.py

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