File: client.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 (1335 lines) | stat: -rw-r--r-- 46,781 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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
#!/usr/bin/env python

"""
Common calendar client utilities.

Copyright (C) 2014, 2015, 2016, 2017 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.config import settings
from imiptools.data import Object, check_delegation, get_address, get_uri, \
                           get_window_end, is_new_object, make_freebusy, \
                           make_uid, to_part, uri_dict, uri_item, uri_items, \
                           uri_parts, uri_values
from imiptools.dates import check_permitted_values, format_datetime, get_default_timezone, \
                            get_duration, get_timestamp
from imiptools.i18n import get_translator
from imiptools.period import SupportAttendee, SupportExpires
from imiptools.profile import Preferences
from imiptools.stores import get_store, get_publisher, get_journal

class Client:

    "Common handler and manager methods."

    default_window_size = 100
    organiser_methods = "ADD", "CANCEL", "DECLINECOUNTER", "PUBLISH", "REQUEST"

    def __init__(self, user, messenger=None, store=None, publisher=None, journal=None,
                 preferences_dir=None):

        """
        Initialise a calendar client with the current 'user', plus any
        'messenger', 'store', 'publisher' and 'journal' objects, indicating any
        specific 'preferences_dir'.
        """

        self.user = user
        self.messenger = messenger
        self.store = store or get_store(settings["STORE_TYPE"], settings["STORE_DIR"])
        self.journal = journal or get_journal(settings["STORE_TYPE"], settings["JOURNAL_DIR"])

        try:
            self.publisher = publisher or get_publisher(settings["PUBLISH_DIR"])
        except OSError:
            self.publisher = None

        self.preferences_dir = preferences_dir
        self.preferences = None

        # Localise the messenger.

        if self.messenger:
            self.messenger.gettext = self.get_translator()

    def get_store(self):
        return self.store

    def get_publisher(self):
        return self.publisher

    def get_journal(self):
        return self.journal

    # Store-related methods.

    def acquire_lock(self):
        self.store.acquire_lock(self.user)

    def release_lock(self):
        self.store.release_lock(self.user)

    # Preferences-related methods.

    def get_preferences(self):
        if not self.preferences and self.user:
            self.preferences = Preferences(self.user, self.preferences_dir)
        return self.preferences

    def get_locale(self):
        prefs = self.get_preferences()
        return prefs and prefs.get("LANG", "en", True) or "en"

    def get_translator(self):
        return get_translator([self.get_locale()])

    def get_user_attributes(self):
        prefs = self.get_preferences()
        return prefs and prefs.get_all(["CN"]) or {}

    def get_tzid(self):
        prefs = self.get_preferences()
        return prefs and prefs.get("TZID") or get_default_timezone()

    def get_window_size(self):
        prefs = self.get_preferences()
        try:
            return prefs and int(prefs.get("window_size")) or self.default_window_size
        except (TypeError, ValueError):
            return self.default_window_size

    def get_window_end(self):
        return get_window_end(self.get_tzid(), self.get_window_size())

    def is_participating(self):

        "Return participation in the calendar system."

        prefs = self.get_preferences()
        return prefs and prefs.get("participating", settings["PARTICIPATING_DEFAULT"]) != "no" or False

    def is_sharing(self):

        "Return whether free/busy information is being generally shared."

        prefs = self.get_preferences()
        return prefs and prefs.get("freebusy_sharing", settings["SHARING_DEFAULT"]) == "share" or False

    def is_bundling(self):

        "Return whether free/busy information is being bundled in messages."

        prefs = self.get_preferences()
        return prefs and prefs.get("freebusy_bundling", settings["BUNDLING_DEFAULT"]) == "always" or False

    def is_notifying(self):

        "Return whether recipients are notified about free/busy payloads."

        prefs = self.get_preferences()
        return prefs and prefs.get("freebusy_messages", settings["NOTIFYING_DEFAULT"]) == "notify" or False

    def is_publishing(self):

        "Return whether free/busy information is being published as Web resources."

        prefs = self.get_preferences()
        return prefs and prefs.get("freebusy_publishing", settings["PUBLISHING_DEFAULT"]) == "publish" or False

    def is_refreshing(self):

        "Return whether a recipient supports requests to refresh event details."

        prefs = self.get_preferences()
        return prefs and prefs.get("event_refreshing", settings["REFRESHING_DEFAULT"]) == "always" or False

    def allow_add(self):
        return self.get_add_method_response() in ("add", "refresh")

    def get_add_method_response(self):
        prefs = self.get_preferences()
        return prefs and prefs.get("add_method_response", settings["ADD_RESPONSE_DEFAULT"]) or "refresh"

    def get_offer_period(self):

        "Decode a specification in the iCalendar duration format."

        prefs = self.get_preferences()
        duration = prefs and prefs.get("freebusy_offers", settings["FREEBUSY_OFFER_DEFAULT"])

        # NOTE: Should probably report an error somehow if None.

        return duration and get_duration(duration) or None

    def get_organiser_replacement(self):
        prefs = self.get_preferences()
        return prefs and prefs.get("organiser_replacement", settings["ORGANISER_REPLACEMENT_DEFAULT"]) or "attendee"

    def have_manager(self):
        return settings["MANAGER_INTERFACE"]

    def get_permitted_values(self):

        """
        Decode a specification of one of the following forms...

        <minute values>
        <hour values>:<minute values>
        <hour values>:<minute values>:<second values>

        ...with each list of values being comma-separated.
        """

        prefs = self.get_preferences()
        permitted_values = prefs and prefs.get("permitted_times")
        if permitted_values:
            try:
                l = []
                for component in permitted_values.split(":")[:3]:
                    if component:
                        l.append(map(int, component.split(",")))
                    else:
                        l.append(None)

            # NOTE: Should probably report an error somehow.

            except ValueError:
                return None
            else:
                l = (len(l) < 2 and [None] or []) + l + (len(l) < 3 and [None] or [])
                return l
        else:
            return None

    # Common operations on calendar data.

    def update_sender(self, attr):

        "Update the SENT-BY attribute of the 'attr' sender metadata."

        if self.messenger and self.messenger.sender != get_address(self.user):
            attr["SENT-BY"] = get_uri(self.messenger.sender)

    def get_periods(self, obj, explicit_only=False):

        """
        Return periods for the given 'obj'. Interpretation of periods can depend
        on the time zone, which is obtained for the current user. If
        'explicit_only' is set to a true value, only explicit periods will be
        returned, not rule-based periods.
        """

        return obj.get_periods(self.get_tzid(), not explicit_only and self.get_window_end() or None)

    # Store operations.

    def get_stored_object(self, uid, recurrenceid, section=None, username=None):

        """
        Return the stored object for the current user, with the given 'uid' and
        'recurrenceid' from the given 'section' and for the given 'username' (if
        specified), or from the standard object collection otherwise.
        """

        if section == "counters":
            fragment = self.store.get_counter(self.user, username, uid, recurrenceid)
        else:
            fragment = self.store.get_event(self.user, uid, recurrenceid, section)
        return fragment and Object(fragment)

    # Free/busy operations.

    def get_freebusy_part(self, freebusy=None):

        """
        Return a message part containing free/busy information for the user,
        either specified as 'freebusy' or obtained from the store directly.
        """

        if self.is_sharing() and self.is_bundling():

            # Invent a unique identifier.

            uid = make_uid(self.user)

            freebusy = freebusy or self.store.get_freebusy(self.user)

            user_attr = {}
            self.update_sender(user_attr)
            return self.to_part("PUBLISH", [make_freebusy(freebusy, uid, self.user, user_attr)])

        return None

    def update_freebusy(self, freebusy, periods, transp, uid, recurrenceid, summary, organiser, expires=None):

        """
        Update the 'freebusy' collection with the given 'periods', indicating a
        'transp' status, explicit 'uid' and 'recurrenceid' to indicate either a
        recurrence or the parent event. The 'summary' and 'organiser' must also
        be provided.

        An optional 'expires' datetime string can be provided to tag a free/busy
        offer.
        """

        # Add specific attendee information for certain collections.

        if isinstance(freebusy, SupportAttendee):
            freebusy.update_freebusy(periods, transp, uid, recurrenceid, summary, organiser, self.user)

        # Add expiry datetime for certain collections.

        elif isinstance(freebusy, SupportExpires):
            freebusy.update_freebusy(periods, transp, uid, recurrenceid, summary, organiser, expires)

        # Provide only the essential attributes for other collections.

        else:
            freebusy.update_freebusy(periods, transp, uid, recurrenceid, summary, organiser)

    # Preparation of content.

    def to_part(self, method, fragments):

        "Return an encoded MIME part for the given 'method' and 'fragments'."

        return to_part(method, fragments, line_length=settings["CALENDAR_LINE_LENGTH"])

    def object_to_part(self, method, obj):

        "Return an encoded MIME part for the given 'method' and 'obj'."

        return obj.to_part(method, line_length=settings["CALENDAR_LINE_LENGTH"])

    # Preparation of messages communicating the state of events.

    def get_message_parts(self, obj, method, attendee=None):

        """
        Return a tuple containing a list of methods and a list of message parts,
        with the parts collectively describing the given object 'obj' and its
        recurrences, using 'method' as the means of publishing details (with
        CANCEL being used to retract or remove details).

        If 'attendee' is indicated, the attendee's participation will be taken
        into account when generating the description.
        """

        # Assume that the outcome will be composed of requests and
        # cancellations. It would not seem completely bizarre to produce
        # publishing messages if a refresh message was unprovoked.

        responses = []
        methods = set()

        # Get the parent event, add SENT-BY details to the organiser.

        if not attendee or self.is_participating(attendee, obj=obj):
            organiser, organiser_attr = uri_item(obj.get_item("ORGANIZER"))
            self.update_sender(organiser_attr)
            responses.append(self.object_to_part(method, obj))
            methods.add(method)

        # Get recurrences for parent events.

        if not self.recurrenceid:

            # Collect active and cancelled recurrences.

            for rl, section, rmethod in [
                (self.store.get_active_recurrences(self.user, self.uid), None, method),
                (self.store.get_cancelled_recurrences(self.user, self.uid), "cancellations", "CANCEL"),
                ]:

                for recurrenceid in rl:

                    # Get the recurrence, add SENT-BY details to the organiser.

                    obj = self.get_stored_object(self.uid, recurrenceid, section)

                    if not attendee or self.is_participating(attendee, obj=obj):
                        organiser, organiser_attr = uri_item(obj.get_item("ORGANIZER"))
                        self.update_sender(organiser_attr)
                        responses.append(self.object_to_part(rmethod, obj))
                        methods.add(rmethod)

        return methods, responses

class ClientForObject(Client):

    "A client maintaining a specific object."

    def __init__(self, obj, user, messenger=None, store=None, publisher=None,
                 journal=None, preferences_dir=None):
        Client.__init__(self, user, messenger, store, publisher, journal, preferences_dir)
        self.set_object(obj)

    def set_object(self, obj):

        "Set the current object to 'obj', obtaining metadata details."

        self.obj = obj
        self.uid = obj and self.obj.get_uid()
        self.recurrenceid = obj and self.obj.get_recurrenceid()
        self.sequence = obj and self.obj.get_value("SEQUENCE")
        self.dtstamp = obj and self.obj.get_value("DTSTAMP")

    def set_identity(self, method):

        """
        Set the current user for the current object in the context of the given
        'method'. It is usually set when initialising the handler, using the
        recipient details, but outgoing messages do not reference the recipient
        in this way.
        """

        pass

    def is_usable(self, method=None):

        "Return whether the current object is usable with the given 'method'."

        return True

    def is_organiser(self):

        """
        Return whether the current user is the organiser in the current object.
        """

        return get_uri(self.obj.get_value("ORGANIZER")) == self.user

    def is_recurrence(self):

        "Return whether the current object is a recurrence of its parent."

        parent = self.get_parent_object()
        return parent and parent.has_recurrence(self.get_tzid(), self.obj.get_recurrenceid())

    # Common operations on calendar data.

    def update_senders(self, obj=None):

        """
        Update sender details in 'obj', or the current object if not indicated,
        removing SENT-BY attributes for attendees other than the current user if
        those attributes give the URI of the calendar system.
        """

        obj = obj or self.obj
        calendar_uri = self.messenger and get_uri(self.messenger.sender)
        for attendee, attendee_attr in uri_items(obj.get_items("ATTENDEE")):
            if attendee != self.user:
                if attendee_attr.get("SENT-BY") == calendar_uri:
                    del attendee_attr["SENT-BY"]
            else:
                attendee_attr["SENT-BY"] = calendar_uri

    def get_sending_attendee(self):

        "Return the attendee who sent the current object."

        # Search for the sender of the message or the calendar system address.

        senders = self.senders or self.messenger and [self.messenger.sender] or []

        for attendee, attendee_attr in uri_items(self.obj.get_items("ATTENDEE")):
            if get_address(attendee) in senders or \
               get_address(attendee_attr.get("SENT-BY")) in senders:
                return get_uri(attendee)

        return None

    def get_unscheduled_parts(self, periods):

        "Return message parts describing unscheduled 'periods'."

        unscheduled_parts = []

        if periods:
            obj = self.obj.copy()
            obj.remove_all(["RRULE", "RDATE", "DTSTART", "DTEND", "DURATION"])

            for p in periods:
                if not p.origin:
                    continue
                obj["RECURRENCE-ID"] = obj["DTSTART"] = [(format_datetime(p.get_start()), p.get_start_attr())]
                obj["DTEND"] = [(format_datetime(p.get_end()), p.get_end_attr())]
                unscheduled_parts.append(self.object_to_part("CANCEL", obj))

        return unscheduled_parts

    # Object update methods.

    def update_recurrenceid(self):

        """
        Update the RECURRENCE-ID in the current object, initialising it from
        DTSTART.
        """

        self.obj["RECURRENCE-ID"] = [self.obj.get_item("DTSTART")]
        self.recurrenceid = self.obj.get_recurrenceid()

    def update_dtstamp(self, obj=None):

        "Update the DTSTAMP in the current object or any given object 'obj'."

        obj = obj or self.obj
        self.dtstamp = obj.update_dtstamp()

    def update_sequence(self, increment=False, obj=None):

        "Update the SEQUENCE in the current object or any given object 'obj'."

        obj = obj or self.obj
        obj.update_sequence(increment)

    def merge_attendance(self, attendees):

        """
        Merge attendance from the current object's 'attendees' into the version
        stored for the current user.
        """

        obj = self.get_stored_object_version()

        if not obj or not self.have_new_object():
            return False

        # Get attendee details in a usable form.

        attendee_map = uri_dict(obj.get_value_map("ATTENDEE"))

        for attendee, attendee_attr in attendees.items():

            # Update attendance in the loaded object for any recognised
            # attendees.

            if attendee_map.has_key(attendee):
                attendee_map[attendee] = attendee_attr

        # Check for delegated attendees.

        for attendee, attendee_attr in attendees.items():

            # Identify delegates and check the delegation using the updated
            # attendee information.

            if not attendee_map.has_key(attendee) and \
               attendee_attr.has_key("DELEGATED-FROM") and \
               check_delegation(attendee_map, attendee, attendee_attr):

                attendee_map[attendee] = attendee_attr

        # Set the new details and store the object.

        obj["ATTENDEE"] = attendee_map.items()

        # Set a specific recurrence or the complete event if not an additional
        # occurrence.

        return self.store.set_event(self.user, self.uid, self.recurrenceid, obj.to_node())

    def update_attendees(self, attendees, removed):

        """
        Update the attendees in the current object with the given 'attendees'
        and 'removed' attendee lists.

        A tuple is returned containing two items: a list of the attendees whose
        attendance is being proposed (in a counter-proposal), a list of the
        attendees whose attendance should be cancelled.
        """

        to_cancel = []

        existing_attendees = uri_items(self.obj.get_items("ATTENDEE") or [])
        existing_attendees_map = dict(existing_attendees)

        # Added attendees are those from the supplied collection not already
        # present in the object.

        added = set(uri_values(attendees)).difference([uri for uri, attr in existing_attendees])
        removed = uri_values(removed)

        if added or removed:

            # The organiser can remove existing attendees.

            if removed and self.is_organiser():
                remaining = []

                for attendee, attendee_attr in existing_attendees:
                    if attendee in removed:

                        # Only when an event has not been published can
                        # attendees be silently removed.

                        if self.obj.is_shared():
                            to_cancel.append((attendee, attendee_attr))
                    else:
                        remaining.append((attendee, attendee_attr))

                existing_attendees = remaining

            # Attendees (when countering) must only include the current user and
            # any added attendees.

            elif not self.is_organiser():
                existing_attendees = []

            # Both organisers and attendees (when countering) can add attendees.

            if added:

                # Obtain a mapping from URIs to name details.

                attendee_map = dict([(attendee_uri, cn) for cn, attendee_uri in uri_parts(attendees)])

                for attendee in added:
                    attendee = attendee.strip()
                    if attendee:
                        cn = attendee_map.get(attendee)
                        attendee_attr = {"CN" : cn} or {}

                        # Only the organiser can reset the participation attributes.

                        if self.is_organiser():
                            attendee_attr.update({"PARTSTAT" : "NEEDS-ACTION", "RSVP" : "TRUE"})

                        existing_attendees.append((attendee, attendee_attr))

            # Attendees (when countering) must only include the current user and
            # any added attendees.

            if not self.is_organiser() and self.user not in existing_attendees:
                user_attr = self.get_user_attributes()
                user_attr.update(existing_attendees_map.get(self.user) or {})
                existing_attendees.append((self.user, user_attr))

            self.obj["ATTENDEE"] = existing_attendees

        return added, to_cancel

    def update_participation(self, partstat=None):

        """
        Update the participation in the current object of the user with the
        given 'partstat'.
        """

        attendee_attr = uri_dict(self.obj.get_value_map("ATTENDEE")).get(self.user)
        if not attendee_attr:
            return None
        if partstat:
            attendee_attr["PARTSTAT"] = partstat
        if attendee_attr.has_key("RSVP"):
            del attendee_attr["RSVP"]
        self.update_sender(attendee_attr)
        return attendee_attr

    # Communication methods.

    def send_message(self, parts, sender, obj, from_organiser, bcc_sender):

        """
        Send the given 'parts' to the appropriate recipients, also sending a
        copy to the 'sender'. The 'obj' together with the 'from_organiser' value
        (which indicates whether the organiser is sending this message) are used
        to determine the recipients of the message.
        """

        # As organiser, send an invitation to attendees, excluding oneself if
        # also attending. The updated event will be saved by the outgoing
        # handler.

        organiser = get_uri(obj.get_value("ORGANIZER"))
        attendees = uri_values(obj.get_values("ATTENDEE"))

        if from_organiser:
            recipients = [get_address(attendee) for attendee in attendees if attendee != self.user]
        else:
            recipients = [get_address(organiser)]

        # Since the outgoing handler updates this user's free/busy details,
        # the stored details will probably not have the updated details at
        # this point, so we update our copy for serialisation as the bundled
        # free/busy object.

        freebusy = self.store.get_freebusy(self.user).copy()
        self.update_freebusy(freebusy, self.user, from_organiser)

        # Bundle free/busy information if appropriate.

        part = self.get_freebusy_part(freebusy)
        if part:
            parts.append(part)

        if recipients or bcc_sender:
            self._send_message(sender, recipients, parts, bcc_sender)

    def _send_message(self, sender, recipients, parts, bcc_sender):

        """
        Send a message, explicitly specifying the 'sender' as an outgoing BCC
        recipient since the generic calendar user will be the actual sender.
        """

        if not self.messenger:
            return

        if not bcc_sender:
            message = self.messenger.make_outgoing_message(parts, recipients)
            self.messenger.sendmail(recipients, message.as_string())
        else:
            message = self.messenger.make_outgoing_message(parts, recipients, outgoing_bcc=sender)
            self.messenger.sendmail(recipients, message.as_string(), outgoing_bcc=sender)

    def send_message_to_self(self, parts):

        "Send a message composed of the given 'parts' to the given user."

        if not self.messenger:
            return

        sender = get_address(self.user)
        message = self.messenger.make_outgoing_message(parts, [sender])
        self.messenger.sendmail([sender], message.as_string())

    # Action methods.

    def process_declined_counter(self, attendee):

        "Process a declined counter-proposal."

        # Obtain the counter-proposal for the attendee.

        obj = self.get_stored_object(self.uid, self.recurrenceid, "counters", attendee)
        if not obj:
            return False

        method = "DECLINECOUNTER"
        self.update_senders(obj=obj)
        obj.update_dtstamp()
        obj.update_sequence(False)
        self._send_message(get_address(self.user), [get_address(attendee)], [self.object_to_part(method, obj)], True)
        return True

    def process_received_request(self, changed=False):

        """
        Process the current request for the current user. Return whether any
        action was taken. If 'changed' is set to a true value, or if 'attendees'
        is specified and differs from the stored attendees, a counter-proposal
        will be sent instead of a reply.
        """

        # Reply only on behalf of this user.

        attendee_attr = self.update_participation()

        if not attendee_attr:
            return False

        if not changed:
            self.obj["ATTENDEE"] = [(self.user, attendee_attr)]
        else:
            self.update_senders()

        self.update_dtstamp()
        self.update_sequence(False)
        self.send_message([self.object_to_part(changed and "COUNTER" or "REPLY", self.obj)],
                          get_address(self.user), self.obj, False, True)
        return True

    def process_created_request(self, method, to_cancel=None, to_unschedule=None):

        """
        Process the current request, sending a created request of the given
        'method' to attendees. Return whether any action was taken.

        If 'to_cancel' is specified, a list of participants to be sent cancel
        messages is provided.

        If 'to_unschedule' is specified, a list of periods to be unscheduled is
        provided.
        """

        # Here, the organiser should be the current user.

        organiser, organiser_attr = uri_item(self.obj.get_item("ORGANIZER"))

        self.update_sender(organiser_attr)
        self.update_senders()
        self.update_dtstamp()
        self.update_sequence(True)

        if method == "REQUEST":
            methods, parts = self.get_message_parts(self.obj, "REQUEST")

            # Add message parts with cancelled occurrence information.

            unscheduled_parts = self.get_unscheduled_parts(to_unschedule)

            # Send the updated event, along with a cancellation for each of the
            # unscheduled occurrences.

            self.send_message(parts + unscheduled_parts, get_address(organiser), self.obj, True, False)

            # Since the organiser can update the SEQUENCE but this can leave any
            # mail/calendar client lagging, issue a PUBLISH message to the
            # user's address.

            methods, parts = self.get_message_parts(self.obj, "PUBLISH")
            self.send_message_to_self(parts + unscheduled_parts)

        # When cancelling, replace the attendees with those for whom the event
        # is now cancelled.

        if method == "CANCEL" or to_cancel:
            if to_cancel:
                obj = self.obj.copy()
                obj["ATTENDEE"] = to_cancel
            else:
                obj = self.obj

            # Send a cancellation to all uninvited attendees.

            parts = [self.object_to_part("CANCEL", obj)]
            self.send_message(parts, get_address(organiser), obj, True, False)

            # Issue a CANCEL message to the user's address.

            if method == "CANCEL":
                self.send_message_to_self(parts)

        return True

    # Object-related tests.

    def is_recognised_organiser(self, organiser):

        """
        Return whether the given 'organiser' is recognised from
        previously-received details. If no stored details exist, True is
        returned.
        """

        obj = self.get_stored_object_version()
        if obj:
            stored_organiser = get_uri(obj.get_value("ORGANIZER"))
            return stored_organiser == organiser
        else:
            return True

    def is_recognised_attendee(self, attendee):

        """
        Return whether the given 'attendee' is recognised from
        previously-received details. If no stored details exist, True is
        returned.
        """

        obj = self.get_stored_object_version()
        if obj:
            stored_attendees = uri_dict(obj.get_value_map("ATTENDEE"))
            return stored_attendees.has_key(attendee)
        else:
            return True

    def get_attendance(self, user=None, obj=None):

        """
        Return the attendance attributes for 'user', or the current user if
        'user' is not specified.
        """

        attendees = uri_dict((obj or self.obj).get_value_map("ATTENDEE"))
        return attendees.get(user or self.user)

    def is_participating(self, user, as_organiser=False, obj=None):

        """
        Return whether, subject to the 'user' indicating an identity and the
        'as_organiser' status of that identity, the user concerned is actually
        participating in the current object event.
        """

        # Use any attendee property information for an organiser, not the
        # organiser property attributes.

        attr = self.get_attendance(user, obj)
        return as_organiser or attr is not None and not attr or \
            attr and attr.get("PARTSTAT") not in ("DECLINED", "DELEGATED", "NEEDS-ACTION")

    def has_indicated_attendance(self, user=None, obj=None):

        """
        Return whether the given 'user' (or the current user if not specified)
        has indicated attendance in the given 'obj' (or the current object if
        not specified).
        """

        attr = self.get_attendance(user, obj)
        return attr and attr.get("PARTSTAT") not in (None, "NEEDS-ACTION")

    def get_overriding_transparency(self, user, as_organiser=False):

        """
        Return the overriding transparency to be associated with the free/busy
        records for an event, subject to the 'user' indicating an identity and
        the 'as_organiser' status of that identity.

        Where an identity is only an organiser and not attending, "ORG" is
        returned. Otherwise, no overriding transparency is defined and None is
        returned.
        """

        attr = self.get_attendance(user)
        return as_organiser and not (attr and attr.get("PARTSTAT")) and "ORG" or None

    def can_schedule(self, freebusy, periods):

        """
        Indicate whether within 'freebusy' the given 'periods' can be scheduled.
        """

        return freebusy.can_schedule(periods, self.uid, self.recurrenceid)

    def have_new_object(self, strict=True):

        """
        Return whether the current object is new to the current user.

        If 'strict' is specified and is a false value, the DTSTAMP test will be
        ignored. This is useful in handling responses from attendees from
        clients (like Claws Mail) that erase time information from DTSTAMP and
        make it invalid.
        """

        obj = self.get_stored_object_version()

        # If found, compare SEQUENCE and potentially DTSTAMP.

        if obj:
            sequence = obj.get_value("SEQUENCE")
            dtstamp = obj.get_value("DTSTAMP")

            # If the request refers to an older version of the object, ignore
            # it.

            return is_new_object(sequence, self.sequence, dtstamp, self.dtstamp, not strict)

        return True

    def possibly_recurring_indefinitely(self):

        "Return whether the object recurs indefinitely."

        # Obtain the stored object to make sure that recurrence information
        # is not being ignored. This might happen if a client sends a
        # cancellation without the complete set of properties, for instance.

        return self.obj.possibly_recurring_indefinitely() or \
               self.get_stored_object_version() and \
               self.get_stored_object_version().possibly_recurring_indefinitely()

    # Constraint application on event periods.

    def check_object(self):

        "Check the object against any scheduling constraints."

        permitted_values = self.get_permitted_values()
        if not permitted_values:
            return None

        invalid = []

        for period in self.obj.get_periods(self.get_tzid()):
            errors = period.check_permitted(permitted_values)
            if errors:
                start_errors, end_errors = errors
                invalid.append((period.origin, start_errors, end_errors))

        return invalid

    def correct_object(self):

        "Correct the object according to any scheduling constraints."

        permitted_values = self.get_permitted_values()
        return permitted_values and self.obj.correct_object(self.get_tzid(), permitted_values)

    def correct_period(self, period):

        "Correct 'period' according to any scheduling constraints."

        permitted_values = self.get_permitted_values()
        if not permitted_values:
            return period
        else:
            return period.get_corrected(permitted_values)

    # Object retrieval.

    def get_stored_object_version(self):

        """
        Return the stored object to which the current object refers for the
        current user.
        """

        return self.get_stored_object(self.uid, self.recurrenceid)

    def get_definitive_object(self, as_organiser):

        """
        Return an object considered definitive for the current transaction,
        using 'as_organiser' to select the current transaction's object if
        false, or selecting a stored object if true.
        """

        return not as_organiser and self.obj or self.get_stored_object_version()

    def get_parent_object(self):

        """
        Return the parent object to which the current object refers for the
        current user.
        """

        return self.recurrenceid and self.get_stored_object(self.uid, None) or None

    def revert_cancellations(self, periods):

        """
        Restore cancelled recurrences corresponding to any of the given
        'periods'.
        """

        for recurrenceid in self.store.get_cancelled_recurrences(self.user, self.uid):
            obj = self.get_stored_object(self.uid, recurrenceid, "cancellations")
            if set(self.get_periods(obj)).intersection(periods):
                self.store.remove_cancellation(self.user, self.uid, recurrenceid)

    # Convenience methods for modifying free/busy collections.

    def get_recurrence_start_point(self, recurrenceid):

        "Get 'recurrenceid' in a form suitable for matching free/busy entries."

        return self.obj.get_recurrence_start_point(recurrenceid, self.get_tzid())

    def remove_from_freebusy(self, freebusy):

        "Remove this event from the given 'freebusy' collection."

        removed = freebusy.remove_event_periods(self.uid, self.recurrenceid)
        if not removed and self.recurrenceid:
            return freebusy.remove_affected_period(self.uid, self.get_recurrence_start_point(self.recurrenceid))
        else:
            return removed

    def remove_freebusy_for_recurrences(self, freebusy, recurrenceids=None):

        """
        Remove from 'freebusy' any original recurrence from parent free/busy
        details for the current object, if the current object is a specific
        additional recurrence. Otherwise, remove all additional recurrence
        information corresponding to 'recurrenceids', or if omitted, all
        recurrences.
        """

        if self.recurrenceid:
            recurrenceid = self.get_recurrence_start_point(self.recurrenceid)
            freebusy.remove_affected_period(self.uid, recurrenceid)
        else:
            # Remove obsolete recurrence periods.

            freebusy.remove_additional_periods(self.uid, recurrenceids)

            # Remove original periods affected by additional recurrences.

            if recurrenceids:
                for recurrenceid in recurrenceids:
                    recurrenceid = self.get_recurrence_start_point(recurrenceid)
                    freebusy.remove_affected_period(self.uid, recurrenceid)

    def update_freebusy(self, freebusy, user, as_organiser, offer=False):

        """
        Update the 'freebusy' collection for this event with the periods and
        transparency associated with the current object, subject to the 'user'
        identity and the attendance details provided for them, indicating
        whether the update is being done 'as_organiser' (for the organiser of
        an event) or not.

        If 'offer' is set to a true value, any free/busy updates will be tagged
        with an expiry time.
        """

        # Obtain the stored object if the current object is not issued by the
        # organiser. Attendees do not have the opportunity to redefine the
        # periods.

        obj = self.get_definitive_object(as_organiser)
        if not obj:
            return

        # Obtain the affected periods.

        periods = self.get_periods(obj)

        # Define an overriding transparency, the indicated event transparency,
        # or the default transparency for the free/busy entry.

        transp = self.get_overriding_transparency(user, as_organiser) or \
                 obj.get_value("TRANSP") or \
                 "OPAQUE"

        # Calculate any expiry time. If no offer period is defined, do not
        # record the offer periods.

        if offer:
            offer_period = self.get_offer_period()
            if offer_period:
                expires = get_timestamp(offer_period)
            else:
                return
        else:
            expires = None

        # Perform the low-level update.

        Client.update_freebusy(self, freebusy, periods, transp,
            self.uid, self.recurrenceid,
            obj.get_value("SUMMARY"),
            get_uri(obj.get_value("ORGANIZER")),
            expires)

    def update_freebusy_for_participant(self, freebusy, user, for_organiser=False,
                                        updating_other=False, offer=False):

        """
        Update the 'freebusy' collection for the given 'user', indicating
        whether the update is 'for_organiser' (being done for the organiser of
        an event) or not, and whether it is 'updating_other' (meaning another
        user's details).

        If 'offer' is set to a true value, any free/busy updates will be tagged
        with an expiry time.
        """

        # Record in the free/busy details unless a non-participating attendee.
        # Remove periods for non-participating attendees.

        if offer or self.is_participating(user, for_organiser and not updating_other):
            self.update_freebusy(freebusy, user,
                for_organiser and not updating_other or
                not for_organiser and updating_other,
                offer
                )
        else:
            self.remove_from_freebusy(freebusy)

    def remove_freebusy_for_participant(self, freebusy, user, for_organiser=False,
                                        updating_other=False):

        """
        Remove details from the 'freebusy' collection for the given 'user',
        indicating whether the modification is 'for_organiser' (being done for
        the organiser of an event) or not, and whether it is 'updating_other'
        (meaning another user's details).
        """

        # Remove from the free/busy details if a specified attendee.

        if self.is_participating(user, for_organiser and not updating_other):
            self.remove_from_freebusy(freebusy)

    # Convenience methods for updating stored free/busy information received
    # from other users.

    def update_freebusy_from_participant(self, user, for_organiser, fn=None):

        """
        For the current user, record the free/busy information for another
        'user', indicating whether the update is 'for_organiser' or not, thus
        maintaining a separate record of their free/busy details.
        """

        fn = fn or self.update_freebusy_for_participant

        # A user does not store free/busy information for themself as another
        # party.

        if user == self.user:
            return

        self.acquire_lock()
        try:
            freebusy = self.store.get_freebusy_for_other_for_update(self.user, user)
            fn(freebusy, user, for_organiser, True)

            # Tidy up any obsolete recurrences.

            self.remove_freebusy_for_recurrences(freebusy, self.store.get_recurrences(self.user, self.uid))
            self.store.set_freebusy_for_other(self.user, freebusy, user)

        finally:
            self.release_lock()

    def update_freebusy_from_organiser(self, organiser):

        "For the current user, record free/busy information from 'organiser'."

        self.update_freebusy_from_participant(organiser, True)

    def update_freebusy_from_attendees(self, attendees):

        "For the current user, record free/busy information from 'attendees'."

        obj = self.get_stored_object_version()

        if not obj or not self.have_new_object():
            return False

        # Filter out unrecognised attendees.

        attendees = set(attendees).intersection(uri_values(obj.get_values("ATTENDEE")))

        for attendee in attendees:
            self.update_freebusy_from_participant(attendee, False)

        return True

    def remove_freebusy_from_organiser(self, organiser):

        "For the current user, remove free/busy information from 'organiser'."

        self.update_freebusy_from_participant(organiser, True, self.remove_freebusy_for_participant)

    def remove_freebusy_from_attendees(self, attendees):

        "For the current user, remove free/busy information from 'attendees'."

        for attendee in attendees.keys():
            self.update_freebusy_from_participant(attendee, False, self.remove_freebusy_for_participant)

    # Convenience methods for updating free/busy details at the event level.

    def update_event_in_freebusy(self, for_organiser=True):

        """
        Update free/busy information when handling an object, doing so for the
        organiser of an event if 'for_organiser' is set to a true value.
        """

        freebusy = self.store.get_freebusy_for_update(self.user)

        # Obtain the attendance attributes for this user, if available.

        self.update_freebusy_for_participant(freebusy, self.user, for_organiser)

        # Remove original recurrence details replaced by additional
        # recurrences, as well as obsolete additional recurrences.

        self.remove_freebusy_for_recurrences(freebusy, self.store.get_recurrences(self.user, self.uid))
        self.store.set_freebusy(self.user, freebusy)

        if self.publisher and self.is_sharing() and self.is_publishing():
            self.publisher.set_freebusy(self.user, freebusy)

        # Update free/busy provider information if the event may recur
        # indefinitely.

        if self.possibly_recurring_indefinitely():
            self.store.append_freebusy_provider(self.user, self.obj)

        return True

    def remove_event_from_freebusy(self):

        "Remove free/busy information when handling an object."

        freebusy = self.store.get_freebusy_for_update(self.user)

        self.remove_from_freebusy(freebusy)
        self.remove_freebusy_for_recurrences(freebusy)
        self.store.set_freebusy(self.user, freebusy)

        if self.publisher and self.is_sharing() and self.is_publishing():
            self.publisher.set_freebusy(self.user, freebusy)

        # Update free/busy provider information if the event may recur
        # indefinitely.

        if self.possibly_recurring_indefinitely():
            self.store.remove_freebusy_provider(self.user, self.obj)

    def update_event_in_freebusy_offers(self):

        "Update free/busy offers when handling an object."

        freebusy = self.store.get_freebusy_offers_for_update(self.user)

        # Obtain the attendance attributes for this user, if available.

        self.update_freebusy_for_participant(freebusy, self.user, offer=True)

        # Remove original recurrence details replaced by additional
        # recurrences, as well as obsolete additional recurrences.

        self.remove_freebusy_for_recurrences(freebusy, self.store.get_recurrences(self.user, self.uid))
        self.store.set_freebusy_offers(self.user, freebusy)

        return True

    def remove_event_from_freebusy_offers(self):

        "Remove free/busy offers when handling an object."

        freebusy = self.store.get_freebusy_offers_for_update(self.user)

        self.remove_from_freebusy(freebusy)
        self.remove_freebusy_for_recurrences(freebusy)
        self.store.set_freebusy_offers(self.user, freebusy)

        return True

    # Convenience methods for removing counter-proposals and updating the
    # request queue.

    def remove_request(self):
        return self.store.dequeue_request(self.user, self.uid, self.recurrenceid)

    def remove_event(self):
        return self.store.remove_event(self.user, self.uid, self.recurrenceid)

    def remove_counter(self, attendee):
        self.remove_counters([attendee])

    def remove_counters(self, attendees):
        for attendee in attendees:
            self.store.remove_counter(self.user, attendee, self.uid, self.recurrenceid)

        if not self.store.get_counters(self.user, self.uid, self.recurrenceid):
            self.store.dequeue_request(self.user, self.uid, self.recurrenceid)

# vim: tabstop=4 expandtab shiftwidth=4