File: resource.py

package info (click to toggle)
imip-agent 0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 2,056 kB
  • sloc: python: 9,888; sh: 4,480; sql: 144; makefile: 8
file content (676 lines) | stat: -rw-r--r-- 23,938 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#!/usr/bin/env python

"""
Common resource functionality for Web calendar clients.

Copyright (C) 2014, 2015, 2016 Paul Boddie <paul@boddie.org.uk>

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
details.

You should have received a copy of the GNU General Public License along with
this program.  If not, see <http://www.gnu.org/licenses/>.
"""

from datetime import datetime, timedelta
from imiptools.client import Client, ClientForObject
from imiptools.data import get_uri
from imiptools.dates import format_datetime, to_date
from imiptools.period import FreeBusyCollection
from imipweb.data import event_period_from_period, form_period_from_period, \
                         FormDate, PeriodError
from imipweb.env import CGIEnvironment
from urllib import urlencode
import babel.dates
import hashlib, hmac
import markup
import pytz
import time

class Resource:

    "A Web application resource."

    def __init__(self, resource=None):

        """
        Initialise a resource, allowing it to share the environment of any given
        existing 'resource'.
        """

        self.encoding = "utf-8"
        self.env = CGIEnvironment(self.encoding)

        self.objects = {}
        self.locale = None
        self.requests = None

        self.out = resource and resource.out or self.env.get_output()
        self.page = resource and resource.page or markup.page()
        self.html_ids = None

    # Presentation methods.

    def new_page(self, title):
        self.page.init(title=title, charset=self.encoding, css=self.env.new_url("styles.css"))
        self.html_ids = set()

    def status(self, code, message):
        self.header("Status", "%s %s" % (code, message))

    def header(self, header, value):
        print >>self.out, "%s: %s" % (header, value)

    def no_user(self):
        self.status(403, "Forbidden")
        self.new_page(title="Forbidden")
        self.page.p("You are not logged in and thus cannot access scheduling requests.")

    def no_page(self):
        self.status(404, "Not Found")
        self.new_page(title="Not Found")
        self.page.p("No page is provided at the given address.")

    def redirect(self, url):
        self.status(302, "Redirect")
        self.header("Location", url)
        self.new_page(title="Redirect")
        self.page.p("Redirecting to: %s" % url)

    def link_to(self, uid=None, recurrenceid=None, args=None):

        """
        Return a link to a resource, being an object with any given 'uid' and
        'recurrenceid', or the main resource otherwise.

        See get_identifiers for the decoding of such links.

        If 'args' is specified, the given dictionary is encoded and included.
        """

        path = []
        if uid:
            path.append(uid)
        if recurrenceid:
            path.append(recurrenceid)
        return "%s%s" % (self.env.new_url("/".join(path)), args and ("?%s" % urlencode(args)) or "")

    # Access to objects.

    def get_identifiers(self, path_info):

        """
        Return identifiers provided by 'path_info', potentially encoded by
        'link_to'.
        """

        parts = path_info.lstrip("/").split("/")

        # UID only.

        if len(parts) == 1:
            return parts[0], None

        # UID and RECURRENCE-ID.

        else:
            return parts[:2]

    def _get_object(self, uid, recurrenceid=None, section=None, username=None):
        if self.objects.has_key((uid, recurrenceid, section, username)):
            return self.objects[(uid, recurrenceid, section, username)]

        obj = self.objects[(uid, recurrenceid, section, username)] = self.get_stored_object(uid, recurrenceid, section, username)
        return obj

    def _get_recurrences(self, uid):
        return self.store.get_recurrences(self.user, uid)

    def _get_active_recurrences(self, uid):
        return self.store.get_active_recurrences(self.user, uid)

    def _get_requests(self):
        if self.requests is None:
            self.requests = self.store.get_requests(self.user)
        return self.requests

    def _have_request(self, uid, recurrenceid=None, type=None, strict=False):
        return self.store.have_request(self._get_requests(), uid, recurrenceid, type, strict)

    def _is_request(self):
        return self._have_request(self.uid, self.recurrenceid)

    def _get_counters(self, uid, recurrenceid=None):
        return self.store.get_counters(self.user, uid, recurrenceid)

    def _get_request_summary(self):

        "Return a list of periods comprising the request summary."

        summary = FreeBusyCollection()

        for uid, recurrenceid, request_type in self._get_requests():

            # Obtain either normal objects or counter-proposals.

            if not request_type:
                objs = [self._get_object(uid, recurrenceid)]
            elif request_type == "COUNTER":
                objs = []
                for attendee in self.store.get_counters(self.user, uid, recurrenceid):
                    objs.append(self._get_object(uid, recurrenceid, "counters", attendee))

            # For each object, obtain the periods involved.

            for obj in objs:
                if obj:
                    recurrenceids = self._get_recurrences(uid)

                    # Obtain only active periods, not those replaced by redefined
                    # recurrences, converting to free/busy periods.

                    for p in obj.get_active_periods(recurrenceids, self.get_tzid(), self.get_window_end()):
                        summary.append(obj.get_freebusy_period(p))

        return summary

    # Preference methods.

    def get_user_locale(self):
        if not self.locale:
            self.locale = self.get_preferences().get("LANG", "en", True) or "en"
        return self.locale

    # Prettyprinting of dates and times.

    def format_date(self, dt, format):
        return self._format_datetime(babel.dates.format_date, dt, format)

    def format_time(self, dt, format):
        return self._format_datetime(babel.dates.format_time, dt, format)

    def format_datetime(self, dt, format):
        return self._format_datetime(
            isinstance(dt, datetime) and babel.dates.format_datetime or babel.dates.format_date,
            dt, format)

    def _format_datetime(self, fn, dt, format):
        return fn(dt, format=format, locale=self.get_user_locale())

