<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[12007] CalendarServer/branches/users/cdaboo/sharing-in-the-store</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/12007">12007</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2013-11-23 13:41:29 -0800 (Sat, 23 Nov 2013)</dd>
</dl>

<h3>Log Message</h3>
<pre>Completed sharing-in-the-store refactoring.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestorecalendarserverpushtesttest_notifierpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/calendarserver/push/test/test_notifier.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretwistedcaldavsharingpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretwistedcaldavstorebridgepy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretwistedcaldavtesttest_sharingpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcaldavdatastoretesttest_sqlpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcaldavdatastoretesttest_sql_sharingpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcarddavdatastoresqlpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcarddavdatastoretesttest_sqlpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcarddavdatastoretesttest_sql_sharingpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresqlpy">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemacurrentoracledialectsql">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemacurrentsql">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemaupgradesoracledialectupgrade_from_28_to_29sql">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql</a></li>
<li><a href="#CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemaupgradespostgresdialectupgrade_from_28_to_29sql">CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServerbranchesuserscdaboosharinginthestorecalendarserverpushtesttest_notifierpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/calendarserver/push/test/test_notifier.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/calendarserver/push/test/test_notifier.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/calendarserver/push/test/test_notifier.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -171,6 +171,7 @@
</span><span class="cx">             [(&quot;/CalDAV/localhost/bar/&quot;, PushPriority.high)])
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> class NotifierFactory(StoreTestCase):
</span><span class="cx"> 
</span><span class="cx">     requirements = {
</span><span class="lines">@@ -223,27 +224,27 @@
</span><span class="cx">     def test_shareWithNotifier(self):
</span><span class="cx"> 
</span><span class="cx">         calendar = yield self.calendarUnderTest()
</span><del>-        home2 = yield self.homeUnderTest(name=&quot;home2&quot;)
-        yield calendar.shareWith(home2, _BIND_MODE_WRITE)
</del><ins>+        yield calendar.inviteUserToShare(&quot;home2&quot;, _BIND_MODE_WRITE, &quot;&quot;)
</ins><span class="cx">         self.assertEquals(
</span><span class="cx">             set(self.notifierFactory.history),
</span><span class="cx">             set([
</span><span class="cx">                 (&quot;/CalDAV/example.com/home1/&quot;, PushPriority.high),
</span><span class="cx">                 (&quot;/CalDAV/example.com/home1/calendar_1/&quot;, PushPriority.high),
</span><span class="cx">                 (&quot;/CalDAV/example.com/home2/&quot;, PushPriority.high),
</span><ins>+                (&quot;/CalDAV/example.com/home2/notification/&quot;, PushPriority.high),
</ins><span class="cx">             ])
</span><span class="cx">         )
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         calendar = yield self.calendarUnderTest()
</span><del>-        home2 = yield self.homeUnderTest(name=&quot;home2&quot;)
-        yield calendar.unshareWith(home2)
</del><ins>+        yield calendar.uninviteUserFromShare(&quot;home2&quot;)
</ins><span class="cx">         self.assertEquals(
</span><span class="cx">             set(self.notifierFactory.history),
</span><span class="cx">             set([
</span><span class="cx">                 (&quot;/CalDAV/example.com/home1/&quot;, PushPriority.high),
</span><span class="cx">                 (&quot;/CalDAV/example.com/home1/calendar_1/&quot;, PushPriority.high),
</span><span class="cx">                 (&quot;/CalDAV/example.com/home2/&quot;, PushPriority.high),
</span><ins>+                (&quot;/CalDAV/example.com/home2/notification/&quot;, PushPriority.high),
</ins><span class="cx">             ])
</span><span class="cx">         )
</span><span class="cx">         yield self.commit()
</span><span class="lines">@@ -253,8 +254,9 @@
</span><span class="cx">     def test_sharedCalendarNotifier(self):
</span><span class="cx"> 
</span><span class="cx">         calendar = yield self.calendarUnderTest()
</span><del>-        home2 = yield self.homeUnderTest(name=&quot;home2&quot;)
-        shareName = yield calendar.shareWith(home2, _BIND_MODE_WRITE)
</del><ins>+        shareeView = yield calendar.inviteUserToShare(&quot;home2&quot;, _BIND_MODE_WRITE, &quot;&quot;)
+        yield shareeView.acceptShare(&quot;&quot;)
+        shareName = shareeView.name()
</ins><span class="cx">         yield self.commit()
</span><span class="cx">         self.notifierFactory.reset()
</span><span class="cx"> 
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretwistedcaldavsharingpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/sharing.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -34,7 +34,8 @@
</span><span class="cx"> from txdav.common.datastore.sql_tables import _BIND_MODE_OWN, \
</span><span class="cx">     _BIND_MODE_READ, _BIND_MODE_WRITE, _BIND_STATUS_INVITED, \
</span><span class="cx">     _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, \
</span><del>-    _BIND_STATUS_INVALID, _ABO_KIND_GROUP, _BIND_STATUS_DELETED
</del><ins>+    _BIND_STATUS_INVALID, _ABO_KIND_GROUP, _BIND_STATUS_DELETED, \
+    _BIND_MODE_DIRECT, _BIND_MODE_INDIRECT
</ins><span class="cx"> from txdav.xml import element
</span><span class="cx"> 
</span><span class="cx"> from twisted.internet.defer import succeed, inlineCallbacks, DeferredList, \
</span><span class="lines">@@ -235,7 +236,8 @@
</span><span class="cx">         return (
</span><span class="cx">             hasattr(self, &quot;_newStoreObject&quot;) and
</span><span class="cx">             hasattr(self._newStoreObject, &quot;owned&quot;) and
</span><del>-            not self._newStoreObject.owned()
</del><ins>+            not self._newStoreObject.owned() and
+            getattr(self._newStoreObject, &quot;_bindMode&quot;, None) is not None
</ins><span class="cx">         )
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="lines">@@ -764,12 +766,13 @@
</span><span class="cx"> }
</span><span class="cx"> invitationBindModeFromXMLMap = dict((v, k) for k, v in invitationBindModeToXMLMap.iteritems())
</span><span class="cx"> 
</span><del>-invitationAccessToBindModeMap = {
-    &quot;own&quot;: _BIND_MODE_OWN,
-    &quot;read-only&quot;: _BIND_MODE_READ,
-    &quot;read-write&quot;: _BIND_MODE_WRITE,
-    }
-invitationAccessFromBindModeMap = dict((v, k) for k, v in invitationAccessToBindModeMap.iteritems())
</del><ins>+invitationAccessFromBindModeMap = {
+    _BIND_MODE_OWN: &quot;own&quot;,
+    _BIND_MODE_READ: &quot;read-only&quot;,
+    _BIND_MODE_WRITE: &quot;read-write&quot;,
+    _BIND_MODE_DIRECT: &quot;read-write&quot;,
+    _BIND_MODE_INDIRECT: &quot;read-write&quot;,
+}
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> class SharedHomeMixin(LinkFollowerMixIn):
</span><span class="lines">@@ -804,7 +807,7 @@
</span><span class="cx">         shareeView = yield self._newStoreHome.acceptShare(inviteUID, summary)
</span><span class="cx"> 
</span><span class="cx">         # Return the URL of the shared collection
</span><del>-        sharedAsURL = joinURL(self.url(), shareeView.name())
</del><ins>+        sharedAsURL = joinURL(self.url(), shareeView.shareName())
</ins><span class="cx">         returnValue(XMLResponse(
</span><span class="cx">             code=responsecode.OK,
</span><span class="cx">             element=customxml.SharedAs(
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretwistedcaldavstorebridgepy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/storebridge.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -3116,23 +3116,6 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def storeRemove(self, request):
-        &quot;&quot;&quot;
-        handle remove of partially shared addressbook, else call super
-        &quot;&quot;&quot;
-        if self.isShareeResource() and self._newStoreObject.shareUID() is None:
-            log.debug(&quot;Removing shared collection %s&quot; % (self,))
-            for childname in (yield self.listChildren()):
-                child = (yield request.locateChildResource(self, childname))
-                if child.isShareeResource():
-                    yield child.storeRemove(request)
-
-            returnValue(NO_CONTENT)
-
-        returnValue((yield super(AddressBookCollectionResource, self).storeRemove(request)))
-
-
-    @inlineCallbacks
</del><span class="cx">     def bulkCreate(self, indexedComponents, request, return_changed, xmlresponses, format):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         bulk create allowing groups to contain member UIDs added during the same bulk create
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretwistedcaldavtesttest_sharingpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/twistedcaldav/test/test_sharing.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -19,7 +19,7 @@
</span><span class="cx"> from twext.web2.http_headers import MimeType
</span><span class="cx"> from twext.web2.iweb import IResponse
</span><span class="cx"> 
</span><del>-from twisted.internet.defer import inlineCallbacks, returnValue, succeed
</del><ins>+from twisted.internet.defer import inlineCallbacks, returnValue
</ins><span class="cx"> 
</span><span class="cx"> from twistedcaldav import customxml
</span><span class="cx"> from twistedcaldav import sharing
</span><span class="lines">@@ -104,6 +104,10 @@
</span><span class="cx">         returnValue(b)
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    def calendarHomeURLs(self):
+        return (self.homepath,)
+
+
</ins><span class="cx">     def principalURL(self):
</span><span class="cx">         return self.path
</span><span class="cx"> 
</span><span class="lines">@@ -141,22 +145,6 @@
</span><span class="cx">             return c
</span><span class="cx"> 
</span><span class="cx">         @patched
</span><del>-        def sendInviteNotification(resourceSelf, record, request):
-            &quot;&quot;&quot;
-            For testing purposes, sending an invite notification succeeds
-            without doing anything.
-            &quot;&quot;&quot;
-            return succeed(True)
-
-        @patched
-        def removeInviteNotification(resourceSelf, record, request):
-            &quot;&quot;&quot;
-            For testing purposes, removing an invite notification succeeds
-            without doing anything.
-            &quot;&quot;&quot;
-            return succeed(True)
-
-        @patched
</del><span class="cx">         def principalForCalendarUserAddress(resourceSelf, cuaddr):
</span><span class="cx">             if &quot;bogus&quot; in cuaddr:
</span><span class="cx">                 return None
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcaldavdatastoretesttest_sqlpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -51,7 +51,7 @@
</span><span class="cx"> 
</span><span class="cx"> from txdav.base.propertystore.base import PropertyName
</span><span class="cx"> from txdav.caldav.datastore.test.common import CommonTests as CalendarCommonTests, \
</span><del>-    test_event_text, OTHER_HOME_UID
</del><ins>+    test_event_text
</ins><span class="cx"> from txdav.caldav.datastore.test.test_file import setUpCalendarStore
</span><span class="cx"> from txdav.caldav.datastore.test.util import buildCalendarStore
</span><span class="cx"> from txdav.caldav.datastore.util import _migrateCalendar, migrateHome
</span><span class="lines">@@ -59,7 +59,7 @@
</span><span class="cx"> from txdav.common.datastore.sql import ECALENDARTYPE, CommonObjectResource
</span><span class="cx"> from txdav.common.datastore.sql_legacy import PostgresLegacyIndexEmulator
</span><span class="cx"> from txdav.common.datastore.sql_tables import schema, _BIND_MODE_DIRECT, \
</span><del>-    _BIND_STATUS_ACCEPTED, _BIND_MODE_WRITE, _BIND_STATUS_INVITED
</del><ins>+    _BIND_STATUS_ACCEPTED
</ins><span class="cx"> from txdav.common.datastore.test.util import populateCalendarsFrom, \
</span><span class="cx">     CommonCommonTests
</span><span class="cx"> from txdav.common.icommondatastore import NoSuchObjectResourceError
</span><span class="lines">@@ -952,13 +952,13 @@
</span><span class="cx"> 
</span><span class="cx">         @inlineCallbacks
</span><span class="cx">         def _defer1():
</span><del>-            yield cal1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary=&quot;Shared Wiki Calendar&quot;)
</del><ins>+            yield cal1.directShareWithUser(&quot;uid2&quot;)
</ins><span class="cx">             yield txn1.commit()
</span><span class="cx">         d1 = _defer1()
</span><span class="cx"> 
</span><span class="cx">         @inlineCallbacks
</span><span class="cx">         def _defer2():
</span><del>-            yield cal2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary=&quot;Shared Wiki Calendar&quot;)
</del><ins>+            yield cal2.directShareWithUser(&quot;uid1&quot;)
</ins><span class="cx">             yield txn2.commit()
</span><span class="cx">         d2 = _defer2()
</span><span class="cx"> 
</span><span class="lines">@@ -1708,90 +1708,6 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def test_shareWithRevision(self):
-        &quot;&quot;&quot;
-        Verify that bindRevision on calendars and shared calendars has the correct value.
-        &quot;&quot;&quot;
-        cal = yield self.calendarUnderTest()
-        self.assertEqual(cal._bindRevision, 0)
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        newCalName = yield cal.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalCal = yield self.calendarUnderTest()
-        self.assertEqual(normalCal._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield otherHome.childWithName(newCalName)
-        self.assertNotEqual(otherCal._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_updateShareRevision(self):
-        &quot;&quot;&quot;
-        Verify that bindRevision on calendars and shared calendars has the correct value.
-        &quot;&quot;&quot;
-        cal = yield self.calendarUnderTest()
-        self.assertEqual(cal._bindRevision, 0)
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        newCalName = yield cal.shareWith(other, _BIND_MODE_WRITE, status=_BIND_STATUS_INVITED)
-        yield self.commit()
-
-        normalCal = yield self.calendarUnderTest()
-        self.assertEqual(normalCal._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield otherHome.invitedObjectWithShareUID(newCalName)
-        self.assertEqual(otherCal._bindRevision, 0)
-        yield self.commit()
-
-        normalCal = yield self.calendarUnderTest()
-        otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield otherHome.invitedObjectWithShareUID(newCalName)
-        yield normalCal.updateShare(otherCal, status=_BIND_STATUS_ACCEPTED)
-        yield self.commit()
-
-        normalCal = yield self.calendarUnderTest()
-        self.assertEqual(normalCal._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield otherHome.childWithName(newCalName)
-        self.assertNotEqual(otherCal._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_sharedRevisions(self):
-        &quot;&quot;&quot;
-        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
-        &quot;&quot;&quot;
-        cal = yield self.calendarUnderTest()
-        self.assertEqual(cal._bindRevision, 0)
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        newCalName = yield cal.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalCal = yield self.calendarUnderTest()
-        self.assertEqual(normalCal._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield otherHome.childWithName(newCalName)
-        self.assertNotEqual(otherCal._bindRevision, 0)
-
-        changed, deleted = yield otherCal.resourceNamesSinceRevision(otherCal._bindRevision - 1)
-        self.assertNotEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        changed, deleted = yield otherCal.resourceNamesSinceRevision(otherCal._bindRevision)
-        self.assertEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        for depth in (&quot;1&quot;, &quot;infinity&quot;,):
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherCal._bindRevision - 1, depth)
-            self.assertNotEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherCal._bindRevision, depth)
-            self.assertEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-
-    @inlineCallbacks
</del><span class="cx">     def test_setAvailability(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Make sure a L{CalendarHome}.setAvailability() works.
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcaldavdatastoretesttest_sql_sharingpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/caldav/datastore/test/test_sql_sharing.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -26,14 +26,14 @@
</span><span class="cx">     _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-class CalendarSharing(CommonCommonTests, TestCase):
</del><ins>+class BaseSharingTests(CommonCommonTests, TestCase):
</ins><span class="cx">     &quot;&quot;&quot;
</span><del>-    Test twistedcaldav.scheduyling.implicit with a Request object.
</del><ins>+    Test store-based calendar sharing.
</ins><span class="cx">     &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def setUp(self):
</span><del>-        yield super(CalendarSharing, self).setUp()
</del><ins>+        yield super(BaseSharingTests, self).setUp()
</ins><span class="cx">         self._sqlCalendarStore = yield buildCalendarStore(self, self.notifierFactory)
</span><span class="cx">         yield self.populate()
</span><span class="cx"> 
</span><span class="lines">@@ -43,12 +43,27 @@
</span><span class="cx">         yield populateCalendarsFrom(self.requirements, self.storeUnderTest())
</span><span class="cx">         self.notifierFactory.reset()
</span><span class="cx"> 
</span><ins>+    cal1 = &quot;&quot;&quot;BEGIN:VCALENDAR
+VERSION:2.0
+CALSCALE:GREGORIAN
+PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
+BEGIN:VEVENT
+UID:uid1
+DTSTART:20131122T140000
+DURATION:PT1H
+CREATED:20060102T190000Z
+DTSTAMP:20051222T210507Z
+SUMMARY:event 1
+END:VEVENT
+END:VCALENDAR
+&quot;&quot;&quot;
</ins><span class="cx"> 
</span><span class="cx">     @classproperty(cache=False)
</span><span class="cx">     def requirements(cls): #@NoSelf
</span><span class="cx">         return {
</span><span class="cx">         &quot;user01&quot;: {
</span><span class="cx">             &quot;calendar&quot;: {
</span><ins>+                &quot;cal1.ics&quot;: (cls.cal1, None,),
</ins><span class="cx">             },
</span><span class="cx">             &quot;inbox&quot;: {
</span><span class="cx">             },
</span><span class="lines">@@ -95,6 +110,9 @@
</span><span class="cx">         returnValue(sharedName)
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
+class CalendarSharing(BaseSharingTests):
+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_no_shares(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -104,6 +122,7 @@
</span><span class="cx">         calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(calendar.isShared())
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -116,6 +135,7 @@
</span><span class="cx">         calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(calendar.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield calendar.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="lines">@@ -123,7 +143,6 @@
</span><span class="cx">         self.assertEqual(invites[0].uid, shareeView.shareUID())
</span><span class="cx">         self.assertEqual(invites[0].ownerUID, &quot;user01&quot;)
</span><span class="cx">         self.assertEqual(invites[0].shareeUID, &quot;user02&quot;)
</span><del>-        self.assertEqual(invites[0].shareeName, shareeView.name())
</del><span class="cx">         self.assertEqual(invites[0].mode, _BIND_MODE_READ)
</span><span class="cx">         self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
</span><span class="cx">         self.assertEqual(invites[0].summary, &quot;summary&quot;)
</span><span class="lines">@@ -137,6 +156,8 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID, ])
</span><span class="cx"> 
</span><ins>+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Uninvite
</span><span class="lines">@@ -152,7 +173,16 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [])
</span><span class="cx"> 
</span><ins>+        self.assertTrue(calendar.isShared())
</ins><span class="cx"> 
</span><ins>+        yield self.commit()
+
+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
+        yield calendar.setShared(False)
+        self.assertFalse(calendar.isShared())
+
+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_accept_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -163,6 +193,7 @@
</span><span class="cx">         calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(calendar.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield calendar.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="lines">@@ -177,6 +208,8 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(len(notifications), 1)
</span><span class="cx"> 
</span><ins>+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Accept
</span><span class="lines">@@ -190,6 +223,9 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</span><span class="cx"> 
</span><ins>+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Re-accept
</span><span class="lines">@@ -203,17 +239,21 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</span><span class="cx"> 
</span><ins>+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_decline_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><del>-        Test that invite+accept creates shares and notifications.
</del><ins>+        Test that invite+decline does not create shares but does create notifications.
</ins><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">         # Invite
</span><span class="cx">         calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(calendar.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield calendar.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="lines">@@ -228,6 +268,8 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(len(notifications), 1)
</span><span class="cx"> 
</span><ins>+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Decline
</span><span class="lines">@@ -241,6 +283,9 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</span><span class="cx"> 
</span><ins>+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Redecline
</span><span class="lines">@@ -254,7 +299,10 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</span><span class="cx"> 
</span><ins>+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_accept_decline_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -266,6 +314,7 @@
</span><span class="cx">         calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(calendar.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield calendar.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="lines">@@ -280,6 +329,8 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(len(notifications), 1)
</span><span class="cx"> 
</span><ins>+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Accept
</span><span class="lines">@@ -293,6 +344,9 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</span><span class="cx"> 
</span><ins>+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Decline
</span><span class="lines">@@ -306,7 +360,10 @@
</span><span class="cx">         notifications = yield notifyHome.listNotificationObjects()
</span><span class="cx">         self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</span><span class="cx"> 
</span><ins>+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertTrue(calendar.isShared())
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_accept_remove_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -382,6 +439,7 @@
</span><span class="cx">         calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(calendar.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield calendar.directShareWithUser(&quot;user02&quot;)
</span><span class="cx">         invites = yield calendar.sharingInvites()
</span><span class="lines">@@ -389,7 +447,6 @@
</span><span class="cx">         self.assertEqual(invites[0].uid, shareeView.shareUID())
</span><span class="cx">         self.assertEqual(invites[0].ownerUID, &quot;user01&quot;)
</span><span class="cx">         self.assertEqual(invites[0].shareeUID, &quot;user02&quot;)
</span><del>-        self.assertEqual(invites[0].shareeName, shareeView.name())
</del><span class="cx">         self.assertEqual(invites[0].mode, _BIND_MODE_DIRECT)
</span><span class="cx">         self.assertEqual(invites[0].status, _BIND_STATUS_ACCEPTED)
</span><span class="cx"> 
</span><span class="lines">@@ -431,3 +488,85 @@
</span><span class="cx">         calendar = yield home.calendarWithName(shared_name)
</span><span class="cx">         self.assertEquals(calendar.notifierID(), (&quot;CalDAV&quot;, &quot;user01/calendar&quot;,))
</span><span class="cx">         yield self.commit()
</span><ins>+
+
+
+class SharingRevisions(BaseSharingTests):
+    &quot;&quot;&quot;
+    Test store-based sharing and interaction with revision table.
+    &quot;&quot;&quot;
+
+    @inlineCallbacks
+    def test_shareWithRevision(self):
+        &quot;&quot;&quot;
+        Verify that bindRevision on calendars and shared calendars has the correct value.
+        &quot;&quot;&quot;
+        sharedName = yield self._createShare()
+
+        normalCal = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherCal = yield self.calendarUnderTest(home=&quot;user02&quot;, name=sharedName)
+        self.assertNotEqual(otherCal._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_updateShareRevision(self):
+        &quot;&quot;&quot;
+        Verify that bindRevision on calendars and shared calendars has the correct value.
+        &quot;&quot;&quot;
+        # Invite
+        calendar = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield calendar.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
+        newCalName = shareeView.shareUID()
+        yield self.commit()
+
+        normalCal = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherHome = yield self.homeUnderTest(name=&quot;user02&quot;)
+        otherCal = yield otherHome.anyObjectWithShareUID(newCalName)
+        self.assertEqual(otherCal._bindRevision, 0)
+        yield self.commit()
+
+        shareeHome = yield self.homeUnderTest(name=&quot;user02&quot;)
+        shareeView = yield shareeHome.acceptShare(newCalName)
+        sharedName = shareeView.name()
+        yield self.commit()
+
+        normalCal = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherCal = yield self.calendarUnderTest(home=&quot;user02&quot;, name=sharedName)
+        self.assertNotEqual(otherCal._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_sharedRevisions(self):
+        &quot;&quot;&quot;
+        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
+        &quot;&quot;&quot;
+        sharedName = yield self._createShare()
+
+        normalCal = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherHome = yield self.homeUnderTest(name=&quot;user02&quot;)
+        otherCal = yield self.calendarUnderTest(home=&quot;user02&quot;, name=sharedName)
+        self.assertNotEqual(otherCal._bindRevision, 0)
+
+        changed, deleted = yield otherCal.resourceNamesSinceRevision(otherCal._bindRevision - 1)
+        self.assertNotEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        changed, deleted = yield otherCal.resourceNamesSinceRevision(otherCal._bindRevision)
+        self.assertEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        for depth in (&quot;1&quot;, &quot;infinity&quot;,):
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherCal._bindRevision - 1, depth)
+            self.assertNotEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
+
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherCal._bindRevision, depth)
+            self.assertEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
</ins></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcarddavdatastoresqlpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/sql.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -14,6 +14,7 @@
</span><span class="cx"> # See the License for the specific language governing permissions and
</span><span class="cx"> # limitations under the License.
</span><span class="cx"> # #
</span><ins>+from txdav.xml import element
</ins><span class="cx"> 
</span><span class="cx"> &quot;&quot;&quot;
</span><span class="cx"> SQL backend for CardDAV storage.
</span><span class="lines">@@ -41,8 +42,8 @@
</span><span class="cx"> from twistedcaldav import carddavxml, customxml
</span><span class="cx"> from twistedcaldav.config import config
</span><span class="cx"> from twistedcaldav.memcacher import Memcacher
</span><del>-from twistedcaldav.vcard import Component as VCard, InvalidVCardDataError, \
-    vCardProductID, Property
</del><ins>+from twistedcaldav.vcard import Component as VCard, InvalidVCardDataError, Property, \
+    vCardProductID
</ins><span class="cx"> 
</span><span class="cx"> from txdav.base.propertystore.base import PropertyName
</span><span class="cx"> from txdav.base.propertystore.sql import PropertyStore
</span><span class="lines">@@ -55,7 +56,8 @@
</span><span class="cx"> from txdav.common.datastore.sql_tables import _ABO_KIND_PERSON, \
</span><span class="cx">     _ABO_KIND_GROUP, _ABO_KIND_RESOURCE, _ABO_KIND_LOCATION, schema, \
</span><span class="cx">     _BIND_MODE_OWN, _BIND_MODE_WRITE, _BIND_STATUS_ACCEPTED, \
</span><del>-    _BIND_STATUS_DECLINED, _BIND_STATUS_INVITED, _BIND_MODE_READ
</del><ins>+    _BIND_STATUS_INVITED, _BIND_MODE_READ, _BIND_MODE_INDIRECT, \
+    _BIND_STATUS_DECLINED
</ins><span class="cx"> from txdav.common.icommondatastore import InternalDataStoreError, \
</span><span class="cx">     InvalidUIDError, UIDExistsError, ObjectResourceTooBigError, \
</span><span class="cx">     InvalidObjectResourceError, InvalidComponentForStoreError, \
</span><span class="lines">@@ -141,8 +143,7 @@
</span><span class="cx"> 
</span><span class="cx">         result = yield super(AddressBookHome, self).initFromStore(no_cache)
</span><span class="cx">         if result is not None:
</span><del>-
-            # created owned address book
</del><ins>+            # Created owned address book
</ins><span class="cx">             addressbook = AddressBook(
</span><span class="cx">                 home=self,
</span><span class="cx">                 name=&quot;addressbook&quot;,
</span><span class="lines">@@ -151,6 +152,12 @@
</span><span class="cx">                 status=_BIND_STATUS_ACCEPTED,
</span><span class="cx">             )
</span><span class="cx">             yield addressbook._loadPropertyStore()
</span><ins>+
+            # Extra check for shared
+            invites = yield addressbook.sharingInvites()
+            if len(invites) != 0:
+                addressbook._bindMessage = &quot;shared&quot;
+
</ins><span class="cx">             self._addressbook = addressbook
</span><span class="cx"> 
</span><span class="cx">         returnValue(result)
</span><span class="lines">@@ -194,6 +201,22 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><ins>+    def anyObjectWithShareUID(self, shareUID):
+        &quot;&quot;&quot;
+        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.
+        &quot;&quot;&quot;
+        result = yield super(AddressBookHome, self).anyObjectWithShareUID(shareUID)
+        if result is None:
+            result = yield AddressBookObject.objectWithBindName(self, shareUID, accepted=None)
+
+        returnValue(result)
+
+
+    @inlineCallbacks
</ins><span class="cx">     def removeUnacceptedShares(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Unbinds any collections that have been shared to this home but not yet
</span><span class="lines">@@ -323,6 +346,31 @@
</span><span class="cx">         return &quot;addressbook&quot;
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    @inlineCallbacks
+    def deleteShare(self):
+        &quot;&quot;&quot;
+        This share is being deleted - decline and decline shared groups too.
+        &quot;&quot;&quot;
+
+        ownerView = yield self.ownerView()
+        if self.direct():
+            yield ownerView.removeShare(self)
+        else:
+            if self.fullyShared():
+                yield self.declineShare()
+            else:
+                # Decline each shared group
+                acceptedGroupIDs = yield self.acceptedGroupIDs()
+                if acceptedGroupIDs:
+                    rows = (yield self._objectResourceNamesWithResourceIDsQuery(acceptedGroupIDs).on(
+                        self._txn, resourceIDs=acceptedGroupIDs
+                    ))
+                    groupNames = sorted([row[0] for row in rows])
+                    for group in groupNames:
+                        groupObject = yield self.objectResourceWithName(group)
+                        yield groupObject.declineShare()
+
+
</ins><span class="cx">     def newShareName(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         For shared address books the resource name of a share is the ownerUID of the owner's resource.
</span><span class="lines">@@ -330,158 +378,52 @@
</span><span class="cx">         return self.ownerHome().uid()
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-#    @inlineCallbacks
-#    def updateShare(self, shareeView, mode=None, status=None, summary=None):
-#        &quot;&quot;&quot;
-#        Update share mode, status, and message for a home child shared with
-#        this (owned) L{CommonHomeChild}.
-#
-#        @param shareeView: The sharee home child that shares this.
-#        @type shareeView: L{CommonHomeChild}
-#
-#        @param mode: The sharing mode; L{_BIND_MODE_READ} or
-#            L{_BIND_MODE_WRITE} or None to not update
-#        @type mode: L{str}
-#
-#        @param status: The sharing status; L{_BIND_STATUS_INVITED} or
-#            L{_BIND_STATUS_ACCEPTED} or L{_BIND_STATUS_DECLINED} or
-#            L{_BIND_STATUS_INVALID}  or None to not update
-#        @type status: L{str}
-#
-#        @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 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}
-#        &quot;&quot;&quot;
-#        # TODO: raise a nice exception if shareeView is not, in fact, a shared
-#        # version of this same L{CommonHomeChild}
-#
-#        # remove None parameters, and substitute None for empty string
-#        bind = self._bindSchema
-#        columnMap = dict([(k, v if v != &quot;&quot; else None)
-#                          for k, v in {bind.BIND_MODE:mode,
-#                            bind.BIND_STATUS:status,
-#                            bind.MESSAGE:summary}.iteritems() if v is not None])
-#
-#        if len(columnMap):
-#
-#            # count accepted
-#            if status is not None:
-#                previouslyAcceptedBindCount = 1 if not shareeView.indirect() else 0
-#                previouslyAcceptedBindCount += len((yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-#                        self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=shareeView._resourceID
-#                )))
-#
-#            yield self._updateBindColumnsQuery(columnMap).on(
-#                self._txn,
-#                resourceID=self._resourceID, homeID=shareeView.viewerHome()._resourceID
-#            )
-#
-#            # update affected attributes
-#            if mode is not None:
-#                shareeView._bindMode = columnMap[bind.BIND_MODE]
-#
-#            if status is not None:
-#                shareeView._bindStatus = columnMap[bind.BIND_STATUS]
-#                if shareeView._bindStatus == _BIND_STATUS_ACCEPTED:
-#                    if 0 == previouslyAcceptedBindCount:
-#                        yield shareeView._initSyncToken()
-#                        yield shareeView._initBindRevision()
-#                        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(shareeView._name, None)
-#                        shareeView.viewerHome()._children.pop(shareeView._resourceID, None)
-#
-#            if summary is not None:
-#                shareeView._bindMessage = columnMap[bind.MESSAGE]
-#
-#            queryCacher = self._txn._queryCacher
-#            if queryCacher:
-#                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)
-#
-#            # Must send notification to ensure cache invalidation occurs
-#            yield self.notifyPropertyChanged()
</del><ins>+    @inlineCallbacks
+    def newShare(self, displayname=None):
+        &quot;&quot;&quot;
+        Override in derived classes to do any specific operations needed when a share
+        is first accepted.
+        &quot;&quot;&quot;
</ins><span class="cx"> 
</span><ins>+        # For a direct share we will copy any displayname 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
</ins><span class="cx"> 
</span><del>-#    @inlineCallbacks
-#    def unshareWith(self, shareeHome):
-#        &quot;&quot;&quot;
-#        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.
-#
-#        @return: a L{Deferred} which will fire with the previous shareUID
-#        &quot;&quot;&quot;
-#        sharedAddressBook = yield shareeHome.addressbookWithName(self.name())
-#        if sharedAddressBook:
-#
-#            acceptedBindCount = 1 if not sharedAddressBook.indirect() else 0
-#            acceptedBindCount += len((yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-#                    self._txn, homeID=shareeHome._resourceID, addressbookID=sharedAddressBook._resourceID
-#            )))
-#            if acceptedBindCount == 1:
-#                yield sharedAddressBook._deletedSyncToken(sharedRemoval=True)
-#                shareeHome._children.pop(self.name(), None)
-#                shareeHome._children.pop(sharedAddressBook._resourceID, None)
-#            elif sharedAddressBook.indirect():
-#                # FIXME: remove objects for this group only using self.removeObjectResource
-#                self._objectNames = None
-#
-#            # Must send notification to ensure cache invalidation occurs
-#            yield self.notifyPropertyChanged()
-#
-#        # delete binds including invites
-#        deletedBindNameRows = 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, self.name())
-#                queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-#        else:
-#            deletedBindName = None
-#
-#        self._initIsShared()
-#        returnValue(deletedBindName)
</del><span class="cx"> 
</span><ins>+    def fullyShared(self):
+        return not self.owned() and not self.indirect() and self.accepted()
</ins><span class="cx"> 
</span><del>-#    @inlineCallbacks
-#    def _isSharedOrInvited(self):
-#        &quot;&quot;&quot;
-#        return True if this L{AddressBook} is shared or invited
-#        &quot;&quot;&quot;
-#        sharedRows = []
-#        if self.owned():
-#            bind = self._bindSchema
-#            sharedRows = yield self._bindFor(
-#                (bind.RESOURCE_ID == Parameter(&quot;resourceID&quot;))).on(
-#                self._txn, resourceID=self._resourceID,
-#            )
-#
-#        returnValue(bool(sharedRows))
-#
-#
-#    @inlineCallbacks
-#    def _initIsShared(self):
-#        isShared = yield self._isSharedOrInvited()
-#        self.setShared(isShared)
</del><span class="cx"> 
</span><ins>+    @inlineCallbacks
+    def _previousAcceptCount(self):
+        previouslyAcceptedBindCount = 1 if self.fullyShared() else 0
+        previouslyAcceptedBindCount += len((yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
+            self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
+        )))
+        returnValue(previouslyAcceptedBindCount)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    @inlineCallbacks
+    def _changedStatus(self, previouslyAcceptedCount):
+        if self._bindStatus == _BIND_STATUS_ACCEPTED:
+            if 0 == previouslyAcceptedCount:
+                yield self._initSyncToken()
+                yield self._initBindRevision()
+                self._home._children[self._name] = self
+                self._home._children[self._resourceID] = self
+        elif self._bindStatus == _BIND_STATUS_DECLINED:
+            if 1 == previouslyAcceptedCount:
+                yield self._deletedSyncToken(sharedRemoval=True)
+                self._home._children.pop(self._name, None)
+                self._home._children.pop(self._resourceID, None)
+
+
+
</ins><span class="cx"> class AddressBook(AddressBookSharingMixIn, CommonHomeChild):
</span><span class="cx">     &quot;&quot;&quot;
</span><span class="cx">     SQL-based implementation of L{IAddressBook}.
</span><span class="lines">@@ -512,7 +454,8 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     def setCreated(self, newValue):
</span><del>-        self.ownerHome()._created = newValue
</del><ins>+        if newValue is not None:
+            self.ownerHome()._created = newValue
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     def getModified(self):
</span><span class="lines">@@ -520,21 +463,13 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     def setModified(self, newValue):
</span><del>-        self.ownerHome()._modified = newValue
</del><ins>+        if newValue is not None:
+            self.ownerHome()._modified = newValue
</ins><span class="cx"> 
</span><span class="cx">     _created = property(getCreated, setCreated,)
</span><span class="cx">     _modified = property(getModified, setModified,)
</span><span class="cx"> 
</span><del>-    ownerAddressBookHome = CommonHomeChild.ownerHome
-    viewerAddressBookHome = CommonHomeChild.viewerHome
-    addressbookObjects = CommonHomeChild.objectResources
-    listAddressBookObjects = CommonHomeChild.listObjectResources
-    addressbookObjectWithName = CommonHomeChild.objectResourceWithName
-    addressbookObjectWithUID = CommonHomeChild.objectResourceWithUID
-    createAddressBookObjectWithName = CommonHomeChild.createObjectResourceWithName
-    addressbookObjectsSinceToken = CommonHomeChild.objectResourcesSinceToken
</del><span class="cx"> 
</span><del>-
</del><span class="cx">     @inlineCallbacks
</span><span class="cx">     def _loadPropertyStore(self, props=None):
</span><span class="cx">         if props is None:
</span><span class="lines">@@ -618,44 +553,44 @@
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def listObjectResources(self):
</span><del>-        # Check for non-group shared
-        if self.owned() or not self.indirect():
-            result = yield super(AddressBook, self).listObjectResources()
-            returnValue(result)
-
-        # Group shared
</del><span class="cx">         if self._objectNames is None:
</span><del>-            acceptedGroupIDs = yield self.acceptedGroupIDs()
-            allowedObjectIDs = yield self.expandGroupIDs(self._txn, acceptedGroupIDs)
-            rows = (yield self._objectResourceNamesWithResourceIDsQuery(allowedObjectIDs).on(
-                self._txn, resourceIDs=allowedObjectIDs
-            ))
-            objectNames = [row[0] for row in rows]
</del><ins>+            # Check for non-group shared
+            if self.owned() or self.fullyShared():
+                yield super(AddressBook, self).listObjectResources()
</ins><span class="cx"> 
</span><del>-            # account for fully-shared address book group
-            if not self.indirect():
-                if not self._groupForSharedAddressBookName() in objectNames:
-                    objectNames.append(self._groupForSharedAddressBookName())
-            self._objectNames = sorted(objectNames)
</del><ins>+            # Group shared
+            else:
+                acceptedGroupIDs = yield self.acceptedGroupIDs()
+                allowedObjectIDs = yield self.expandGroupIDs(self._txn, acceptedGroupIDs)
+                rows = (yield self._objectResourceNamesWithResourceIDsQuery(allowedObjectIDs).on(
+                    self._txn, resourceIDs=allowedObjectIDs
+                ))
+                self._objectNames = sorted([row[0] for row in rows])
</ins><span class="cx"> 
</span><ins>+            # Account for fully-shared address book group
+            if self.fullyShared():
+                if not self._groupForSharedAddressBookName() in self._objectNames:
+                    self._objectNames.append(self._groupForSharedAddressBookName())
+
</ins><span class="cx">         returnValue(self._objectNames)
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def countObjectResources(self):
</span><del>-        # Check for non-group shared
-        if self.owned() or not self.indirect():
-            result = yield super(AddressBook, self).countObjectResources()
-            returnValue(result)
-
-        # Group shared
</del><span class="cx">         if self._objectNames is None:
</span><del>-            acceptedGroupIDs = yield self.acceptedGroupIDs()
-            count = len((yield self.expandGroupIDs(self._txn, acceptedGroupIDs)))
</del><ins>+            # Check for non-group shared
+            if self.owned() or self.fullyShared():
+                count = yield super(AddressBook, self).countObjectResources()
</ins><span class="cx"> 
</span><del>-            # account for fully-shared address book group
-            if not self.indirect():
</del><ins>+            # Group shared
+            else:
+                acceptedGroupIDs = yield self.acceptedGroupIDs()
+                count = len((yield self.expandGroupIDs(self._txn, acceptedGroupIDs)))
+
+            # Account for fully-shared address book group
+            if self.fullyShared():
</ins><span class="cx">                 count += 1
</span><ins>+
</ins><span class="cx">             returnValue(count)
</span><span class="cx"> 
</span><span class="cx">         returnValue(len(self._objectNames))
</span><span class="lines">@@ -696,7 +631,7 @@
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def _groupForSharedAddressBookComponent(self):
</span><span class="cx"> 
</span><del>-        n = self.name()
</del><ins>+        n = self.viewerHome().uid()
</ins><span class="cx">         fn = n
</span><span class="cx">         uid = self._groupForSharedAddressBookUID()
</span><span class="cx"> 
</span><span class="lines">@@ -708,14 +643,18 @@
</span><span class="cx">         component = VCard.fromString(
</span><span class="cx">             &quot;&quot;&quot;BEGIN:VCARD
</span><span class="cx"> VERSION:3.0
</span><del>-PRODID:%s
-UID:%s
-FN:%s
-N:%s;;;;
</del><ins>+PRODID:{prodid}
+UID:{uid}
+FN:{fn}
+N:{n};;;;
</ins><span class="cx"> X-ADDRESSBOOKSERVER-KIND:group
</span><span class="cx"> END:VCARD
</span><del>-&quot;&quot;&quot;.replace(&quot;\n&quot;, &quot;\r\n&quot;) % (vCardProductID, uid, n, fn,)
-        )
</del><ins>+&quot;&quot;&quot;.replace(&quot;\n&quot;, &quot;\r\n&quot;).format(
+            prodid=vCardProductID,
+            uid=uid,
+            fn=fn,
+            n=n,
+        ))
</ins><span class="cx"> 
</span><span class="cx">         # then get member UIDs
</span><span class="cx">         abo = schema.ADDRESSBOOK_OBJECT
</span><span class="lines">@@ -754,39 +693,26 @@
</span><span class="cx"> 
</span><span class="cx">         @return: an iterable of C{str}s.
</span><span class="cx">         &quot;&quot;&quot;
</span><del>-        names = yield super(AddressBook, cls).listObjects(home)
-        names.insert(0, home.addressbook().name())
-        returnValue(names)
</del><span class="cx"> 
</span><del>-#    @classmethod
-#    @inlineCallbacks
-#    def listObjects(cls, home):
-#        &quot;&quot;&quot;
-#        Retrieve the names of the children with invitations in the given home.
-#
-#        @return: an iterable of C{str}s.
-#        &quot;&quot;&quot;
-#        names = set([home.addressbook().name()])
-#
-#        rows = yield cls._acceptedBindForHomeID.on(
-#            home._txn, homeID=home._resourceID
-#        )
-#        for row in rows:
-#            bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
-#            ownerHome = yield home._txn.homeWithResourceID(home._homeType, resourceID, create=True)
-#            names |= set([ownerHome.uid()])
-#
-#        groupRows = yield AddressBookObject._acceptedBindForHomeID.on(
-#            home._txn, homeID=home._resourceID
-#        )
-#        for groupRow in groupRows:
-#            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.uid()])
-#        returnValue(tuple(names))
</del><ins>+        # Default address book
+        names = set([home.addressbook().name()])
</ins><span class="cx"> 
</span><ins>+        # Fully shared address books
+        names |= set((yield super(AddressBook, cls).listObjects(home)))
</ins><span class="cx"> 
</span><ins>+        # Group shared
+        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
+            ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
+            ownerHome = yield home._txn.homeWithResourceID(home._homeType, ownerAddressBookID, create=True)
+            names |= set([ownerHome.uid()])
+
+        returnValue(tuple(names))
+
+
</ins><span class="cx">     @classmethod
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def loadAllObjects(cls, home):
</span><span class="lines">@@ -798,93 +724,78 @@
</span><span class="cx">         optimization for Depth:1 operations on the home.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><del>-        results = yield super(AddressBook, cls).loadAllObjects(home)
-        results.insert(0, home.addressbook())
-        returnValue(results)
</del><ins>+        results = [home.addressbook()]
+        ownerHomeToDataRowMap = {}
</ins><span class="cx"> 
</span><ins>+        # Load from the main table first
+        dataRows = yield cls._childrenAndMetadataForHomeID.on(
+            home._txn, homeID=home._resourceID
+        )
+        # get ownerHomeIDs
+        for dataRow in dataRows:
+            bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
+            ownerHome = yield home.ownerHomeWithChildID(resourceID)
+            ownerHomeToDataRowMap[ownerHome] = dataRow
</ins><span class="cx"> 
</span><del>-#    @classmethod
-#    @inlineCallbacks
-#    def loadAllObjects(cls, home):
-#        &quot;&quot;&quot;
-#        Load all L{CommonHomeChild} instances which are children of a given
-#        L{CommonHome} and return a L{Deferred} firing a list of them.  This must
-#        create the child classes and initialize them using &quot;batched&quot; SQL
-#        operations to keep this constant wrt the number of children.  This is an
-#        optimization for Depth:1 operations on the home.
-#        &quot;&quot;&quot;
-#        results = [home.addressbook()]
-#        ownerHomeToDataRowMap = {}
-#
-#        # Load from the main table first
-#        dataRows = yield cls._childrenAndMetadataForHomeID.on(
-#            home._txn, homeID=home._resourceID
-#        )
-#        # get ownerHomeIDs
-#        for dataRow in dataRows:
-#            bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
-#            ownerHome = yield home.ownerHomeWithChildID(resourceID)
-#            ownerHomeToDataRowMap[ownerHome] = dataRow
-#
-#        # now get group rows:
-#        groupBindRows = yield AddressBookObject._childrenAndMetadataForHomeID.on(
-#            home._txn, homeID=home._resourceID
-#        )
-#        for groupBindRow in groupBindRows:
-#            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  # name
-#                groupBindRow[4] = None  # bindStatus
-#                groupBindRow[6] = None  # bindMessage
-#                ownerHomeToDataRowMap[ownerHome] = groupBindRow
-#
-#        if ownerHomeToDataRowMap:
-#            # Get property stores for all these child resources (if any found)
-#            addressbookPropertyStoreIDs = [ownerHome._addressbookPropertyStoreID for ownerHome in ownerHomeToDataRowMap]
-#            propertyStores = yield PropertyStore.forMultipleResourcesWithResourceIDs(
-#                home.uid(), home._txn, addressbookPropertyStoreIDs
-#            )
-#
-#            addressbookResourceIDs = [ownerHome.addressbook()._resourceID for ownerHome in ownerHomeToDataRowMap]
-#            revisions = yield cls._revisionsForResourceIDs(addressbookResourceIDs).on(home._txn, resourceIDs=addressbookResourceIDs)
-#            revisions = dict(revisions)
-#
-#            # Create the actual objects merging in properties
-#            for ownerHome, dataRow in ownerHomeToDataRowMap.iteritems():
-#                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=name,
-#                    resourceID=ownerHome._resourceID,
-#                    mode=bindMode,
-#                    status=bindStatus,
-#                    revision=bindRevision,
-#                    message=bindMessage,
-#                    ownerHome=ownerHome,
-#                )
-#
-#                for attr, value in zip(cls.additionalBindAttributes(), additionalBind):
-#                    setattr(child, attr, value)
-#                for attr, value in zip(cls.metadataAttributes(), metadata):
-#                    setattr(child, attr, value)
-#                child._syncTokenRevision = revisions[child._resourceID]
-#                propstore = propertyStores.get(ownerHome._addressbookPropertyStoreID, None)
-#                # We have to re-adjust the property store object to account for possible shared
-#                # collections as previously we loaded them all as if they were owned
-#                if propstore:
-#                    propstore._setDefaultUserUID(ownerHome.uid())
-#                yield child._loadPropertyStore(propstore)
-#                results.append(child)
-#
-#        returnValue(results)
</del><ins>+        # now get group rows:
+        groupBindRows = yield AddressBookObject._childrenAndMetadataForHomeID.on(
+            home._txn, homeID=home._resourceID
+        )
+        for groupBindRow in groupBindRows:
+            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_INDIRECT
+                groupBindRow[3] = None  # bindName
+                groupBindRow[4] = None  # bindStatus
+                groupBindRow[6] = None  # bindMessage
+                ownerHomeToDataRowMap[ownerHome] = groupBindRow
</ins><span class="cx"> 
</span><ins>+        if ownerHomeToDataRowMap:
+            # Get property stores for all these child resources (if any found)
+            addressbookPropertyStoreIDs = [ownerHome._addressbookPropertyStoreID for ownerHome in ownerHomeToDataRowMap]
+            propertyStores = yield PropertyStore.forMultipleResourcesWithResourceIDs(
+                home.uid(), home._txn, addressbookPropertyStoreIDs
+            )
</ins><span class="cx"> 
</span><ins>+            addressbookResourceIDs = [ownerHome.addressbook()._resourceID for ownerHome in ownerHomeToDataRowMap]
+            revisions = yield cls._revisionsForResourceIDs(addressbookResourceIDs).on(home._txn, resourceIDs=addressbookResourceIDs)
+            revisions = dict(revisions)
+
+            # Create the actual objects merging in properties
+            for ownerHome, dataRow in ownerHomeToDataRowMap.iteritems():
+                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.uid(),
+                    resourceID=ownerHome._resourceID,
+                    mode=bindMode,
+                    status=bindStatus,
+                    revision=bindRevision,
+                    message=bindMessage,
+                    ownerHome=ownerHome,
+                )
+
+                for attr, value in zip(cls.additionalBindAttributes(), additionalBind):
+                    setattr(child, attr, value)
+                for attr, value in zip(cls.metadataAttributes(), metadata):
+                    setattr(child, attr, value)
+                child._syncTokenRevision = revisions[child._resourceID]
+                propstore = propertyStores.get(ownerHome._addressbookPropertyStoreID, None)
+                # We have to re-adjust the property store object to account for possible shared
+                # collections as previously we loaded them all as if they were owned
+                if propstore:
+                    propstore._setDefaultUserUID(ownerHome.uid())
+                yield child._loadPropertyStore(propstore)
+                results.append(child)
+
+        returnValue(results)
+
+
</ins><span class="cx">     @classmethod
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def objectWithName(cls, home, name, accepted=True):
</span><span class="lines">@@ -899,94 +810,18 @@
</span><span class="cx">         @return: an L{CommonHomeChild} or C{None} if no such child exists.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><ins>+        # Try owned address book first
</ins><span class="cx">         if name == home.addressbook().name():
</span><span class="cx">             returnValue(home.addressbook())
</span><span class="cx"> 
</span><ins>+        # Try fully shared next
</ins><span class="cx">         result = yield super(AddressBook, cls).objectWithName(home, name, accepted)
</span><del>-        returnValue(result)
</del><span class="cx"> 
</span><ins>+        # Look for indirect shares
+        if result is None:
+            result = yield cls._indirectObjectWithNameOrID(home, name=name, accepted=accepted)
</ins><span class="cx"> 
</span><del>-#    @classmethod
-#    @inlineCallbacks
-#    def objectWithName(cls, home, name, accepted=True):
-#        &quot;&quot;&quot;
-#        Retrieve the child with the given 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 C{None} if no such child
-#            exists.
-#        &quot;&quot;&quot;
-#        if accepted and name == home.addressbook().name():
-#            returnValue(home.addressbook())
-#        # shared address books only from this point on
-#
-#        rows = None
-#        queryCacher = home._txn._queryCacher
-#        ownerHome = None
-#
-#        if queryCacher:
-#            # Retrieve data from cache
-#            cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
-#            rows = yield queryCacher.get(cacheKey)
-#
-#        if not rows:
-#            # name must be a home uid
-#            ownerHome = yield home._txn.addressbookHomeWithUID(name)
-#            if ownerHome:
-#                # see if address book resource id in bind table
-#                ownerAddressBook = ownerHome.addressbook()
-#                bindRows = yield cls._bindForResourceIDAndHomeID.on(
-#                    home._txn, resourceID=ownerAddressBook._resourceID, homeID=home._resourceID
-#                )
-#                if bindRows:
-#                    bindRows[0].insert(cls.bindColumnCount, ownerAddressBook._resourceID)
-#                    bindRows[0].insert(cls.bindColumnCount + 1, bindRows[0][4])  # cachedStatus = bindStatus
-#                    rows = bindRows
-#                else:
-#                    groupBindRows = yield AddressBookObject._bindForHomeIDAndAddressBookID.on(
-#                            home._txn, homeID=home._resourceID, addressbookID=ownerAddressBook._resourceID
-#                    )
-#                    for groupBindRow in groupBindRows:
-#                        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
-#                queryCacher.setAfterCommit(home._txn, cacheKey, rows)
-#
-#        if not rows:
-#            returnValue(None)
-#
-#        row = rows[0]
-#        bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage, ownerAddressBookID, cachedBindStatus = row[:cls.bindColumnCount + 2] #@UnusedVariable
-#
-#        # if wrong status, exit here.  Item is in queryCache
-#        if accepted is not None and (cachedBindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
-#            returnValue(None)
-#
-#        ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
-#        child = cls(
-#                home=home,
-#                name=name,
-#                resourceID=ownerAddressBookID,
-#                mode=bindMode,
-#                status=bindStatus,
-#                revision=bindRevision,
-#                message=bindMessage,
-#                ownerHome=ownerHome,
-#            )
-#        yield child.initFromStore()
-#        returnValue(child)
</del><ins>+        returnValue(result)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @classmethod
</span><span class="lines">@@ -1001,64 +836,88 @@
</span><span class="cx">         @return: an L{CommonHomeChild} or C{None} if no such child
</span><span class="cx">             exists.
</span><span class="cx">         &quot;&quot;&quot;
</span><ins>+
+        # Try owned address book first
</ins><span class="cx">         if home._resourceID == resourceID:
</span><span class="cx">             returnValue(home.addressbook())
</span><span class="cx"> 
</span><ins>+        # Try fully shared next
</ins><span class="cx">         result = yield super(AddressBook, cls).objectWithID(home, resourceID, accepted)
</span><ins>+
+        # Look for indirect shares
+        if result is None:
+            result = yield cls._indirectObjectWithNameOrID(home, resourceID=resourceID, accepted=accepted)
+
</ins><span class="cx">         returnValue(result)
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-#    @classmethod
-#    @inlineCallbacks
-#    def objectWithID(cls, home, resourceID, accepted=True):
-#        &quot;&quot;&quot;
-#        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.
-#        &quot;&quot;&quot;
-#        if home._resourceID == resourceID:
-#            returnValue(home.addressbook())
-#
-#        bindRows = yield cls._bindForResourceIDAndHomeID.on(
-#            home._txn, resourceID=resourceID, homeID=home._resourceID
-#        )
-#        if bindRows:
-#            bindRow = bindRows[0]
-#            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 bindStatus == _BIND_STATUS_ACCEPTED:
-#                returnValue((yield home.childWithName(ownerHome.uid())))
-#            else:
-#                returnValue((yield cls.objectWithName(home, ownerHome.uid(), accepted=False)))
-#
-#        groupBindRows = yield AddressBookObject._bindForHomeIDAndAddressBookID.on(
-#                    home._txn, homeID=home._resourceID, addressbookID=resourceID
-#        )
-#        if groupBindRows:
-#            groupBindRow = groupBindRows[0]
-#            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 bindStatus == _BIND_STATUS_ACCEPTED:
-#                returnValue((yield home.childWithName(ownerHome.uid())))
-#            else:
-#                returnValue((yield cls.objectWithName(home, ownerHome.uid(), accepted=False)))
-#
-#        returnValue(None)
</del><ins>+    @classmethod
+    @inlineCallbacks
+    def _indirectObjectWithNameOrID(cls, home, name=None, resourceID=None, accepted=True):
+        # replaces objectWithName()
+        &quot;&quot;&quot;
+        Synthesize and indirect child for matching name or id based on whether shared groups exist.
</ins><span class="cx"> 
</span><ins>+        @param home: a L{CommonHome}.
</ins><span class="cx"> 
</span><ins>+        @param name: a string; the name of the L{CommonHomeChild} to retrieve.
+
+        @return: an L{CommonHomeChild} or C{None} if no such child
+            exists.
+        &quot;&quot;&quot;
+        rows = None
+        ownerHome = None
+
+        # TODO: add queryCacher support
+
+        if rows is None:
+            # No cached copy
+            if name:
+                ownerHome = yield home._txn.addressbookHomeWithUID(name)
+                if ownerHome is None:
+                    returnValue(None)
+                resourceID = ownerHome.addressbook()._resourceID
+            rows = yield AddressBookObject._bindForHomeIDAndAddressBookID.on(
+                home._txn, homeID=home._resourceID, addressbookID=resourceID
+            )
+
+        if not rows:
+            returnValue(None)
+
+        groupID = None
+        overallBindStatus = _BIND_STATUS_INVITED
+        minBindRevision = None
+        for row in rows:
+            bindMode, homeID, resourceGroupID, name, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
+            if groupID is None:
+                groupID = resourceGroupID
+            minBindRevision = min(minBindRevision, bindRevision) if minBindRevision is not None else bindRevision
+            if bindStatus == _BIND_STATUS_ACCEPTED:
+                overallBindStatus = _BIND_STATUS_ACCEPTED
+
+        if accepted is not None and (overallBindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+            returnValue(None)
+        additionalBind = row[cls.bindColumnCount:cls.bindColumnCount + len(cls.additionalBindColumns())]
+
+        if ownerHome is None:
+            ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, groupID)
+            ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
+
+        child = cls(
+            home=home,
+            name=ownerHome.uid(),
+            resourceID=resourceID,
+            mode=_BIND_MODE_INDIRECT,
+            status=overallBindStatus,
+            revision=minBindRevision,
+            message=&quot;&quot;,
+            ownerHome=ownerHome,
+            ownerName=ownerHome.uid()
+        )
+        yield child.initFromStore(additionalBind)
+        returnValue(child)
+
+
</ins><span class="cx">     @classmethod
</span><span class="cx">     def _memberIDsWithGroupIDsQuery(cls, groupIDs):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -1181,15 +1040,15 @@
</span><span class="cx">         ids = set([row[1] for row in rows])
</span><span class="cx"> 
</span><span class="cx">         # Everything is read-write
</span><del>-        if self.owned() or self._bindMode == _BIND_MODE_WRITE:
</del><ins>+        if self.owned() or self.fullyShared() and self._bindMode == _BIND_MODE_WRITE:
</ins><span class="cx">             returnValue(tuple(readOnlyIDs), tuple(ids))
</span><span class="cx"> 
</span><span class="cx">         # Fully shared but mode is read-only
</span><del>-        if self._bindMode == _BIND_MODE_READ:
</del><ins>+        if self.fullyShared() and self._bindMode == _BIND_MODE_READ:
</ins><span class="cx">             ids |= set([self._resourceID, ])
</span><span class="cx">             readOnlyIDs = set(ids)
</span><span class="cx"> 
</span><del>-        # Look for shared groups and for those that tare read-write, transfer their object ids
</del><ins>+        # Look for shared groups and for those that are read-write, transfer their object ids
</ins><span class="cx">         # to the read-write set
</span><span class="cx">         groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
</span><span class="cx">             self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
</span><span class="lines">@@ -1229,36 +1088,333 @@
</span><span class="cx">         readOnlyIDs, readWriteIDs = yield self.accessControlObjectIDs()
</span><span class="cx">         returnValue((readOnlyIDs + readWriteIDs))
</span><span class="cx"> 
</span><ins>+    # Convenient names for some methods
+    ownerAddressBookHome = CommonHomeChild.ownerHome
+    viewerAddressBookHome = CommonHomeChild.viewerHome
+    addressbookObjects = CommonHomeChild.objectResources
+    listAddressBookObjects = listObjectResources
+    countAddressBookObjects = countObjectResources
+    addressbookObjectWithName = CommonHomeChild.objectResourceWithName
+    addressbookObjectWithUID = CommonHomeChild.objectResourceWithUID
+    createAddressBookObjectWithName = CommonHomeChild.createObjectResourceWithName
+    addressbookObjectsSinceToken = CommonHomeChild.objectResourcesSinceToken
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> class AddressBookObjectSharingMixIn(SharingMixIn):
</span><span class="cx">     &quot;&quot;&quot;
</span><del>-        Sharing code for AddressBookObject
</del><ins>+    Sharing code for AddressBookObject
</ins><span class="cx">     &quot;&quot;&quot;
</span><span class="cx"> 
</span><del>-#    @inlineCallbacks
-#    def _isSharedOrInvited(self):
-#        &quot;&quot;&quot;
-#        return True if this L{AddressBook} is shared or invited
-#        &quot;&quot;&quot;
-#        sharedRows = []
-#        if self.owned():
-#            bind = self._bindSchema
-#            sharedRows = yield self._bindFor(
-#                (bind.RESOURCE_ID == Parameter(&quot;resourceID&quot;))).on(
-#                self._txn, resourceID=self._resourceID,
-#            )
-#
-#        returnValue(bool(sharedRows))
-#
-#
-#    @inlineCallbacks
-#    def _initIsShared(self):
-#        isShared = yield self._isSharedOrInvited()
-#        self.setShared(isShared)
</del><ins>+    def sharedResourceType(self):
+        &quot;&quot;&quot;
+        The sharing resource type
+        &quot;&quot;&quot;
+        return &quot;group&quot;
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    #
+    # Lower level API
+    #
</ins><span class="cx"> 
</span><ins>+    @inlineCallbacks
+    def ownerView(self):
+        &quot;&quot;&quot;
+        Return the owner resource counterpart of this shared resource.
+        &quot;&quot;&quot;
+        # Get the child of the owner home that has the same resource id as the owned one
+        ownerView = yield self.ownerHome().addressbook().objectResourceWithID(self.id())
+        returnValue(ownerView)
+
+
+    @inlineCallbacks
+    def shareeView(self, shareeUID):
+        &quot;&quot;&quot;
+        Return the shared resource counterpart of this owned resource for the specified sharee.
+        &quot;&quot;&quot;
+
+        # Get the shared address book, then the child within
+        shareeAdbk = yield self.addressbook().shareeView(shareeUID)
+        shareeView = (yield shareeAdbk.objectResourceWithID(self.id())) if shareeAdbk is not None else None
+        returnValue(shareeView if shareeView is not None and shareeView.shareMode() is not None else None)
+
+
+    @inlineCallbacks
+    def shareWith(self, shareeHome, mode, status=None, summary=None):
+        &quot;&quot;&quot;
+        Share this (owned) L{AddressBookObject} with another home.
+
+        @param shareeHome: The home of the sharee.
+        @type shareeHome: L{CommonHome}
+
+        @param mode: The sharing mode; L{_BIND_MODE_READ} or
+            L{_BIND_MODE_WRITE} or L{_BIND_MODE_DIRECT}
+        @type mode: L{str}
+
+        @param status: The sharing status; L{_BIND_STATUS_INVITED} or
+            L{_BIND_STATUS_ACCEPTED}
+        @type mode: L{str}
+
+        @param summary: The proposed message to go along with the share, which
+            will be used as the default display name.
+        @type summary: L{str}
+
+        @return: the name of the shared group in the sharee home.
+        @rtype: L{str}
+        &quot;&quot;&quot;
+
+        if status is None:
+            status = _BIND_STATUS_ACCEPTED
+
+        @inlineCallbacks
+        def doInsert(subt):
+            newName = self.newShareName()
+            yield self._bindInsertQuery.on(
+                subt,
+                homeID=shareeHome._resourceID,
+                resourceID=self._resourceID,
+                name=newName,
+                mode=mode,
+                bindStatus=status,
+                message=summary
+            )
+            returnValue(newName)
+        try:
+            bindName = yield self._txn.subtransaction(doInsert)
+        except AllRetriesFailed:
+            group = yield self.shareeView(shareeHome.uid())
+            yield self.updateShare(
+                group, mode=mode, status=status,
+                summary=summary
+            )
+            bindName = group.name()
+        else:
+            if status == _BIND_STATUS_ACCEPTED:
+                shareeView = yield shareeHome.anyObjectWithShareUID(bindName)
+                yield shareeView.addressbook()._initSyncToken()
+                yield shareeView._initBindRevision()
+
+        queryCacher = self._txn._queryCacher
+        if queryCacher:
+            cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().name())
+            queryCacher.invalidateAfterCommit(self._txn, cacheKey)
+
+        yield self.setShared(True)
+
+        # Must send notification to ensure cache invalidation occurs
+        yield self.notifyChanged()
+
+        returnValue(bindName)
+
+
+    @inlineCallbacks
+    def createShare(self, shareeUID, mode, summary=None):
+        &quot;&quot;&quot;
+        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.
+        &quot;&quot;&quot;
+
+        if self._kind == _ABO_KIND_GROUP:
+            shareeView = yield super(AddressBookObjectSharingMixIn, self).createShare(shareeUID, mode, summary)
+            returnValue(shareeView)
+        else:
+            returnValue(None)
+
+
+    @inlineCallbacks
+    def unshare(self):
+        &quot;&quot;&quot;
+        Unshares a group, regardless of which &quot;direction&quot; it was shared.
+        &quot;&quot;&quot;
+        if self._kind == _ABO_KIND_GROUP:
+            yield super(AddressBookObjectSharingMixIn, self).unshare()
+
+
+    @inlineCallbacks
+    def updateShare(self, shareeView, mode=None, status=None, summary=None):
+        &quot;&quot;&quot;
+        Update share mode, status, and message for a home child shared with
+        this (owned) L{CommonHomeChild}.
+
+        @param shareeView: The sharee home child that shares this.
+        @type shareeView: L{CommonHomeChild}
+
+        @param mode: The sharing mode; L{_BIND_MODE_READ} or
+            L{_BIND_MODE_WRITE} or None to not update
+        @type mode: L{str}
+
+        @param status: The sharing status; L{_BIND_STATUS_INVITED} or
+            L{_BIND_STATUS_ACCEPTED} or L{_BIND_STATUS_DECLINED} or
+            L{_BIND_STATUS_INVALID}  or None to not update
+        @type status: L{str}
+
+        @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 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}
+        &quot;&quot;&quot;
+        # TODO: raise a nice exception if shareeView is not, in fact, a shared
+        # version of this same L{CommonHomeChild}
+
+        # remove None parameters, and substitute None for empty string
+        bind = self._bindSchema
+        columnMap = dict([(k, v if v != &quot;&quot; else None) for k, v in {
+            bind.BIND_MODE:mode,
+            bind.BIND_STATUS:status,
+            bind.MESSAGE:summary
+        }.iteritems() if v is not None])
+
+        if len(columnMap):
+
+            # count accepted
+            if status is not None:
+                previouslyAcceptedBindCount = 1 if self.addressbook().fullyShared() else 0
+                previouslyAcceptedBindCount += len((
+                    yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
+                        self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=self.addressbook()._resourceID
+                    )
+                ))
+
+            yield self._updateBindColumnsQuery(columnMap).on(
+                self._txn,
+                resourceID=self._resourceID,
+                homeID=shareeView.addressbook().viewerHome()._resourceID
+            )
+
+            # update affected attributes
+            if mode is not None:
+                shareeView._bindMode = columnMap[bind.BIND_MODE]
+
+            if status is not None:
+                shareeView._bindStatus = columnMap[bind.BIND_STATUS]
+                if shareeView._bindStatus == _BIND_STATUS_ACCEPTED:
+                    if 0 == previouslyAcceptedBindCount:
+                        yield shareeView.addressbook()._initSyncToken()
+                        yield shareeView._initBindRevision()
+                        shareeView.viewerHome()._children[shareeView.addressbook().name()] = shareeView.addressbook()
+                        shareeView.viewerHome()._children[shareeView.addressbook().id()] = shareeView.addressbook()
+                elif shareeView._bindStatus != _BIND_STATUS_INVITED:
+                    if 1 == previouslyAcceptedBindCount:
+                        yield shareeView.addressbook()._deletedSyncToken(sharedRemoval=True)
+                        shareeView.viewerHome()._children.pop(shareeView.addressbook().name(), None)
+                        shareeView.viewerHome()._children.pop(shareeView.addressbook().id(), None)
+
+            if summary is not None:
+                shareeView._bindMessage = columnMap[bind.MESSAGE]
+
+            # Must send notification to ensure cache invalidation occurs
+            yield self.notifyChanged()
+
+
+    @inlineCallbacks
+    def removeShare(self, shareeView):
+        &quot;&quot;&quot;
+        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.
+
+        @return: a L{Deferred} which will fire with the previously-used name.
+        &quot;&quot;&quot;
+
+        shareeHome = shareeView.addressbook().viewerHome()
+        sharedAddressBook = yield shareeHome.addressbookWithName(self.addressbook().name())
+
+        if sharedAddressBook:
+
+            acceptedBindCount = 1 if sharedAddressBook.fullyShared() else 0
+            acceptedBindCount += len((
+                yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
+                    self._txn, homeID=shareeHome._resourceID, addressbookID=sharedAddressBook._resourceID
+                )
+            ))
+
+            if acceptedBindCount == 1:
+                yield sharedAddressBook._deletedSyncToken(sharedRemoval=True)
+                shareeHome._children.pop(shareeView.addressbook().name(), None)
+                shareeHome._children.pop(shareeView.addressbook().id(), None)
+
+            # Must send notification to ensure cache invalidation occurs
+            yield self.notifyChanged()
+
+        # Must send notification to ensure cache invalidation occurs
+        yield self.notifyChanged()
+
+        # delete binds including invites
+        yield self._deleteBindForResourceIDAndHomeID.on(
+            self._txn,
+            resourceID=self._resourceID,
+            homeID=shareeHome._resourceID,
+        )
+
+        queryCacher = self._txn._queryCacher
+        if queryCacher:
+            cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().name())
+            queryCacher.invalidateAfterCommit(self._txn, cacheKey)
+
+
+    @inlineCallbacks
+    def sharingInvites(self):
+        &quot;&quot;&quot;
+        Retrieve the list of all L{SharingInvitation} for this L{CommonHomeChild}, irrespective of mode.
+
+        @return: L{SharingInvitation} objects
+        @rtype: a L{Deferred} which fires with a L{list} of L{SharingInvitation}s.
+        &quot;&quot;&quot;
+        if not self.owned() or self._kind != _ABO_KIND_GROUP:
+            returnValue([])
+
+        # Get all binds
+        acceptedRows = yield self._sharedInvitationBindForResourceID.on(
+            self._txn, resourceID=self._resourceID, homeID=self.addressbook()._home._resourceID
+        )
+
+        result = []
+        for homeUID, homeRID, resourceID, resourceName, bindMode, bindStatus, bindMessage in acceptedRows: #@UnusedVariable
+            invite = SharingInvitation(
+                resourceName,
+                self.addressbook()._home.name(),
+                self.addressbook()._home.id(),
+                homeUID,
+                homeRID,
+                bindMode,
+                bindStatus,
+                bindMessage,
+            )
+            result.append(invite)
+        returnValue(result)
+
+
+    @inlineCallbacks
+    def _initBindRevision(self):
+        # FIXME: not sure about all this revision stuff
+        yield self.addressbook()._initBindRevision()
+
+        bind = self._bindSchema
+        yield self._updateBindColumnsQuery(
+            {bind.BIND_REVISION : Parameter(&quot;revision&quot;), }
+        ).on(
+            self._txn,
+            revision=self.addressbook()._bindRevision,
+            resourceID=self._resourceID,
+            homeID=self.viewerHome()._resourceID,
+        )
+        yield self.invalidateQueryCache()
+
+
+    def shareUID(self):
+        &quot;&quot;&quot;
+        @see: L{ICalendar.shareUID}
+        &quot;&quot;&quot;
+        return self._bindName if self._bindName else self._name
+
+
+
</ins><span class="cx"> class AddressBookObject(CommonObjectResource, AddressBookObjectSharingMixIn):
</span><span class="cx"> 
</span><span class="cx">     implements(IAddressBookObject)
</span><span class="lines">@@ -1325,10 +1481,10 @@
</span><span class="cx">             yield self.unshare() # storebridge should already have done this
</span><span class="cx">         else:
</span><span class="cx">             # handled in storebridge as unshare, should not be here.  assert instead?
</span><del>-            if self.isGroupForSharedAddressBook() or self.shareUID():
</del><ins>+            if self.isGroupForSharedAddressBook() or self._bindMode is not None:
</ins><span class="cx">                 raise HTTPError(FORBIDDEN)
</span><span class="cx"> 
</span><del>-        if not self.owned() and self.addressbook().indirect():
</del><ins>+        if not self.owned() and not self.addressbook().fullyShared():
</ins><span class="cx">             readWriteObjectIDs = []
</span><span class="cx">             readWriteGroupIDs = yield self.addressbook().readWriteGroupIDs()
</span><span class="cx">             if readWriteGroupIDs:
</span><span class="lines">@@ -1372,17 +1528,16 @@
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def readWriteAccess(self):
</span><span class="cx">         assert not self.owned(), &quot;Don't call items in owned address book&quot;
</span><del>-        yield None
</del><span class="cx"> 
</span><del>-        #shared address book group is always read-only
</del><ins>+        # Shared address book group always read-only
</ins><span class="cx">         if self.isGroupForSharedAddressBook():
</span><span class="cx">             returnValue(False)
</span><span class="cx"> 
</span><del>-        # if fully shared and rw, must be RW since sharing group read-only has no affect
-        if not self.addressbook().indirect() and self.addressbook().shareMode() == _BIND_MODE_WRITE:
</del><ins>+        # If fully shared and rw, must be RW since sharing group read-only has no affect
+        if self.addressbook().fullyShared() and self.addressbook().shareMode() == _BIND_MODE_WRITE:
</ins><span class="cx">             returnValue(True)
</span><span class="cx"> 
</span><del>-        #otherwise, must be in a read-write group
</del><ins>+        # Otherwise, must be in a read-write group
</ins><span class="cx">         readWriteGroupIDs = yield self.addressbook().readWriteGroupIDs()
</span><span class="cx">         readWriteIDs = yield self.addressbook().expandGroupIDs(self._txn, readWriteGroupIDs)
</span><span class="cx">         returnValue(self._resourceID in readWriteIDs)
</span><span class="lines">@@ -1420,7 +1575,39 @@
</span><span class="cx">             Where=obj.RESOURCE_ID == Parameter(&quot;resourceID&quot;),)
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    @classmethod
</ins><span class="cx">     @inlineCallbacks
</span><ins>+    def objectWithBindName(cls, home, name, accepted):
+        &quot;&quot;&quot;
+        Retrieve the 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{ObjectResource} or C{None} if no such resource exists.
+        &quot;&quot;&quot;
+
+        groupBindRows = yield cls._bindForNameAndHomeID.on(
+            home._txn, name=name, homeID=home._resourceID
+        )
+        if groupBindRows:
+            groupBindRow = groupBindRows[0]
+            bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+
+            if accepted is not None and (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+                returnValue(None)
+
+            ownerAddressBookID = yield cls.ownerAddressBookIDFromGroupID(home._txn, resourceID)
+            ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
+            addressbook = yield home.anyObjectWithShareUID(ownerHome.uid())
+            returnValue((yield addressbook.objectResourceWithID(resourceID)))
+
+        returnValue(None)
+
+
+    @inlineCallbacks
</ins><span class="cx">     def initFromStore(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Initialise this object from the store. We read in and cache all the
</span><span class="lines">@@ -1431,11 +1618,31 @@
</span><span class="cx">         @return: L{self} if object exists in the DB, else C{None}
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         abo = None
</span><del>-        if self.owned() or not self.addressbook().indirect():  # owned or fully shared
</del><ins>+        if self.owned() or self.addressbook().fullyShared():  # owned or fully shared
</ins><span class="cx">             abo = yield super(AddressBookObject, self).initFromStore()
</span><ins>+
+            # Might be special group
+            if abo is None and self.addressbook().fullyShared():
+                rows = None
+                if self._name:
+                    if self._name == self.addressbook()._groupForSharedAddressBookName():
+                        rows = [self.addressbook()._groupForSharedAddressBookRow()]
+                elif self._uid:
+                    if self._uid == (yield self.addressbook()._groupForSharedAddressBookUID()):
+                        rows = [self.addressbook()._groupForSharedAddressBookRow()]
+                elif self._resourceID:
+                    if self.isGroupForSharedAddressBook():
+                        rows = [self.addressbook()._groupForSharedAddressBookRow()]
+
+                if rows:
+                    self._initFromRow(tuple(rows[0]))
+                    yield self._loadPropertyStore()
+                    abo = self
+
</ins><span class="cx">         else:
</span><span class="cx">             acceptedGroupIDs = yield self.addressbook().acceptedGroupIDs()
</span><span class="cx">             allowedObjectIDs = yield self.addressbook().expandGroupIDs(self._txn, acceptedGroupIDs)
</span><ins>+            rows = None
</ins><span class="cx">             if self._name:
</span><span class="cx">                 if allowedObjectIDs:
</span><span class="cx">                     rows = (yield self._allColumnsWithResourceIDsAndName(allowedObjectIDs).on(
</span><span class="lines">@@ -1475,9 +1682,11 @@
</span><span class="cx">                     self._bindStatus = bindStatus
</span><span class="cx">                     self._bindMessage = bindMessage
</span><span class="cx">                     self._bindName = bindName
</span><ins>+                else:
+                    invites = yield self.sharingInvites()
+                    if len(invites):
+                        self._bindMessage = &quot;shared&quot;
</ins><span class="cx"> 
</span><del>-                #yield self._initIsShared()
-
</del><span class="cx">             returnValue(self)
</span><span class="cx">         else:
</span><span class="cx">             returnValue(None)
</span><span class="lines">@@ -1532,8 +1741,10 @@
</span><span class="cx">     @classmethod
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def _allColumnsWithParent(cls, addressbook):
</span><del>-        if addressbook.owned() or not addressbook.indirect():
</del><ins>+        if addressbook.owned() or addressbook.fullyShared():
</ins><span class="cx">             rows = yield super(AddressBookObject, cls)._allColumnsWithParent(addressbook)
</span><ins>+            if addressbook.fullyShared():
+                rows.append(addressbook._groupForSharedAddressBookRow())
</ins><span class="cx">         else:
</span><span class="cx">             acceptedGroupIDs = yield addressbook.acceptedGroupIDs()
</span><span class="cx">             allowedObjectIDs = yield addressbook.expandGroupIDs(addressbook._txn, acceptedGroupIDs)
</span><span class="lines">@@ -1555,8 +1766,10 @@
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def _allColumnsWithParentAndNames(cls, addressbook, names):
</span><span class="cx"> 
</span><del>-        if addressbook.owned() or not addressbook.indirect():
</del><ins>+        if addressbook.owned() or addressbook.fullyShared():
</ins><span class="cx">             rows = yield super(AddressBookObject, cls)._allColumnsWithParentAndNames(addressbook, names)
</span><ins>+            if addressbook.fullyShared() and addressbook._groupForSharedAddressBookName() in names:
+                rows.append(addressbook._groupForSharedAddressBookRow())
</ins><span class="cx">         else:
</span><span class="cx">             acceptedGroupIDs = yield addressbook.acceptedGroupIDs()
</span><span class="cx">             allowedObjectIDs = yield addressbook.expandGroupIDs(addressbook._txn, acceptedGroupIDs)
</span><span class="lines">@@ -1649,7 +1862,7 @@
</span><span class="cx">                 raise InvalidUIDError(&quot;Cannot change the UID in an existing resource.&quot;)
</span><span class="cx">         else:
</span><span class="cx">             # for partially shared addressbooks, cannot use name that already exists in owner
</span><del>-            if not self.owned() and self.addressbook().indirect():
</del><ins>+            if not self.owned() and not self.addressbook().fullyShared():
</ins><span class="cx">                 nameElsewhere = (yield self.ownerHome().addressbook().addressbookObjectWithName(self.name()))
</span><span class="cx">                 if nameElsewhere is not None:
</span><span class="cx">                     raise ObjectResourceNameAlreadyExistsError(self.name() + ' in use by owning addressbook.')
</span><span class="lines">@@ -1680,7 +1893,7 @@
</span><span class="cx">             if self._kind == _ABO_KIND_GROUP:  # optimization
</span><span class="cx">                 invites = yield self.sharingInvites()
</span><span class="cx">                 for invite in invites:
</span><del>-                    shareeHome = (yield self._txn.homeWithResourceID(self.addressbook()._home._homeType, invite.shareeHomeID()))
</del><ins>+                    shareeHome = (yield self._txn.homeWithResourceID(self.addressbook()._home._homeType, invite.shareeHomeID))
</ins><span class="cx">                     yield self._changeAddressBookRevision(shareeHome.addressbook(), inserting)
</span><span class="cx">                     # one is enough because all have the same resourceID
</span><span class="cx">                     break
</span><span class="lines">@@ -1784,7 +1997,7 @@
</span><span class="cx">             foundUIDs.append(self._uid) # circular self reference is OK
</span><span class="cx">             missingUIDs = set(memberUIDs) - set(foundUIDs)
</span><span class="cx"> 
</span><del>-            if not self.owned() and self.addressbook().indirect():
</del><ins>+            if not self.owned() and not self.addressbook().fullyShared():
</ins><span class="cx">                 # in partially shared addressbook, all members UIDs must be inside the shared groups
</span><span class="cx">                 # except during bulk operations, when other UIDs added are OK
</span><span class="cx">                 coaddedUIDs = set() if self._options.get(&quot;coaddedUIDs&quot;) is None else self._options[&quot;coaddedUIDs&quot;]
</span><span class="lines">@@ -1851,7 +2064,7 @@
</span><span class="cx">             ).on(self._txn)
</span><span class="cx">             groupIDs = set([groupIDRow[0] for groupIDRow in groupIDRows])
</span><span class="cx"> 
</span><del>-            if not self.owned() and self.addressbook().indirect():
</del><ins>+            if not self.owned() and not self.addressbook().fullyShared():
</ins><span class="cx">                 readWriteGroupIDs = yield self.addressbook().readWriteGroupIDs()
</span><span class="cx">                 assert readWriteGroupIDs, &quot;no access&quot;
</span><span class="cx">                 groupIDs |= set(readWriteGroupIDs)
</span><span class="lines">@@ -2017,13 +2230,6 @@
</span><span class="cx">         pass
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def sharedResourceType(self):
-        &quot;&quot;&quot;
-        The sharing resource type
-        &quot;&quot;&quot;
-        return &quot;group&quot;
-
-
</del><span class="cx">     # IDataStoreObject
</span><span class="cx">     def contentType(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -2032,18 +2238,6 @@
</span><span class="cx">         return MimeType.fromString(&quot;text/vcard; charset=utf-8&quot;)
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def owned(self):
-        return self.addressbook().owned()
-
-
-    def ownerHome(self):
-        return self.addressbook().ownerHome()
-
-
-    def viewerHome(self):
-        return self.addressbook().viewerHome()
-
-
</del><span class="cx">     @classmethod
</span><span class="cx">     def metadataColumns(cls):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -2076,6 +2270,13 @@
</span><span class="cx">         return self.addressbook().notifyChanged()
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    def notifyPropertyChanged(self):
+        &quot;&quot;&quot;
+        Send notifications when properties on this object change.
+        &quot;&quot;&quot;
+        return self.addressbook().notifyPropertyChanged()
+
+
</ins><span class="cx">     @classproperty
</span><span class="cx">     def _addressbookIDForResourceID(cls): #@NoSelf
</span><span class="cx">         obj = cls._objectSchema
</span><span class="lines">@@ -2092,281 +2293,6 @@
</span><span class="cx">         returnValue(ownerAddressBookIDRows[0][0])
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    @inlineCallbacks
-    def sharingInvites(self):
-        &quot;&quot;&quot;
-        Retrieve the list of all L{SharingInvitation} for this L{CommonHomeChild}, irrespective of mode.
-
-        @return: L{SharingInvitation} objects
-        @rtype: a L{Deferred} which fires with a L{list} of L{SharingInvitation}s.
-        &quot;&quot;&quot;
-        if not self.owned():
-            returnValue([])
-
-        # get all accepted binds
-        acceptedRows = yield self._sharedInvitationBindForResourceID.on(
-            self._txn, resourceID=self._resourceID, homeID=self.addressbook()._home._resourceID
-        )
-
-        result = []
-        for homeUID, homeRID, resourceID, resourceName, bindMode, bindStatus, bindMessage in acceptedRows: #@UnusedVariable
-            invite = SharingInvitation(
-                resourceName,
-                self.addressbook()._home.name(),
-                self.addressbook()._home._resourceID,
-                homeUID,
-                homeRID,
-                resourceID,
-                self.addressbook().name(),
-                bindMode,
-                bindStatus,
-                bindMessage,
-            )
-            result.append(invite)
-        returnValue(result)
-
-
-    @inlineCallbacks
-    def unshare(self):
-        &quot;&quot;&quot;
-        Unshares a group, regardless of which &quot;direction&quot; it was shared.
-        &quot;&quot;&quot;
-        if self._kind == _ABO_KIND_GROUP:
-            if self.owned():
-                # This collection may be shared to others
-                invites = yield self.sharingInvites()
-                for invite in invites:
-                    shareeHome = (yield self._txn.homeWithResourceID(self.addressbook()._home._homeType, invite.shareeHomeID()))
-                    (yield self.unshareWith(shareeHome))
-            else:
-                # This collection is shared to me
-                ownerAddressBook = self.addressbook().ownerHome().addressbook()
-                ownerGroup = yield ownerAddressBook.objectResourceWithID(self._resourceID)
-                if ownerGroup:
-                    yield ownerGroup.unshareWith(self._home)
-
-
-    @inlineCallbacks
-    def unshareWith(self, shareeHome):
-        &quot;&quot;&quot;
-        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.
-
-        @return: a L{Deferred} which will fire with the previously-used name.
-        &quot;&quot;&quot;
-        sharedAddressBook = yield shareeHome.addressbookWithName(self.addressbook().name())
-
-        if sharedAddressBook:
-
-            acceptedBindCount = 1 if not sharedAddressBook.indirect() else 0
-            acceptedBindCount += len((
-                yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                    self._txn, homeID=shareeHome._resourceID, addressbookID=sharedAddressBook._resourceID
-                )
-            ))
-
-            if acceptedBindCount == 1:
-                yield sharedAddressBook._deletedSyncToken(sharedRemoval=True)
-                shareeHome._children.pop(self.addressbook().name(), None)
-                shareeHome._children.pop(self.addressbook()._resourceID, None)
-
-            # Must send notification to ensure cache invalidation occurs
-            yield self.notifyChanged()
-
-        # delete binds including invites
-        deletedBindNameRows = 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, self.addressbook().name())
-                queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-        else:
-            deletedBindName = None
-
-        #yield self._initIsShared()
-        returnValue(deletedBindName)
-
-
-    @inlineCallbacks
-    def shareWith(self, shareeHome, mode, status=None, summary=None):
-        &quot;&quot;&quot;
-        Share this (owned) L{AddressBookObject} with another home.
-
-        @param shareeHome: The home of the sharee.
-        @type shareeHome: L{CommonHome}
-
-        @param mode: The sharing mode; L{_BIND_MODE_READ} or
-            L{_BIND_MODE_WRITE} or L{_BIND_MODE_DIRECT}
-        @type mode: L{str}
-
-        @param status: The sharing status; L{_BIND_STATUS_INVITED} or
-            L{_BIND_STATUS_ACCEPTED}
-        @type mode: L{str}
-
-        @param summary: The proposed message to go along with the share, which
-            will be used as the default display name.
-        @type summary: L{str}
-
-        @return: the name of the shared group in the sharee home.
-        @rtype: L{str}
-        &quot;&quot;&quot;
-
-        if status is None:
-            status = _BIND_STATUS_ACCEPTED
-
-        @inlineCallbacks
-        def doInsert(subt):
-            newName = self.newShareName()
-            yield self._bindInsertQuery.on(
-                subt, homeID=shareeHome._resourceID,
-                resourceID=self._resourceID, name=newName,
-                mode=mode, bindStatus=status, message=summary
-            )
-            returnValue(newName)
-        try:
-            bindName = yield self._txn.subtransaction(doInsert)
-        except AllRetriesFailed:
-            # FIXME: catch more specific exception
-            groupBindRows = yield self._bindForResourceIDAndHomeID.on(
-                self._txn, resourceID=self._resourceID, homeID=shareeHome._resourceID
-            )
-            groupBindRow = groupBindRows[0]
-            bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:self.bindColumnCount] #@UnusedVariable
-            if bindStatus == _BIND_STATUS_ACCEPTED:
-                group = yield shareeHome.objectWithShareUID(bindName)
-            else:
-                group = yield shareeHome.invitedObjectWithShareUID(bindName)
-            bindName = yield self.updateShare(
-                group, mode=mode, status=status,
-                summary=summary
-            )
-        else:
-            if status == _BIND_STATUS_ACCEPTED:
-                shareeView = yield shareeHome.objectWithShareUID(bindName)
-                yield shareeView.addressbook()._initSyncToken()
-                yield shareeView._initBindRevision()
-
-        queryCacher = self._txn._queryCacher
-        if queryCacher:
-            cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().name())
-            queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-
-        # Must send notification to ensure cache invalidation occurs
-        yield self.notifyChanged()
-        self.setShared(True)
-        returnValue(bindName)
-
-
-    @inlineCallbacks
-    def _initBindRevision(self):
-        yield self.addressbook()._initBindRevision()
-
-        bind = self._bindSchema
-        yield self._updateBindColumnsQuery(
-            {bind.BIND_REVISION : Parameter(&quot;revision&quot;), }).on(
-            self._txn,
-            revision=self.addressbook()._bindRevision,
-            resourceID=self._resourceID,
-            homeID=self.viewerHome()._resourceID,
-        )
-        yield self.invalidateQueryCache()
-
-
-    @inlineCallbacks
-    def updateShare(self, shareeView, mode=None, status=None, summary=None):
-        &quot;&quot;&quot;
-        Update share mode, status, and message for a home child shared with
-        this (owned) L{CommonHomeChild}.
-
-        @param shareeView: The sharee home child that shares this.
-        @type shareeView: L{CommonHomeChild}
-
-        @param mode: The sharing mode; L{_BIND_MODE_READ} or
-            L{_BIND_MODE_WRITE} or None to not update
-        @type mode: L{str}
-
-        @param status: The sharing status; L{_BIND_STATUS_INVITED} or
-            L{_BIND_STATUS_ACCEPTED} or L{_BIND_STATUS_DECLINED} or
-            L{_BIND_STATUS_INVALID}  or None to not update
-        @type status: L{str}
-
-        @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 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}
-        &quot;&quot;&quot;
-        # TODO: raise a nice exception if shareeView is not, in fact, a shared
-        # version of this same L{CommonHomeChild}
-
-        # remove None parameters, and substitute None for empty string
-        bind = self._bindSchema
-        columnMap = dict([(k, v if v != &quot;&quot; else None)
-                          for k, v in {bind.BIND_MODE:mode,
-                            bind.BIND_STATUS:status,
-                            bind.MESSAGE:summary}.iteritems() if v is not None])
-
-        if len(columnMap):
-
-            # count accepted
-            if status is not None:
-                previouslyAcceptedBindCount = 1 if not self.addressbook().indirect() else 0
-                previouslyAcceptedBindCount += len((
-                    yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                        self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=self.addressbook()._resourceID
-                    )
-                ))
-
-            bindNameRows = yield self._updateBindColumnsQuery(columnMap).on(
-                self._txn,
-                resourceID=self._resourceID, homeID=shareeView.viewerHome()._resourceID
-            )
-
-            # update affected attributes
-            if mode is not None:
-                shareeView._bindMode = columnMap[bind.BIND_MODE]
-
-            if status is not None:
-                shareeView._bindStatus = columnMap[bind.BIND_STATUS]
-                if shareeView._bindStatus == _BIND_STATUS_ACCEPTED:
-                    if 0 == previouslyAcceptedBindCount:
-                        yield shareeView.addressbook()._initSyncToken()
-                        yield shareeView._initBindRevision()
-                        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().name(), None)
-                        shareeView.viewerHome()._children.pop(shareeView._resourceID, 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().name())
-                queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-
-            shareeView._name = bindNameRows[0][0]
-
-            # Must send notification to ensure cache invalidation occurs
-            yield self.notifyChanged()
-
-        returnValue(shareeView._name)
-
-
</del><span class="cx">     @classproperty
</span><span class="cx">     def _acceptedBindForHomeIDAndAddressBookID(cls): #@NoSelf
</span><span class="cx">         bind = cls._bindSchema
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcarddavdatastoretesttest_sqlpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -22,7 +22,7 @@
</span><span class="cx"> from twext.enterprise.dal.syntax import Select, Parameter
</span><span class="cx"> 
</span><span class="cx"> from twisted.internet import reactor
</span><del>-from twisted.internet.defer import inlineCallbacks, returnValue, DeferredList
</del><ins>+from twisted.internet.defer import inlineCallbacks, returnValue
</ins><span class="cx"> from twisted.internet.task import deferLater
</span><span class="cx"> 
</span><span class="cx"> from twisted.trial import unittest
</span><span class="lines">@@ -40,9 +40,7 @@
</span><span class="cx"> 
</span><span class="cx"> from txdav.common.icommondatastore import NoSuchObjectResourceError
</span><span class="cx"> from txdav.common.datastore.sql import EADDRESSBOOKTYPE, CommonObjectResource
</span><del>-from txdav.common.datastore.sql_tables import  _ABO_KIND_PERSON, _ABO_KIND_GROUP, \
-    schema, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED, _BIND_MODE_WRITE, \
-    _BIND_STATUS_INVITED
</del><ins>+from txdav.common.datastore.sql_tables import  _ABO_KIND_PERSON, _ABO_KIND_GROUP, schema
</ins><span class="cx"> from txdav.common.datastore.test.util import buildStore
</span><span class="cx"> 
</span><span class="cx"> from txdav.xml.rfc2518 import GETContentLanguage, ResourceType
</span><span class="lines">@@ -741,13 +739,13 @@
</span><span class="cx"> 
</span><span class="cx">         @inlineCallbacks
</span><span class="cx">         def _defer1():
</span><del>-            yield ab1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary=&quot;Shared Wiki AddressBook&quot;)
</del><ins>+            yield ab1.directShareWithUser(&quot;uid2&quot;)
</ins><span class="cx">             yield txn1.commit()
</span><span class="cx">         d1 = _defer1()
</span><span class="cx"> 
</span><span class="cx">         @inlineCallbacks
</span><span class="cx">         def _defer2():
</span><del>-            yield ab2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, summary=&quot;Shared Wiki AddressBook&quot;)
</del><ins>+            yield ab2.directShareWithUser(&quot;uid1&quot;)
</ins><span class="cx">             yield txn2.commit()
</span><span class="cx">         d2 = _defer2()
</span><span class="cx"> 
</span><span class="lines">@@ -865,250 +863,3 @@
</span><span class="cx">         obj = (yield self.addressbookObjectUnderTest())
</span><span class="cx">         addressbookObject = (yield home.objectResourceWithID(obj._resourceID))
</span><span class="cx">         self.assertNotEquals(addressbookObject, None)
</span><del>-
-
-    @inlineCallbacks
-    def test_shareWithRevision(self):
-        &quot;&quot;&quot;
-        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
-        &quot;&quot;&quot;
-        ab = yield self.addressbookUnderTest()
-        self.assertEqual(ab._bindRevision, 0)
-        other = yield self.homeUnderTest(name=&quot;home2&quot;)
-        newABShareUID = yield ab.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest()
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherAB = yield otherHome.objectWithShareUID(newABShareUID)
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_shareGroupWithRevision(self):
-        &quot;&quot;&quot;
-        Verify that bindRevision on addressbooks and shared groups has the correct value.
-        &quot;&quot;&quot;
-        ab = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(ab._bindRevision, 0)
-        group = yield ab.objectResourceWithName(&quot;4.vcf&quot;)
-        other = yield self.homeUnderTest(name=&quot;home2&quot;)
-        newGroupShareUID = yield group.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherGroup = yield otherHome.objectWithShareUID(newGroupShareUID)
-        otherAB = otherGroup.addressbook()
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_updateShareRevision(self):
-        &quot;&quot;&quot;
-        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
-        &quot;&quot;&quot;
-        ab = yield self.addressbookUnderTest()
-        self.assertEqual(ab._bindRevision, 0)
-        other = yield self.homeUnderTest(name=&quot;home2&quot;)
-        newABShareUID = yield ab.shareWith(other, _BIND_MODE_WRITE, status=_BIND_STATUS_INVITED)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest()
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherAB = yield otherHome.invitedObjectWithShareUID(newABShareUID)
-        self.assertEqual(otherAB._bindRevision, 0)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest()
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherAB = yield otherHome.invitedObjectWithShareUID(newABShareUID)
-        yield normalAB.updateShare(otherAB, status=_BIND_STATUS_ACCEPTED)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest()
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherAB = yield otherHome.objectWithShareUID(newABShareUID)
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_updateSharedGroupRevision(self):
-        &quot;&quot;&quot;
-        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
-        &quot;&quot;&quot;
-        ab = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(ab._bindRevision, 0)
-        group = yield ab.objectResourceWithName(&quot;4.vcf&quot;)
-        other = yield self.homeUnderTest(name=&quot;home2&quot;)
-        newGroupShareUID = yield group.shareWith(other, _BIND_MODE_WRITE, status=_BIND_STATUS_INVITED)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherGroup = yield otherHome.invitedObjectWithShareUID(newGroupShareUID)
-        otherAB = otherGroup.addressbook()
-        self.assertEqual(otherAB._bindRevision, 0)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        normalGroup = yield normalAB.objectResourceWithName(&quot;4.vcf&quot;)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherGroup = yield otherHome.invitedObjectWithShareUID(newGroupShareUID)
-        yield normalGroup.updateShare(otherGroup, status=_BIND_STATUS_ACCEPTED)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherGroup = yield otherHome.objectWithShareUID(newGroupShareUID)
-        otherAB = otherGroup.addressbook()
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_sharedRevisions(self):
-        &quot;&quot;&quot;
-        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
-        &quot;&quot;&quot;
-        ab = yield self.addressbookUnderTest()
-        self.assertEqual(ab._bindRevision, 0)
-        other = yield self.homeUnderTest(name=&quot;home2&quot;)
-        newABShareUID = yield ab.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest()
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherAB = yield otherHome.objectWithShareUID(newABShareUID)
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision - 1)
-        self.assertNotEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision)
-        self.assertEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        for depth in (&quot;1&quot;, &quot;infinity&quot;,):
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision - 1, depth)
-            self.assertNotEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision, depth)
-            self.assertEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-
-    @inlineCallbacks
-    def test_sharedGroupRevisions(self):
-        &quot;&quot;&quot;
-        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
-        &quot;&quot;&quot;
-        ab = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(ab._bindRevision, 0)
-        group = yield ab.objectResourceWithName(&quot;4.vcf&quot;)
-        other = yield self.homeUnderTest(name=&quot;home2&quot;)
-        newGroupShareUID = yield group.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home=&quot;home3&quot;)
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name=&quot;home2&quot;)
-        otherGroup = yield otherHome.objectWithShareUID(newGroupShareUID)
-        otherAB = otherGroup.addressbook()
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision - 1)
-        self.assertNotEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision)
-        self.assertEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        for depth in (&quot;1&quot;, &quot;infinity&quot;,):
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision - 1, depth)
-            self.assertNotEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision, depth)
-            self.assertEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-
-    @inlineCallbacks
-    def test_addressbookRevisionChangeConcurrency(self):
-        &quot;&quot;&quot;
-        Test that two concurrent attempts to add resources in two separate
-        calendar homes does not deadlock on the revision table update.
-        &quot;&quot;&quot;
-
-        # Make sure homes are provisioned
-        txn = self.transactionUnderTest()
-        home_uid1 = yield txn.homeWithUID(EADDRESSBOOKTYPE, &quot;user01&quot;, create=True)
-        home_uid2 = yield txn.homeWithUID(EADDRESSBOOKTYPE, &quot;user02&quot;, create=True)
-        self.assertNotEqual(home_uid1, None)
-        self.assertNotEqual(home_uid2, None)
-        yield self.commit()
-
-        # Create first events in different calendar homes
-        txn1 = self._sqlStore.newTransaction()
-        txn2 = self._sqlStore.newTransaction()
-
-        addressbook_uid1_in_txn1 = yield self.addressbookUnderTest(txn1, &quot;addressbook&quot;, &quot;user01&quot;)
-        addressbook_uid2_in_txn2 = yield self.addressbookUnderTest(txn2, &quot;addressbook&quot;, &quot;user02&quot;)
-
-        data = &quot;&quot;&quot;BEGIN:VCARD
-VERSION:3.0
-PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
-UID:data%(ctr)s
-FN:Data %(ctr)s
-N:Sub Group;;;;
-REV:20120503T194243Z
-END:VCARD
-
-&quot;&quot;&quot;
-
-        component = VComponent.fromString(data % {&quot;ctr&quot;: 1})
-        yield addressbook_uid1_in_txn1.createAddressBookObjectWithName(&quot;data1.ics&quot;, component)
-
-        component = VComponent.fromString(data % {&quot;ctr&quot;: 2})
-        yield addressbook_uid2_in_txn2.createAddressBookObjectWithName(&quot;data2.ics&quot;, component)
-
-        # Setup deferreds to run concurrently and create second events in the calendar homes
-        # previously used by the other transaction - this could create the deadlock.
-        @inlineCallbacks
-        def _defer_uid3():
-            addressbook_uid1_in_txn2 = yield self.addressbookUnderTest(txn2, &quot;addressbook&quot;, &quot;user01&quot;)
-            component = VComponent.fromString(data % {&quot;ctr&quot;: 3})
-            yield addressbook_uid1_in_txn2.createAddressBookObjectWithName(&quot;data3.ics&quot;, component)
-            yield txn2.commit()
-        d1 = _defer_uid3()
-
-        @inlineCallbacks
-        def _defer_uid4():
-            addressbook_uid2_in_txn1 = yield self.addressbookUnderTest(txn1, &quot;addressbook&quot;, &quot;user02&quot;)
-            component = VComponent.fromString(data % {&quot;ctr&quot;: 4})
-            yield addressbook_uid2_in_txn1.createAddressBookObjectWithName(&quot;data4.ics&quot;, component)
-            yield txn1.commit()
-        d2 = _defer_uid4()
-
-        # Now do the concurrent provision attempt
-        yield DeferredList([d1, d2])
-
-        # Verify we did not have a deadlock and all resources have been created.
-        vcarddata1 = yield self.addressbookObjectUnderTest(name=&quot;data1.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user01&quot;)
-        vcarddata2 = yield self.addressbookObjectUnderTest(name=&quot;data2.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user02&quot;)
-        vcarddata3 = yield self.addressbookObjectUnderTest(name=&quot;data3.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user01&quot;)
-        vcarddata4 = yield self.addressbookObjectUnderTest(name=&quot;data4.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user02&quot;)
-        self.assertNotEqual(vcarddata1, None)
-        self.assertNotEqual(vcarddata2, None)
-        self.assertNotEqual(vcarddata3, None)
-        self.assertNotEqual(vcarddata4, None)
</del></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcarddavdatastoretesttest_sql_sharingpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/carddav/datastore/test/test_sql_sharing.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -15,24 +15,26 @@
</span><span class="cx"> ##
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-from twisted.internet.defer import inlineCallbacks, returnValue
</del><ins>+from twisted.internet.defer import inlineCallbacks, returnValue, DeferredList
</ins><span class="cx"> from twisted.trial.unittest import TestCase
</span><span class="cx"> 
</span><del>-from twistedcaldav.vcard import Component as VCard
</del><ins>+from twistedcaldav.vcard import Component as VCard, Component
</ins><span class="cx"> from twext.python.clsprop import classproperty
</span><span class="cx"> from txdav.common.datastore.test.util import CommonCommonTests, buildStore
</span><span class="cx"> from txdav.common.datastore.sql_tables import _BIND_MODE_READ, \
</span><del>-    _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED
</del><ins>+    _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED, \
+    _BIND_MODE_WRITE
</ins><span class="cx"> 
</span><span class="cx"> 
</span><del>-class CalendarSharing(CommonCommonTests, TestCase):
</del><ins>+
+class BaseSharingTests(CommonCommonTests, TestCase):
</ins><span class="cx">     &quot;&quot;&quot;
</span><del>-    Test twistedcaldav.scheduyling.implicit with a Request object.
</del><ins>+    Test store-based address book sharing.
</ins><span class="cx">     &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="cx">     def setUp(self):
</span><del>-        yield super(CalendarSharing, self).setUp()
</del><ins>+        yield super(BaseSharingTests, self).setUp()
</ins><span class="cx">         self._sqlStore = yield buildStore(self, self.notifierFactory)
</span><span class="cx">         yield self.populate()
</span><span class="cx"> 
</span><span class="lines">@@ -57,12 +59,65 @@
</span><span class="cx">         yield populateTxn.commit()
</span><span class="cx">         self.notifierFactory.reset()
</span><span class="cx"> 
</span><ins>+    # Data to populate
+    card1 = &quot;&quot;&quot;BEGIN:VCARD
+VERSION:3.0
+UID:card1
+FN:Card 1
+N:card1;;;;
+END:VCARD
+&quot;&quot;&quot;
</ins><span class="cx"> 
</span><ins>+    card2 = &quot;&quot;&quot;BEGIN:VCARD
+VERSION:3.0
+UID:card2
+FN:Card 2
+N:card2;;;;
+END:VCARD
+&quot;&quot;&quot;
+
+    card3 = &quot;&quot;&quot;BEGIN:VCARD
+VERSION:3.0
+UID:card3
+FN:Card 3
+N:card3;;;;
+END:VCARD
+&quot;&quot;&quot;
+
+    group1 = &quot;&quot;&quot;BEGIN:VCARD
+VERSION:3.0
+UID:group1
+FN:Group 1
+N:group1;;;;
+X-ADDRESSBOOKSERVER-KIND:group
+X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:card1
+X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:card2
+END:VCARD
+&quot;&quot;&quot;
+
+    group2 = &quot;&quot;&quot;BEGIN:VCARD
+VERSION:3.0
+UID:group2
+FN:Group 2
+N:group2;;;;
+X-ADDRESSBOOKSERVER-KIND:group
+X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:card1
+X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:card3
+X-ADDRESSBOOKSERVER-MEMBER:urn:uuid:foreign
+END:VCARD
+&quot;&quot;&quot;
+
+
</ins><span class="cx">     @classproperty(cache=False)
</span><span class="cx">     def requirements(cls): #@NoSelf
</span><span class="cx">         return {
</span><span class="cx">         &quot;user01&quot;: {
</span><span class="cx">             &quot;addressbook&quot;: {
</span><ins>+                &quot;card1.vcf&quot;: cls.card1,
+                &quot;card2.vcf&quot;: cls.card2,
+                &quot;card3.vcf&quot;: cls.card3,
+                &quot;group1.vcf&quot;: cls.group1,
+                &quot;group2.vcf&quot;: cls.group2,
</ins><span class="cx">             },
</span><span class="cx">         },
</span><span class="cx">         &quot;user02&quot;: {
</span><span class="lines">@@ -75,7 +130,12 @@
</span><span class="cx">         },
</span><span class="cx">     }
</span><span class="cx"> 
</span><ins>+    fully_shared_children = [&quot;addressbook.vcf&quot;, &quot;group1.vcf&quot;, &quot;group2.vcf&quot;, &quot;card1.vcf&quot;, &quot;card2.vcf&quot;, &quot;card3.vcf&quot;, ]
+    all_children = [&quot;group1.vcf&quot;, &quot;group2.vcf&quot;, &quot;card1.vcf&quot;, &quot;card2.vcf&quot;, &quot;card3.vcf&quot;, ]
+    group1_children = [&quot;group1.vcf&quot;, &quot;card1.vcf&quot;, &quot;card2.vcf&quot;, ]
+    group2_children = [&quot;group2.vcf&quot;, &quot;card1.vcf&quot;, &quot;card3.vcf&quot;, ]
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx">     def storeUnderTest(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Create and return a L{CalendarStore} for testing.
</span><span class="lines">@@ -84,16 +144,28 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def _createShare(self):
</del><ins>+    def _createShare(self, mode=_BIND_MODE_READ):
+        inviteUID = yield self._inviteShare(mode)
+        sharedName = yield self._acceptShare(inviteUID)
+        returnValue(sharedName)
+
+
+    @inlineCallbacks
+    def _inviteShare(self, mode=_BIND_MODE_READ):
</ins><span class="cx">         # Invite
</span><span class="cx">         addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><span class="cx"> 
</span><del>-        shareeView = yield addressbook.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</del><ins>+        shareeView = yield addressbook.inviteUserToShare(&quot;user02&quot;, mode, &quot;summary&quot;)
</ins><span class="cx">         inviteUID = shareeView.shareUID()
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><ins>+        returnValue(inviteUID)
+
+
+    @inlineCallbacks
+    def _acceptShare(self, inviteUID):
</ins><span class="cx">         # Accept
</span><span class="cx">         shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
</span><span class="cx">         shareeView = yield shareeHome.acceptShare(inviteUID)
</span><span class="lines">@@ -104,6 +176,78 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><ins>+    def _createGroupShare(self, groupname=&quot;group1.vcf&quot;, mode=_BIND_MODE_READ):
+        inviteUID = yield self._inviteGroupShare(groupname, mode)
+        sharedName = yield self._acceptGroupShare(inviteUID)
+        returnValue(sharedName)
+
+
+    @inlineCallbacks
+    def _inviteGroupShare(self, groupname=&quot;group1.vcf&quot;, mode=_BIND_MODE_READ):
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=groupname)
+        shareeView = yield group.inviteUserToShare(&quot;user02&quot;, mode, &quot;summary&quot;)
+        inviteUID = shareeView.shareUID()
+        yield self.commit()
+
+        returnValue(inviteUID)
+
+
+    @inlineCallbacks
+    def _acceptGroupShare(self, inviteUID):
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.acceptShare(inviteUID)
+        yield self.commit()
+
+        returnValue(inviteUID)
+
+
+    @inlineCallbacks
+    def _check_notifications(self, home, items):
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID(home)
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(set(notifications), set(items))
+
+
+    @inlineCallbacks
+    def _check_addressbook(self, home, addressbook_name, child_names):
+        sharedParent = yield self.addressbookUnderTest(home=home, name=addressbook_name)
+        self.assertTrue(sharedParent is not None, msg=&quot;Missing parent:{}&quot;.format(addressbook_name))
+
+        children = yield sharedParent.listAddressBookObjects()
+        self.assertEqual(set(children), set(child_names))
+
+        number = yield sharedParent.countAddressBookObjects()
+        self.assertEqual(number, len(child_names))
+
+        for child in child_names:
+            shared = yield self.addressbookObjectUnderTest(home=home, addressbook_name=addressbook_name, name=child)
+            self.assertTrue(shared is not None, msg=&quot;Missing child:{}&quot;.format(child))
+
+
+    @inlineCallbacks
+    def _check_read_only(self, home, addressbook_name, child_names):
+        for child in child_names:
+            shared = yield self.addressbookObjectUnderTest(home=home, addressbook_name=addressbook_name, name=child)
+            rw_mode = yield shared.readWriteAccess()
+            self.assertFalse(rw_mode)
+
+
+    @inlineCallbacks
+    def _check_read_write(self, home, addressbook_name, child_names):
+        for child in child_names:
+            shared = yield self.addressbookObjectUnderTest(home=home, addressbook_name=addressbook_name, name=child)
+            rw_mode = yield shared.readWriteAccess()
+            self.assertTrue(rw_mode, msg=&quot;Wrong mode: {}&quot;.format(child))
+
+
+
+class AddressBookSharing(BaseSharingTests):
+    &quot;&quot;&quot;
+    Test store-based address book sharing.
+    &quot;&quot;&quot;
+    @inlineCallbacks
</ins><span class="cx">     def test_no_shares(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Test that initially there are no shares.
</span><span class="lines">@@ -112,6 +256,7 @@
</span><span class="cx">         addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(addressbook.isShared())
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -124,6 +269,7 @@
</span><span class="cx">         addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(addressbook.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield addressbook.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="lines">@@ -131,38 +277,41 @@
</span><span class="cx">         self.assertEqual(invites[0].uid, shareeView.shareUID())
</span><span class="cx">         self.assertEqual(invites[0].ownerUID, &quot;user01&quot;)
</span><span class="cx">         self.assertEqual(invites[0].shareeUID, &quot;user02&quot;)
</span><del>-        self.assertEqual(invites[0].shareeName, shareeView.name())
</del><span class="cx">         self.assertEqual(invites[0].mode, _BIND_MODE_READ)
</span><span class="cx">         self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
</span><span class="cx">         self.assertEqual(invites[0].summary, &quot;summary&quot;)
</span><span class="cx">         inviteUID = shareeView.shareUID()
</span><span class="cx"> 
</span><del>-        self.assertEqual(invites[0].shareeName, &quot;user01&quot;)
-
</del><span class="cx">         sharedName = shareeView.name()
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID, ])
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
</ins><span class="cx"> 
</span><ins>+        self.assertTrue(addressbook.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Uninvite
</span><span class="cx">         addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 1)
</span><ins>+        self.assertTrue(addressbook.isShared())
</ins><span class="cx"> 
</span><span class="cx">         yield addressbook.uninviteUserFromShare(&quot;user02&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [])
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [])
</ins><span class="cx"> 
</span><ins>+        self.assertTrue(addressbook.isShared())
</ins><span class="cx"> 
</span><ins>+        yield self.commit()
+
+        addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertFalse(addressbook.isShared())
+
+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_accept_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -173,6 +322,7 @@
</span><span class="cx">         addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(addressbook.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield addressbook.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="lines">@@ -183,10 +333,10 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(len(notifications), 1)
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
</ins><span class="cx"> 
</span><ins>+        self.assertTrue(addressbook.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Accept
</span><span class="lines">@@ -196,10 +346,12 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is not None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><ins>+        addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertTrue(addressbook.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Re-accept
</span><span class="lines">@@ -209,21 +361,24 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is not None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><ins>+        addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertTrue(addressbook.isShared())
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_decline_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><del>-        Test that invite+accept creates shares and notifications.
</del><ins>+        Test that invite+decline does not create shares but does create notifications.
</ins><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">         # Invite
</span><span class="cx">         addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><ins>+        self.assertFalse(addressbook.isShared())
</ins><span class="cx"> 
</span><span class="cx">         shareeView = yield addressbook.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="lines">@@ -234,10 +389,10 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(len(notifications), 1)
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
</ins><span class="cx"> 
</span><ins>+        self.assertTrue(addressbook.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Decline
</span><span class="lines">@@ -247,10 +402,11 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><ins>+        addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertTrue(addressbook.isShared())
+
</ins><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="cx">         # Redecline
</span><span class="lines">@@ -260,11 +416,12 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><ins>+        addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertTrue(addressbook.isShared())
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx">     @inlineCallbacks
</span><span class="cx">     def test_accept_decline_share(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -286,9 +443,7 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(len(notifications), 1)
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
</ins><span class="cx"> 
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="lines">@@ -299,9 +454,8 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is not None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="lines">@@ -312,9 +466,7 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -338,9 +490,7 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(len(notifications), 1)
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
</ins><span class="cx"> 
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="lines">@@ -351,9 +501,8 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is not None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="lines">@@ -364,9 +513,7 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user01&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(notifications, [inviteUID + &quot;-reply&quot;, ])
</del><ins>+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -386,7 +533,6 @@
</span><span class="cx">         self.assertEqual(invites[0].uid, shareeView.shareUID())
</span><span class="cx">         self.assertEqual(invites[0].ownerUID, &quot;user01&quot;)
</span><span class="cx">         self.assertEqual(invites[0].shareeUID, &quot;user02&quot;)
</span><del>-        self.assertEqual(invites[0].shareeName, shareeView.name())
</del><span class="cx">         self.assertEqual(invites[0].mode, _BIND_MODE_DIRECT)
</span><span class="cx">         self.assertEqual(invites[0].status, _BIND_STATUS_ACCEPTED)
</span><span class="cx"> 
</span><span class="lines">@@ -394,9 +540,8 @@
</span><span class="cx">         shared = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=sharedName)
</span><span class="cx">         self.assertTrue(shared is not None)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(len(notifications), 0)
</del><ins>+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_notifications(&quot;user02&quot;, [])
</ins><span class="cx"> 
</span><span class="cx">         yield self.commit()
</span><span class="cx"> 
</span><span class="lines">@@ -408,9 +553,7 @@
</span><span class="cx">         invites = yield addressbook.sharingInvites()
</span><span class="cx">         self.assertEqual(len(invites), 0)
</span><span class="cx"> 
</span><del>-        notifyHome = yield self.transactionUnderTest().notificationsWithUID(&quot;user02&quot;)
-        notifications = yield notifyHome.listNotificationObjects()
-        self.assertEqual(len(notifications), 0)
</del><ins>+        yield self._check_notifications(&quot;user02&quot;, [])
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -428,3 +571,678 @@
</span><span class="cx">         addressbook = yield home.addressbookWithName(shared_name)
</span><span class="cx">         self.assertEquals(addressbook.notifierID(), (&quot;CardDAV&quot;, &quot;user01/addressbook&quot;,))
</span><span class="cx">         yield self.commit()
</span><ins>+
+
+
+class GroupSharing(BaseSharingTests):
+    &quot;&quot;&quot;
+    Test store-based group book sharing.
+    &quot;&quot;&quot;
+
+    @inlineCallbacks
+    def test_no_shares(self):
+        &quot;&quot;&quot;
+        Test that initially there are no shares.
+        &quot;&quot;&quot;
+
+        addressbook = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+
+    @inlineCallbacks
+    def test_invite_sharee(self):
+        &quot;&quot;&quot;
+        Test invite/uninvite creates/removes shares and notifications.
+        &quot;&quot;&quot;
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertEqual(invites[0].uid, shareeView.shareUID())
+        self.assertEqual(invites[0].ownerUID, &quot;user01&quot;)
+        self.assertEqual(invites[0].shareeUID, &quot;user02&quot;)
+        self.assertEqual(invites[0].mode, _BIND_MODE_READ)
+        self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
+        self.assertEqual(invites[0].summary, &quot;summary&quot;)
+        inviteUID = shareeView.shareUID()
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Uninvite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertTrue(group.isShared())
+
+        yield group.uninviteUserFromShare(&quot;user02&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertTrue(group.isShared())
+
+        yield self._check_notifications(&quot;user02&quot;, [])
+
+        yield self.commit()
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertFalse(group.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_share(self):
+        &quot;&quot;&quot;
+        Test that invite+accept creates shares and notifications.
+        &quot;&quot;&quot;
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group1_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Re-accept
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group1_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+
+    @inlineCallbacks
+    def test_decline_share(self):
+        &quot;&quot;&quot;
+        Test that invite+decline does not create shares but does create notifications.
+        &quot;&quot;&quot;
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID)
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Re-decline
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID)
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_decline_share(self):
+        &quot;&quot;&quot;
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the home.
+        &quot;&quot;&quot;
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group1_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID)
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(group.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_remove_share(self):
+        &quot;&quot;&quot;
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the shared collection (removal).
+        &quot;&quot;&quot;
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield group.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_READ, &quot;summary&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user02&quot;, [inviteUID, ])
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group1_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+        yield self.commit()
+
+        # Delete
+        group = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;group1.vcf&quot;)
+        yield group.deleteShare()
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID + &quot;-reply&quot;, ])
+
+
+    @inlineCallbacks
+    def test_accept_two_groups(self):
+        &quot;&quot;&quot;
+        Test that accept of two groups works.
+        &quot;&quot;&quot;
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname=&quot;group1.vcf&quot;)
+        inviteUID2 = yield self._createGroupShare(groupname=&quot;group2.vcf&quot;)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID1 + &quot;-reply&quot;, inviteUID2 + &quot;-reply&quot;, ])
+
+
+    @inlineCallbacks
+    def test_accept_uninvite_two_groups(self):
+        &quot;&quot;&quot;
+        Test that accept of two groups works, then uninvite each one.
+        &quot;&quot;&quot;
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname=&quot;group1.vcf&quot;)
+        inviteUID2 = yield self._createGroupShare(groupname=&quot;group2.vcf&quot;)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID1 + &quot;-reply&quot;, inviteUID2 + &quot;-reply&quot;, ])
+
+        yield self.commit()
+
+        # Uninvite one
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        yield group.uninviteUserFromShare(&quot;user02&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group2_children)
+
+        shared = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(shared is None)
+        shared = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;card2.vcf&quot;)
+        self.assertTrue(shared is None)
+
+        yield self.commit()
+
+        # Uninvite other
+        group = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;group2.vcf&quot;)
+        yield group.uninviteUserFromShare(&quot;user02&quot;)
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+
+    @inlineCallbacks
+    def test_accept_decline_two_groups(self):
+        &quot;&quot;&quot;
+        Test that accept of two groups works, then decline each one.
+        &quot;&quot;&quot;
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname=&quot;group1.vcf&quot;)
+        inviteUID2 = yield self._createGroupShare(groupname=&quot;group2.vcf&quot;)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID1 + &quot;-reply&quot;, inviteUID2 + &quot;-reply&quot;, ])
+
+        yield self.commit()
+
+        # Decline one
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID1)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group2_children)
+
+        shared = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;group1.vcf&quot;)
+        self.assertTrue(shared is None)
+        shared = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;card2.vcf&quot;)
+        self.assertTrue(shared is None)
+
+        yield self.commit()
+
+        # Decline other
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID2)
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+
+    @inlineCallbacks
+    def test_accept_two_groups_different_access(self):
+        &quot;&quot;&quot;
+        Test that accept of two groups works, then uninvite each one.
+        &quot;&quot;&quot;
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname=&quot;group1.vcf&quot;)
+        inviteUID2 = yield self._createGroupShare(groupname=&quot;group2.vcf&quot;, mode=_BIND_MODE_WRITE)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_notifications(&quot;user01&quot;, [inviteUID1 + &quot;-reply&quot;, inviteUID2 + &quot;-reply&quot;, ])
+
+        # Read only for all, write for group2's items
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, [&quot;group1.vcf&quot;, &quot;card2.vcf&quot;, ])
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [&quot;group2.vcf&quot;, &quot;card1.vcf&quot;, &quot;card3.vcf&quot;, ])
+
+        yield self.commit()
+
+        # Decline one
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID2)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.group1_children)
+
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, [&quot;group1.vcf&quot;, &quot;card1.vcf&quot;, &quot;card2.vcf&quot;, ])
+
+        shared = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;group2.vcf&quot;)
+        self.assertTrue(shared is None)
+        shared = yield self.addressbookObjectUnderTest(home=&quot;user02&quot;, addressbook_name=&quot;user01&quot;, name=&quot;card3.vcf&quot;)
+        self.assertTrue(shared is None)
+
+        yield self.commit()
+
+        # Decline other
+        shareeHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        yield shareeHome.declineShare(inviteUID1)
+
+        sharedParent = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertTrue(sharedParent is None)
+
+
+
+class MixedSharing(BaseSharingTests):
+    &quot;&quot;&quot;
+    Test store-based combined address book and group book sharing.
+    &quot;&quot;&quot;
+
+    @inlineCallbacks
+    def test_addressbook_ro_then_groups(self):
+
+        # Share address book read-only
+        shareeName = yield self._createShare()
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [])
+        yield self._check_notifications(&quot;user02&quot;, [shareeName, ])
+
+        # Add group1 read-write
+        inviteUID1 = yield self._createGroupShare(groupname=&quot;group1.vcf&quot;, mode=_BIND_MODE_WRITE)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, [&quot;group2.vcf&quot;, &quot;card3.vcf&quot;, ])
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [&quot;group1.vcf&quot;, &quot;card1.vcf&quot;, &quot;card2.vcf&quot;, ])
+        yield self._check_notifications(&quot;user02&quot;, [shareeName, inviteUID1, ])
+
+        # Add group2 read-write
+        inviteUID2 = yield self._createGroupShare(groupname=&quot;group2.vcf&quot;, mode=_BIND_MODE_WRITE)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, [])
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_notifications(&quot;user02&quot;, [shareeName, inviteUID1, inviteUID2])
+
+        # Uninvite group1
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        yield group.uninviteUserFromShare(&quot;user02&quot;)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, [&quot;group1.vcf&quot;, &quot;card2.vcf&quot;, ])
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [&quot;group2.vcf&quot;, &quot;card1.vcf&quot;, &quot;card3.vcf&quot;, ])
+
+        # Uninvite group2
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group2.vcf&quot;)
+        yield group.uninviteUserFromShare(&quot;user02&quot;)
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [])
+
+
+    @inlineCallbacks
+    def test_addressbook_ro_then_group_no_accept(self):
+
+        # Share address book read-only
+        shareeName = yield self._createShare()
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [])
+        yield self._check_notifications(&quot;user02&quot;, [shareeName, ])
+
+        # Add group1 read-write - but do not accept
+        group = yield self.addressbookObjectUnderTest(home=&quot;user01&quot;, addressbook_name=&quot;addressbook&quot;, name=&quot;group1.vcf&quot;)
+        invited = yield group.inviteUserToShare(&quot;user02&quot;, _BIND_MODE_WRITE, &quot;summary&quot;)
+        yield self._check_notifications(&quot;user02&quot;, [shareeName, invited.shareUID(), ])
+
+        yield self._check_addressbook(&quot;user02&quot;, &quot;user01&quot;, self.fully_shared_children)
+        yield self._check_read_only(&quot;user02&quot;, &quot;user01&quot;, self.all_children)
+        yield self._check_read_write(&quot;user02&quot;, &quot;user01&quot;, [])
+
+
+
+class SharingRevisions(BaseSharingTests):
+    &quot;&quot;&quot;
+    Test store-based sharing and interaction with revision table.
+    &quot;&quot;&quot;
+
+    @inlineCallbacks
+    def test_shareWithRevision(self):
+        &quot;&quot;&quot;
+        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
+        &quot;&quot;&quot;
+        yield self._createShare()
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_shareGroupWithRevision(self):
+        &quot;&quot;&quot;
+        Verify that bindRevision on addressbooks and shared groups has the correct value.
+        &quot;&quot;&quot;
+
+        yield self._createGroupShare(groupname=&quot;group1.vcf&quot;)
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_updateShareRevision(self):
+        &quot;&quot;&quot;
+        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
+        &quot;&quot;&quot;
+        newABShareUID = yield self._inviteShare()
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        otherAB = yield otherHome.anyObjectWithShareUID(&quot;user01&quot;)
+        self.assertEqual(otherAB._bindRevision, 0)
+        yield self.commit()
+
+        yield self._acceptShare(newABShareUID)
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_updateSharedGroupRevision(self):
+        &quot;&quot;&quot;
+        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
+        &quot;&quot;&quot;
+        newGroupShareUID = yield self._inviteGroupShare(groupname=&quot;group1.vcf&quot;)
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        otherAB = yield otherHome.anyObjectWithShareUID(&quot;user01&quot;)
+        self.assertEqual(otherAB._bindRevision, 0)
+        yield self.commit()
+
+        yield self._acceptGroupShare(newGroupShareUID)
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+#    @inlineCallbacks
+    def test_sharedRevisions(self):
+        &quot;&quot;&quot;
+        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
+        &quot;&quot;&quot;
+
+        yield self._createShare()
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision - 1)
+        self.assertNotEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision)
+        self.assertEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        otherHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        for depth in (&quot;1&quot;, &quot;infinity&quot;,):
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision - 1, depth)
+            self.assertNotEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
+
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision, depth)
+            self.assertEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
+
+
+    @inlineCallbacks
+    def test_sharedGroupRevisions(self):
+        &quot;&quot;&quot;
+        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
+        &quot;&quot;&quot;
+
+        yield self._createGroupShare(&quot;group1.vcf&quot;)
+
+        normalAB = yield self.addressbookUnderTest(home=&quot;user01&quot;, name=&quot;addressbook&quot;)
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home=&quot;user02&quot;, name=&quot;user01&quot;)
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision - 1)
+        self.assertNotEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision)
+        self.assertEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        otherHome = yield self.addressbookHomeUnderTest(name=&quot;user02&quot;)
+        for depth in (&quot;1&quot;, &quot;infinity&quot;,):
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision - 1, depth)
+            self.assertNotEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
+
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherAB._bindRevision, depth)
+            self.assertEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
+
+
+    @inlineCallbacks
+    def test_addressbookRevisionChangeConcurrency(self):
+        &quot;&quot;&quot;
+        Test that two concurrent attempts to add resources in two separate
+        calendar homes does not deadlock on the revision table update.
+        &quot;&quot;&quot;
+
+        # Create first events in different addressbook homes
+        txn1 = self._sqlStore.newTransaction()
+        txn2 = self._sqlStore.newTransaction()
+
+        addressbook_uid1_in_txn1 = yield self.addressbookUnderTest(txn1, &quot;addressbook&quot;, &quot;user01&quot;)
+        addressbook_uid2_in_txn2 = yield self.addressbookUnderTest(txn2, &quot;addressbook&quot;, &quot;user02&quot;)
+
+        data = &quot;&quot;&quot;BEGIN:VCARD
+VERSION:3.0
+PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
+UID:data%(ctr)s
+FN:Data %(ctr)s
+N:Sub Group;;;;
+REV:20120503T194243Z
+END:VCARD
+
+&quot;&quot;&quot;
+
+        component = Component.fromString(data % {&quot;ctr&quot;: 1})
+        yield addressbook_uid1_in_txn1.createAddressBookObjectWithName(&quot;data1.ics&quot;, component)
+
+        component = Component.fromString(data % {&quot;ctr&quot;: 2})
+        yield addressbook_uid2_in_txn2.createAddressBookObjectWithName(&quot;data2.ics&quot;, component)
+
+        # Setup deferreds to run concurrently and create second events in the calendar homes
+        # previously used by the other transaction - this could create the deadlock.
+        @inlineCallbacks
+        def _defer_uid3():
+            addressbook_uid1_in_txn2 = yield self.addressbookUnderTest(txn2, &quot;addressbook&quot;, &quot;user01&quot;)
+            component = Component.fromString(data % {&quot;ctr&quot;: 3})
+            yield addressbook_uid1_in_txn2.createAddressBookObjectWithName(&quot;data3.ics&quot;, component)
+            yield txn2.commit()
+        d1 = _defer_uid3()
+
+        @inlineCallbacks
+        def _defer_uid4():
+            addressbook_uid2_in_txn1 = yield self.addressbookUnderTest(txn1, &quot;addressbook&quot;, &quot;user02&quot;)
+            component = Component.fromString(data % {&quot;ctr&quot;: 4})
+            yield addressbook_uid2_in_txn1.createAddressBookObjectWithName(&quot;data4.ics&quot;, component)
+            yield txn1.commit()
+        d2 = _defer_uid4()
+
+        # Now do the concurrent provision attempt
+        yield DeferredList([d1, d2])
+
+        # Verify we did not have a deadlock and all resources have been created.
+        vcarddata1 = yield self.addressbookObjectUnderTest(name=&quot;data1.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user01&quot;)
+        vcarddata2 = yield self.addressbookObjectUnderTest(name=&quot;data2.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user02&quot;)
+        vcarddata3 = yield self.addressbookObjectUnderTest(name=&quot;data3.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user01&quot;)
+        vcarddata4 = yield self.addressbookObjectUnderTest(name=&quot;data4.ics&quot;, addressbook_name=&quot;addressbook&quot;, home=&quot;user02&quot;)
+        self.assertNotEqual(vcarddata1, None)
+        self.assertNotEqual(vcarddata2, None)
+        self.assertNotEqual(vcarddata3, None)
+        self.assertNotEqual(vcarddata4, None)
</ins></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresqlpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql.py        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -1842,28 +1842,6 @@
</span><span class="cx">         return self._childClass.objectWithName(self, name)
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def objectWithShareUID(self, shareUID):
-        &quot;&quot;&quot;
-        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.
-        &quot;&quot;&quot;
-        return self.childWithName(shareUID)
-
-
-    def invitedObjectWithShareUID(self, shareUID):
-        &quot;&quot;&quot;
-        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.
-        &quot;&quot;&quot;
-        return self._childClass.objectWithName(self, shareUID, accepted=False)
-
-
</del><span class="cx">     def anyObjectWithShareUID(self, shareUID):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Retrieve the child accepted or otherwise with the given bind identifier contained in this
</span><span class="lines">@@ -2793,7 +2771,7 @@
</span><span class="cx"> 
</span><span class="cx"> SharingInvitation = namedtuple(
</span><span class="cx">     &quot;SharingInvitation&quot;,
</span><del>-    [&quot;uid&quot;, &quot;ownerUID&quot;, &quot;shareeUID&quot;, &quot;shareeName&quot;, &quot;mode&quot;, &quot;status&quot;, &quot;summary&quot;]
</del><ins>+    [&quot;uid&quot;, &quot;ownerUID&quot;, &quot;ownerHomeID&quot;, &quot;shareeUID&quot;, &quot;shareeHomeID&quot;, &quot;mode&quot;, &quot;status&quot;, &quot;summary&quot;]
</ins><span class="cx"> )
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="lines">@@ -2962,26 +2940,6 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def indirectShareWithUser(self, shareeUID):
-        &quot;&quot;&quot;
-        Create a indirect share with the specified user. An indirect share is one created as a
-        side-effect of some other object being shared.
-
-        NB no invitations are used with indirect sharing.
-
-        @param shareeUID: UID of the sharee
-        @type shareeUID: C{str}
-        &quot;&quot;&quot;
-
-        # Ignore if it already exists
-        shareeView = yield self.shareeView(shareeUID)
-        if shareeView is None:
-            shareeView = yield self.createShare(shareeUID=shareeUID, mode=_BIND_MODE_INDIRECT)
-            yield shareeView.newShare()
-        returnValue(shareeView)
-
-
-    @inlineCallbacks
</del><span class="cx">     def uninviteUserFromShare(self, shareeUID):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Remove a user from a share. Make sure a notification is sent as well.
</span><span class="lines">@@ -2995,7 +2953,7 @@
</span><span class="cx">         if shareeView is not None:
</span><span class="cx">             # If current user state is accepted then we send an invite with the new state, otherwise
</span><span class="cx">             # we cancel any existing invites for the user
</span><del>-            if shareeView.useInvite():
</del><ins>+            if not shareeView.direct():
</ins><span class="cx">                 if shareeView.shareStatus() != _BIND_STATUS_ACCEPTED:
</span><span class="cx">                     yield self._removeInviteNotification(shareeView)
</span><span class="cx">                 else:
</span><span class="lines">@@ -3011,7 +2969,7 @@
</span><span class="cx">         This share is being accepted.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><del>-        if self.useInvite() and self.shareStatus() != _BIND_STATUS_ACCEPTED:
</del><ins>+        if not self.direct() and self.shareStatus() != _BIND_STATUS_ACCEPTED:
</ins><span class="cx">             ownerView = yield self.ownerView()
</span><span class="cx">             yield ownerView.updateShare(self, status=_BIND_STATUS_ACCEPTED)
</span><span class="cx">             yield self.newShare(displayname=summary)
</span><span class="lines">@@ -3024,7 +2982,7 @@
</span><span class="cx">         This share is being declined.
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><del>-        if self.useInvite() and self.shareStatus() != _BIND_STATUS_DECLINED:
</del><ins>+        if not self.direct() and self.shareStatus() != _BIND_STATUS_DECLINED:
</ins><span class="cx">             ownerView = yield self.ownerView()
</span><span class="cx">             yield ownerView.updateShare(self, status=_BIND_STATUS_DECLINED)
</span><span class="cx">             yield self._sendReplyNotification(ownerView)
</span><span class="lines">@@ -3037,10 +2995,10 @@
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">         ownerView = yield self.ownerView()
</span><del>-        if self.useInvite():
-            yield self.declineShare()
-        else:
</del><ins>+        if self.direct():
</ins><span class="cx">             yield ownerView.removeShare(self)
</span><ins>+        else:
+            yield self.declineShare()
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     def newShare(self, displayname=None):
</span><span class="lines">@@ -3058,8 +3016,8 @@
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         invitations = yield self.sharingInvites()
</span><span class="cx"> 
</span><del>-        # remove direct/indirect shares as those are not &quot;real&quot; invitations
-        invitations = filter(lambda x: x.mode not in (_BIND_MODE_DIRECT, _BIND_MODE_INDIRECT), invitations)
</del><ins>+        # remove direct shares as those are not &quot;real&quot; invitations
+        invitations = filter(lambda x: x.mode != _BIND_MODE_DIRECT, invitations)
</ins><span class="cx">         invitations.sort(key=lambda invitation: invitation.shareeUID)
</span><span class="cx">         returnValue(invitations)
</span><span class="cx"> 
</span><span class="lines">@@ -3071,13 +3029,9 @@
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">         # When deleting the message is the sharee's display name
</span><ins>+        displayname = shareeView.shareMessage()
</ins><span class="cx">         if notificationState == _BIND_STATUS_DELETED:
</span><del>-            try:
-                displayname = str(shareeView.properties()[PropertyName.fromElement(element.DisplayName)])
-            except KeyError:
-                displayname = shareeView.name()
-        else:
-            displayname = shareeView.shareMessage()
</del><ins>+            displayname = str(shareeView.properties().get(PropertyName.fromElement(element.DisplayName), displayname))
</ins><span class="cx"> 
</span><span class="cx">         notificationtype = {
</span><span class="cx">             &quot;notification-type&quot;: &quot;invite-notification&quot;,
</span><span class="lines">@@ -3148,7 +3102,30 @@
</span><span class="cx">     #
</span><span class="cx">     # Lower level API
</span><span class="cx">     #
</span><ins>+
</ins><span class="cx">     @inlineCallbacks
</span><ins>+    def ownerView(self):
+        &quot;&quot;&quot;
+        Return the owner resource counterpart of this shared resource.
+        &quot;&quot;&quot;
+        # 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)
+
+
+    @inlineCallbacks
+    def shareeView(self, shareeUID):
+        &quot;&quot;&quot;
+        Return the shared resource counterpart of this owned resource for the specified sharee.
+        &quot;&quot;&quot;
+
+        # 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
</ins><span class="cx">     def shareWith(self, shareeHome, mode, status=None, summary=None):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Share this (owned) L{CommonHomeChild} with another home.
</span><span class="lines">@@ -3179,18 +3156,20 @@
</span><span class="cx">         def doInsert(subt):
</span><span class="cx">             newName = self.newShareName()
</span><span class="cx">             yield self._bindInsertQuery.on(
</span><del>-                subt, homeID=shareeHome._resourceID,
-                resourceID=self._resourceID, name=newName,
-                mode=mode, bindStatus=status, message=summary
</del><ins>+                subt,
+                homeID=shareeHome._resourceID,
+                resourceID=self._resourceID,
+                name=newName,
+                mode=mode,
+                bindStatus=status,
+                message=summary
</ins><span class="cx">             )
</span><span class="cx">             returnValue(newName)
</span><span class="cx">         try:
</span><span class="cx">             bindName = yield self._txn.subtransaction(doInsert)
</span><span class="cx">         except AllRetriesFailed:
</span><span class="cx">             # FIXME: catch more specific exception
</span><del>-            child = yield shareeHome.childWithID(self._resourceID)
-            if not child:
-                child = yield shareeHome.objectWithID(shareeHome, self._resourceID, accepted=False)
</del><ins>+            child = yield shareeHome.allChildWithID(self._resourceID)
</ins><span class="cx">             yield self.updateShare(
</span><span class="cx">                 child, mode=mode, status=status,
</span><span class="cx">                 summary=summary
</span><span class="lines">@@ -3198,7 +3177,7 @@
</span><span class="cx">             bindName = child._name
</span><span class="cx">         else:
</span><span class="cx">             if status == _BIND_STATUS_ACCEPTED:
</span><del>-                shareeView = yield shareeHome.objectWithShareUID(bindName)
</del><ins>+                shareeView = yield shareeHome.anyObjectWithShareUID(bindName)
</ins><span class="cx">                 yield shareeView._initSyncToken()
</span><span class="cx">                 yield shareeView._initBindRevision()
</span><span class="cx"> 
</span><span class="lines">@@ -3213,28 +3192,6 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def ownerView(self):
-        &quot;&quot;&quot;
-        Return the owner resource counterpart of this shared resource.
-        &quot;&quot;&quot;
-        # 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)
-
-
-    @inlineCallbacks
-    def shareeView(self, shareeUID):
-        &quot;&quot;&quot;
-        Return the shared resource counterpart of this owned resource for the specified sharee.
-        &quot;&quot;&quot;
-
-        # 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
</del><span class="cx">     def createShare(self, shareeUID, mode, summary=None):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Create a new shared resource. If the mode is direct, the share is created in accepted state,
</span><span class="lines">@@ -3245,7 +3202,7 @@
</span><span class="cx">         yield self.shareWith(
</span><span class="cx">             shareeHome,
</span><span class="cx">             mode=mode,
</span><del>-            status=_BIND_STATUS_INVITED if mode not in (_BIND_MODE_DIRECT, _BIND_MODE_INDIRECT) else _BIND_STATUS_ACCEPTED,
</del><ins>+            status=_BIND_STATUS_INVITED if mode != _BIND_MODE_DIRECT else _BIND_STATUS_ACCEPTED,
</ins><span class="cx">             summary=summary,
</span><span class="cx">         )
</span><span class="cx">         shareeView = yield self.shareeView(shareeUID)
</span><span class="lines">@@ -3290,6 +3247,10 @@
</span><span class="cx"> 
</span><span class="cx">         if len(columnMap):
</span><span class="cx"> 
</span><ins>+            # Count accepted
+            if status is not None:
+                previouslyAcceptedCount = yield shareeView._previousAcceptCount()
+
</ins><span class="cx">             yield self._updateBindColumnsQuery(columnMap).on(
</span><span class="cx">                 self._txn,
</span><span class="cx">                 resourceID=self._resourceID, homeID=shareeView._home._resourceID
</span><span class="lines">@@ -3301,15 +3262,7 @@
</span><span class="cx"> 
</span><span class="cx">             if status is not None:
</span><span class="cx">                 shareeView._bindStatus = columnMap[bind.BIND_STATUS]
</span><del>-                if shareeView._bindStatus == _BIND_STATUS_ACCEPTED:
-                    yield shareeView._initSyncToken()
-                    yield shareeView._initBindRevision()
-                    shareeView._home._children[shareeView._name] = shareeView
-                    shareeView._home._children[shareeView._resourceID] = shareeView
-                elif shareeView._bindStatus == _BIND_STATUS_DECLINED:
-                    yield shareeView._deletedSyncToken(sharedRemoval=True)
-                    shareeView._home._children.pop(shareeView._name, None)
-                    shareeView._home._children.pop(shareeView._resourceID, None)
</del><ins>+                yield shareeView._changedStatus(previouslyAcceptedCount)
</ins><span class="cx"> 
</span><span class="cx">             if summary is not None:
</span><span class="cx">                 shareeView._bindMessage = columnMap[bind.MESSAGE]
</span><span class="lines">@@ -3326,7 +3279,24 @@
</span><span class="cx">             yield shareeView.viewerHome().notifyChanged()
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    def _previousAcceptCount(self):
+        return succeed(1)
+
+
</ins><span class="cx">     @inlineCallbacks
</span><ins>+    def _changedStatus(self, previouslyAcceptedCount):
+        if self._bindStatus == _BIND_STATUS_ACCEPTED:
+            yield self._initSyncToken()
+            yield self._initBindRevision()
+            self._home._children[self._name] = self
+            self._home._children[self._resourceID] = self
+        elif self._bindStatus in (_BIND_STATUS_INVITED, _BIND_STATUS_DECLINED):
+            yield self._deletedSyncToken(sharedRemoval=True)
+            self._home._children.pop(self._name, None)
+            self._home._children.pop(self._resourceID, None)
+
+
+    @inlineCallbacks
</ins><span class="cx">     def removeShare(self, shareeView):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Remove the shared version of this (owned) L{CommonHomeChild} from the
</span><span class="lines">@@ -3350,7 +3320,11 @@
</span><span class="cx">         yield shareeHome.notifyChanged()
</span><span class="cx"> 
</span><span class="cx">         # delete binds including invites
</span><del>-        yield self._deleteBindForResourceIDAndHomeID.on(self._txn, resourceID=self._resourceID, homeID=shareeHome._resourceID)
</del><ins>+        yield self._deleteBindForResourceIDAndHomeID.on(
+            self._txn,
+            resourceID=self._resourceID,
+            homeID=shareeHome._resourceID,
+        )
</ins><span class="cx"> 
</span><span class="cx">         queryCacher = self._txn._queryCacher
</span><span class="cx">         if queryCacher:
</span><span class="lines">@@ -3373,8 +3347,8 @@
</span><span class="cx">                 yield self.removeShare(shareeView)
</span><span class="cx">         else:
</span><span class="cx">             # This collection is shared to me
</span><del>-            ownerHomeChild = yield self.ownerHome().childWithID(self._resourceID)
-            yield ownerHomeChild.removeShare(self)
</del><ins>+            ownerView = yield self.ownerView()
+            yield ownerView.removeShare(self)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -3398,8 +3372,9 @@
</span><span class="cx">             invite = SharingInvitation(
</span><span class="cx">                 resourceName,
</span><span class="cx">                 self.ownerHome().name(),
</span><ins>+                self.ownerHome().id(),
</ins><span class="cx">                 homeUID,
</span><del>-                resourceName,
</del><ins>+                homeRID,
</ins><span class="cx">                 bindMode,
</span><span class="cx">                 bindStatus,
</span><span class="cx">                 bindMessage,
</span><span class="lines">@@ -3507,15 +3482,6 @@
</span><span class="cx">         return self._bindMode == _BIND_MODE_INDIRECT
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def useInvite(self):
-        &quot;&quot;&quot;
-        Does this type of share use invitations?
-
-        @return: a boolean indicating whether invitations are used.
-        &quot;&quot;&quot;
-        return self._bindMode not in (_BIND_MODE_DIRECT, _BIND_MODE_INDIRECT)
-
-
</del><span class="cx">     def shareUID(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         @see: L{ICalendar.shareUID}
</span><span class="lines">@@ -3550,6 +3516,13 @@
</span><span class="cx">         return self._bindStatus
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    def accepted(self):
+        &quot;&quot;&quot;
+        @see: L{ICalendar.shareStatus}
+        &quot;&quot;&quot;
+        return self._bindStatus == _BIND_STATUS_ACCEPTED
+
+
</ins><span class="cx">     def shareMessage(self):
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         @see: L{ICalendar.shareMessage}
</span><span class="lines">@@ -3818,17 +3791,17 @@
</span><span class="cx"> 
</span><span class="cx">     @classmethod
</span><span class="cx">     def objectWithName(cls, home, name, accepted=True):
</span><del>-        return cls.objectWithNameOrID(home, name=name, accepted=accepted)
</del><ins>+        return cls._objectWithNameOrID(home, name=name, accepted=accepted)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @classmethod
</span><span class="cx">     def objectWithID(cls, home, resourceID, accepted=True):
</span><del>-        return cls.objectWithNameOrID(home, resourceID=resourceID, accepted=accepted)
</del><ins>+        return cls._objectWithNameOrID(home, resourceID=resourceID, accepted=accepted)
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @classmethod
</span><span class="cx">     @inlineCallbacks
</span><del>-    def objectWithNameOrID(cls, home, name=None, resourceID=None, accepted=True):
</del><ins>+    def _objectWithNameOrID(cls, home, name=None, resourceID=None, accepted=True):
</ins><span class="cx">         # replaces objectWithName()
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Retrieve the child with the given C{name} or C{resourceID} contained in the given
</span><span class="lines">@@ -3984,9 +3957,7 @@
</span><span class="cx">             dataRows = None
</span><span class="cx">         if dataRows is None:
</span><span class="cx">             # No cached copy
</span><del>-            dataRows = (
-                yield self._metadataByIDQuery.on(self._txn,
-                    resourceID=self._resourceID))[0]
</del><ins>+            dataRows = (yield self._metadataByIDQuery.on(self._txn, resourceID=self._resourceID))[0]
</ins><span class="cx">             if queryCacher:
</span><span class="cx">                 # Cache the results
</span><span class="cx">                 yield queryCacher.setAfterCommit(self._txn, cacheKey, dataRows)
</span><span class="lines">@@ -4557,8 +4528,7 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def _notifyChanged(self, property_change=False,
-            category=ChangeCategory.default):
</del><ins>+    def _notifyChanged(self, property_change=False, category=ChangeCategory.default):
</ins><span class="cx">         &quot;&quot;&quot;
</span><span class="cx">         Send notifications, change sync token and bump last modified because
</span><span class="cx">         the resource has changed.  We ensure we only do this once per object
</span><span class="lines">@@ -4992,6 +4962,18 @@
</span><span class="cx">         return self._parentCollection
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    def owned(self):
+        return self._parentCollection.owned()
+
+
+    def ownerHome(self):
+        return self._parentCollection.ownerHome()
+
+
+    def viewerHome(self):
+        return self._parentCollection.viewerHome()
+
+
</ins><span class="cx">     @classmethod
</span><span class="cx">     def _selectForUpdateQuery(cls, nowait): #@NoSelf
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="lines">@@ -5366,12 +5348,16 @@
</span><span class="cx">         yield notificationObject.setData(uid, notificationtype, notificationdata, inserting=inserting)
</span><span class="cx">         if inserting:
</span><span class="cx">             yield self._insertRevision(&quot;%s.xml&quot; % (uid,))
</span><ins>+            if self._notificationNames is not None:
+                self._notificationNames.append(notificationObject.uid())
</ins><span class="cx">         else:
</span><span class="cx">             yield self._updateRevision(&quot;%s.xml&quot; % (uid,))
</span><span class="cx">         yield self.notifyChanged()
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     def removeNotificationObjectWithName(self, name):
</span><ins>+        if self._notificationNames is not None:
+            self._notificationNames.remove(self._nameToUID(name))
</ins><span class="cx">         return self.removeNotificationObjectWithUID(self._nameToUID(name))
</span><span class="cx"> 
</span><span class="cx">     _removeByUIDQuery = Delete(
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemacurrentoracledialectsql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current-oracle-dialect.sql        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -58,7 +58,7 @@
</span><span class="cx">     &quot;NOTIFICATION_HOME_RESOURCE_ID&quot; integer not null references NOTIFICATION_HOME,
</span><span class="cx">     &quot;NOTIFICATION_UID&quot; nvarchar2(255),
</span><span class="cx">     &quot;NOTIFICATION_TYPE&quot; nvarchar2(255),
</span><del>-    &quot;XML_DATA&quot; nclob,
</del><ins>+    &quot;NOTIFICATION_DATA&quot; nclob,
</ins><span class="cx">     &quot;MD5&quot; nchar(32),
</span><span class="cx">     &quot;CREATED&quot; timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
</span><span class="cx">     &quot;MODIFIED&quot; timestamp default CURRENT_TIMESTAMP at time zone 'UTC', 
</span><span class="lines">@@ -92,6 +92,7 @@
</span><span class="cx"> insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('read', 1);
</span><span class="cx"> insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('write', 2);
</span><span class="cx"> insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('direct', 3);
</span><ins>+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('indirect', 4);
</ins><span class="cx"> create table CALENDAR_BIND_STATUS (
</span><span class="cx">     &quot;ID&quot; integer primary key,
</span><span class="cx">     &quot;DESCRIPTION&quot; nvarchar2(16) unique
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemacurrentsql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/current.sql        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -702,7 +702,7 @@
</span><span class="cx">   VALUE                         varchar(255)
</span><span class="cx"> );
</span><span class="cx"> 
</span><del>-insert into CALENDARSERVER values ('VERSION', '30');
</del><ins>+insert into CALENDARSERVER values ('VERSION', '29');
</ins><span class="cx"> insert into CALENDARSERVER values ('CALENDAR-DATAVERSION', '5');
</span><span class="cx"> insert into CALENDARSERVER values ('ADDRESSBOOK-DATAVERSION', '2');
</span><span class="cx"> insert into CALENDARSERVER values ('NOTIFICATION-DATAVERSION', '1');
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemaupgradesoracledialectupgrade_from_28_to_29sql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -18,7 +18,7 @@
</span><span class="cx"> -- Upgrade database schema from VERSION 28 to 29 --
</span><span class="cx"> ---------------------------------------------------
</span><span class="cx"> 
</span><del>--- Push notification work related updates
</del><ins>+-- Sharing notification related updates
</ins><span class="cx"> 
</span><span class="cx"> alter table NOTIFICATION_HOME
</span><span class="cx">  add (&quot;DATAVERSION&quot; integer default 0 not null);
</span><span class="lines">@@ -28,5 +28,11 @@
</span><span class="cx"> alter table NOTIFICATION
</span><span class="cx">   rename column XML_DATA to NOTIFICATION_DATA;
</span><span class="cx"> 
</span><ins>+  -- Sharing enumeration updates
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('indirect', 4);
+
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('deleted', 4);
+
</ins><span class="cx"> -- Now update the version
</span><span class="cx"> update CALENDARSERVER set VALUE = '29' where NAME = 'VERSION';
</span><ins>+insert into CALENDARSERVER (NAME, VALUE) values ('NOTIFICATION-DATAVERSION', '1');
</ins></span></pre></div>
<a id="CalendarServerbranchesuserscdaboosharinginthestoretxdavcommondatastoresql_schemaupgradespostgresdialectupgrade_from_28_to_29sql"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql (12006 => 12007)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql        2013-11-23 05:43:57 UTC (rev 12006)
+++ CalendarServer/branches/users/cdaboo/sharing-in-the-store/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql        2013-11-23 21:41:29 UTC (rev 12007)
</span><span class="lines">@@ -18,7 +18,7 @@
</span><span class="cx"> -- Upgrade database schema from VERSION 28 to 29 --
</span><span class="cx"> ---------------------------------------------------
</span><span class="cx"> 
</span><del>--- Push notification work related updates
</del><ins>+-- Sharing notification related updates
</ins><span class="cx"> 
</span><span class="cx"> alter table NOTIFICATION_HOME
</span><span class="cx">   add column DATAVERSION integer default 0 not null;
</span><span class="lines">@@ -28,5 +28,11 @@
</span><span class="cx"> alter table NOTIFICATION
</span><span class="cx">   rename column XML_DATA to NOTIFICATION_DATA;
</span><span class="cx"> 
</span><ins>+-- Sharing enumeration updates
+insert into CALENDAR_BIND_MODE values (4, 'indirect');
+
+insert into CALENDAR_BIND_STATUS values (4, 'deleted');
+
</ins><span class="cx"> -- Now update the version
</span><span class="cx"> update CALENDARSERVER set VALUE = '29' where NAME = 'VERSION';
</span><ins>+insert into CALENDARSERVER values ('NOTIFICATION-DATAVERSION', '1');
</ins></span></pre>
</div>
</div>

</body>
</html>