summaryrefslogtreecommitdiffstats
path: root/wallace/module_resources.py
blob: 6a9e4ba610bb4319b67b1d1e99f5270822450134 (plain)
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
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Kolab Systems AG (http://www.kolabsys.com)
#
# Jeroen van Meeuwen (Kolab Systems) <vanmeeuwen a kolabsys.com>
#
# 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; version 3 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#

import datetime
import icalendar
import os
import pytz
import random
import tempfile
import time
from urlparse import urlparse
import urllib

from email import message_from_string
from email.parser import Parser
from email.utils import formataddr
from email.utils import getaddresses

import modules

import pykolab
import kolabformat

from pykolab.auth import Auth
from pykolab.conf import Conf
from pykolab.imap import IMAP
from pykolab.xml import event_from_ical
from pykolab.xml import event_from_string
from pykolab.xml import to_dt
from pykolab.translate import _

log = pykolab.getLogger('pykolab.wallace')
conf = pykolab.getConf()

mybasepath = '/var/spool/pykolab/wallace/resources/'

auth = None
imap = None

def __init__():
    modules.register('resources', execute, description=description())

def accept(filepath):
    new_filepath = os.path.join(
            mybasepath,
            'ACCEPT',
            os.path.basename(filepath)
        )

    cleanup()
    os.rename(filepath, new_filepath)
    filepath = new_filepath
    exec('modules.cb_action_ACCEPT(%r, %r)' % ('resources',filepath))

def description():
    return """Resource management module."""

def cleanup():
    global auth, imap

    log.debug("cleanup(): %r, %r" % (auth, imap), level=9)

    auth.disconnect()
    del auth

    # Disconnect IMAP or we lock the mailbox almost constantly
    imap.disconnect()
    del imap

def execute(*args, **kw):
    global auth, imap

    if not os.path.isdir(mybasepath):
        os.makedirs(mybasepath)

    for stage in ['incoming', 'ACCEPT', 'REJECT', 'HOLD', 'DEFER' ]:
        if not os.path.isdir(os.path.join(mybasepath, stage)):
            os.makedirs(os.path.join(mybasepath, stage))

    log.debug(_("Resource Management called for %r, %r") % (args, kw), level=9)

    auth = Auth()
    imap = IMAP()

    # TODO: Test for correct call.
    filepath = args[0]

    if kw.has_key('stage'):
        log.debug(
                _("Issuing callback after processing to stage %s") % (
                        kw['stage']
                    ),
                level=8
            )

        log.debug(_("Testing cb_action_%s()") % (kw['stage']), level=8)
        if hasattr(modules, 'cb_action_%s' % (kw['stage'])):
            log.debug(
                    _("Attempting to execute cb_action_%s()") % (kw['stage']),
                    level=8
                )

            exec(
                    'modules.cb_action_%s(%r, %r)' % (
                            kw['stage'],
                            'resources',
                            filepath
                        )
                )

            return filepath
    else:
        # Move to incoming
        new_filepath = os.path.join(
                mybasepath,
                'incoming',
                os.path.basename(filepath)
            )

        if not filepath == new_filepath:
            log.debug("Renaming %r to %r" % (filepath, new_filepath))
            os.rename(filepath, new_filepath)
            filepath = new_filepath

    # parse full message
    message = Parser().parse(open(filepath, 'r'))

    recipients = [address for displayname,address in getaddresses(message.get_all('X-Kolab-To'))]

    any_itips = False
    any_resources = False
    possibly_any_resources = True

    # An iTip message may contain multiple events. Later on, test if the message
    # is an iTip message by checking the length of this list.
    try:
        itip_events = itip_events_from_message(message)
    except Exception, e:
        log.error(_("Failed to parse iTip events from message: %r" % (e)))
        itip_events = []

    if not len(itip_events) > 0:
        log.info(
                _("Message is not an iTip message or does not contain any " + \
                    "(valid) iTip.")
            )

    else:
        any_itips = True

        log.debug(
                _("iTip events attached to this message contain the " + \
                    "following information: %r") % (itip_events),
                level=9
            )

    if any_itips:
        # See if any iTip actually allocates a resource.
        if len([x['resources'] for x in itip_events if x.has_key('resources')]) == 0:
            if len([x['attendees'] for x in itip_events if x.has_key('attendees')]) == 0:
                possibly_any_resources = False
        else:
            possibly_any_resources = False

    if possibly_any_resources:
        auth.connect()

        for recipient in recipients:
            if not len(resource_record_from_email_address(recipient)) == 0:
                resource_recipient = recipient
                any_resources = True

    if any_resources:
        if not any_itips:
            log.debug(_("Not an iTip message, but sent to resource nonetheless. Reject message"), level=5)
            reject(filepath)
            return False
        else:
            # Continue. Resources and iTips. We like.
            pass
    else:
        if not any_itips:
            log.debug(_("No itips, no resources, pass along %r") % (filepath), level=5)
            return filepath
        else:
            log.debug(_("iTips, but no resources, pass along %r") % (filepath), level=5)
            return filepath

    # A simple list of merely resource entry IDs that hold any relevance to the
    # iTip events
    resource_dns = resource_records_from_itip_events(itip_events, resource_recipient)

    # check if resource attendees match the envelope recipient
    if len(resource_dns) == 0:
        log.info(_("No resource attendees matching envelope recipient %s, Reject message") % (resource_recipient))
        reject(filepath)
        return False


    # Get the resource details, which includes details on the IMAP folder
    # This may append resource collection members to recource_dns
    resources = get_resource_records(resource_dns)

    log.debug(_("Resources: %r; %r") % (resource_dns, resources), level=8)

    imap.connect()

    done = False
    receiving_resource = resources[resource_dns[0]]

    for itip_event in itip_events:
        try:
            receiving_attendee = itip_event['xml'].get_attendee_by_email(receiving_resource['mail'])
            log.debug(_("Receiving Resource: %r; %r") % (receiving_resource, receiving_attendee), level=9)
        except Exception, e:
            log.error("Could not find envelope attendee: %r" % (e))
            continue

        # ignore updates and cancellations to resource collections who already delegated the event
        if receiving_attendee.get_delegated_to().size() > 0 or receiving_attendee.get_role() == kolabformat.NonParticipant:
            done = True
            log.debug(_("Recipient %r is non-participant, ignoring message") % (receiving_resource['mail']), level=8)

        # process CANCEL messages
        if not done and itip_event['method'] == "CANCEL":
            for resource in resource_dns:
                if resources[resource]['mail'] in [a.get_email() for a in itip_event['xml'].get_attendees()]:
                    delete_resource_event(itip_event['uid'], resources[resource])

            done = True

    if done:
        os.unlink(filepath)
        cleanup()
        return


    # do the magic for the receiving attendee
    (available_resource, itip_event) = check_availability(itip_events, resource_dns, resources, receiving_attendee)

    # accept reservation
    if available_resource is not None:
        if available_resource['mail'] in [a.get_email() for a in itip_event['xml'].get_attendees()]:
            # replace existing copy of this event
            if len(available_resource['existing_events']) > 0:
                for uid in available_resource['existing_events']:
                    delete_resource_event(uid, available_resource)

            log.debug(_("Accept invitation for individual resource %r / %r") % (available_resource['dn'], available_resource['mail']), level=8)

            # check if reservation was delegated
            original_resource = None
            if available_resource['mail'] != receiving_resource['mail'] and receiving_attendee.get_participant_status() == kolabformat.PartDelegated:
                original_resource = receiving_resource

            accept_reservation_request(itip_event, available_resource, original_resource)

        else:
            # This must have been a resource collection originally.
            # We have inserted the reference to the original resource
            # record in 'memberof'.
            if available_resource.has_key('memberof'):
                original_resource = resources[available_resource['memberof']]

                if original_resource['mail'] in [a.get_email() for a in itip_event['xml'].get_attendees()]:
                    #
                    # Delegate:
                    # - delegator: the original resource collection
                    # - delegatee: the target resource
                    #
                    itip_event['xml'].delegate(original_resource['mail'], available_resource['mail'], available_resource['cn'])

                    # set delegator to NON-PARTICIPANT and RSVP=FALSE
                    delegator = itip_event['xml'].get_attendee_by_email(original_resource['mail'])
                    delegator.set_role(kolabformat.NonParticipant)
                    delegator.set_rsvp(False)

                    log.debug(_("Delegate invitation for resource collection %r to %r") % (original_resource['mail'], available_resource['mail']), level=8)
                    accept_reservation_request(itip_event, available_resource, original_resource)

    # decline reservation
    else:
        resource = resources[resource_dns[0]]  # this is the receiving resource record
        decline_reservation_request(itip_event, resource)

    cleanup()

    os.unlink(filepath)


def check_availability(itip_events, resource_dns, resources, receiving_attendee=None):
    """
        For each resource, determine if any of the events in question are in conflict.
    """

    # Store the (first) conflicting event(s) alongside the resource information.
    start = time.time()
    num_messages = 0
    available_resource = None

    for resource in resources.keys():
        # skip this for resource collections
        if not resources[resource].has_key('kolabtargetfolder'):
            continue

        # sets the 'conflicting' flag and adds a list of conflicting events found
        try:
            num_messages += read_resource_calendar(resources[resource], itip_events)
        except Exception, e:
            log.error(_("Failed to read resource calendar for %r: %r") % (resource, e))

    end = time.time()

    log.debug(_("start: %r, end: %r, total: %r, messages: %d") % (start, end, (end-start), num_messages), level=9)


    # For each resource (collections are first!)
    # check conflicts and either accept or decline the reservation request
    for resource in resource_dns:
        log.debug(_("Polling for resource %r") % (resource), level=9)

        if not resources.has_key(resource):
            log.debug(_("Resource %r has been popped from the list") % (resource), level=9)
            continue

        if not resources[resource].has_key('conflicting_events'):
            log.debug(_("Resource is a collection"), level=9)

            # check if there are non-conflicting collection members
            conflicting_members = [x for x in resources[resource]['uniquemember'] if resources[x]['conflict']]

            # found at least one non-conflicting member, remove the conflicting ones and continue
            if len(conflicting_members) < len(resources[resource]['uniquemember']):
                for member in conflicting_members:
                    resources[resource]['uniquemember'] = [x for x in resources[resource]['uniquemember'] if x != member]
                    del resources[member]

                log.debug(_("Removed conflicting resources from %r: (%r) => %r") % (
                    resource, conflicting_members, resources[resource]['uniquemember']
                ), level=9)

            else:
                # TODO: shuffle existing bookings of collection members in order
                # to make one availale for the requested time
                pass

            continue

        if len(resources[resource]['conflicting_events']) > 0:
            log.debug(_("Conflicting events: %r for resource %r") % (resources[resource]['conflicting_events'], resource), level=9)

            # This is the event being conflicted with!
            for itip_event in itip_events:
                # Now we have the event that was conflicting
                if resources[resource]['mail'] in [a.get_email() for a in itip_event['xml'].get_attendees()]:
                    # this resource initially was delegated from a collection ?
                    if receiving_attendee and receiving_attendee.get_email() == resources[resource]['mail'] \
                            and len(receiving_attendee.get_delegated_from()) > 0:
                        for delegator in receiving_attendee.get_delegated_from():
                            collection_data = get_resource_collection(delegator.email())
                            if collection_data is not None:
                                # check if another collection member is available
                                (available_resource, dummy) = check_availability(itip_events, collection_data[0], collection_data[1])
                                break

                        if available_resource is not None:
                            log.debug(_("Delegate to another resource collection member: %r to %r") % \
                                (resources[resource]['mail'], available_resource['mail']), level=8)

                            # set this new resource as delegate for the receiving_attendee
                            itip_event['xml'].delegate(resources[resource]['mail'], available_resource['mail'], available_resource['cn'])

                            # set delegator to NON-PARTICIPANT and RSVP=FALSE
                            receiving_attendee.set_role(kolabformat.NonParticipant)
                            receiving_attendee.set_rsvp(False)
                            receiving_attendee.setDelegatedFrom([])

                            # remove existing_events as we now delegated back to the collection
                            if len(resources[resource]['existing_events']) > 0:
                                for uid in resources[resource]['existing_events']:
                                    delete_resource_event(uid, resources[resource])

                    done = True

                if done:
                    break

        else:
            # No conflicts, go accept
            for itip_event in itip_events:
                # directly invited resource
                if resources[resource]['mail'] in [a.get_email() for a in itip_event['xml'].get_attendees()]:
                    available_resource = resources[resource]
                    done = True

                else:
                    # This must have been a resource collection originally.
                    # We have inserted the reference to the original resource
                    # record in 'memberof'.
                    if resources[resource].has_key('memberof'):
                        original_resource = resources[resources[resource]['memberof']]

                        # Randomly select a target resource from the resource collection.
                        available_resource = resources[original_resource['uniquemember'][random.randint(0,(len(original_resource['uniquemember'])-1))]]
                        done = True

        if done:
            break

    # end for resource in resource_dns:

    return (available_resource, itip_event)


def read_resource_calendar(resource_rec, itip_events):
    """
        Read all booked events from the given resource's calendar
        and check for conflicts with the given list if itip events
    """
    global imap

    resource_rec['conflict'] = False
    resource_rec['conflicting_events'] = []
    resource_rec['existing_events'] = []

    mailbox = resource_rec['kolabtargetfolder']

    log.debug(
        _("Checking events in resource folder %r") % (mailbox),
        level=9
    )

    # might raise an exception, let that bubble
    imap.imap.m.select(imap.folder_quote(mailbox))
    typ, data = imap.imap.m.search(None, 'ALL')

    num_messages = len(data[0].split())

    for num in data[0].split():
        # For efficiency, makes the routine non-deterministic
        if resource_rec['conflict']:
            continue

        log.debug(
            _("Fetching message UID %r from folder %r") % (num, mailbox),
            level=9
        )

        typ, data = imap.imap.m.fetch(num, '(RFC822)')

        event_message = message_from_string(data[0][1])

        if event_message.is_multipart():
            for part in event_message.walk():
                if part.get_content_type() == "application/calendar+xml":
                    payload = part.get_payload(decode=True)
                    event = pykolab.xml.event_from_string(payload)

                    for itip in itip_events:
                        _es = to_dt(event.get_start())
                        _ee = to_dt(event.get_end())

                        conflict = False

                        # naive loops to check for collisions in (recurring) events
                        # TODO: compare recurrence rules directly (e.g. matching time slot or weekday or monthday)
                        while not conflict and _es is not None:
                            _is = to_dt(itip['start'])
                            _ie = to_dt(itip['end'])

                            while not conflict and _is is not None:
                                log.debug("* Comparing event dates at %s/%s with %s/%s" % (_es, _ee, _is, _ie), level=9)
                                conflict = check_date_conflict(_es, _ee, _is, _ie)
                                _is = to_dt(itip['xml'].get_next_occurence(_is)) if event.is_recurring() else None
                                _ie = to_dt(itip['xml'].get_occurence_end_date(_is))

                            _es = to_dt(event.get_next_occurence(_es)) if event.is_recurring() else None
                            _ee = to_dt(event.get_occurence_end_date(_es))

                        if event.get_uid() == itip['uid']:
                            resource_rec['existing_events'].append(itip['uid'])

                            # don't register conflict for updates
                            if itip['sequence'] > 0 and itip['sequence'] >= event.get_sequence():
                                conflict = False

                        if conflict:
                            log.info(
                                _("Event %r conflicts with event %r") % (
                                    itip['xml'].get_uid(),
                                    event.get_uid()
                                )
                            )

                            resource_rec['conflicting_events'].append(event.get_uid())
                            resource_rec['conflict'] = True

    return num_messages

def check_date_conflict(_es, _ee, _is, _ie):
    conflict = False

    # TODO: add margin for all-day dates (+13h; -12h)

    if _es < _is:
        if _es <= _ie:
            if _ee <= _is:
                conflict = False
            else:
                conflict = True
        else:
            conflict = True
    elif _es == _is:
        conflict = True
    else: # _es > _is
        if _es <= _ie:
            conflict = True
        else:
            conflict = False
    
    return conflict


def accept_reservation_request(itip_event, resource, delegator=None):
    """
        Accepts the given iTip event by booking it into the resource's
        calendar. Then set the attendee status of the given resource to
        ACCEPTED and sends an iTip reply message to the organizer.
    """

    itip_event['xml'].set_attendee_participant_status(
        itip_event['xml'].get_attendee_by_email(resource['mail']),
        "ACCEPTED"
    )

    saved = save_resource_event(itip_event, resource)

    log.debug(
        _("Adding event to %r: %r") % (resource['kolabtargetfolder'], saved),
        level=8
    )

    send_response(delegator['mail'] if delegator else resource['mail'], itip_event, get_resource_owner(resource))


def decline_reservation_request(itip_event, resource):
    """
        Set the attendee status of the given resource to
        DECLINED and send an according iTip reply to the organizer.
    """

    itip_event['xml'].set_attendee_participant_status(
        itip_event['xml'].get_attendee_by_email(resource['mail']),
        "DECLINED"
    )

    send_response(resource['mail'], itip_event, get_resource_owner(resource))


def save_resource_event(itip_event, resource):
    """
        Append the given event object to the resource's calendar
    """
    try:
        # Administrator login name comes from configuration.
        targetfolder = imap.folder_quote(resource['kolabtargetfolder'])
        imap.imap.m.setacl(targetfolder, conf.get(conf.get('kolab', 'imap_backend'), 'admin_login'), "lrswipkxtecda")
        result = imap.imap.m.append(
            targetfolder,
            None,
            None,
            itip_event['xml'].to_message().as_string()
        )
        return result

    except Exception, e:
        log.error(_("Failed to save event to resource calendar at %r: %r") % (
            resource['kolabtargetfolder'], e
        ))

    return False


def delete_resource_event(uid, resource):
    """
        Removes the IMAP object with the given UID from a resource's calendar folder
    """
    targetfolder = imap.folder_quote(resource['kolabtargetfolder'])
    imap.imap.m.setacl(targetfolder, conf.get(conf.get('kolab', 'imap_backend'), 'admin_login'), "lrswipkxtecda")
    imap.imap.m.select(targetfolder)

    typ, data = imap.imap.m.search(None, '(HEADER SUBJECT "%s")' % uid)

    log.debug(_("Delete resource calendar object %r in %r: %r") % (
        uid, resource['kolabtargetfolder'], data
    ), level=9)

    for num in data[0].split():
        imap.imap.m.store(num, '+FLAGS', '\\Deleted')

    imap.imap.m.expunge()


def itip_events_from_message(message):
    """
        Obtain the iTip payload from email.message <message>
    """
    # Placeholder for any itip_events found in the message.
    itip_events = []
    seen_uids = []

    # iTip methods we are actually interested in. Other methods will be ignored.
    itip_methods = [ "REQUEST", "CANCEL" ]

    # Are all iTip messages multipart? No! RFC 6047, section 2.4 states "A
    # MIME body part containing content information that conforms to this
    # document MUST have (...)" but does not state whether an iTip message must
    # therefore also be multipart.

    # Check each part
    for part in message.walk():

        # The iTip part MUST be Content-Type: text/calendar (RFC 6047, section 2.4)
        # But in real word, other mime-types are used as well
        if part.get_content_type() in [ "text/calendar", "text/x-vcalendar", "application/ics" ]:
            if not str(part.get_param('method')).upper() in itip_methods:
                log.error(_("Method %r not really interesting for us.") % (part.get_param('method')))
                continue

            # Get the itip_payload
            itip_payload = part.get_payload(decode=True)

            log.debug(_("Raw iTip payload: %s") % (itip_payload), level=9)

            # Python iCalendar prior to 3.0 uses "from_string".
            if hasattr(icalendar.Calendar, 'from_ical'):
                cal = icalendar.Calendar.from_ical(itip_payload)
            elif hasattr(icalendar.Calendar, 'from_string'):
                cal = icalendar.Calendar.from_string(itip_payload)

            # If we can't read it, we're out
            else:
                log.error(_("Could not read iTip from message."))
                return []

            for c in cal.walk():
                if c.name == "VEVENT":
                    itip = {}

                    if c['uid'] in seen_uids:
                        log.debug(_("Duplicate iTip event: %s") % (c['uid']), level=9)
                        continue

                    # From the event, take the following properties:
                    #
                    # - method
                    # - uid
                    # - sequence
                    # - start
                    # - end (if any)
                    # - duration (if any)
                    # - organizer
                    # - attendees (if any)
                    # - resources (if any)
                    #

                    itip['uid'] = str(c['uid'])
                    itip['method'] = str(cal['method']).upper()
                    itip['sequence'] = int(c['sequence']) if c.has_key('sequence') else 0

                    if c.has_key('dtstart'):
                        itip['start'] = c['dtstart'].dt
                    else:
                        log.error(_("iTip event without a start"))
                        continue

                    if c.has_key('dtend'):
                        itip['end'] = c['dtend'].dt

                    if c.has_key('duration'):
                        itip['duration'] = c['duration'].dt
                        itip['end'] = itip['start'] + c['duration'].dt

                    itip['organizer'] = c['organizer']

                    itip['attendees'] = c['attendee']

                    if c.has_key('resources'):
                        itip['resources'] = c['resources']

                    itip['raw'] = itip_payload

                    try:
                        itip['xml'] = event_from_ical(c.to_ical())
                    except Exception, e:
                        log.error("event_from_ical() exception: %r" % (e))
                        continue

                    itip_events.append(itip)

                    seen_uids.append(c['uid'])

                # end if c.name == "VEVENT"

            # end for c in cal.walk()

        # end if part.get_content_type() == "text/calendar"

    # end for part in message.walk()

    if not len(itip_events) and not message.is_multipart():
        log.debug(_("Message is not an iTip message (non-multipart message)"), level=5)

    return itip_events

def reject(filepath):
    new_filepath = os.path.join(
            mybasepath,
            'REJECT',
            os.path.basename(filepath)
        )

    os.rename(filepath, new_filepath)
    filepath = new_filepath
    exec('modules.cb_action_REJECT(%r, %r)' % ('resources',filepath))


def resource_record_from_email_address(email_address):
    """
        Resolves the given email address to a resource entity
    """
    global auth

    if not auth:
        auth = Auth()
        auth.connect()

    resource_records = []

    local_domains = auth.list_domains()

    if not local_domains == None:
        local_domains = list(set(local_domains.keys()))

    if not email_address.split('@')[1] in local_domains:
        return []

    log.debug(
        _("Checking if email address %r belongs to a resource (collection)") % (email_address),
        level=8
    )

    resource_records = auth.find_resource(email_address)

    if isinstance(resource_records, list):
        if len(resource_records) > 0:
            log.debug(_("Resource record(s): %r") % (resource_records), level=8)
        else:
            log.debug(_("No resource (collection) records found for %r") % (email_address), level=9)

    elif isinstance(resource_records, basestring):
        resource_records = [ resource_records ]
        log.debug(_("Resource record: %r") % (resource_records), level=8)

    auth.disconnect()

    return resource_records


def resource_records_from_itip_events(itip_events, recipient_email=None):
    """
        Given a list of itip_events, determine which resources have been
        invited as attendees and/or resources.
    """
    global auth

    if not auth:
        auth = Auth()
        auth.connect()

    resource_records = []

    log.debug(_("Raw itip_events: %r") % (itip_events), level=9)
    attendees_raw = []
    for list_attendees_raw in [x for x in [y['attendees'] for y in itip_events if y.has_key('attendees') and isinstance(y['attendees'], list)]]:
        attendees_raw.extend(list_attendees_raw)

    for list_attendees_raw in [y['attendees'] for y in itip_events if y.has_key('attendees') and isinstance(y['attendees'], basestring)]:
        attendees_raw.append(list_attendees_raw)

    log.debug(_("Raw set of attendees: %r") % (attendees_raw), level=9)

    # TODO: Resources are actually not implemented in the format. We reset this
    # list later.
    resources_raw = []
    for list_resources_raw in [x for x in [y['resources'] for y in itip_events if y.has_key('resources')]]:
        resources_raw.extend(list_resources_raw)

    log.debug(_("Raw set of resources: %r") % (resources_raw), level=9)

    # TODO: We expect the format of an attendee line to literally be:
    #
    #   ATTENDEE:RSVP=TRUE;ROLE=REQ-PARTICIPANT;MAILTO:lydia.bossers@kolabsys.com
    #
    # which makes the attendees_raw contain:
    #
    #   RSVP=TRUE;ROLE=REQ-PARTICIPANT;MAILTO:lydia.bossers@kolabsys.com
    #
    attendees = [x.split(':')[-1] for x in attendees_raw]

    # Limit the attendee resources to the one that is actually invited
    # with the current message. Considering all invited resources would result in
    # duplicate responses from every iTip message sent to a resource.
    if recipient_email is not None:
        attendees = [a for a in attendees if a == recipient_email]

    for attendee in attendees:
        log.debug(_("Checking if attendee %r is a resource (collection)") % (attendee), level=8)

        _resource_records = auth.find_resource(attendee)

        if isinstance(_resource_records, list):
            if len(_resource_records) > 0:
                resource_records.extend(_resource_records)
                log.debug(_("Resource record(s): %r") % (_resource_records), level=8)
            else:
                log.debug(_("No resource (collection) records found for %r") % (attendee), level=9)

        elif isinstance(_resource_records, basestring):
            resource_records.append(_resource_records)
            log.debug(_("Resource record: %r") % (_resource_records), level=8)

        else:
            log.warning(_("Resource reservation made but no resource records found"))

    # Escape the non-implementation of the free-form, undefined RESOURCES
    # list(s) in iTip.
    if len(resource_records) == 0:

        # TODO: We don't know how to handle this yet!
        # We expect the format of an resource line to literally be:
        #   RESOURCES:MAILTO:resource-car@kolabsys.com
        resources_raw = []

        resources = [x.split(':')[-1] for x in resources_raw]

        # Limit the attendee resources to the one that is actually invited
        # with the current message.
        if recipient_email is not None:
            resources = [a for a in resources if a == recipient_email]

        for resource in resources:
            log.debug(_("Checking if resource %r is a resource (collection)") % (resource), level=8)

            _resource_records = auth.find_resource(resource)
            if isinstance(_resource_records, list):
                if len(_resource_records) > 0:
                    resource_records.extend(_resource_records)
                    log.debug(_("Resource record(s): %r") % (_resource_records), level=8)

                else:
                    log.debug(_("No resource (collection) records found for %r") % (resource), level=8)

            elif isinstance(_resource_records, basestring):
                resource_records.append(_resource_records)
                log.debug(_("Resource record: %r") % (_resource_records), level=8)
            else:
                log.warning(_("Resource reservation made but no resource records found"))


    log.debug(_("The following resources are being referred to in the " + \
                "iTip: %r") % (resource_records), level=8)

    return resource_records


def get_resource_records(resource_dns):
    """
        Get the resource details, which includes details on the IMAP folder
    """
    global auth

    resources = {}
    for resource_dn in list(set(resource_dns)):
        # Get the attributes for the record
        # See if it is a resource collection
        #   If it is, expand to individual resources
        #   If it is not, ...
        resource_attrs = auth.get_entry_attributes(None, resource_dn, ['*'])
        resource_attrs['dn'] = resource_dn
        if not 'kolabsharedfolder' in [x.lower() for x in resource_attrs['objectclass']]:
            if resource_attrs.has_key('uniquemember'):
                resources[resource_dn] = resource_attrs
                for uniquemember in resource_attrs['uniquemember']:
                    resource_attrs = auth.get_entry_attributes(
                            None,
                            uniquemember,
                            ['*']
                        )

                    if 'kolabsharedfolder' in [x.lower() for x in resource_attrs['objectclass']]:
                        resource_attrs['dn'] = uniquemember
                        resources[uniquemember] = resource_attrs
                        resources[uniquemember]['memberof'] = resource_dn
                        if not resource_attrs.has_key('owner') and resources[resource_dn].has_key('owner'):
                            resources[uniquemember]['owner'] = resources[resource_dn]['owner']
                        resource_dns.append(uniquemember)
        else:
            resources[resource_dn] = resource_attrs

    return resources


def get_resource_collection(email_address):
    """
        
    """
    resource_dns = resource_record_from_email_address(email_address)
    if len(resource_dns) == 1:
        resource_attrs = auth.get_entry_attributes(None, resource_dns[0], ['objectclass'])
        if not 'kolabsharedfolder' in [x.lower() for x in resource_attrs['objectclass']]:
            resources = get_resource_records(resource_dns)
            return (resource_dns, resources)

    return None


def get_resource_owner(resource):
    """
        Get this resource's owner record
    """
    global auth

    if not auth:
        auth = Auth()
        auth.connect()

    owners = []

    if resource.has_key('owner'):
        if not isinstance(resource['owner'], list):
            owners = [ resource['owner'] ]
        else:
            owners = resource['owner']

    else:
        # get owner attribute from collection
        collections = auth.search_entry_by_attribute('uniquemember', resource['dn'])
        if not isinstance(collections, list):
            collections = [ collections ]

        for dn,collection in collections:
            if collection.has_key('owner') and isinstance(collection['owner'], list):
                owners += collection['owner']
            elif collection.has_key('owner'):
                owners.append(collection['owner'])

    for dn in owners:
        owner = auth.get_entry_attributes(None, dn, ['cn','mail','telephoneNumber'])
        if owner is not None:
            return owner

    return None


def send_response(from_address, itip_events, owner=None):
    """
        Send the given iCal events as a valid iTip response to the organizer.
        In case the invited resource coolection was delegated to a concrete
        resource, this will send an additional DELEGATED response message.
    """

    import smtplib
    smtp = smtplib.SMTP("localhost", 10027)

    if conf.debuglevel > 8:
        smtp.set_debuglevel(True)

    if isinstance(itip_events, dict):
        itip_events = [ itip_events ]

    for itip_event in itip_events:
        attendee = itip_event['xml'].get_attendee_by_email(from_address)
        participant_status = itip_event['xml'].get_ical_attendee_participant_status(attendee)

        message_text = reservation_response_text(participant_status, owner)

        if participant_status == "DELEGATED":
            # Extra actions to take
            delegator = itip_event['xml'].get_attendee_by_email(from_address)
            delegatee = [a for a in itip_event['xml'].get_attendees() if from_address in [b.email() for b in a.get_delegated_from()]][0]
            delegatee_status = itip_event['xml'].get_ical_attendee_participant_status(delegatee)

            message = itip_event['xml'].to_message_itip(delegatee.get_email(),
                method="REPLY",
                participant_status=delegatee_status,
                message_text=reservation_response_text(delegatee_status, owner)
            )
            smtp.sendmail(message['From'], message['To'], message.as_string())

            # restore list of attendees after to_message_itip()
            itip_event['xml']._attendees = [ delegator, delegatee ]
            itip_event['xml'].event.setAttendees(itip_event['xml']._attendees)

            participant_status = "DELEGATED"
            message_text = _("""
                *** This is an automated response, please do not reply! ***

                Your reservation was delegated to "%s" which is available for the requested time.
            """) % (delegatee.get_name())

        message = itip_event['xml'].to_message_itip(from_address,
            method="REPLY",
            participant_status=participant_status,
            message_text=message_text
        )
        smtp.sendmail(message['From'], message['To'], message.as_string())

    smtp.quit()


def reservation_response_text(status, owner):
    message_text = _("""
        *** This is an automated response, please do not reply! ***
        
        We hereby inform you that your reservation was %s.
    """) % (_(status))

    if owner:
        message_text += _("""
            If you have questions about this reservation, please contact
            %s <%s> %s
        """) % (owner['cn'], owner['mail'], owner['telephoneNumber'] if owner.has_key('telephoneNumber') else '')
    
    return message_text