class ResourceClient(Resource, Client):

    "A Web application resource and calendar client."

    def __init__(self, resource=None):
        Resource.__init__(self, resource)
        user = self.env.get_user()
        Client.__init__(self, user and get_uri(user) or None)

class ResourceClientForObject(Resource, ClientForObject):

    "A Web application resource and calendar client for a specific object."

    def __init__(self, resource=None, messenger=None):
        Resource.__init__(self, resource)
        user = self.env.get_user()
        ClientForObject.__init__(self, None, user and get_uri(user) or None, messenger)

class FormUtilities:

    "Utility methods resource mix-in."

    def get_validation_token(self, details=None):

        "Return a token suitable for validating a form submission."

        # Use a secret held in the user's preferences.

        prefs = self.get_preferences()
        if not prefs.has_key("secret"):
            prefs["secret"] = str(time.time())

        # Combine it with the user identity and any supplied details.

        secret = prefs["secret"].encode("utf-8")
        details = u"".join([self.env.get_user()] + (details or [])).encode("utf-8")

        return hmac.new(secret, details, hashlib.sha256).hexdigest()

    def check_validation_token(self, name="token", details=None):

        """
        Check the field having the given 'name', returning if its value matches
        the validation token generated using any given 'details'.
        """

        return self.env.get_args().get(name, [None])[0] == self.get_validation_token(details)

    def validator(self, name="token", details=None):

        """
        Show a control having the given 'name' that is used to validate form
        submissions, employing any additional 'details' in the construction of
        the validation token.
        """

        self.page.input(name=name, type="hidden", value=self.get_validation_token(details))

    def prefixed_args(self, prefix, convert=None):

        """
        Return values for all arguments having the given 'prefix' in their
        names, removing the prefix to obtain each value from the argument name
        itself. The 'convert' callable can be specified to perform a conversion
        (to int, for example).
        """

        args = self.env.get_args()

        values = []
        for name in args.keys():
            if name.startswith(prefix):
                value = name[len(prefix):]
                if convert:
                    try:
                        value = convert(value)
                    except ValueError:
                        pass
                values.append(value)
        return values

    def control(self, name, type, value, selected=False, **kw):

        """
        Show a control with the given 'name', 'type' and 'value', with
        'selected' indicating whether it should be selected (checked or
        equivalent), and with keyword arguments setting other properties.
        """

        page = self.page
        if type in ("checkbox", "radio") and selected:
            page.input(name=name, type=type, value=value, checked="checked", **kw)
        else:
            page.input(name=name, type=type, value=value, **kw)

    def menu(self, name, default, items, values=None, class_="", index=None):

        """
        Show a select menu having the given 'name', set to the given 'default',
        providing the given (value, label) 'items', selecting the given 'values'
        (or using the request parameters if not specified), and employing the
        given CSS 'class_' if specified.
        """

        page = self.page
        values = values or self.env.get_args().get(name, [default])
        if index is not None:
            values = values[index:]
            values = values and values[0:1] or [default]

        page.select(name=name, class_=class_)
        for v, label in items:
            if v is None:
                continue
            if v in values:
                page.option(label, value=v, selected="selected")
            else:
                page.option(label, value=v)
        page.select.close()

    def date_controls(self, name, default, index=None, show_tzid=True, read_only=False):

        """
        Show date controls for a field with the given 'name' and 'default' form
        date value.

        If 'index' is specified, default field values will be overridden by the
        element from a collection of existing form values with the specified
        index; otherwise, field values will be overridden by a single form
        value.

        If 'show_tzid' is set to a false value, the time zone menu will not be
        provided.

        If 'read_only' is set to a true value, the controls will be hidden and
        labels will be employed instead.
        """

        page = self.page

        # Show dates for up to one week around the current date.

        page.span(class_="date enabled")

        dt = default.as_datetime()
        if not dt:
            dt = date.today()

        base = to_date(dt)

        # Show a date label with a hidden field if read-only.

        if read_only:
            self.control("%s-date" % name, "hidden", format_datetime(base))
            page.span(self.format_date(base, "long"))

        # Show dates for up to one week around the current date.
        # NOTE: Support paging to other dates.

        else:
            items = []
            for i in range(-7, 8):
                d = base + timedelta(i)
                items.append((format_datetime(d), self.format_date(d, "full")))
            self.menu("%s-date" % name, format_datetime(base), items, index=index)

        page.span.close()

        # Show time details.

        page.span(class_="time enabled")

        if read_only:
            page.span("%s:%s:%s" % (default.get_hour(), default.get_minute(), default.get_second()))
            self.control("%s-hour" % name, "hidden", default.get_hour())
            self.control("%s-minute" % name, "hidden", default.get_minute())
            self.control("%s-second" % name, "hidden", default.get_second())
        else:
            self.control("%s-hour" % name, "text", default.get_hour(), maxlength=2, size=2)
            page.add(":")
            self.control("%s-minute" % name, "text", default.get_minute(), maxlength=2, size=2)
            page.add(":")
            self.control("%s-second" % name, "text", default.get_second(), maxlength=2, size=2)

        # Show time zone details.

        if show_tzid:
            page.add(" ")
            tzid = default.get_tzid() or self.get_tzid()

            # Show a label if read-only or a menu otherwise.

            if read_only:
                self.control("%s-tzid" % name, "hidden", tzid)
                page.span(tzid)
            else:
                self.timezone_menu("%s-tzid" % name, tzid, index)

        page.span.close()

    def timezone_menu(self, name, default, index=None):

        """
        Show timezone controls using a menu with the given 'name', set to the
        given 'default' unless a field of the given 'name' provides a value.
        """

        entries = [(tzid, tzid) for tzid in pytz.all_timezones]
        self.menu(name, default, entries, index=index)

