[CalendarServer-changes] [11960] CalendarServer/branches/users/cdaboo/sharing-in-the-store
source_changes at macosforge.org
source_changes at macosforge.org
Wed Mar 12 11:18:22 PDT 2014
Revision: 11960
http://trac.calendarserver.org//changeset/11960
Author: cdaboo at apple.com
Date: 2013-11-18 07:30:49 -0800 (Mon, 18 Nov 2013)
Log Message:
-----------
Checkpoint changes: move sharing invitations into the store. Major api changes and clean-up done. Still need to rework address books/group
sharing some more to simplify that api.
Modified Paths:
--------------
CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/resource.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/base/datastore/util.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/sql.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/common.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_tables.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/test/util.py
Added Paths:
-----------
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py
CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/resource.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/resource.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/resource.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -691,7 +691,7 @@
elif qname == customxml.SharedURL.qname():
if self.isShareeResource():
- returnValue(customxml.SharedURL(element.HRef.fromString(self._share.url())))
+ returnValue(customxml.SharedURL(element.HRef.fromString(self._share_url)))
else:
returnValue(None)
@@ -860,7 +860,7 @@
"""
if self.isShareeResource():
- parent = (yield self.locateParent(request, self._share.url()))
+ parent = (yield self.locateParent(request, self._share_url))
else:
parent = (yield self.locateParent(request, request.urlForResource(self)))
if parent and isinstance(parent, CalDAVResource):
@@ -876,7 +876,7 @@
Return the DAV:owner property value (MUST be a DAV:href or None).
"""
if self.isShareeResource():
- parent = (yield self.locateParent(request, self._share.url()))
+ parent = (yield self.locateParent(request, self._share_url))
else:
parent = (yield self.locateParent(request, request.urlForResource(self)))
if parent and isinstance(parent, CalDAVResource):
@@ -1251,13 +1251,13 @@
sharedParent = None
if self.isShareeResource():
# A sharee collection's quota root is the resource owner's root
- sharedParent = (yield request.locateResource(parentForURL(self._share.url())))
+ sharedParent = (yield request.locateResource(parentForURL(self._share_url)))
else:
parent = (yield self.locateParent(request, request.urlForResource(self)))
if isCalendarCollectionResource(parent) or isAddressBookCollectionResource(parent):
if parent.isShareeResource():
# A sharee collection's quota root is the resource owner's root
- sharedParent = (yield request.locateResource(parentForURL(parent._share.url())))
+ sharedParent = (yield request.locateResource(parentForURL(parent._share_url)))
if sharedParent:
result = (yield sharedParent.quotaRootResource(request))
@@ -2542,6 +2542,11 @@
return config.Sharing.Enabled and config.Sharing.Calendars.Enabled and self.exists()
+ def _otherPrincipalHomeURL(self, otherUID):
+ ownerPrincipal = self.principalForUID(otherUID)
+ return ownerPrincipal.calendarHomeURLs()[0]
+
+
@inlineCallbacks
def makeRegularChild(self, name):
newCalendar = yield self._newStoreHome.calendarWithName(name)
@@ -2794,6 +2799,11 @@
return config.Sharing.Enabled and config.Sharing.AddressBooks.Enabled and self.exists()
+ def _otherPrincipalHomeURL(self, otherUID):
+ ownerPrincipal = self.principalForUID(otherUID)
+ return ownerPrincipal.addressBookHomeURLs()[0]
+
+
@inlineCallbacks
def makeRegularChild(self, name):
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -22,6 +22,7 @@
__all__ = [
"SharedResourceMixin",
+ "SharedHomeMixin",
]
from twext.web2 import responsecode
@@ -30,11 +31,10 @@
from twext.web2.dav.resource import TwistedACLInheritable
from twext.web2.dav.util import allDataFromStream, joinURL
-from txdav.common.datastore.sql import SharingInvitation
from txdav.common.datastore.sql_tables import _BIND_MODE_OWN, \
_BIND_MODE_READ, _BIND_MODE_WRITE, _BIND_STATUS_INVITED, \
- _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, \
- _BIND_STATUS_INVALID, _ABO_KIND_GROUP
+ _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, \
+ _BIND_STATUS_INVALID, _ABO_KIND_GROUP, _BIND_STATUS_DELETED
from txdav.xml import element
from twisted.internet.defer import succeed, inlineCallbacks, DeferredList, \
@@ -46,26 +46,11 @@
from twistedcaldav.directory.wiki import WikiDirectoryService, getWikiAccess
from twistedcaldav.linkresource import LinkFollowerMixIn
-from pycalendar.datetime import DateTime
-
-# FIXME: Get rid of these imports
-from twistedcaldav.directory.util import TRANSACTION_KEY
-# circular import
-# from txdav.common.datastore.sql import ECALENDARTYPE, EADDRESSBOOKTYPE
-ECALENDARTYPE = 0
-EADDRESSBOOKTYPE = 1
-# ENOTIFICATIONTYPE = 2
-
-
class SharedResourceMixin(object):
"""
A mix-in for calendar/addressbook resources that implements sharing-related
functionality.
-
- @ivar _share: If this L{SharedResourceMixin} is the sharee's version of a
- resource, this refers to the L{Share} that describes it.
- @type _share: L{Share} or L{NoneType}
"""
@inlineCallbacks
@@ -78,15 +63,15 @@
def invitePropertyElement(invitation, includeUID=True):
- userid = "urn:uuid:" + invitation.shareeUID()
- principal = self.principalForUID(invitation.shareeUID())
- cn = principal.displayName() if principal else invitation.shareeUID()
+ userid = "urn:uuid:" + invitation.shareeUID
+ principal = self.principalForUID(invitation.shareeUID)
+ cn = principal.displayName() if principal else invitation.shareeUID
return customxml.InviteUser(
- customxml.UID.fromString(invitation.uid()) if includeUID else None,
+ customxml.UID.fromString(invitation.uid) if includeUID else None,
element.HRef.fromString(userid),
customxml.CommonName.fromString(cn),
- customxml.InviteAccess(invitationBindModeToXMLMap[invitation.mode()]()),
- invitationBindStatusToXMLMap[invitation.status()](),
+ customxml.InviteAccess(invitationBindModeToXMLMap[invitation.mode]()),
+ invitationBindStatusToXMLMap[invitation.status](),
)
# See if this property is on the shared calendar
@@ -98,11 +83,12 @@
# See if it is on the sharee calendar
if self.isShareeResource():
- original = (yield request.locateResource(self._share.url()))
+ original = yield self._newStoreObject.ownerView()
if original is not None:
- invitations = yield original.validateInvites(request)
+ invitations = yield original.allInvitations()
+ invitations = yield self.validateInvites(request, invitations)
- ownerPrincipal = (yield original.ownerPrincipal(request))
+ ownerPrincipal = self.principalForUID(self._newStoreObject.ownerHome().uid())
# FIXME: use urn:uuid in all cases
if self.isCalendarCollection():
owner = ownerPrincipal.principalURL()
@@ -138,35 +124,13 @@
yield self._newStoreObject.setShared(False)
# Remove all invitees
- for invitation in (yield self._allInvitations()):
- yield self.uninviteFromShare(invitation, request)
+ for invitation in (yield self._newStoreObject.allInvitations()):
+ yield self._newStoreObject.uninviteUserFromShare(invitation.shareeUID)
returnValue(True)
@inlineCallbacks
- def changeUserInviteState(self, request, inviteUID, shareeUID, state, summary=None):
- if not self.isShared():
- raise HTTPError(ErrorResponse(
- responsecode.FORBIDDEN,
- (customxml.calendarserver_namespace, "valid-request"),
- "Invalid share",
- ))
-
- invitation = yield self._invitationForUID(inviteUID)
- if invitation is None or invitation.shareeUID() != shareeUID:
- raise HTTPError(ErrorResponse(
- responsecode.FORBIDDEN,
- (customxml.calendarserver_namespace, "valid-request"),
- "Invalid invitation uid: %s" % (inviteUID,),
- ))
-
- # Only certain states are owner controlled
- if invitation.status() in (_BIND_STATUS_INVITED, _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED,):
- yield self._updateInvitation(invitation, status=state, summary=summary)
-
-
- @inlineCallbacks
def directShare(self, request):
"""
Directly bind an accessible calendar/address book collection into the
@@ -233,11 +197,16 @@
))
# Accept it
- directUID = Share.directUID(shareeHomeResource._newStoreHome, self._newStoreObject)
- response = (yield shareeHomeResource.acceptDirectShare(request, hostURL, directUID, self.displayName()))
+ shareeView = yield self._newStoreObject.directShareWithUser(sharee.principalUID())
# Return the URL of the shared calendar
- returnValue(response)
+ sharedAsURL = joinURL(shareeHomeResource.url(), shareeView.name())
+ returnValue(XMLResponse(
+ code=responsecode.OK,
+ element=customxml.SharedAs(
+ element.HRef.fromString(sharedAsURL)
+ )
+ ))
def isShared(self):
@@ -250,54 +219,33 @@
return False
- def setShare(self, share):
+ def setShare(self, share_url):
"""
- Set the L{Share} associated with this L{SharedResourceMixin}. (This
+ Set the URL associated with this L{SharedResourceMixin}. (This
is only invoked on the sharee's resource, not the owner's.)
"""
self._isShareeResource = True
- self._share = share
+ self._share_url = share_url
def isShareeResource(self):
"""
- Return True if this is a sharee view of a shared calendar collection.
+ Return True if this is a sharee view of a shared collection.
"""
- return hasattr(self, "_isShareeResource")
+ return (
+ hasattr(self, "_newStoreObject") and
+ hasattr(self._newStoreObject, "owned") and
+ not self._newStoreObject.owned()
+ )
- @inlineCallbacks
def removeShareeResource(self, request):
"""
Called when the sharee DELETEs a shared collection.
"""
+ return self._newStoreObject.deleteShare()
- sharee = self.principalForUID(self._share.shareeUID())
- # Remove from sharee's calendar/address book home
- if self.isCalendarCollection():
- shareeHome = yield sharee.calendarHome(request)
- elif self.isAddressBookCollection() or self.isGroup():
- shareeHome = yield sharee.addressBookHome(request)
- returnValue((yield shareeHome.removeShare(request, self._share)))
-
-
- def sharedResourceType(self):
- """
- Return the DAV:resourcetype stripped of any shared elements.
- """
-
- if self.isCalendarCollection():
- return "calendar"
- elif self.isAddressBookCollection():
- return "addressbook"
- elif self.isGroup():
- # TODO: Add group xml resource type ?
- return "group"
- else:
- return ""
-
-
@inlineCallbacks
def _checkAccessControl(self):
"""
@@ -315,13 +263,12 @@
access control mechanism has dictate the home should no longer have
any access at all.
"""
- if self._share.direct():
- ownerUID = self._share.ownerUID()
- owner = self.principalForUID(ownerUID)
+ if self._newStoreObject.direct():
+ owner = self.principalForUID(self._newStoreObject.ownerHome().uid())
if owner.record.recordType == WikiDirectoryService.recordType_wikis:
# Access level comes from what the wiki has granted to the
# sharee
- sharee = self.principalForUID(self._share.shareeUID())
+ sharee = self.principalForUID(self._newStoreObject.viewerHome().uid())
userID = sharee.record.guid
wikiID = owner.record.shortNames[0]
access = (yield getWikiAccess(userID, wikiID))
@@ -366,13 +313,12 @@
assert self._isShareeResource, "Only call this for a sharee resource"
assert self.isCalendarCollection() or self.isAddressBookCollection(), "Only call this for a address book or calendar resource"
- sharee = self.principalForUID(self._share.shareeUID())
+ sharee = self.principalForUID(self._newStoreObject.viewerHome().uid())
access = yield self._checkAccessControl()
if access == "original":
- original = (yield request.locateResource(self._share.url()))
- result = (yield original.accessControlList(request, *args,
- **kwargs))
+ original = (yield request.locateResource(self._share_url))
+ result = (yield original.accessControlList(request, *args, **kwargs))
returnValue(result)
# Direct shares use underlying privileges of shared collection
@@ -476,18 +422,17 @@
@inlineCallbacks
- def validateInvites(self, request):
+ def validateInvites(self, request, invitations=None):
"""
Make sure each userid in an invite is valid - if not re-write status.
"""
# assert request
- invitations = yield self._allInvitations()
+ if invitations is None:
+ invitations = yield self._newStoreObject.allInvitations()
for invitation in invitations:
- if invitation.status() != _BIND_STATUS_INVALID:
- if not (yield self.validUserIDForShare("urn:uuid:" + invitation.shareeUID(), request)):
- # FIXME: temporarily disable this to deal with flaky directory
- #yield self._updateInvitation(invitation, status=_BIND_STATUS_INVALID)
- self.log.error("Invalid sharee detected: {uid}", uid=invitation.shareeUID())
+ if invitation.status != _BIND_STATUS_INVALID:
+ if not (yield self.validUserIDForShare("urn:uuid:" + invitation.shareeUID, request)):
+ self.log.error("Invalid sharee detected: {uid}", uid=invitation.shareeUID)
returnValue(invitations)
@@ -549,78 +494,6 @@
@inlineCallbacks
- def _createInvitation(self, shareeUID, mode, summary,):
- """
- Create a new homeChild and wrap it in an Invitation
- """
- if self.isCalendarCollection():
- shareeHome = yield self._newStoreObject._txn.calendarHomeWithUID(shareeUID, create=True)
- elif self.isAddressBookCollection() or self.isGroup():
- shareeHome = yield self._newStoreObject._txn.addressbookHomeWithUID(shareeUID, create=True)
-
- shareUID = yield self._newStoreObject.shareWith(shareeHome,
- mode=mode,
- status=_BIND_STATUS_INVITED,
- message=summary)
- shareeStoreObject = yield shareeHome.invitedObjectWithShareUID(shareUID)
- invitation = SharingInvitation.fromCommonHomeChild(shareeStoreObject)
- returnValue(invitation)
-
-
- @inlineCallbacks
- def _updateInvitation(self, invitation, mode=None, status=None, summary=None):
- yield self._newStoreObject.updateShareFromSharingInvitation(invitation, mode=mode, status=status, message=summary)
- if mode is not None:
- invitation.setMode(mode)
- if status is not None:
- invitation.setStatus(status)
- if summary is not None:
- invitation.setSummary(summary)
-
-
- @inlineCallbacks
- def _allInvitations(self):
- """
- Get list of all invitations (non-direct) to this object.
- """
- if not self.exists():
- returnValue([])
-
- invitations = yield self._newStoreObject.sharingInvites()
-
- # remove direct shares as those are not "real" invitations
- invitations = filter(lambda x: x.mode() != _BIND_MODE_DIRECT, invitations)
-
- invitations.sort(key=lambda invitation: invitation.shareeUID())
-
- returnValue(invitations)
-
-
- @inlineCallbacks
- def _invitationForShareeUID(self, shareeUID):
- """
- Get an invitation for this sharee principal UID
- """
- invitations = yield self._allInvitations()
- for invitation in invitations:
- if invitation.shareeUID() == shareeUID:
- returnValue(invitation)
- returnValue(None)
-
-
- @inlineCallbacks
- def _invitationForUID(self, uid):
- """
- Get an invitation for an invitations uid
- """
- invitations = yield self._allInvitations()
- for invitation in invitations:
- if invitation.uid() == uid:
- returnValue(invitation)
- returnValue(None)
-
-
- @inlineCallbacks
def inviteSingleUserToShare(self, userid, cn, ace, summary, request): #@UnusedVariable
# We currently only handle local users
@@ -628,71 +501,32 @@
if not sharee:
returnValue(False)
- shareeUID = sharee.principalUID()
+ result = (yield self._newStoreObject.inviteUserToShare(
+ sharee.principalUID(),
+ invitationBindModeFromXMLMap[type(ace)],
+ summary,
+ ))
- # Look for existing invite and update its fields or create new one
- invitation = yield self._invitationForShareeUID(shareeUID)
- if invitation:
- status = _BIND_STATUS_INVITED if invitation.status() in (_BIND_STATUS_DECLINED, _BIND_STATUS_INVALID) else None
- yield self._updateInvitation(invitation, mode=invitationBindModeFromXMLMap[type(ace)], status=status, summary=summary)
- else:
- invitation = yield self._createInvitation(
- shareeUID=shareeUID,
- mode=invitationBindModeFromXMLMap[type(ace)],
- summary=summary)
- # Send invite notification
- yield self.sendInviteNotification(invitation, request)
+ returnValue(result)
- returnValue(True)
-
@inlineCallbacks
def uninviteSingleUserFromShare(self, userid, aces, request): #@UnusedVariable
- # Cancel invites - we'll just use whatever userid we are given
+ # Cancel invites - we'll just use whatever userid we are given
sharee = self.principalForCalendarUserAddress(userid)
if not sharee:
returnValue(False)
- shareeUID = sharee.principalUID()
+ result = (yield self._newStoreObject.uninviteUserFromShare(sharee.principalUID()))
- invitation = yield self._invitationForShareeUID(shareeUID)
- if invitation:
- result = (yield self.uninviteFromShare(invitation, request))
- else:
- result = False
-
returnValue(result)
@inlineCallbacks
def uninviteFromShare(self, invitation, request):
- # Remove any shared calendar or address book
- sharee = self.principalForUID(invitation.shareeUID())
- if sharee:
- previousInvitationStatus = invitation.status()
- displayName = None
- if self.isCalendarCollection():
- shareeHomeResource = yield sharee.calendarHome(request)
- if shareeHomeResource is not None:
- displayName = yield shareeHomeResource.removeShareByUID(request, invitation.uid())
- elif self.isAddressBookCollection() or self.isGroup():
- shareeHomeResource = yield sharee.addressBookHome(request)
- if shareeHomeResource is not None:
- yield shareeHomeResource.removeShareByUID(request, invitation.uid())
-
- # If current user state is accepted then we send an invite with the new state, otherwise
- # we cancel any existing invites for the user
- if shareeHomeResource is not None:
- if previousInvitationStatus != _BIND_STATUS_ACCEPTED:
- yield self.removeInviteNotification(invitation, request)
- else:
- yield self.sendInviteNotification(invitation, request, displayName=displayName, notificationState="DELETED")
-
- # Direct shares for with valid sharee principal will already be deleted
- yield self._newStoreObject.unshareWithUID(invitation.shareeUID())
-
+ yield self._newStoreObject.uninviteFromShare(invitation)
returnValue(True)
@@ -703,74 +537,6 @@
@inlineCallbacks
- def sendInviteNotification(self, invitation, request, notificationState=None, displayName=None):
-
- ownerPrincipal = (yield self.ownerPrincipal(request))
-
- # Locate notifications collection for user
- sharee = self.principalForUID(invitation.shareeUID())
- if sharee is None:
- raise ValueError("sharee is None but principalUID was valid before")
-
- hosturl = self._newStoreObject.name()
- if self.sharedResourceType() == "group":
- hosturl = self._newStoreObject.parentCollection().name() + "/" + hosturl
-
- # We need to look up the resource so that the response cache notifier is properly initialized
- notificationResource = (yield request.locateResource(sharee.notificationURL()))
- notifications = notificationResource._newStoreNotifications
-
- '''
- # Look for existing notification
- # oldnotification is not used don't query for it
- oldnotification = (yield notifications.notificationObjectWithUID(invitation.uid()))
- if oldnotification:
- # TODO: rollup changes?
- pass
- '''
-
- # Generate invite XML
- state = notificationState if notificationState else invitation.status()
- summary = invitation.summary() if displayName is None else displayName
-
- notificationtype = {
- "notification-type": "invite-notification",
- "shared-type": self.sharedResourceType(),
- }
- notificationdata = {
- "notification-type": "invite-notification",
- "shared-type": self.sharedResourceType(),
- "dtstamp": DateTime.getNowUTC().getText(),
- "owner": ownerPrincipal.principalUID(),
- "sharee": invitation.shareeUID(),
- "uid": invitation.uid(),
- "status": state,
- "access": invitation.mode(),
- "name": hosturl,
- "summary": summary,
- }
- if self.isCalendarCollection():
- notificationdata["supported-components"] = self._newStoreObject.getSupportedComponents()
-
- # Add to collections
- yield notifications.writeNotificationObject(invitation.uid(), notificationtype, notificationdata)
-
-
- @inlineCallbacks
- def removeInviteNotification(self, invitation, request):
-
- # Locate notifications collection for user
- sharee = self.principalForUID(invitation.shareeUID())
- if sharee is None:
- raise ValueError("sharee is None but principalUID was valid before")
- notificationResource = (yield request.locateResource(sharee.notificationURL()))
- notifications = notificationResource._newStoreNotifications
-
- # Add to collections
- yield notifications.removeNotificationObjectWithUID(invitation.uid())
-
-
- @inlineCallbacks
def _xmlHandleInvite(self, request, docroot):
yield self.authorize(request, (element.Read(), element.Write()))
result = (yield self._handleInvite(request, docroot))
@@ -988,7 +754,7 @@
_BIND_STATUS_ACCEPTED : customxml.InviteStatusAccepted,
_BIND_STATUS_DECLINED : customxml.InviteStatusDeclined,
_BIND_STATUS_INVALID : customxml.InviteStatusInvalid,
- "DELETED" : customxml.InviteStatusDeleted,
+ _BIND_STATUS_DELETED : customxml.InviteStatusDeleted,
}
invitationBindStatusFromXMLMap = dict((v, k) for k, v in invitationBindStatusToXMLMap.iteritems())
@@ -1015,219 +781,30 @@
@inlineCallbacks
def provisionShare(self, child, request=None):
"""
- If the given child resource (a L{SharedResourceMixin}) of this
- L{SharedHomeMixin} is a I{sharee}'s view of a shared calendar object,
- associate it with a L{Share}.
+ Set shared state and check access control.
"""
- share = yield self._shareForStoreObject(child._newStoreObject, request)
- if share:
- child.setShare(share)
+ if child._newStoreObject is not None and not child._newStoreObject.owned():
+ ownerHomeURL = self._otherPrincipalHomeURL(child._newStoreObject.ownerHome().uid())
+ ownerView = yield child._newStoreObject.ownerView()
+ child.setShare(joinURL(ownerHomeURL, ownerView.name()))
access = yield child._checkAccessControl()
if access is None:
returnValue(None)
returnValue(child)
- @inlineCallbacks
- def _shareForStoreObject(self, storeObject, request=None):
- """
- Determine the L{Share} associated with the given child.
+ def _otherPrincipalHomeURL(self, otherUID):
+ pass
- @param child: A calendar or addressbook data store object, a child of
- the resource represented by this L{SharedHomeMixin} instance, which
- may be shared.
- @type child: L{txdav.caldav.icalendarstore.ICalendar} or
- L{txdav.carddav.iaddressbookstore.IAddressBook}
- @return: a L{Share} if C{child} is not the owner's view of the share,
- or C{None}.
- @rtype: L{Share} or L{NoneType}
- """
- # Find a matching share
- # use "storeObject.shareUID is not None" to prevent partially shared address books form getting a share
- if storeObject is None or storeObject.owned():
- returnValue(None)
-
- # Get the shared object's URL - we may need to fake this if the sharer principal is missing or disabled
- url = None
- owner = self.principalForUID(storeObject.ownerHome().uid())
- from twistedcaldav.directory.principal import DirectoryCalendarPrincipalResource
- if isinstance(owner, DirectoryCalendarPrincipalResource):
-
- if not request:
- # FIXEME: Fake up a request that can be used to get the owner home resource
- class _FakeRequest(object):
- pass
- fakeRequest = _FakeRequest()
- setattr(fakeRequest, TRANSACTION_KEY, self._newStoreHome._txn)
- request = fakeRequest
-
- if self._newStoreHome._homeType == ECALENDARTYPE:
- ownerHomeCollection = yield owner.calendarHome(request)
- elif self._newStoreHome._homeType == EADDRESSBOOKTYPE:
- ownerHomeCollection = yield owner.addressBookHome(request)
-
- if ownerHomeCollection is not None:
- url = ownerHomeCollection.url()
-
- if url is None:
- url = "/calendars/__uids__/%s/" % (storeObject.ownerHome().uid(),)
-
- ownerHomeChild = yield storeObject.ownerHome().childWithID(storeObject._resourceID)
- if ownerHomeChild:
- assert ownerHomeChild != storeObject
- url = joinURL(url, ownerHomeChild.name())
- share = Share(shareeStoreObject=storeObject, ownerStoreObject=ownerHomeChild, url=url)
- else:
- for ownerHomeChild in (yield storeObject.ownerHome().children()):
- if ownerHomeChild.owned():
- sharedGroup = yield ownerHomeChild.objectResourceWithID(storeObject._resourceID)
- if sharedGroup:
- url = joinURL(url, ownerHomeChild.name(), sharedGroup.name())
- share = Share(shareeStoreObject=storeObject, ownerStoreObject=sharedGroup, url=url)
- break
-
- returnValue(share)
-
-
@inlineCallbacks
- def _shareForUID(self, shareUID, request):
+ def acceptShare(self, request, inviteUID, summary):
- if shareUID is not None: # shareUID may be None for partially shared addressbooks
- shareeStoreObject = yield self._newStoreHome.objectWithShareUID(shareUID)
- if shareeStoreObject:
- share = yield self._shareForStoreObject(shareeStoreObject, request)
- if share:
- returnValue(share)
+ # Accept the share
+ shareeView = yield self._newStoreHome.acceptShare(inviteUID, summary)
- # find direct shares
- children = yield self._newStoreHome.children()
- for child in children:
- share = yield self._shareForStoreObject(child, request)
- if share and share.uid() == shareUID:
- returnValue(share)
-
- returnValue(None)
-
-
- @inlineCallbacks
- def acceptInviteShare(self, request, hostUrl, inviteUID, displayname=None):
-
- # Check for old share
- oldShare = yield self._shareForUID(inviteUID, request)
-
- # Send the invite reply then add the link
- yield self._changeShare(request, _BIND_STATUS_ACCEPTED, hostUrl, inviteUID, displayname)
- if oldShare:
- share = oldShare
- else:
- sharedResource = yield request.locateResource(hostUrl)
- shareeStoreObject = yield self._newStoreHome.objectWithShareUID(inviteUID)
-
- share = Share(shareeStoreObject=shareeStoreObject,
- ownerStoreObject=sharedResource._newStoreObject,
- url=hostUrl)
-
- response = yield self._acceptShare(request, not oldShare, share, displayname)
- returnValue(response)
-
-
- @inlineCallbacks
- def acceptDirectShare(self, request, hostUrl, resourceUID,
- displayname=None):
-
- # Just add the link
- oldShare = yield self._shareForUID(resourceUID, request)
- if oldShare:
- share = oldShare
- else:
- sharedCollection = yield request.locateResource(hostUrl)
- shareUID = yield sharedCollection._newStoreObject.shareWith(
- shareeHome=self._newStoreHome,
- mode=_BIND_MODE_DIRECT,
- status=_BIND_STATUS_ACCEPTED,
- message=displayname
- )
-
- shareeStoreObject = yield self._newStoreHome.objectWithShareUID(shareUID)
- share = Share(shareeStoreObject=shareeStoreObject,
- ownerStoreObject=sharedCollection._newStoreObject,
- url=hostUrl)
-
- response = yield self._acceptShare(request, not oldShare, share, displayname)
- returnValue(response)
-
-
- @inlineCallbacks
- def _acceptShare(self, request, isNewShare, share, displayname=None):
- """
- Mark a pending shared invitation I{to} this, the owner's collection, as
- accepted, generating the HTTP response to the request that accepted it.
-
- @param request: The HTTP request that is accepting it.
- @type request: L{twext.web2.iweb.IRequest}
-
- @param isNewShare: a boolean indicating whether this share is new.
- @type isNewShare: L{bool}
-
- @param share: The share referencing the proposed sharer and sharee.
- @type share: L{Share}
-
- @param displayname: the UTF-8 encoded contents of the display-name
- property on the resource to be created while accepting.
- @type displayname: L{bytes}
-
- @return: a L{twext.web2.iweb.IResponse} containing a serialized
- L{customxml.SharedAs} element as its body.
- @rtype: L{Deferred} firing L{XMLResponse}
- """
- # Get shared collection in non-share mode first
- sharedResource = yield request.locateResource(share.url())
- sharee = self.principalForUID(share.shareeUID())
-
- if sharedResource.isCalendarCollection():
- shareeHomeResource = yield sharee.calendarHome(request)
- sharedAsURL = joinURL(shareeHomeResource.url(), share.name())
- shareeCalender = yield request.locateResource(sharedAsURL)
- shareeCalender.setShare(share)
-
- # For calendars only, per-user displayname and color
- if displayname:
- yield shareeCalender.writeProperty(element.DisplayName.fromString(displayname), request)
-
- if isNewShare:
- # For a direct share we will copy any calendar-color over using the owners view
- if share.direct():
- try:
- color = yield sharedResource.readProperty(customxml.CalendarColor, request)
- except HTTPError:
- color = None
- if color:
- yield shareeCalender.writeProperty(customxml.CalendarColor.fromString(color), request)
-
- # Calendars always start out transparent and with empty default alarms
- yield shareeCalender._newStoreObject.setUsedForFreeBusy(False)
- yield shareeCalender._newStoreObject.setDefaultAlarm("empty", True, True)
- yield shareeCalender._newStoreObject.setDefaultAlarm("empty", True, False)
- yield shareeCalender._newStoreObject.setDefaultAlarm("empty", False, True)
- yield shareeCalender._newStoreObject.setDefaultAlarm("empty", False, False)
-
- elif sharedResource.isAddressBookCollection():
- shareeHomeResource = yield sharee.addressBookHome(request)
- sharedAsURL = joinURL(shareeHomeResource.url(), share.ownerUID())
- shareeAddressBook = yield request.locateResource(sharedAsURL)
- shareeAddressBook.setShare(share)
-
- elif sharedResource.isGroup():
- shareeHomeResource = yield sharee.addressBookHome(request)
- sharedAsURL = joinURL(shareeHomeResource.url(), share.ownerUID(), share.name())
- shareeGroup = yield request.locateResource(sharedAsURL)
- shareeGroup.setShare(share)
-
- # Notify client of changes
- yield self.notifyChanged()
-
# Return the URL of the shared collection
+ sharedAsURL = joinURL(self.url(), shareeView.name())
returnValue(XMLResponse(
code=responsecode.OK,
element=customxml.SharedAs(
@@ -1237,132 +814,13 @@
@inlineCallbacks
- def removeShare(self, request, share):
- """
- Remove a shared collection named in resourceName
- """
+ def declineShare(self, request, inviteUID):
- if share.direct():
- yield self.removeDirectShare(request, share)
- returnValue(None)
- else:
- # Send a decline when an invite share is removed only
- result = yield self.declineShare(request, share.url(), share.uid())
- returnValue(result)
-
-
- @inlineCallbacks
- def removeShareByUID(self, request, shareUID):
- """
- Remove a shared collection but do not send a decline back. Return the
- current display name of the shared collection.
- """
-
- share = yield self._shareForUID(shareUID, request)
- if share:
- displayName = (yield self.removeDirectShare(request, share))
- returnValue(displayName)
- else:
- returnValue(None)
-
-
- @inlineCallbacks
- def removeDirectShare(self, request, share):
- """
- Remove a shared collection but do not send a decline back. Return the
- current display name of the shared collection.
- """
- # FIXME: only works for calendar
- shareURL = joinURL(self.url(), share.name())
- shared = (yield request.locateResource(shareURL))
- displayname = shared.displayName()
-
- if share.direct():
- yield share._ownerStoreObject.unshareWith(share._shareeStoreObject.viewerHome())
- else:
- yield share._ownerStoreObject.updateShare(share._shareeStoreObject, status=_BIND_STATUS_DECLINED)
-
- returnValue(displayname)
-
-
- @inlineCallbacks
- def declineShare(self, request, hostUrl, inviteUID):
-
# Remove it if it is in the DB
- yield self.removeShareByUID(request, inviteUID)
- yield self._changeShare(request, _BIND_STATUS_DECLINED, hostUrl, inviteUID, processed=True)
+ yield self._newStoreHome.declineShare(inviteUID)
returnValue(Response(code=responsecode.NO_CONTENT))
- @inlineCallbacks
- def _changeShare(self, request, state, hostUrl, replytoUID, displayname=None, processed=False):
- """
- Accept or decline an invite to a shared collection.
- """
- # Change state in owner invite
- ownerPrincipal = (yield self.ownerPrincipal(request))
- ownerPrincipalUID = ownerPrincipal.principalUID()
- sharedResource = (yield request.locateResource(hostUrl))
- if sharedResource is None:
- # FIXME: have to return here rather than raise to allow removal of a share for a sharer
- # whose principal is no longer valid yet still exists in the store. Really we need to get rid of
- # locateResource calls and just do everything via store objects.
- returnValue(None)
- # Original shared collection is gone - nothing we can do except ignore it
- raise HTTPError(ErrorResponse(
- responsecode.FORBIDDEN,
- (customxml.calendarserver_namespace, "valid-request"),
- "Invalid shared collection",
- ))
-
- # Change the record
- if not processed:
- yield sharedResource.changeUserInviteState(request, replytoUID, ownerPrincipalUID, state, displayname)
-
- yield self.sendReply(request, ownerPrincipal, sharedResource, state, hostUrl, replytoUID, displayname)
-
-
- @inlineCallbacks
- def sendReply(self, request, shareePrincipal, sharedResource, state, hostUrl, replytoUID, displayname=None):
-
- # Locate notifications collection for owner
- ownerPrincipal = (yield sharedResource.ownerPrincipal(request))
- if ownerPrincipal is None:
- # FIXME: have to return here rather than raise to allow removal of a share for a sharer
- # whose principal is no longer valid yet still exists in the store. Really we need to get rid of
- # locateResource calls and just do everything via store objects.
- returnValue(None)
-
- hosturl = sharedResource._newStoreObject.name()
- if sharedResource.sharedResourceType() == "group":
- hosturl = sharedResource._newStoreObject.parentCollection().name() + "/" + hosturl
-
- notificationResource = (yield request.locateResource(ownerPrincipal.notificationURL()))
- notifications = notificationResource._newStoreNotifications
-
- # Generate invite XML
- notificationUID = "%s-reply" % (replytoUID,)
-
- notificationtype = {
- "notification-type": "invite-reply",
- }
-
- notificationdata = {
- "notification-type": "invite-reply",
- "shared-type": sharedResource.sharedResourceType(),
- "dtstamp": DateTime.getNowUTC().getText(),
- "owner": ownerPrincipal.principalUID(),
- "sharee": shareePrincipal.principalUID(),
- "status": state,
- "name": hosturl,
- "in-reply-to": replytoUID,
- "summary": displayname if displayname is not None else "",
- }
-
- # Add to collections
- yield notifications.writeNotificationObject(notificationUID, notificationtype, notificationdata)
-
-
def _handleInviteReply(self, request, invitereplydoc):
"""
Handle a user accepting or declining a sharing invite
@@ -1392,80 +850,6 @@
"Missing required XML elements",
))
if accepted:
- return self.acceptInviteShare(request, hostUrl, replytoUID, displayname=summary)
+ return self.acceptShare(request, replytoUID, summary=summary)
else:
- return self.declineShare(request, hostUrl, replytoUID)
-
-
-
-class Share(object):
- """
- A L{Share} represents information about a collection which has been shared
- from one user to another.
- """
-
- def __init__(self, ownerStoreObject, shareeStoreObject, url):
- """
- @param sharerHomeChild: The data store object representing the shared
- collection as present in the owner's home collection; the owner's
- reference.
- @type sharerHomeChild: L{txdav.caldav.icalendarstore.ICalendar}
-
- @param shareeHomeChild: The data store object representing the
- collection as present in the sharee's home collection; the sharee's
- reference.
- @type shareeHomeChild: L{txdav.caldav.icalendarstore.ICalendar}
-
- @param url: The URL referring to the sharer's version of the resource.
- @type url: L{bytes}
- """
- self._shareeStoreObject = shareeStoreObject
- self._ownerStoreObject = ownerStoreObject
- self._ownerResourceURL = url
-
-
- @classmethod
- def directUID(cls, shareeHome, ownerHomeChild):
- return "Direct-%s-%s" % (shareeHome._resourceID,
- ownerHomeChild._resourceID,)
-
-
- def uid(self):
- # Move to CommonHomeChild shareUID?
- if self._shareeStoreObject.shareMode() == _BIND_MODE_DIRECT:
- return self.directUID(shareeHome=self._shareeStoreObject.viewerHome(),
- ownerHomeChild=self._ownerStoreObject,)
- else:
- return self._shareeStoreObject.shareUID()
-
-
- def direct(self):
- """
- Is this L{Share} a "direct" share?
-
- @return: a boolean indicating whether it's direct.
- """
- return self._shareeStoreObject.shareMode() == _BIND_MODE_DIRECT
-
-
- def url(self):
- """
- @return: The URL to the owner's version of the shared collection.
- """
- return self._ownerResourceURL
-
-
- def name(self):
- return self._shareeStoreObject.name()
-
-
- def summary(self):
- return self._shareeStoreObject.shareMessage()
-
-
- def shareeUID(self):
- return self._shareeStoreObject.viewerHome().uid()
-
-
- def ownerUID(self):
- return self._shareeStoreObject.ownerHome().uid()
+ return self.declineShare(request, replytoUID)
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -277,7 +277,7 @@
def owner_url(self):
if self.isShareeResource():
- return joinURL(self._share.url(), "/")
+ return joinURL(self._share_url, "/")
else:
return self.url()
@@ -1642,23 +1642,23 @@
for invite in invites:
# Only want accepted invites
- if invite.status() != _BIND_STATUS_ACCEPTED:
+ if invite.status != _BIND_STATUS_ACCEPTED:
continue
userprivs = [
]
- if invite.mode() in (_BIND_MODE_READ, _BIND_MODE_WRITE,):
+ if invite.mode in (_BIND_MODE_READ, _BIND_MODE_WRITE,):
userprivs.append(davxml.Privilege(davxml.Read()))
userprivs.append(davxml.Privilege(davxml.ReadACL()))
userprivs.append(davxml.Privilege(davxml.ReadCurrentUserPrivilegeSet()))
- if invite.mode() in (_BIND_MODE_READ,):
+ if invite.mode in (_BIND_MODE_READ,):
userprivs.append(davxml.Privilege(davxml.WriteProperties()))
- if invite.mode() in (_BIND_MODE_WRITE,):
+ if invite.mode in (_BIND_MODE_WRITE,):
userprivs.append(davxml.Privilege(davxml.Write()))
proxyprivs = list(userprivs)
proxyprivs.remove(davxml.Privilege(davxml.ReadACL()))
- principal = self.principalForUID(invite.shareeUID())
+ principal = self.principalForUID(invite.shareeUID)
aces += (
# Inheritable specific access for the resource's associated principal.
davxml.ACE(
@@ -1953,10 +1953,10 @@
access control mechanism has dictate the home should no longer have
any access at all.
"""
- if invite.mode() in (_BIND_MODE_DIRECT,):
- ownerUID = invite.ownerUID()
+ if invite.mode in (_BIND_MODE_DIRECT,):
+ ownerUID = invite.ownerUID
owner = self.principalForUID(ownerUID)
- shareeUID = invite.shareeUID()
+ shareeUID = invite.shareeUID
if owner.record.recordType == WikiDirectoryService.recordType_wikis:
# Access level comes from what the wiki has granted to the
# sharee
@@ -1972,9 +1972,9 @@
returnValue(None)
else:
returnValue("original")
- elif invite.mode() in (_BIND_MODE_READ,):
+ elif invite.mode in (_BIND_MODE_READ,):
returnValue("read-only")
- elif invite.mode() in (_BIND_MODE_WRITE,):
+ elif invite.mode in (_BIND_MODE_WRITE,):
returnValue("read-write")
returnValue("original")
@@ -1987,7 +1987,7 @@
for invite in invites:
# Only want accepted invites
- if invite.status() != _BIND_STATUS_ACCEPTED:
+ if invite.status != _BIND_STATUS_ACCEPTED:
continue
privileges = [
@@ -1999,7 +1999,7 @@
if access in ("read-only", "read-write",):
userprivs.extend(privileges)
- principal = self.principalForUID(invite.shareeUID())
+ principal = self.principalForUID(invite.shareeUID)
aces += (
# Inheritable specific access for the resource's associated principal.
davxml.ACE(
@@ -3771,7 +3771,7 @@
invitationBindStatusToXMLMap[jsondata["status"]](),
customxml.InviteAccess(invitationBindModeToXMLMap[jsondata["access"]]()),
customxml.HostURL(
- element.HRef.fromString(urljoin(ownerHomeURL, jsondata["name"])),
+ element.HRef.fromString(urljoin(ownerHomeURL, jsondata["ownerName"])),
),
customxml.Organizer(
element.HRef.fromString(owner),
@@ -3802,22 +3802,21 @@
commonName = shareePrincipal.displayName()
record = shareePrincipal.record
+ typeAttr = {"shared-type": jsondata["shared-type"]}
xmldata = customxml.Notification(
customxml.DTStamp.fromString(jsondata["dtstamp"]),
customxml.InviteReply(
- *(
- (
- element.HRef.fromString(cua),
- invitationBindStatusToXMLMap[jsondata["status"]](),
- customxml.HostURL(
- element.HRef.fromString(urljoin(ownerHomeURL, jsondata["name"])),
- ),
- customxml.InReplyTo.fromString(jsondata["in-reply-to"]),
- ) + ((customxml.InviteSummary.fromString(jsondata["summary"]),) if jsondata["summary"] else ())
- + ((customxml.CommonName.fromString(commonName),) if commonName else ())
- + ((customxml.FirstNameProperty(record.firstName),) if record.firstName else ())
- + ((customxml.LastNameProperty(record.lastName),) if record.lastName else ())
- )
+ element.HRef.fromString(cua),
+ invitationBindStatusToXMLMap[jsondata["status"]](),
+ customxml.HostURL(
+ element.HRef.fromString(urljoin(ownerHomeURL, jsondata["ownerName"])),
+ ),
+ customxml.InReplyTo.fromString(jsondata["in-reply-to"]),
+ customxml.InviteSummary.fromString(jsondata["summary"]) if jsondata["summary"] else None,
+ customxml.CommonName.fromString(commonName) if commonName else None,
+ customxml.FirstNameProperty(record.firstName) if record.firstName else None,
+ customxml.LastNameProperty(record.lastName) if record.lastName else None,
+ #**typeAttr
),
)
else:
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -52,8 +52,7 @@
class FakeHome(object):
- def removeShareByUID(self, request, uid):
- pass
+ pass
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/base/datastore/util.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/base/datastore/util.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/base/datastore/util.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -95,7 +95,7 @@
# Home child objects by id
def keyForObjectWithResourceID(self, homeResourceID, resourceID):
- return "objectWithName:%s:%s" % (homeResourceID, resourceID)
+ return "objectWithResourceID:%s:%s" % (homeResourceID, resourceID)
# Home metadata (Created/Modified)
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/sql.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/sql.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/sql.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
##
+from txdav.xml import element
"""
@@ -396,6 +397,8 @@
implements(ICalendarHome)
+ _homeType = ECALENDARTYPE
+
# structured tables. (new, preferred)
_homeSchema = schema.CALENDAR_HOME
_bindSchema = schema.CALENDAR_BIND
@@ -1245,6 +1248,44 @@
)
+ def sharedResourceType(self):
+ """
+ The sharing resource type
+ """
+ return "calendar"
+
+
+ @inlineCallbacks
+ def newShare(self, displayname=None):
+ """
+ Override in derived classes to do any specific operations needed when a share
+ is first accepted.
+ """
+
+ # For a direct share we will copy any displayname and calendar-color over using the owners view
+ if self.direct():
+ ownerView = yield self.ownerView()
+ try:
+ displayname = ownerView.properties()[PropertyName.fromElement(element.DisplayName)]
+ self.properties()[PropertyName.fromElement(element.DisplayName)] = displayname
+ except KeyError:
+ pass
+ try:
+ color = ownerView.properties()[PropertyName.fromElement(customxml.CalendarColor)]
+ self.properties()[PropertyName.fromElement(customxml.CalendarColor)] = color
+ except KeyError:
+ pass
+ elif displayname:
+ self.properties()[PropertyName.fromElement(element.DisplayName)] = element.DisplayName.fromString(displayname)
+
+ # Calendars always start out transparent and with empty default alarms
+ yield self.setUsedForFreeBusy(False)
+ yield self.setDefaultAlarm("empty", True, True)
+ yield self.setDefaultAlarm("empty", True, False)
+ yield self.setDefaultAlarm("empty", False, True)
+ yield self.setDefaultAlarm("empty", False, False)
+
+
# FIXME: this is DAV-ish. Data store calendar objects don't have
# mime types. -wsv
def contentType(self):
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/common.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/common.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/common.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -41,7 +41,6 @@
from txdav.common.icommondatastore import ObjectResourceNameAlreadyExistsError
from txdav.common.inotifications import INotificationObject
from txdav.common.datastore.test.util import CommonCommonTests
-from txdav.common.datastore.sql_tables import _BIND_MODE_WRITE, _BIND_MODE_READ
from txdav.caldav.icalendarstore import (
ICalendarObject, ICalendarHome,
@@ -974,156 +973,6 @@
@inlineCallbacks
- def test_shareWith(self):
- """
- L{ICalendar.shareWith} will share a calendar with a given home UID.
- """
- cal = yield self.calendarUnderTest()
- other = yield self.homeUnderTest(name=OTHER_HOME_UID)
- newCalName = yield cal.shareWith(other, _BIND_MODE_WRITE)
- self.sharedName = newCalName
- yield self.commit()
- normalCal = yield self.calendarUnderTest()
- otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
- otherCal = yield otherHome.childWithName(newCalName)
- self.assertNotIdentical(otherCal, None)
- self.assertEqual(
- (yield
- (yield otherCal.calendarObjectWithName("1.ics")).component()),
- (yield
- (yield normalCal.calendarObjectWithName("1.ics")).component())
- )
-
-
- @inlineCallbacks
- def test_shareAgainChangesMode(self):
- """
- If a calendar is already shared with a given calendar home,
- L{ICalendar.shareWith} will change the sharing mode.
- """
- yield self.test_shareWith()
- # yield self.commit() # txn is none? why?
- cal = yield self.calendarUnderTest()
- other = yield self.homeUnderTest(name=OTHER_HOME_UID)
- newName = yield cal.shareWith(other, _BIND_MODE_READ)
- otherCal = yield other.childWithName(self.sharedName)
-
- # Name should not change just because we updated the mode.
- self.assertEqual(newName, self.sharedName)
- self.assertNotIdentical(otherCal, None)
-
- invitedCals = yield cal.sharingInvites()
- self.assertEqual(len(invitedCals), 1)
- self.assertEqual(invitedCals[0].mode(), _BIND_MODE_READ)
-
-
- @inlineCallbacks
- def test_unshareWith(self, commit=False):
- """
- L{ICalendar.unshareWith} will remove a previously-shared calendar from
- another user's calendar home.
- """
- yield self.test_shareWith()
- if commit:
- yield self.commit()
- cal = yield self.calendarUnderTest()
- other = yield self.homeUnderTest(name=OTHER_HOME_UID)
- newName = yield cal.unshareWith(other)
- otherCal = yield other.childWithName(newName)
- self.assertIdentical(otherCal, None)
- invitedCals = yield cal.sharingInvites()
- self.assertEqual(len(invitedCals), 0)
-
-
- @inlineCallbacks
- def test_unshareSharerSide(self, commit=False):
- """
- Verify the coll.unshare( ) method works when called from the
- sharer's copy
- """
- yield self.test_shareWith()
- if commit:
- yield self.commit()
- cal = yield self.calendarUnderTest()
- other = yield self.homeUnderTest(name=OTHER_HOME_UID)
- otherCal = yield other.childWithName(self.sharedName)
- self.assertNotEqual(otherCal, None)
- yield cal.unshare()
- otherCal = yield other.childWithName(self.sharedName)
- self.assertEqual(otherCal, None)
- invitedCals = yield cal.sharingInvites()
- self.assertEqual(len(invitedCals), 0)
-
-
- @inlineCallbacks
- def test_unshareShareeSide(self, commit=False):
- """
- Verify the coll.unshare( ) method works when called from the
- sharee's copy
- """
- yield self.test_shareWith()
- if commit:
- yield self.commit()
- cal = yield self.calendarUnderTest()
- other = yield self.homeUnderTest(name=OTHER_HOME_UID)
- otherCal = yield other.childWithName(self.sharedName)
- self.assertNotEqual(otherCal, None)
- yield otherCal.unshare()
- otherCal = yield other.childWithName(self.sharedName)
- self.assertEqual(otherCal, None)
- invitedCals = yield cal.sharingInvites()
- self.assertEqual(len(invitedCals), 0)
-
-
- @inlineCallbacks
- def test_unshareWithInDifferentTransaction(self):
- """
- L{ICalendar.unshareWith} will remove a previously-shared calendar from
- another user's calendar home, assuming the sharing was committed in a
- previous transaction.
- """
- yield self.test_unshareWith(True)
-
-
- @inlineCallbacks
- def test_sharingInvites(self):
- """
- L{ICalendar.sharingInvites} returns an iterable of all versions of a shared
- calendar.
- """
- cal = yield self.calendarUnderTest()
- sharedBefore = yield cal.sharingInvites()
- # It's not shared yet; make sure sharingInvites doesn't include owner version.
- self.assertEqual(len(sharedBefore), 0)
- yield self.test_shareWith()
- # FIXME: don't know why this separate transaction is needed; remove it.
- yield self.commit()
- cal = yield self.calendarUnderTest()
- sharedAfter = yield cal.sharingInvites()
- self.assertEqual(len(sharedAfter), 1)
- self.assertEqual(sharedAfter[0].mode(), _BIND_MODE_WRITE)
- self.assertEqual(sharedAfter[0].shareeUID(), OTHER_HOME_UID)
-
-
- @inlineCallbacks
- def test_sharedNotifierID(self):
- yield self.test_shareWith()
- yield self.commit()
-
- home = yield self.homeUnderTest()
- self.assertEquals(home.notifierID(), ("CalDAV", "home1",))
- calendar = yield home.calendarWithName("calendar_1")
- self.assertEquals(calendar.notifierID(), ("CalDAV", "home1/calendar_1",))
- yield self.commit()
-
- home = yield self.homeUnderTest(name=OTHER_HOME_UID)
- self.assertEquals(home.notifierID(), ("CalDAV", OTHER_HOME_UID,))
- calendar = yield home.calendarWithName(self.sharedName)
- self.assertEquals(calendar.notifierID(), ("CalDAV", "home1/calendar_1",))
- yield self.commit()
-
-
- @inlineCallbacks
def test_hasCalendarResourceUIDSomewhereElse(self):
"""
L{ICalendarHome.hasCalendarResourceUIDSomewhereElse} will determine if
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -952,13 +952,13 @@
@inlineCallbacks
def _defer1():
- yield cal1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki Calendar")
+ yield cal1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary="Shared Wiki Calendar")
yield txn1.commit()
d1 = _defer1()
@inlineCallbacks
def _defer2():
- yield cal2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki Calendar")
+ yield cal2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary="Shared Wiki Calendar")
yield txn2.commit()
d2 = _defer2()
Added: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py (rev 0)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -0,0 +1,433 @@
+##
+# Copyright (c) 2005-2013 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.
+##
+
+
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twisted.trial.unittest import TestCase
+
+from twext.python.clsprop import classproperty
+from txdav.common.datastore.test.util import CommonCommonTests, \
+ populateCalendarsFrom
+from txdav.caldav.datastore.test.util import buildCalendarStore
+from txdav.common.datastore.sql_tables import _BIND_MODE_READ, \
+ _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED
+
+
+class CalendarSharing(CommonCommonTests, TestCase):
+ """
+ Test twistedcaldav.scheduyling.implicit with a Request object.
+ """
+
+ @inlineCallbacks
+ def setUp(self):
+ yield super(CalendarSharing, self).setUp()
+ self._sqlCalendarStore = yield buildCalendarStore(self, self.notifierFactory)
+ yield self.populate()
+
+
+ @inlineCallbacks
+ def populate(self):
+ yield populateCalendarsFrom(self.requirements, self.storeUnderTest())
+ self.notifierFactory.reset()
+
+
+ @classproperty(cache=False)
+ def requirements(cls): #@NoSelf
+ return {
+ "user01": {
+ "calendar": {
+ },
+ "inbox": {
+ },
+ },
+ "user02": {
+ "calendar": {
+ },
+ "inbox": {
+ },
+ },
+ "user03": {
+ "calendar": {
+ },
+ "inbox": {
+ },
+ },
+ }
+
+
+ def storeUnderTest(self):
+ """
+ Create and return a L{CalendarStore} for testing.
+ """
+ return self._sqlCalendarStore
+
+
+ @inlineCallbacks
+ def _createShare(self):
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ inviteUID = shareeView.shareUID()
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.homeUnderTest(name="user02")
+ shareeView = yield shareeHome.acceptShare(inviteUID)
+ sharedName = shareeView.name()
+ yield self.commit()
+
+ returnValue(sharedName)
+
+
+ @inlineCallbacks
+ def test_no_shares(self):
+ """
+ Test that initially there are no shares.
+ """
+
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+
+ @inlineCallbacks
+ def test_invite_sharee(self):
+ """
+ Test invite/uninvite creates/removes shares and notifications.
+ """
+
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ self.assertEqual(invites[0].uid, shareeView.shareUID())
+ self.assertEqual(invites[0].ownerUID, "user01")
+ self.assertEqual(invites[0].shareeUID, "user02")
+ self.assertEqual(invites[0].shareeName, shareeView.name())
+ self.assertEqual(invites[0].mode, _BIND_MODE_READ)
+ self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
+ self.assertEqual(invites[0].summary, "summary")
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID, ])
+
+ yield self.commit()
+
+ # Uninvite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+
+ yield calendar.uninviteUserFromShare("user02")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [])
+
+
+ @inlineCallbacks
+ def test_accept_share(self):
+ """
+ Test that invite+accept creates shares and notifications.
+ """
+
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Re-accept
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_decline_share(self):
+ """
+ Test that invite+accept creates shares and notifications.
+ """
+
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Decline
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.declineShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Redecline
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.declineShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_accept_decline_share(self):
+ """
+ Test that invite+accept/decline creates/removes shares and notifications.
+ Decline via the home.
+ """
+
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Decline
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.declineShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_accept_remove_share(self):
+ """
+ Test that invite+accept/decline creates/removes shares and notifications.
+ Decline via the shared collection (removal).
+ """
+
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.homeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Delete
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ yield shared.deleteShare()
+
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_inviteProperties(self):
+
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ yield calendar.setUsedForFreeBusy(True)
+ yield self.commit()
+
+ shared_name = yield self._createShare()
+
+ shared = yield self.calendarUnderTest(home="user02", name=shared_name)
+ self.assertFalse(shared.isUsedForFreeBusy())
+
+
+ @inlineCallbacks
+ def test_direct_sharee(self):
+ """
+ Test invite/uninvite creates/removes shares and notifications.
+ """
+
+ # Invite
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield calendar.directShareWithUser("user02")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ self.assertEqual(invites[0].uid, shareeView.shareUID())
+ self.assertEqual(invites[0].ownerUID, "user01")
+ self.assertEqual(invites[0].shareeUID, "user02")
+ self.assertEqual(invites[0].shareeName, shareeView.name())
+ self.assertEqual(invites[0].mode, _BIND_MODE_DIRECT)
+ self.assertEqual(invites[0].status, _BIND_STATUS_ACCEPTED)
+
+ sharedName = shareeView.name()
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 0)
+
+ yield self.commit()
+
+ # Remove
+ shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+ yield shared.deleteShare()
+
+ calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+ invites = yield calendar.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 0)
+
+
+ @inlineCallbacks
+ def test_sharedNotifierID(self):
+ shared_name = yield self._createShare()
+
+ home = yield self.homeUnderTest(name="user01")
+ self.assertEquals(home.notifierID(), ("CalDAV", "user01",))
+ calendar = yield home.calendarWithName("calendar")
+ self.assertEquals(calendar.notifierID(), ("CalDAV", "user01/calendar",))
+ yield self.commit()
+
+ home = yield self.homeUnderTest(name="user02")
+ self.assertEquals(home.notifierID(), ("CalDAV", "user02",))
+ calendar = yield home.calendarWithName(shared_name)
+ self.assertEquals(calendar.notifierID(), ("CalDAV", "user01/calendar",))
+ yield self.commit()
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -61,8 +61,6 @@
InvalidObjectResourceError, InvalidComponentForStoreError, \
AllRetriesFailed, ObjectResourceNameAlreadyExistsError
-from uuid import uuid4
-
from zope.interface.declarations import implements
@@ -70,6 +68,8 @@
implements(IAddressBookHome)
+ _homeType = EADDRESSBOOKTYPE
+
# structured tables. (new, preferred)
_homeSchema = schema.ADDRESSBOOK_HOME
_bindSchema = schema.SHARED_ADDRESSBOOK_BIND
@@ -217,32 +217,6 @@
return self._addressbook
- def shareeAddressBookName(self):
- return self.uid()
-
-
- def objectWithShareUID(self, shareUID):
- """
- Retrieve the child with the given bind identifier contained in this
- home.
-
- @param name: a string.
- @return: an L{ICalendar} or C{None} if no such child exists.
- """
- return self._childClass.objectWithBindName(self, shareUID, accepted=True)
-
-
- def invitedObjectWithShareUID(self, shareUID):
- """
- Retrieve the child invitation with the given bind identifier contained in this
- home.
-
- @param name: a string.
- @return: an L{ICalendar} or C{None} if no such child exists.
- """
- return self._childClass.objectWithBindName(self, shareUID, accepted=False)
-
-
@inlineCallbacks
def ownerHomeWithChildID(self, resourceID):
"""
@@ -344,20 +318,6 @@
Sharing code shared between AddressBook and AddressBookObject
"""
- def setShared(self, shared):
- """
- Set an owned collection to shared or unshared state. Technically this is not useful as "shared"
- really means it has invitees, but the current sharing spec supports a notion of a shared collection
- that has not yet had invitees added. For the time being we will support that option by using a new
- MESSAGE value to indicate an owned collection that is "shared".
-
- @param shared: whether or not the owned collection is "shared"
- @type shared: C{bool}
- """
- if self.owned():
- self._bindMessage = "shared" if shared else None
-
-
@inlineCallbacks
def _isSharedOrInvited(self):
"""
@@ -396,11 +356,10 @@
_objectSchema = schema.ADDRESSBOOK_OBJECT
- def __init__(self, home, name, resourceID, mode, status, revision=0, message=None, ownerHome=None, bindName=None):
+ def __init__(self, home, name, resourceID, mode, status, revision=0, message=None, ownerHome=None):
ownerName = ownerHome.addressbook().name() if ownerHome else None
super(AddressBook, self).__init__(home, name, resourceID, mode, status, revision=revision, message=message, ownerHome=ownerHome, ownerName=ownerName)
self._index = PostgresLegacyABIndexEmulator(self)
- self._bindName = bindName
def __repr__(self):
@@ -435,21 +394,13 @@
addressbookObjectsSinceToken = CommonHomeChild.objectResourcesSinceToken
- def shareeName(self):
+ def newShareName(self):
"""
- The sharee's name for a shared address book is the sharer's home ownerUID.
+ For shared address books the resource name of a share is the ownerUID of the owner's resource.
"""
- return self.ownerHome().shareeAddressBookName()
+ return self.ownerHome().uid()
- def bindNameIsResourceName(self):
- """
- For shared address books the resource name of an accepted share is not the same as the name
- in the bind table.
- """
- return False
-
-
@inlineCallbacks
def _loadPropertyStore(self, props=None):
if props is None:
@@ -475,6 +426,13 @@
)
+ def sharedResourceType(self):
+ """
+ The sharing resource type
+ """
+ return "addressbook"
+
+
def contentType(self):
"""
The content type of addressbook objects is text/vcard.
@@ -609,7 +567,7 @@
@inlineCallbacks
def _groupForSharedAddressBookComponent(self):
- n = self.shareeName()
+ n = self.name()
fn = n
uid = self._groupForSharedAddressBookUID()
@@ -677,7 +635,7 @@
)
# get ownerHomeIDs
for dataRow in dataRows:
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
ownerHome = yield home.ownerHomeWithChildID(resourceID)
ownerHomeToDataRowMap[ownerHome] = dataRow
@@ -686,12 +644,12 @@
home._txn, homeID=home._resourceID
)
for groupBindRow in groupBindRows:
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
if ownerHome not in ownerHomeToDataRowMap:
groupBindRow[0] = _BIND_MODE_WRITE
- groupBindRow[3] = None # bindName
+ groupBindRow[3] = None # name
groupBindRow[4] = None # bindStatus
groupBindRow[6] = None # bindMessage
ownerHomeToDataRowMap[ownerHome] = groupBindRow
@@ -709,18 +667,19 @@
# Create the actual objects merging in properties
for ownerHome, dataRow in ownerHomeToDataRowMap.iteritems():
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
additionalBind = dataRow[cls.bindColumnCount:cls.bindColumnCount + len(cls.additionalBindColumns())]
metadata = dataRow[cls.bindColumnCount + len(cls.additionalBindColumns()):]
child = cls(
home=home,
- name=ownerHome.shareeAddressBookName(),
+ name=name,
resourceID=ownerHome._resourceID,
- mode=bindMode, status=bindStatus,
+ mode=bindMode,
+ status=bindStatus,
revision=bindRevision,
- message=bindMessage, ownerHome=ownerHome,
- bindName=bindName
+ message=bindMessage,
+ ownerHome=ownerHome,
)
for attr, value in zip(cls.additionalBindAttributes(), additionalBind):
@@ -764,9 +723,7 @@
if queryCacher:
# Retrieve data from cache
cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
- cachedRows = yield queryCacher.get(cacheKey)
- if cachedRows and (cachedRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
- rows = cachedRows
+ rows = yield queryCacher.get(cacheKey)
if not rows:
# name must be a home uid
@@ -777,7 +734,7 @@
bindRows = yield cls._bindForResourceIDAndHomeID.on(
home._txn, resourceID=ownerAddressBook._resourceID, homeID=home._resourceID
)
- if bindRows and (bindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
+ if bindRows:
bindRows[0].insert(cls.bindColumnCount, ownerAddressBook._resourceID)
bindRows[0].insert(cls.bindColumnCount + 1, bindRows[0][4]) # cachedStatus = bindStatus
rows = bindRows
@@ -786,15 +743,14 @@
home._txn, homeID=home._resourceID, addressbookID=ownerAddressBook._resourceID
)
for groupBindRow in groupBindRows:
- if (groupBindRow[4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
- groupBindRow.insert(AddressBookObject.bindColumnCount, ownerAddressBook._resourceID)
- groupBindRow.insert(AddressBookObject.bindColumnCount + 1, groupBindRow[4])
- groupBindRow[0] = _BIND_MODE_WRITE
- groupBindRow[3] = None # bindName
- groupBindRow[4] = None # bindStatus
- groupBindRow[6] = None # bindMessage
- rows = [groupBindRow]
- break
+ groupBindRow.insert(AddressBookObject.bindColumnCount, ownerAddressBook._resourceID)
+ groupBindRow.insert(AddressBookObject.bindColumnCount + 1, groupBindRow[4])
+ groupBindRow[0] = _BIND_MODE_WRITE
+ groupBindRow[3] = ownerHome.uid() # bindName
+ groupBindRow[4] = None # bindStatus
+ groupBindRow[6] = None # bindMessage
+ rows = [groupBindRow]
+ break
if rows and queryCacher:
# Cache the result
@@ -804,20 +760,22 @@
returnValue(None)
row = rows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage, ownerAddressBookID, cachedBindStatus = row[:cls.bindColumnCount + 2] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage, ownerAddressBookID, cachedBindStatus = row[:cls.bindColumnCount + 2] #@UnusedVariable
# if wrong status, exit here. Item is in queryCache
- if (cachedBindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+ if accepted is not None and (cachedBindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
returnValue(None)
ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
child = cls(
home=home,
- name=ownerHome.shareeAddressBookName(), resourceID=ownerAddressBookID,
- mode=bindMode, status=bindStatus,
+ name=name,
+ resourceID=ownerAddressBookID,
+ mode=bindMode,
+ status=bindStatus,
revision=bindRevision,
- message=bindMessage, ownerHome=ownerHome,
- bindName=bindName,
+ message=bindMessage,
+ ownerHome=ownerHome,
)
yield child.initFromStore()
returnValue(child)
@@ -825,57 +783,6 @@
@classmethod
@inlineCallbacks
- def objectWithBindName(cls, home, name, accepted):
- """
- Retrieve the child or objectResource with the given bind name C{name} contained in the given
- C{home}.
-
- @param home: a L{CommonHome}.
-
- @param name: a string; the name of the L{CommonHomeChild} to retrieve.
-
- @return: an L{CommonHomeChild} or L{ObjectResource} or C{None} if no such child
- exists.
- """
- bindRows = yield cls._bindForNameAndHomeID.on(home._txn, name=name, homeID=home._resourceID)
- if bindRows and (bindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
- bindRow = bindRows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = bindRow[:cls.bindColumnCount] #@UnusedVariable
-
- # alt:
- # returnValue((yield cls.objectWithID(home, resourceID)))
- ownerHome = yield home.ownerHomeWithChildID(resourceID)
- if accepted:
- returnValue((yield home.childWithName(ownerHome.shareeAddressBookName())))
- else:
- returnValue((yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)))
-
- groupBindRows = yield AddressBookObject._bindForNameAndHomeID.on(
- home._txn, name=name, homeID=home._resourceID
- )
- if groupBindRows and (groupBindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
- groupBindRow = groupBindRows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
-
- ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
- # alt:
- # addressbook = yield cls.objectWithID(home, ownerAddressBookID)
- ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
- addressbook = yield home.childWithName(ownerHome.shareeAddressBookName())
- if not addressbook:
- addressbook = yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)
- assert addressbook
-
- if accepted:
- returnValue((yield addressbook.objectResourceWithID(resourceID)))
- else:
- returnValue((yield AddressBookObject.objectWithID(addressbook, resourceID))) # avoids object cache
-
- returnValue(None)
-
-
- @classmethod
- @inlineCallbacks
def objectWithID(cls, home, resourceID, accepted=True):
"""
Retrieve the child with the given C{resourceID} contained in the given
@@ -892,40 +799,39 @@
bindRows = yield cls._bindForResourceIDAndHomeID.on(
home._txn, resourceID=resourceID, homeID=home._resourceID
)
- if bindRows and (bindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
+ if bindRows:
bindRow = bindRows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = bindRow[:cls.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = bindRow[:cls.bindColumnCount] #@UnusedVariable
+ if accepted is not None and (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+ returnValue(None)
+
ownerHome = yield home.ownerHomeWithChildID(resourceID)
- if accepted:
- returnValue((yield home.childWithName(ownerHome.shareeAddressBookName())))
+ if bindStatus == _BIND_STATUS_ACCEPTED:
+ returnValue((yield home.childWithName(ownerHome.uid())))
else:
- returnValue((yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)))
+ returnValue((yield cls.objectWithName(home, ownerHome.uid(), accepted=False)))
groupBindRows = yield AddressBookObject._bindForHomeIDAndAddressBookID.on(
home._txn, homeID=home._resourceID, addressbookID=resourceID
)
- if groupBindRows and (groupBindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
+ if groupBindRows:
groupBindRow = groupBindRows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+ if accepted is not None and (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+ returnValue(None)
+
ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
- if accepted:
- returnValue((yield home.childWithName(ownerHome.shareeAddressBookName())))
+ if bindStatus == _BIND_STATUS_ACCEPTED:
+ returnValue((yield home.childWithName(ownerHome.uid())))
else:
- returnValue((yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)))
+ returnValue((yield cls.objectWithName(home, ownerHome.uid(), accepted=False)))
returnValue(None)
- def shareUID(self):
- """
- @see: L{ICalendar.shareUID}
- """
- return self._bindName
-
-
def fullyShared(self):
return not self.owned() and self._bindStatus == _BIND_STATUS_ACCEPTED
@@ -944,18 +850,18 @@
home._txn, homeID=home._resourceID
)
for row in rows:
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
ownerHome = yield home._txn.homeWithResourceID(home._homeType, resourceID, create=True)
- names |= set([ownerHome.shareeAddressBookName()])
+ names |= set([ownerHome.uid()])
groupRows = yield AddressBookObject._acceptedBindForHomeID.on(
home._txn, homeID=home._resourceID
)
for groupRow in groupRows:
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
ownerHome = yield home._txn.homeWithResourceID(home._homeType, ownerAddressBookID, create=True)
- names |= set([ownerHome.shareeAddressBookName()])
+ names |= set([ownerHome.uid()])
returnValue(tuple(names))
@@ -1023,7 +929,7 @@
readWriteGroupIDs = []
readOnlyGroupIDs = []
for groupBindRow in groupBindRows:
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
if bindMode == _BIND_MODE_WRITE:
readWriteGroupIDs.append(resourceID)
else:
@@ -1071,7 +977,7 @@
readWriteGroupIDs = []
readOnlyGroupIDs = []
for groupBindRow in groupBindRows:
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
if bindMode == _BIND_MODE_WRITE:
readWriteGroupIDs.append(resourceID)
else:
@@ -1105,7 +1011,7 @@
@inlineCallbacks
- def updateShare(self, shareeView, mode=None, status=None, message=None):
+ def updateShare(self, shareeView, mode=None, status=None, summary=None):
"""
Update share mode, status, and message for a home child shared with
this (owned) L{CommonHomeChild}.
@@ -1122,9 +1028,9 @@
L{_BIND_STATUS_INVALID} or None to not update
@type status: L{str}
- @param message: The proposed message to go along with the share, which
+ @param summary: The proposed message to go along with the share, which
will be used as the default display name, or None to not update
- @type message: L{str}
+ @type summary: L{str}
@return: the name of the shared item in the sharee's home.
@rtype: a L{Deferred} which fires with a L{str}
@@ -1137,7 +1043,7 @@
columnMap = dict([(k, v if v != "" else None)
for k, v in {bind.BIND_MODE:mode,
bind.BIND_STATUS:status,
- bind.MESSAGE:message}.iteritems() if v is not None])
+ bind.MESSAGE:summary}.iteritems() if v is not None])
if len(columnMap):
@@ -1163,21 +1069,23 @@
if 0 == previouslyAcceptedBindCount:
yield shareeView._initSyncToken()
yield shareeView._initBindRevision()
- shareeView.viewerHome()._children[self.shareeName()] = shareeView
+ shareeView.viewerHome()._children[shareeView._name] = shareeView
shareeView.viewerHome()._children[shareeView._resourceID] = shareeView
elif shareeView._bindStatus == _BIND_STATUS_DECLINED:
if 1 == previouslyAcceptedBindCount:
yield shareeView._deletedSyncToken(sharedRemoval=True)
- shareeView.viewerHome()._children.pop(self.shareeName(), None)
+ shareeView.viewerHome()._children.pop(shareeView._name, None)
shareeView.viewerHome()._children.pop(shareeView._resourceID, None)
- if message is not None:
+ if summary is not None:
shareeView._bindMessage = columnMap[bind.MESSAGE]
queryCacher = self._txn._queryCacher
if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeView.viewerHome()._resourceID, self.shareeName())
- queryCacher.invalidateAfterCommit(self._txn, cacheKey)
+ cacheKey = queryCacher.keyForObjectWithName(shareeView._home._resourceID, shareeView._name)
+ yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
+ cacheKey = queryCacher.keyForObjectWithResourceID(shareeView._home._resourceID, shareeView._resourceID)
+ yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
shareeView._name = bindNameRows[0][0]
@@ -1188,22 +1096,6 @@
@inlineCallbacks
- def shareWith(self, shareeHome, mode, status=None, message=None):
- """
- call super and set isShared = True
- """
- bindName = yield super(AddressBook, self).shareWith(shareeHome, mode, status, message)
-
- queryCacher = self._txn._queryCacher
- if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.shareeName())
- queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-
- self.setShared(True)
- returnValue(bindName)
-
-
- @inlineCallbacks
def unshareWith(self, shareeHome):
"""
Remove the shared version of this (owned) L{CommonHomeChild} from the
@@ -1216,7 +1108,7 @@
@return: a L{Deferred} which will fire with the previous shareUID
"""
- sharedAddressBook = yield shareeHome.addressbookWithName(self.shareeName())
+ sharedAddressBook = yield shareeHome.addressbookWithName(self.name())
if sharedAddressBook:
acceptedBindCount = 1 if sharedAddressBook.fullyShared() else 0
@@ -1225,7 +1117,7 @@
)))
if acceptedBindCount == 1:
yield sharedAddressBook._deletedSyncToken(sharedRemoval=True)
- shareeHome._children.pop(self.shareeName(), None)
+ shareeHome._children.pop(self.name(), None)
shareeHome._children.pop(sharedAddressBook._resourceID, None)
elif not sharedAddressBook.fullyShared():
# FIXME: remove objects for this group only using self.removeObjectResource
@@ -1242,7 +1134,7 @@
deletedBindName = deletedBindNameRows[0][0]
queryCacher = self._txn._queryCacher
if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.shareeName())
+ cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.name())
queryCacher.invalidateAfterCommit(self._txn, cacheKey)
else:
deletedBindName = None
@@ -1618,7 +1510,7 @@
def validAddressDataCheck(self, component, inserting): #@UnusedVariable
"""
- Check that the calendar data is valid iCalendar.
+ Check that the calendar data is valid IAddressBook.
@return: tuple: (True/False if the calendar data is valid,
log message string).
"""
@@ -2039,6 +1931,13 @@
pass
+ def sharedResourceType(self):
+ """
+ The sharing resource type
+ """
+ return "group"
+
+
# IDataStoreObject
def contentType(self):
"""
@@ -2059,13 +1958,6 @@
return self.addressbook().viewerHome()
- def shareUID(self):
- """
- @see: L{ICalendar.shareUID}
- """
- return self._bindName
-
-
@classmethod
def metadataColumns(cls):
"""
@@ -2139,7 +2031,7 @@
homeUID,
homeRID,
resourceID,
- self.addressbook().shareeName(),
+ self.addressbook().name(),
bindMode,
bindStatus,
bindMessage,
@@ -2181,7 +2073,7 @@
@return: a L{Deferred} which will fire with the previously-used name.
"""
- sharedAddressBook = yield shareeHome.addressbookWithName(self.addressbook().shareeName())
+ sharedAddressBook = yield shareeHome.addressbookWithName(self.addressbook().name())
if sharedAddressBook:
@@ -2194,7 +2086,7 @@
if acceptedBindCount == 1:
yield sharedAddressBook._deletedSyncToken(sharedRemoval=True)
- shareeHome._children.pop(self.addressbook().shareeName(), None)
+ shareeHome._children.pop(self.addressbook().name(), None)
shareeHome._children.pop(self.addressbook()._resourceID, None)
# Must send notification to ensure cache invalidation occurs
@@ -2209,7 +2101,7 @@
deletedBindName = deletedBindNameRows[0][0]
queryCacher = self._txn._queryCacher
if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().shareeName())
+ cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().name())
queryCacher.invalidateAfterCommit(self._txn, cacheKey)
else:
deletedBindName = None
@@ -2219,7 +2111,7 @@
@inlineCallbacks
- def shareWith(self, shareeHome, mode, status=None, message=None):
+ def shareWith(self, shareeHome, mode, status=None, summary=None):
"""
Share this (owned) L{AddressBookObject} with another home.
@@ -2234,9 +2126,9 @@
L{_BIND_STATUS_ACCEPTED}
@type mode: L{str}
- @param message: The proposed message to go along with the share, which
+ @param summary: The proposed message to go along with the share, which
will be used as the default display name.
- @type mode: L{str}
+ @type summary: L{str}
@return: the name of the shared group in the sharee home.
@rtype: L{str}
@@ -2247,11 +2139,11 @@
@inlineCallbacks
def doInsert(subt):
- newName = str(uuid4())
+ newName = self.newShareName()
yield self._bindInsertQuery.on(
subt, homeID=shareeHome._resourceID,
resourceID=self._resourceID, name=newName,
- mode=mode, bindStatus=status, message=message
+ mode=mode, bindStatus=status, message=summary
)
returnValue(newName)
try:
@@ -2269,7 +2161,7 @@
group = yield shareeHome.invitedObjectWithShareUID(bindName)
bindName = yield self.updateShare(
group, mode=mode, status=status,
- message=message
+ summary=summary
)
else:
if status == _BIND_STATUS_ACCEPTED:
@@ -2279,7 +2171,7 @@
queryCacher = self._txn._queryCacher
if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().shareeName())
+ cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().name())
queryCacher.invalidateAfterCommit(self._txn, cacheKey)
# Must send notification to ensure cache invalidation occurs
@@ -2304,7 +2196,7 @@
@inlineCallbacks
- def updateShare(self, shareeView, mode=None, status=None, message=None):
+ def updateShare(self, shareeView, mode=None, status=None, summary=None):
"""
Update share mode, status, and message for a home child shared with
this (owned) L{CommonHomeChild}.
@@ -2321,9 +2213,9 @@
L{_BIND_STATUS_INVALID} or None to not update
@type status: L{str}
- @param message: The proposed message to go along with the share, which
+ @param summary: The proposed message to go along with the share, which
will be used as the default display name, or None to not update
- @type message: L{str}
+ @type summary: L{str}
@return: the name of the shared item in the sharee's home.
@rtype: a L{Deferred} which fires with a L{str}
@@ -2336,7 +2228,7 @@
columnMap = dict([(k, v if v != "" else None)
for k, v in {bind.BIND_MODE:mode,
bind.BIND_STATUS:status,
- bind.MESSAGE:message}.iteritems() if v is not None])
+ bind.MESSAGE:summary}.iteritems() if v is not None])
if len(columnMap):
@@ -2364,21 +2256,21 @@
if 0 == previouslyAcceptedBindCount:
yield shareeView.addressbook()._initSyncToken()
yield shareeView._initBindRevision()
- shareeView.viewerHome()._children[self.addressbook().shareeName()] = shareeView.addressbook()
+ shareeView.viewerHome()._children[self.addressbook().name()] = shareeView.addressbook()
shareeView.viewerHome()._children[shareeView._resourceID] = shareeView.addressbook()
elif shareeView._bindStatus != _BIND_STATUS_INVITED:
if 1 == previouslyAcceptedBindCount:
yield shareeView.addressbook()._deletedSyncToken(sharedRemoval=True)
- shareeView.viewerHome()._children.pop(self.addressbook().shareeName(), None)
+ shareeView.viewerHome()._children.pop(self.addressbook().name(), None)
shareeView.viewerHome()._children.pop(shareeView._resourceID, None)
- if message is not None:
+ if summary is not None:
shareeView._bindMessage = columnMap[bind.MESSAGE]
# safer to just invalidate in all cases rather than calculate when to invalidate
queryCacher = self._txn._queryCacher
if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeView.viewerHome()._resourceID, self.addressbook().shareeName())
+ cacheKey = queryCacher.keyForObjectWithName(shareeView.viewerHome()._resourceID, self.addressbook().name())
queryCacher.invalidateAfterCommit(self._txn, cacheKey)
shareeView._name = bindNameRows[0][0]
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -741,13 +741,13 @@
@inlineCallbacks
def _defer1():
- yield ab1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki AddressBook")
+ yield ab1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary="Shared Wiki AddressBook")
yield txn1.commit()
d1 = _defer1()
@inlineCallbacks
def _defer2():
- yield ab2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki AddressBook")
+ yield ab2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary="Shared Wiki AddressBook")
yield txn2.commit()
d2 = _defer2()
Added: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py (rev 0)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -0,0 +1,430 @@
+##
+# Copyright (c) 2005-2013 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.
+##
+
+
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twisted.trial.unittest import TestCase
+
+from twistedcaldav.vcard import Component as VCard
+from twext.python.clsprop import classproperty
+from txdav.common.datastore.test.util import CommonCommonTests, buildStore
+from txdav.common.datastore.sql_tables import _BIND_MODE_READ, \
+ _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED
+
+
+class CalendarSharing(CommonCommonTests, TestCase):
+ """
+ Test twistedcaldav.scheduyling.implicit with a Request object.
+ """
+
+ @inlineCallbacks
+ def setUp(self):
+ yield super(CalendarSharing, self).setUp()
+ self._sqlStore = yield buildStore(self, self.notifierFactory)
+ yield self.populate()
+
+
+ @inlineCallbacks
+ def populate(self):
+ populateTxn = self.storeUnderTest().newTransaction()
+ for homeUID in self.requirements:
+ addressbooks = self.requirements[homeUID]
+ if addressbooks is not None:
+ home = yield populateTxn.addressbookHomeWithUID(homeUID, True)
+ addressbook = home.addressbook()
+
+ addressbookObjNames = addressbooks[addressbook.name()]
+ if addressbookObjNames is not None:
+ for objectName in addressbookObjNames:
+ objData = addressbookObjNames[objectName]
+ yield addressbook.createAddressBookObjectWithName(
+ objectName, VCard.fromString(objData)
+ )
+
+ yield populateTxn.commit()
+ self.notifierFactory.reset()
+
+
+ @classproperty(cache=False)
+ def requirements(cls): #@NoSelf
+ return {
+ "user01": {
+ "addressbook": {
+ },
+ },
+ "user02": {
+ "addressbook": {
+ },
+ },
+ "user03": {
+ "addressbook": {
+ },
+ },
+ }
+
+
+ def storeUnderTest(self):
+ """
+ Create and return a L{CalendarStore} for testing.
+ """
+ return self._sqlStore
+
+
+ @inlineCallbacks
+ def _createShare(self):
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ inviteUID = shareeView.shareUID()
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ shareeView = yield shareeHome.acceptShare(inviteUID)
+ sharedName = shareeView.name()
+ yield self.commit()
+
+ returnValue(sharedName)
+
+
+ @inlineCallbacks
+ def test_no_shares(self):
+ """
+ Test that initially there are no shares.
+ """
+
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+
+ @inlineCallbacks
+ def test_invite_sharee(self):
+ """
+ Test invite/uninvite creates/removes shares and notifications.
+ """
+
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ self.assertEqual(invites[0].uid, shareeView.shareUID())
+ self.assertEqual(invites[0].ownerUID, "user01")
+ self.assertEqual(invites[0].shareeUID, "user02")
+ self.assertEqual(invites[0].shareeName, shareeView.name())
+ self.assertEqual(invites[0].mode, _BIND_MODE_READ)
+ self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
+ self.assertEqual(invites[0].summary, "summary")
+ inviteUID = shareeView.shareUID()
+
+ self.assertEqual(invites[0].shareeName, "user01")
+
+ sharedName = shareeView.name()
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID, ])
+
+ yield self.commit()
+
+ # Uninvite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+
+ yield addressbook.uninviteUserFromShare("user02")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [])
+
+
+ @inlineCallbacks
+ def test_accept_share(self):
+ """
+ Test that invite+accept creates shares and notifications.
+ """
+
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Re-accept
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_decline_share(self):
+ """
+ Test that invite+accept creates shares and notifications.
+ """
+
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Decline
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.declineShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Redecline
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.declineShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_accept_decline_share(self):
+ """
+ Test that invite+accept/decline creates/removes shares and notifications.
+ Decline via the home.
+ """
+
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Decline
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.declineShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_accept_remove_share(self):
+ """
+ Test that invite+accept/decline creates/removes shares and notifications.
+ Decline via the shared collection (removal).
+ """
+
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ inviteUID = shareeView.shareUID()
+
+ sharedName = shareeView.name()
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 1)
+
+ yield self.commit()
+
+ # Accept
+ shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+ yield shareeHome.acceptShare(inviteUID)
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+ yield self.commit()
+
+ # Delete
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ yield shared.deleteShare()
+
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+ @inlineCallbacks
+ def test_direct_sharee(self):
+ """
+ Test invite/uninvite creates/removes shares and notifications.
+ """
+
+ # Invite
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ shareeView = yield addressbook.directShareWithUser("user02")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 1)
+ self.assertEqual(invites[0].uid, shareeView.shareUID())
+ self.assertEqual(invites[0].ownerUID, "user01")
+ self.assertEqual(invites[0].shareeUID, "user02")
+ self.assertEqual(invites[0].shareeName, shareeView.name())
+ self.assertEqual(invites[0].mode, _BIND_MODE_DIRECT)
+ self.assertEqual(invites[0].status, _BIND_STATUS_ACCEPTED)
+
+ sharedName = shareeView.name()
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ self.assertTrue(shared is not None)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 0)
+
+ yield self.commit()
+
+ # Remove
+ shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+ yield shared.deleteShare()
+
+ addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+ invites = yield addressbook.sharingInvites()
+ self.assertEqual(len(invites), 0)
+
+ notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+ notifications = yield notifyHome.listNotificationObjects()
+ self.assertEqual(len(notifications), 0)
+
+
+ @inlineCallbacks
+ def test_sharedNotifierID(self):
+ shared_name = yield self._createShare()
+
+ home = yield self.addressbookHomeUnderTest(name="user01")
+ self.assertEquals(home.notifierID(), ("CardDAV", "user01",))
+ addressbook = yield home.addressbookWithName("addressbook")
+ self.assertEquals(addressbook.notifierID(), ("CardDAV", "user01/addressbook",))
+ yield self.commit()
+
+ home = yield self.addressbookHomeUnderTest(name="user02")
+ self.assertEquals(home.notifierID(), ("CardDAV", "user02",))
+ addressbook = yield home.addressbookWithName(shared_name)
+ self.assertEquals(addressbook.notifierID(), ("CardDAV", "user01/addressbook",))
+ yield self.commit()
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -14,6 +14,9 @@
# See the License for the specific language governing permissions and
# limitations under the License.
##
+from collections import namedtuple
+from txdav.xml import element
+from txdav.base.propertystore.base import PropertyName
"""
SQL data store.
@@ -60,7 +63,8 @@
from txdav.carddav.iaddressbookstore import IAddressBookTransaction
from txdav.common.datastore.common import HomeChildBase
from txdav.common.datastore.sql_tables import _BIND_MODE_OWN, \
- _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED
+ _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, _BIND_STATUS_INVALID, \
+ _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_DELETED
from txdav.common.datastore.sql_tables import schema, splitSQLString
from txdav.common.icommondatastore import ConcurrentModification
from txdav.common.icommondatastore import HomeChildNameNotAllowedError, \
@@ -1433,10 +1437,43 @@
-class CommonHome(object):
+class SharingHomeMixIn(object):
+ """
+ Common class for CommonHome to implement sharing operations
+ """
+
+ @inlineCallbacks
+ def acceptShare(self, shareUID, summary=None):
+ """
+ This share is being accepted.
+ """
+
+ shareeView = yield self.anyObjectWithShareUID(shareUID)
+ if shareeView is not None:
+ yield shareeView.acceptShare(summary)
+
+ returnValue(shareeView)
+
+
+ @inlineCallbacks
+ def declineShare(self, shareUID):
+ """
+ This share is being declined.
+ """
+
+ shareeView = yield self.anyObjectWithShareUID(shareUID)
+ if shareeView is not None:
+ yield shareeView.declineShare()
+
+ returnValue(shareeView)
+
+
+
+class CommonHome(SharingHomeMixIn):
log = Logger()
# All these need to be initialized by derived classes for each store type
+ _homeType = None
_homeTable = None
_homeMetaDataTable = None
_childClass = None
@@ -1794,6 +1831,17 @@
return self._childClass.objectWithName(self, shareUID, accepted=False)
+ def anyObjectWithShareUID(self, shareUID):
+ """
+ Retrieve the child accepted or otherwise with the given bind identifier contained in this
+ home.
+
+ @param name: a string.
+ @return: an L{ICalendar} or C{None} if no such child exists.
+ """
+ return self._childClass.objectWithName(self, shareUID, accepted=None)
+
+
@memoizedKey("resourceID", "_children")
def childWithID(self, resourceID):
"""
@@ -1806,6 +1854,17 @@
return self._childClass.objectWithID(self, resourceID)
+ def allChildWithID(self, resourceID):
+ """
+ Retrieve the child with the given C{resourceID} contained in this
+ home.
+
+ @param name: a string.
+ @return: an L{ICalendar} or C{None} if no such child exists.
+ """
+ return self._childClass.objectWithID(self, resourceID, accepted=None)
+
+
@inlineCallbacks
def createChildWithName(self, name):
if name.startswith("."):
@@ -2699,125 +2758,13 @@
-class SharingInvitation(object):
- """
- SharingInvitation covers all the information needed to expose sharing invites to upper layers. Its primarily used to
- minimize the need to load full properties/data when only this subset of information is needed.
- """
- def __init__(self, uid, owner_uid, owner_rid, sharee_uid, sharee_rid, resource_id, resource_name, mode, status, summary):
- self._uid = uid
- self._owner_uid = owner_uid
- self._owner_rid = owner_rid
- self._sharee_uid = sharee_uid
- self._sharee_rid = sharee_rid
- self._resource_id = resource_id
- self._resource_name = resource_name
- self._mode = mode
- self._status = status
- self._summary = summary
+SharingInvitation = namedtuple(
+ "SharingInvitation",
+ ["uid", "ownerUID", "shareeUID", "shareeName", "mode", "status", "summary"]
+)
- @classmethod
- def fromCommonHomeChild(cls, homeChild):
- return cls(
- homeChild.shareUID(),
- homeChild.ownerHome().uid(),
- homeChild.ownerHome()._resourceID,
- homeChild.viewerHome().uid(),
- homeChild.viewerHome()._resourceID,
- homeChild._resourceID,
- homeChild.shareeName(),
- homeChild.shareMode(),
- homeChild.shareStatus(),
- homeChild.shareMessage(),
- )
-
- def uid(self):
- """
- This maps to the resource name in the bind table, the "bind name". This is used as the "uid"
- for invites, and is not necessarily the name of the resource as it appears in the collection.
- """
- return self._uid
-
-
- def ownerUID(self):
- """
- The ownerUID of the sharer.
- """
- return self._owner_uid
-
-
- def ownerHomeID(self):
- """
- The resourceID of the sharer's L{CommonHome}.
- """
- return self._owner_rid
-
-
- def shareeUID(self):
- """
- The ownerUID of the sharee.
- """
- return self._sharee_uid
-
-
- def shareeHomeID(self):
- """
- The resourceID of the sharee's L{CommonHome}.
- """
- return self._sharee_rid
-
-
- def resourceID(self):
- """
- The resourceID of the shared object.
- """
- return self._resource_id
-
-
- def resourceName(self):
- """
- This maps to the name of the shared resource in the collection it is bound into. It is not necessarily the
- same as the "bind name" which is used as the "uid" for invites.
- """
- return self._resource_name
-
-
- def mode(self):
- """
- The sharing mode: one of the _BIND_MODE_XXX values.
- """
- return self._mode
-
-
- def setMode(self, mode):
- self._mode = mode
-
-
- def status(self):
- """
- The sharing status: one of the _BIND_STATUS_XXX values.
- """
- return self._status
-
-
- def setStatus(self, status):
- self._status = status
-
-
- def summary(self):
- """
- Message associated with the invitation.
- """
- return self._summary
-
-
- def setSummary(self, summary):
- self._summary = summary
-
-
-
class SharingMixIn(object):
"""
Common class for CommonHomeChild and AddressBookObject
@@ -2843,29 +2790,20 @@
@classmethod
def _updateBindColumnsQuery(cls, columnMap): #@NoSelf
bind = cls._bindSchema
- return Update(columnMap,
- Where=(bind.RESOURCE_ID == Parameter("resourceID"))
- .And(bind.HOME_RESOURCE_ID == Parameter("homeID")),
- Return=bind.RESOURCE_NAME)
+ return Update(
+ columnMap,
+ Where=(bind.RESOURCE_ID == Parameter("resourceID"))
+ .And(bind.HOME_RESOURCE_ID == Parameter("homeID")),
+ )
@classproperty
- def _updateBindQuery(cls): #@NoSelf
- bind = cls._bindSchema
- return cls._updateBindColumnsQuery(
- {bind.BIND_MODE: Parameter("mode"),
- bind.BIND_STATUS: Parameter("status"),
- bind.MESSAGE: Parameter("message")})
-
-
- @classproperty
def _deleteBindForResourceIDAndHomeID(cls): #@NoSelf
bind = cls._bindSchema
return Delete(
From=bind,
Where=(bind.RESOURCE_ID == Parameter("resourceID"))
.And(bind.HOME_RESOURCE_ID == Parameter("homeID")),
- Return=bind.RESOURCE_NAME,
)
@@ -2939,9 +2877,226 @@
)
+ #
+ # Higher level API
+ #
@inlineCallbacks
- def shareWith(self, shareeHome, mode, status=None, message=None):
+ def inviteUserToShare(self, shareeUID, mode, summary):
"""
+ Invite a user to share this collection - either create the share if it does not exist, or
+ update the existing share with new values. Make sure a notification is sent as well.
+
+ @param shareeUID: UID of the sharee
+ @type shareeUID: C{str}
+ @param mode: access mode
+ @type mode: C{int}
+ @param summary: share message
+ @type summary: C{str}
+ """
+
+ # Look for existing invite and update its fields or create new one
+ shareeView = yield self.shareeView(shareeUID)
+ if shareeView is not None:
+ status = _BIND_STATUS_INVITED if shareeView.shareStatus() in (_BIND_STATUS_DECLINED, _BIND_STATUS_INVALID) else None
+ yield self.updateShare(shareeView, mode=mode, status=status, summary=summary)
+ else:
+ shareeView = yield self.createShare(shareeUID=shareeUID, mode=mode, summary=summary)
+
+ # Send invite notification
+ yield self._sendInviteNotification(shareeView)
+ returnValue(shareeView)
+
+
+ @inlineCallbacks
+ def directShareWithUser(self, shareeUID):
+ """
+ Create a direct share with the specified user. Note it is currently up to the app layer
+ to enforce access control - this is not ideal as we really should have control of that in
+ the store. Once we do, this api will need to verify that access is allowed for a direct share.
+
+ NB no invitations are used with direct sharing.
+
+ @param shareeUID: UID of the sharee
+ @type shareeUID: C{str}
+ """
+
+ # Ignore if it already exists
+ shareeView = yield self.shareeView(shareeUID)
+ if shareeView is None:
+ shareeView = yield self.createShare(shareeUID=shareeUID, mode=_BIND_MODE_DIRECT)
+ yield shareeView.newShare()
+ returnValue(shareeView)
+
+
+ @inlineCallbacks
+ def uninviteUserFromShare(self, shareeUID):
+ """
+ Remove a user from a share. Make sure a notification is sent as well.
+
+ @param shareeUID: UID of the sharee
+ @type shareeUID: C{str}
+ """
+ # Cancel invites - we'll just use whatever userid we are given
+
+ shareeView = yield self.shareeView(shareeUID)
+ if shareeView is not None:
+ # If current user state is accepted then we send an invite with the new state, otherwise
+ # we cancel any existing invites for the user
+ if shareeView.shareStatus() != _BIND_STATUS_ACCEPTED:
+ yield self._removeInviteNotification(shareeView)
+ else:
+ yield self._sendInviteNotification(shareeView, notificationState=_BIND_STATUS_DELETED)
+
+ # Remove the bind
+ yield self.removeShare(shareeView)
+
+
+ @inlineCallbacks
+ def acceptShare(self, summary=None):
+ """
+ This share is being accepted.
+ """
+
+ if self.shareStatus() != _BIND_STATUS_ACCEPTED:
+ ownerView = yield self.ownerView()
+ yield ownerView.updateShare(self, status=_BIND_STATUS_ACCEPTED)
+ yield self.newShare(displayname=summary)
+ yield self._sendReplyNotification(ownerView, summary)
+
+
+ @inlineCallbacks
+ def declineShare(self):
+ """
+ This share is being declined.
+ """
+
+ if self.shareStatus() != _BIND_STATUS_DECLINED:
+ ownerView = yield self.ownerView()
+ yield ownerView.updateShare(self, status=_BIND_STATUS_DECLINED)
+ yield self._sendReplyNotification(ownerView)
+
+
+ @inlineCallbacks
+ def deleteShare(self):
+ """
+ This share is being deleted - either decline or remove (for direct shares).
+ """
+
+ ownerView = yield self.ownerView()
+ if self.direct():
+ yield ownerView.removeShare(self)
+ else:
+ yield self.declineShare()
+
+
+ def newShare(self, displayname=None):
+ """
+ Override in derived classes to do any specific operations needed when a share
+ is first accepted.
+ """
+ return succeed(None)
+
+
+ @inlineCallbacks
+ def allInvitations(self):
+ """
+ Get list of all invitations (non-direct) to this object.
+ """
+ invitations = yield self.sharingInvites()
+
+ # remove direct shares as those are not "real" invitations
+ invitations = filter(lambda x: x.mode != _BIND_MODE_DIRECT, invitations)
+ invitations.sort(key=lambda invitation: invitation.shareeUID)
+ returnValue(invitations)
+
+
+ @inlineCallbacks
+ def _sendInviteNotification(self, shareeView, notificationState=None):
+ """
+ Called on the owner's resource.
+ """
+
+ # When deleting the message is the sharee's display name
+ if notificationState == _BIND_STATUS_DELETED:
+ try:
+ displayname = str(shareeView.properties()[PropertyName.fromElement(element.DisplayName)])
+ except KeyError:
+ displayname = shareeView.name()
+ else:
+ displayname = shareeView.shareMessage()
+
+ notificationtype = {
+ "notification-type": "invite-notification",
+ "shared-type": shareeView.sharedResourceType(),
+ }
+ notificationdata = {
+ "notification-type": "invite-notification",
+ "shared-type": shareeView.sharedResourceType(),
+ "dtstamp": DateTime.getNowUTC().getText(),
+ "owner": shareeView.ownerHome().uid(),
+ "sharee": shareeView.viewerHome().uid(),
+ "uid": shareeView.shareUID(),
+ "status": shareeView.shareStatus() if notificationState is None else notificationState,
+ "access": shareeView.shareMode(),
+ "ownerName": self.shareName(),
+ "summary": displayname,
+ }
+ if hasattr(self, "getSupportedComponents"):
+ notificationdata["supported-components"] = self.getSupportedComponents()
+
+ # Add to sharee's collection
+ notifications = yield self._txn.notificationsWithUID(shareeView.viewerHome().uid())
+ yield notifications.writeNotificationObject(shareeView.shareUID(), notificationtype, notificationdata)
+
+
+ @inlineCallbacks
+ def _sendReplyNotification(self, ownerView, summary=None):
+ """
+ Create a reply notification based on the current state of this shared resource.
+ """
+
+ # Generate invite XML
+ notificationUID = "%s-reply" % (self.shareUID(),)
+
+ notificationtype = {
+ "notification-type": "invite-reply",
+ "shared-type": self.sharedResourceType(),
+ }
+
+ notificationdata = {
+ "notification-type": "invite-reply",
+ "shared-type": self.sharedResourceType(),
+ "dtstamp": DateTime.getNowUTC().getText(),
+ "owner": self.ownerHome().uid(),
+ "sharee": self.viewerHome().uid(),
+ "status": self.shareStatus(),
+ "ownerName": ownerView.shareName(),
+ "in-reply-to": self.shareUID(),
+ "summary": summary,
+ }
+
+ # Add to owner notification collection
+ notifications = yield self._txn.notificationsWithUID(self.ownerHome().uid())
+ yield notifications.writeNotificationObject(notificationUID, notificationtype, notificationdata)
+
+
+ @inlineCallbacks
+ def _removeInviteNotification(self, shareeView):
+ """
+ Called on the owner's resource.
+ """
+
+ # Remove from sharee's collection
+ notifications = yield self._txn.notificationsWithUID(shareeView.viewerHome().uid())
+ yield notifications.removeNotificationObjectWithUID(shareeView.shareUID())
+
+
+ #
+ # Lower level API
+ #
+ @inlineCallbacks
+ def shareWith(self, shareeHome, mode, status=None, summary=None):
+ """
Share this (owned) L{CommonHomeChild} with another home.
@param shareeHome: The home of the sharee.
@@ -2955,9 +3110,9 @@
L{_BIND_STATUS_ACCEPTED}
@type mode: L{str}
- @param message: The proposed message to go along with the share, which
+ @param summary: The proposed message to go along with the share, which
will be used as the default display name.
- @type mode: L{str}
+ @type summary: L{str}
@return: the name of the shared calendar in the new calendar home.
@rtype: L{str}
@@ -2968,11 +3123,11 @@
@inlineCallbacks
def doInsert(subt):
- newName = str(uuid4())
+ newName = self.newShareName()
yield self._bindInsertQuery.on(
subt, homeID=shareeHome._resourceID,
resourceID=self._resourceID, name=newName,
- mode=mode, bindStatus=status, message=message
+ mode=mode, bindStatus=status, message=summary
)
returnValue(newName)
try:
@@ -2982,16 +3137,20 @@
child = yield shareeHome.childWithID(self._resourceID)
if not child:
child = yield shareeHome.objectWithID(shareeHome, self._resourceID, accepted=False)
- bindName = yield self.updateShare(
+ yield self.updateShare(
child, mode=mode, status=status,
- message=message
+ summary=summary
)
+ bindName = child._name
else:
if status == _BIND_STATUS_ACCEPTED:
shareeView = yield shareeHome.objectWithShareUID(bindName)
yield shareeView._initSyncToken()
yield shareeView._initBindRevision()
+ # Mark this as shared
+ yield self.setShared(True)
+
# Must send notification to ensure cache invalidation occurs
yield self.notifyPropertyChanged()
yield shareeHome.notifyChanged()
@@ -3000,26 +3159,48 @@
@inlineCallbacks
- def updateShareFromSharingInvitation(self, invitation, mode=None, status=None, message=None):
+ def ownerView(self):
"""
- Like L{updateShare} except that the original invitation is provided. That is used
- to find the actual sharee L{CommonHomeChild} which is then passed to L{updateShare}.
+ Return the owner resource counterpart of this shared resource.
"""
+ # Get the child of the owner home that has the same resource id as the owned one
+ ownerView = yield self.ownerHome().childWithID(self.id())
+ returnValue(ownerView)
- # Look up the shared child - might be accepted or not. If accepted use the resource name
- # to look it up, else use the invitation uid (bind name)
- shareeHome = yield self._txn.homeWithUID(self._home._homeType, invitation.shareeUID())
- shareeView = yield shareeHome.childWithName(invitation.resourceName())
- if shareeView is None:
- shareeView = yield shareeHome.invitedObjectWithShareUID(invitation.uid())
- result = yield self.updateShare(shareeView, mode, status, message)
- returnValue(result)
+ @inlineCallbacks
+ def shareeView(self, shareeUID):
+ """
+ Return the shared resource counterpart of this owned resource for the specified sharee.
+ """
+ # Get the child of the sharee home that has the same resource id as the owned one
+ shareeHome = yield self._txn.homeWithUID(self._home._homeType, shareeUID)
+ shareeView = (yield shareeHome.allChildWithID(self.id())) if shareeHome is not None else None
+ returnValue(shareeView)
+
@inlineCallbacks
- def updateShare(self, shareeView, mode=None, status=None, message=None):
+ def createShare(self, shareeUID, mode, summary=None):
"""
+ Create a new shared resource. If the mode is direct, the share is created in accepted state,
+ otherwise the share is created in invited state.
+ """
+ shareeHome = yield self._txn.homeWithUID(self.ownerHome()._homeType, shareeUID, create=True)
+
+ yield self.shareWith(
+ shareeHome,
+ mode=mode,
+ status=_BIND_STATUS_INVITED if mode != _BIND_MODE_DIRECT else _BIND_STATUS_ACCEPTED,
+ summary=summary,
+ )
+ shareeView = yield self.shareeView(shareeUID)
+ returnValue(shareeView)
+
+
+ @inlineCallbacks
+ def updateShare(self, shareeView, mode=None, status=None, summary=None):
+ """
Update share mode, status, and message for a home child shared with
this (owned) L{CommonHomeChild}.
@@ -3035,9 +3216,9 @@
L{_BIND_STATUS_INVALID} or None to not update
@type status: L{str}
- @param message: The proposed message to go along with the share, which
+ @param summary: The proposed message to go along with the share, which
will be used as the default display name, or None to not update
- @type message: L{str}
+ @type summary: L{str}
@return: the name of the shared item in the sharee's home.
@rtype: a L{Deferred} which fires with a L{str}
@@ -3050,14 +3231,14 @@
columnMap = dict([(k, v if v != "" else None)
for k, v in {bind.BIND_MODE:mode,
bind.BIND_STATUS:status,
- bind.MESSAGE:message}.iteritems() if v is not None])
+ bind.MESSAGE:summary}.iteritems() if v is not None])
if len(columnMap):
- sharedname = yield self._updateBindColumnsQuery(columnMap).on(
- self._txn,
- resourceID=self._resourceID, homeID=shareeView._home._resourceID
- )
+ yield self._updateBindColumnsQuery(columnMap).on(
+ self._txn,
+ resourceID=self._resourceID, homeID=shareeView._home._resourceID
+ )
#update affected attributes
if mode is not None:
@@ -3075,7 +3256,7 @@
shareeView._home._children.pop(shareeView._name, None)
shareeView._home._children.pop(shareeView._resourceID, None)
- if message is not None:
+ if summary is not None:
shareeView._bindMessage = columnMap[bind.MESSAGE]
queryCacher = self._txn._queryCacher
@@ -3085,71 +3266,45 @@
cacheKey = queryCacher.keyForObjectWithResourceID(shareeView._home._resourceID, shareeView._resourceID)
yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
- shareeView._name = sharedname[0][0]
-
# Must send notification to ensure cache invalidation occurs
yield self.notifyPropertyChanged()
yield shareeView.viewerHome().notifyChanged()
- returnValue(shareeView._name)
-
@inlineCallbacks
- def unshareWithUID(self, shareeUID):
+ def removeShare(self, shareeView):
"""
- Like L{unshareWith} except this is passed a sharee UID which is then used to lookup the
- L{CommonHome} for the sharee to pass to L{unshareWith}.
- """
-
- shareeHome = yield self._txn.homeWithUID(self._home._homeType, shareeUID)
- result = yield self.unshareWith(shareeHome)
- returnValue(result)
-
-
- @inlineCallbacks
- def unshareWith(self, shareeHome):
- """
Remove the shared version of this (owned) L{CommonHomeChild} from the
referenced L{CommonHome}.
@see: L{CommonHomeChild.shareWith}
- @param shareeHome: The home with which this L{CommonHomeChild} was
- previously shared.
+ @param shareeView: The shared resource being removed.
@return: a L{Deferred} which will fire with the previous shareUID
"""
- #remove sync tokens
- shareeChildren = yield shareeHome.children()
- for shareeChild in shareeChildren:
- if not shareeChild.owned() and shareeChild._resourceID == self._resourceID:
- yield shareeChild._deletedSyncToken(sharedRemoval=True)
- shareeHome._children.pop(shareeChild._name, None)
- shareeHome._children.pop(shareeChild._resourceID, None)
- # Must send notification to ensure cache invalidation occurs
- yield self.notifyPropertyChanged()
- yield shareeHome.notifyChanged()
- break
+ # remove sync tokens
+ shareeHome = shareeView.viewerHome()
+ yield shareeView._deletedSyncToken(sharedRemoval=True)
+ shareeHome._children.pop(shareeView._name, None)
+ shareeHome._children.pop(shareeView._resourceID, None)
+ # Must send notification to ensure cache invalidation occurs
+ yield self.notifyPropertyChanged()
+ yield shareeHome.notifyChanged()
+
# delete binds including invites
- deletedBindNameRows = yield self._deleteBindForResourceIDAndHomeID.on(self._txn, resourceID=self._resourceID,
- homeID=shareeHome._resourceID)
+ yield self._deleteBindForResourceIDAndHomeID.on(self._txn, resourceID=self._resourceID, homeID=shareeHome._resourceID)
- if deletedBindNameRows:
- deletedBindName = deletedBindNameRows[0][0]
- queryCacher = self._txn._queryCacher
- if queryCacher:
- cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, shareeChild._name)
- yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
- cacheKey = queryCacher.keyForObjectWithResourceID(shareeHome._resourceID, shareeChild._resourceID)
- yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
- else:
- deletedBindName = None
+ queryCacher = self._txn._queryCacher
+ if queryCacher:
+ cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, shareeView._name)
+ yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
+ cacheKey = queryCacher.keyForObjectWithResourceID(shareeHome._resourceID, shareeView._resourceID)
+ yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
- returnValue(deletedBindName)
-
@inlineCallbacks
def unshare(self):
"""
@@ -3159,12 +3314,12 @@
# This collection may be shared to others
invites = yield self.sharingInvites()
for invite in invites:
- shareeHome = (yield self._txn.homeWithResourceID(self._home._homeType, invite.shareeHomeID()))
- (yield self.unshareWith(shareeHome))
+ shareeView = yield self.shareeView(invite.shareeUID)
+ yield self.removeShare(shareeView)
else:
# This collection is shared to me
ownerHomeChild = yield self.ownerHome().childWithID(self._resourceID)
- yield ownerHomeChild.unshareWith(self._home)
+ yield ownerHomeChild.removeShare(self)
@inlineCallbacks
@@ -3187,12 +3342,9 @@
for homeUID, homeRID, resourceID, resourceName, bindMode, bindStatus, bindMessage in acceptedRows: #@UnusedVariable
invite = SharingInvitation(
resourceName,
- self._home.name(),
- self._home._resourceID,
+ self.ownerHome().name(),
homeUID,
- homeRID,
- resourceID,
- resourceName if self.bindNameIsResourceName() else self.shareeName(),
+ resourceName,
bindMode,
bindStatus,
bindMessage,
@@ -3216,13 +3368,23 @@
yield self.invalidateQueryCache()
- def shareMode(self):
+ def sharedResourceType(self):
"""
- @see: L{ICalendar.shareMode}
+ The sharing resource type. Needs to be overridden by each type of resource that can be shared.
+
+ @return: an identifier for the type of the share.
+ @rtype: C{str}
"""
- return self._bindMode
+ return ""
+ def newShareName(self):
+ """
+ Name used when creating a new share. By default this is a UUID.
+ """
+ return str(uuid4())
+
+
def owned(self):
"""
@see: L{ICalendar.owned}
@@ -3253,8 +3415,13 @@
"""
assert self.owned()
- self._bindMessage = "shared" if shared else None
+ # Only if change is needed
+ newMessage = "shared" if shared else None
+ if self._bindMessage == newMessage:
+ returnValue(None)
+ self._bindMessage = newMessage
+
bind = self._bindSchema
yield Update(
{bind.MESSAGE: self._bindMessage},
@@ -3266,20 +3433,42 @@
yield self.notifyPropertyChanged()
- def shareeName(self):
+ def direct(self):
"""
- The sharee's name for a shared L{CommonHomeChild} is the name of the resource by default.
+ Is this a "direct" share?
+
+ @return: a boolean indicating whether it's direct.
"""
+ return self._bindMode == _BIND_MODE_DIRECT
+
+
+ def shareUID(self):
+ """
+ @see: L{ICalendar.shareUID}
+ """
return self.name()
- def bindNameIsResourceName(self):
+ def shareMode(self):
"""
- By default, the shared resource name of an accepted share is the same as the name in the bind table.
+ @see: L{ICalendar.shareMode}
"""
- return True
+ return self._bindMode
+ def shareName(self):
+ """
+ This is a path like name for the resource within the home being shared. For object resource
+ shares this will be a combination of the L{CommonHomeChild} name and the L{CommonObjecrResource}
+ name. Otherwise it is just the L{CommonHomeChild} name. This is needed to expose a value to the
+ app-layer such that it can construct a URI for the actual WebDAV resource being shared.
+ """
+ name = self.name()
+ if self.sharedResourceType() == "group":
+ name = self.parentCollection().name() + "/" + name
+ return name
+
+
def shareStatus(self):
"""
@see: L{ICalendar.shareStatus}
@@ -3294,13 +3483,6 @@
return self._bindMessage
- def shareUID(self):
- """
- @see: L{ICalendar.shareUID}
- """
- return self.name()
-
-
@classmethod
def metadataColumns(cls):
"""
@@ -3536,10 +3718,13 @@
child = cls(
home=home,
- name=bindName, resourceID=resourceID,
- mode=bindMode, status=bindStatus,
+ name=bindName,
+ resourceID=resourceID,
+ mode=bindMode,
+ status=bindStatus,
revision=bindRevision,
- message=bindMessage, ownerHome=ownerHome,
+ message=bindMessage,
+ ownerHome=ownerHome,
ownerName=ownerName,
)
for attr, value in zip(cls.additionalBindAttributes(), additionalBind):
@@ -3558,11 +3743,21 @@
@classmethod
+ def objectWithName(cls, home, name, accepted=True):
+ return cls.objectWithNameOrID(home, name=name, accepted=accepted)
+
+
+ @classmethod
+ def objectWithID(cls, home, resourceID, accepted=True):
+ return cls.objectWithNameOrID(home, resourceID=resourceID, accepted=accepted)
+
+
+ @classmethod
@inlineCallbacks
- def objectWithName(cls, home, name, accepted=True):
+ def objectWithNameOrID(cls, home, name=None, resourceID=None, accepted=True):
# replaces objectWithName()
"""
- Retrieve the child with the given C{name} contained in the given
+ Retrieve the child with the given C{name} or C{resourceID} contained in the given
C{home}.
@param home: a L{CommonHome}.
@@ -3577,97 +3772,65 @@
if queryCacher:
# Retrieve data from cache
- cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
+ if name:
+ cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
+ else:
+ cacheKey = queryCacher.keyForObjectWithResourceID(home._resourceID, resourceID)
rows = yield queryCacher.get(cacheKey)
if rows is None:
# No cached copy
- rows = yield cls._bindForNameAndHomeID.on(home._txn, name=name, homeID=home._resourceID)
+ if name:
+ rows = yield cls._bindForNameAndHomeID.on(home._txn, name=name, homeID=home._resourceID)
+ else:
+ rows = yield cls._bindForResourceIDAndHomeID.on(home._txn, resourceID=resourceID, homeID=home._resourceID)
- if rows and queryCacher:
- # Cache the result
- queryCacher.setAfterCommit(home._txn, cacheKey, rows)
- queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithResourceID(home._resourceID, rows[0][2]), rows)
-
if not rows:
returnValue(None)
row = rows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
- if (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+ bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
+
+ if queryCacher:
+ # Cache the result
+ queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithName(home._resourceID, name), rows)
+ queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithResourceID(home._resourceID, resourceID), rows)
+
+ if accepted is not None and (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
returnValue(None)
additionalBind = row[cls.bindColumnCount:cls.bindColumnCount + len(cls.additionalBindColumns())]
if bindMode == _BIND_MODE_OWN:
ownerHome = home
- ownerName = bindName
+ ownerName = name
else:
ownerHome, ownerName = yield home.ownerHomeAndChildNameForChildID(resourceID)
child = cls(
home=home,
- name=name, resourceID=resourceID,
- mode=bindMode, status=bindStatus,
+ name=name,
+ resourceID=resourceID,
+ mode=bindMode,
+ status=bindStatus,
revision=bindRevision,
- message=bindMessage, ownerHome=ownerHome,
+ message=bindMessage,
+ ownerHome=ownerHome,
ownerName=ownerName
)
yield child.initFromStore(additionalBind)
returnValue(child)
- @classmethod
- @inlineCallbacks
- def objectWithID(cls, home, resourceID, accepted=True):
- """
- Retrieve the child with the given C{resourceID} contained in the given
- C{home}.
-
- @param home: a L{CommonHome}.
- @param resourceID: a string.
- @return: an L{CommonHomeChild} or C{None} if no such child
- exists.
- """
-
- rows = None
- queryCacher = home._txn._queryCacher
-
- if queryCacher:
- # Retrieve data from cache
- cacheKey = queryCacher.keyForObjectWithResourceID(home._resourceID, resourceID)
- rows = yield queryCacher.get(cacheKey)
-
- if rows is None:
- # No cached copy
- rows = yield cls._bindForResourceIDAndHomeID.on(home._txn, resourceID=resourceID, homeID=home._resourceID)
-
- if rows and queryCacher:
- # Cache the result (under both the ID and name values)
- queryCacher.setAfterCommit(home._txn, cacheKey, rows)
- queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithName(home._resourceID, rows[0][3]), rows)
-
- if not rows:
- returnValue(None)
-
- row = rows[0]
- bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable]
- if (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
- returnValue(None)
-
- if accepted:
- returnValue((yield home.objectWithShareUID(bindName)))
- else:
- returnValue((yield home.invitedObjectWithShareUID(bindName)))
-
-
@classproperty
def _insertHomeChild(cls): #@NoSelf
"""
DAL statement to create a home child with all default values.
"""
child = cls._homeChildSchema
- return Insert({child.RESOURCE_ID: schema.RESOURCE_ID_SEQ},
- Return=(child.RESOURCE_ID))
+ return Insert(
+ {child.RESOURCE_ID: schema.RESOURCE_ID_SEQ},
+ Return=(child.RESOURCE_ID)
+ )
@classproperty
@@ -5496,14 +5659,16 @@
if inserting:
rows = yield self._newNotificationQuery.on(
self._txn, homeID=self._home._resourceID, uid=uid,
- notificationType=json.dumps(self._notificationType), notificationData=notificationtext, md5=self._md5
+ notificationType=json.dumps(self._notificationType),
+ notificationData=notificationtext, md5=self._md5
)
self._resourceID, self._created, self._modified = rows[0]
self._loadPropertyStore()
else:
rows = yield self._updateNotificationQuery.on(
self._txn, homeID=self._home._resourceID, uid=uid,
- notificationType=json.dumps(self._notificationType), notificationData=notificationtext, md5=self._md5
+ notificationType=json.dumps(self._notificationType),
+ notificationData=notificationtext, md5=self._md5
)
self._modified = rows[0][0]
self._notificationData = notificationdata
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql 2013-11-18 15:30:49 UTC (rev 11960)
@@ -101,6 +101,7 @@
insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('accepted', 1);
insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('declined', 2);
insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('invalid', 3);
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('deleted', 4);
create table CALENDAR_TRANSP (
"ID" integer primary key,
"DESCRIPTION" nvarchar2(16) unique
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql 2013-11-18 15:30:49 UTC (rev 11960)
@@ -181,6 +181,7 @@
insert into CALENDAR_BIND_STATUS values (1, 'accepted');
insert into CALENDAR_BIND_STATUS values (2, 'declined');
insert into CALENDAR_BIND_STATUS values (3, 'invalid');
+insert into CALENDAR_BIND_STATUS values (4, 'deleted');
-- Enumeration of transparency
@@ -700,7 +701,7 @@
VALUE varchar(255)
);
-insert into CALENDARSERVER values ('VERSION', '29');
+insert into CALENDARSERVER values ('VERSION', '30');
insert into CALENDARSERVER values ('CALENDAR-DATAVERSION', '5');
insert into CALENDARSERVER values ('ADDRESSBOOK-DATAVERSION', '2');
insert into CALENDARSERVER values ('NOTIFICATION-DATAVERSION', '1');
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_tables.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_tables.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_tables.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -142,6 +142,7 @@
_BIND_STATUS_ACCEPTED = _bindStatus('accepted')
_BIND_STATUS_DECLINED = _bindStatus('declined')
_BIND_STATUS_INVALID = _bindStatus('invalid')
+_BIND_STATUS_DELETED = _bindStatus('deleted')
_transpValues = _schemaConstants(
Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/test/util.py
===================================================================
--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/test/util.py 2013-11-16 05:15:04 UTC (rev 11959)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/test/util.py 2013-11-18 15:30:49 UTC (rev 11960)
@@ -707,7 +707,36 @@
.calendarObjectWithName(name)))
+ def addressbookHomeUnderTest(self, txn=None, name="home1"):
+ """
+ Get the addressbook home detailed by C{requirements['home1']}.
+ """
+ if txn is None:
+ txn = self.transactionUnderTest()
+ return txn.addressbookHomeWithUID(name)
+
+ @inlineCallbacks
+ def addressbookUnderTest(self, txn=None, name="addressbook", home="home1"):
+ """
+ Get the addressbook detailed by C{requirements['home1']['addressbook']}.
+ """
+ returnValue((yield
+ (yield self.addressbookHomeUnderTest(txn=txn, name=home)).addressbookWithName(name))
+ )
+
+
+ @inlineCallbacks
+ def addressbookObjectUnderTest(self, txn=None, name="1.vcf", addressbook_name="addressbook", home="home1"):
+ """
+ Get the addressbook detailed by
+ C{requirements['home1']['addressbook']['1.vcf']}.
+ """
+ returnValue((yield (yield self.addressbookUnderTest(txn=txn, name=addressbook_name, home=home))
+ .addressbookObjectWithName(name)))
+
+
+
class StubNotifierFactory(object):
"""
For testing push notifications without an XMPP server.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20140312/c1fee0e7/attachment.html>
More information about the calendarserver-changes
mailing list