This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
/
static.py
835 lines (679 loc) · 30.3 KB
/
static.py
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
##
# Copyright (c) 2005-2007 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
"""
CalDAV-aware static resources.
"""
__all__ = [
"CalDAVFile",
"AutoProvisioningFileMixIn",
"CalendarHomeProvisioningFile",
"CalendarHomeUIDProvisioningFile",
"CalendarHomeFile",
"ScheduleFile",
"ScheduleInboxFile",
"ScheduleOutboxFile",
"DropBoxHomeFile",
"DropBoxCollectionFile",
"DropBoxChildFile",
"NotificationsCollectionFile",
"NotificationFile",
]
import datetime
import os
import errno
from urlparse import urlsplit
from twisted.internet.defer import deferredGenerator, fail, succeed, waitForDeferred
from twisted.python import log
from twisted.web2 import responsecode
from twisted.web2.http import HTTPError, StatusResponse
from twisted.web2.dav import davxml
from twisted.web2.dav.fileop import mkcollection, rmdir
from twisted.web2.dav.http import ErrorResponse
from twisted.web2.dav.idav import IDAVResource
from twisted.web2.dav.method import put_common as put_common_base
from twisted.web2.dav.resource import AccessDeniedError
from twisted.web2.dav.resource import davPrivilegeSet
from twisted.web2.dav.util import parentForURL, bindMethods
from twistedcaldav import caldavxml
from twistedcaldav import customxml
from twistedcaldav.caldavxml import caldav_namespace
from twistedcaldav.config import config
from twistedcaldav.extensions import DAVFile
from twistedcaldav.ical import Component as iComponent
from twistedcaldav.ical import Property as iProperty
from twistedcaldav.index import Index, IndexSchedule
from twistedcaldav.notifications import NotificationsCollectionResource, NotificationResource
from twistedcaldav.resource import CalDAVResource, isCalendarCollectionResource, isPseudoCalendarCollectionResource
from twistedcaldav.schedule import ScheduleInboxResource, ScheduleOutboxResource
from twistedcaldav.dropbox import DropBoxHomeResource, DropBoxCollectionResource, DropBoxChildResource
from twistedcaldav.directory.calendar import uidsResourceName
from twistedcaldav.directory.calendar import DirectoryCalendarHomeProvisioningResource
from twistedcaldav.directory.calendar import DirectoryCalendarHomeTypeProvisioningResource
from twistedcaldav.directory.calendar import DirectoryCalendarHomeUIDProvisioningResource
from twistedcaldav.directory.calendar import DirectoryCalendarHomeResource
from twistedcaldav.directory.resource import AutoProvisioningResourceMixIn
class CalDAVFile (CalDAVResource, DAVFile):
"""
CalDAV-accessible L{DAVFile} resource.
"""
def __repr__(self):
if self.isCalendarCollection():
return "<%s (calendar collection): %s>" % (self.__class__.__name__, self.fp.path)
else:
return super(CalDAVFile, self).__repr__()
##
# CalDAV
##
def resourceType(self):
if self.isCalendarCollection():
return davxml.ResourceType.calendar
else:
return super(CalDAVFile, self).resourceType()
def createCalendar(self, request):
#
# request object is required because we need to validate against parent
# resources, and we need the request in order to locate the parents.
#
if self.fp.exists():
log.err("Attempt to create collection where file exists: %s" % (self.fp.path,))
raise HTTPError(StatusResponse(responsecode.NOT_ALLOWED, "File exists"))
if not os.path.isdir(os.path.dirname(self.fp.path)):
log.err("Attempt to create collection with no parent: %s" % (self.fp.path,))
raise HTTPError(StatusResponse(responsecode.CONFLICT, "No parent collection"))
#
# Verify that no parent collection is a calendar also
#
log.msg("Creating calendar collection %s" % (self,))
def _defer(parent):
if parent is not None:
log.err("Cannot create a calendar collection within a calendar collection %s" % (parent,))
raise HTTPError(ErrorResponse(
responsecode.FORBIDDEN,
(caldavxml.caldav_namespace, "calendar-collection-location-ok")
))
return self.createCalendarCollection()
parent = self._checkParents(request, isPseudoCalendarCollectionResource)
parent.addCallback(_defer)
return parent
def createCalendarCollection(self):
#
# Create the collection once we know it is safe to do so
#
def onCalendarCollection(status):
if status != responsecode.CREATED:
raise HTTPError(status)
# Initialize CTag on the calendar collection
self.updateCTag()
# Create the index so its ready when the first PUTs come in
self.index().create()
return status
d = self.createSpecialCollection(davxml.ResourceType.calendar)
d.addCallback(onCalendarCollection)
return d
def createSpecialCollection(self, resourceType=None):
#
# Create the collection once we know it is safe to do so
#
def onCollection(status):
if status != responsecode.CREATED:
raise HTTPError(status)
self.writeDeadProperty(resourceType)
return status
def onError(f):
try:
rmdir(self.fp)
except Exception, e:
log.err("Unable to clean up after failed MKCOL (special resource type: %s): %s" % (e, resourceType,))
return f
d = mkcollection(self.fp)
if resourceType is not None:
d.addCallback(onCollection)
d.addErrback(onError)
return d
def iCalendarRolledup(self, request):
if self.isPseudoCalendarCollection():
# Generate a monolithic calendar
calendar = iComponent("VCALENDAR")
calendar.addProperty(iProperty("VERSION", "2.0"))
# Do some optimisation of access control calculation by determining any inherited ACLs outside of
# the child resource loop and supply those to the checkPrivileges on each child.
filteredaces = waitForDeferred(self.inheritedACEsforChildren(request))
yield filteredaces
filteredaces = filteredaces.getResult()
# Must verify ACLs which means we need a request object at this point
for name, uid, type in self.index().search(None): #@UnusedVariable
try:
child = waitForDeferred(request.locateChildResource(self, name))
yield child
child = child.getResult()
child = IDAVResource(child)
except TypeError:
child = None
if child is not None:
# Check privileges of child - skip if access denied
try:
d = waitForDeferred(child.checkPrivileges(request, (davxml.Read(),), inherited_aces=filteredaces))
yield d
d.getResult()
except AccessDeniedError:
continue
subcalendar = self.iCalendar(name)
assert subcalendar.name() == "VCALENDAR"
for component in subcalendar.subcomponents():
calendar.addComponent(component)
yield calendar
return
yield fail(HTTPError((ErrorResponse(responsecode.BAD_REQUEST))))
iCalendarRolledup = deferredGenerator(iCalendarRolledup)
def iCalendarText(self, name=None):
if self.isPseudoCalendarCollection():
if name is None:
return str(self.iCalendar())
try:
calendar_file = self.fp.child(name).open()
except IOError, e:
if e[0] == errno.ENOENT: return None
raise
elif self.isCollection():
return None
else:
if name is not None:
raise AssertionError("name must be None for non-collection calendar resource")
calendar_file = self.fp.open()
# FIXME: This is blocking I/O
try:
calendar_data = calendar_file.read()
finally:
calendar_file.close()
return calendar_data
def iCalendarXML(self, name=None):
return caldavxml.CalendarData.fromCalendarData(self.iCalendarText(name))
def supportedPrivileges(self, request):
# read-free-busy support on calendar collection and calendar object resources
if self.isCollection():
return succeed(calendarPrivilegeSet)
else:
def gotParent(parent):
if parent and isCalendarCollectionResource(parent):
return succeed(calendarPrivilegeSet)
else:
return super(CalDAVFile, self).supportedPrivileges(request)
d = self.locateParent(request, request.urlForResource(self))
d.addCallback(gotParent)
return d
return super(CalDAVFile, self).supportedPrivileges(request)
##
# Public additions
##
def index(self):
"""
Obtains the index for a calendar collection resource.
@return: the index object for this resource.
@raise AssertionError: if this resource is not a calendar collection
resource.
"""
return Index(self)
##
# File
##
def listChildren(self):
return [
child for child in super(CalDAVFile, self).listChildren()
if not child.startswith(".")
]
def updateCTag(self):
assert self.isCollection()
self.writeDeadProperty(customxml.GETCTag(str(datetime.datetime.now())))
##
# Quota
##
def quotaSize(self, request):
"""
Get the size of this resource.
TODO: Take into account size of dead-properties. Does stat
include xattrs size?
@return: an L{Deferred} with a C{int} result containing the size of the resource.
"""
if self.isCollection():
def walktree(top):
"""
Recursively descend the directory tree rooted at top,
calling the callback function for each regular file
@param top: L{FilePath} for the directory to walk.
"""
total = 0
for f in top.listdir():
# Ignore the database
if f.startswith("."):
continue
child = top.child(f)
if child.isdir():
# It's a directory, recurse into it
result = waitForDeferred(walktree(child))
yield result
total += result.getResult()
elif child.isfile():
# It's a file, call the callback function
total += child.getsize()
else:
# Unknown file type, print a message
pass
yield total
walktree = deferredGenerator(walktree)
return walktree(self.fp)
else:
return succeed(self.fp.getsize())
##
# Utilities
##
@staticmethod
def _isChildURI(request, uri, immediateChild=True):
"""
Verify that the supplied URI represents a resource that is a child
of the request resource.
@param request: the request currently in progress
@param uri: the URI to test
@return: True if the supplied URI is a child resource
False if not
"""
if uri is None: return False
#
# Parse the URI
#
(scheme, host, path, query, fragment) = urlsplit(uri) #@UnusedVariable
# Request hostname and child uri hostname have to be the same.
if host and host != request.headers.getHeader("host"):
return False
# Child URI must start with request uri text.
parent = request.uri
if not parent.endswith("/"):
parent += "/"
return path.startswith(parent) and (len(path) > len(parent)) and (not immediateChild or (path.find("/", len(parent)) == -1))
def _checkParents(self, request, test):
"""
@param request: the request being processed.
@param test: a callable
@return: the closest parent for this resource using the request URI from
the given request for which C{test(parent)} evaluates to a true
value, or C{None} if no parent matches.
"""
parent = self
parent_uri = request.uri
while True:
parent_uri = parentForURL(parent_uri)
if not parent_uri: break
parent = waitForDeferred(request.locateResource(parent_uri))
yield parent
parent = parent.getResult()
if test(parent):
yield parent
return
yield None
_checkParents = deferredGenerator(_checkParents)
class AutoProvisioningFileMixIn (AutoProvisioningResourceMixIn):
def provision(self):
self.provisionFile()
return super(AutoProvisioningFileMixIn, self).provision()
def provisionFile(self):
fp = self.fp
fp.restat(False)
if fp.exists():
return False
log.msg("Provisioning file: %s" % (self,))
if hasattr(self, "parent"):
parent = self.parent
if not parent.exists() and isinstance(parent, AutoProvisioningFileMixIn):
parent.provision()
assert parent.exists(), "Parent %s of %s does not exist" % (parent, self)
assert parent.isCollection(), "Parent %s of %s is not a collection" % (parent, self)
if self.isCollection():
try:
fp.makedirs()
except OSError:
# It's possible someone else created the directory in the meantime...
# Check our status again, and re-raise if we're not a collection.
if not self.isCollection():
raise
fp.restat(False)
else:
fp.open("w").close()
fp.restat(False)
return True
class CalendarHomeProvisioningFile (AutoProvisioningFileMixIn, DirectoryCalendarHomeProvisioningResource, DAVFile):
"""
Resource which provisions calendar home collections as needed.
"""
def __init__(self, path, directory, url):
"""
@param path: the path to the file which will back the resource.
@param directory: an L{IDirectoryService} to provision calendars from.
@param url: the canonical URL for the resource.
"""
DAVFile.__init__(self, path)
DirectoryCalendarHomeProvisioningResource.__init__(self, directory, url)
def provisionChild(self, name):
if name == uidsResourceName:
return CalendarHomeUIDProvisioningFile(self.fp.child(name).path, self)
return CalendarHomeTypeProvisioningFile(self.fp.child(name).path, self, name)
def createSimilarFile(self, path):
raise HTTPError(responsecode.NOT_FOUND)
class CalendarHomeTypeProvisioningFile (AutoProvisioningFileMixIn, DirectoryCalendarHomeTypeProvisioningResource, DAVFile):
def __init__(self, path, parent, recordType):
"""
@param path: the path to the file which will back the resource.
@param parent: the parent of this resource
@param recordType: the directory record type to provision.
"""
DAVFile.__init__(self, path)
DirectoryCalendarHomeTypeProvisioningResource.__init__(self, parent, recordType)
class CalendarHomeUIDProvisioningFile (AutoProvisioningFileMixIn, DirectoryCalendarHomeUIDProvisioningResource, DAVFile):
def __init__(self, path, parent):
"""
@param path: the path to the file which will back the resource.
"""
DAVFile.__init__(self, path)
DirectoryCalendarHomeUIDProvisioningResource.__init__(self, parent)
def provisionChild(self, name):
record = self.directory.recordWithGUID(name)
if record is None:
log.msg("No directory record with GUID %r" % (name,))
return None
if not record.enabledForCalendaring:
log.msg("Directory record %r is not enabled for calendaring" % (record,))
return None
childPath = self.fp.child(name)
child = CalendarHomeFile(childPath.path, self, record)
if not child.exists():
self.provision()
oldPath = self.parent.getChild(record.recordType).fp.child(record.shortName)
if oldPath.exists():
#
# The child exists at the old (pre-1.2) location (ie. in the types
# hierarchy instead of the GUID hierarchy). Move to new location.
#
log.msg("Moving calendar home from old location %r to new location %r." % (oldPath, childPath))
try:
oldPath.moveTo(childPath)
except (OSError, IOError), e:
log.err("Error moving calendar home %r: %s" % (oldPath, e))
raise HTTPError(StatusResponse(
responsecode.INTERNAL_SERVER_ERROR,
"Unable to move calendar home."
))
else:
#
# NOTE: provisionDefaultCalendars() returns a deferred, which we are ignoring.
# The result being that the default calendars will be present at some point
# in the future, not necessarily right now, and we don't have a way to wait
# on that to finish.
#
child.provisionDefaultCalendars()
return child
def createSimilarFile(self, path):
raise HTTPError(responsecode.NOT_FOUND)
class CalendarHomeFile (AutoProvisioningFileMixIn, DirectoryCalendarHomeResource, CalDAVFile):
"""
Calendar home collection resource.
"""
def __init__(self, path, parent, record):
"""
@param path: the path to the file which will back the resource.
"""
CalDAVFile.__init__(self, path)
DirectoryCalendarHomeResource.__init__(self, parent, record)
def provisionChild(self, name):
if config.EnableDropBox:
DropBoxHomeFileClass = DropBoxHomeFile
else:
DropBoxHomeFileClass = None
if config.EnableNotifications:
NotificationsCollectionFileClass = NotificationsCollectionFile
else:
NotificationsCollectionFileClass = None
cls = {
"inbox" : ScheduleInboxFile,
"outbox" : ScheduleOutboxFile,
"dropbox" : DropBoxHomeFileClass,
"notifications": NotificationsCollectionFileClass,
}.get(name, None)
if cls is not None:
return cls(self.fp.child(name).path, self)
return self.createSimilarFile(self.fp.child(name).path)
def createSimilarFile(self, path):
if path == self.fp.path:
return self
else:
return CalDAVFile(path, principalCollections=self.principalCollections())
def getChild(self, name):
# This avoids finding case variants of put children on case-insensitive filesystems.
if name not in self.putChildren and name.lower() in (x.lower() for x in self.putChildren):
return None
return super(CalendarHomeFile, self).getChild(name)
class ScheduleFile (AutoProvisioningFileMixIn, CalDAVFile):
def __init__(self, path, parent):
super(ScheduleFile, self).__init__(path, principalCollections=parent.principalCollections())
def isCollection(self):
return True
def createSimilarFile(self, path):
if path == self.fp.path:
return self
else:
return CalDAVFile(path, principalCollections=self.principalCollections())
def index(self):
"""
Obtains the index for an schedule collection resource.
@return: the index object for this resource.
@raise AssertionError: if this resource is not a calendar collection
resource.
"""
return IndexSchedule(self)
def http_COPY (self, request): return responsecode.FORBIDDEN
def http_MOVE (self, request): return responsecode.FORBIDDEN
def http_DELETE (self, request): return responsecode.FORBIDDEN
def http_MKCOL (self, request): return responsecode.FORBIDDEN
def http_MKCALENDAR(self, request):
return ErrorResponse(
responsecode.FORBIDDEN,
(caldav_namespace, "calendar-collection-location-ok")
)
##
# ACL
##
def supportedPrivileges(self, request):
return succeed(schedulePrivilegeSet)
class ScheduleInboxFile (ScheduleInboxResource, ScheduleFile):
"""
Calendar scheduling inbox collection resource.
"""
def __init__(self, path, parent):
ScheduleFile.__init__(self, path, parent)
ScheduleInboxResource.__init__(self, parent)
def provision(self):
if self.provisionFile():
# Initialize CTag on the calendar collection
self.updateCTag()
return super(ScheduleInboxFile, self).provision()
def __repr__(self):
return "<%s (calendar inbox collection): %s>" % (self.__class__.__name__, self.fp.path)
class ScheduleOutboxFile (ScheduleOutboxResource, ScheduleFile):
"""
Calendar scheduling outbox collection resource.
"""
def __init__(self, path, parent):
ScheduleFile.__init__(self, path, parent)
ScheduleOutboxResource.__init__(self, parent)
def provision(self):
if self.provisionFile():
# Initialize CTag on the calendar collection
self.updateCTag()
return super(ScheduleOutboxFile, self).provision()
def __repr__(self):
return "<%s (calendar outbox collection): %s>" % (self.__class__.__name__, self.fp.path)
class DropBoxHomeFile (AutoProvisioningFileMixIn, DropBoxHomeResource, CalDAVFile):
def __init__(self, path, parent):
DropBoxHomeResource.__init__(self)
CalDAVFile.__init__(self, path, principalCollections=parent.principalCollections())
self.parent = parent
def createSimilarFile(self, path):
if path == self.fp.path:
return self
else:
return DropBoxCollectionFile(path, self)
def __repr__(self):
return "<%s (dropbox home collection): %s>" % (self.__class__.__name__, self.fp.path)
class DropBoxCollectionFile (DropBoxCollectionResource, CalDAVFile):
def __init__(self, path, parent):
DropBoxCollectionResource.__init__(self)
CalDAVFile.__init__(self, path, principalCollections=parent.principalCollections())
def createSimilarFile(self, path):
if path == self.fp.path:
return self
else:
return DropBoxChildFile(path, self)
def __repr__(self):
return "<%s (dropbox collection): %s>" % (self.__class__.__name__, self.fp.path)
http_DELETE = DropBoxCollectionResource.http_DELETE
http_PUT = DropBoxCollectionResource.http_PUT
http_MKCALENDAR = DropBoxCollectionResource.http_MKCALENDAR
http_POST = DropBoxCollectionResource.http_POST
class DropBoxChildFile (DropBoxChildResource, CalDAVFile):
def __init__(self, path, parent):
DropBoxChildResource.__init__(self)
CalDAVFile.__init__(self, path, principalCollections=parent.principalCollections())
assert self.fp.isfile() or not self.fp.exists()
def createSimilarFile(self, path):
if path == self.fp.path:
return self
else:
return responsecode.NOT_FOUND
http_MKCOL = DropBoxChildResource.http_MKCOL
http_MKCALENDAR = DropBoxChildResource.http_MKCALENDAR
http_PUT = DropBoxChildResource.http_PUT
class NotificationsCollectionFile (AutoProvisioningFileMixIn, NotificationsCollectionResource, CalDAVFile):
def __init__(self, path, parent):
NotificationsCollectionResource.__init__(self)
CalDAVFile.__init__(self, path, principalCollections=parent.principalCollections())
self._parent = parent
def createSimilarFile(self, path):
if path == self.fp.path:
return self
else:
return NotificationFile(path, self)
def __repr__(self):
return "<%s (notifications collection): %s>" % (self.__class__.__name__, self.fp.path)
http_PUT = NotificationsCollectionResource.http_PUT
http_MKCOL = NotificationsCollectionResource.http_MKCOL
http_MKCALENDAR = NotificationsCollectionResource.http_MKCALENDAR
class NotificationFile (NotificationResource, DAVFile):
def __init__(self, path, parent):
super(NotificationFile, self).__init__(path, principalCollections=parent.principalCollections())
def create(self, request, timestamp, parentURL):
"""
Create the resource, fill out the body, and add properties.
"""
# Create body XML
elements = []
elements.append(customxml.TimeStamp.fromString(timestamp))
elements.append(customxml.Changed(davxml.HRef.fromString(parentURL)))
xml = customxml.Notification(*elements)
d = waitForDeferred(put_common_base.storeResource(request, data=xml.toxml(), destination=self, destination_uri=request.urlForResource(self)))
yield d
d.getResult()
# Write properties
for element in elements:
self.writeDeadProperty(element)
create = deferredGenerator(create)
##
# Utilities
##
def locateExistingChild(resource, request, segments):
"""
This C{locateChild()} implementation fails to find children if C{getChild()}
doesn't return one.
"""
# If getChild() finds a child resource, return it
child = resource.getChild(segments[0])
if child is not None:
return (child, segments[1:])
# Otherwise, there is no child
return (None, ())
def _schedulePrivilegeSet():
edited = False
top_supported_privileges = []
for supported_privilege in davPrivilegeSet.childrenOfType(davxml.SupportedPrivilege):
all_privilege = supported_privilege.childOfType(davxml.Privilege)
if isinstance(all_privilege.children[0], davxml.All):
all_description = supported_privilege.childOfType(davxml.Description)
all_supported_privileges = list(supported_privilege.childrenOfType(davxml.SupportedPrivilege))
all_supported_privileges.append(
davxml.SupportedPrivilege(
davxml.Privilege(caldavxml.Schedule()),
davxml.Description("schedule privileges for current principal", **{"xml:lang": "en"}),
),
)
top_supported_privileges.append(
davxml.SupportedPrivilege(all_privilege, all_description, *all_supported_privileges)
)
edited = True
else:
top_supported_privileges.append(supported_privilege)
assert edited, "Structure of davPrivilegeSet changed in a way that I don't know how to extend for schedulePrivilegeSet"
return davxml.SupportedPrivilegeSet(*top_supported_privileges)
schedulePrivilegeSet = _schedulePrivilegeSet()
def _calendarPrivilegeSet ():
edited = False
top_supported_privileges = []
for supported_privilege in davPrivilegeSet.childrenOfType(davxml.SupportedPrivilege):
all_privilege = supported_privilege.childOfType(davxml.Privilege)
if isinstance(all_privilege.children[0], davxml.All):
all_description = supported_privilege.childOfType(davxml.Description)
all_supported_privileges = []
for all_supported_privilege in supported_privilege.childrenOfType(davxml.SupportedPrivilege):
read_privilege = all_supported_privilege.childOfType(davxml.Privilege)
if isinstance(read_privilege.children[0], davxml.Read):
read_description = all_supported_privilege.childOfType(davxml.Description)
read_supported_privileges = list(all_supported_privilege.childrenOfType(davxml.SupportedPrivilege))
read_supported_privileges.append(
davxml.SupportedPrivilege(
davxml.Privilege(caldavxml.ReadFreeBusy()),
davxml.Description("allow free busy report query", **{"xml:lang": "en"}),
),
)
all_supported_privileges.append(
davxml.SupportedPrivilege(read_privilege, read_description, *read_supported_privileges)
)
edited = True
else:
all_supported_privileges.append(all_supported_privilege)
top_supported_privileges.append(
davxml.SupportedPrivilege(all_privilege, all_description, *all_supported_privileges)
)
else:
top_supported_privileges.append(supported_privilege)
assert edited, "Structure of davPrivilegeSet changed in a way that I don't know how to extend for calendarPrivilegeSet"
return davxml.SupportedPrivilegeSet(*top_supported_privileges)
calendarPrivilegeSet = _calendarPrivilegeSet()
##
# Attach methods
##
import twistedcaldav.method
bindMethods(twistedcaldav.method, CalDAVFile)
# FIXME: Little bit of a circular dependency here...
twistedcaldav.method.copymove.CalDAVFile = CalDAVFile
twistedcaldav.method.delete.CalDAVFile = CalDAVFile
twistedcaldav.method.get.CalDAVFile = CalDAVFile
twistedcaldav.method.mkcol.CalDAVFile = CalDAVFile
twistedcaldav.method.put.CalDAVFile = CalDAVFile