class DateTimeFormUtilities:

    "Date/time control methods resource mix-in."

    # Control naming helpers.

    def element_identifier(self, name, index=None):
        return index is not None and "%s-%d" % (name, index) or name

    def element_name(self, name, suffix, index=None):
        return index is not None and "%s-%s" % (name, suffix) or name

    def element_enable(self, index=None):
        return index is not None and str(index) or "enable"

    def show_object_datetime_controls(self, period, index=None):

        """
        Show datetime-related controls if already active or if an object needs
        them for the given 'period'. The given 'index' is used to parameterise
        individual controls for dynamic manipulation.
        """

        p = form_period_from_period(period)

        page = self.page
        args = self.env.get_args()
        _id = self.element_identifier
        _name = self.element_name
        _enable = self.element_enable

        # Add a dynamic stylesheet to permit the controls to modify the display.
        # NOTE: The style details need to be coordinated with the static
        # NOTE: stylesheet.

        if index is not None:
            page.style(type="text/css")

            # Unlike the rules for object properties, these affect recurrence
            # properties.

            page.add("""\
input#dttimes-enable-%(index)d,
input#dtend-enable-%(index)d,
input#dttimes-enable-%(index)d:not(:checked) ~ .recurrence td.objectvalue .time.enabled,
input#dttimes-enable-%(index)d:checked ~ .recurrence td.objectvalue .time.disabled,
input#dtend-enable-%(index)d:not(:checked) ~ .recurrence td.objectvalue.dtend .dt.enabled,
input#dtend-enable-%(index)d:checked ~ .recurrence td.objectvalue.dtend .dt.disabled {
    display: none;
}

input#dtend-enable-%(index)d:not(:checked) ~ .recurrence td.objectvalue.dtend .date.enabled,
input#dtend-enable-%(index)d:checked ~ .recurrence td.objectvalue.dtend .date.disabled {
    visibility: hidden;
}""" % {"index" : index})

            page.style.close()

        self.control(
            _name("dtend-control", "recur", index), "checkbox",
            _enable(index), p.end_enabled,
            id=_id("dtend-enable", index)
            )

        self.control(
            _name("dttimes-control", "recur", index), "checkbox",
            _enable(index), p.times_enabled,
            id=_id("dttimes-enable", index)
            )

    def show_datetime_controls(self, formdate, show_start):

        """
        Show datetime details from the current object for the 'formdate',
        showing start details if 'show_start' is set to a true value. Details
        will appear as controls for organisers and labels for attendees.
        """

        page = self.page

        # Show controls for editing.

        page.td(class_="objectvalue dt%s" % (show_start and "start" or "end"))

        if show_start:
            page.div(class_="dt enabled")
            self.date_controls("dtstart", formdate)
            page.br()
            page.label("Specify times", for_="dttimes-enable", class_="time disabled enable")
            page.label("Specify dates only", for_="dttimes-enable", class_="time enabled disable")
            page.div.close()

        else:
            self.date_controls("dtend", formdate)
            page.div(class_="dt disabled")
            page.label("Specify end date", for_="dtend-enable", class_="enable")
            page.div.close()
            page.div(class_="dt enabled")
            page.label("End on same day", for_="dtend-enable", class_="disable")
            page.div.close()

        page.td.close()

    def show_recurrence_controls(self, index, period, recurrenceid, show_start):

        """
        Show datetime details from the current object for the recurrence having
        the given 'index', with the recurrence period described by 'period',
        indicating a start, end and origin of the period from the event details,
        employing any 'recurrenceid' for the object to configure the displayed
        information.

        If 'show_start' is set to a true value, the start details will be shown;
        otherwise, the end details will be shown.
        """

        page = self.page
        _id = self.element_identifier
        _name = self.element_name

        period = form_period_from_period(period)

        # Show controls for editing.

        if not period.replaced:
            page.td(class_="objectvalue dt%s" % (show_start and "start" or "end"))

            read_only = period.origin == "RRULE"

            if show_start:
                page.div(class_="dt enabled")
                self.date_controls(_name("dtstart", "recur", index), period.get_form_start(), index=index, read_only=read_only)
                if not read_only:
                    page.br()
                    page.label("Specify times", for_=_id("dttimes-enable", index), class_="time disabled enable")
                    page.label("Specify dates only", for_=_id("dttimes-enable", index), class_="time enabled disable")
                page.div.close()

                # Put the origin somewhere.

                self.control("recur-origin", "hidden", period.origin or "")
                self.control("recur-replaced", "hidden", period.replaced and str(index) or "")

            else:
                self.date_controls(_name("dtend", "recur", index), period.get_form_end(), index=index, show_tzid=False, read_only=read_only)
                if not read_only:
                    page.div(class_="dt disabled")
                    page.label("Specify end date", for_=_id("dtend-enable", index), class_="enable")
                    page.div.close()
                    page.div(class_="dt enabled")
                    page.label("End on same day", for_=_id("dtend-enable", index), class_="disable")
                    page.div.close()

            page.td.close()

        # Show label as attendee.

        else:
            self.show_recurrence_label(index, period, recurrenceid, show_start)

    def show_recurrence_label(self, index, period, recurrenceid, show_start):

        """
        Show datetime details from the current object for the recurrence having
        the given 'index', for the given recurrence 'period', employing any
        'recurrenceid' for the object to configure the displayed information.

        If 'show_start' is set to a true value, the start details will be shown;
        otherwise, the end details will be shown.
        """

        page = self.page
        _name = self.element_name

        try:
            p = event_period_from_period(period)
        except PeriodError, exc:
            affected = False
        else:
            affected = p.is_affected(recurrenceid)

        period = form_period_from_period(period)

        css = " ".join([
            period.replaced and "replaced" or "",
            affected and "affected" or ""
            ])

        formdate = show_start and period.get_form_start() or period.get_form_end()
        dt = formdate.as_datetime()
        if dt:
            page.td(class_=css)
            if show_start:
                self.date_controls(_name("dtstart", "recur", index), period.get_form_start(), index=index, read_only=True)
                self.control("recur-origin", "hidden", period.origin or "")
                self.control("recur-replaced", "hidden", period.replaced and str(index) or "")
            else:
                self.date_controls(_name("dtend", "recur", index), period.get_form_end(), index=index, show_tzid=False, read_only=True)
            page.td.close()
        else:
            page.td("(Unrecognised date)")

    def get_date_control_values(self, name, multiple=False, tzid_name=None):

        """
        Return a form date object representing fields starting with 'name'. If
        'multiple' is set to a true value, many date objects will be returned
        corresponding to a collection of datetimes.

        If 'tzid_name' is specified, the time zone information will be acquired
        from fields starting with 'tzid_name' instead of 'name'.
        """

        args = self.env.get_args()

        dates = args.get("%s-date" % name, [])
        hours = args.get("%s-hour" % name, [])
        minutes = args.get("%s-minute" % name, [])
        seconds = args.get("%s-second" % name, [])
        tzids = args.get("%s-tzid" % (tzid_name or name), [])

        # Handle absent values by employing None values.

        field_values = map(None, dates, hours, minutes, seconds, tzids)

        if not field_values and not multiple:
            all_values = FormDate()
        else:
            all_values = []
            for date, hour, minute, second, tzid in field_values:
                value = FormDate(date, hour, minute, second, tzid or self.get_tzid())

                # Return a single value or append to a collection of all values.

                if not multiple:
                    return value
                else:
                    all_values.append(value)

        return all_values

    def set_date_control_values(self, name, formdates, tzid_name=None):

        """
        Replace form fields starting with 'name' using the values of the given
        'formdates'.

        If 'tzid_name' is specified, the time zone information will be stored in
        fields starting with 'tzid_name' instead of 'name'.
        """

        args = self.env.get_args()

        args["%s-date" % name] = [d.date for d in formdates]
        args["%s-hour" % name] = [d.hour for d in formdates]
        args["%s-minute" % name] = [d.minute for d in formdates]
        args["%s-second" % name] = [d.second for d in formdates]
        args["%s-tzid" % (tzid_name or name)] = [d.tzid for d in formdates]

# vim: tabstop=4 expandtab shiftwidth=4