[CalendarServer-changes] [12132] CalendarServer/branches/users/gaya/sharedgroupfixes

source_changes at macosforge.org source_changes at macosforge.org
Wed Mar 12 11:16:08 PDT 2014


Revision: 12132
          http://trac.calendarserver.org//changeset/12132
Author:   gaya at apple.com
Date:     2013-12-18 17:14:42 -0800 (Wed, 18 Dec 2013)
Log Message:
-----------
merge in 12017 from trunk

Modified Paths:
--------------
    CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-access.xml
    CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-put.xml
    CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-unshare.xml
    CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/notifier.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/test/test_notifier.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/tap/caldav.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twext/python/test/test_launchd.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/customxml.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/notifications.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/resource.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/sharing.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/storebridge.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/test/test_sharing.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/base/datastore/util.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/sql.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/common.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/sql.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/file.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current-oracle-dialect.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_tables.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/test/util.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrade.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/util.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/inotifications.py

Added Paths:
-----------
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql_sharing.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql_sharing.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/oracle-dialect/v29.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/postgres-dialect/v29.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_29_to_30.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_29_to_30.sql
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/notification_upgrade_from_0_to_1.py
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/test/test_notification_upgrade_from_0_to_1.py

Removed Paths:
-------------
    CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/addressbook_store/ho/me/home_empty/

Property Changed:
----------------
    CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/
    CalendarServer/branches/users/gaya/sharedgroupfixes/


Property changes on: CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV
___________________________________________________________________
Modified: svn:mergeinfo
   - /CalDAVTester/branches/release/CalDAVTester-3.0-dev/scripts/tests/CardDAV:7584
/CalDAVTester/branches/release/CalDAVTester-4.3-dev/scripts/tests/CardDAV:10193
/CalDAVTester/branches/users/cdaboo/attendee-comments-2887/scripts/tests/CardDAV:2888-2910
/CalDAVTester/branches/users/cdaboo/better-proxy-3148/scripts/tests/CardDAV:3149-3163
/CalDAVTester/branches/users/cdaboo/component-set-fixes/scripts/tests/CardDAV:8221-8346
/CalDAVTester/branches/users/cdaboo/conditional-4466/scripts/tests/CardDAV:4467-4469
/CalDAVTester/branches/users/cdaboo/implicitauto-2948/scripts/tests/CardDAV:2949-2989
/CalDAVTester/branches/users/cdaboo/location-partial-accept-3574/scripts/tests/CardDAV:3575-3581
/CalDAVTester/branches/users/cdaboo/managed-attachments/scripts/tests/CardDAV:9986-10145
/CalDAVTester/branches/users/cdaboo/normalize-cuaddr-3533/scripts/tests/CardDAV:3534-3558
/CalDAVTester/branches/users/cdaboo/pycalendar/scripts/tests/CardDAV:7160-7206
/CalDAVTester/branches/users/cdaboo/pycard/scripts/tests/CardDAV:7226-7237
/CalDAVTester/branches/users/cdaboo/sharing-5228/scripts/tests/CardDAV:5229-5440
/CalDAVTester/branches/users/gaya/sharedgroupstester-2/scripts/tests/CardDAV:11078-11181
/CalDAVTester/branches/users/gaya/sharedgroupstester-3/scripts/tests/CardDAV:11181-11204
/CalDAVTester/trunk/scripts/tests/CardDAV:11742-12016
   + /CalDAVTester/branches/release/CalDAVTester-3.0-dev/scripts/tests/CardDAV:7584
/CalDAVTester/branches/release/CalDAVTester-4.3-dev/scripts/tests/CardDAV:10193
/CalDAVTester/branches/users/cdaboo/attendee-comments-2887/scripts/tests/CardDAV:2888-2910
/CalDAVTester/branches/users/cdaboo/better-proxy-3148/scripts/tests/CardDAV:3149-3163
/CalDAVTester/branches/users/cdaboo/component-set-fixes/scripts/tests/CardDAV:8221-8346
/CalDAVTester/branches/users/cdaboo/conditional-4466/scripts/tests/CardDAV:4467-4469
/CalDAVTester/branches/users/cdaboo/implicitauto-2948/scripts/tests/CardDAV:2949-2989
/CalDAVTester/branches/users/cdaboo/location-partial-accept-3574/scripts/tests/CardDAV:3575-3581
/CalDAVTester/branches/users/cdaboo/managed-attachments/scripts/tests/CardDAV:9986-10145
/CalDAVTester/branches/users/cdaboo/normalize-cuaddr-3533/scripts/tests/CardDAV:3534-3558
/CalDAVTester/branches/users/cdaboo/pycalendar/scripts/tests/CardDAV:7160-7206
/CalDAVTester/branches/users/cdaboo/pycard/scripts/tests/CardDAV:7226-7237
/CalDAVTester/branches/users/cdaboo/sharing-5228/scripts/tests/CardDAV:5229-5440
/CalDAVTester/branches/users/gaya/sharedgroupstester-2/scripts/tests/CardDAV:11078-11181
/CalDAVTester/branches/users/gaya/sharedgroupstester-3/scripts/tests/CardDAV:11181-11204
/CalDAVTester/trunk/scripts/tests/CardDAV:11742-12020

Modified: CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-access.xml
===================================================================
--- CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-access.xml	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-access.xml	2013-12-19 01:14:42 UTC (rev 12132)
@@ -27,7 +27,7 @@
 	</require-feature>
 
 	<start>
-		<description>clean up old data</description>
+		<!-- clean up old data -->
 		<request user="$useradmin:" pswd="$pswdadmin:">
 			<method>DELETEALL</method>
 			<ruri>$addressbookhome1:/</ruri>
@@ -36,7 +36,7 @@
 			<ruri>$notificationpath2:/</ruri>
 		</request>
 
-		<description>add 5 persons and 2 groups to user2 address book</description>
+		<!-- add 5 persons and 2 groups to user2 address book -->
 		<request user="$userid2:" pswd="$pswd2:">
 			<method>PUT</method>
 			<ruri>$addressbookpath2:/1.vcf</ruri>
@@ -104,7 +104,7 @@
 				<ruri>$addressbookhome1:/</ruri>
 				<ruri>$notificationpath1:/</ruri>
 			</request>
-			<description>user2 POSTs invitation</description>
+			<!-- user2 POSTs invitation -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/</ruri>
@@ -113,7 +113,7 @@
 					<filepath>Resource/CardDAV/sharing/access/addressbook/1.xml</filepath>
 				</data>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -126,7 +126,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -305,6 +305,7 @@
 			</request>
 		</test>
 	</test-suite>
+
 	<test-suite name='fully-shared read-only addressbook' ignore='no'>
 		<test name='0' ignore='no'>
 			<description>reset user1 home and share user2 addressbook read-only</description>
@@ -314,7 +315,7 @@
 				<ruri>$notificationpath1:/</ruri>
 				<ruri>$notificationpath2:/</ruri>
 			</request>
-			<description>user2 POSTs invitation</description>
+			<!-- user2 POSTs invitation -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/</ruri>
@@ -323,7 +324,7 @@
 					<filepath>Resource/CardDAV/sharing/access/addressbook/4.xml</filepath>
 				</data>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -336,7 +337,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -495,7 +496,7 @@
 				<ruri>$addressbookhome1:/</ruri>
 				<ruri>$notificationpath1:/</ruri>
 			</request>
-			<description>user2 POSTs invitation</description>
+			<!-- user2 POSTs invitation -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/g123.vcf</ruri>
@@ -507,7 +508,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -520,7 +521,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -695,7 +696,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>delete added vCard</description>
+			<!-- delete added vCard -->
 			<request user="$userid2:" pswd="$pswd2:">
 				<method>DELETE</method>
 				<ruri>$addressbookpath2:/6.vcf</ruri>
@@ -703,7 +704,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>add back removed vCard</description>
+			<!-- add back removed vCard -->
 			<request user="$userid2:" pswd="$pswd2:">
 				<method>PUT</method>
 				<ruri>$addressbookpath2:/2.vcf</ruri>
@@ -728,7 +729,7 @@
 				<ruri>$notificationpath1:/</ruri>
 				<ruri>$notificationpath2:/</ruri>
 			</request>
-			<description>user2 POSTs invitation</description>
+			<!-- user2 POSTs invitation -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/g345.vcf</ruri>
@@ -740,7 +741,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -753,7 +754,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -905,7 +906,7 @@
 				<ruri>$addressbookhome1:/</ruri>
 				<ruri>$notificationpath1:/</ruri>
 			</request>
-			<description>user2 POSTs read-write invitation to group</description>
+			<!-- user2 POSTs read-write invitation to group -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/g123.vcf</ruri>
@@ -917,7 +918,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -930,7 +931,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -943,8 +944,7 @@
 				<method>DELETE</method>
 				<ruri>$notificationpath1:/$inviteuid:</ruri>
 			</request>
-			
-			<description>user2 POSTs invitation read-only to group</description>
+			<!-- user2 POSTs invitation read-only to group -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/g345.vcf</ruri>
@@ -956,7 +956,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -969,7 +969,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -1229,7 +1229,7 @@
 	<test-suite name='overlapping read-only, read-write shared groups, read-write addressbook' ignore='no'>
 		<test name='0' ignore='no'>
 			<description>share user2 addressbook read-write</description>
-			<description>user2 POSTs invitation</description>
+			<!-- user2 POSTs invitation -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/</ruri>
@@ -1238,7 +1238,7 @@
 					<filepath>Resource/CardDAV/sharing/access/addressbook/1.xml</filepath>
 				</data>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -1251,7 +1251,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -1373,7 +1373,7 @@
 	<test-suite name='overlapping read-only, read-write shared groups, read-only addressbook' ignore='no'>
 		<test name='0' ignore='no'>
 			<description>share user2 addressbook read-only</description>
-			<description>user2 POSTs invitation</description>
+			<!-- user2 POSTs invitation -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/</ruri>
@@ -1382,7 +1382,7 @@
 					<filepath>Resource/CardDAV/sharing/access/addressbook/4.xml</filepath>
 				</data>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -1395,7 +1395,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>
@@ -1486,7 +1486,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>user2 POSTs invitation read-write to group 345</description>
+			<!-- user2 POSTs invitation read-write to group 345 -->
 			<request user="$userid2:" pswd="$pswd2:" print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookpath2:/g345.vcf</ruri>
@@ -1498,7 +1498,7 @@
 					<callback>statusCode</callback>
 				</verify>
 			</request>
-			<description>Check user1 notification collection and get invite uid</description>
+			<!-- Check user1 notification collection and get invite uid -->
 			<request print-response="no">
 				<method>WAITCOUNT 1</method>
 				<ruri>$notificationpath1:/</ruri>
@@ -1511,7 +1511,7 @@
 					<variable>$inviteuid:</variable>
 				</grabelement>
 			</request>
-			<description>user1 replies ACCEPTED and deletes notification</description>
+			<!-- user1 replies ACCEPTED and deletes notification -->
 			<request print-response="no">
 				<method>POST</method>
 				<ruri>$addressbookhome1:/</ruri>

Modified: CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-put.xml
===================================================================
--- CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-put.xml	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-put.xml	2013-12-19 01:14:42 UTC (rev 12132)
@@ -27,7 +27,7 @@
 	</require-feature>
 
 	<start>
-		<description>clean up old data</description>
+		<!-- clean up old data -->
 		<request user="$useradmin:" pswd="$pswdadmin:">
 			<method>DELETEALL</method>
 			<ruri>$addressbookhome1:/</ruri>
@@ -36,7 +36,7 @@
 			<ruri>$notificationpath2:/</ruri>
 		</request>
 
-		<description>add 1 person in two groups to user2 address book</description>
+		<!-- add 1 person in two groups to user2 address book -->
 		<request user="$userid2:" pswd="$pswd2:">
 			<method>PUT</method>
 			<ruri>$addressbookpath2:/1.vcf</ruri>
@@ -61,7 +61,7 @@
 				<filepath>Resource/CardDAV/sharing/put/3.vcf</filepath>
 			</data>
 		</request>
-		<description>user2 POSTs invitation</description>
+		<!-- user2 POSTs invitation -->
 		<request user="$userid2:" pswd="$pswd2:" print-response="no">
 			<method>POST</method>
 			<ruri>$addressbookpath2:/2.vcf</ruri>
@@ -73,7 +73,7 @@
 				<callback>statusCode</callback>
 			</verify>
 		</request>
-		<description>Check user1 notification collection and get invite uid</description>
+		<!-- Check user1 notification collection and get invite uid -->
 		<request print-response="no">
 			<method>WAITCOUNT 1</method>
 			<ruri>$notificationpath1:/</ruri>
@@ -86,7 +86,7 @@
 				<variable>$inviteuid:</variable>
 			</grabelement>
 		</request>
-		<description>user1 replies ACCEPTED and deletes notification</description>
+		<!-- user1 replies ACCEPTED and deletes notification -->
 		<request print-response="no">
 			<method>POST</method>
 			<ruri>$addressbookhome1:/</ruri>

Modified: CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-unshare.xml
===================================================================
--- CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-unshare.xml	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalDAVTester/branches/users/gaya/sharedgroupfixestester/scripts/tests/CardDAV/sharing-unshare.xml	2013-12-19 01:14:42 UTC (rev 12132)
@@ -1203,7 +1203,7 @@
 				<ruri>$addressbookhome2:/</ruri>
 				<data substitutions='yes'>
 					<content-type>application/xml; charset=utf-8</content-type>
-					<filepath>Resource/CardDAV/sharing/unshare/shareedecline/2.xml</filepath>
+					<filepath>Resource/CardDAV/sharing/unshare/shareedecline/4.xml</filepath>
 				</data>
 				<verify>
 					<callback>statusCode</callback>
@@ -1245,7 +1245,7 @@
 					<callback>xmlDataMatch</callback>
 					<arg>
 						<name>filepath</name>
-						<value>Resource/CardDAV/sharing/unshare/shareedecline/1.xml</value>
+						<value>Resource/CardDAV/sharing/unshare/shareedecline/3.xml</value>
 					</arg>
 					<arg>
 						<name>filter</name>
@@ -1262,6 +1262,7 @@
 			</request>
 		</test>
 	</test-suite>	
+
 	<test-suite name='reshare group, sharee delete addressbook' ignore='no'>
 		<test name='1' ignore='no'>
 			<description>POST invitation</description>
@@ -1458,6 +1459,7 @@
 			</request>
 		</test>
 	</test-suite>	
+
 	<test-suite name='rehare group, sharee delete group' ignore='no'>
 		<test name='1' ignore='no'>
 			<description>POST invitation</description>
@@ -1654,6 +1656,7 @@
 			</request>
 		</test>
 	</test-suite>	
+
 	<test-suite name='reshare group, sharer uninvite' ignore='no'>
 		<test name='1' ignore='no'>
 			<description>POST invitation</description>
@@ -1850,6 +1853,7 @@
 			</request>
 		</test>
 	</test-suite>	
+
 	<test-suite name='reshare group, sharer delete group' ignore='no'>
 		<test name='1' ignore='no'>
 			<description>POST invitation</description>
@@ -2047,6 +2051,7 @@
 			</request>
 		</test>
 	</test-suite>	
+
 	<test-suite name='recreate and share group, sharer delete addressbook' ignore='no'>
 		<test name='0' ignore='no'>
 			<request user="$userid1:" pswd="$pswd1:">


Property changes on: CalendarServer/branches/users/gaya/sharedgroupfixes
___________________________________________________________________
Modified: svn:mergeinfo
   - /CalDAVTester/trunk:11193-11198
/CalendarServer/branches/config-separation:4379-4443
/CalendarServer/branches/egg-info-351:4589-4625
/CalendarServer/branches/generic-sqlstore:6167-6191
/CalendarServer/branches/new-store:5594-5934
/CalendarServer/branches/new-store-no-caldavfile:5911-5935
/CalendarServer/branches/new-store-no-caldavfile-2:5936-5981
/CalendarServer/branches/release/CalendarServer-4.3-dev:10180-10190,10192
/CalendarServer/branches/release/CalendarServer-5.1-dev:11846
/CalendarServer/branches/users/cdaboo/batchupload-6699:6700-7198
/CalendarServer/branches/users/cdaboo/cached-subscription-calendars-5692:5693-5702
/CalendarServer/branches/users/cdaboo/component-set-fixes:8130-8346
/CalendarServer/branches/users/cdaboo/directory-cache-on-demand-3627:3628-3644
/CalendarServer/branches/users/cdaboo/fix-no-ischedule:11607-11871
/CalendarServer/branches/users/cdaboo/implicituidrace:8137-8141
/CalendarServer/branches/users/cdaboo/ischedule-dkim:9747-9979
/CalendarServer/branches/users/cdaboo/json:11622-11912
/CalendarServer/branches/users/cdaboo/managed-attachments:9985-10145
/CalendarServer/branches/users/cdaboo/more-sharing-5591:5592-5601
/CalendarServer/branches/users/cdaboo/partition-4464:4465-4957
/CalendarServer/branches/users/cdaboo/performance-tweaks:11824-11836
/CalendarServer/branches/users/cdaboo/pods:7297-7377
/CalendarServer/branches/users/cdaboo/pycalendar:7085-7206
/CalendarServer/branches/users/cdaboo/pycard:7227-7237
/CalendarServer/branches/users/cdaboo/queued-attendee-refreshes:7740-8287
/CalendarServer/branches/users/cdaboo/relative-config-paths-5070:5071-5105
/CalendarServer/branches/users/cdaboo/reverse-proxy-pods:11875-11900
/CalendarServer/branches/users/cdaboo/shared-calendars-5187:5188-5440
/CalendarServer/branches/users/cdaboo/store-scheduling:10876-11129
/CalendarServer/branches/users/cdaboo/timezones:7443-7699
/CalendarServer/branches/users/cdaboo/txn-debugging:8730-8743
/CalendarServer/branches/users/gaya/sharedgroups-3:11088-11204
/CalendarServer/branches/users/glyph/always-abort-txn-on-error:9958-9969
/CalendarServer/branches/users/glyph/case-insensitive-uid:8772-8805
/CalendarServer/branches/users/glyph/conn-limit:6574-6577
/CalendarServer/branches/users/glyph/contacts-server-merge:4971-5080
/CalendarServer/branches/users/glyph/dalify:6932-7023
/CalendarServer/branches/users/glyph/db-reconnect:6824-6876
/CalendarServer/branches/users/glyph/deploybuild:7563-7572
/CalendarServer/branches/users/glyph/digest-auth-redux:10624-10635
/CalendarServer/branches/users/glyph/disable-quota:7718-7727
/CalendarServer/branches/users/glyph/dont-start-postgres:6592-6614
/CalendarServer/branches/users/glyph/enforce-max-requests:11640-11643
/CalendarServer/branches/users/glyph/hang-fix:11465-11491
/CalendarServer/branches/users/glyph/imip-and-admin-html:7866-7984
/CalendarServer/branches/users/glyph/ipv6-client:9054-9105
/CalendarServer/branches/users/glyph/launchd-wrapper-bis:11413-11436
/CalendarServer/branches/users/glyph/linux-tests:6893-6900
/CalendarServer/branches/users/glyph/log-cleanups:11691-11731
/CalendarServer/branches/users/glyph/migrate-merge:8690-8713
/CalendarServer/branches/users/glyph/misc-portability-fixes:7365-7374
/CalendarServer/branches/users/glyph/more-deferreds-6:6322-6368
/CalendarServer/branches/users/glyph/more-deferreds-7:6369-6445
/CalendarServer/branches/users/glyph/multiget-delete:8321-8330
/CalendarServer/branches/users/glyph/new-export:7444-7485
/CalendarServer/branches/users/glyph/one-home-list-api:10048-10073
/CalendarServer/branches/users/glyph/oracle:7106-7155
/CalendarServer/branches/users/glyph/oracle-nulls:7340-7351
/CalendarServer/branches/users/glyph/other-html:8062-8091
/CalendarServer/branches/users/glyph/parallel-sim:8240-8251
/CalendarServer/branches/users/glyph/parallel-upgrade:8376-8400
/CalendarServer/branches/users/glyph/parallel-upgrade_to_1:8571-8583
/CalendarServer/branches/users/glyph/q:9560-9688
/CalendarServer/branches/users/glyph/queue-locking-and-timing:10204-10289
/CalendarServer/branches/users/glyph/quota:7604-7637
/CalendarServer/branches/users/glyph/sendfdport:5388-5424
/CalendarServer/branches/users/glyph/shared-pool-fixes:8436-8443
/CalendarServer/branches/users/glyph/shared-pool-take2:8155-8174
/CalendarServer/branches/users/glyph/sharedpool:6490-6550
/CalendarServer/branches/users/glyph/sharing-api:9192-9205
/CalendarServer/branches/users/glyph/skip-lonely-vtimezones:8524-8535
/CalendarServer/branches/users/glyph/sql-store:5929-6073
/CalendarServer/branches/users/glyph/start-service-start-loop:11060-11065
/CalendarServer/branches/users/glyph/subtransactions:7248-7258
/CalendarServer/branches/users/glyph/table-alias:8651-8664
/CalendarServer/branches/users/glyph/uidexport:7673-7676
/CalendarServer/branches/users/glyph/unshare-when-access-revoked:10562-10595
/CalendarServer/branches/users/glyph/use-system-twisted:5084-5149
/CalendarServer/branches/users/glyph/uuid-normalize:9268-9296
/CalendarServer/branches/users/glyph/warning-cleanups:11347-11357
/CalendarServer/branches/users/glyph/whenNotProposed:11881-11897
/CalendarServer/branches/users/glyph/xattrs-from-files:7757-7769
/CalendarServer/branches/users/sagen/applepush:8126-8184
/CalendarServer/branches/users/sagen/inboxitems:7380-7381
/CalendarServer/branches/users/sagen/locations-resources:5032-5051
/CalendarServer/branches/users/sagen/locations-resources-2:5052-5061
/CalendarServer/branches/users/sagen/purge_old_events:6735-6746
/CalendarServer/branches/users/sagen/resource-delegates-4038:4040-4067
/CalendarServer/branches/users/sagen/resource-delegates-4066:4068-4075
/CalendarServer/branches/users/sagen/resources-2:5084-5093
/CalendarServer/branches/users/sagen/testing:10827-10851,10853-10855
/CalendarServer/branches/users/wsanchez/transations:5515-5593
/CalendarServer/trunk:11632-11860,11862-12016
   + /CalDAVTester/trunk:11193-11198
/CalendarServer/branches/config-separation:4379-4443
/CalendarServer/branches/egg-info-351:4589-4625
/CalendarServer/branches/generic-sqlstore:6167-6191
/CalendarServer/branches/new-store:5594-5934
/CalendarServer/branches/new-store-no-caldavfile:5911-5935
/CalendarServer/branches/new-store-no-caldavfile-2:5936-5981
/CalendarServer/branches/release/CalendarServer-4.3-dev:10180-10190,10192
/CalendarServer/branches/release/CalendarServer-5.1-dev:11846
/CalendarServer/branches/users/cdaboo/batchupload-6699:6700-7198
/CalendarServer/branches/users/cdaboo/cached-subscription-calendars-5692:5693-5702
/CalendarServer/branches/users/cdaboo/component-set-fixes:8130-8346
/CalendarServer/branches/users/cdaboo/directory-cache-on-demand-3627:3628-3644
/CalendarServer/branches/users/cdaboo/fix-no-ischedule:11607-11871
/CalendarServer/branches/users/cdaboo/implicituidrace:8137-8141
/CalendarServer/branches/users/cdaboo/ischedule-dkim:9747-9979
/CalendarServer/branches/users/cdaboo/json:11622-11912
/CalendarServer/branches/users/cdaboo/managed-attachments:9985-10145
/CalendarServer/branches/users/cdaboo/more-sharing-5591:5592-5601
/CalendarServer/branches/users/cdaboo/partition-4464:4465-4957
/CalendarServer/branches/users/cdaboo/performance-tweaks:11824-11836
/CalendarServer/branches/users/cdaboo/pods:7297-7377
/CalendarServer/branches/users/cdaboo/pycalendar:7085-7206
/CalendarServer/branches/users/cdaboo/pycard:7227-7237
/CalendarServer/branches/users/cdaboo/queued-attendee-refreshes:7740-8287
/CalendarServer/branches/users/cdaboo/relative-config-paths-5070:5071-5105
/CalendarServer/branches/users/cdaboo/reverse-proxy-pods:11875-11900
/CalendarServer/branches/users/cdaboo/shared-calendars-5187:5188-5440
/CalendarServer/branches/users/cdaboo/sharing-in-the-store:11935-12016
/CalendarServer/branches/users/cdaboo/store-scheduling:10876-11129
/CalendarServer/branches/users/cdaboo/timezones:7443-7699
/CalendarServer/branches/users/cdaboo/txn-debugging:8730-8743
/CalendarServer/branches/users/gaya/sharedgroups-3:11088-11204
/CalendarServer/branches/users/glyph/always-abort-txn-on-error:9958-9969
/CalendarServer/branches/users/glyph/case-insensitive-uid:8772-8805
/CalendarServer/branches/users/glyph/conn-limit:6574-6577
/CalendarServer/branches/users/glyph/contacts-server-merge:4971-5080
/CalendarServer/branches/users/glyph/dalify:6932-7023
/CalendarServer/branches/users/glyph/db-reconnect:6824-6876
/CalendarServer/branches/users/glyph/deploybuild:7563-7572
/CalendarServer/branches/users/glyph/digest-auth-redux:10624-10635
/CalendarServer/branches/users/glyph/disable-quota:7718-7727
/CalendarServer/branches/users/glyph/dont-start-postgres:6592-6614
/CalendarServer/branches/users/glyph/enforce-max-requests:11640-11643
/CalendarServer/branches/users/glyph/hang-fix:11465-11491
/CalendarServer/branches/users/glyph/imip-and-admin-html:7866-7984
/CalendarServer/branches/users/glyph/ipv6-client:9054-9105
/CalendarServer/branches/users/glyph/launchd-wrapper-bis:11413-11436
/CalendarServer/branches/users/glyph/linux-tests:6893-6900
/CalendarServer/branches/users/glyph/log-cleanups:11691-11731
/CalendarServer/branches/users/glyph/migrate-merge:8690-8713
/CalendarServer/branches/users/glyph/misc-portability-fixes:7365-7374
/CalendarServer/branches/users/glyph/more-deferreds-6:6322-6368
/CalendarServer/branches/users/glyph/more-deferreds-7:6369-6445
/CalendarServer/branches/users/glyph/multiget-delete:8321-8330
/CalendarServer/branches/users/glyph/new-export:7444-7485
/CalendarServer/branches/users/glyph/one-home-list-api:10048-10073
/CalendarServer/branches/users/glyph/oracle:7106-7155
/CalendarServer/branches/users/glyph/oracle-nulls:7340-7351
/CalendarServer/branches/users/glyph/other-html:8062-8091
/CalendarServer/branches/users/glyph/parallel-sim:8240-8251
/CalendarServer/branches/users/glyph/parallel-upgrade:8376-8400
/CalendarServer/branches/users/glyph/parallel-upgrade_to_1:8571-8583
/CalendarServer/branches/users/glyph/q:9560-9688
/CalendarServer/branches/users/glyph/queue-locking-and-timing:10204-10289
/CalendarServer/branches/users/glyph/quota:7604-7637
/CalendarServer/branches/users/glyph/sendfdport:5388-5424
/CalendarServer/branches/users/glyph/shared-pool-fixes:8436-8443
/CalendarServer/branches/users/glyph/shared-pool-take2:8155-8174
/CalendarServer/branches/users/glyph/sharedpool:6490-6550
/CalendarServer/branches/users/glyph/sharing-api:9192-9205
/CalendarServer/branches/users/glyph/skip-lonely-vtimezones:8524-8535
/CalendarServer/branches/users/glyph/sql-store:5929-6073
/CalendarServer/branches/users/glyph/start-service-start-loop:11060-11065
/CalendarServer/branches/users/glyph/subtransactions:7248-7258
/CalendarServer/branches/users/glyph/table-alias:8651-8664
/CalendarServer/branches/users/glyph/uidexport:7673-7676
/CalendarServer/branches/users/glyph/unshare-when-access-revoked:10562-10595
/CalendarServer/branches/users/glyph/use-system-twisted:5084-5149
/CalendarServer/branches/users/glyph/uuid-normalize:9268-9296
/CalendarServer/branches/users/glyph/warning-cleanups:11347-11357
/CalendarServer/branches/users/glyph/whenNotProposed:11881-11897
/CalendarServer/branches/users/glyph/xattrs-from-files:7757-7769
/CalendarServer/branches/users/sagen/applepush:8126-8184
/CalendarServer/branches/users/sagen/inboxitems:7380-7381
/CalendarServer/branches/users/sagen/locations-resources:5032-5051
/CalendarServer/branches/users/sagen/locations-resources-2:5052-5061
/CalendarServer/branches/users/sagen/purge_old_events:6735-6746
/CalendarServer/branches/users/sagen/resource-delegates-4038:4040-4067
/CalendarServer/branches/users/sagen/resource-delegates-4066:4068-4075
/CalendarServer/branches/users/sagen/resources-2:5084-5093
/CalendarServer/branches/users/sagen/testing:10827-10851,10853-10855
/CalendarServer/branches/users/wsanchez/transations:5515-5593
/CalendarServer/trunk:11632-11860,11862-12017

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/notifier.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/notifier.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/notifier.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -38,7 +38,6 @@
 
 
 
-
 class PushNotificationWork(WorkItem, fromTable(schema.PUSH_NOTIFICATION_WORK)):
 
     group = property(lambda self: self.pushID)

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/test/test_notifier.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/test/test_notifier.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/push/test/test_notifier.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -99,6 +99,7 @@
         return(succeed(None))
 
 
+
 class PushNotificationWorkTests(StoreTestCase):
 
     @inlineCallbacks
@@ -179,6 +180,7 @@
             [("/CalDAV/localhost/bar/", PushPriority.high)])
 
 
+
 class NotifierFactory(StoreTestCase):
 
     requirements = {
@@ -231,27 +233,27 @@
     def test_shareWithNotifier(self):
 
         calendar = yield self.calendarUnderTest()
-        home2 = yield self.homeUnderTest(name="home2")
-        yield calendar.shareWith(home2, _BIND_MODE_WRITE)
+        yield calendar.inviteUserToShare("home2", _BIND_MODE_WRITE, "")
         self.assertEquals(
             set(self.notifierFactory.history),
             set([
                 ("/CalDAV/example.com/home1/", PushPriority.high),
                 ("/CalDAV/example.com/home1/calendar_1/", PushPriority.high),
                 ("/CalDAV/example.com/home2/", PushPriority.high),
+                ("/CalDAV/example.com/home2/notification/", PushPriority.high),
             ])
         )
         yield self.commit()
 
         calendar = yield self.calendarUnderTest()
-        home2 = yield self.homeUnderTest(name="home2")
-        yield calendar.unshareWith(home2)
+        yield calendar.uninviteUserFromShare("home2")
         self.assertEquals(
             set(self.notifierFactory.history),
             set([
                 ("/CalDAV/example.com/home1/", PushPriority.high),
                 ("/CalDAV/example.com/home1/calendar_1/", PushPriority.high),
                 ("/CalDAV/example.com/home2/", PushPriority.high),
+                ("/CalDAV/example.com/home2/notification/", PushPriority.high),
             ])
         )
         yield self.commit()
@@ -261,8 +263,9 @@
     def test_sharedCalendarNotifier(self):
 
         calendar = yield self.calendarUnderTest()
-        home2 = yield self.homeUnderTest(name="home2")
-        shareName = yield calendar.shareWith(home2, _BIND_MODE_WRITE)
+        shareeView = yield calendar.inviteUserToShare("home2", _BIND_MODE_WRITE, "")
+        yield shareeView.acceptShare("")
+        shareName = shareeView.name()
         yield self.commit()
         self.notifierFactory.reset()
 

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/tap/caldav.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/tap/caldav.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/calendarserver/tap/caldav.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -72,8 +72,7 @@
 from txdav.common.datastore.upgrade.sql.upgrade import (
     UpgradeDatabaseSchemaStep, UpgradeDatabaseAddressBookDataStep,
     UpgradeDatabaseCalendarDataStep, UpgradeDatabaseOtherStep,
-    UpgradeAcquireLockStep, UpgradeReleaseLockStep
-)
+    UpgradeAcquireLockStep, UpgradeReleaseLockStep, UpgradeDatabaseNotificationDataStep)
 from txdav.common.datastore.upgrade.migrate import UpgradeToDatabaseStep
 from txdav.caldav.datastore.scheduling.imip.inbound import MailRetriever
 from txdav.caldav.datastore.scheduling.imip.inbound import scheduleNextMailPoll
@@ -1420,6 +1419,12 @@
                 )
 
                 pps.addStep(
+                    UpgradeDatabaseNotificationDataStep(
+                        store, uid=overrideUID, gid=overrideGID
+                    )
+                )
+
+                pps.addStep(
                     UpgradeToDatabaseStep(
                         UpgradeToDatabaseStep.fileStoreFromPath(
                             CachingFilePath(config.DocumentRoot)

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twext/python/test/test_launchd.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twext/python/test/test_launchd.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twext/python/test/test_launchd.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -17,7 +17,7 @@
 """
 Tests for L{twext.python.launchd}.
 """
-
+'''
 import sys, os, plistlib, socket, json
 
 if __name__ == '__main__':
@@ -393,5 +393,5 @@
         err = self.stderr.getContent()
         if 'Traceback' in err:
             self.fail(err)
+'''
 
-

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/customxml.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/customxml.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/customxml.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -639,8 +639,9 @@
     name = "dtstamp"
 
     def __init__(self, *children):
-        super(DTStamp, self).__init__(children)
-        self.children = (PCDATAElement(DateTime.getNowUTC().getText()),)
+        super(DTStamp, self).__init__(*children)
+        if not self.children:
+            self.children = (PCDATAElement(DateTime.getNowUTC().getText()),)
 
 
 

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/notifications.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/notifications.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/notifications.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -35,6 +35,7 @@
 
 from txdav.common.icommondatastore import SyncTokenValidException
 
+import json
 import os
 import types
 
@@ -92,17 +93,6 @@
         return davxml.ResourceType.notification
 
 
-    @inlineCallbacks
-    def addNotification(self, request, uid, xmltype, xmldata):
-
-        # Write data to file
-        rname = uid + ".xml"
-        yield self._writeNotification(request, uid, rname, xmltype, xmldata)
-
-        # Update database
-        self.notificationsDB().addOrUpdateRecord(NotificationRecord(uid, rname, xmltype.name))
-
-
     def getNotifictionMessages(self, request, componentType=None, returnLatestVersion=True):
         return succeed([])
 
@@ -144,10 +134,10 @@
 
 class NotificationRecord(object):
 
-    def __init__(self, uid, name, xmltype):
+    def __init__(self, uid, name, notificationtype):
         self.uid = uid
         self.name = name
-        self.xmltype = xmltype
+        self.notificationtype = notificationtype if isinstance(notificationtype, dict) else json.loads(notificationtype)
 
 
 
@@ -184,7 +174,7 @@
 
         self._db_execute("""insert or replace into NOTIFICATIONS (UID, NAME, TYPE)
             values (:1, :2, :3)
-            """, record.uid, record.name, record.xmltype,
+            """, record.uid, record.name, json.dumps(record.notificationtype),
         )
 
         self._db_execute(

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/resource.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/resource.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/resource.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -691,7 +691,7 @@
 
         elif qname == customxml.SharedURL.qname():
             if self.isShareeResource():
-                returnValue(customxml.SharedURL(element.HRef.fromString(self._share.url())))
+                returnValue(customxml.SharedURL(element.HRef.fromString(self._share_url)))
             else:
                 returnValue(None)
 
@@ -859,8 +859,12 @@
         Return the DAV:owner property value (MUST be a DAV:href or None).
         """
 
-        if self.isShareeResource():
-            parent = (yield self.locateParent(request, self._share.url()))
+        if hasattr(self, "_newStoreObject"):
+            if not hasattr(self._newStoreObject, "ownerHome"):
+                home = self._newStoreObject.parentCollection().ownerHome()
+            else:
+                home = self._newStoreObject.ownerHome()
+            returnValue(element.HRef(self.principalForUID(home.uid()).principalURL()))
         else:
             parent = (yield self.locateParent(request, request.urlForResource(self)))
         if parent and isinstance(parent, CalDAVResource):
@@ -875,8 +879,12 @@
         """
         Return the DAV:owner property value (MUST be a DAV:href or None).
         """
-        if self.isShareeResource():
-            parent = (yield self.locateParent(request, self._share.url()))
+        if hasattr(self, "_newStoreObject"):
+            if not hasattr(self._newStoreObject, "ownerHome"):
+                home = self._newStoreObject.parentCollection().ownerHome()
+            else:
+                home = self._newStoreObject.ownerHome()
+            returnValue(self.principalForUID(home.uid()))
         else:
             parent = (yield self.locateParent(request, request.urlForResource(self)))
         if parent and isinstance(parent, CalDAVResource):
@@ -1251,13 +1259,13 @@
         sharedParent = None
         if self.isShareeResource():
             # A sharee collection's quota root is the resource owner's root
-            sharedParent = (yield request.locateResource(parentForURL(self._share.url())))
+            sharedParent = (yield request.locateResource(parentForURL(self._share_url)))
         else:
             parent = (yield self.locateParent(request, request.urlForResource(self)))
             if isCalendarCollectionResource(parent) or isAddressBookCollectionResource(parent):
                 if parent.isShareeResource():
                     # A sharee collection's quota root is the resource owner's root
-                    sharedParent = (yield request.locateResource(parentForURL(parent._share.url())))
+                    sharedParent = (yield request.locateResource(parentForURL(parent._share_url)))
 
         if sharedParent:
             result = (yield sharedParent.quotaRootResource(request))
@@ -2542,6 +2550,11 @@
         return config.Sharing.Enabled and config.Sharing.Calendars.Enabled and self.exists()
 
 
+    def _otherPrincipalHomeURL(self, otherUID):
+        ownerPrincipal = self.principalForUID(otherUID)
+        return ownerPrincipal.calendarHomeURLs()[0]
+
+
     @inlineCallbacks
     def makeRegularChild(self, name):
         newCalendar = yield self._newStoreHome.calendarWithName(name)
@@ -2794,6 +2807,11 @@
         return config.Sharing.Enabled and config.Sharing.AddressBooks.Enabled and self.exists()
 
 
+    def _otherPrincipalHomeURL(self, otherUID):
+        ownerPrincipal = self.principalForUID(otherUID)
+        return ownerPrincipal.addressBookHomeURLs()[0]
+
+
     @inlineCallbacks
     def makeRegularChild(self, name):
 

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/sharing.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/sharing.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/sharing.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -22,6 +22,7 @@
 
 __all__ = [
     "SharedResourceMixin",
+    "SharedHomeMixin",
 ]
 
 from twext.web2 import responsecode
@@ -30,11 +31,11 @@
 from twext.web2.dav.resource import TwistedACLInheritable
 from twext.web2.dav.util import allDataFromStream, joinURL
 
-from txdav.common.datastore.sql import SharingInvitation
 from txdav.common.datastore.sql_tables import _BIND_MODE_OWN, \
     _BIND_MODE_READ, _BIND_MODE_WRITE, _BIND_STATUS_INVITED, \
-    _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, \
-    _BIND_STATUS_INVALID, _ABO_KIND_GROUP
+    _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, \
+    _BIND_STATUS_INVALID, _ABO_KIND_GROUP, _BIND_STATUS_DELETED, \
+    _BIND_MODE_DIRECT, _BIND_MODE_INDIRECT
 from txdav.xml import element
 
 from twisted.internet.defer import succeed, inlineCallbacks, DeferredList, \
@@ -46,26 +47,11 @@
 from twistedcaldav.directory.wiki import WikiDirectoryService, getWikiAccess
 from twistedcaldav.linkresource import LinkFollowerMixIn
 
-from pycalendar.datetime import DateTime
 
-
-# FIXME: Get rid of these imports
-from twistedcaldav.directory.util import TRANSACTION_KEY
-# circular import
-# from txdav.common.datastore.sql import ECALENDARTYPE, EADDRESSBOOKTYPE
-ECALENDARTYPE = 0
-EADDRESSBOOKTYPE = 1
-# ENOTIFICATIONTYPE = 2
-
-
 class SharedResourceMixin(object):
     """
     A mix-in for calendar/addressbook resources that implements sharing-related
     functionality.
-
-    @ivar _share: If this L{SharedResourceMixin} is the sharee's version of a
-        resource, this refers to the L{Share} that describes it.
-    @type _share: L{Share} or L{NoneType}
     """
 
     @inlineCallbacks
@@ -78,15 +64,15 @@
 
             def invitePropertyElement(invitation, includeUID=True):
 
-                userid = "urn:uuid:" + invitation.shareeUID()
-                principal = self.principalForUID(invitation.shareeUID())
-                cn = principal.displayName() if principal else invitation.shareeUID()
+                userid = "urn:uuid:" + invitation.shareeUID
+                principal = self.principalForUID(invitation.shareeUID)
+                cn = principal.displayName() if principal else invitation.shareeUID
                 return customxml.InviteUser(
-                    customxml.UID.fromString(invitation.uid()) if includeUID else None,
+                    customxml.UID.fromString(invitation.uid) if includeUID else None,
                     element.HRef.fromString(userid),
                     customxml.CommonName.fromString(cn),
-                    customxml.InviteAccess(invitationBindModeToXMLMap[invitation.mode()]()),
-                    invitationBindStatusToXMLMap[invitation.status()](),
+                    customxml.InviteAccess(invitationBindModeToXMLMap[invitation.mode]()),
+                    invitationBindStatusToXMLMap[invitation.status](),
                 )
 
             # See if this property is on the shared calendar
@@ -98,11 +84,12 @@
 
             # See if it is on the sharee calendar
             if self.isShareeResource():
-                original = (yield request.locateResource(self._share.url()))
+                original = yield self._newStoreObject.ownerView()
                 if original is not None:
-                    invitations = yield original.validateInvites(request)
+                    invitations = yield original.allInvitations()
+                    invitations = yield self.validateInvites(request, invitations)
 
-                    ownerPrincipal = (yield original.ownerPrincipal(request))
+                    ownerPrincipal = self.principalForUID(self._newStoreObject.ownerHome().uid())
                     # FIXME:  use urn:uuid in all cases
                     if self.isCalendarCollection():
                         owner = ownerPrincipal.principalURL()
@@ -138,35 +125,13 @@
         yield self._newStoreObject.setShared(False)
 
         # Remove all invitees
-        for invitation in (yield self._allInvitations()):
-            yield self.uninviteFromShare(invitation, request)
+        for invitation in (yield self._newStoreObject.allInvitations()):
+            yield self._newStoreObject.uninviteUserFromShare(invitation.shareeUID)
 
         returnValue(True)
 
 
     @inlineCallbacks
-    def changeUserInviteState(self, request, inviteUID, shareeUID, state, summary=None):
-        if not self.isShared():
-            raise HTTPError(ErrorResponse(
-                responsecode.FORBIDDEN,
-                (customxml.calendarserver_namespace, "valid-request"),
-                "Invalid share",
-            ))
-
-        invitation = yield self._invitationForUID(inviteUID)
-        if invitation is None or invitation.shareeUID() != shareeUID:
-            raise HTTPError(ErrorResponse(
-                responsecode.FORBIDDEN,
-                (customxml.calendarserver_namespace, "valid-request"),
-                "Invalid invitation uid: %s" % (inviteUID,),
-            ))
-
-        # Only certain states are owner controlled
-        if invitation.status() in (_BIND_STATUS_INVITED, _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED,):
-            yield self._updateInvitation(invitation, status=state, summary=summary)
-
-
-    @inlineCallbacks
     def directShare(self, request):
         """
         Directly bind an accessible calendar/address book collection into the
@@ -233,11 +198,16 @@
             ))
 
         # Accept it
-        directUID = Share.directUID(shareeHomeResource._newStoreHome, self._newStoreObject)
-        response = (yield shareeHomeResource.acceptDirectShare(request, hostURL, directUID, self.displayName()))
+        shareeView = yield self._newStoreObject.directShareWithUser(sharee.principalUID())
 
         # Return the URL of the shared calendar
-        returnValue(response)
+        sharedAsURL = joinURL(shareeHomeResource.url(), shareeView.name())
+        returnValue(XMLResponse(
+            code=responsecode.OK,
+            element=customxml.SharedAs(
+                element.HRef.fromString(sharedAsURL)
+            )
+        ))
 
 
     def isShared(self):
@@ -250,54 +220,34 @@
             return False
 
 
-    def setShare(self, share):
+    def setShare(self, share_url):
         """
-        Set the L{Share} associated with this L{SharedResourceMixin}.  (This
+        Set the URL associated with this L{SharedResourceMixin}.  (This
         is only invoked on the sharee's resource, not the owner's.)
         """
         self._isShareeResource = True
-        self._share = share
+        self._share_url = share_url
 
 
     def isShareeResource(self):
         """
-        Return True if this is a sharee view of a shared calendar collection.
+        Return True if this is a sharee view of a shared collection.
         """
-        return hasattr(self, "_isShareeResource")
+        return (
+            hasattr(self, "_newStoreObject") and
+            hasattr(self._newStoreObject, "owned") and
+            not self._newStoreObject.owned() and
+            getattr(self._newStoreObject, "_bindMode", None) is not None
+        )
 
 
-    @inlineCallbacks
     def removeShareeResource(self, request):
         """
         Called when the sharee DELETEs a shared collection.
         """
+        return self._newStoreObject.deleteShare()
 
-        sharee = self.principalForUID(self._share.shareeUID())
 
-        # Remove from sharee's calendar/address book home
-        if self.isCalendarCollection():
-            shareeHome = yield sharee.calendarHome(request)
-        elif self.isAddressBookCollection() or self.isGroup():
-            shareeHome = yield sharee.addressBookHome(request)
-        returnValue((yield shareeHome.removeShare(request, self._share)))
-
-
-    def sharedResourceType(self):
-        """
-        Return the DAV:resourcetype stripped of any shared elements.
-        """
-
-        if self.isCalendarCollection():
-            return "calendar"
-        elif self.isAddressBookCollection():
-            return "addressbook"
-        elif self.isGroup():
-            # TODO: Add group xml resource type ?
-            return "group"
-        else:
-            return ""
-
-
     @inlineCallbacks
     def _checkAccessControl(self):
         """
@@ -315,13 +265,12 @@
             access control mechanism has dictate the home should no longer have
             any access at all.
         """
-        if self._share.direct():
-            ownerUID = self._share.ownerUID()
-            owner = self.principalForUID(ownerUID)
+        if self._newStoreObject.direct():
+            owner = self.principalForUID(self._newStoreObject.ownerHome().uid())
             if owner.record.recordType == WikiDirectoryService.recordType_wikis:
                 # Access level comes from what the wiki has granted to the
                 # sharee
-                sharee = self.principalForUID(self._share.shareeUID())
+                sharee = self.principalForUID(self._newStoreObject.viewerHome().uid())
                 userID = sharee.record.guid
                 wikiID = owner.record.shortNames[0]
                 access = (yield getWikiAccess(userID, wikiID))
@@ -366,13 +315,12 @@
         assert self._isShareeResource, "Only call this for a sharee resource"
         assert self.isCalendarCollection() or self.isAddressBookCollection(), "Only call this for a address book or calendar resource"
 
-        sharee = self.principalForUID(self._share.shareeUID())
+        sharee = self.principalForUID(self._newStoreObject.viewerHome().uid())
         access = yield self._checkAccessControl()
 
         if access == "original":
-            original = (yield request.locateResource(self._share.url()))
-            result = (yield original.accessControlList(request, *args,
-                **kwargs))
+            original = (yield request.locateResource(self._share_url))
+            result = (yield original.accessControlList(request, *args, **kwargs))
             returnValue(result)
 
         # Direct shares use underlying privileges of shared collection
@@ -476,18 +424,17 @@
 
 
     @inlineCallbacks
-    def validateInvites(self, request):
+    def validateInvites(self, request, invitations=None):
         """
         Make sure each userid in an invite is valid - if not re-write status.
         """
         # assert request
-        invitations = yield self._allInvitations()
+        if invitations is None:
+            invitations = yield self._newStoreObject.allInvitations()
         for invitation in invitations:
-            if invitation.status() != _BIND_STATUS_INVALID:
-                if not (yield self.validUserIDForShare("urn:uuid:" + invitation.shareeUID(), request)):
-                    # FIXME: temporarily disable this to deal with flaky directory
-                    #yield self._updateInvitation(invitation, status=_BIND_STATUS_INVALID)
-                    self.log.error("Invalid sharee detected: {uid}", uid=invitation.shareeUID())
+            if invitation.status != _BIND_STATUS_INVALID:
+                if not (yield self.validUserIDForShare("urn:uuid:" + invitation.shareeUID, request)):
+                    self.log.error("Invalid sharee detected: {uid}", uid=invitation.shareeUID)
 
         returnValue(invitations)
 
@@ -549,78 +496,6 @@
 
 
     @inlineCallbacks
-    def _createInvitation(self, shareeUID, mode, summary,):
-        """
-        Create a new homeChild and wrap it in an Invitation
-        """
-        if self.isCalendarCollection():
-            shareeHome = yield self._newStoreObject._txn.calendarHomeWithUID(shareeUID, create=True)
-        elif self.isAddressBookCollection() or self.isGroup():
-            shareeHome = yield self._newStoreObject._txn.addressbookHomeWithUID(shareeUID, create=True)
-
-        shareUID = yield self._newStoreObject.shareWith(shareeHome,
-                                                    mode=mode,
-                                                    status=_BIND_STATUS_INVITED,
-                                                    message=summary)
-        shareeStoreObject = yield shareeHome.invitedObjectWithShareUID(shareUID)
-        invitation = SharingInvitation.fromCommonHomeChild(shareeStoreObject)
-        returnValue(invitation)
-
-
-    @inlineCallbacks
-    def _updateInvitation(self, invitation, mode=None, status=None, summary=None):
-        yield self._newStoreObject.updateShareFromSharingInvitation(invitation, mode=mode, status=status, message=summary)
-        if mode is not None:
-            invitation.setMode(mode)
-        if status is not None:
-            invitation.setStatus(status)
-        if summary is not None:
-            invitation.setSummary(summary)
-
-
-    @inlineCallbacks
-    def _allInvitations(self):
-        """
-        Get list of all invitations (non-direct) to this object.
-        """
-        if not self.exists():
-            returnValue([])
-
-        invitations = yield self._newStoreObject.sharingInvites()
-
-        # remove direct shares as those are not "real" invitations
-        invitations = filter(lambda x: x.mode() != _BIND_MODE_DIRECT, invitations)
-
-        invitations.sort(key=lambda invitation: invitation.shareeUID())
-
-        returnValue(invitations)
-
-
-    @inlineCallbacks
-    def _invitationForShareeUID(self, shareeUID):
-        """
-        Get an invitation for this sharee principal UID
-        """
-        invitations = yield self._allInvitations()
-        for invitation in invitations:
-            if invitation.shareeUID() == shareeUID:
-                returnValue(invitation)
-        returnValue(None)
-
-
-    @inlineCallbacks
-    def _invitationForUID(self, uid):
-        """
-        Get an invitation for an invitations uid
-        """
-        invitations = yield self._allInvitations()
-        for invitation in invitations:
-            if invitation.uid() == uid:
-                returnValue(invitation)
-        returnValue(None)
-
-
-    @inlineCallbacks
     def inviteSingleUserToShare(self, userid, cn, ace, summary, request): #@UnusedVariable
 
         # We currently only handle local users
@@ -628,71 +503,32 @@
         if not sharee:
             returnValue(False)
 
-        shareeUID = sharee.principalUID()
+        result = (yield self._newStoreObject.inviteUserToShare(
+            sharee.principalUID(),
+            invitationBindModeFromXMLMap[type(ace)],
+            summary,
+        ))
 
-        # Look for existing invite and update its fields or create new one
-        invitation = yield self._invitationForShareeUID(shareeUID)
-        if invitation:
-            status = _BIND_STATUS_INVITED if invitation.status() in (_BIND_STATUS_DECLINED, _BIND_STATUS_INVALID) else None
-            yield self._updateInvitation(invitation, mode=invitationBindModeFromXMLMap[type(ace)], status=status, summary=summary)
-        else:
-            invitation = yield self._createInvitation(
-                                shareeUID=shareeUID,
-                                mode=invitationBindModeFromXMLMap[type(ace)],
-                                summary=summary)
-        # Send invite notification
-        yield self.sendInviteNotification(invitation, request)
+        returnValue(result)
 
-        returnValue(True)
 
-
     @inlineCallbacks
     def uninviteSingleUserFromShare(self, userid, aces, request): #@UnusedVariable
-        # Cancel invites - we'll just use whatever userid we are given
 
+        # Cancel invites - we'll just use whatever userid we are given
         sharee = self.principalForCalendarUserAddress(userid)
         if not sharee:
             returnValue(False)
 
-        shareeUID = sharee.principalUID()
+        result = (yield self._newStoreObject.uninviteUserFromShare(sharee.principalUID()))
 
-        invitation = yield self._invitationForShareeUID(shareeUID)
-        if invitation:
-            result = (yield self.uninviteFromShare(invitation, request))
-        else:
-            result = False
-
         returnValue(result)
 
 
     @inlineCallbacks
     def uninviteFromShare(self, invitation, request):
 
-        # Remove any shared calendar or address book
-        sharee = self.principalForUID(invitation.shareeUID())
-        if sharee:
-            previousInvitationStatus = invitation.status()
-            displayName = None
-            if self.isCalendarCollection():
-                shareeHomeResource = yield sharee.calendarHome(request)
-                if shareeHomeResource is not None:
-                    displayName = yield shareeHomeResource.removeShareByUID(request, invitation.uid())
-            elif self.isAddressBookCollection() or self.isGroup():
-                shareeHomeResource = yield sharee.addressBookHome(request)
-                if shareeHomeResource is not None:
-                    yield shareeHomeResource.removeShareByUID(request, invitation.uid())
-
-            # If current user state is accepted then we send an invite with the new state, otherwise
-            # we cancel any existing invites for the user
-            if shareeHomeResource is not None:
-                if previousInvitationStatus != _BIND_STATUS_ACCEPTED:
-                    yield self.removeInviteNotification(invitation, request)
-                else:
-                    yield self.sendInviteNotification(invitation, request, displayName=displayName, notificationState="DELETED")
-
-        # Direct shares for  with valid sharee principal will already be deleted
-        yield self._newStoreObject.unshareWithUID(invitation.shareeUID())
-
+        yield self._newStoreObject.uninviteFromShare(invitation)
         returnValue(True)
 
 
@@ -703,81 +539,6 @@
 
 
     @inlineCallbacks
-    def sendInviteNotification(self, invitation, request, notificationState=None, displayName=None):
-
-        ownerPrincipal = (yield self.ownerPrincipal(request))
-        # FIXME:  use urn:uuid in all cases
-        if self.isCalendarCollection():
-            owner = ownerPrincipal.principalURL()
-        else:
-            owner = "urn:uuid:" + ownerPrincipal.principalUID()
-        ownerCN = ownerPrincipal.displayName()
-        hosturl = (yield self.canonicalURL(request))
-
-        # Locate notifications collection for user
-        sharee = self.principalForUID(invitation.shareeUID())
-        if sharee is None:
-            raise ValueError("sharee is None but principalUID was valid before")
-
-        # We need to look up the resource so that the response cache notifier is properly initialized
-        notificationResource = (yield request.locateResource(sharee.notificationURL()))
-        notifications = notificationResource._newStoreNotifications
-
-        '''
-        # Look for existing notification
-        # oldnotification is not used don't query for it
-        oldnotification = (yield notifications.notificationObjectWithUID(invitation.uid()))
-        if oldnotification:
-            # TODO: rollup changes?
-            pass
-        '''
-
-        # Generate invite XML
-        userid = "urn:uuid:" + invitation.shareeUID()
-        state = notificationState if notificationState else invitation.status()
-        summary = invitation.summary() if displayName is None else displayName
-
-        typeAttr = {'shared-type': self.sharedResourceType()}
-        xmltype = customxml.InviteNotification(**typeAttr)
-        xmldata = customxml.Notification(
-            customxml.DTStamp.fromString(DateTime.getNowUTC().getText()),
-            customxml.InviteNotification(
-                customxml.UID.fromString(invitation.uid()),
-                element.HRef.fromString(userid),
-                invitationBindStatusToXMLMap[state](),
-                customxml.InviteAccess(invitationBindModeToXMLMap[invitation.mode()]()),
-                customxml.HostURL(
-                    element.HRef.fromString(hosturl),
-                ),
-                customxml.Organizer(
-                    element.HRef.fromString(owner),
-                    customxml.CommonName.fromString(ownerCN),
-                ),
-                customxml.InviteSummary.fromString(summary),
-                self.getSupportedComponentSet() if self.isCalendarCollection() else None,
-                **typeAttr
-            ),
-        ).toxml()
-
-        # Add to collections
-        yield notifications.writeNotificationObject(invitation.uid(), xmltype, xmldata)
-
-
-    @inlineCallbacks
-    def removeInviteNotification(self, invitation, request):
-
-        # Locate notifications collection for user
-        sharee = self.principalForUID(invitation.shareeUID())
-        if sharee is None:
-            raise ValueError("sharee is None but principalUID was valid before")
-        notificationResource = (yield request.locateResource(sharee.notificationURL()))
-        notifications = notificationResource._newStoreNotifications
-
-        # Add to collections
-        yield notifications.removeNotificationObjectWithUID(invitation.uid())
-
-
-    @inlineCallbacks
     def _xmlHandleInvite(self, request, docroot):
         yield self.authorize(request, (element.Read(), element.Write()))
         result = (yield self._handleInvite(request, docroot))
@@ -995,7 +756,7 @@
     _BIND_STATUS_ACCEPTED     : customxml.InviteStatusAccepted,
     _BIND_STATUS_DECLINED     : customxml.InviteStatusDeclined,
     _BIND_STATUS_INVALID      : customxml.InviteStatusInvalid,
-    "DELETED"                 : customxml.InviteStatusDeleted,
+    _BIND_STATUS_DELETED      : customxml.InviteStatusDeleted,
 }
 invitationBindStatusFromXMLMap = dict((v, k) for k, v in invitationBindStatusToXMLMap.iteritems())
 
@@ -1005,12 +766,13 @@
 }
 invitationBindModeFromXMLMap = dict((v, k) for k, v in invitationBindModeToXMLMap.iteritems())
 
-invitationAccessToBindModeMap = {
-    "own": _BIND_MODE_OWN,
-    "read-only": _BIND_MODE_READ,
-    "read-write": _BIND_MODE_WRITE,
-    }
-invitationAccessFromBindModeMap = dict((v, k) for k, v in invitationAccessToBindModeMap.iteritems())
+invitationAccessFromBindModeMap = {
+    _BIND_MODE_OWN: "own",
+    _BIND_MODE_READ: "read-only",
+    _BIND_MODE_WRITE: "read-write",
+    _BIND_MODE_DIRECT: "read-write",
+    _BIND_MODE_INDIRECT: "read-write",
+}
 
 
 class SharedHomeMixin(LinkFollowerMixIn):
@@ -1022,219 +784,30 @@
     @inlineCallbacks
     def provisionShare(self, child, request=None):
         """
-        If the given child resource (a L{SharedResourceMixin}) of this
-        L{SharedHomeMixin} is a I{sharee}'s view of a shared calendar object,
-        associate it with a L{Share}.
+        Set shared state and check access control.
         """
-        share = yield self._shareForStoreObject(child._newStoreObject, request)
-        if share:
-            child.setShare(share)
+        if child._newStoreObject is not None and not child._newStoreObject.owned():
+            ownerHomeURL = self._otherPrincipalHomeURL(child._newStoreObject.ownerHome().uid())
+            ownerView = yield child._newStoreObject.ownerView()
+            child.setShare(joinURL(ownerHomeURL, ownerView.name()))
             access = yield child._checkAccessControl()
             if access is None:
                 returnValue(None)
         returnValue(child)
 
 
-    @inlineCallbacks
-    def _shareForStoreObject(self, storeObject, request=None):
-        """
-        Determine the L{Share} associated with the given child.
+    def _otherPrincipalHomeURL(self, otherUID):
+        pass
 
-        @param child: A calendar or addressbook data store object, a child of
-            the resource represented by this L{SharedHomeMixin} instance, which
-            may be shared.
-        @type child: L{txdav.caldav.icalendarstore.ICalendar} or
-            L{txdav.carddav.iaddressbookstore.IAddressBook}
 
-        @return: a L{Share} if C{child} is not the owner's view of the share,
-            or C{None}.
-        @rtype: L{Share} or L{NoneType}
-        """
-        # Find a matching share
-        # use "storeObject.shareUID is not None" to prevent partially shared address books form getting a share
-        if storeObject is None or storeObject.owned():
-            returnValue(None)
-
-        # Get the shared object's URL - we may need to fake this if the sharer principal is missing or disabled
-        url = None
-        owner = self.principalForUID(storeObject.ownerHome().uid())
-        from twistedcaldav.directory.principal import DirectoryCalendarPrincipalResource
-        if isinstance(owner, DirectoryCalendarPrincipalResource):
-
-            if not request:
-                # FIXEME:  Fake up a request that can be used to get the owner home resource
-                class _FakeRequest(object):
-                    pass
-                fakeRequest = _FakeRequest()
-                setattr(fakeRequest, TRANSACTION_KEY, self._newStoreHome._txn)
-                request = fakeRequest
-
-            if self._newStoreHome._homeType == ECALENDARTYPE:
-                ownerHomeCollection = yield owner.calendarHome(request)
-            elif self._newStoreHome._homeType == EADDRESSBOOKTYPE:
-                ownerHomeCollection = yield owner.addressBookHome(request)
-
-            if ownerHomeCollection is not None:
-                url = ownerHomeCollection.url()
-
-        if url is None:
-            url = "/calendars/__uids__/%s/" % (storeObject.ownerHome().uid(),)
-
-        ownerHomeChild = yield storeObject.ownerHome().childWithID(storeObject._resourceID)
-        if ownerHomeChild:
-            assert ownerHomeChild != storeObject
-            url = joinURL(url, ownerHomeChild.name())
-            share = Share(shareeStoreObject=storeObject, ownerStoreObject=ownerHomeChild, url=url)
-        else:
-            for ownerHomeChild in (yield storeObject.ownerHome().children()):
-                if ownerHomeChild.owned():
-                    sharedGroup = yield ownerHomeChild.objectResourceWithID(storeObject._resourceID)
-                    if sharedGroup:
-                        url = joinURL(url, ownerHomeChild.name(), sharedGroup.name())
-                        share = Share(shareeStoreObject=storeObject, ownerStoreObject=sharedGroup, url=url)
-                        break
-
-        returnValue(share)
-
-
     @inlineCallbacks
-    def _shareForUID(self, shareUID, request):
+    def acceptShare(self, request, inviteUID, summary):
 
-        if shareUID is not None:  # shareUID may be None for partially shared addressbooks
-            shareeStoreObject = yield self._newStoreHome.objectWithShareUID(shareUID)
-            if shareeStoreObject:
-                share = yield self._shareForStoreObject(shareeStoreObject, request)
-                if share:
-                    returnValue(share)
+        # Accept the share
+        shareeView = yield self._newStoreHome.acceptShare(inviteUID, summary)
 
-            # find direct shares
-            children = yield self._newStoreHome.children()
-            for child in children:
-                share = yield self._shareForStoreObject(child, request)
-                if share and share.uid() == shareUID:
-                    returnValue(share)
-
-        returnValue(None)
-
-
-    @inlineCallbacks
-    def acceptInviteShare(self, request, hostUrl, inviteUID, displayname=None):
-
-        # Check for old share
-        oldShare = yield self._shareForUID(inviteUID, request)
-
-        # Send the invite reply then add the link
-        yield self._changeShare(request, _BIND_STATUS_ACCEPTED, hostUrl, inviteUID, displayname)
-        if oldShare:
-            share = oldShare
-        else:
-            sharedResource = yield request.locateResource(hostUrl)
-            shareeStoreObject = yield self._newStoreHome.objectWithShareUID(inviteUID)
-
-            share = Share(shareeStoreObject=shareeStoreObject,
-                          ownerStoreObject=sharedResource._newStoreObject,
-                          url=hostUrl)
-
-        response = yield self._acceptShare(request, not oldShare, share, displayname)
-        returnValue(response)
-
-
-    @inlineCallbacks
-    def acceptDirectShare(self, request, hostUrl, resourceUID,
-                          displayname=None):
-
-        # Just add the link
-        oldShare = yield self._shareForUID(resourceUID, request)
-        if oldShare:
-            share = oldShare
-        else:
-            sharedCollection = yield request.locateResource(hostUrl)
-            shareUID = yield sharedCollection._newStoreObject.shareWith(
-                shareeHome=self._newStoreHome,
-                mode=_BIND_MODE_DIRECT,
-                status=_BIND_STATUS_ACCEPTED,
-                message=displayname
-            )
-
-            shareeStoreObject = yield self._newStoreHome.objectWithShareUID(shareUID)
-            share = Share(shareeStoreObject=shareeStoreObject,
-                          ownerStoreObject=sharedCollection._newStoreObject,
-                          url=hostUrl)
-
-        response = yield self._acceptShare(request, not oldShare, share, displayname)
-        returnValue(response)
-
-
-    @inlineCallbacks
-    def _acceptShare(self, request, isNewShare, share, displayname=None):
-        """
-        Mark a pending shared invitation I{to} this, the owner's collection, as
-        accepted, generating the HTTP response to the request that accepted it.
-
-        @param request: The HTTP request that is accepting it.
-        @type request: L{twext.web2.iweb.IRequest}
-
-        @param isNewShare: a boolean indicating whether this share is new.
-        @type isNewShare: L{bool}
-
-        @param share: The share referencing the proposed sharer and sharee.
-        @type share: L{Share}
-
-        @param displayname: the UTF-8 encoded contents of the display-name
-            property on the resource to be created while accepting.
-        @type displayname: L{bytes}
-
-        @return: a L{twext.web2.iweb.IResponse} containing a serialized
-            L{customxml.SharedAs} element as its body.
-        @rtype: L{Deferred} firing L{XMLResponse}
-        """
-        # Get shared collection in non-share mode first
-        sharedResource = yield request.locateResource(share.url())
-        sharee = self.principalForUID(share.shareeUID())
-
-        if sharedResource.isCalendarCollection():
-            shareeHomeResource = yield sharee.calendarHome(request)
-            sharedAsURL = joinURL(shareeHomeResource.url(), share.name())
-            shareeCalender = yield request.locateResource(sharedAsURL)
-            shareeCalender.setShare(share)
-
-            # For calendars only, per-user displayname and color
-            if displayname:
-                yield shareeCalender.writeProperty(element.DisplayName.fromString(displayname), request)
-
-            if isNewShare:
-                # For a direct share we will copy any calendar-color over using the owners view
-                if share.direct():
-                    try:
-                        color = yield sharedResource.readProperty(customxml.CalendarColor, request)
-                    except HTTPError:
-                        color = None
-                    if color:
-                        yield shareeCalender.writeProperty(customxml.CalendarColor.fromString(color), request)
-
-                # Calendars always start out transparent and with empty default alarms
-                yield shareeCalender._newStoreObject.setUsedForFreeBusy(False)
-                yield shareeCalender._newStoreObject.setDefaultAlarm("empty", True, True)
-                yield shareeCalender._newStoreObject.setDefaultAlarm("empty", True, False)
-                yield shareeCalender._newStoreObject.setDefaultAlarm("empty", False, True)
-                yield shareeCalender._newStoreObject.setDefaultAlarm("empty", False, False)
-
-        elif sharedResource.isAddressBookCollection():
-            shareeHomeResource = yield sharee.addressBookHome(request)
-            sharedAsURL = joinURL(shareeHomeResource.url(), share.ownerUID())
-            shareeAddressBook = yield request.locateResource(sharedAsURL)
-            shareeAddressBook.setShare(share)
-
-        elif sharedResource.isGroup():
-            shareeHomeResource = yield sharee.addressBookHome(request)
-            sharedAsURL = joinURL(shareeHomeResource.url(), share.ownerUID(), share.name())
-            shareeGroup = yield request.locateResource(sharedAsURL)
-            shareeGroup.setShare(share)
-
-        # Notify client of changes
-        yield self.notifyChanged()
-
         # Return the URL of the shared collection
+        sharedAsURL = joinURL(self.url(), shareeView.shareName())
         returnValue(XMLResponse(
             code=responsecode.OK,
             element=customxml.SharedAs(
@@ -1244,146 +817,13 @@
 
 
     @inlineCallbacks
-    def removeShare(self, request, share):
-        """
-        Remove a shared collection named in resourceName
-        """
+    def declineShare(self, request, inviteUID):
 
-        if share.direct():
-            yield self.removeDirectShare(request, share)
-            returnValue(None)
-        else:
-            # Send a decline when an invite share is removed only
-            result = yield self.declineShare(request, share.url(), share.uid())
-            returnValue(result)
-
-
-    @inlineCallbacks
-    def removeShareByUID(self, request, shareUID):
-        """
-        Remove a shared collection but do not send a decline back. Return the
-        current display name of the shared collection.
-        """
-
-        share = yield self._shareForUID(shareUID, request)
-        if share:
-            displayName = (yield self.removeDirectShare(request, share))
-            returnValue(displayName)
-        else:
-            returnValue(None)
-
-
-    @inlineCallbacks
-    def removeDirectShare(self, request, share):
-        """
-        Remove a shared collection but do not send a decline back. Return the
-        current display name of the shared collection.
-        """
-        # FIXME: only works for calendar
-        shareURL = joinURL(self.url(), share.name())
-        shared = (yield request.locateResource(shareURL))
-        displayname = shared.displayName()
-
-        if share.direct():
-            yield share._ownerStoreObject.unshareWith(share._shareeStoreObject.viewerHome())
-        else:
-            yield share._ownerStoreObject.updateShare(share._shareeStoreObject, status=_BIND_STATUS_DECLINED)
-
-        returnValue(displayname)
-
-
-    @inlineCallbacks
-    def declineShare(self, request, hostUrl, inviteUID):
-
         # Remove it if it is in the DB
-        yield self.removeShareByUID(request, inviteUID)
-        yield self._changeShare(request, _BIND_STATUS_DECLINED, hostUrl, inviteUID, processed=True)
+        yield self._newStoreHome.declineShare(inviteUID)
         returnValue(Response(code=responsecode.NO_CONTENT))
 
 
-    @inlineCallbacks
-    def _changeShare(self, request, state, hostUrl, replytoUID, displayname=None, processed=False):
-        """
-        Accept or decline an invite to a shared collection.
-        """
-        # Change state in owner invite
-        ownerPrincipal = (yield self.ownerPrincipal(request))
-        ownerPrincipalUID = ownerPrincipal.principalUID()
-        sharedResource = (yield request.locateResource(hostUrl))
-        if sharedResource is None:
-            # FIXME: have to return here rather than raise to allow removal of a share for a sharer
-            # whose principal is no longer valid yet still exists in the store. Really we need to get rid of
-            # locateResource calls and just do everything via store objects.
-            returnValue(None)
-            # Original shared collection is gone - nothing we can do except ignore it
-            raise HTTPError(ErrorResponse(
-                responsecode.FORBIDDEN,
-                (customxml.calendarserver_namespace, "valid-request"),
-                "Invalid shared collection",
-            ))
-
-        # Change the record
-        if not processed:
-            yield sharedResource.changeUserInviteState(request, replytoUID, ownerPrincipalUID, state, displayname)
-
-        yield self.sendReply(request, ownerPrincipal, sharedResource, state, hostUrl, replytoUID, displayname)
-
-
-    @inlineCallbacks
-    def sendReply(self, request, shareePrincipal, sharedResource, state, hostUrl, replytoUID, displayname=None):
-
-        # Locate notifications collection for owner
-        owner = (yield sharedResource.ownerPrincipal(request))
-        if owner is None:
-            # FIXME: have to return here rather than raise to allow removal of a share for a sharer
-            # whose principal is no longer valid yet still exists in the store. Really we need to get rid of
-            # locateResource calls and just do everything via store objects.
-            returnValue(None)
-
-        notificationResource = (yield request.locateResource(owner.notificationURL()))
-        notifications = notificationResource._newStoreNotifications
-
-        # Generate invite XML
-        notificationUID = "%s-reply" % (replytoUID,)
-        xmltype = customxml.InviteReply()
-
-        # FIXME:  use urn:uuid in all cases
-        if self._newStoreHome and self._newStoreHome._homeType == EADDRESSBOOKTYPE:
-            cua = "urn:uuid:" + shareePrincipal.principalUID()
-        else:
-            # Prefer mailto:, otherwise use principal URL
-            for cua in shareePrincipal.calendarUserAddresses():
-                if cua.startswith("mailto:"):
-                    break
-            else:
-                cua = shareePrincipal.principalURL()
-
-        commonName = shareePrincipal.displayName()
-        record = shareePrincipal.record
-
-        xmldata = customxml.Notification(
-            customxml.DTStamp.fromString(DateTime.getNowUTC().getText()),
-            customxml.InviteReply(
-                *(
-                    (
-                        element.HRef.fromString(cua),
-                        invitationBindStatusToXMLMap[state](),
-                        customxml.HostURL(
-                            element.HRef.fromString(hostUrl),
-                        ),
-                        customxml.InReplyTo.fromString(replytoUID),
-                    ) + ((customxml.InviteSummary.fromString(displayname),) if displayname is not None else ())
-                      + ((customxml.CommonName.fromString(commonName),) if commonName is not None else ())
-                      + ((customxml.FirstNameProperty(record.firstName),) if record.firstName is not None else ())
-                      + ((customxml.LastNameProperty(record.lastName),) if record.lastName is not None else ())
-                )
-            ),
-        ).toxml()
-
-        # Add to collections
-        yield notifications.writeNotificationObject(notificationUID, xmltype, xmldata)
-
-
     def _handleInviteReply(self, request, invitereplydoc):
         """
         Handle a user accepting or declining a sharing invite
@@ -1413,80 +853,6 @@
                 "Missing required XML elements",
             ))
         if accepted:
-            return self.acceptInviteShare(request, hostUrl, replytoUID, displayname=summary)
+            return self.acceptShare(request, replytoUID, summary=summary)
         else:
-            return self.declineShare(request, hostUrl, replytoUID)
-
-
-
-class Share(object):
-    """
-    A L{Share} represents information about a collection which has been shared
-    from one user to another.
-    """
-
-    def __init__(self, ownerStoreObject, shareeStoreObject, url):
-        """
-        @param sharerHomeChild: The data store object representing the shared
-            collection as present in the owner's home collection; the owner's
-            reference.
-        @type sharerHomeChild: L{txdav.caldav.icalendarstore.ICalendar}
-
-        @param shareeHomeChild: The data store object representing the
-            collection as present in the sharee's home collection; the sharee's
-            reference.
-        @type shareeHomeChild: L{txdav.caldav.icalendarstore.ICalendar}
-
-        @param url: The URL referring to the sharer's version of the resource.
-        @type url: L{bytes}
-        """
-        self._shareeStoreObject = shareeStoreObject
-        self._ownerStoreObject = ownerStoreObject
-        self._ownerResourceURL = url
-
-
-    @classmethod
-    def directUID(cls, shareeHome, ownerHomeChild):
-        return "Direct-%s-%s" % (shareeHome._resourceID,
-                                 ownerHomeChild._resourceID,)
-
-
-    def uid(self):
-        # Move to CommonHomeChild shareUID?
-        if self._shareeStoreObject.shareMode() == _BIND_MODE_DIRECT:
-            return self.directUID(shareeHome=self._shareeStoreObject.viewerHome(),
-                                  ownerHomeChild=self._ownerStoreObject,)
-        else:
-            return self._shareeStoreObject.shareUID()
-
-
-    def direct(self):
-        """
-        Is this L{Share} a "direct" share?
-
-        @return: a boolean indicating whether it's direct.
-        """
-        return self._shareeStoreObject.shareMode() == _BIND_MODE_DIRECT
-
-
-    def url(self):
-        """
-        @return: The URL to the owner's version of the shared collection.
-        """
-        return self._ownerResourceURL
-
-
-    def name(self):
-        return self._shareeStoreObject.name()
-
-
-    def summary(self):
-        return self._shareeStoreObject.shareMessage()
-
-
-    def shareeUID(self):
-        return self._shareeStoreObject.viewerHome().uid()
-
-
-    def ownerUID(self):
-        return self._shareeStoreObject.ownerHome().uid()
+            return self.declineShare(request, replytoUID)

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/storebridge.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/storebridge.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/storebridge.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -70,10 +70,10 @@
     UIDExistsElsewhereError, InvalidUIDError, InvalidResourceMove, \
     InvalidComponentForStoreError
 from txdav.idav import PropertyChangeNotAllowedError
-from txdav.xml import element as davxml
+from txdav.xml import element as davxml, element
 from txdav.xml.base import dav_namespace, WebDAVUnknownElement, encodeXMLName
 
-from urlparse import urlsplit
+from urlparse import urlsplit, urljoin
 import hashlib
 import time
 import uuid
@@ -84,6 +84,8 @@
     TooManyInstancesError
 from twistedcaldav.util import bestAcceptType
 import collections
+from twistedcaldav.sharing import invitationBindStatusToXMLMap, \
+    invitationBindModeToXMLMap
 
 """
 Wrappers to translate between the APIs in L{txdav.caldav.icalendarstore} and
@@ -275,7 +277,7 @@
 
     def owner_url(self):
         if self.isShareeResource():
-            return joinURL(self._share.url(), "/")
+            return joinURL(self._share_url, "/")
         else:
             return self.url()
 
@@ -1640,23 +1642,23 @@
         for invite in invites:
 
             # Only want accepted invites
-            if invite.status() != _BIND_STATUS_ACCEPTED:
+            if invite.status != _BIND_STATUS_ACCEPTED:
                 continue
 
             userprivs = [
             ]
-            if invite.mode() in (_BIND_MODE_READ, _BIND_MODE_WRITE,):
+            if invite.mode in (_BIND_MODE_READ, _BIND_MODE_WRITE,):
                 userprivs.append(davxml.Privilege(davxml.Read()))
                 userprivs.append(davxml.Privilege(davxml.ReadACL()))
                 userprivs.append(davxml.Privilege(davxml.ReadCurrentUserPrivilegeSet()))
-            if invite.mode() in (_BIND_MODE_READ,):
+            if invite.mode in (_BIND_MODE_READ,):
                 userprivs.append(davxml.Privilege(davxml.WriteProperties()))
-            if invite.mode() in (_BIND_MODE_WRITE,):
+            if invite.mode in (_BIND_MODE_WRITE,):
                 userprivs.append(davxml.Privilege(davxml.Write()))
             proxyprivs = list(userprivs)
             proxyprivs.remove(davxml.Privilege(davxml.ReadACL()))
 
-            principal = self.principalForUID(invite.shareeUID())
+            principal = self.principalForUID(invite.shareeUID)
             aces += (
                 # Inheritable specific access for the resource's associated principal.
                 davxml.ACE(
@@ -1951,10 +1953,10 @@
             access control mechanism has dictate the home should no longer have
             any access at all.
         """
-        if invite.mode() in (_BIND_MODE_DIRECT,):
-            ownerUID = invite.ownerUID()
+        if invite.mode in (_BIND_MODE_DIRECT,):
+            ownerUID = invite.ownerUID
             owner = self.principalForUID(ownerUID)
-            shareeUID = invite.shareeUID()
+            shareeUID = invite.shareeUID
             if owner.record.recordType == WikiDirectoryService.recordType_wikis:
                 # Access level comes from what the wiki has granted to the
                 # sharee
@@ -1970,9 +1972,9 @@
                     returnValue(None)
             else:
                 returnValue("original")
-        elif invite.mode() in (_BIND_MODE_READ,):
+        elif invite.mode in (_BIND_MODE_READ,):
             returnValue("read-only")
-        elif invite.mode() in (_BIND_MODE_WRITE,):
+        elif invite.mode in (_BIND_MODE_WRITE,):
             returnValue("read-write")
         returnValue("original")
 
@@ -1985,7 +1987,7 @@
         for invite in invites:
 
             # Only want accepted invites
-            if invite.status() != _BIND_STATUS_ACCEPTED:
+            if invite.status != _BIND_STATUS_ACCEPTED:
                 continue
 
             privileges = [
@@ -1997,7 +1999,7 @@
             if access in ("read-only", "read-write",):
                 userprivs.extend(privileges)
 
-            principal = self.principalForUID(invite.shareeUID())
+            principal = self.principalForUID(invite.shareeUID)
             aces += (
                 # Inheritable specific access for the resource's associated principal.
                 davxml.ACE(
@@ -3108,29 +3110,12 @@
         call super and provision group share
         """
         abObjectResource = yield super(AddressBookCollectionResource, self).makeChild(name)
-        if abObjectResource.exists() and abObjectResource._newStoreObject.shareUID() is not None:
-            abObjectResource = yield self.parentResource().provisionShare(abObjectResource)
+        #if abObjectResource.exists() and abObjectResource._newStoreObject.shareUID() is not None:
+        #    abObjectResource = yield self.parentResource().provisionShare(abObjectResource)
         returnValue(abObjectResource)
 
 
     @inlineCallbacks
-    def storeRemove(self, request):
-        """
-        handle remove of partially shared addressbook, else call super
-        """
-        if self.isShareeResource() and self._newStoreObject.shareUID() is None:
-            log.debug("Removing shared collection %s" % (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
     def bulkCreate(self, indexedComponents, request, return_changed, xmlresponses, format):
         """
         bulk create allowing groups to contain member UIDs added during the same bulk create
@@ -3666,13 +3651,6 @@
         )
 
 
-    def addNotification(self, request, uid, xmltype, xmldata):
-        return maybeDeferred(
-            self._newStoreNotifications.writeNotificationObject,
-            uid, xmltype, xmldata
-        )
-
-
     def deleteNotification(self, request, record):
         return maybeDeferred(
             self._newStoreNotifications.removeNotificationObjectWithName,
@@ -3717,7 +3695,15 @@
             qname = prop.qname()
 
         if qname == customxml.NotificationType.qname():
-            returnValue(self._newStoreObject.xmlType())
+            jsontype = self._newStoreObject.notificationType()
+            if jsontype["notification-type"] == "invite-notification":
+                typeAttr = {"shared-type": jsontype["shared-type"]}
+                xmltype = customxml.InviteNotification(**typeAttr)
+            elif jsontype["notification-type"] == "invite-reply":
+                xmltype = customxml.InviteReply()
+            else:
+                raise HTTPError(responsecode.INTERNAL_SERVER_ERROR)
+            returnValue(customxml.NotificationType(xmltype))
 
         returnValue((yield super(StoreNotificationObjectFile, self).readProperty(prop, request)))
 
@@ -3730,11 +3716,97 @@
         return succeed(self._newStoreObject.size())
 
 
+    @inlineCallbacks
     def text(self, ignored=None):
         assert ignored is None, "This is a notification object, not a notification"
-        return self._newStoreObject.xmldata()
+        jsondata = (yield self._newStoreObject.notificationData())
+        if jsondata["notification-type"] == "invite-notification":
+            ownerPrincipal = self.principalForUID(jsondata["owner"])
+            ownerCN = ownerPrincipal.displayName()
+            ownerHomeURL = ownerPrincipal.calendarHomeURLs()[0] if jsondata["shared-type"] == "calendar" else ownerPrincipal.addressBookHomeURLs()[0]
 
+            # FIXME:  use urn:uuid always?
+            if jsondata["shared-type"] == "calendar":
+                owner = ownerPrincipal.principalURL()
+            else:
+                owner = "urn:uuid:" + ownerPrincipal.principalUID()
 
+            shareePrincipal = self.principalForUID(jsondata["sharee"])
+
+            if "supported-components" in jsondata:
+                comps = jsondata["supported-components"]
+                if comps:
+                    comps = comps.split(",")
+                else:
+                    comps = ical.allowedStoreComponents
+                supported = caldavxml.SupportedCalendarComponentSet(
+                    *[caldavxml.CalendarComponent(name=item) for item in comps]
+                )
+            else:
+                supported = None
+
+            typeAttr = {"shared-type": jsondata["shared-type"]}
+            xmldata = customxml.Notification(
+                customxml.DTStamp.fromString(jsondata["dtstamp"]),
+                customxml.InviteNotification(
+                    customxml.UID.fromString(jsondata["uid"]),
+                    element.HRef.fromString("urn:uuid:" + jsondata["sharee"]),
+                    invitationBindStatusToXMLMap[jsondata["status"]](),
+                    customxml.InviteAccess(invitationBindModeToXMLMap[jsondata["access"]]()),
+                    customxml.HostURL(
+                        element.HRef.fromString(urljoin(ownerHomeURL, jsondata["ownerName"])),
+                    ),
+                    customxml.Organizer(
+                        element.HRef.fromString(owner),
+                        customxml.CommonName.fromString(ownerCN),
+                    ),
+                    customxml.InviteSummary.fromString(jsondata["summary"]),
+                    supported,
+                    **typeAttr
+                ),
+            )
+        elif jsondata["notification-type"] == "invite-reply":
+            ownerPrincipal = self.principalForUID(jsondata["owner"])
+            ownerHomeURL = ownerPrincipal.calendarHomeURLs()[0] if jsondata["shared-type"] == "calendar" else ownerPrincipal.addressBookHomeURLs()[0]
+
+            shareePrincipal = self.principalForUID(jsondata["sharee"])
+
+            # FIXME:  use urn:uuid always?
+            if jsondata["shared-type"] == "calendar":
+                # Prefer mailto:, otherwise use principal URL
+                for cua in shareePrincipal.calendarUserAddresses():
+                    if cua.startswith("mailto:"):
+                        break
+                else:
+                    cua = shareePrincipal.principalURL()
+            else:
+                cua = "urn:uuid:" + shareePrincipal.principalUID()
+
+            commonName = shareePrincipal.displayName()
+            record = shareePrincipal.record
+
+            typeAttr = {"shared-type": jsondata["shared-type"]}
+            xmldata = customxml.Notification(
+                customxml.DTStamp.fromString(jsondata["dtstamp"]),
+                customxml.InviteReply(
+                    element.HRef.fromString(cua),
+                    invitationBindStatusToXMLMap[jsondata["status"]](),
+                    customxml.HostURL(
+                        element.HRef.fromString(urljoin(ownerHomeURL, jsondata["ownerName"])),
+                    ),
+                    customxml.InReplyTo.fromString(jsondata["in-reply-to"]),
+                    customxml.InviteSummary.fromString(jsondata["summary"]) if jsondata["summary"] else None,
+                    customxml.CommonName.fromString(commonName) if commonName else None,
+                    customxml.FirstNameProperty(record.firstName) if record.firstName else None,
+                    customxml.LastNameProperty(record.lastName) if record.lastName else None,
+                    #**typeAttr
+                ),
+            )
+        else:
+            raise HTTPError(responsecode.INTERNAL_SERVER_ERROR)
+        returnValue(xmldata.toxml())
+
+
     @requiresPermissions(davxml.Read())
     @inlineCallbacks
     def http_GET(self, request):

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/test/test_sharing.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/test/test_sharing.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/twistedcaldav/test/test_sharing.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -19,7 +19,7 @@
 from twext.web2.http_headers import MimeType
 from twext.web2.iweb import IResponse
 
-from twisted.internet.defer import inlineCallbacks, returnValue, succeed
+from twisted.internet.defer import inlineCallbacks, returnValue
 
 from twistedcaldav import customxml
 from twistedcaldav import sharing
@@ -52,8 +52,7 @@
 
 
 class FakeHome(object):
-    def removeShareByUID(self, request, uid):
-        pass
+    pass
 
 
 
@@ -105,6 +104,10 @@
         returnValue(b)
 
 
+    def calendarHomeURLs(self):
+        return (self.homepath,)
+
+
     def principalURL(self):
         return self.path
 
@@ -142,22 +145,6 @@
             return c
 
         @patched
-        def sendInviteNotification(resourceSelf, record, request):
-            """
-            For testing purposes, sending an invite notification succeeds
-            without doing anything.
-            """
-            return succeed(True)
-
-        @patched
-        def removeInviteNotification(resourceSelf, record, request):
-            """
-            For testing purposes, removing an invite notification succeeds
-            without doing anything.
-            """
-            return succeed(True)
-
-        @patched
         def principalForCalendarUserAddress(resourceSelf, cuaddr):
             if "bogus" in cuaddr:
                 return None

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/base/datastore/util.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/base/datastore/util.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/base/datastore/util.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -95,7 +95,7 @@
     # Home child objects by id
 
     def keyForObjectWithResourceID(self, homeResourceID, resourceID):
-        return "objectWithName:%s:%s" % (homeResourceID, resourceID)
+        return "objectWithResourceID:%s:%s" % (homeResourceID, resourceID)
 
 
     # Home metadata (Created/Modified)

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/sql.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/sql.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/sql.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from txdav.xml import element
 
 
 """
@@ -396,6 +397,8 @@
 
     implements(ICalendarHome)
 
+    _homeType = ECALENDARTYPE
+
     # structured tables.  (new, preferred)
     _homeSchema = schema.CALENDAR_HOME
     _bindSchema = schema.CALENDAR_BIND
@@ -1245,6 +1248,44 @@
         )
 
 
+    def sharedResourceType(self):
+        """
+        The sharing resource type
+        """
+        return "calendar"
+
+
+    @inlineCallbacks
+    def newShare(self, displayname=None):
+        """
+        Override in derived classes to do any specific operations needed when a share
+        is first accepted.
+        """
+
+        # For a direct share we will copy any displayname and calendar-color over using the owners view
+        if self.direct():
+            ownerView = yield self.ownerView()
+            try:
+                displayname = ownerView.properties()[PropertyName.fromElement(element.DisplayName)]
+                self.properties()[PropertyName.fromElement(element.DisplayName)] = displayname
+            except KeyError:
+                pass
+            try:
+                color = ownerView.properties()[PropertyName.fromElement(customxml.CalendarColor)]
+                self.properties()[PropertyName.fromElement(customxml.CalendarColor)] = color
+            except KeyError:
+                pass
+        elif displayname:
+            self.properties()[PropertyName.fromElement(element.DisplayName)] = element.DisplayName.fromString(displayname)
+
+        # Calendars always start out transparent and with empty default alarms
+        yield self.setUsedForFreeBusy(False)
+        yield self.setDefaultAlarm("empty", True, True)
+        yield self.setDefaultAlarm("empty", True, False)
+        yield self.setDefaultAlarm("empty", False, True)
+        yield self.setDefaultAlarm("empty", False, False)
+
+
     # FIXME: this is DAV-ish.  Data store calendar objects don't have
     # mime types.  -wsv
     def contentType(self):

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/common.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/common.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/common.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -41,21 +41,21 @@
 from txdav.common.icommondatastore import ObjectResourceNameAlreadyExistsError
 from txdav.common.inotifications import INotificationObject
 from txdav.common.datastore.test.util import CommonCommonTests
-from txdav.common.datastore.sql_tables import _BIND_MODE_WRITE, _BIND_MODE_READ
 
 from txdav.caldav.icalendarstore import (
     ICalendarObject, ICalendarHome,
     ICalendar, ICalendarTransaction,
     ComponentUpdateState)
 
-from twistedcaldav.customxml import InviteNotification, InviteSummary
 from txdav.common.datastore.test.util import transactionClean
 from txdav.common.icommondatastore import ConcurrentModification
 from twistedcaldav.ical import Component
 from twistedcaldav.config import config
 from calendarserver.push.util import PushPriority
 
+import json
 
+
 storePath = FilePath(__file__).parent().child("calendar_store")
 
 homeRoot = storePath.child("ho").child("me").child("home1")
@@ -374,9 +374,11 @@
     def notificationUnderTest(self):
         txn = self.transactionUnderTest()
         notifications = yield txn.notificationsWithUID("home1")
-        inviteNotification = InviteNotification()
-        yield notifications.writeNotificationObject("abc", inviteNotification,
-            inviteNotification.toxml())
+        yield notifications.writeNotificationObject(
+            "abc",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+        )
         notificationObject = yield notifications.notificationObjectWithUID("abc")
         returnValue(notificationObject)
 
@@ -399,10 +401,17 @@
         """
         txn = self.transactionUnderTest()
         coll = yield txn.notificationsWithUID("home1")
-        invite1 = InviteNotification()
-        yield coll.writeNotificationObject("1", invite1, invite1.toxml())
+        yield coll.writeNotificationObject(
+            "1",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+        )
         st = yield coll.syncToken()
-        yield coll.writeNotificationObject("2", invite1, invite1.toxml())
+        yield coll.writeNotificationObject(
+            "2",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+        )
         rev = self.token2revision(st)
         yield coll.removeNotificationObjectWithUID("1")
         st2 = yield coll.syncToken()
@@ -424,14 +433,21 @@
         notifications = yield self.transactionUnderTest().notificationsWithUID(
             "home1"
         )
-        inviteNotification = InviteNotification()
-        yield notifications.writeNotificationObject("abc", inviteNotification,
-            inviteNotification.toxml())
-        inviteNotification2 = InviteNotification(InviteSummary("a summary"))
         yield notifications.writeNotificationObject(
-            "abc", inviteNotification, inviteNotification2.toxml())
+            "abc",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+        )
+        yield notifications.writeNotificationObject(
+            "abc",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\",\"summary\":\"a summary\"}"),
+        )
         abc = yield notifications.notificationObjectWithUID("abc")
-        self.assertEquals((yield abc.xmldata()), inviteNotification2.toxml())
+        self.assertEquals(
+            (yield abc.notificationData()),
+            json.loads("{\"notification-type\":\"invite-notification\",\"summary\":\"a summary\"}"),
+        )
 
 
     @inlineCallbacks
@@ -450,9 +466,11 @@
             "home1"
         )
         self.notifierFactory.reset()
-        inviteNotification = InviteNotification()
-        yield notifications.writeNotificationObject("abc", inviteNotification,
-            inviteNotification.toxml())
+        yield notifications.writeNotificationObject(
+            "abc",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+        )
 
         # notify is called prior to commit
         self.assertEquals(
@@ -492,12 +510,16 @@
         notifications = yield self.transactionUnderTest().notificationsWithUID(
             "home1"
         )
-        inviteNotification = InviteNotification()
-        yield notifications.writeNotificationObject("abc", inviteNotification,
-            inviteNotification.toxml())
-        inviteNotification2 = InviteNotification(InviteSummary("a summary"))
         yield notifications.writeNotificationObject(
-            "def", inviteNotification, inviteNotification2.toxml())
+            "abc",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+        )
+        yield notifications.writeNotificationObject(
+            "def",
+            json.loads("{\"notification-type\":\"invite-notification\"}"),
+            json.loads("{\"notification-type\":\"invite-notification\",\"summary\":\"a summary\"}"),
+        )
 
         yield self.commit()
 
@@ -951,156 +973,6 @@
 
 
     @inlineCallbacks
-    def test_shareWith(self):
-        """
-        L{ICalendar.shareWith} will share a calendar with a given home UID.
-        """
-        cal = yield self.calendarUnderTest()
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        newCalName = yield cal.shareWith(other, _BIND_MODE_WRITE)
-        self.sharedName = newCalName
-        yield self.commit()
-        normalCal = yield self.calendarUnderTest()
-        otherHome = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield otherHome.childWithName(newCalName)
-        self.assertNotIdentical(otherCal, None)
-        self.assertEqual(
-            (yield
-             (yield otherCal.calendarObjectWithName("1.ics")).component()),
-            (yield
-             (yield normalCal.calendarObjectWithName("1.ics")).component())
-        )
-
-
-    @inlineCallbacks
-    def test_shareAgainChangesMode(self):
-        """
-        If a calendar is already shared with a given calendar home,
-        L{ICalendar.shareWith} will change the sharing mode.
-        """
-        yield self.test_shareWith()
-        # yield self.commit() # txn is none? why?
-        cal = yield self.calendarUnderTest()
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        newName = yield cal.shareWith(other, _BIND_MODE_READ)
-        otherCal = yield other.childWithName(self.sharedName)
-
-        # Name should not change just because we updated the mode.
-        self.assertEqual(newName, self.sharedName)
-        self.assertNotIdentical(otherCal, None)
-
-        invitedCals = yield cal.sharingInvites()
-        self.assertEqual(len(invitedCals), 1)
-        self.assertEqual(invitedCals[0].mode(), _BIND_MODE_READ)
-
-
-    @inlineCallbacks
-    def test_unshareWith(self, commit=False):
-        """
-        L{ICalendar.unshareWith} will remove a previously-shared calendar from
-        another user's calendar home.
-        """
-        yield self.test_shareWith()
-        if commit:
-            yield self.commit()
-        cal = yield self.calendarUnderTest()
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        newName = yield cal.unshareWith(other)
-        otherCal = yield other.childWithName(newName)
-        self.assertIdentical(otherCal, None)
-        invitedCals = yield cal.sharingInvites()
-        self.assertEqual(len(invitedCals), 0)
-
-
-    @inlineCallbacks
-    def test_unshareSharerSide(self, commit=False):
-        """
-        Verify the coll.unshare( ) method works when called from the
-        sharer's copy
-        """
-        yield self.test_shareWith()
-        if commit:
-            yield self.commit()
-        cal = yield self.calendarUnderTest()
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield other.childWithName(self.sharedName)
-        self.assertNotEqual(otherCal, None)
-        yield cal.unshare()
-        otherCal = yield other.childWithName(self.sharedName)
-        self.assertEqual(otherCal, None)
-        invitedCals = yield cal.sharingInvites()
-        self.assertEqual(len(invitedCals), 0)
-
-
-    @inlineCallbacks
-    def test_unshareShareeSide(self, commit=False):
-        """
-        Verify the coll.unshare( ) method works when called from the
-        sharee's copy
-        """
-        yield self.test_shareWith()
-        if commit:
-            yield self.commit()
-        cal = yield self.calendarUnderTest()
-        other = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        otherCal = yield other.childWithName(self.sharedName)
-        self.assertNotEqual(otherCal, None)
-        yield otherCal.unshare()
-        otherCal = yield other.childWithName(self.sharedName)
-        self.assertEqual(otherCal, None)
-        invitedCals = yield cal.sharingInvites()
-        self.assertEqual(len(invitedCals), 0)
-
-
-    @inlineCallbacks
-    def test_unshareWithInDifferentTransaction(self):
-        """
-        L{ICalendar.unshareWith} will remove a previously-shared calendar from
-        another user's calendar home, assuming the sharing was committed in a
-        previous transaction.
-        """
-        yield self.test_unshareWith(True)
-
-
-    @inlineCallbacks
-    def test_sharingInvites(self):
-        """
-        L{ICalendar.sharingInvites} returns an iterable of all versions of a shared
-        calendar.
-        """
-        cal = yield self.calendarUnderTest()
-        sharedBefore = yield cal.sharingInvites()
-        # It's not shared yet; make sure sharingInvites doesn't include owner version.
-        self.assertEqual(len(sharedBefore), 0)
-        yield self.test_shareWith()
-        # FIXME: don't know why this separate transaction is needed; remove it.
-        yield self.commit()
-        cal = yield self.calendarUnderTest()
-        sharedAfter = yield cal.sharingInvites()
-        self.assertEqual(len(sharedAfter), 1)
-        self.assertEqual(sharedAfter[0].mode(), _BIND_MODE_WRITE)
-        self.assertEqual(sharedAfter[0].shareeUID(), OTHER_HOME_UID)
-
-
-    @inlineCallbacks
-    def test_sharedNotifierID(self):
-        yield self.test_shareWith()
-        yield self.commit()
-
-        home = yield self.homeUnderTest()
-        self.assertEquals(home.notifierID(), ("CalDAV", "home1",))
-        calendar = yield home.calendarWithName("calendar_1")
-        self.assertEquals(calendar.notifierID(), ("CalDAV", "home1/calendar_1",))
-        yield self.commit()
-
-        home = yield self.homeUnderTest(name=OTHER_HOME_UID)
-        self.assertEquals(home.notifierID(), ("CalDAV", OTHER_HOME_UID,))
-        calendar = yield home.calendarWithName(self.sharedName)
-        self.assertEquals(calendar.notifierID(), ("CalDAV", "home1/calendar_1",))
-        yield self.commit()
-
-
-    @inlineCallbacks
     def test_hasCalendarResourceUIDSomewhereElse(self):
         """
         L{ICalendarHome.hasCalendarResourceUIDSomewhereElse} will determine if

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -51,7 +51,7 @@
 
 from txdav.base.propertystore.base import PropertyName
 from txdav.caldav.datastore.test.common import CommonTests as CalendarCommonTests, \
-    test_event_text, OTHER_HOME_UID
+    test_event_text
 from txdav.caldav.datastore.test.test_file import setUpCalendarStore
 from txdav.caldav.datastore.test.util import buildCalendarStore
 from txdav.caldav.datastore.util import _migrateCalendar, migrateHome
@@ -59,7 +59,7 @@
 from txdav.common.datastore.sql import ECALENDARTYPE, CommonObjectResource
 from txdav.common.datastore.sql_legacy import PostgresLegacyIndexEmulator
 from txdav.common.datastore.sql_tables import schema, _BIND_MODE_DIRECT, \
-    _BIND_STATUS_ACCEPTED, _BIND_MODE_WRITE, _BIND_STATUS_INVITED
+    _BIND_STATUS_ACCEPTED
 from txdav.common.datastore.test.util import populateCalendarsFrom, \
     CommonCommonTests
 from txdav.common.icommondatastore import NoSuchObjectResourceError
@@ -952,13 +952,13 @@
 
         @inlineCallbacks
         def _defer1():
-            yield cal1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki Calendar")
+            yield cal1.directShareWithUser("uid2")
             yield txn1.commit()
         d1 = _defer1()
 
         @inlineCallbacks
         def _defer2():
-            yield cal2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki Calendar")
+            yield cal2.directShareWithUser("uid1")
             yield txn2.commit()
         d2 = _defer2()
 
@@ -1708,90 +1708,6 @@
 
 
     @inlineCallbacks
-    def test_shareWithRevision(self):
-        """
-        Verify that bindRevision on calendars and shared calendars has the correct value.
-        """
-        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):
-        """
-        Verify that bindRevision on calendars and shared calendars has the correct value.
-        """
-        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):
-        """
-        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
-        """
-        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(0)
-        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 ("1", "infinity",):
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(0, 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
     def test_setAvailability(self):
         """
         Make sure a L{CalendarHome}.setAvailability() works.

Copied: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql_sharing.py (from rev 12017, CalendarServer/trunk/txdav/caldav/datastore/test/test_sql_sharing.py)
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql_sharing.py	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/caldav/datastore/test/test_sql_sharing.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,572 @@
+##
+# Copyright (c) 2005-2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twisted.trial.unittest import TestCase
+
+from twext.python.clsprop import classproperty
+from txdav.common.datastore.test.util import CommonCommonTests, \
+    populateCalendarsFrom
+from txdav.caldav.datastore.test.util import buildCalendarStore
+from txdav.common.datastore.sql_tables import _BIND_MODE_READ, \
+    _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED
+
+
+class BaseSharingTests(CommonCommonTests, TestCase):
+    """
+    Test store-based calendar sharing.
+    """
+
+    @inlineCallbacks
+    def setUp(self):
+        yield super(BaseSharingTests, self).setUp()
+        self._sqlCalendarStore = yield buildCalendarStore(self, self.notifierFactory)
+        yield self.populate()
+
+
+    @inlineCallbacks
+    def populate(self):
+        yield populateCalendarsFrom(self.requirements, self.storeUnderTest())
+        self.notifierFactory.reset()
+
+    cal1 = """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
+"""
+
+    @classproperty(cache=False)
+    def requirements(cls): #@NoSelf
+        return {
+        "user01": {
+            "calendar": {
+                "cal1.ics": (cls.cal1, None,),
+            },
+            "inbox": {
+            },
+        },
+        "user02": {
+            "calendar": {
+            },
+            "inbox": {
+            },
+        },
+        "user03": {
+            "calendar": {
+            },
+            "inbox": {
+            },
+        },
+    }
+
+
+    def storeUnderTest(self):
+        """
+        Create and return a L{CalendarStore} for testing.
+        """
+        return self._sqlCalendarStore
+
+
+    @inlineCallbacks
+    def _createShare(self):
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        inviteUID = shareeView.shareUID()
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.homeUnderTest(name="user02")
+        shareeView = yield shareeHome.acceptShare(inviteUID)
+        sharedName = shareeView.name()
+        yield self.commit()
+
+        returnValue(sharedName)
+
+
+
+class CalendarSharing(BaseSharingTests):
+
+    @inlineCallbacks
+    def test_no_shares(self):
+        """
+        Test that initially there are no shares.
+        """
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(calendar.isShared())
+
+
+    @inlineCallbacks
+    def test_invite_sharee(self):
+        """
+        Test invite/uninvite creates/removes shares and notifications.
+        """
+
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(calendar.isShared())
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertEqual(invites[0].uid, shareeView.shareUID())
+        self.assertEqual(invites[0].ownerUID, "user01")
+        self.assertEqual(invites[0].shareeUID, "user02")
+        self.assertEqual(invites[0].mode, _BIND_MODE_READ)
+        self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
+        self.assertEqual(invites[0].summary, "summary")
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID, ])
+
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Uninvite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+
+        yield calendar.uninviteUserFromShare("user02")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [])
+
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+        yield calendar.setShared(False)
+        self.assertFalse(calendar.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_share(self):
+        """
+        Test that invite+accept creates shares and notifications.
+        """
+
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(calendar.isShared())
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(len(notifications), 1)
+
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Re-accept
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+
+
+    @inlineCallbacks
+    def test_decline_share(self):
+        """
+        Test that invite+decline does not create shares but does create notifications.
+        """
+
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(calendar.isShared())
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(len(notifications), 1)
+
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Redecline
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_decline_share(self):
+        """
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the home.
+        """
+
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(calendar.isShared())
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(len(notifications), 1)
+
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertTrue(calendar.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_remove_share(self):
+        """
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the shared collection (removal).
+        """
+
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(len(notifications), 1)
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.homeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+        yield self.commit()
+
+        # Delete
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        yield shared.deleteShare()
+
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user01")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(notifications, [inviteUID + "-reply", ])
+
+
+    @inlineCallbacks
+    def test_inviteProperties(self):
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        yield calendar.setUsedForFreeBusy(True)
+        yield self.commit()
+
+        shared_name = yield self._createShare()
+
+        shared = yield self.calendarUnderTest(home="user02", name=shared_name)
+        self.assertFalse(shared.isUsedForFreeBusy())
+
+
+    @inlineCallbacks
+    def test_direct_sharee(self):
+        """
+        Test invite/uninvite creates/removes shares and notifications.
+        """
+
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(calendar.isShared())
+
+        shareeView = yield calendar.directShareWithUser("user02")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertEqual(invites[0].uid, shareeView.shareUID())
+        self.assertEqual(invites[0].ownerUID, "user01")
+        self.assertEqual(invites[0].shareeUID, "user02")
+        self.assertEqual(invites[0].mode, _BIND_MODE_DIRECT)
+        self.assertEqual(invites[0].status, _BIND_STATUS_ACCEPTED)
+
+        sharedName = shareeView.name()
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(len(notifications), 0)
+
+        yield self.commit()
+
+        # Remove
+        shared = yield self.calendarUnderTest(home="user02", name=sharedName)
+        yield shared.deleteShare()
+
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        notifyHome = yield self.transactionUnderTest().notificationsWithUID("user02")
+        notifications = yield notifyHome.listNotificationObjects()
+        self.assertEqual(len(notifications), 0)
+
+
+    @inlineCallbacks
+    def test_sharedNotifierID(self):
+        shared_name = yield self._createShare()
+
+        home = yield self.homeUnderTest(name="user01")
+        self.assertEquals(home.notifierID(), ("CalDAV", "user01",))
+        calendar = yield home.calendarWithName("calendar")
+        self.assertEquals(calendar.notifierID(), ("CalDAV", "user01/calendar",))
+        yield self.commit()
+
+        home = yield self.homeUnderTest(name="user02")
+        self.assertEquals(home.notifierID(), ("CalDAV", "user02",))
+        calendar = yield home.calendarWithName(shared_name)
+        self.assertEquals(calendar.notifierID(), ("CalDAV", "user01/calendar",))
+        yield self.commit()
+
+
+
+class SharingRevisions(BaseSharingTests):
+    """
+    Test store-based sharing and interaction with revision table.
+    """
+
+    @inlineCallbacks
+    def test_shareWithRevision(self):
+        """
+        Verify that bindRevision on calendars and shared calendars has the correct value.
+        """
+        sharedName = yield self._createShare()
+
+        normalCal = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherCal = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertNotEqual(otherCal._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_updateShareRevision(self):
+        """
+        Verify that bindRevision on calendars and shared calendars has the correct value.
+        """
+        # Invite
+        calendar = yield self.calendarUnderTest(home="user01", name="calendar")
+        invites = yield calendar.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield calendar.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        newCalName = shareeView.shareUID()
+        yield self.commit()
+
+        normalCal = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherHome = yield self.homeUnderTest(name="user02")
+        otherCal = yield otherHome.anyObjectWithShareUID(newCalName)
+        self.assertEqual(otherCal._bindRevision, 0)
+        yield self.commit()
+
+        shareeHome = yield self.homeUnderTest(name="user02")
+        shareeView = yield shareeHome.acceptShare(newCalName)
+        sharedName = shareeView.name()
+        yield self.commit()
+
+        normalCal = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherCal = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertNotEqual(otherCal._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_sharedRevisions(self):
+        """
+        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
+        """
+        sharedName = yield self._createShare()
+
+        normalCal = yield self.calendarUnderTest(home="user01", name="calendar")
+        self.assertEqual(normalCal._bindRevision, 0)
+        otherHome = yield self.homeUnderTest(name="user02")
+        otherCal = yield self.calendarUnderTest(home="user02", name=sharedName)
+        self.assertNotEqual(otherCal._bindRevision, 0)
+
+        changed, deleted = yield otherCal.resourceNamesSinceRevision(0)
+        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 ("1", "infinity",):
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(0, 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)

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/sql.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/sql.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/sql.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # #
+from txdav.xml import element
 
 """
 SQL backend for CardDAV storage.
@@ -41,8 +42,8 @@
 from twistedcaldav import carddavxml, customxml
 from twistedcaldav.config import config
 from twistedcaldav.memcacher import Memcacher
-from twistedcaldav.vcard import Component as VCard, InvalidVCardDataError, \
-    vCardProductID, Property
+from twistedcaldav.vcard import Component as VCard, InvalidVCardDataError, Property, \
+    vCardProductID
 
 from txdav.base.propertystore.base import PropertyName
 from txdav.base.propertystore.sql import PropertyStore
@@ -55,15 +56,13 @@
 from txdav.common.datastore.sql_tables import _ABO_KIND_PERSON, \
     _ABO_KIND_GROUP, _ABO_KIND_RESOURCE, _ABO_KIND_LOCATION, schema, \
     _BIND_MODE_OWN, _BIND_MODE_WRITE, _BIND_STATUS_ACCEPTED, \
-    _BIND_STATUS_DECLINED
+    _BIND_STATUS_INVITED, _BIND_MODE_INDIRECT, _BIND_STATUS_DECLINED
 from txdav.common.icommondatastore import InternalDataStoreError, \
     InvalidUIDError, UIDExistsError, ObjectResourceTooBigError, \
     InvalidObjectResourceError, InvalidComponentForStoreError, \
     AllRetriesFailed, ObjectResourceNameAlreadyExistsError, \
     SyncTokenValidException
 
-from uuid import uuid4
-
 from zope.interface.declarations import implements
 
 
@@ -71,6 +70,8 @@
 
     implements(IAddressBookHome)
 
+    _homeType = EADDRESSBOOKTYPE
+
     # structured tables.  (new, preferred)
     _homeSchema = schema.ADDRESSBOOK_HOME
     _bindSchema = schema.SHARED_ADDRESSBOOK_BIND
@@ -102,13 +103,36 @@
     removeAddressBookWithName = CommonHome.removeChildWithName
 
 
-    @classproperty
-    def _resourceIDAndHomeResourceIDFromOwnerQuery(cls): #@NoSelf
-        home = cls._homeSchema
-        return Select([home.RESOURCE_ID, home.ADDRESSBOOK_PROPERTY_STORE_ID],
-                      From=home, Where=home.OWNER_UID == Parameter("ownerUID"))
+    @classmethod
+    def homeColumns(cls):
+        """
+        Return a list of column names to retrieve when doing an ownerUID->home lookup.
+        """
 
+        # Common behavior is to have created and modified
 
+        return (
+            cls._homeSchema.RESOURCE_ID,
+            cls._homeSchema.OWNER_UID,
+            cls._homeSchema.ADDRESSBOOK_PROPERTY_STORE_ID,
+        )
+
+
+    @classmethod
+    def homeAttributes(cls):
+        """
+        Return a list of attributes names to map L{homeColumns} to.
+        """
+
+        # Common behavior is to have created and modified
+
+        return (
+            "_resourceID",
+            "_ownerUID",
+            "_addressbookPropertyStoreID",
+        )
+
+
     @inlineCallbacks
     def initFromStore(self, no_cache=False):
         """
@@ -116,48 +140,27 @@
         extra meta-data from the DB to avoid having to do DB queries for those
         individually later.
         """
-        result = yield self._cacher.get(self._ownerUID)
-        if result is None:
-            result = yield self._resourceIDAndHomeResourceIDFromOwnerQuery.on(
-                self._txn, ownerUID=self._ownerUID)
-            if result and not no_cache:
-                yield self._cacher.set(self._ownerUID, result)
 
-        if result:
-            self._resourceID, self._addressbookPropertyStoreID = result[0]
-
-            queryCacher = self._txn._queryCacher
-            if queryCacher:
-                # Get cached copy
-                cacheKey = queryCacher.keyForHomeMetaData(self._resourceID)
-                data = yield queryCacher.get(cacheKey)
-            else:
-                data = None
-            if data is None:
-                # Don't have a cached copy
-                data = (yield self._metaDataQuery.on(
-                    self._txn, resourceID=self._resourceID))[0]
-                if queryCacher:
-                    # Cache the data
-                    yield queryCacher.setAfterCommit(self._txn, cacheKey, data)
-
-            # self._created, self._modified = data
-            yield self._loadPropertyStore()
-
-            # created owned address book
+        result = yield super(AddressBookHome, self).initFromStore(no_cache)
+        if result is not None:
+            # Created owned address book
             addressbook = AddressBook(
                 home=self,
-                name="addressbook", resourceID=self._resourceID,
-                mode=_BIND_MODE_OWN, status=_BIND_STATUS_ACCEPTED,
+                name="addressbook",
+                resourceID=self._resourceID,
+                mode=_BIND_MODE_OWN,
+                status=_BIND_STATUS_ACCEPTED,
             )
-            self._created, self._modified = data
             yield addressbook._loadPropertyStore()
-            yield addressbook._initIsShared()
+
+            # Extra check for shared
+            invites = yield addressbook.sharingInvites()
+            if len(invites) != 0:
+                addressbook._bindMessage = "shared"
+
             self._addressbook = addressbook
 
-            returnValue(self)
-        else:
-            returnValue(None)
+        returnValue(result)
 
 
     @inlineCallbacks
@@ -198,6 +201,22 @@
 
 
     @inlineCallbacks
+    def anyObjectWithShareUID(self, shareUID):
+        """
+        Retrieve the child accepted or otherwise with the given bind identifier contained in this
+        home.
+
+        @param name: a string.
+        @return: an L{ICalendar} or C{None} if no such child exists.
+        """
+        result = yield super(AddressBookHome, self).anyObjectWithShareUID(shareUID)
+        if result is None:
+            result = yield AddressBookObject.objectWithBindName(self, shareUID, accepted=None)
+
+        returnValue(result)
+
+
+    @inlineCallbacks
     def removeUnacceptedShares(self):
         """
         Unbinds any collections that have been shared to this home but not yet
@@ -205,6 +224,7 @@
         """
         super(AddressBookHome, self).removeUnacceptedShares()
 
+        # Remove group binds too
         bind = AddressBookObject._bindSchema
         kwds = {"homeResourceID" : self._resourceID}
         yield Delete(
@@ -218,32 +238,6 @@
         return self._addressbook
 
 
-    def shareeAddressBookName(self):
-        return self.uid()
-
-
-    def objectWithShareUID(self, shareUID):
-        """
-        Retrieve the child with the given bind identifier contained in this
-        home.
-
-        @param name: a string.
-        @return: an L{ICalendar} or C{None} if no such child exists.
-        """
-        return self._childClass.objectWithBindName(self, shareUID, accepted=True)
-
-
-    def invitedObjectWithShareUID(self, shareUID):
-        """
-        Retrieve the child invitation with the given bind identifier contained in this
-        home.
-
-        @param name: a string.
-        @return: an L{ICalendar} or C{None} if no such child exists.
-        """
-        return self._childClass.objectWithBindName(self, shareUID, accepted=False)
-
-
     @inlineCallbacks
     def ownerHomeWithChildID(self, resourceID):
         """
@@ -365,44 +359,92 @@
         Sharing code shared between AddressBook and AddressBookObject
     """
 
-    def setShared(self, shared):
+    def sharedResourceType(self):
         """
-        Set an owned collection to shared or unshared state. Technically this is not useful as "shared"
-        really means it has invitees, but the current sharing spec supports a notion of a shared collection
-        that has not yet had invitees added. For the time being we will support that option by using a new
-        MESSAGE value to indicate an owned collection that is "shared".
+        The sharing resource type
+        """
+        return "addressbook"
 
-        @param shared: whether or not the owned collection is "shared"
-        @type shared: C{bool}
+
+    @inlineCallbacks
+    def deleteShare(self):
         """
-        if self.owned():
-            self._bindMessage = "shared" if shared else None
+        This share is being deleted - decline and decline shared groups too.
+        """
 
+        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()
 
+
+    def newShareName(self):
+        """
+        For shared address books the resource name of a share is the ownerUID of the owner's resource.
+        """
+        return self.ownerHome().uid()
+
+
     @inlineCallbacks
-    def _isSharedOrInvited(self):
+    def newShare(self, displayname=None):
         """
-        return True if this L{AddressBook} is shared or invited
+        Override in derived classes to do any specific operations needed when a share
+        is first accepted.
         """
-        sharedRows = []
-        if self.owned():
-            bind = self._bindSchema
-            sharedRows = yield self._bindFor(
-                (bind.RESOURCE_ID == Parameter("resourceID"))).on(
-                self._txn, resourceID=self._resourceID,
-            )
 
-        returnValue(bool(sharedRows))
+        # 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
 
 
+    def fullyShared(self):
+        return not self.owned() and not self.indirect() and self.accepted()
+
+
     @inlineCallbacks
-    def _initIsShared(self):
-        isShared = yield self._isSharedOrInvited()
-        self.setShared(isShared)
+    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)
 
 
+    @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)
 
-class AddressBook(CommonHomeChild, AddressBookSharingMixIn):
+
+
+class AddressBook(AddressBookSharingMixIn, CommonHomeChild):
     """
     SQL-based implementation of L{IAddressBook}.
     """
@@ -417,14 +459,13 @@
     _objectSchema = schema.ADDRESSBOOK_OBJECT
 
 
-    def __init__(self, home, name, resourceID, mode, status, revision=0, message=None, ownerHome=None, bindName=None):
+    def __init__(self, home, name, resourceID, mode, status, revision=0, message=None, ownerHome=None, ownerName=None):
         ownerName = ownerHome.addressbook().name() if ownerHome else None
         super(AddressBook, self).__init__(
             home, name, resourceID, mode, status, revision=revision,
             message=message, ownerHome=ownerHome, ownerName=ownerName
         )
         self._index = PostgresLegacyABIndexEmulator(self)
-        self._bindName = bindName
 
 
     def __repr__(self):
@@ -436,7 +477,8 @@
 
 
     def setCreated(self, newValue):
-        self.ownerHome()._created = newValue
+        if newValue is not None:
+            self.ownerHome()._created = newValue
 
 
     def getModified(self):
@@ -444,36 +486,13 @@
 
 
     def setModified(self, newValue):
-        self.ownerHome()._modified = newValue
+        if newValue is not None:
+            self.ownerHome()._modified = newValue
 
     _created = property(getCreated, setCreated,)
     _modified = property(getModified, setModified,)
 
-    ownerAddressBookHome = CommonHomeChild.ownerHome
-    viewerAddressBookHome = CommonHomeChild.viewerHome
-    addressbookObjects = CommonHomeChild.objectResources
-    listAddressBookObjects = CommonHomeChild.listObjectResources
-    addressbookObjectWithName = CommonHomeChild.objectResourceWithName
-    addressbookObjectWithUID = CommonHomeChild.objectResourceWithUID
-    createAddressBookObjectWithName = CommonHomeChild.createObjectResourceWithName
-    addressbookObjectsSinceToken = CommonHomeChild.objectResourcesSinceToken
 
-
-    def shareeName(self):
-        """
-        The sharee's name for a shared address book is the sharer's home ownerUID.
-        """
-        return self.ownerHome().shareeAddressBookName()
-
-
-    def bindNameIsResourceName(self):
-        """
-        For shared address books the resource name of an accepted share is not the same as the name
-        in the bind table.
-        """
-        return False
-
-
     @classproperty
     def _deleteBumpTokenQuery(cls): #@NoSelf
         rev = cls._revisionsSchema
@@ -782,22 +801,24 @@
     @inlineCallbacks
     def listObjectResources(self):
         if self._objectNames is None:
+            # Check for non-group shared
             if self.owned() or self.fullyShared():
-                rows = yield self._objectResourceNamesQuery.on(
-                    self._txn, resourceID=self._resourceID)
+                yield super(AddressBook, self).listObjectResources()
+
+            # Group shared
             else:
                 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]
+                self._objectNames = sorted([row[0] for row in rows])
 
-            # account for fully-shared address book group
+            # Account for fully-shared address book group
             if self.fullyShared():
-                if not self._groupForSharedAddressBookName() in objectNames:
-                    objectNames.append(self._groupForSharedAddressBookName())
-            self._objectNames = sorted(objectNames)
+                if not self._groupForSharedAddressBookName() in self._objectNames:
+                    self._objectNames.append(self._groupForSharedAddressBookName())
+                    self._objectNames.sort()
 
         returnValue(self._objectNames)
 
@@ -805,18 +826,19 @@
     @inlineCallbacks
     def countObjectResources(self):
         if self._objectNames is None:
+            # Check for non-group shared
             if self.owned() or self.fullyShared():
-                rows = yield self._objectCountQuery.on(
-                    self._txn, resourceID=self._resourceID
-                )
-                count = rows[0][0]
+                count = yield super(AddressBook, self).countObjectResources()
+
+            # Group shared
             else:
                 acceptedGroupIDs = yield self.acceptedGroupIDs()
                 count = len((yield self.expandGroupIDs(self._txn, acceptedGroupIDs)))
 
-            # account for fully-shared address book group
+            # Account for fully-shared address book group
             if self.fullyShared():
                 count += 1
+
             returnValue(count)
 
         returnValue(len(self._objectNames))
@@ -857,7 +879,7 @@
     @inlineCallbacks
     def _groupForSharedAddressBookComponent(self):
 
-        n = self.shareeName()
+        n = self.viewerHome().uid()
         fn = n
         uid = self._groupForSharedAddressBookUID()
 
@@ -869,14 +891,18 @@
         component = VCard.fromString(
             """BEGIN:VCARD
 VERSION:3.0
-PRODID:%s
-UID:%s
-FN:%s
-N:%s;;;;
+PRODID:{prodid}
+UID:{uid}
+FN:{fn}
+N:{n};;;;
 X-ADDRESSBOOKSERVER-KIND:group
 END:VCARD
-""".replace("\n", "\r\n") % (vCardProductID, uid, n, fn,)
-        )
+""".replace("\n", "\r\n").format(
+            prodid=vCardProductID,
+            uid=uid,
+            fn=fn,
+            n=n,
+        ))
 
         # then get member UIDs
         abo = schema.ADDRESSBOOK_OBJECT
@@ -905,6 +931,35 @@
 
     @classmethod
     @inlineCallbacks
+    def listObjects(cls, home):
+        """
+        Retrieve the names of the children with invitations in the given home. Make sure
+        to include the default owner address book.
+
+        @return: an iterable of C{str}s.
+        """
+
+        # Default address book
+        names = set([home.addressbook().name()])
+
+        # Fully shared address books
+        names |= set((yield super(AddressBook, cls).listObjects(home)))
+
+        # 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))
+
+
+    @classmethod
+    @inlineCallbacks
     def loadAllObjects(cls, home):
         """
         Load all L{CommonHomeChild} instances which are children of a given
@@ -913,6 +968,7 @@
         operations to keep this constant wrt the number of children.  This is an
         optimization for Depth:1 operations on the home.
         """
+
         results = [home.addressbook()]
         ownerHomeToDataRowMap = {}
 
@@ -931,11 +987,11 @@
             home._txn, homeID=home._resourceID
         )
         for groupBindRow in groupBindRows:
-            bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+            bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
             ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
             ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
             if ownerHome not in ownerHomeToDataRowMap:
-                groupBindRow[0] = _BIND_MODE_WRITE
+                groupBindRow[0] = _BIND_MODE_INDIRECT
                 groupBindRow[3:7] = 4 * [None]  # bindName, bindStatus, bindRevision, bindMessage
                 ownerHomeToDataRowMap[ownerHome] = groupBindRow
 
@@ -952,18 +1008,19 @@
 
             # Create the actual objects merging in properties
             for ownerHome, dataRow in ownerHomeToDataRowMap.iteritems():
-                bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
+                bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = dataRow[:cls.bindColumnCount] #@UnusedVariable
                 additionalBind = dataRow[cls.bindColumnCount:cls.bindColumnCount + len(cls.additionalBindColumns())]
                 metadata = dataRow[cls.bindColumnCount + len(cls.additionalBindColumns()):]
 
                 child = cls(
                     home=home,
-                    name=ownerHome.shareeAddressBookName(),
+                    name=ownerHome.uid(),
                     resourceID=ownerHome._resourceID,
-                    mode=bindMode, status=bindStatus,
+                    mode=bindMode,
+                    status=bindStatus,
                     revision=bindRevision,
-                    message=bindMessage, ownerHome=ownerHome,
-                    bindName=bindName
+                    message=bindMessage,
+                    ownerHome=ownerHome,
                 )
 
                 for attr, value in zip(cls.additionalBindAttributes(), additionalBind):
@@ -993,217 +1050,117 @@
 
         @param name: a string; the name of the L{CommonHomeChild} to retrieve.
 
-        @return: an L{CommonHomeChild} or C{None} if no such child
-            exists.
+        @return: an L{CommonHomeChild} or C{None} if no such child exists.
         """
-        if accepted and name == home.addressbook().name():
+
+        # Try owned address book first
+        if name == home.addressbook().name():
             returnValue(home.addressbook())
-        # shared address books only from this point on
 
-        rows = None
-        queryCacher = home._txn._queryCacher
-        ownerHome = None
+        # Try fully shared next
+        result = yield super(AddressBook, cls).objectWithName(home, name, accepted)
 
-        if queryCacher:
-            # Retrieve data from cache
-            cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
-            cachedRows = yield queryCacher.get(cacheKey)
-            if cachedRows and (cachedRows[0][8] == _BIND_STATUS_ACCEPTED) == bool(accepted): #cachedRows[0][8] == cachedBindStatus
-                rows = cachedRows
+        # Look for indirect shares
+        if result is None:
+            result = yield cls._indirectObjectWithNameOrID(home, name=name, accepted=accepted)
 
-        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 and (bindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
-                    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
-                    )
-                    # prefer a bindStatus match, otherwise get row for cache
-                    matchingGroupBindRows = [groupBindRow for groupBindRow in groupBindRows if (groupBindRow[4] == _BIND_STATUS_ACCEPTED) == bool(accepted)]
-                    if matchingGroupBindRows:
-                        groupBindRows = matchingGroupBindRows
-                    elif bindRows:
-                        bindRows[0].insert(cls.bindColumnCount, ownerAddressBook._resourceID)
-                        bindRows[0].insert(cls.bindColumnCount + 1, bindRows[0][4])  # cachedStatus = bindStatus
-                        rows = bindRows
+        returnValue(result)
 
-                    if not rows and groupBindRows:
-                        groupBindRow = groupBindRows[0]
-                        groupBindRow.insert(AddressBookObject.bindColumnCount, ownerAddressBook._resourceID)
-                        groupBindRow.insert(AddressBookObject.bindColumnCount + 1, groupBindRow[4])
-                        groupBindRow[0] = _BIND_MODE_WRITE
-                        groupBindRow[3:7] = 4 * [None]  # bindName, bindStatus, bindRevision, bindMessage
-                        rows = [groupBindRow]
 
-            if rows and queryCacher:
-                # Cache the result
-                queryCacher.setAfterCommit(home._txn, cacheKey, rows)
-
-        if not rows:
-            returnValue(None)
-
-        row = rows[0]
-        bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage, ownerAddressBookID, cachedBindStatus = row[:cls.bindColumnCount + 2] #@UnusedVariable
-
-        # if wrong status, exit here.  Item is in queryCache
-        if (cachedBindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
-            returnValue(None)
-
-        ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
-        child = cls(
-                home=home,
-                name=ownerHome.shareeAddressBookName(), resourceID=ownerAddressBookID,
-                mode=bindMode, status=bindStatus,
-                revision=bindRevision,
-                message=bindMessage, ownerHome=ownerHome,
-                bindName=bindName,
-            )
-        yield child.initFromStore()
-        returnValue(child)
-
-
     @classmethod
     @inlineCallbacks
-    def objectWithBindName(cls, home, name, accepted):
+    def objectWithID(cls, home, resourceID, accepted=True):
         """
-        Retrieve the child or objectResource with the given bind name C{name} contained in the given
+        Retrieve the child with the given C{resourceID} contained in the given
         C{home}.
 
         @param home: a L{CommonHome}.
-
-        @param name: a string; the name of the L{CommonHomeChild} to retrieve.
-
-        @return: an L{CommonHomeChild} or L{ObjectResource} or C{None} if no such child
+        @param resourceID: a string.
+        @return: an L{CommonHomeChild} or C{None} if no such child
             exists.
         """
-        bindRows = yield cls._bindForNameAndHomeID.on(home._txn, name=name, homeID=home._resourceID)
-        if bindRows and (bindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
-            resourceID = bindRows[0][2]
 
-            # alt:
-            # returnValue((yield cls.objectWithID(home, resourceID)))
-            ownerHome = yield home.ownerHomeWithChildID(resourceID)
-            if accepted:
-                returnValue((yield home.childWithName(ownerHome.shareeAddressBookName())))
-            else:
-                returnValue((yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)))
+        # Try owned address book first
+        if home._resourceID == resourceID:
+            returnValue(home.addressbook())
 
-        groupBindRows = yield AddressBookObject._bindForNameAndHomeID.on(
-            home._txn, name=name, homeID=home._resourceID
-        )
-        if groupBindRows and (groupBindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
-            resourceID = groupBindRows[0][2]
+        # Try fully shared next
+        result = yield super(AddressBook, cls).objectWithID(home, resourceID, accepted)
 
-            ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
-            # alt:
-            # addressbook = yield cls.objectWithID(home, ownerAddressBookID)
-            ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
-            addressbook = yield home.childWithName(ownerHome.shareeAddressBookName())
-            if not addressbook:
-                addressbook = yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)
-                assert addressbook
+        # Look for indirect shares
+        if result is None:
+            result = yield cls._indirectObjectWithNameOrID(home, resourceID=resourceID, accepted=accepted)
 
-            if accepted:
-                returnValue((yield addressbook.objectResourceWithID(resourceID)))
-            else:
-                returnValue((yield AddressBookObject.objectWithID(addressbook, resourceID)))  # avoids object cache
+        returnValue(result)
 
-        returnValue(None)
 
-
     @classmethod
     @inlineCallbacks
-    def objectWithID(cls, home, resourceID, accepted=True):
+    def _indirectObjectWithNameOrID(cls, home, name=None, resourceID=None, accepted=True):
+        # replaces objectWithName()
         """
-        Retrieve the child with the given C{resourceID} contained in the given
-        C{home}.
+        Synthesize and indirect child for matching name or id based on whether shared groups exist.
 
         @param home: a L{CommonHome}.
-        @param resourceID: a string.
+
+        @param name: a string; the name of the L{CommonHomeChild} to retrieve.
+
         @return: an L{CommonHomeChild} or C{None} if no such child
             exists.
         """
-        if home._resourceID == resourceID:
-            returnValue(home.addressbook())
+        rows = None
+        ownerHome = None
 
-        bindRows = yield cls._bindForResourceIDAndHomeID.on(
-            home._txn, resourceID=resourceID, homeID=home._resourceID
-        )
-        if bindRows and (bindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
-            resourceID = bindRows[0][2]
+        # TODO: add queryCacher support
 
-            ownerHome = yield home.ownerHomeWithChildID(resourceID)
-            if accepted:
-                returnValue((yield home.childWithName(ownerHome.shareeAddressBookName())))
-            else:
-                returnValue((yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)))
+        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
+            )
 
-        groupBindRows = yield AddressBookObject._bindForHomeIDAndAddressBookID.on(
-                    home._txn, homeID=home._resourceID, addressbookID=resourceID
-        )
-        if groupBindRows and (groupBindRows[0][4] == _BIND_STATUS_ACCEPTED) == bool(accepted):
-            resourceID = groupBindRows[0][2]
+        if not rows:
+            returnValue(None)
 
-            ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
-            ownerHome = yield home.ownerHomeWithChildID(ownerAddressBookID)
-            if accepted:
-                returnValue((yield home.childWithName(ownerHome.shareeAddressBookName())))
-            else:
-                returnValue((yield cls.objectWithName(home, ownerHome.shareeAddressBookName(), accepted=False)))
+        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
 
-        returnValue(None)
+        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)
 
-    def shareUID(self):
-        """
-        @see: L{ICalendar.shareUID}
-        """
-        return self._bindName
-
-
-    def fullyShared(self):
-        return not self.owned() and self._bindStatus == _BIND_STATUS_ACCEPTED
-
-
-    @classmethod
-    @inlineCallbacks
-    def listObjects(cls, home):
-        """
-        Retrieve the names of the children with invitations in the given home.
-
-        @return: an iterable of C{str}s.
-        """
-        names = set([home.addressbook().name()])
-
-        rows = yield cls._acceptedBindForHomeID.on(
-            home._txn, homeID=home._resourceID
+        child = cls(
+            home=home,
+            name=ownerHome.uid(),
+            resourceID=resourceID,
+            mode=_BIND_MODE_INDIRECT,
+            status=overallBindStatus,
+            revision=minBindRevision,
+            message="",
+            ownerHome=ownerHome,
+            ownerName=ownerHome.uid()
         )
-        for row in rows:
-            resourceID = row[2]
-            ownerHome = yield home._txn.homeWithResourceID(home._homeType, resourceID, create=True)
-            names.add(ownerHome.shareeAddressBookName())
+        yield child.initFromStore(additionalBind)
+        returnValue(child)
 
-        groupRows = yield AddressBookObject._acceptedBindForHomeID.on(
-            home._txn, homeID=home._resourceID
-        )
-        for groupRow in groupRows:
-            resourceID = groupRow[2]
-            ownerAddressBookID = yield AddressBookObject.ownerAddressBookIDFromGroupID(home._txn, resourceID)
-            ownerHome = yield home._txn.homeWithResourceID(home._homeType, ownerAddressBookID, create=True)
-            names.add(ownerHome.shareeAddressBookName())
-        returnValue(tuple(names))
 
-
     @classmethod
     def _memberIDsWithGroupIDsQuery(cls, groupIDs):
         """
@@ -1267,7 +1224,7 @@
     @inlineCallbacks
     def expandGroupIDs(cls, txn, groupIDs, atRevision=0, includeGroupIDs=True):
         """
-        Get all AddressBookObject resource IDs contains in the given shared groups with the given groupIDs
+        Get all AddressBookObject resource IDs contained in the given shared groups with the given groupIDs
         """
         objectIDs = set(groupIDs) if includeGroupIDs else set()
         examinedIDs = set()
@@ -1285,38 +1242,49 @@
 
     @inlineCallbacks
     def unacceptedGroupIDs(self):
+        """
+        Return the list of shared groups that have not yet been accepted.
+        """
         if self.owned():
             returnValue([])
         else:
             groupBindRows = yield AddressBookObject._unacceptedBindForHomeIDAndAddressBookID.on(
-                    self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
+                self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
             )
             returnValue([groupBindRow[2] for groupBindRow in groupBindRows])
 
 
     @inlineCallbacks
     def acceptedGroupIDs(self):
+        """
+        Return the list of accepted shared groups.
+        """
         if self.owned():
             returnValue([])
         else:
             groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                    self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
+                self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
             )
             returnValue([groupBindRow[2] for groupBindRow in groupBindRows])
 
 
     @inlineCallbacks
     def _groupIDAccessSets(self):
+        """
+        For each accepted shared group, determine what its access mode is and return the sets of read-only
+        and read-write groups. Handle the case where a read-only group is actually nested in a read-write
+        group by putting the read-only one into the read-write list.
+        """
         if self.owned():
             returnValue((set(), set()))
         else:
             groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                    self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
+                self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
             )
             readWriteGroupIDs = set()
             readOnlyGroupIDs = set()
             for groupBindRow in groupBindRows:
-                bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+                bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
                 if bindMode == _BIND_MODE_WRITE:
                     readWriteGroupIDs.add(resourceID)
                 else:
@@ -1347,24 +1315,37 @@
     # FIXME: Unused:  Use for caching access
     @inlineCallbacks
     def accessControlObjectIDs(self):
+        """
+        For each object resource in this collection, determine what its access mode is and return the sets of read-only
+        and read-write objects. Handle the case where a read-only group is actually nested in a read-write
+        group by putting the read-only one into the read-write list.
+        """
+
         readOnlyIDs = set()
         readWriteIDs = set()
-        if self.owned() or self.fullyShared():
-            rows = yield self._allColumnsWithParent(self)
-            ids = set([row[1] for row in rows])
-            if self.fullyShared():
-                ids.add(self._resourceID)
-            if self.owned() or self._bindMode == _BIND_MODE_WRITE:
-                returnValue(tuple(readOnlyIDs), tuple(readWriteIDs))
+
+        # All objects in the collection
+        rows = yield self._allColumnsWithParent(self)
+        ids = set([row[1] for row in rows])
+
+        # Everything is read-write
+        if self.owned() or self.fullyShared() and self._bindMode == _BIND_MODE_WRITE:
+            returnValue(tuple(readOnlyIDs), tuple(ids))
+
+        # Fully shared but mode is read-only
+        if self.fullyShared() and self._bindMode == _BIND_MODE_READ:
+            ids |= set([self._resourceID, ])
             readOnlyIDs = set(ids)
 
+        # Look for shared groups and for those that are read-write, transfer their object ids
+        # to the read-write set
         groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
+            self._txn, homeID=self._home._resourceID, addressbookID=self._resourceID
         )
         readWriteGroupIDs = []
         readOnlyGroupIDs = []
         for groupBindRow in groupBindRows:
-            bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
+            bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = groupBindRow[:AddressBookObject.bindColumnCount] #@UnusedVariable
             if bindMode == _BIND_MODE_WRITE:
                 readWriteGroupIDs.append(resourceID)
             else:
@@ -1397,16 +1378,168 @@
         returnValue((readOnlyIDs + readWriteIDs))
     '''
 
+    # 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
+
+
+
+class AddressBookObjectSharingMixIn(SharingMixIn):
+    """
+    Sharing code for AddressBookObject
+    """
+
+    def sharedResourceType(self):
+        """
+        The sharing resource type
+        """
+        return "group"
+
+
+    #
+    # Lower level API
+    #
+
     @inlineCallbacks
-    def updateShare(self, shareeView, mode=None, status=None, message=None):
+    def ownerView(self):
         """
-        Update share mode, status, and message for a home child shared with
-        this (owned) L{CommonHomeChild}.
+        Return the owner resource counterpart of this shared resource.
+        """
+        # Get the child of the owner home that has the same resource id as the owned one
+        ownerView = yield self.ownerHome().addressbook().objectResourceWithID(self.id())
+        returnValue(ownerView)
 
-        @param shareeView: The sharee home child that shares this.
-        @type shareeView: L{CommonHomeChild}
 
+    @inlineCallbacks
+    def shareeView(self, shareeUID):
+        """
+        Return the shared resource counterpart of this owned resource for the specified sharee.
+        """
+
+        # 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):
+        """
+        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}
+        """
+
+        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.addressbook().notifyPropertyChanged()
+        yield shareeHome.notifyChanged()
+
+        returnValue(bindName)
+
+
+    @inlineCallbacks
+    def createShare(self, shareeUID, mode, summary=None):
+        """
+        Create a new shared resource. If the mode is direct, the share is created in accepted state,
+        otherwise the share is created in invited state.
+        """
+
+        if self._kind == _ABO_KIND_GROUP:
+            shareeView = yield super(AddressBookObjectSharingMixIn, self).createShare(shareeUID, mode, summary)
+            returnValue(shareeView)
+        else:
+            returnValue(None)
+
+
+    @inlineCallbacks
+    def unshare(self):
+        """
+        Unshares a group, regardless of which "direction" it was shared.
+        """
+        if self._kind == _ABO_KIND_GROUP:
+            yield super(AddressBookObjectSharingMixIn, self).unshare()
+
+
+    @property
+    def _syncTokenRevision(self):
+        return self.addressbook()._syncTokenRevision
+
+
+    def syncToken(self):
+        return self.addressbook().syncToken() # init self.addressbook()._syncTokenRevision
+
+
+    @inlineCallbacks
+    def updateShare(self, shareeView, mode=None, status=None, summary=None):
+        """
+        Update share mode, status, and message for a address book group with
+        this (owned) L{AddressBookObject}.
+
+        @param shareeView: The sharee addressbook group that shares this.
+        @type shareeView: L{AddressBookObject}
+
+        @param mode: The sharing mode; L{_BIND_MODE_READ} or
             L{_BIND_MODE_WRITE} or None to not update
         @type mode: L{str}
 
@@ -1418,9 +1551,6 @@
         @param message: The proposed message to go along with the share, which
             will be used as the default display name, or None to not update
         @type message: L{str}
-
-        @return: the name of the shared item in the sharee's home.
-        @rtype: a L{Deferred} which fires with a L{str}
         """
         # TODO: raise a nice exception if shareeView is not, in fact, a shared
         # version of this same L{CommonHomeChild}
@@ -1432,20 +1562,20 @@
             columnMap[bind.BIND_MODE] = mode
         if status != None and status != shareeView._bindStatus:
             columnMap[bind.BIND_STATUS] = status
-        if message != None and message != shareeView._bindMessage:
-            columnMap[bind.MESSAGE] = message
+        if summary != None and summary != shareeView._bindMessage:
+            columnMap[bind.MESSAGE] = summary
 
         if columnMap:
 
             # count accepted
             if bind.BIND_STATUS in columnMap:
-                previouslyAcceptedBindCount = 1 if shareeView.fullyShared() else 0
+                previouslyAcceptedBindCount = 1 if shareeView.addressbook().fullyShared() else 0
                 groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                        self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=shareeView._resourceID
+                    self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=self.addressbook()._resourceID
                 )
                 previouslyAcceptedBindCount += len(groupBindRows)
 
-            bindNameRows = yield self._updateBindColumnsQuery(columnMap).on(
+            yield self._updateBindColumnsQuery(columnMap).on(
                 self._txn,
                 resourceID=self._resourceID,
                 homeID=shareeView.viewerHome()._resourceID
@@ -1459,63 +1589,44 @@
                 shareeView._bindStatus = columnMap[bind.BIND_STATUS]
                 if shareeView._bindStatus == _BIND_STATUS_ACCEPTED:
                     if 0 == previouslyAcceptedBindCount:
-                        yield shareeView._initSyncToken()
-                        shareeView.viewerHome()._children[self.shareeName()] = shareeView
-                        shareeView.viewerHome()._children[shareeView._resourceID] = shareeView
+                        yield shareeView.addressbook()._initSyncToken()
+                        shareeView.viewerHome()._children[self.addressbook().ownerHome().uid()] = shareeView.addressbook()
+                        shareeView.viewerHome()._children[shareeView._resourceID] = shareeView.addressbook()
                     yield shareeView._initBindRevision()
                 elif shareeView._bindStatus == _BIND_STATUS_DECLINED:
                     if 1 == previouslyAcceptedBindCount:
-                        yield shareeView._deletedSyncToken(sharedRemoval=True)
-                        shareeView.viewerHome()._children.pop(self.shareeName(), None)
+                        yield shareeView.addressbook()._deletedSyncToken(sharedRemoval=True)
+                        shareeView.viewerHome()._children.pop(self.addressbook().ownerHome().uid(), None)
                         shareeView.viewerHome()._children.pop(shareeView._resourceID, None)
                     else:
-                        #update revision in all remaining bind table rows for this address book
-                        yield shareeView.notifyPropertyChanged()
+                        # update revision in all remaining bind table rows for this address book
+                        yield shareeView.addressbook().notifyPropertyChanged()
                         for groupBindRow in groupBindRows:
-                            groupObject = yield shareeView.objectResourceWithID(groupBindRow[2])
-                            yield groupObject._initBindRevision()
-                        shareeView._objects = {}
-                        shareeView._objectNames = None
+                            if groupBindRow[2] != shareeView._resourceID:
+                                groupObject = yield shareeView.addressbook().objectResourceWithID(groupBindRow[2])
+                                yield groupObject._initBindRevision()
+                        if shareeView.addressbook().fullyShared():
+                            yield shareeView.addressbook()._initBindRevision()
+                        shareeView.addressbook()._objects = {}
+                        shareeView.addressbook()._objectNames = None
 
             if bind.MESSAGE in columnMap:
                 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.shareeName())
+                cacheKey = queryCacher.keyForObjectWithName(shareeView.viewerHome()._resourceID, self.addressbook().ownerHome().uid())
                 queryCacher.invalidateAfterCommit(self._txn, cacheKey)
 
-            shareeView._name = bindNameRows[0][0]
-
             # Must send notification to ensure cache invalidation occurs
-            yield self.notifyPropertyChanged()
+            yield self.addressbook().notifyPropertyChanged()
             yield shareeView.viewerHome().notifyChanged()
 
-        returnValue(shareeView._name)
 
-
     @inlineCallbacks
-    def shareWith(self, shareeHome, mode, status=None, message=None):
+    def removeShare(self, shareeView):
         """
-            call super and set self.isShared True
-        """
-
-        # Note: super always calls shareView._initSyncToken():
-        # even when shareView is previously shared via group sharing
-        bindName = yield super(AddressBook, self).shareWith(shareeHome, mode, status, message)
-
-        queryCacher = self._txn._queryCacher
-        if queryCacher:
-            cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.shareeName())
-            queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-
-        self.setShared(True)
-        returnValue(bindName)
-
-
-    @inlineCallbacks
-    def unshareWith(self, shareeHome):
-        """
         Remove the shared version of this (owned) L{CommonHomeChild} from the
         referenced L{CommonHome}.
 
@@ -1524,53 +1635,100 @@
         @param shareeHome: The home with which this L{CommonHomeChild} was
             previously shared.
 
-        @return: a L{Deferred} which will fire with the previous shareUID
+        @return: a L{Deferred} which will fire with the previously-used name.
         """
-        shareeAddressBook = yield shareeHome.addressbookWithName(self.shareeName())
-        if shareeAddressBook:
 
-            acceptedBindCount = 1 if shareeAddressBook.fullyShared() else 0
+        shareeHome = shareeView.addressbook().viewerHome()
+        addressbookAsShared = yield shareeHome.addressbookWithName(self.addressbook().ownerHome().uid())
+        if addressbookAsShared:
+
+            acceptedBindCount = 1 if addressbookAsShared.fullyShared() else 0
             groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                    self._txn, homeID=shareeHome._resourceID, addressbookID=shareeAddressBook._resourceID
+                    self._txn, homeID=shareeHome._resourceID, addressbookID=addressbookAsShared._resourceID
             )
             acceptedBindCount += len(groupBindRows)
             if acceptedBindCount == 1:
-                yield shareeAddressBook._deletedSyncToken(sharedRemoval=True)
-                shareeHome._children.pop(self.shareeName(), None)
-                shareeHome._children.pop(shareeAddressBook._resourceID, None)
+                yield addressbookAsShared._deletedSyncToken(sharedRemoval=True)
+                shareeHome._children.pop(self.ownerHome().uid(), None)
+                shareeHome._children.pop(addressbookAsShared._resourceID, None)
             else:
-                yield shareeAddressBook.notifyPropertyChanged()
+                yield addressbookAsShared.notifyPropertyChanged()
                 #update revision in all remaining bind table rows for this address book
                 for groupBindRow in groupBindRows:
-                    groupObject = yield shareeAddressBook.objectResourceWithID(groupBindRow[2])
+                    groupObject = yield addressbookAsShared.objectResourceWithID(groupBindRow[2])
                     yield groupObject._initBindRevision()
-                shareeAddressBook._objects = {}
-                shareeAddressBook._objectNames = None
+                addressbookAsShared._objects = {}
+                addressbookAsShared._objectNames = None
 
             # Must send notification to ensure cache invalidation occurs
             yield self.notifyPropertyChanged()
             yield shareeHome.notifyChanged()
 
         # delete bind table rows for this share
-        deletedBindNameRows = yield self._deleteBindForResourceIDAndHomeID.on(self._txn, resourceID=self._resourceID,
-             homeID=shareeHome._resourceID
+        yield self._deleteBindForResourceIDAndHomeID.on(self._txn,
+            resourceID=self._resourceID, homeID=shareeHome._resourceID
         )
-        if deletedBindNameRows:
-            deletedBindName = deletedBindNameRows[0][0]
-            queryCacher = self._txn._queryCacher
-            if queryCacher:
-                cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.shareeName())
-                queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-        else:
-            deletedBindName = None
 
-        self._initIsShared()
-        returnValue(deletedBindName)
 
+    @inlineCallbacks
+    def sharingInvites(self):
+        """
+        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.
+        """
+        if not self.owned() or self._kind != _ABO_KIND_GROUP:
+            returnValue([])
 
-class AddressBookObject(CommonObjectResource, AddressBookSharingMixIn):
+        # 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("revision"), }
+        ).on(
+            self._txn,
+            revision=self.addressbook()._bindRevision,
+            resourceID=self._resourceID,
+            homeID=self.viewerHome()._resourceID,
+        )
+        yield self.invalidateQueryCache()
+
+
+    def shareUID(self):
+        """
+        @see: L{ICalendar.shareUID}
+        """
+        return self._bindName
+
+
+
+class AddressBookObject(CommonObjectResource, AddressBookObjectSharingMixIn):
+
     implements(IAddressBookObject)
 
     _homeSchema = schema.ADDRESSBOOK_HOME
@@ -1724,17 +1882,16 @@
     @inlineCallbacks
     def readWriteAccess(self):
         assert not self.owned(), "Don't call items in owned address book"
-        yield None
 
-        #shared address book group is always read-only
+        # Shared address book group always read-only
         if self.isGroupForSharedAddressBook():
             returnValue(False)
 
-        # if fully shared and rw, must be RW since sharing group read-only has no affect
+        # 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:
             returnValue(True)
 
-        #otherwise, must be in a read-write group
+        # Otherwise, must be in a read-write group
         readWriteGroupIDs = yield self.addressbook().readWriteGroupIDs()
         readWriteObjectIDs = yield self.addressbook().expandGroupIDs(self._txn, readWriteGroupIDs)
         returnValue(self._resourceID in readWriteObjectIDs)
@@ -1772,7 +1929,39 @@
             Where=obj.RESOURCE_ID == Parameter("resourceID"),)
 
 
+    @classmethod
     @inlineCallbacks
+    def objectWithBindName(cls, home, name, accepted):
+        """
+        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.
+        """
+
+        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
     def initFromStore(self):
         """
         Initialise this object from the store. We read in and cache all the
@@ -1782,25 +1971,13 @@
 
         @return: L{self} if object exists in the DB, else C{None}
         """
-        rows = None
+        abo = None
         if self.owned() or self.addressbook().fullyShared():  # owned or fully shared
-            if self._name:
-                rows = yield self._allColumnsWithParentAndName.on(
-                    self._txn, name=self._name,
-                    parentID=self._parentCollection._resourceID
-                )
-            elif self._uid:
-                rows = yield self._allColumnsWithParentAndUID.on(
-                    self._txn, uid=self._uid,
-                    parentID=self._parentCollection._resourceID
-                )
-            elif self._resourceID:
-                rows = yield self._allColumnsWithParentAndID.on(
-                    self._txn, resourceID=self._resourceID,
-                    parentID=self._parentCollection._resourceID
-                )
+            abo = yield super(AddressBookObject, self).initFromStore()
 
-            if not rows and self.addressbook().fullyShared():  # perhaps add special group
+            # 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()]
@@ -1810,9 +1987,16 @@
                 elif self._resourceID:
                     if self.isGroupForSharedAddressBook():
                         rows = [self.addressbook()._groupForSharedAddressBookRow()]
+
+                if rows:
+                    self._initFromRow(tuple(rows[0]))
+                    yield self._loadPropertyStore()
+                    abo = self
+
         else:
             acceptedGroupIDs = yield self.addressbook().acceptedGroupIDs()
             allowedObjectIDs = yield self.addressbook().expandGroupIDs(self._txn, acceptedGroupIDs)
+            rows = None
             if self._name:
                 if allowedObjectIDs:
                     rows = (yield self._allColumnsWithResourceIDsAndName(allowedObjectIDs).on(
@@ -1831,10 +2015,12 @@
                     rows = (yield self._allColumnsWithResourceID.on(
                         self._txn, resourceID=self._resourceID,
                     ))
+            if rows:
+                self._initFromRow(tuple(rows[0]))
+                yield self._loadPropertyStore()
+                abo = self
 
-        if rows:
-            self._initFromRow(tuple(rows[0]))
-
+        if abo is not None:
             if self._kind == _ABO_KIND_GROUP:
 
                 groupBindRows = yield AddressBookObject._bindForResourceIDAndHomeID.on(
@@ -1849,9 +2035,11 @@
                     self._bindMessage = bindMessage
                     self._bindName = bindName
                     self._bindRevision = bindRevision
+                else:
+                    invites = yield self.sharingInvites()
+                    if len(invites):
+                        self._bindMessage = "shared"
 
-                yield self._initIsShared()
-
             yield self._loadPropertyStore()
 
             returnValue(self)
@@ -1973,7 +2161,7 @@
 
     def validAddressDataCheck(self, component, inserting): #@UnusedVariable
         """
-        Check that the calendar data is valid iCalendar.
+        Check that the calendar data is valid IAddressBook.
         @return:         tuple: (True/False if the calendar data is valid,
                                  log message string).
         """
@@ -2449,25 +2637,6 @@
         return MimeType.fromString("text/vcard; charset=utf-8")
 
 
-    def owned(self):
-        return self.addressbook().owned()
-
-
-    def ownerHome(self):
-        return self.addressbook().ownerHome()
-
-
-    def viewerHome(self):
-        return self.addressbook().viewerHome()
-
-
-    def shareUID(self):
-        """
-        @see: L{ICalendar.shareUID}
-        """
-        return self._bindName
-
-
     @classmethod
     def metadataColumns(cls):
         """
@@ -2496,6 +2665,13 @@
                            ).And(bind.BIND_STATUS == _BIND_STATUS_ACCEPTED))
 
 
+    def notifyPropertyChanged(self):
+        """
+        Send notifications when properties on this object change.
+        """
+        return self.addressbook().notifyPropertyChanged()
+
+
     @classproperty
     def _addressbookIDForResourceID(cls): #@NoSelf
         obj = cls._objectSchema
@@ -2512,307 +2688,6 @@
         returnValue(ownerAddressBookIDRows[0][0])
 
 
-    @inlineCallbacks
-    def sharingInvites(self):
-        """
-        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.
-        """
-        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().shareeName(),
-                bindMode,
-                bindStatus,
-                bindMessage,
-            )
-            result.append(invite)
-        returnValue(result)
-
-
-    @inlineCallbacks
-    def unshare(self):
-        """
-        Unshares a group, regardless of which "direction" it was shared.
-        """
-        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):
-        """
-        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.
-        """
-        shareeAddressBook = yield shareeHome.addressbookWithName(self.addressbook().shareeName())
-
-        if shareeAddressBook and shareeAddressBook._bindStatus == _BIND_STATUS_ACCEPTED:
-
-            acceptedBindCount = 1 if shareeAddressBook.fullyShared() else 0
-            groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                self._txn, homeID=shareeHome._resourceID, addressbookID=shareeAddressBook._resourceID
-            )
-            acceptedBindCount += len(groupBindRows)
-
-            if acceptedBindCount == 1:
-                yield shareeAddressBook._deletedSyncToken(sharedRemoval=True)
-                shareeHome._children.pop(self.addressbook().shareeName(), None)
-                shareeHome._children.pop(self.addressbook()._resourceID, None)
-            else:
-                shareeAddressBook.notifyPropertyChanged()
-                #update revision in all remaining bind table rows for this address book
-                for groupBindRow in groupBindRows:
-                    groupObject = yield shareeAddressBook.objectResourceWithID(groupBindRow[2])
-                    yield groupObject._initBindRevision()
-                if shareeAddressBook.fullyShared():
-                    yield shareeAddressBook._initBindRevision()
-                shareeAddressBook._objects = {}
-                shareeAddressBook._objectNames = None
-
-            # Must send notification to ensure cache invalidation occurs
-            yield self.addressbook().notifyPropertyChanged()
-            yield shareeHome.notifyChanged()
-
-        # delete bind 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().shareeName())
-                queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-        else:
-            deletedBindName = None
-
-        yield self._initIsShared()
-        returnValue(deletedBindName)
-
-
-    @inlineCallbacks
-    def shareWith(self, shareeHome, mode, status=None, message=None):
-        """
-        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 message: The proposed message to go along with the share, which
-            will be used as the default display name.
-        @type mode: L{str}
-
-        @return: the name of the shared group in the sharee home.
-        @rtype: L{str}
-        """
-
-        if status is None:
-            status = _BIND_STATUS_ACCEPTED
-
-        @inlineCallbacks
-        def doInsert(subt):
-            newName = str(uuid4())
-            yield self._bindInsertQuery.on(
-                subt, homeID=shareeHome._resourceID,
-                resourceID=self._resourceID, name=newName,
-                mode=mode, bindStatus=status, message=message
-            )
-            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,
-                message=message
-            )
-        else:
-            if status == _BIND_STATUS_ACCEPTED:
-                shareeView = yield shareeHome.objectWithShareUID(bindName)
-                if not shareeView.addressbook().fullyShared():
-                    groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                            self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=shareeView.addressbook()._resourceID
-                    )
-                    if len(groupBindRows) == 1:
-                        yield shareeView.addressbook()._initSyncToken()
-                yield shareeView._initBindRevision()
-
-        queryCacher = self._txn._queryCacher
-        if queryCacher:
-            cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, self.addressbook().shareeName())
-            queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-
-        # Must send notification to ensure cache invalidation occurs
-        yield self.addressbook().notifyPropertyChanged()
-        yield shareeHome.notifyChanged()
-
-        self.setShared(True)
-        returnValue(bindName)
-
-
-    @property
-    def _syncTokenRevision(self):
-        return self.addressbook()._syncTokenRevision
-
-
-    def syncToken(self):
-        return self.addressbook().syncToken() # init self.addressbook()._syncTokenRevision
-
-
-    @inlineCallbacks
-    def updateShare(self, shareeView, mode=None, status=None, message=None):
-        """
-        Update share mode, status, and message for a address book group with
-        this (owned) L{AddressBookObject}.
-
-        @param shareeView: The sharee addressbook group that shares this.
-        @type shareeView: L{AddressBookObject}
-
-        @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 message: The proposed message to go along with the share, which
-            will be used as the default display name, or None to not update
-        @type message: L{str}
-
-        @return: the name of the shared item in the sharee's home.
-        @rtype: a L{Deferred} which fires with a L{str}
-        """
-        # 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 = {}
-        if mode != None and mode != shareeView._bindMode:
-            columnMap[bind.BIND_MODE] = mode
-        if status != None and status != shareeView._bindStatus:
-            columnMap[bind.BIND_STATUS] = status
-        if message != None and message != shareeView._bindMessage:
-            columnMap[bind.MESSAGE] = message
-
-        if columnMap:
-
-            # count accepted
-            if bind.BIND_STATUS in columnMap:
-                previouslyAcceptedBindCount = 1 if shareeView.addressbook().fullyShared() else 0
-                groupBindRows = yield AddressBookObject._acceptedBindForHomeIDAndAddressBookID.on(
-                    self._txn, homeID=shareeView.viewerHome()._resourceID, addressbookID=self.addressbook()._resourceID
-                )
-                previouslyAcceptedBindCount += len(groupBindRows)
-
-            bindNameRows = yield self._updateBindColumnsQuery(columnMap).on(
-                self._txn,
-                resourceID=self._resourceID,
-                homeID=shareeView.viewerHome()._resourceID
-            )
-
-            # update affected attributes
-            if bind.BIND_MODE in columnMap:
-                shareeView._bindMode = columnMap[bind.BIND_MODE]
-
-            if bind.BIND_STATUS in columnMap:
-                shareeView._bindStatus = columnMap[bind.BIND_STATUS]
-                if shareeView._bindStatus == _BIND_STATUS_ACCEPTED:
-                    if 0 == previouslyAcceptedBindCount:
-                        yield shareeView.addressbook()._initSyncToken()
-                        shareeView.viewerHome()._children[self.addressbook().shareeName()] = shareeView.addressbook()
-                        shareeView.viewerHome()._children[shareeView._resourceID] = shareeView.addressbook()
-                    yield shareeView._initBindRevision()
-                elif shareeView._bindStatus == _BIND_STATUS_DECLINED:
-                    if 1 == previouslyAcceptedBindCount:
-                        yield shareeView.addressbook()._deletedSyncToken(sharedRemoval=True)
-                        shareeView.viewerHome()._children.pop(self.addressbook().shareeName(), None)
-                        shareeView.viewerHome()._children.pop(shareeView._resourceID, None)
-                    else:
-                        # update revision in all remaining bind table rows for this address book
-                        yield shareeView.addressbook().notifyPropertyChanged()
-                        for groupBindRow in groupBindRows:
-                            if groupBindRow[2] != shareeView._resourceID:
-                                groupObject = yield shareeView.addressbook().objectResourceWithID(groupBindRow[2])
-                                yield groupObject._initBindRevision()
-                        if shareeView.addressbook().fullyShared():
-                            yield shareeView.addressbook()._initBindRevision()
-                        shareeView.addressbook()._objects = {}
-                        shareeView.addressbook()._objectNames = None
-
-            if bind.MESSAGE in columnMap:
-                shareeView._bindMessage = columnMap[bind.MESSAGE]
-
-            # safer to just invalidate in all cases rather than calculate when to invalidate
-            queryCacher = self._txn._queryCacher
-            if queryCacher:
-                cacheKey = queryCacher.keyForObjectWithName(shareeView.viewerHome()._resourceID, self.addressbook().shareeName())
-                queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-
-            shareeView._name = bindNameRows[0][0]
-
-            # Must send notification to ensure cache invalidation occurs
-            yield self.addressbook().notifyPropertyChanged()
-            yield shareeView.viewerHome().notifyChanged()
-
-        returnValue(shareeView._name)
-
-
     @classproperty
     def _acceptedBindForHomeIDAndAddressBookID(cls): #@NoSelf
         bind = cls._bindSchema

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -22,7 +22,7 @@
 from twext.enterprise.dal.syntax import Select, Parameter
 
 from twisted.internet import reactor
-from twisted.internet.defer import inlineCallbacks, returnValue, DeferredList
+from twisted.internet.defer import inlineCallbacks, returnValue
 from twisted.internet.task import deferLater
 
 from twisted.trial import unittest
@@ -40,9 +40,7 @@
 
 from txdav.common.icommondatastore import NoSuchObjectResourceError
 from txdav.common.datastore.sql import EADDRESSBOOKTYPE, CommonObjectResource
-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
+from txdav.common.datastore.sql_tables import  _ABO_KIND_PERSON, _ABO_KIND_GROUP, schema
 from txdav.common.datastore.test.util import buildStore
 from txdav.carddav.datastore.sql import AddressBook
 
@@ -756,13 +754,13 @@
 
         @inlineCallbacks
         def _defer1():
-            yield ab1.shareWith(shareeHome=sharerHome1, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki AddressBook")
+            yield ab1.directShareWithUser("uid2")
             yield txn1.commit()
         d1 = _defer1()
 
         @inlineCallbacks
         def _defer2():
-            yield ab2.shareWith(shareeHome=sharerHome2, mode=_BIND_MODE_DIRECT, status=_BIND_STATUS_ACCEPTED, message="Shared Wiki AddressBook")
+            yield ab2.directShareWithUser("uid1")
             yield txn2.commit()
         d2 = _defer2()
 
@@ -880,268 +878,3 @@
         obj = (yield self.addressbookObjectUnderTest())
         addressbookObject = (yield home.objectResourceWithID(obj._resourceID))
         self.assertNotEquals(addressbookObject, None)
-
-
-    @inlineCallbacks
-    def test_shareWithRevision(self):
-        """
-        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
-        """
-        ab = yield self.addressbookUnderTest()
-        self.assertEqual(ab._bindRevision, 0)
-        other = yield self.homeUnderTest(name="home2")
-        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="home2")
-        otherAB = yield otherHome.objectWithShareUID(newABShareUID)
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_shareGroupWithRevision(self):
-        """
-        Verify that bindRevision on addressbooks and shared groups has the correct value.
-        """
-        ab = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(ab._bindRevision, 0)
-        group = yield ab.objectResourceWithName("4.vcf")
-        other = yield self.homeUnderTest(name="home2")
-        newGroupShareUID = yield group.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name="home2")
-        otherGroup = yield otherHome.objectWithShareUID(newGroupShareUID)
-        self.assertNotEqual(otherGroup._bindRevision, 0)
-        otherAB = otherGroup.addressbook()
-        self.assertEqual(otherAB._bindRevision, None)
-
-
-    @inlineCallbacks
-    def test_updateShareRevision(self):
-        """
-        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
-        """
-        ab = yield self.addressbookUnderTest()
-        self.assertEqual(ab._bindRevision, 0)
-        other = yield self.homeUnderTest(name="home2")
-        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="home2")
-        otherAB = yield otherHome.invitedObjectWithShareUID(newABShareUID)
-        self.assertEqual(otherAB._bindRevision, 0)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest()
-        otherHome = yield self.homeUnderTest(name="home2")
-        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="home2")
-        otherAB = yield otherHome.objectWithShareUID(newABShareUID)
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-
-    @inlineCallbacks
-    def test_updateSharedGroupRevision(self):
-        """
-        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
-        """
-        ab = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(ab._bindRevision, 0)
-        group = yield ab.objectResourceWithName("4.vcf")
-        other = yield self.homeUnderTest(name="home2")
-        newGroupShareUID = yield group.shareWith(other, _BIND_MODE_WRITE, status=_BIND_STATUS_INVITED)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name="home2")
-        otherGroup = yield otherHome.invitedObjectWithShareUID(newGroupShareUID)
-        self.assertEqual(otherGroup._bindRevision, 0)
-        otherAB = otherGroup.addressbook()
-        self.assertEqual(otherAB._bindRevision, None)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home="home3")
-        normalGroup = yield normalAB.objectResourceWithName("4.vcf")
-        otherHome = yield self.homeUnderTest(name="home2")
-        otherGroup = yield otherHome.invitedObjectWithShareUID(newGroupShareUID)
-        yield normalGroup.updateShare(otherGroup, status=_BIND_STATUS_ACCEPTED)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name="home2")
-        otherGroup = yield otherHome.objectWithShareUID(newGroupShareUID)
-        self.assertNotEqual(otherGroup._bindRevision, 0)
-        otherAB = otherGroup.addressbook()
-        self.assertEqual(otherAB._bindRevision, None)
-
-
-    @inlineCallbacks
-    def test_sharedRevisions(self):
-        """
-        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
-        """
-        ab = yield self.addressbookUnderTest()
-        self.assertEqual(ab._bindRevision, 0)
-        other = yield self.homeUnderTest(name="home2")
-        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="home2")
-        otherAB = yield otherHome.objectWithShareUID(newABShareUID)
-        self.assertNotEqual(otherAB._bindRevision, 0)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(0)
-        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 ("1", "infinity",):
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(0, 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):
-        """
-        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
-        """
-        ab = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(ab._bindRevision, 0)
-        group = yield ab.objectResourceWithName("4.vcf")
-        other = yield self.homeUnderTest(name="home2")
-        newGroupShareUID = yield group.shareWith(other, _BIND_MODE_WRITE)
-        yield self.commit()
-
-        normalAB = yield self.addressbookUnderTest(home="home3")
-        self.assertEqual(normalAB._bindRevision, 0)
-        otherHome = yield self.homeUnderTest(name="home2")
-        otherGroup = yield otherHome.objectWithShareUID(newGroupShareUID)
-        self.assertNotEqual(otherGroup._bindRevision, 0)
-        otherAB = otherGroup.addressbook()
-        self.assertEqual(otherAB._bindRevision, None)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(0)
-        self.assertEqual(set(changed), set(['1.vcf', '4.vcf', '2.vcf', ]))
-        self.assertEqual(len(deleted), 0)
-
-        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherGroup._bindRevision)
-        self.assertEqual(len(changed), 0)
-        self.assertEqual(len(deleted), 0)
-
-        for depth, result in (
-            ("1", ['addressbook/',
-                   'home3/', ]
-            ),
-            ("infinity", ['addressbook/',
-                          'addressbook/1.vcf',
-                          'addressbook/2.vcf',
-                          'addressbook/3.vcf',
-                          'addressbook/4.vcf',
-                          'addressbook/5.vcf',
-                          'home3/',
-                          'home3/1.vcf',
-                          'home3/2.vcf',
-                          'home3/4.vcf', ]
-             )):
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(0, depth)
-            self.assertEqual(set(changed), set(result))
-            self.assertEqual(len(deleted), 0)
-
-            changed, deleted = yield otherHome.resourceNamesSinceRevision(otherGroup._bindRevision, depth)
-            self.assertEqual(len(changed), 0)
-            self.assertEqual(len(deleted), 0)
-
-
-    @inlineCallbacks
-    def test_addressbookRevisionChangeConcurrency(self):
-        """
-        Test that two concurrent attempts to add resources in two separate
-        calendar homes does not deadlock on the revision table update.
-        """
-
-        # Make sure homes are provisioned
-        txn = self.transactionUnderTest()
-        home_uid1 = yield txn.homeWithUID(EADDRESSBOOKTYPE, "user01", create=True)
-        home_uid2 = yield txn.homeWithUID(EADDRESSBOOKTYPE, "user02", 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, "addressbook", "user01")
-        addressbook_uid2_in_txn2 = yield self.addressbookUnderTest(txn2, "addressbook", "user02")
-
-        data = """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
-
-"""
-
-        component = VComponent.fromString(data % {"ctr": 1})
-        yield addressbook_uid1_in_txn1.createAddressBookObjectWithName("data1.ics", component)
-
-        component = VComponent.fromString(data % {"ctr": 2})
-        yield addressbook_uid2_in_txn2.createAddressBookObjectWithName("data2.ics", 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, "addressbook", "user01")
-            component = VComponent.fromString(data % {"ctr": 3})
-            yield addressbook_uid1_in_txn2.createAddressBookObjectWithName("data3.ics", component)
-            yield txn2.commit()
-        d1 = _defer_uid3()
-
-        @inlineCallbacks
-        def _defer_uid4():
-            addressbook_uid2_in_txn1 = yield self.addressbookUnderTest(txn1, "addressbook", "user02")
-            component = VComponent.fromString(data % {"ctr": 4})
-            yield addressbook_uid2_in_txn1.createAddressBookObjectWithName("data4.ics", 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="data1.ics", addressbook_name="addressbook", home="user01")
-        vcarddata2 = yield self.addressbookObjectUnderTest(name="data2.ics", addressbook_name="addressbook", home="user02")
-        vcarddata3 = yield self.addressbookObjectUnderTest(name="data3.ics", addressbook_name="addressbook", home="user01")
-        vcarddata4 = yield self.addressbookObjectUnderTest(name="data4.ics", addressbook_name="addressbook", home="user02")
-        self.assertNotEqual(vcarddata1, None)
-        self.assertNotEqual(vcarddata2, None)
-        self.assertNotEqual(vcarddata3, None)
-        self.assertNotEqual(vcarddata4, None)

Copied: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql_sharing.py (from rev 12017, CalendarServer/trunk/txdav/carddav/datastore/test/test_sql_sharing.py)
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql_sharing.py	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/carddav/datastore/test/test_sql_sharing.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,1256 @@
+##
+# Copyright (c) 2005-2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+
+from twisted.internet.defer import inlineCallbacks, returnValue, DeferredList
+from twisted.trial.unittest import TestCase
+
+from twistedcaldav.vcard import Component as VCard, Component
+from twext.python.clsprop import classproperty
+from txdav.common.datastore.test.util import CommonCommonTests, buildStore
+from txdav.common.datastore.sql_tables import _BIND_MODE_READ, \
+    _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_ACCEPTED, \
+    _BIND_MODE_WRITE
+
+
+
+class BaseSharingTests(CommonCommonTests, TestCase):
+    """
+    Test store-based address book sharing.
+    """
+
+    @inlineCallbacks
+    def setUp(self):
+        yield super(BaseSharingTests, self).setUp()
+        self._sqlStore = yield buildStore(self, self.notifierFactory)
+        yield self.populate()
+
+
+    @inlineCallbacks
+    def populate(self):
+        populateTxn = self.storeUnderTest().newTransaction()
+        for homeUID in self.requirements:
+            addressbooks = self.requirements[homeUID]
+            if addressbooks is not None:
+                home = yield populateTxn.addressbookHomeWithUID(homeUID, True)
+                addressbook = home.addressbook()
+
+                addressbookObjNames = addressbooks[addressbook.name()]
+                if addressbookObjNames is not None:
+                    for objectName in addressbookObjNames:
+                        objData = addressbookObjNames[objectName]
+                        yield addressbook.createAddressBookObjectWithName(
+                            objectName, VCard.fromString(objData)
+                        )
+
+        yield populateTxn.commit()
+        self.notifierFactory.reset()
+
+    # Data to populate
+    card1 = """BEGIN:VCARD
+VERSION:3.0
+UID:card1
+FN:Card 1
+N:card1;;;;
+END:VCARD
+"""
+
+    card2 = """BEGIN:VCARD
+VERSION:3.0
+UID:card2
+FN:Card 2
+N:card2;;;;
+END:VCARD
+"""
+
+    card3 = """BEGIN:VCARD
+VERSION:3.0
+UID:card3
+FN:Card 3
+N:card3;;;;
+END:VCARD
+"""
+
+    group1 = """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
+"""
+
+    group2 = """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
+"""
+
+
+    @classproperty(cache=False)
+    def requirements(cls): #@NoSelf
+        return {
+        "user01": {
+            "addressbook": {
+                "card1.vcf": cls.card1,
+                "card2.vcf": cls.card2,
+                "card3.vcf": cls.card3,
+                "group1.vcf": cls.group1,
+                "group2.vcf": cls.group2,
+            },
+        },
+        "user02": {
+            "addressbook": {
+            },
+        },
+        "user03": {
+            "addressbook": {
+            },
+        },
+    }
+
+    fully_shared_children = ["addressbook.vcf", "group1.vcf", "group2.vcf", "card1.vcf", "card2.vcf", "card3.vcf", ]
+    all_children = ["group1.vcf", "group2.vcf", "card1.vcf", "card2.vcf", "card3.vcf", ]
+    group1_children = ["group1.vcf", "card1.vcf", "card2.vcf", ]
+    group2_children = ["group2.vcf", "card1.vcf", "card3.vcf", ]
+
+
+    def storeUnderTest(self):
+        """
+        Create and return a L{CalendarStore} for testing.
+        """
+        return self._sqlStore
+
+
+    @inlineCallbacks
+    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):
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield addressbook.inviteUserToShare("user02", mode, "summary")
+        inviteUID = shareeView.shareUID()
+        yield self.commit()
+
+        returnValue(inviteUID)
+
+
+    @inlineCallbacks
+    def _acceptShare(self, inviteUID):
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        shareeView = yield shareeHome.acceptShare(inviteUID)
+        sharedName = shareeView.name()
+        yield self.commit()
+
+        returnValue(sharedName)
+
+
+    @inlineCallbacks
+    def _createGroupShare(self, groupname="group1.vcf", mode=_BIND_MODE_READ):
+        inviteUID = yield self._inviteGroupShare(groupname, mode)
+        sharedName = yield self._acceptGroupShare(inviteUID)
+        returnValue(sharedName)
+
+
+    @inlineCallbacks
+    def _inviteGroupShare(self, groupname="group1.vcf", mode=_BIND_MODE_READ):
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name=groupname)
+        shareeView = yield group.inviteUserToShare("user02", mode, "summary")
+        inviteUID = shareeView.shareUID()
+        yield self.commit()
+
+        returnValue(inviteUID)
+
+
+    @inlineCallbacks
+    def _acceptGroupShare(self, inviteUID):
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        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="Missing parent:{}".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="Missing child:{}".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="Wrong mode: {}".format(child))
+
+
+
+class AddressBookSharing(BaseSharingTests):
+    """
+    Test store-based address book sharing.
+    """
+    @inlineCallbacks
+    def test_no_shares(self):
+        """
+        Test that initially there are no shares.
+        """
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(addressbook.isShared())
+
+
+    @inlineCallbacks
+    def test_invite_sharee(self):
+        """
+        Test invite/uninvite creates/removes shares and notifications.
+        """
+
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(addressbook.isShared())
+
+        shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertEqual(invites[0].uid, shareeView.shareUID())
+        self.assertEqual(invites[0].ownerUID, "user01")
+        self.assertEqual(invites[0].shareeUID, "user02")
+        self.assertEqual(invites[0].mode, _BIND_MODE_READ)
+        self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
+        self.assertEqual(invites[0].summary, "summary")
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        self.assertTrue(addressbook.isShared())
+
+        yield self.commit()
+
+        # Uninvite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertTrue(addressbook.isShared())
+
+        yield addressbook.uninviteUserFromShare("user02")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        yield self._check_notifications("user02", [])
+
+        self.assertTrue(addressbook.isShared())
+
+        yield self.commit()
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertFalse(addressbook.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_share(self):
+        """
+        Test that invite+accept creates shares and notifications.
+        """
+
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(addressbook.isShared())
+
+        shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        self.assertTrue(addressbook.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertTrue(addressbook.isShared())
+
+        yield self.commit()
+
+        # Re-accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertTrue(addressbook.isShared())
+
+
+    @inlineCallbacks
+    def test_decline_share(self):
+        """
+        Test that invite+decline does not create shares but does create notifications.
+        """
+
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(addressbook.isShared())
+
+        shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        self.assertTrue(addressbook.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertTrue(addressbook.isShared())
+
+        yield self.commit()
+
+        # Redecline
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertTrue(addressbook.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_decline_share(self):
+        """
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the home.
+        """
+
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+
+    @inlineCallbacks
+    def test_accept_remove_share(self):
+        """
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the shared collection (removal).
+        """
+
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield addressbook.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedName = shareeView.name()
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        yield self.commit()
+
+        # Delete
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        yield shared.deleteShare()
+
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+
+    @inlineCallbacks
+    def test_direct_sharee(self):
+        """
+        Test invite/uninvite creates/removes shares and notifications.
+        """
+
+        # Invite
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield addressbook.directShareWithUser("user02")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertEqual(invites[0].uid, shareeView.shareUID())
+        self.assertEqual(invites[0].ownerUID, "user01")
+        self.assertEqual(invites[0].shareeUID, "user02")
+        self.assertEqual(invites[0].mode, _BIND_MODE_DIRECT)
+        self.assertEqual(invites[0].status, _BIND_STATUS_ACCEPTED)
+
+        sharedName = shareeView.name()
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        self.assertTrue(shared is not None)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_notifications("user02", [])
+
+        yield self.commit()
+
+        # Remove
+        shared = yield self.addressbookUnderTest(home="user02", name=sharedName)
+        yield shared.deleteShare()
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        yield self._check_notifications("user02", [])
+
+
+    @inlineCallbacks
+    def test_sharedNotifierID(self):
+        shared_name = yield self._createShare()
+
+        home = yield self.addressbookHomeUnderTest(name="user01")
+        self.assertEquals(home.notifierID(), ("CardDAV", "user01",))
+        addressbook = yield home.addressbookWithName("addressbook")
+        self.assertEquals(addressbook.notifierID(), ("CardDAV", "user01/addressbook",))
+        yield self.commit()
+
+        home = yield self.addressbookHomeUnderTest(name="user02")
+        self.assertEquals(home.notifierID(), ("CardDAV", "user02",))
+        addressbook = yield home.addressbookWithName(shared_name)
+        self.assertEquals(addressbook.notifierID(), ("CardDAV", "user01/addressbook",))
+        yield self.commit()
+
+
+
+class GroupSharing(BaseSharingTests):
+    """
+    Test store-based group book sharing.
+    """
+
+    @inlineCallbacks
+    def test_no_shares(self):
+        """
+        Test that initially there are no shares.
+        """
+
+        addressbook = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        invites = yield addressbook.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+
+    @inlineCallbacks
+    def test_invite_sharee(self):
+        """
+        Test invite/uninvite creates/removes shares and notifications.
+        """
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertEqual(invites[0].uid, shareeView.shareUID())
+        self.assertEqual(invites[0].ownerUID, "user01")
+        self.assertEqual(invites[0].shareeUID, "user02")
+        self.assertEqual(invites[0].mode, _BIND_MODE_READ)
+        self.assertEqual(invites[0].status, _BIND_STATUS_INVITED)
+        self.assertEqual(invites[0].summary, "summary")
+        inviteUID = shareeView.shareUID()
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Uninvite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        self.assertTrue(group.isShared())
+
+        yield group.uninviteUserFromShare("user02")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertTrue(group.isShared())
+
+        yield self._check_notifications("user02", [])
+
+        yield self.commit()
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertFalse(group.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_share(self):
+        """
+        Test that invite+accept creates shares and notifications.
+        """
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook("user02", "user01", self.group1_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Re-accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook("user02", "user01", self.group1_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+
+    @inlineCallbacks
+    def test_decline_share(self):
+        """
+        Test that invite+decline does not create shares but does create notifications.
+        """
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Re-decline
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_decline_share(self):
+        """
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the home.
+        """
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+        self.assertFalse(group.isShared())
+
+        shareeView = yield group.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook("user02", "user01", self.group1_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+        yield self.commit()
+
+        # Decline
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID)
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        self.assertTrue(group.isShared())
+
+
+    @inlineCallbacks
+    def test_accept_remove_share(self):
+        """
+        Test that invite+accept/decline creates/removes shares and notifications.
+        Decline via the shared collection (removal).
+        """
+
+        # Invite
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        shareeView = yield group.inviteUserToShare("user02", _BIND_MODE_READ, "summary")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 1)
+        inviteUID = shareeView.shareUID()
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user02", [inviteUID, ])
+
+        yield self.commit()
+
+        # Accept
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.acceptShare(inviteUID)
+
+        yield self._check_addressbook("user02", "user01", self.group1_children)
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+        yield self.commit()
+
+        # Delete
+        group = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="group1.vcf")
+        yield group.deleteShare()
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+        yield self._check_notifications("user01", [inviteUID + "-reply", ])
+
+
+    @inlineCallbacks
+    def test_accept_two_groups(self):
+        """
+        Test that accept of two groups works.
+        """
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname="group1.vcf")
+        inviteUID2 = yield self._createGroupShare(groupname="group2.vcf")
+
+        yield self._check_addressbook("user02", "user01", self.all_children)
+        yield self._check_notifications("user01", [inviteUID1 + "-reply", inviteUID2 + "-reply", ])
+
+
+    @inlineCallbacks
+    def test_accept_uninvite_two_groups(self):
+        """
+        Test that accept of two groups works, then uninvite each one.
+        """
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname="group1.vcf")
+        inviteUID2 = yield self._createGroupShare(groupname="group2.vcf")
+
+        yield self._check_addressbook("user02", "user01", self.all_children)
+        yield self._check_notifications("user01", [inviteUID1 + "-reply", inviteUID2 + "-reply", ])
+
+        yield self.commit()
+
+        # Uninvite one
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        yield group.uninviteUserFromShare("user02")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        yield self._check_addressbook("user02", "user01", self.group2_children)
+
+        shared = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="group1.vcf")
+        self.assertTrue(shared is None)
+        shared = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="card2.vcf")
+        self.assertTrue(shared is None)
+
+        yield self.commit()
+
+        # Uninvite other
+        group = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="group2.vcf")
+        yield group.uninviteUserFromShare("user02")
+        invites = yield group.sharingInvites()
+        self.assertEqual(len(invites), 0)
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+
+    @inlineCallbacks
+    def test_accept_decline_two_groups(self):
+        """
+        Test that accept of two groups works, then decline each one.
+        """
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname="group1.vcf")
+        inviteUID2 = yield self._createGroupShare(groupname="group2.vcf")
+
+        yield self._check_addressbook("user02", "user01", self.all_children)
+        yield self._check_notifications("user01", [inviteUID1 + "-reply", inviteUID2 + "-reply", ])
+
+        yield self.commit()
+
+        # Decline one
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID1)
+
+        yield self._check_addressbook("user02", "user01", self.group2_children)
+
+        shared = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="group1.vcf")
+        self.assertTrue(shared is None)
+        shared = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="card2.vcf")
+        self.assertTrue(shared is None)
+
+        yield self.commit()
+
+        # Decline other
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID2)
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+
+    @inlineCallbacks
+    def test_accept_two_groups_different_access(self):
+        """
+        Test that accept of two groups works, then uninvite each one.
+        """
+
+        # Two shares
+        inviteUID1 = yield self._createGroupShare(groupname="group1.vcf")
+        inviteUID2 = yield self._createGroupShare(groupname="group2.vcf", mode=_BIND_MODE_WRITE)
+
+        yield self._check_addressbook("user02", "user01", self.all_children)
+        yield self._check_notifications("user01", [inviteUID1 + "-reply", inviteUID2 + "-reply", ])
+
+        # Read only for all, write for group2's items
+        yield self._check_read_only("user02", "user01", ["group1.vcf", "card2.vcf", ])
+        yield self._check_read_write("user02", "user01", ["group2.vcf", "card1.vcf", "card3.vcf", ])
+
+        yield self.commit()
+
+        # Decline one
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID2)
+
+        yield self._check_addressbook("user02", "user01", self.group1_children)
+
+        yield self._check_read_only("user02", "user01", ["group1.vcf", "card1.vcf", "card2.vcf", ])
+
+        shared = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="group2.vcf")
+        self.assertTrue(shared is None)
+        shared = yield self.addressbookObjectUnderTest(home="user02", addressbook_name="user01", name="card3.vcf")
+        self.assertTrue(shared is None)
+
+        yield self.commit()
+
+        # Decline other
+        shareeHome = yield self.addressbookHomeUnderTest(name="user02")
+        yield shareeHome.declineShare(inviteUID1)
+
+        sharedParent = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertTrue(sharedParent is None)
+
+
+
+class MixedSharing(BaseSharingTests):
+    """
+    Test store-based combined address book and group book sharing.
+    """
+
+    @inlineCallbacks
+    def test_addressbook_ro_then_groups(self):
+
+        # Share address book read-only
+        shareeName = yield self._createShare()
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", self.all_children)
+        yield self._check_read_write("user02", "user01", [])
+        yield self._check_notifications("user02", [shareeName, ])
+
+        # Add group1 read-write
+        inviteUID1 = yield self._createGroupShare(groupname="group1.vcf", mode=_BIND_MODE_WRITE)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", ["group2.vcf", "card3.vcf", ])
+        yield self._check_read_write("user02", "user01", ["group1.vcf", "card1.vcf", "card2.vcf", ])
+        yield self._check_notifications("user02", [shareeName, inviteUID1, ])
+
+        # Add group2 read-write
+        inviteUID2 = yield self._createGroupShare(groupname="group2.vcf", mode=_BIND_MODE_WRITE)
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", [])
+        yield self._check_read_write("user02", "user01", self.all_children)
+        yield self._check_notifications("user02", [shareeName, inviteUID1, inviteUID2])
+
+        # Uninvite group1
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        yield group.uninviteUserFromShare("user02")
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", ["group1.vcf", "card2.vcf", ])
+        yield self._check_read_write("user02", "user01", ["group2.vcf", "card1.vcf", "card3.vcf", ])
+
+        # Uninvite group2
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group2.vcf")
+        yield group.uninviteUserFromShare("user02")
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", self.all_children)
+        yield self._check_read_write("user02", "user01", [])
+
+
+    @inlineCallbacks
+    def test_addressbook_ro_then_group_no_accept(self):
+
+        # Share address book read-only
+        shareeName = yield self._createShare()
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", self.all_children)
+        yield self._check_read_write("user02", "user01", [])
+        yield self._check_notifications("user02", [shareeName, ])
+
+        # Add group1 read-write - but do not accept
+        group = yield self.addressbookObjectUnderTest(home="user01", addressbook_name="addressbook", name="group1.vcf")
+        invited = yield group.inviteUserToShare("user02", _BIND_MODE_WRITE, "summary")
+        yield self._check_notifications("user02", [shareeName, invited.shareUID(), ])
+
+        yield self._check_addressbook("user02", "user01", self.fully_shared_children)
+        yield self._check_read_only("user02", "user01", self.all_children)
+        yield self._check_read_write("user02", "user01", [])
+
+
+
+class SharingRevisions(BaseSharingTests):
+    """
+    Test store-based sharing and interaction with revision table.
+    """
+
+    @inlineCallbacks
+    def test_shareWithRevision(self):
+        """
+        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
+        """
+        yield self._createShare()
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_shareGroupWithRevision(self):
+        """
+        Verify that bindRevision on addressbooks and shared groups has the correct value.
+        """
+
+        yield self._createGroupShare(groupname="group1.vcf")
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_updateShareRevision(self):
+        """
+        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
+        """
+        newABShareUID = yield self._inviteShare()
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherHome = yield self.addressbookHomeUnderTest(name="user02")
+        otherAB = yield otherHome.anyObjectWithShareUID("user01")
+        self.assertEqual(otherAB._bindRevision, 0)
+        yield self.commit()
+
+        yield self._acceptShare(newABShareUID)
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+    @inlineCallbacks
+    def test_updateSharedGroupRevision(self):
+        """
+        Verify that bindRevision on addressbooks and shared addressbooks has the correct value.
+        """
+        newGroupShareUID = yield self._inviteGroupShare(groupname="group1.vcf")
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherHome = yield self.addressbookHomeUnderTest(name="user02")
+        otherAB = yield otherHome.anyObjectWithShareUID("user01")
+        self.assertEqual(otherAB._bindRevision, 0)
+        yield self.commit()
+
+        yield self._acceptGroupShare(newGroupShareUID)
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+
+#    @inlineCallbacks
+    def test_sharedRevisions(self):
+        """
+        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
+        """
+
+        yield self._createShare()
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(0)
+        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="user02")
+        for depth in ("1", "infinity",):
+            changed, deleted = yield otherHome.resourceNamesSinceRevision(0, 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):
+        """
+        Verify that resourceNamesSinceRevision returns all resources after initial bind and sync.
+        """
+
+        yield self._createGroupShare("group1.vcf")
+
+        normalAB = yield self.addressbookUnderTest(home="user01", name="addressbook")
+        self.assertEqual(normalAB._bindRevision, 0)
+        otherAB = yield self.addressbookUnderTest(home="user02", name="user01")
+        self.assertNotEqual(otherAB._bindRevision, 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(0)
+        self.assertEqual(set(changed), set(['card1.vcf', 'card2.vcf', 'group1.vcf']))
+        self.assertEqual(len(deleted), 0)
+
+        changed, deleted = yield otherAB.resourceNamesSinceRevision(otherAB._bindRevision)
+        self.assertEqual(len(changed), 0)
+        self.assertEqual(len(deleted), 0)
+
+        for depth, result in (
+            ("1", ['addressbook/',
+                   'user01/', ]
+            ),
+            ("infinity", ['addressbook/',
+                             'user01/',
+                             'user01/card1.vcf',
+                             'user01/card2.vcf',
+                             'user01/group1.vcf']
+             )):
+            changed, deleted = yield otherAB.viewerHome().resourceNamesSinceRevision(0, depth)
+            self.assertEqual(set(changed), set(result))
+            self.assertEqual(len(deleted), 0)
+
+            changed, deleted = yield otherAB.viewerHome().resourceNamesSinceRevision(otherAB._bindRevision, depth)
+            self.assertEqual(len(changed), 0)
+            self.assertEqual(len(deleted), 0)
+
+
+    @inlineCallbacks
+    def test_addressbookRevisionChangeConcurrency(self):
+        """
+        Test that two concurrent attempts to add resources in two separate
+        calendar homes does not deadlock on the revision table update.
+        """
+
+        # Create first events in different addressbook homes
+        txn1 = self._sqlStore.newTransaction()
+        txn2 = self._sqlStore.newTransaction()
+
+        addressbook_uid1_in_txn1 = yield self.addressbookUnderTest(txn1, "addressbook", "user01")
+        addressbook_uid2_in_txn2 = yield self.addressbookUnderTest(txn2, "addressbook", "user02")
+
+        data = """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
+
+"""
+
+        component = Component.fromString(data % {"ctr": 1})
+        yield addressbook_uid1_in_txn1.createAddressBookObjectWithName("data1.ics", component)
+
+        component = Component.fromString(data % {"ctr": 2})
+        yield addressbook_uid2_in_txn2.createAddressBookObjectWithName("data2.ics", 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, "addressbook", "user01")
+            component = Component.fromString(data % {"ctr": 3})
+            yield addressbook_uid1_in_txn2.createAddressBookObjectWithName("data3.ics", component)
+            yield txn2.commit()
+        d1 = _defer_uid3()
+
+        @inlineCallbacks
+        def _defer_uid4():
+            addressbook_uid2_in_txn1 = yield self.addressbookUnderTest(txn1, "addressbook", "user02")
+            component = Component.fromString(data % {"ctr": 4})
+            yield addressbook_uid2_in_txn1.createAddressBookObjectWithName("data4.ics", 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="data1.ics", addressbook_name="addressbook", home="user01")
+        vcarddata2 = yield self.addressbookObjectUnderTest(name="data2.ics", addressbook_name="addressbook", home="user02")
+        vcarddata3 = yield self.addressbookObjectUnderTest(name="data3.ics", addressbook_name="addressbook", home="user01")
+        vcarddata4 = yield self.addressbookObjectUnderTest(name="data4.ics", addressbook_name="addressbook", home="user02")
+        self.assertNotEqual(vcarddata1, None)
+        self.assertNotEqual(vcarddata2, None)
+        self.assertNotEqual(vcarddata3, None)
+        self.assertNotEqual(vcarddata4, None)

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/file.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/file.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/file.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -58,6 +58,7 @@
 from errno import EEXIST, ENOENT
 from zope.interface import implements, directlyProvides
 
+import json
 import uuid
 from twistedcaldav.sql import AbstractSQLDatabase, db_prefix
 import os
@@ -1499,17 +1500,17 @@
         return self.notificationObjectWithName(name)
 
 
-    def writeNotificationObject(self, uid, xmltype, xmldata):
+    def writeNotificationObject(self, uid, notificationtype, notificationdata):
         name = uid + ".xml"
         if name.startswith("."):
             raise ObjectResourceNameNotAllowedError(name)
 
         objectResource = NotificationObject(name, self)
-        objectResource.setData(uid, xmltype, xmldata)
+        objectResource.setData(uid, notificationtype, notificationdata)
         self._cachedObjectResources[name] = objectResource
 
         # Update database
-        self.retrieveOldIndex().addOrUpdateRecord(NotificationRecord(uid, name, xmltype.name))
+        self.retrieveOldIndex().addOrUpdateRecord(NotificationRecord(uid, name, notificationtype))
 
         self.notifyChanged()
 
@@ -1572,15 +1573,16 @@
 
 
     @writeOperation
-    def setData(self, uid, xmltype, xmldata, inserting=False):
+    def setData(self, uid, notificationtype, notificationdata, inserting=False):
 
         rname = uid + ".xml"
         self._parentCollection.retrieveOldIndex().addOrUpdateRecord(
-            NotificationRecord(uid, rname, xmltype.name)
+            NotificationRecord(uid, rname, notificationtype)
         )
 
-        self._xmldata = xmldata
-        md5 = hashlib.md5(xmldata).hexdigest()
+        self._notificationdata = notificationdata
+        notificationtext = json.dumps(self._notificationdata)
+        md5 = hashlib.md5(notificationtext).hexdigest()
 
         def do():
             backup = None
@@ -1591,7 +1593,7 @@
             try:
                 # FIXME: concurrency problem; if this write is interrupted
                 # halfway through, the underlying file will be corrupt.
-                fh.write(xmldata)
+                fh.write(notificationtext)
             finally:
                 fh.close()
             def undo():
@@ -1610,7 +1612,7 @@
 
         props = self.properties()
         props[PropertyName(*GETContentType.qname())] = GETContentType.fromString(generateContentType(MimeType("text", "xml", params={"charset": "utf-8"})))
-        props[PropertyName.fromElement(NotificationType)] = NotificationType(xmltype)
+        props[PropertyName.fromElement(NotificationType)] = NotificationType(json.dumps(notificationtype))
         props[PropertyName.fromElement(TwistedGETContentMD5)] = TwistedGETContentMD5.fromString(md5)
 
         # FIXME: the property store's flush() method may already have been
@@ -1620,11 +1622,11 @@
         # manipulation methods won't work.
         self._transaction.addOperation(self.properties().flush, "post-update property flush")
 
-    _xmldata = None
+    _notificationdata = None
 
-    def xmldata(self):
-        if self._xmldata is not None:
-            return self._xmldata
+    def notificationData(self):
+        if self._notificationdata is not None:
+            return self._notificationdata
         try:
             fh = self._path.open()
         except IOError, e:
@@ -1638,14 +1640,14 @@
         finally:
             fh.close()
 
-        return text
+        return json.loads(text)
 
 
     def uid(self):
         return self._uid
 
 
-    def xmlType(self):
+    def notificationType(self):
         # NB This is the NotificationType property element
         return self.properties()[PropertyName.fromElement(NotificationType)]
 

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -14,6 +14,9 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 ##
+from collections import namedtuple
+from txdav.xml import element
+from txdav.base.propertystore.base import PropertyName
 
 """
 SQL data store.
@@ -50,7 +53,6 @@
 from twisted.python.util import FancyEqMixin
 
 from twistedcaldav.config import config
-from twistedcaldav.customxml import NotificationType
 from twistedcaldav.dateops import datetimeMktime, pyCalendarTodatetime
 
 from txdav.base.datastore.util import QueryCacher
@@ -61,7 +63,9 @@
 from txdav.carddav.iaddressbookstore import IAddressBookTransaction
 from txdav.common.datastore.common import HomeChildBase
 from txdav.common.datastore.sql_tables import _BIND_MODE_OWN, \
-    _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED
+    _BIND_STATUS_ACCEPTED, _BIND_STATUS_DECLINED, _BIND_STATUS_INVALID, \
+    _BIND_STATUS_INVITED, _BIND_MODE_DIRECT, _BIND_STATUS_DELETED, \
+    _BIND_MODE_INDIRECT
 from txdav.common.datastore.sql_tables import schema, splitSQLString
 from txdav.common.icommondatastore import ConcurrentModification
 from txdav.common.icommondatastore import HomeChildNameNotAllowedError, \
@@ -73,13 +77,13 @@
 from txdav.common.idirectoryservice import IStoreDirectoryService
 from txdav.common.inotifications import INotificationCollection, \
     INotificationObject
-from txdav.xml.parser import WebDAVDocument
 from txdav.idav import ChangeCategory
 
 from uuid import uuid4, UUID
 
 from zope.interface import implements, directlyProvides
 
+import json
 import sys
 import time
 
@@ -640,6 +644,14 @@
         return NotificationCollection.notificationsWithUID(self, uid, create)
 
 
+    @memoizedKey("rid", "_notificationHomes")
+    def notificationsWithResourceID(self, rid):
+        """
+        Implement notificationsWithResourceID.
+        """
+        return NotificationCollection.notificationsWithResourceID(self, rid)
+
+
     @classproperty
     def _insertAPNSubscriptionQuery(cls): #@NoSelf
         apn = schema.APN_SUBSCRIPTIONS
@@ -1427,10 +1439,43 @@
 
 
 
-class CommonHome(object):
+class SharingHomeMixIn(object):
+    """
+    Common class for CommonHome to implement sharing operations
+    """
+
+    @inlineCallbacks
+    def acceptShare(self, shareUID, summary=None):
+        """
+        This share is being accepted.
+        """
+
+        shareeView = yield self.anyObjectWithShareUID(shareUID)
+        if shareeView is not None:
+            yield shareeView.acceptShare(summary)
+
+        returnValue(shareeView)
+
+
+    @inlineCallbacks
+    def declineShare(self, shareUID):
+        """
+        This share is being declined.
+        """
+
+        shareeView = yield self.anyObjectWithShareUID(shareUID)
+        if shareeView is not None:
+            yield shareeView.declineShare()
+
+        returnValue(shareeView)
+
+
+
+class CommonHome(SharingHomeMixIn):
     log = Logger()
 
     # All these need to be initialized by derived classes for each store type
+    _homeType = None
     _homeTable = None
     _homeMetaDataTable = None
     _childClass = None
@@ -1473,10 +1518,13 @@
 
 
     @classproperty
-    def _resourceIDFromOwnerQuery(cls): #@NoSelf
+    def _homeColumnsFromOwnerQuery(cls): #@NoSelf
         home = cls._homeSchema
-        return Select([home.RESOURCE_ID],
-                      From=home, Where=home.OWNER_UID == Parameter("ownerUID"))
+        return Select(
+            cls.homeColumns(),
+            From=home,
+            Where=home.OWNER_UID == Parameter("ownerUID")
+        )
 
 
     @classproperty
@@ -1496,6 +1544,34 @@
 
 
     @classmethod
+    def homeColumns(cls):
+        """
+        Return a list of column names to retrieve when doing an ownerUID->home lookup.
+        """
+
+        # Common behavior is to have created and modified
+
+        return (
+            cls._homeSchema.RESOURCE_ID,
+            cls._homeSchema.OWNER_UID,
+        )
+
+
+    @classmethod
+    def homeAttributes(cls):
+        """
+        Return a list of attributes names to map L{homeColumns} to.
+        """
+
+        # Common behavior is to have created and modified
+
+        return (
+            "_resourceID",
+            "_ownerUID",
+        )
+
+
+    @classmethod
     def metadataColumns(cls):
         """
         Return a list of column name for retrieval of metadata. This allows
@@ -1536,13 +1612,14 @@
         """
         result = yield self._cacher.get(self._ownerUID)
         if result is None:
-            result = yield self._resourceIDFromOwnerQuery.on(
+            result = yield self._homeColumnsFromOwnerQuery.on(
                 self._txn, ownerUID=self._ownerUID)
             if result and not no_cache:
                 yield self._cacher.set(self._ownerUID, result)
 
         if result:
-            self._resourceID = result[0][0]
+            for attr, value in zip(self.homeAttributes(), result[0]):
+                setattr(self, attr, value)
 
             queryCacher = self._txn._queryCacher
             if queryCacher:
@@ -1766,30 +1843,30 @@
         return self._childClass.objectWithName(self, name)
 
 
-    def objectWithShareUID(self, shareUID):
+    def anyObjectWithShareUID(self, shareUID):
         """
-        Retrieve the child with the given bind identifier contained in this
+        Retrieve the child accepted or otherwise with the given bind identifier contained in this
         home.
 
         @param name: a string.
         @return: an L{ICalendar} or C{None} if no such child exists.
         """
-        return self.childWithName(shareUID)
+        return self._childClass.objectWithName(self, shareUID, accepted=None)
 
 
-    def invitedObjectWithShareUID(self, shareUID):
+    @memoizedKey("resourceID", "_children")
+    def childWithID(self, resourceID):
         """
-        Retrieve the child invitation with the given bind identifier contained in this
+        Retrieve the child with the given C{resourceID} contained in this
         home.
 
         @param name: a string.
         @return: an L{ICalendar} or C{None} if no such child exists.
         """
-        return self._childClass.objectWithName(self, shareUID, accepted=False)
+        return self._childClass.objectWithID(self, resourceID)
 
 
-    @memoizedKey("resourceID", "_children")
-    def childWithID(self, resourceID):
+    def allChildWithID(self, resourceID):
         """
         Retrieve the child with the given C{resourceID} contained in this
         home.
@@ -1797,7 +1874,7 @@
         @param name: a string.
         @return: an L{ICalendar} or C{None} if no such child exists.
         """
-        return self._childClass.objectWithID(self, resourceID)
+        return self._childClass.objectWithID(self, resourceID, accepted=None)
 
 
     @inlineCallbacks
@@ -2660,125 +2737,13 @@
 
 
 
-class SharingInvitation(object):
-    """
-    SharingInvitation covers all the information needed to expose sharing invites to upper layers. Its primarily used to
-    minimize the need to load full properties/data when only this subset of information is needed.
-    """
-    def __init__(self, uid, owner_uid, owner_rid, sharee_uid, sharee_rid, resource_id, resource_name, mode, status, summary):
-        self._uid = uid
-        self._owner_uid = owner_uid
-        self._owner_rid = owner_rid
-        self._sharee_uid = sharee_uid
-        self._sharee_rid = sharee_rid
-        self._resource_id = resource_id
-        self._resource_name = resource_name
-        self._mode = mode
-        self._status = status
-        self._summary = summary
+SharingInvitation = namedtuple(
+    "SharingInvitation",
+    ["uid", "ownerUID", "ownerHomeID", "shareeUID", "shareeHomeID", "mode", "status", "summary"]
+)
 
 
-    @classmethod
-    def fromCommonHomeChild(cls, homeChild):
-        return cls(
-            homeChild.shareUID(),
-            homeChild.ownerHome().uid(),
-            homeChild.ownerHome()._resourceID,
-            homeChild.viewerHome().uid(),
-            homeChild.viewerHome()._resourceID,
-            homeChild._resourceID,
-            homeChild.shareeName(),
-            homeChild.shareMode(),
-            homeChild.shareStatus(),
-            homeChild.shareMessage(),
-        )
 
-
-    def uid(self):
-        """
-        This maps to the resource name in the bind table, the "bind name". This is used as the "uid"
-        for invites, and is not necessarily the name of the resource as it appears in the collection.
-        """
-        return self._uid
-
-
-    def ownerUID(self):
-        """
-        The ownerUID of the sharer.
-        """
-        return self._owner_uid
-
-
-    def ownerHomeID(self):
-        """
-        The resourceID of the sharer's L{CommonHome}.
-        """
-        return self._owner_rid
-
-
-    def shareeUID(self):
-        """
-        The ownerUID of the sharee.
-        """
-        return self._sharee_uid
-
-
-    def shareeHomeID(self):
-        """
-        The resourceID of the sharee's L{CommonHome}.
-        """
-        return self._sharee_rid
-
-
-    def resourceID(self):
-        """
-        The resourceID of the shared object.
-        """
-        return self._resource_id
-
-
-    def resourceName(self):
-        """
-        This maps to the name of the shared resource in the collection it is bound into. It is not necessarily the
-        same as the "bind name" which is used as the "uid" for invites.
-        """
-        return self._resource_name
-
-
-    def mode(self):
-        """
-        The sharing mode: one of the _BIND_MODE_XXX values.
-        """
-        return self._mode
-
-
-    def setMode(self, mode):
-        self._mode = mode
-
-
-    def status(self):
-        """
-        The sharing status: one of the _BIND_STATUS_XXX values.
-        """
-        return self._status
-
-
-    def setStatus(self, status):
-        self._status = status
-
-
-    def summary(self):
-        """
-        Message associated with the invitation.
-        """
-        return self._summary
-
-
-    def setSummary(self, summary):
-        self._summary = summary
-
-
-
 class SharingMixIn(object):
     """
     Common class for CommonHomeChild and AddressBookObject
@@ -2804,29 +2769,20 @@
     @classmethod
     def _updateBindColumnsQuery(cls, columnMap): #@NoSelf
         bind = cls._bindSchema
-        return Update(columnMap,
-                      Where=(bind.RESOURCE_ID == Parameter("resourceID"))
-                      .And(bind.HOME_RESOURCE_ID == Parameter("homeID")),
-                      Return=bind.RESOURCE_NAME)
+        return Update(
+            columnMap,
+            Where=(bind.RESOURCE_ID == Parameter("resourceID"))
+                   .And(bind.HOME_RESOURCE_ID == Parameter("homeID")),
+        )
 
 
     @classproperty
-    def _updateBindQuery(cls): #@NoSelf
-        bind = cls._bindSchema
-        return cls._updateBindColumnsQuery(
-                    {bind.BIND_MODE: Parameter("mode"),
-                     bind.BIND_STATUS: Parameter("status"),
-                     bind.MESSAGE: Parameter("message")})
-
-
-    @classproperty
     def _deleteBindForResourceIDAndHomeID(cls): #@NoSelf
         bind = cls._bindSchema
         return Delete(
             From=bind,
             Where=(bind.RESOURCE_ID == Parameter("resourceID"))
                   .And(bind.HOME_RESOURCE_ID == Parameter("homeID")),
-            Return=bind.RESOURCE_NAME,
         )
 
 
@@ -2900,9 +2856,246 @@
                                )
 
 
+    #
+    # Higher level API
+    #
     @inlineCallbacks
-    def shareWith(self, shareeHome, mode, status=None, message=None):
+    def inviteUserToShare(self, shareeUID, mode, summary):
         """
+        Invite a user to share this collection - either create the share if it does not exist, or
+        update the existing share with new values. Make sure a notification is sent as well.
+
+        @param shareeUID: UID of the sharee
+        @type shareeUID: C{str}
+        @param mode: access mode
+        @type mode: C{int}
+        @param summary: share message
+        @type summary: C{str}
+        """
+
+        # Look for existing invite and update its fields or create new one
+        shareeView = yield self.shareeView(shareeUID)
+        if shareeView is not None:
+            status = _BIND_STATUS_INVITED if shareeView.shareStatus() in (_BIND_STATUS_DECLINED, _BIND_STATUS_INVALID) else None
+            yield self.updateShare(shareeView, mode=mode, status=status, summary=summary)
+        else:
+            shareeView = yield self.createShare(shareeUID=shareeUID, mode=mode, summary=summary)
+
+        # Send invite notification
+        yield self._sendInviteNotification(shareeView)
+        returnValue(shareeView)
+
+
+    @inlineCallbacks
+    def directShareWithUser(self, shareeUID):
+        """
+        Create a direct share with the specified user. Note it is currently up to the app layer
+        to enforce access control - this is not ideal as we really should have control of that in
+        the store. Once we do, this api will need to verify that access is allowed for a direct share.
+
+        NB no invitations are used with direct sharing.
+
+        @param shareeUID: UID of the sharee
+        @type shareeUID: C{str}
+        """
+
+        # Ignore if it already exists
+        shareeView = yield self.shareeView(shareeUID)
+        if shareeView is None:
+            shareeView = yield self.createShare(shareeUID=shareeUID, mode=_BIND_MODE_DIRECT)
+            yield shareeView.newShare()
+        returnValue(shareeView)
+
+
+    @inlineCallbacks
+    def uninviteUserFromShare(self, shareeUID):
+        """
+        Remove a user from a share. Make sure a notification is sent as well.
+
+        @param shareeUID: UID of the sharee
+        @type shareeUID: C{str}
+        """
+        # Cancel invites - we'll just use whatever userid we are given
+
+        shareeView = yield self.shareeView(shareeUID)
+        if shareeView is not None:
+            # If current user state is accepted then we send an invite with the new state, otherwise
+            # we cancel any existing invites for the user
+            if not shareeView.direct():
+                if shareeView.shareStatus() != _BIND_STATUS_ACCEPTED:
+                    yield self._removeInviteNotification(shareeView)
+                else:
+                    yield self._sendInviteNotification(shareeView, notificationState=_BIND_STATUS_DELETED)
+
+            # Remove the bind
+            yield self.removeShare(shareeView)
+
+
+    @inlineCallbacks
+    def acceptShare(self, summary=None):
+        """
+        This share is being accepted.
+        """
+
+        if not self.direct() and self.shareStatus() != _BIND_STATUS_ACCEPTED:
+            ownerView = yield self.ownerView()
+            yield ownerView.updateShare(self, status=_BIND_STATUS_ACCEPTED)
+            yield self.newShare(displayname=summary)
+            yield self._sendReplyNotification(ownerView, summary)
+
+
+    @inlineCallbacks
+    def declineShare(self):
+        """
+        This share is being declined.
+        """
+
+        if not self.direct() and self.shareStatus() != _BIND_STATUS_DECLINED:
+            ownerView = yield self.ownerView()
+            yield ownerView.updateShare(self, status=_BIND_STATUS_DECLINED)
+            yield self._sendReplyNotification(ownerView)
+
+
+    @inlineCallbacks
+    def deleteShare(self):
+        """
+        This share is being deleted - either decline or remove (for direct shares).
+        """
+
+        ownerView = yield self.ownerView()
+        if self.direct():
+            yield ownerView.removeShare(self)
+        else:
+            yield self.declineShare()
+
+
+    def newShare(self, displayname=None):
+        """
+        Override in derived classes to do any specific operations needed when a share
+        is first accepted.
+        """
+        return succeed(None)
+
+
+    @inlineCallbacks
+    def allInvitations(self):
+        """
+        Get list of all invitations (non-direct) to this object.
+        """
+        invitations = yield self.sharingInvites()
+
+        # remove direct shares as those are not "real" invitations
+        invitations = filter(lambda x: x.mode != _BIND_MODE_DIRECT, invitations)
+        invitations.sort(key=lambda invitation: invitation.shareeUID)
+        returnValue(invitations)
+
+
+    @inlineCallbacks
+    def _sendInviteNotification(self, shareeView, notificationState=None):
+        """
+        Called on the owner's resource.
+        """
+
+        # When deleting the message is the sharee's display name
+        displayname = shareeView.shareMessage()
+        if notificationState == _BIND_STATUS_DELETED:
+            displayname = str(shareeView.properties().get(PropertyName.fromElement(element.DisplayName), displayname))
+
+        notificationtype = {
+            "notification-type": "invite-notification",
+            "shared-type": shareeView.sharedResourceType(),
+        }
+        notificationdata = {
+            "notification-type": "invite-notification",
+            "shared-type": shareeView.sharedResourceType(),
+            "dtstamp": DateTime.getNowUTC().getText(),
+            "owner": shareeView.ownerHome().uid(),
+            "sharee": shareeView.viewerHome().uid(),
+            "uid": shareeView.shareUID(),
+            "status": shareeView.shareStatus() if notificationState is None else notificationState,
+            "access": shareeView.shareMode(),
+            "ownerName": self.shareName(),
+            "summary": displayname,
+        }
+        if hasattr(self, "getSupportedComponents"):
+            notificationdata["supported-components"] = self.getSupportedComponents()
+
+        # Add to sharee's collection
+        notifications = yield self._txn.notificationsWithUID(shareeView.viewerHome().uid())
+        yield notifications.writeNotificationObject(shareeView.shareUID(), notificationtype, notificationdata)
+
+
+    @inlineCallbacks
+    def _sendReplyNotification(self, ownerView, summary=None):
+        """
+        Create a reply notification based on the current state of this shared resource.
+        """
+
+        # Generate invite XML
+        notificationUID = "%s-reply" % (self.shareUID(),)
+
+        notificationtype = {
+            "notification-type": "invite-reply",
+            "shared-type": self.sharedResourceType(),
+        }
+
+        notificationdata = {
+            "notification-type": "invite-reply",
+            "shared-type": self.sharedResourceType(),
+            "dtstamp": DateTime.getNowUTC().getText(),
+            "owner": self.ownerHome().uid(),
+            "sharee": self.viewerHome().uid(),
+            "status": self.shareStatus(),
+            "ownerName": ownerView.shareName(),
+            "in-reply-to": self.shareUID(),
+            "summary": summary,
+        }
+
+        # Add to owner notification collection
+        notifications = yield self._txn.notificationsWithUID(self.ownerHome().uid())
+        yield notifications.writeNotificationObject(notificationUID, notificationtype, notificationdata)
+
+
+    @inlineCallbacks
+    def _removeInviteNotification(self, shareeView):
+        """
+        Called on the owner's resource.
+        """
+
+        # Remove from sharee's collection
+        notifications = yield self._txn.notificationsWithUID(shareeView.viewerHome().uid())
+        yield notifications.removeNotificationObjectWithUID(shareeView.shareUID())
+
+
+    #
+    # Lower level API
+    #
+
+    @inlineCallbacks
+    def ownerView(self):
+        """
+        Return the owner resource counterpart of this shared resource.
+        """
+        # Get the child of the owner home that has the same resource id as the owned one
+        ownerView = yield self.ownerHome().childWithID(self.id())
+        returnValue(ownerView)
+
+
+    @inlineCallbacks
+    def shareeView(self, shareeUID):
+        """
+        Return the shared resource counterpart of this owned resource for the specified sharee.
+        """
+
+        # Get the child of the sharee home that has the same resource id as the owned one
+        shareeHome = yield self._txn.homeWithUID(self._home._homeType, shareeUID)
+        shareeView = (yield shareeHome.allChildWithID(self.id())) if shareeHome is not None else None
+        returnValue(shareeView)
+
+
+    @inlineCallbacks
+    def shareWith(self, shareeHome, mode, status=None, summary=None):
+        """
         Share this (owned) L{CommonHomeChild} with another home.
 
         @param shareeHome: The home of the sharee.
@@ -2916,9 +3109,9 @@
             L{_BIND_STATUS_ACCEPTED}
         @type mode: L{str}
 
-        @param message: The proposed message to go along with the share, which
+        @param summary: The proposed message to go along with the share, which
             will be used as the default display name.
-        @type mode: L{str}
+        @type summary: L{str}
 
         @return: the name of the shared calendar in the new calendar home.
         @rtype: L{str}
@@ -2929,30 +3122,36 @@
 
         @inlineCallbacks
         def doInsert(subt):
-            newName = str(uuid4())
+            newName = self.newShareName()
             yield self._bindInsertQuery.on(
-                subt, homeID=shareeHome._resourceID,
-                resourceID=self._resourceID, name=newName,
-                mode=mode, bindStatus=status, message=message
+                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
-            child = yield shareeHome.childWithID(self._resourceID)
-            if not child:
-                child = yield shareeHome.objectWithID(shareeHome, self._resourceID, accepted=False)
-            bindName = yield self.updateShare(
+            child = yield shareeHome.allChildWithID(self._resourceID)
+            yield self.updateShare(
                 child, mode=mode, status=status,
-                message=message
+                summary=summary
             )
+            bindName = child._name
         else:
             if status == _BIND_STATUS_ACCEPTED:
-                shareeView = yield shareeHome.objectWithShareUID(bindName)
+                shareeView = yield shareeHome.anyObjectWithShareUID(bindName)
                 yield shareeView._initSyncToken()
                 yield shareeView._initBindRevision()
 
+        # Mark this as shared
+        yield self.setShared(True)
+
         # Must send notification to ensure cache invalidation occurs
         yield self.notifyPropertyChanged()
         yield shareeHome.notifyChanged()
@@ -2961,26 +3160,25 @@
 
 
     @inlineCallbacks
-    def updateShareFromSharingInvitation(self, invitation, mode=None, status=None, message=None):
+    def createShare(self, shareeUID, mode, summary=None):
         """
-        Like L{updateShare} except that the original invitation is provided. That is used
-        to find the actual sharee L{CommonHomeChild} which is then passed to L{updateShare}.
+        Create a new shared resource. If the mode is direct, the share is created in accepted state,
+        otherwise the share is created in invited state.
         """
+        shareeHome = yield self._txn.homeWithUID(self.ownerHome()._homeType, shareeUID, create=True)
 
-        # Look up the shared child - might be accepted or not. If accepted use the resource name
-        # to look it up, else use the invitation uid (bind name)
-        shareeHome = yield self._txn.homeWithUID(self._home._homeType, invitation.shareeUID())
-        shareeView = yield shareeHome.objectWithShareUID(invitation.uid())
-        if shareeView is None:
-            shareeView = yield shareeHome.invitedObjectWithShareUID(invitation.uid())
-            assert shareeView
+        yield self.shareWith(
+            shareeHome,
+            mode=mode,
+            status=_BIND_STATUS_INVITED if mode != _BIND_MODE_DIRECT else _BIND_STATUS_ACCEPTED,
+            summary=summary,
+        )
+        shareeView = yield self.shareeView(shareeUID)
+        returnValue(shareeView)
 
-        result = yield self.updateShare(shareeView, mode, status, message)
-        returnValue(result)
 
-
     @inlineCallbacks
-    def updateShare(self, shareeView, mode=None, status=None, message=None):
+    def updateShare(self, shareeView, mode=None, status=None, summary=None):
         """
         Update share mode, status, and message for a home child shared with
         this (owned) L{CommonHomeChild}.
@@ -2997,50 +3195,41 @@
             L{_BIND_STATUS_INVALID}  or None to not update
         @type status: L{str}
 
-        @param message: The proposed message to go along with the share, which
+        @param summary: The proposed message to go along with the share, which
             will be used as the default display name, or None to not update
-        @type message: L{str}
-
-        @return: the name of the shared item in the sharee's home.
-        @rtype: a L{Deferred} which fires with a L{str}
+        @type summary: L{str}
         """
         # 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 = {}
-        if mode != None and mode != shareeView._bindMode:
-            columnMap[bind.BIND_MODE] = mode
-        if status != None and status != shareeView._bindStatus:
-            columnMap[bind.BIND_STATUS] = status
-        if message != None and message != shareeView._bindMessage:
-            columnMap[bind.MESSAGE] = message
+        columnMap = dict([(k, v if v != "" else None) for k, v in {
+            bind.BIND_MODE:mode,
+            bind.BIND_STATUS:status,
+            bind.MESSAGE:summary
+        }.iteritems() if v is not None])
 
         if columnMap:
 
-            sharedname = yield self._updateBindColumnsQuery(columnMap).on(
-                            self._txn,
-                            resourceID=self._resourceID, homeID=shareeView._home._resourceID
-                        )
+            # Count accepted
+            if status is not None:
+                previouslyAcceptedCount = yield shareeView._previousAcceptCount()
 
-            #update affected attributes
+            yield self._updateBindColumnsQuery(columnMap).on(
+                self._txn,
+                resourceID=self._resourceID, homeID=shareeView._home._resourceID
+            )
+
+            # Update affected attributes
             if bind.BIND_MODE in columnMap:
                 shareeView._bindMode = columnMap[bind.BIND_MODE]
 
             if bind.BIND_STATUS in columnMap:
                 shareeView._bindStatus = columnMap[bind.BIND_STATUS]
-                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)
+                yield shareeView._changedStatus(previouslyAcceptedCount)
 
-            if bind.MESSAGE in columnMap:
+            if summary is not None:
                 shareeView._bindMessage = columnMap[bind.MESSAGE]
 
             queryCacher = self._txn._queryCacher
@@ -3050,71 +3239,66 @@
                 cacheKey = queryCacher.keyForObjectWithResourceID(shareeView._home._resourceID, shareeView._resourceID)
                 yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
 
-            shareeView._name = sharedname[0][0]
-
             # Must send notification to ensure cache invalidation occurs
             yield self.notifyPropertyChanged()
             yield shareeView.viewerHome().notifyChanged()
 
-        returnValue(shareeView._name)
 
+    def _previousAcceptCount(self):
+        return succeed(1)
 
+
     @inlineCallbacks
-    def unshareWithUID(self, shareeUID):
-        """
-        Like L{unshareWith} except this is passed a sharee UID which is then used to lookup the
-        L{CommonHome} for the sharee to pass to L{unshareWith}.
-        """
+    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)
 
-        shareeHome = yield self._txn.homeWithUID(self._home._homeType, shareeUID)
-        result = yield self.unshareWith(shareeHome)
-        returnValue(result)
 
-
     @inlineCallbacks
-    def unshareWith(self, shareeHome):
+    def removeShare(self, shareeView):
         """
         Remove the shared version of this (owned) L{CommonHomeChild} from the
         referenced L{CommonHome}.
 
         @see: L{CommonHomeChild.shareWith}
 
-        @param shareeHome: The home with which this L{CommonHomeChild} was
-            previously shared.
+        @param shareeView: The shared resource being removed.
 
         @return: a L{Deferred} which will fire with the previous shareUID
         """
-        #remove sync tokens
-        shareeChildren = yield shareeHome.children()
-        for shareeChild in shareeChildren:
-            if not shareeChild.owned() and shareeChild._resourceID == self._resourceID:
-                yield shareeChild._deletedSyncToken(sharedRemoval=True)
-                shareeHome._children.pop(shareeChild._name, None)
-                shareeHome._children.pop(shareeChild._resourceID, None)
 
-                # Must send notification to ensure cache invalidation occurs
-                yield self.notifyPropertyChanged()
-                yield shareeHome.notifyChanged()
-                break
+        # remove sync tokens
+        shareeHome = shareeView.viewerHome()
+        yield shareeView._deletedSyncToken(sharedRemoval=True)
+        shareeHome._children.pop(shareeView._name, None)
+        shareeHome._children.pop(shareeView._resourceID, None)
 
+        # Must send notification to ensure cache invalidation occurs
+        yield self.notifyPropertyChanged()
+        yield shareeHome.notifyChanged()
+
         # delete binds including invites
-        deletedBindNameRows = yield self._deleteBindForResourceIDAndHomeID.on(self._txn, resourceID=self._resourceID,
-             homeID=shareeHome._resourceID)
+        yield self._deleteBindForResourceIDAndHomeID.on(
+            self._txn,
+            resourceID=self._resourceID,
+            homeID=shareeHome._resourceID,
+        )
 
-        if deletedBindNameRows:
-            deletedBindName = deletedBindNameRows[0][0]
-            queryCacher = self._txn._queryCacher
-            if queryCacher:
-                cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, shareeChild._name)
-                yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-                cacheKey = queryCacher.keyForObjectWithResourceID(shareeHome._resourceID, shareeChild._resourceID)
-                yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
-        else:
-            deletedBindName = None
+        queryCacher = self._txn._queryCacher
+        if queryCacher:
+            cacheKey = queryCacher.keyForObjectWithName(shareeHome._resourceID, shareeView._name)
+            yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
+            cacheKey = queryCacher.keyForObjectWithResourceID(shareeHome._resourceID, shareeView._resourceID)
+            yield queryCacher.invalidateAfterCommit(self._txn, cacheKey)
 
-        returnValue(deletedBindName)
 
-
     @inlineCallbacks
     def unshare(self):
         """
@@ -3124,12 +3308,12 @@
             # This collection may be shared to others
             invites = yield self.sharingInvites()
             for invite in invites:
-                shareeHome = (yield self._txn.homeWithResourceID(self._home._homeType, invite.shareeHomeID()))
-                (yield self.unshareWith(shareeHome))
+                shareeView = yield self.shareeView(invite.shareeUID)
+                yield self.removeShare(shareeView)
         else:
             # This collection is shared to me
-            ownerHomeChild = yield self.ownerHome().childWithID(self._resourceID)
-            yield ownerHomeChild.unshareWith(self._home)
+            ownerView = yield self.ownerView()
+            yield ownerView.removeShare(self)
 
 
     @inlineCallbacks
@@ -3152,12 +3336,10 @@
         for homeUID, homeRID, resourceID, resourceName, bindMode, bindStatus, bindMessage in acceptedRows: #@UnusedVariable
             invite = SharingInvitation(
                 resourceName,
-                self._home.name(),
-                self._home._resourceID,
+                self.ownerHome().name(),
+                self.ownerHome().id(),
                 homeUID,
                 homeRID,
-                resourceID,
-                resourceName if self.bindNameIsResourceName() else self.shareeName(),
                 bindMode,
                 bindStatus,
                 bindMessage,
@@ -3173,7 +3355,8 @@
 
         bind = self._bindSchema
         yield self._updateBindColumnsQuery(
-            {bind.BIND_REVISION : Parameter("revision"), }).on(
+            {bind.BIND_REVISION : Parameter("revision"), }
+        ).on(
             self._txn,
             revision=self._bindRevision,
             resourceID=self._resourceID,
@@ -3182,13 +3365,23 @@
         yield self.invalidateQueryCache()
 
 
-    def shareMode(self):
+    def sharedResourceType(self):
         """
-        @see: L{ICalendar.shareMode}
+        The sharing resource type. Needs to be overridden by each type of resource that can be shared.
+
+        @return: an identifier for the type of the share.
+        @rtype: C{str}
         """
-        return self._bindMode
+        return ""
 
 
+    def newShareName(self):
+        """
+        Name used when creating a new share. By default this is a UUID.
+        """
+        return str(uuid4())
+
+
     def owned(self):
         """
         @see: L{ICalendar.owned}
@@ -3219,8 +3412,13 @@
         """
         assert self.owned()
 
-        self._bindMessage = "shared" if shared else None
+        # Only if change is needed
+        newMessage = "shared" if shared else None
+        if self._bindMessage == newMessage:
+            returnValue(None)
 
+        self._bindMessage = newMessage
+
         bind = self._bindSchema
         yield Update(
             {bind.MESSAGE: self._bindMessage},
@@ -3232,20 +3430,51 @@
         yield self.notifyPropertyChanged()
 
 
-    def shareeName(self):
+    def direct(self):
         """
-        The sharee's name for a shared L{CommonHomeChild} is the name of the resource by default.
+        Is this a "direct" share?
+
+        @return: a boolean indicating whether it's direct.
         """
+        return self._bindMode == _BIND_MODE_DIRECT
+
+
+    def indirect(self):
+        """
+        Is this an "indirect" share?
+
+        @return: a boolean indicating whether it's indirect.
+        """
+        return self._bindMode == _BIND_MODE_INDIRECT
+
+
+    def shareUID(self):
+        """
+        @see: L{ICalendar.shareUID}
+        """
         return self.name()
 
 
-    def bindNameIsResourceName(self):
+    def shareMode(self):
         """
-        By default, the shared resource name of an accepted share is the same as the name in the bind table.
+        @see: L{ICalendar.shareMode}
         """
-        return True
+        return self._bindMode
 
 
+    def shareName(self):
+        """
+        This is a path like name for the resource within the home being shared. For object resource
+        shares this will be a combination of the L{CommonHomeChild} name and the L{CommonObjecrResource}
+        name. Otherwise it is just the L{CommonHomeChild} name. This is needed to expose a value to the
+        app-layer such that it can construct a URI for the actual WebDAV resource being shared.
+        """
+        name = self.name()
+        if self.sharedResourceType() == "group":
+            name = self.parentCollection().name() + "/" + name
+        return name
+
+
     def shareStatus(self):
         """
         @see: L{ICalendar.shareStatus}
@@ -3253,18 +3482,18 @@
         return self._bindStatus
 
 
-    def shareMessage(self):
+    def accepted(self):
         """
-        @see: L{ICalendar.shareMessage}
+        @see: L{ICalendar.shareStatus}
         """
-        return self._bindMessage
+        return self._bindStatus == _BIND_STATUS_ACCEPTED
 
 
-    def shareUID(self):
+    def shareMessage(self):
         """
-        @see: L{ICalendar.shareUID}
+        @see: L{ICalendar.shareMessage}
         """
-        return self.name()
+        return self._bindMessage
 
 
     @classmethod
@@ -3454,7 +3683,7 @@
         """
         # FIXME: tests don't cover this as directly as they should.
         rows = yield cls._acceptedBindForHomeID.on(
-                home._txn, homeID=home._resourceID
+            home._txn, homeID=home._resourceID
         )
         names = [row[3] for row in rows]
         returnValue(names)
@@ -3502,10 +3731,13 @@
 
             child = cls(
                 home=home,
-                name=bindName, resourceID=resourceID,
-                mode=bindMode, status=bindStatus,
+                name=bindName,
+                resourceID=resourceID,
+                mode=bindMode,
+                status=bindStatus,
                 revision=bindRevision,
-                message=bindMessage, ownerHome=ownerHome,
+                message=bindMessage,
+                ownerHome=ownerHome,
                 ownerName=ownerName,
             )
             for attr, value in zip(cls.additionalBindAttributes(), additionalBind):
@@ -3524,11 +3756,21 @@
 
 
     @classmethod
+    def objectWithName(cls, home, name, accepted=True):
+        return cls._objectWithNameOrID(home, name=name, accepted=accepted)
+
+
+    @classmethod
+    def objectWithID(cls, home, resourceID, accepted=True):
+        return cls._objectWithNameOrID(home, resourceID=resourceID, accepted=accepted)
+
+
+    @classmethod
     @inlineCallbacks
-    def objectWithName(cls, home, name, accepted=True):
+    def _objectWithNameOrID(cls, home, name=None, resourceID=None, accepted=True):
         # replaces objectWithName()
         """
-        Retrieve the child with the given C{name} contained in the given
+        Retrieve the child with the given C{name} or C{resourceID} contained in the given
         C{home}.
 
         @param home: a L{CommonHome}.
@@ -3543,97 +3785,65 @@
 
         if queryCacher:
             # Retrieve data from cache
-            cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
+            if name:
+                cacheKey = queryCacher.keyForObjectWithName(home._resourceID, name)
+            else:
+                cacheKey = queryCacher.keyForObjectWithResourceID(home._resourceID, resourceID)
             rows = yield queryCacher.get(cacheKey)
 
         if rows is None:
             # No cached copy
-            rows = yield cls._bindForNameAndHomeID.on(home._txn, name=name, homeID=home._resourceID)
+            if name:
+                rows = yield cls._bindForNameAndHomeID.on(home._txn, name=name, homeID=home._resourceID)
+            else:
+                rows = yield cls._bindForResourceIDAndHomeID.on(home._txn, resourceID=resourceID, homeID=home._resourceID)
 
-            if rows and queryCacher:
-                # Cache the result
-                queryCacher.setAfterCommit(home._txn, cacheKey, rows)
-                queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithResourceID(home._resourceID, rows[0][2]), rows)
-
         if not rows:
             returnValue(None)
 
         row = rows[0]
-        bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
-        if (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
+        bindMode, homeID, resourceID, name, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable
+
+        if queryCacher:
+            # Cache the result
+            queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithName(home._resourceID, name), rows)
+            queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithResourceID(home._resourceID, resourceID), rows)
+
+        if accepted is not None and (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
             returnValue(None)
         additionalBind = row[cls.bindColumnCount:cls.bindColumnCount + len(cls.additionalBindColumns())]
 
         if bindMode == _BIND_MODE_OWN:
             ownerHome = home
-            ownerName = bindName
+            ownerName = name
         else:
             ownerHome, ownerName = yield home.ownerHomeAndChildNameForChildID(resourceID)
 
         child = cls(
             home=home,
-            name=name, resourceID=resourceID,
-            mode=bindMode, status=bindStatus,
+            name=name,
+            resourceID=resourceID,
+            mode=bindMode,
+            status=bindStatus,
             revision=bindRevision,
-            message=bindMessage, ownerHome=ownerHome,
+            message=bindMessage,
+            ownerHome=ownerHome,
             ownerName=ownerName
         )
         yield child.initFromStore(additionalBind)
         returnValue(child)
 
 
-    @classmethod
-    @inlineCallbacks
-    def objectWithID(cls, home, resourceID, accepted=True):
-        """
-        Retrieve the child with the given C{resourceID} contained in the given
-        C{home}.
-
-        @param home: a L{CommonHome}.
-        @param resourceID: a string.
-        @return: an L{CommonHomeChild} or C{None} if no such child
-            exists.
-        """
-
-        rows = None
-        queryCacher = home._txn._queryCacher
-
-        if queryCacher:
-            # Retrieve data from cache
-            cacheKey = queryCacher.keyForObjectWithResourceID(home._resourceID, resourceID)
-            rows = yield queryCacher.get(cacheKey)
-
-        if rows is None:
-            # No cached copy
-            rows = yield cls._bindForResourceIDAndHomeID.on(home._txn, resourceID=resourceID, homeID=home._resourceID)
-
-            if rows and queryCacher:
-                # Cache the result (under both the ID and name values)
-                queryCacher.setAfterCommit(home._txn, cacheKey, rows)
-                queryCacher.setAfterCommit(home._txn, queryCacher.keyForObjectWithName(home._resourceID, rows[0][3]), rows)
-
-        if not rows:
-            returnValue(None)
-
-        row = rows[0]
-        bindMode, homeID, resourceID, bindName, bindStatus, bindRevision, bindMessage = row[:cls.bindColumnCount] #@UnusedVariable]
-        if (bindStatus == _BIND_STATUS_ACCEPTED) != bool(accepted):
-            returnValue(None)
-
-        if accepted:
-            returnValue((yield home.objectWithShareUID(bindName)))
-        else:
-            returnValue((yield home.invitedObjectWithShareUID(bindName)))
-
-
     @classproperty
     def _insertHomeChild(cls): #@NoSelf
         """
         DAL statement to create a home child with all default values.
         """
         child = cls._homeChildSchema
-        return Insert({child.RESOURCE_ID: schema.RESOURCE_ID_SEQ},
-                      Return=(child.RESOURCE_ID))
+        return Insert(
+            {child.RESOURCE_ID: schema.RESOURCE_ID_SEQ},
+            Return=(child.RESOURCE_ID)
+        )
 
 
     @classproperty
@@ -3713,9 +3923,7 @@
             dataRows = None
         if dataRows is None:
             # No cached copy
-            dataRows = (
-                yield self._metadataByIDQuery.on(self._txn,
-                    resourceID=self._resourceID))[0]
+            dataRows = (yield self._metadataByIDQuery.on(self._txn, resourceID=self._resourceID))[0]
             if queryCacher:
                 # Cache the results
                 yield queryCacher.setAfterCommit(self._txn, cacheKey, dataRows)
@@ -4351,8 +4559,7 @@
 
 
     @inlineCallbacks
-    def _notifyChanged(self, property_change=False,
-            category=ChangeCategory.default):
+    def _notifyChanged(self, property_change=False, category=ChangeCategory.default):
         """
         Send notifications, change sync token and bump last modified because
         the resource has changed.  We ensure we only do this once per object
@@ -4462,7 +4669,7 @@
         self._size = None
         self._created = None
         self._modified = None
-        self._objectText = None
+        self._notificationData = None
 
         self._locked = False
 
@@ -4786,6 +4993,18 @@
         return self._parentCollection
 
 
+    def owned(self):
+        return self._parentCollection.owned()
+
+
+    def ownerHome(self):
+        return self._parentCollection.ownerHome()
+
+
+    def viewerHome(self):
+        return self._parentCollection.viewerHome()
+
+
     @classmethod
     def _selectForUpdateQuery(cls, nowait): #@NoSelf
         """
@@ -4873,7 +5092,7 @@
         self._size = None
         self._created = None
         self._modified = None
-        self._objectText = None
+        self._notificationData = None
 
 
     def uid(self):
@@ -4917,19 +5136,19 @@
 
     @inlineCallbacks
     def _text(self):
-        if self._objectText is None:
+        if self._notificationData is None:
             texts = (
                 yield self._textByIDQuery.on(self._txn,
                                              resourceID=self._resourceID)
             )
             if texts:
                 text = texts[0][0]
-                self._objectText = text
+                self._notificationData = text
                 returnValue(text)
             else:
                 raise ConcurrentModification()
         else:
-            returnValue(self._objectText)
+            returnValue(self._notificationData)
 
 
 
@@ -4952,6 +5171,7 @@
         self._txn = txn
         self._uid = uid
         self._resourceID = resourceID
+        self._dataVersion = None
         self._notifications = {}
         self._notificationNames = None
         self._syncTokenRevision = None
@@ -4964,6 +5184,10 @@
         [_homeSchema.RESOURCE_ID], From=_homeSchema,
         Where=_homeSchema.OWNER_UID == Parameter("uid"))
 
+    _UIDFromResourceIDQuery = Select(
+        [_homeSchema.OWNER_UID], From=_homeSchema,
+        Where=_homeSchema.RESOURCE_ID == Parameter("rid"))
+
     _provisionNewNotificationsQuery = Insert(
         {_homeSchema.OWNER_UID: Parameter("uid")},
         Return=_homeSchema.RESOURCE_ID
@@ -5022,7 +5246,20 @@
         returnValue(collection)
 
 
+    @classmethod
     @inlineCallbacks
+    def notificationsWithResourceID(cls, txn, rid):
+        rows = yield cls._UIDFromResourceIDQuery.on(txn, rid=rid)
+
+        if rows:
+            uid = rows[0][0]
+            result = (yield cls.notificationsWithUID(txn, uid, create=False))
+            returnValue(result)
+        else:
+            returnValue(None)
+
+
+    @inlineCallbacks
     def _loadPropertyStore(self):
         self._propertyStore = yield PropertyStore.load(
             self._uid,
@@ -5047,6 +5284,23 @@
         return self._resourceID
 
 
+    @classproperty
+    def _dataVersionQuery(cls): #@NoSelf
+        nh = cls._homeSchema
+        return Select(
+            [nh.DATAVERSION], From=nh,
+            Where=nh.RESOURCE_ID == Parameter("resourceID")
+        )
+
+
+    @inlineCallbacks
+    def dataVersion(self):
+        if self._dataVersion is None:
+            self._dataVersion = (yield self._dataVersionQuery.on(
+                self._txn, resourceID=self._resourceID))[0][0]
+        returnValue(self._dataVersion)
+
+
     def name(self):
         return "notification"
 
@@ -5115,22 +5369,26 @@
 
 
     @inlineCallbacks
-    def writeNotificationObject(self, uid, xmltype, xmldata):
+    def writeNotificationObject(self, uid, notificationtype, notificationdata):
 
         inserting = False
         notificationObject = yield self.notificationObjectWithUID(uid)
         if notificationObject is None:
             notificationObject = NotificationObject(self, uid)
             inserting = True
-        yield notificationObject.setData(uid, xmltype, xmldata, inserting=inserting)
+        yield notificationObject.setData(uid, notificationtype, notificationdata, inserting=inserting)
         if inserting:
             yield self._insertRevision("%s.xml" % (uid,))
+            if self._notificationNames is not None:
+                self._notificationNames.append(notificationObject.uid())
         else:
             yield self._updateRevision("%s.xml" % (uid,))
         yield self.notifyChanged()
 
 
     def removeNotificationObjectWithName(self, name):
+        if self._notificationNames is not None:
+            self._notificationNames.remove(self._nameToUID(name))
         return self.removeNotificationObjectWithUID(self._nameToUID(name))
 
     _removeByUIDQuery = Delete(
@@ -5271,6 +5529,11 @@
 
 
 class NotificationObject(FancyEqMixin, object):
+    """
+    This used to store XML data and an XML element for the type. But we are now switching it
+    to use JSON internally. The app layer will convert that to XML and fill in the "blanks" as
+    needed for the app.
+    """
     log = Logger()
 
     implements(INotificationObject)
@@ -5290,8 +5553,8 @@
         self._size = None
         self._created = None
         self._modified = None
-        self._xmlType = None
-        self._objectText = None
+        self._notificationType = None
+        self._notificationData = None
 
 
     def __repr__(self):
@@ -5304,12 +5567,12 @@
         DAL query to load all columns by home ID.
         """
         obj = cls._objectSchema
-        return Select([obj.RESOURCE_ID, obj.NOTIFICATION_UID, obj.MD5,
-                       Len(obj.XML_DATA), obj.XML_TYPE, obj.CREATED,
-                       obj.MODIFIED],
-                      From=obj,
-                      Where=(obj.NOTIFICATION_HOME_RESOURCE_ID == Parameter(
-                          "homeID")))
+        return Select(
+            [obj.RESOURCE_ID, obj.NOTIFICATION_UID, obj.MD5,
+             Len(obj.NOTIFICATION_DATA), obj.NOTIFICATION_TYPE, obj.CREATED, obj.MODIFIED],
+            From=obj,
+            Where=(obj.NOTIFICATION_HOME_RESOURCE_ID == Parameter("homeID"))
+        )
 
 
     @classmethod
@@ -5346,9 +5609,13 @@
              child._uid,
              child._md5,
              child._size,
-             child._xmlType,
+             child._notificationType,
              child._created,
              child._modified,) = tuple(row)
+            try:
+                child._notificationType = json.loads(child._notificationType)
+            except ValueError:
+                pass
             child._loadPropertyStore(
                 props=propertyStores.get(child._resourceID, None)
             )
@@ -5364,8 +5631,8 @@
             [
                 no.RESOURCE_ID,
                 no.MD5,
-                Len(no.XML_DATA),
-                no.XML_TYPE,
+                Len(no.NOTIFICATION_DATA),
+                no.NOTIFICATION_TYPE,
                 no.CREATED,
                 no.MODIFIED
             ],
@@ -5390,9 +5657,13 @@
             (self._resourceID,
              self._md5,
              self._size,
-             self._xmlType,
+             self._notificationType,
              self._created,
              self._modified,) = tuple(rows[0])
+            try:
+                self._notificationType = json.loads(self._notificationType)
+            except ValueError:
+                pass
             self._loadPropertyStore()
             returnValue(self)
         else:
@@ -5443,8 +5714,8 @@
             {
                 no.NOTIFICATION_HOME_RESOURCE_ID: Parameter("homeID"),
                 no.NOTIFICATION_UID: Parameter("uid"),
-                no.XML_TYPE: Parameter("xmlType"),
-                no.XML_DATA: Parameter("xmlData"),
+                no.NOTIFICATION_TYPE: Parameter("notificationType"),
+                no.NOTIFICATION_DATA: Parameter("notificationData"),
                 no.MD5: Parameter("md5"),
             },
             Return=[no.RESOURCE_ID, no.CREATED, no.MODIFIED]
@@ -5456,8 +5727,8 @@
         no = cls._objectSchema
         return Update(
             {
-                no.XML_TYPE: Parameter("xmlType"),
-                no.XML_DATA: Parameter("xmlData"),
+                no.NOTIFICATION_TYPE: Parameter("notificationType"),
+                no.NOTIFICATION_DATA: Parameter("notificationData"),
                 no.MD5: Parameter("md5"),
             },
             Where=(no.NOTIFICATION_HOME_RESOURCE_ID == Parameter("homeID")).And(
@@ -5467,41 +5738,46 @@
 
 
     @inlineCallbacks
-    def setData(self, uid, xmltype, xmldata, inserting=False):
+    def setData(self, uid, notificationtype, notificationdata, inserting=False):
         """
         Set the object resource data and update and cached metadata.
         """
 
-        self._xmlType = NotificationType(xmltype)
-        self._md5 = hashlib.md5(xmldata).hexdigest()
-        self._size = len(xmldata)
+        notificationtext = json.dumps(notificationdata)
+        self._notificationType = notificationtype
+        self._md5 = hashlib.md5(notificationtext).hexdigest()
+        self._size = len(notificationtext)
         if inserting:
             rows = yield self._newNotificationQuery.on(
                 self._txn, homeID=self._home._resourceID, uid=uid,
-                xmlType=self._xmlType.toxml(), xmlData=xmldata, md5=self._md5
+                notificationType=json.dumps(self._notificationType),
+                notificationData=notificationtext, md5=self._md5
             )
             self._resourceID, self._created, self._modified = rows[0]
             self._loadPropertyStore()
         else:
             rows = yield self._updateNotificationQuery.on(
                 self._txn, homeID=self._home._resourceID, uid=uid,
-                xmlType=self._xmlType.toxml(), xmlData=xmldata, md5=self._md5
+                notificationType=json.dumps(self._notificationType),
+                notificationData=notificationtext, md5=self._md5
             )
             self._modified = rows[0][0]
-        self._objectText = xmldata
+        self._notificationData = notificationdata
 
-    _xmlDataFromID = Select(
-        [_objectSchema.XML_DATA], From=_objectSchema,
+    _notificationDataFromID = Select(
+        [_objectSchema.NOTIFICATION_DATA], From=_objectSchema,
         Where=_objectSchema.RESOURCE_ID == Parameter("resourceID"))
 
 
     @inlineCallbacks
-    def xmldata(self):
-        if self._objectText is None:
-            self._objectText = (
-                yield self._xmlDataFromID.on(
-                    self._txn, resourceID=self._resourceID))[0][0]
-        returnValue(self._objectText)
+    def notificationData(self):
+        if self._notificationData is None:
+            self._notificationData = (yield self._notificationDataFromID.on(self._txn, resourceID=self._resourceID))[0][0]
+            try:
+                self._notificationData = json.loads(self._notificationData)
+            except ValueError:
+                pass
+        returnValue(self._notificationData)
 
 
     def contentType(self):
@@ -5519,15 +5795,10 @@
         return self._size
 
 
-    def xmlType(self):
-        # NB This is the NotificationType property element
-        if isinstance(self._xmlType, str):
-            # Convert into NotificationType property element
-            self._xmlType = WebDAVDocument.fromString(self._xmlType).root_element
+    def notificationType(self):
+        return self._notificationType
 
-        return self._xmlType
 
-
     def created(self):
         return datetimeMktime(parseSQLTimestamp(self._created))
 

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current-oracle-dialect.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current-oracle-dialect.sql	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current-oracle-dialect.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -49,15 +49,16 @@
 
 create table NOTIFICATION_HOME (
     "RESOURCE_ID" integer primary key,
-    "OWNER_UID" nvarchar2(255) unique
+    "OWNER_UID" nvarchar2(255) unique,
+    "DATAVERSION" integer default 0 not null
 );
 
 create table NOTIFICATION (
     "RESOURCE_ID" integer primary key,
     "NOTIFICATION_HOME_RESOURCE_ID" integer not null references NOTIFICATION_HOME,
     "NOTIFICATION_UID" nvarchar2(255),
-    "XML_TYPE" nvarchar2(255),
-    "XML_DATA" nclob,
+    "NOTIFICATION_TYPE" nvarchar2(255),
+    "NOTIFICATION_DATA" nclob,
     "MD5" nchar(32),
     "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
     "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC', 
@@ -91,6 +92,7 @@
 insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('read', 1);
 insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('write', 2);
 insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('direct', 3);
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('indirect', 4);
 create table CALENDAR_BIND_STATUS (
     "ID" integer primary key,
     "DESCRIPTION" nvarchar2(16) unique
@@ -100,6 +102,7 @@
 insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('accepted', 1);
 insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('declined', 2);
 insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('invalid', 3);
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('deleted', 4);
 create table CALENDAR_TRANSP (
     "ID" integer primary key,
     "DESCRIPTION" nvarchar2(16) unique
@@ -370,9 +373,10 @@
     "VALUE" nvarchar2(255)
 );
 
-insert into CALENDARSERVER (NAME, VALUE) values ('VERSION', '29');
+insert into CALENDARSERVER (NAME, VALUE) values ('VERSION', '30');
 insert into CALENDARSERVER (NAME, VALUE) values ('CALENDAR-DATAVERSION', '5');
 insert into CALENDARSERVER (NAME, VALUE) values ('ADDRESSBOOK-DATAVERSION', '2');
+insert into CALENDARSERVER (NAME, VALUE) values ('NOTIFICATION-DATAVERSION', '1');
 create index CALENDAR_HOME_METADAT_3cb9049e on CALENDAR_HOME_METADATA (
     DEFAULT_EVENTS
 );

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current.sql	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/current.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -109,15 +109,16 @@
 
 create table NOTIFICATION_HOME (
   RESOURCE_ID integer      primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
-  OWNER_UID   varchar(255) not null unique                                 -- implicit index
+  OWNER_UID   varchar(255) not null unique,                                -- implicit index
+  DATAVERSION integer      default 0 not null
 );
 
 create table NOTIFICATION (
   RESOURCE_ID                   integer      primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
   NOTIFICATION_HOME_RESOURCE_ID integer      not null references NOTIFICATION_HOME,
   NOTIFICATION_UID              varchar(255) not null,
-  XML_TYPE                      varchar(255) not null,
-  XML_DATA                      text         not null,
+  NOTIFICATION_TYPE             varchar(255) not null,
+  NOTIFICATION_DATA             text         not null,
   MD5                           char(32)     not null,
   CREATED                       timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
   MODIFIED                      timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
@@ -168,6 +169,7 @@
 insert into CALENDAR_BIND_MODE values (1, 'read' );
 insert into CALENDAR_BIND_MODE values (2, 'write');
 insert into CALENDAR_BIND_MODE values (3, 'direct');
+insert into CALENDAR_BIND_MODE values (4, 'indirect');
 
 -- Enumeration of statuses
 
@@ -180,6 +182,7 @@
 insert into CALENDAR_BIND_STATUS values (1, 'accepted');
 insert into CALENDAR_BIND_STATUS values (2, 'declined');
 insert into CALENDAR_BIND_STATUS values (3, 'invalid');
+insert into CALENDAR_BIND_STATUS values (4, 'deleted');
 
 
 -- Enumeration of transparency
@@ -708,6 +711,7 @@
   VALUE                         varchar(255)
 );
 
-insert into CALENDARSERVER values ('VERSION', '29');
+insert into CALENDARSERVER values ('VERSION', '30');
 insert into CALENDARSERVER values ('CALENDAR-DATAVERSION', '5');
 insert into CALENDARSERVER values ('ADDRESSBOOK-DATAVERSION', '2');
+insert into CALENDARSERVER values ('NOTIFICATION-DATAVERSION', '1');

Added: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/oracle-dialect/v29.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/oracle-dialect/v29.sql	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/oracle-dialect/v29.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,505 @@
+create sequence RESOURCE_ID_SEQ;
+create sequence INSTANCE_ID_SEQ;
+create sequence ATTACHMENT_ID_SEQ;
+create sequence REVISION_SEQ;
+create sequence WORKITEM_SEQ;
+create table NODE_INFO (
+    "HOSTNAME" nvarchar2(255),
+    "PID" integer not null,
+    "PORT" integer not null,
+    "TIME" timestamp default CURRENT_TIMESTAMP at time zone 'UTC' not null, 
+    primary key("HOSTNAME", "PORT")
+);
+
+create table NAMED_LOCK (
+    "LOCK_NAME" nvarchar2(255) primary key
+);
+
+create table CALENDAR_HOME (
+    "RESOURCE_ID" integer primary key,
+    "OWNER_UID" nvarchar2(255) unique,
+    "DATAVERSION" integer default 0 not null
+);
+
+create table CALENDAR (
+    "RESOURCE_ID" integer primary key
+);
+
+create table CALENDAR_HOME_METADATA (
+    "RESOURCE_ID" integer primary key references CALENDAR_HOME on delete cascade,
+    "QUOTA_USED_BYTES" integer default 0 not null,
+    "DEFAULT_EVENTS" integer default null references CALENDAR on delete set null,
+    "DEFAULT_TASKS" integer default null references CALENDAR on delete set null,
+    "DEFAULT_POLLS" integer default null references CALENDAR on delete set null,
+    "ALARM_VEVENT_TIMED" nclob default null,
+    "ALARM_VEVENT_ALLDAY" nclob default null,
+    "ALARM_VTODO_TIMED" nclob default null,
+    "ALARM_VTODO_ALLDAY" nclob default null,
+    "AVAILABILITY" nclob default null,
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
+
+create table CALENDAR_METADATA (
+    "RESOURCE_ID" integer primary key references CALENDAR on delete cascade,
+    "SUPPORTED_COMPONENTS" nvarchar2(255) default null,
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
+
+create table NOTIFICATION_HOME (
+    "RESOURCE_ID" integer primary key,
+    "OWNER_UID" nvarchar2(255) unique,
+    "DATAVERSION" integer default 0 not null
+);
+
+create table NOTIFICATION (
+    "RESOURCE_ID" integer primary key,
+    "NOTIFICATION_HOME_RESOURCE_ID" integer not null references NOTIFICATION_HOME,
+    "NOTIFICATION_UID" nvarchar2(255),
+    "NOTIFICATION_TYPE" nvarchar2(255),
+    "NOTIFICATION_DATA" nclob,
+    "MD5" nchar(32),
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC', 
+    unique("NOTIFICATION_UID", "NOTIFICATION_HOME_RESOURCE_ID")
+);
+
+create table CALENDAR_BIND (
+    "CALENDAR_HOME_RESOURCE_ID" integer not null references CALENDAR_HOME,
+    "CALENDAR_RESOURCE_ID" integer not null references CALENDAR on delete cascade,
+    "CALENDAR_RESOURCE_NAME" nvarchar2(255),
+    "BIND_MODE" integer not null,
+    "BIND_STATUS" integer not null,
+    "BIND_REVISION" integer default 0 not null,
+    "MESSAGE" nclob,
+    "TRANSP" integer default 0 not null,
+    "ALARM_VEVENT_TIMED" nclob default null,
+    "ALARM_VEVENT_ALLDAY" nclob default null,
+    "ALARM_VTODO_TIMED" nclob default null,
+    "ALARM_VTODO_ALLDAY" nclob default null,
+    "TIMEZONE" nclob default null, 
+    primary key("CALENDAR_HOME_RESOURCE_ID", "CALENDAR_RESOURCE_ID"), 
+    unique("CALENDAR_HOME_RESOURCE_ID", "CALENDAR_RESOURCE_NAME")
+);
+
+create table CALENDAR_BIND_MODE (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(16) unique
+);
+
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('own', 0);
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('read', 1);
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('write', 2);
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('direct', 3);
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('indirect', 4);
+create table CALENDAR_BIND_STATUS (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(16) unique
+);
+
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('invited', 0);
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('accepted', 1);
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('declined', 2);
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('invalid', 3);
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('deleted', 4);
+create table CALENDAR_TRANSP (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(16) unique
+);
+
+insert into CALENDAR_TRANSP (DESCRIPTION, ID) values ('opaque', 0);
+insert into CALENDAR_TRANSP (DESCRIPTION, ID) values ('transparent', 1);
+create table CALENDAR_OBJECT (
+    "RESOURCE_ID" integer primary key,
+    "CALENDAR_RESOURCE_ID" integer not null references CALENDAR on delete cascade,
+    "RESOURCE_NAME" nvarchar2(255),
+    "ICALENDAR_TEXT" nclob,
+    "ICALENDAR_UID" nvarchar2(255),
+    "ICALENDAR_TYPE" nvarchar2(255),
+    "ATTACHMENTS_MODE" integer default 0 not null,
+    "DROPBOX_ID" nvarchar2(255),
+    "ORGANIZER" nvarchar2(255),
+    "RECURRANCE_MIN" date,
+    "RECURRANCE_MAX" date,
+    "ACCESS" integer default 0 not null,
+    "SCHEDULE_OBJECT" integer default 0,
+    "SCHEDULE_TAG" nvarchar2(36) default null,
+    "SCHEDULE_ETAGS" nclob default null,
+    "PRIVATE_COMMENTS" integer default 0 not null,
+    "MD5" nchar(32),
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC', 
+    unique("CALENDAR_RESOURCE_ID", "RESOURCE_NAME")
+);
+
+create table CALENDAR_OBJECT_ATTACHMENTS_MO (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(16) unique
+);
+
+insert into CALENDAR_OBJECT_ATTACHMENTS_MO (DESCRIPTION, ID) values ('none', 0);
+insert into CALENDAR_OBJECT_ATTACHMENTS_MO (DESCRIPTION, ID) values ('read', 1);
+insert into CALENDAR_OBJECT_ATTACHMENTS_MO (DESCRIPTION, ID) values ('write', 2);
+create table CALENDAR_ACCESS_TYPE (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(32) unique
+);
+
+insert into CALENDAR_ACCESS_TYPE (DESCRIPTION, ID) values ('', 0);
+insert into CALENDAR_ACCESS_TYPE (DESCRIPTION, ID) values ('public', 1);
+insert into CALENDAR_ACCESS_TYPE (DESCRIPTION, ID) values ('private', 2);
+insert into CALENDAR_ACCESS_TYPE (DESCRIPTION, ID) values ('confidential', 3);
+insert into CALENDAR_ACCESS_TYPE (DESCRIPTION, ID) values ('restricted', 4);
+create table TIME_RANGE (
+    "INSTANCE_ID" integer primary key,
+    "CALENDAR_RESOURCE_ID" integer not null references CALENDAR on delete cascade,
+    "CALENDAR_OBJECT_RESOURCE_ID" integer not null references CALENDAR_OBJECT on delete cascade,
+    "FLOATING" integer not null,
+    "START_DATE" timestamp not null,
+    "END_DATE" timestamp not null,
+    "FBTYPE" integer not null,
+    "TRANSPARENT" integer not null
+);
+
+create table FREE_BUSY_TYPE (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(16) unique
+);
+
+insert into FREE_BUSY_TYPE (DESCRIPTION, ID) values ('unknown', 0);
+insert into FREE_BUSY_TYPE (DESCRIPTION, ID) values ('free', 1);
+insert into FREE_BUSY_TYPE (DESCRIPTION, ID) values ('busy', 2);
+insert into FREE_BUSY_TYPE (DESCRIPTION, ID) values ('busy-unavailable', 3);
+insert into FREE_BUSY_TYPE (DESCRIPTION, ID) values ('busy-tentative', 4);
+create table TRANSPARENCY (
+    "TIME_RANGE_INSTANCE_ID" integer not null references TIME_RANGE on delete cascade,
+    "USER_ID" nvarchar2(255),
+    "TRANSPARENT" integer not null
+);
+
+create table ATTACHMENT (
+    "ATTACHMENT_ID" integer primary key,
+    "CALENDAR_HOME_RESOURCE_ID" integer not null references CALENDAR_HOME,
+    "DROPBOX_ID" nvarchar2(255),
+    "CONTENT_TYPE" nvarchar2(255),
+    "SIZE" integer not null,
+    "MD5" nchar(32),
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "PATH" nvarchar2(1024)
+);
+
+create table ATTACHMENT_CALENDAR_OBJECT (
+    "ATTACHMENT_ID" integer not null references ATTACHMENT on delete cascade,
+    "MANAGED_ID" nvarchar2(255),
+    "CALENDAR_OBJECT_RESOURCE_ID" integer not null references CALENDAR_OBJECT on delete cascade, 
+    primary key("ATTACHMENT_ID", "CALENDAR_OBJECT_RESOURCE_ID"), 
+    unique("MANAGED_ID", "CALENDAR_OBJECT_RESOURCE_ID")
+);
+
+create table RESOURCE_PROPERTY (
+    "RESOURCE_ID" integer not null,
+    "NAME" nvarchar2(255),
+    "VALUE" nclob,
+    "VIEWER_UID" nvarchar2(255), 
+    primary key("RESOURCE_ID", "NAME", "VIEWER_UID")
+);
+
+create table ADDRESSBOOK_HOME (
+    "RESOURCE_ID" integer primary key,
+    "ADDRESSBOOK_PROPERTY_STORE_ID" integer not null,
+    "OWNER_UID" nvarchar2(255) unique,
+    "DATAVERSION" integer default 0 not null
+);
+
+create table ADDRESSBOOK_HOME_METADATA (
+    "RESOURCE_ID" integer primary key references ADDRESSBOOK_HOME on delete cascade,
+    "QUOTA_USED_BYTES" integer default 0 not null,
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
+
+create table SHARED_ADDRESSBOOK_BIND (
+    "ADDRESSBOOK_HOME_RESOURCE_ID" integer not null references ADDRESSBOOK_HOME,
+    "OWNER_HOME_RESOURCE_ID" integer not null references ADDRESSBOOK_HOME on delete cascade,
+    "ADDRESSBOOK_RESOURCE_NAME" nvarchar2(255),
+    "BIND_MODE" integer not null,
+    "BIND_STATUS" integer not null,
+    "BIND_REVISION" integer default 0 not null,
+    "MESSAGE" nclob, 
+    primary key("ADDRESSBOOK_HOME_RESOURCE_ID", "OWNER_HOME_RESOURCE_ID"), 
+    unique("ADDRESSBOOK_HOME_RESOURCE_ID", "ADDRESSBOOK_RESOURCE_NAME")
+);
+
+create table ADDRESSBOOK_OBJECT (
+    "RESOURCE_ID" integer primary key,
+    "ADDRESSBOOK_HOME_RESOURCE_ID" integer not null references ADDRESSBOOK_HOME on delete cascade,
+    "RESOURCE_NAME" nvarchar2(255),
+    "VCARD_TEXT" nclob,
+    "VCARD_UID" nvarchar2(255),
+    "KIND" integer not null,
+    "MD5" nchar(32),
+    "CREATED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "MODIFIED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC', 
+    unique("ADDRESSBOOK_HOME_RESOURCE_ID", "RESOURCE_NAME"), 
+    unique("ADDRESSBOOK_HOME_RESOURCE_ID", "VCARD_UID")
+);
+
+create table ADDRESSBOOK_OBJECT_KIND (
+    "ID" integer primary key,
+    "DESCRIPTION" nvarchar2(16) unique
+);
+
+insert into ADDRESSBOOK_OBJECT_KIND (DESCRIPTION, ID) values ('person', 0);
+insert into ADDRESSBOOK_OBJECT_KIND (DESCRIPTION, ID) values ('group', 1);
+insert into ADDRESSBOOK_OBJECT_KIND (DESCRIPTION, ID) values ('resource', 2);
+insert into ADDRESSBOOK_OBJECT_KIND (DESCRIPTION, ID) values ('location', 3);
+create table ABO_MEMBERS (
+    "GROUP_ID" integer not null references ADDRESSBOOK_OBJECT on delete cascade,
+    "ADDRESSBOOK_ID" integer not null references ADDRESSBOOK_HOME on delete cascade,
+    "MEMBER_ID" integer not null references ADDRESSBOOK_OBJECT, 
+    primary key("GROUP_ID", "MEMBER_ID")
+);
+
+create table ABO_FOREIGN_MEMBERS (
+    "GROUP_ID" integer not null references ADDRESSBOOK_OBJECT on delete cascade,
+    "ADDRESSBOOK_ID" integer not null references ADDRESSBOOK_HOME on delete cascade,
+    "MEMBER_ADDRESS" nvarchar2(255), 
+    primary key("GROUP_ID", "MEMBER_ADDRESS")
+);
+
+create table SHARED_GROUP_BIND (
+    "ADDRESSBOOK_HOME_RESOURCE_ID" integer not null references ADDRESSBOOK_HOME,
+    "GROUP_RESOURCE_ID" integer not null references ADDRESSBOOK_OBJECT on delete cascade,
+    "GROUP_ADDRESSBOOK_NAME" nvarchar2(255),
+    "BIND_MODE" integer not null,
+    "BIND_STATUS" integer not null,
+    "BIND_REVISION" integer default 0 not null,
+    "MESSAGE" nclob, 
+    primary key("ADDRESSBOOK_HOME_RESOURCE_ID", "GROUP_RESOURCE_ID"), 
+    unique("ADDRESSBOOK_HOME_RESOURCE_ID", "GROUP_ADDRESSBOOK_NAME")
+);
+
+create table CALENDAR_OBJECT_REVISIONS (
+    "CALENDAR_HOME_RESOURCE_ID" integer not null references CALENDAR_HOME,
+    "CALENDAR_RESOURCE_ID" integer references CALENDAR,
+    "CALENDAR_NAME" nvarchar2(255) default null,
+    "RESOURCE_NAME" nvarchar2(255),
+    "REVISION" integer not null,
+    "DELETED" integer not null
+);
+
+create table ADDRESSBOOK_OBJECT_REVISIONS (
+    "ADDRESSBOOK_HOME_RESOURCE_ID" integer not null references ADDRESSBOOK_HOME,
+    "OWNER_HOME_RESOURCE_ID" integer references ADDRESSBOOK_HOME,
+    "ADDRESSBOOK_NAME" nvarchar2(255) default null,
+    "RESOURCE_NAME" nvarchar2(255),
+    "REVISION" integer not null,
+    "DELETED" integer not null
+);
+
+create table NOTIFICATION_OBJECT_REVISIONS (
+    "NOTIFICATION_HOME_RESOURCE_ID" integer not null references NOTIFICATION_HOME on delete cascade,
+    "RESOURCE_NAME" nvarchar2(255),
+    "REVISION" integer not null,
+    "DELETED" integer not null, 
+    unique("NOTIFICATION_HOME_RESOURCE_ID", "RESOURCE_NAME")
+);
+
+create table APN_SUBSCRIPTIONS (
+    "TOKEN" nvarchar2(255),
+    "RESOURCE_KEY" nvarchar2(255),
+    "MODIFIED" integer not null,
+    "SUBSCRIBER_GUID" nvarchar2(255),
+    "USER_AGENT" nvarchar2(255) default null,
+    "IP_ADDR" nvarchar2(255) default null, 
+    primary key("TOKEN", "RESOURCE_KEY")
+);
+
+create table IMIP_TOKENS (
+    "TOKEN" nvarchar2(255),
+    "ORGANIZER" nvarchar2(255),
+    "ATTENDEE" nvarchar2(255),
+    "ICALUID" nvarchar2(255),
+    "ACCESSED" timestamp default CURRENT_TIMESTAMP at time zone 'UTC', 
+    primary key("ORGANIZER", "ATTENDEE", "ICALUID")
+);
+
+create table IMIP_INVITATION_WORK (
+    "WORK_ID" integer primary key not null,
+    "NOT_BEFORE" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "FROM_ADDR" nvarchar2(255),
+    "TO_ADDR" nvarchar2(255),
+    "ICALENDAR_TEXT" nclob
+);
+
+create table IMIP_POLLING_WORK (
+    "WORK_ID" integer primary key not null,
+    "NOT_BEFORE" timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
+
+create table IMIP_REPLY_WORK (
+    "WORK_ID" integer primary key not null,
+    "NOT_BEFORE" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "ORGANIZER" nvarchar2(255),
+    "ATTENDEE" nvarchar2(255),
+    "ICALENDAR_TEXT" nclob
+);
+
+create table PUSH_NOTIFICATION_WORK (
+    "WORK_ID" integer primary key not null,
+    "NOT_BEFORE" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "PUSH_ID" nvarchar2(255),
+    "PRIORITY" integer not null
+);
+
+create table GROUP_CACHER_POLLING_WORK (
+    "WORK_ID" integer primary key not null,
+    "NOT_BEFORE" timestamp default CURRENT_TIMESTAMP at time zone 'UTC'
+);
+
+create table CALENDAR_OBJECT_SPLITTER_WORK (
+    "WORK_ID" integer primary key not null,
+    "NOT_BEFORE" timestamp default CURRENT_TIMESTAMP at time zone 'UTC',
+    "RESOURCE_ID" integer not null references CALENDAR_OBJECT on delete cascade
+);
+
+create table CALENDARSERVER (
+    "NAME" nvarchar2(255) primary key,
+    "VALUE" nvarchar2(255)
+);
+
+insert into CALENDARSERVER (NAME, VALUE) values ('VERSION', '29');
+insert into CALENDARSERVER (NAME, VALUE) values ('CALENDAR-DATAVERSION', '5');
+insert into CALENDARSERVER (NAME, VALUE) values ('ADDRESSBOOK-DATAVERSION', '2');
+insert into CALENDARSERVER (NAME, VALUE) values ('NOTIFICATION-DATAVERSION', '1');
+create index CALENDAR_HOME_METADAT_3cb9049e on CALENDAR_HOME_METADATA (
+    DEFAULT_EVENTS
+);
+
+create index CALENDAR_HOME_METADAT_d55e5548 on CALENDAR_HOME_METADATA (
+    DEFAULT_TASKS
+);
+
+create index CALENDAR_HOME_METADAT_910264ce on CALENDAR_HOME_METADATA (
+    DEFAULT_POLLS
+);
+
+create index NOTIFICATION_NOTIFICA_f891f5f9 on NOTIFICATION (
+    NOTIFICATION_HOME_RESOURCE_ID
+);
+
+create index CALENDAR_BIND_RESOURC_e57964d4 on CALENDAR_BIND (
+    CALENDAR_RESOURCE_ID
+);
+
+create index CALENDAR_OBJECT_CALEN_a9a453a9 on CALENDAR_OBJECT (
+    CALENDAR_RESOURCE_ID,
+    ICALENDAR_UID
+);
+
+create index CALENDAR_OBJECT_CALEN_96e83b73 on CALENDAR_OBJECT (
+    CALENDAR_RESOURCE_ID,
+    RECURRANCE_MAX
+);
+
+create index CALENDAR_OBJECT_ICALE_82e731d5 on CALENDAR_OBJECT (
+    ICALENDAR_UID
+);
+
+create index CALENDAR_OBJECT_DROPB_de041d80 on CALENDAR_OBJECT (
+    DROPBOX_ID
+);
+
+create index TIME_RANGE_CALENDAR_R_beb6e7eb on TIME_RANGE (
+    CALENDAR_RESOURCE_ID
+);
+
+create index TIME_RANGE_CALENDAR_O_acf37bd1 on TIME_RANGE (
+    CALENDAR_OBJECT_RESOURCE_ID
+);
+
+create index TRANSPARENCY_TIME_RAN_5f34467f on TRANSPARENCY (
+    TIME_RANGE_INSTANCE_ID
+);
+
+create index ATTACHMENT_CALENDAR_H_0078845c on ATTACHMENT (
+    CALENDAR_HOME_RESOURCE_ID
+);
+
+create index ATTACHMENT_CALENDAR_O_81508484 on ATTACHMENT_CALENDAR_OBJECT (
+    CALENDAR_OBJECT_RESOURCE_ID
+);
+
+create index SHARED_ADDRESSBOOK_BI_e9a2e6d4 on SHARED_ADDRESSBOOK_BIND (
+    OWNER_HOME_RESOURCE_ID
+);
+
+create index ABO_MEMBERS_ADDRESSBO_4effa879 on ABO_MEMBERS (
+    ADDRESSBOOK_ID
+);
+
+create index ABO_MEMBERS_MEMBER_ID_8d66adcf on ABO_MEMBERS (
+    MEMBER_ID
+);
+
+create index ABO_FOREIGN_MEMBERS_A_1fd2c5e9 on ABO_FOREIGN_MEMBERS (
+    ADDRESSBOOK_ID
+);
+
+create index SHARED_GROUP_BIND_RES_cf52f95d on SHARED_GROUP_BIND (
+    GROUP_RESOURCE_ID
+);
+
+create index CALENDAR_OBJECT_REVIS_3a3956c4 on CALENDAR_OBJECT_REVISIONS (
+    CALENDAR_HOME_RESOURCE_ID,
+    CALENDAR_RESOURCE_ID
+);
+
+create index CALENDAR_OBJECT_REVIS_6d9d929c on CALENDAR_OBJECT_REVISIONS (
+    CALENDAR_RESOURCE_ID,
+    RESOURCE_NAME,
+    DELETED,
+    REVISION
+);
+
+create index CALENDAR_OBJECT_REVIS_265c8acf on CALENDAR_OBJECT_REVISIONS (
+    CALENDAR_RESOURCE_ID,
+    REVISION
+);
+
+create index ADDRESSBOOK_OBJECT_RE_2bfcf757 on ADDRESSBOOK_OBJECT_REVISIONS (
+    ADDRESSBOOK_HOME_RESOURCE_ID,
+    OWNER_HOME_RESOURCE_ID
+);
+
+create index ADDRESSBOOK_OBJECT_RE_00fe8288 on ADDRESSBOOK_OBJECT_REVISIONS (
+    OWNER_HOME_RESOURCE_ID,
+    RESOURCE_NAME,
+    DELETED,
+    REVISION
+);
+
+create index ADDRESSBOOK_OBJECT_RE_45004780 on ADDRESSBOOK_OBJECT_REVISIONS (
+    OWNER_HOME_RESOURCE_ID,
+    REVISION
+);
+
+create index NOTIFICATION_OBJECT_R_036a9cee on NOTIFICATION_OBJECT_REVISIONS (
+    NOTIFICATION_HOME_RESOURCE_ID,
+    REVISION
+);
+
+create index APN_SUBSCRIPTIONS_RES_9610d78e on APN_SUBSCRIPTIONS (
+    RESOURCE_KEY
+);
+
+create index IMIP_TOKENS_TOKEN_e94b918f on IMIP_TOKENS (
+    TOKEN
+);
+
+create index CALENDAR_OBJECT_SPLIT_af71dcda on CALENDAR_OBJECT_SPLITTER_WORK (
+    RESOURCE_ID
+);
+

Added: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/postgres-dialect/v29.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/postgres-dialect/v29.sql	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/old/postgres-dialect/v29.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,708 @@
+-- -*- test-case-name: txdav.caldav.datastore.test.test_sql,txdav.carddav.datastore.test.test_sql -*-
+
+----
+-- Copyright (c) 2010-2013 Apple Inc. All rights reserved.
+--
+-- Licensed under the Apache License, Version 2.0 (the "License");
+-- you may not use this file except in compliance with the License.
+-- You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+----
+
+
+-----------------
+-- Resource ID --
+-----------------
+
+create sequence RESOURCE_ID_SEQ;
+
+
+-------------------------
+-- Cluster Bookkeeping --
+-------------------------
+
+-- Information about a process connected to this database.
+
+-- Note that this must match the node info schema in twext.enterprise.queue.
+create table NODE_INFO (
+  HOSTNAME  varchar(255) not null,
+  PID       integer      not null,
+  PORT      integer      not null,
+  TIME      timestamp    not null default timezone('UTC', CURRENT_TIMESTAMP),
+
+  primary key (HOSTNAME, PORT)
+);
+
+-- Unique named locks.  This table should always be empty, but rows are
+-- temporarily created in order to prevent undesirable concurrency.
+create table NAMED_LOCK (
+    LOCK_NAME varchar(255) primary key
+);
+
+
+-------------------
+-- Calendar Home --
+-------------------
+
+create table CALENDAR_HOME (
+  RESOURCE_ID      integer      primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
+  OWNER_UID        varchar(255) not null unique,                                 -- implicit index
+  DATAVERSION      integer      default 0 not null
+);
+
+--------------
+-- Calendar --
+--------------
+
+create table CALENDAR (
+  RESOURCE_ID integer   primary key default nextval('RESOURCE_ID_SEQ') -- implicit index
+);
+
+----------------------------
+-- Calendar Home Metadata --
+----------------------------
+
+create table CALENDAR_HOME_METADATA (
+  RESOURCE_ID              integer     primary key references CALENDAR_HOME on delete cascade, -- implicit index
+  QUOTA_USED_BYTES         integer     default 0 not null,
+  DEFAULT_EVENTS           integer     default null references CALENDAR on delete set null,
+  DEFAULT_TASKS            integer     default null references CALENDAR on delete set null,
+  DEFAULT_POLLS            integer     default null references CALENDAR on delete set null,
+  ALARM_VEVENT_TIMED       text        default null,
+  ALARM_VEVENT_ALLDAY      text        default null,
+  ALARM_VTODO_TIMED        text        default null,
+  ALARM_VTODO_ALLDAY       text        default null,
+  AVAILABILITY             text        default null,
+  CREATED                  timestamp   default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED                 timestamp   default timezone('UTC', CURRENT_TIMESTAMP)
+);
+
+create index CALENDAR_HOME_METADATA_DEFAULT_EVENTS on
+	CALENDAR_HOME_METADATA(DEFAULT_EVENTS);
+create index CALENDAR_HOME_METADATA_DEFAULT_TASKS on
+	CALENDAR_HOME_METADATA(DEFAULT_TASKS);
+create index CALENDAR_HOME_METADATA_DEFAULT_POLLS on
+	CALENDAR_HOME_METADATA(DEFAULT_POLLS);
+
+-----------------------
+-- Calendar Metadata --
+-----------------------
+
+create table CALENDAR_METADATA (
+  RESOURCE_ID           integer      primary key references CALENDAR on delete cascade, -- implicit index
+  SUPPORTED_COMPONENTS  varchar(255) default null,
+  CREATED               timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED              timestamp    default timezone('UTC', CURRENT_TIMESTAMP)
+);
+
+
+---------------------------
+-- Sharing Notifications --
+---------------------------
+
+create table NOTIFICATION_HOME (
+  RESOURCE_ID integer      primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
+  OWNER_UID   varchar(255) not null unique,                                -- implicit index
+  DATAVERSION integer      default 0 not null
+);
+
+create table NOTIFICATION (
+  RESOURCE_ID                   integer      primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
+  NOTIFICATION_HOME_RESOURCE_ID integer      not null references NOTIFICATION_HOME,
+  NOTIFICATION_UID              varchar(255) not null,
+  NOTIFICATION_TYPE             varchar(255) not null,
+  NOTIFICATION_DATA             text         not null,
+  MD5                           char(32)     not null,
+  CREATED                       timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED                      timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+
+  unique(NOTIFICATION_UID, NOTIFICATION_HOME_RESOURCE_ID) -- implicit index
+);
+
+create index NOTIFICATION_NOTIFICATION_HOME_RESOURCE_ID on
+	NOTIFICATION(NOTIFICATION_HOME_RESOURCE_ID);
+
+
+-------------------
+-- Calendar Bind --
+-------------------
+
+-- Joins CALENDAR_HOME and CALENDAR
+
+create table CALENDAR_BIND (
+  CALENDAR_HOME_RESOURCE_ID integer      not null references CALENDAR_HOME,
+  CALENDAR_RESOURCE_ID      integer      not null references CALENDAR on delete cascade,
+  CALENDAR_RESOURCE_NAME    varchar(255) not null,
+  BIND_MODE                 integer      not null, -- enum CALENDAR_BIND_MODE
+  BIND_STATUS               integer      not null, -- enum CALENDAR_BIND_STATUS
+  BIND_REVISION				integer      default 0 not null,
+  MESSAGE                   text,
+  TRANSP                    integer      default 0 not null, -- enum CALENDAR_TRANSP
+  ALARM_VEVENT_TIMED        text         default null,
+  ALARM_VEVENT_ALLDAY       text         default null,
+  ALARM_VTODO_TIMED         text         default null,
+  ALARM_VTODO_ALLDAY        text         default null,
+  TIMEZONE                  text         default null,
+
+  primary key(CALENDAR_HOME_RESOURCE_ID, CALENDAR_RESOURCE_ID), -- implicit index
+  unique(CALENDAR_HOME_RESOURCE_ID, CALENDAR_RESOURCE_NAME)     -- implicit index
+);
+
+create index CALENDAR_BIND_RESOURCE_ID on
+	CALENDAR_BIND(CALENDAR_RESOURCE_ID);
+
+-- Enumeration of calendar bind modes
+
+create table CALENDAR_BIND_MODE (
+  ID          integer     primary key,
+  DESCRIPTION varchar(16) not null unique
+);
+
+insert into CALENDAR_BIND_MODE values (0, 'own'  );
+insert into CALENDAR_BIND_MODE values (1, 'read' );
+insert into CALENDAR_BIND_MODE values (2, 'write');
+insert into CALENDAR_BIND_MODE values (3, 'direct');
+insert into CALENDAR_BIND_MODE values (4, 'indirect');
+
+-- Enumeration of statuses
+
+create table CALENDAR_BIND_STATUS (
+  ID          integer     primary key,
+  DESCRIPTION varchar(16) not null unique
+);
+
+insert into CALENDAR_BIND_STATUS values (0, 'invited' );
+insert into CALENDAR_BIND_STATUS values (1, 'accepted');
+insert into CALENDAR_BIND_STATUS values (2, 'declined');
+insert into CALENDAR_BIND_STATUS values (3, 'invalid');
+insert into CALENDAR_BIND_STATUS values (4, 'deleted');
+
+
+-- Enumeration of transparency
+
+create table CALENDAR_TRANSP (
+  ID          integer     primary key,
+  DESCRIPTION varchar(16) not null unique
+);
+
+insert into CALENDAR_TRANSP values (0, 'opaque' );
+insert into CALENDAR_TRANSP values (1, 'transparent');
+
+
+---------------------
+-- Calendar Object --
+---------------------
+
+create table CALENDAR_OBJECT (
+  RESOURCE_ID          integer      primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
+  CALENDAR_RESOURCE_ID integer      not null references CALENDAR on delete cascade,
+  RESOURCE_NAME        varchar(255) not null,
+  ICALENDAR_TEXT       text         not null,
+  ICALENDAR_UID        varchar(255) not null,
+  ICALENDAR_TYPE       varchar(255) not null,
+  ATTACHMENTS_MODE     integer      default 0 not null, -- enum CALENDAR_OBJECT_ATTACHMENTS_MODE
+  DROPBOX_ID           varchar(255),
+  ORGANIZER            varchar(255),
+  RECURRANCE_MIN       date,        -- minimum date that recurrences have been expanded to.
+  RECURRANCE_MAX       date,        -- maximum date that recurrences have been expanded to.
+  ACCESS               integer      default 0 not null,
+  SCHEDULE_OBJECT      boolean      default false,
+  SCHEDULE_TAG         varchar(36)  default null,
+  SCHEDULE_ETAGS       text         default null,
+  PRIVATE_COMMENTS     boolean      default false not null,
+  MD5                  char(32)     not null,
+  CREATED              timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED             timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+
+  unique (CALENDAR_RESOURCE_ID, RESOURCE_NAME) -- implicit index
+
+  -- since the 'inbox' is a 'calendar resource' for the purpose of storing
+  -- calendar objects, this constraint has to be selectively enforced by the
+  -- application layer.
+
+  -- unique(CALENDAR_RESOURCE_ID, ICALENDAR_UID)
+);
+
+create index CALENDAR_OBJECT_CALENDAR_RESOURCE_ID_AND_ICALENDAR_UID on
+  CALENDAR_OBJECT(CALENDAR_RESOURCE_ID, ICALENDAR_UID);
+
+create index CALENDAR_OBJECT_CALENDAR_RESOURCE_ID_RECURRANCE_MAX on
+  CALENDAR_OBJECT(CALENDAR_RESOURCE_ID, RECURRANCE_MAX);
+
+create index CALENDAR_OBJECT_ICALENDAR_UID on
+  CALENDAR_OBJECT(ICALENDAR_UID);
+
+create index CALENDAR_OBJECT_DROPBOX_ID on
+  CALENDAR_OBJECT(DROPBOX_ID);
+
+-- Enumeration of attachment modes
+
+create table CALENDAR_OBJECT_ATTACHMENTS_MODE (
+  ID          integer     primary key,
+  DESCRIPTION varchar(16) not null unique
+);
+
+insert into CALENDAR_OBJECT_ATTACHMENTS_MODE values (0, 'none' );
+insert into CALENDAR_OBJECT_ATTACHMENTS_MODE values (1, 'read' );
+insert into CALENDAR_OBJECT_ATTACHMENTS_MODE values (2, 'write');
+
+
+-- Enumeration of calendar access types
+
+create table CALENDAR_ACCESS_TYPE (
+  ID          integer     primary key,
+  DESCRIPTION varchar(32) not null unique
+);
+
+insert into CALENDAR_ACCESS_TYPE values (0, ''             );
+insert into CALENDAR_ACCESS_TYPE values (1, 'public'       );
+insert into CALENDAR_ACCESS_TYPE values (2, 'private'      );
+insert into CALENDAR_ACCESS_TYPE values (3, 'confidential' );
+insert into CALENDAR_ACCESS_TYPE values (4, 'restricted'   );
+
+
+-----------------
+-- Instance ID --
+-----------------
+
+create sequence INSTANCE_ID_SEQ;
+
+
+----------------
+-- Time Range --
+----------------
+
+create table TIME_RANGE (
+  INSTANCE_ID                 integer        primary key default nextval('INSTANCE_ID_SEQ'), -- implicit index
+  CALENDAR_RESOURCE_ID        integer        not null references CALENDAR on delete cascade,
+  CALENDAR_OBJECT_RESOURCE_ID integer        not null references CALENDAR_OBJECT on delete cascade,
+  FLOATING                    boolean        not null,
+  START_DATE                  timestamp      not null,
+  END_DATE                    timestamp      not null,
+  FBTYPE                      integer        not null,
+  TRANSPARENT                 boolean        not null
+);
+
+create index TIME_RANGE_CALENDAR_RESOURCE_ID on
+  TIME_RANGE(CALENDAR_RESOURCE_ID);
+create index TIME_RANGE_CALENDAR_OBJECT_RESOURCE_ID on
+  TIME_RANGE(CALENDAR_OBJECT_RESOURCE_ID);
+
+
+-- Enumeration of free/busy types
+
+create table FREE_BUSY_TYPE (
+  ID          integer     primary key,
+  DESCRIPTION varchar(16) not null unique
+);
+
+insert into FREE_BUSY_TYPE values (0, 'unknown'         );
+insert into FREE_BUSY_TYPE values (1, 'free'            );
+insert into FREE_BUSY_TYPE values (2, 'busy'            );
+insert into FREE_BUSY_TYPE values (3, 'busy-unavailable');
+insert into FREE_BUSY_TYPE values (4, 'busy-tentative'  );
+
+
+------------------
+-- Transparency --
+------------------
+
+create table TRANSPARENCY (
+  TIME_RANGE_INSTANCE_ID      integer      not null references TIME_RANGE on delete cascade,
+  USER_ID                     varchar(255) not null,
+  TRANSPARENT                 boolean      not null
+);
+
+create index TRANSPARENCY_TIME_RANGE_INSTANCE_ID on
+  TRANSPARENCY(TIME_RANGE_INSTANCE_ID);
+
+
+----------------
+-- Attachment --
+----------------
+
+create sequence ATTACHMENT_ID_SEQ;
+
+create table ATTACHMENT (
+  ATTACHMENT_ID               integer           primary key default nextval('ATTACHMENT_ID_SEQ'), -- implicit index
+  CALENDAR_HOME_RESOURCE_ID   integer           not null references CALENDAR_HOME,
+  DROPBOX_ID                  varchar(255),
+  CONTENT_TYPE                varchar(255)      not null,
+  SIZE                        integer           not null,
+  MD5                         char(32)          not null,
+  CREATED                     timestamp default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED                    timestamp default timezone('UTC', CURRENT_TIMESTAMP),
+  PATH                        varchar(1024)     not null
+);
+
+create index ATTACHMENT_CALENDAR_HOME_RESOURCE_ID on
+  ATTACHMENT(CALENDAR_HOME_RESOURCE_ID);
+
+-- Many-to-many relationship between attachments and calendar objects
+create table ATTACHMENT_CALENDAR_OBJECT (
+  ATTACHMENT_ID                  integer      not null references ATTACHMENT on delete cascade,
+  MANAGED_ID                     varchar(255) not null,
+  CALENDAR_OBJECT_RESOURCE_ID    integer      not null references CALENDAR_OBJECT on delete cascade,
+
+  primary key (ATTACHMENT_ID, CALENDAR_OBJECT_RESOURCE_ID), -- implicit index
+  unique (MANAGED_ID, CALENDAR_OBJECT_RESOURCE_ID) --implicit index
+);
+
+create index ATTACHMENT_CALENDAR_OBJECT_CALENDAR_OBJECT_RESOURCE_ID on
+	ATTACHMENT_CALENDAR_OBJECT(CALENDAR_OBJECT_RESOURCE_ID);
+
+-----------------------
+-- Resource Property --
+-----------------------
+
+create table RESOURCE_PROPERTY (
+  RESOURCE_ID integer      not null, -- foreign key: *.RESOURCE_ID
+  NAME        varchar(255) not null,
+  VALUE       text         not null, -- FIXME: xml?
+  VIEWER_UID  varchar(255),
+
+  primary key (RESOURCE_ID, NAME, VIEWER_UID) -- implicit index
+);
+
+
+----------------------
+-- AddressBook Home --
+----------------------
+
+create table ADDRESSBOOK_HOME (
+  RESOURCE_ID      				integer			primary key default nextval('RESOURCE_ID_SEQ'), -- implicit index
+  ADDRESSBOOK_PROPERTY_STORE_ID	integer      	default nextval('RESOURCE_ID_SEQ') not null, 	-- implicit index
+  OWNER_UID        				varchar(255) 	not null unique,                                -- implicit index
+  DATAVERSION      				integer      	default 0 not null
+);
+
+
+-------------------------------
+-- AddressBook Home Metadata --
+-------------------------------
+
+create table ADDRESSBOOK_HOME_METADATA (
+  RESOURCE_ID      integer      primary key references ADDRESSBOOK_HOME on delete cascade, -- implicit index
+  QUOTA_USED_BYTES integer      default 0 not null,
+  CREATED          timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED         timestamp    default timezone('UTC', CURRENT_TIMESTAMP)
+);
+
+
+-----------------------------
+-- Shared AddressBook Bind --
+-----------------------------
+
+-- Joins sharee ADDRESSBOOK_HOME and owner ADDRESSBOOK_HOME
+
+create table SHARED_ADDRESSBOOK_BIND (
+  ADDRESSBOOK_HOME_RESOURCE_ID			integer			not null references ADDRESSBOOK_HOME,
+  OWNER_HOME_RESOURCE_ID    			integer      	not null references ADDRESSBOOK_HOME on delete cascade,
+  ADDRESSBOOK_RESOURCE_NAME    			varchar(255) 	not null,
+  BIND_MODE                    			integer      	not null,	-- enum CALENDAR_BIND_MODE
+  BIND_STATUS                  			integer      	not null,	-- enum CALENDAR_BIND_STATUS
+  BIND_REVISION				   			integer      	default 0 not null,
+  MESSAGE                      			text,                  		-- FIXME: xml?
+
+  primary key (ADDRESSBOOK_HOME_RESOURCE_ID, OWNER_HOME_RESOURCE_ID), -- implicit index
+  unique (ADDRESSBOOK_HOME_RESOURCE_ID, ADDRESSBOOK_RESOURCE_NAME)     -- implicit index
+);
+
+create index SHARED_ADDRESSBOOK_BIND_RESOURCE_ID on
+  SHARED_ADDRESSBOOK_BIND(OWNER_HOME_RESOURCE_ID);
+
+
+------------------------
+-- AddressBook Object --
+------------------------
+
+create table ADDRESSBOOK_OBJECT (
+  RESOURCE_ID             		integer   		primary key default nextval('RESOURCE_ID_SEQ'),    -- implicit index
+  ADDRESSBOOK_HOME_RESOURCE_ID 	integer      	not null references ADDRESSBOOK_HOME on delete cascade,
+  RESOURCE_NAME           		varchar(255) 	not null,
+  VCARD_TEXT              		text         	not null,
+  VCARD_UID               		varchar(255) 	not null,
+  KIND 			  		  		integer      	not null,  -- enum ADDRESSBOOK_OBJECT_KIND
+  MD5                     		char(32)     	not null,
+  CREATED                 		timestamp    	default timezone('UTC', CURRENT_TIMESTAMP),
+  MODIFIED                		timestamp    	default timezone('UTC', CURRENT_TIMESTAMP),
+
+  unique (ADDRESSBOOK_HOME_RESOURCE_ID, RESOURCE_NAME), -- implicit index
+  unique (ADDRESSBOOK_HOME_RESOURCE_ID, VCARD_UID)      -- implicit index
+);
+
+
+-----------------------------
+-- AddressBook Object kind --
+-----------------------------
+
+create table ADDRESSBOOK_OBJECT_KIND (
+  ID          integer     primary key,
+  DESCRIPTION varchar(16) not null unique
+);
+
+insert into ADDRESSBOOK_OBJECT_KIND values (0, 'person');
+insert into ADDRESSBOOK_OBJECT_KIND values (1, 'group' );
+insert into ADDRESSBOOK_OBJECT_KIND values (2, 'resource');
+insert into ADDRESSBOOK_OBJECT_KIND values (3, 'location');
+
+
+---------------------------------
+-- Address Book Object Members --
+---------------------------------
+
+create table ABO_MEMBERS (
+    GROUP_ID              integer      not null references ADDRESSBOOK_OBJECT on delete cascade,	-- AddressBook Object's (kind=='group') RESOURCE_ID
+ 	ADDRESSBOOK_ID		  integer      not null references ADDRESSBOOK_HOME on delete cascade,
+    MEMBER_ID             integer      not null references ADDRESSBOOK_OBJECT,						-- member AddressBook Object's RESOURCE_ID
+
+    primary key (GROUP_ID, MEMBER_ID) -- implicit index
+);
+
+create index ABO_MEMBERS_ADDRESSBOOK_ID on
+	ABO_MEMBERS(ADDRESSBOOK_ID);
+create index ABO_MEMBERS_MEMBER_ID on
+	ABO_MEMBERS(MEMBER_ID);
+
+------------------------------------------
+-- Address Book Object Foreign Members  --
+------------------------------------------
+
+create table ABO_FOREIGN_MEMBERS (
+    GROUP_ID              integer      not null references ADDRESSBOOK_OBJECT on delete cascade,	-- AddressBook Object's (kind=='group') RESOURCE_ID
+ 	ADDRESSBOOK_ID		  integer      not null references ADDRESSBOOK_HOME on delete cascade,
+    MEMBER_ADDRESS  	  varchar(255) not null, 													-- member AddressBook Object's 'calendar' address
+
+    primary key (GROUP_ID, MEMBER_ADDRESS) -- implicit index
+);
+
+create index ABO_FOREIGN_MEMBERS_ADDRESSBOOK_ID on
+	ABO_FOREIGN_MEMBERS(ADDRESSBOOK_ID);
+
+-----------------------
+-- Shared Group Bind --
+-----------------------
+
+-- Joins ADDRESSBOOK_HOME and ADDRESSBOOK_OBJECT (kind == group)
+
+create table SHARED_GROUP_BIND (	
+  ADDRESSBOOK_HOME_RESOURCE_ID 		integer      not null references ADDRESSBOOK_HOME,
+  GROUP_RESOURCE_ID      			integer      not null references ADDRESSBOOK_OBJECT on delete cascade,
+  GROUP_ADDRESSBOOK_NAME			varchar(255) not null,
+  BIND_MODE                    		integer      not null, -- enum CALENDAR_BIND_MODE
+  BIND_STATUS                  		integer      not null, -- enum CALENDAR_BIND_STATUS
+  BIND_REVISION				   		integer      default 0 not null,
+  MESSAGE                      		text,                  -- FIXME: xml?
+
+  primary key (ADDRESSBOOK_HOME_RESOURCE_ID, GROUP_RESOURCE_ID), -- implicit index
+  unique (ADDRESSBOOK_HOME_RESOURCE_ID, GROUP_ADDRESSBOOK_NAME)     -- implicit index
+);
+
+create index SHARED_GROUP_BIND_RESOURCE_ID on
+  SHARED_GROUP_BIND(GROUP_RESOURCE_ID);
+
+
+---------------
+-- Revisions --
+---------------
+
+create sequence REVISION_SEQ;
+
+
+-------------------------------
+-- Calendar Object Revisions --
+-------------------------------
+
+create table CALENDAR_OBJECT_REVISIONS (
+  CALENDAR_HOME_RESOURCE_ID integer      not null references CALENDAR_HOME,
+  CALENDAR_RESOURCE_ID      integer      references CALENDAR,
+  CALENDAR_NAME             varchar(255) default null,
+  RESOURCE_NAME             varchar(255),
+  REVISION                  integer      default nextval('REVISION_SEQ') not null,
+  DELETED                   boolean      not null
+);
+
+create index CALENDAR_OBJECT_REVISIONS_HOME_RESOURCE_ID_CALENDAR_RESOURCE_ID
+  on CALENDAR_OBJECT_REVISIONS(CALENDAR_HOME_RESOURCE_ID, CALENDAR_RESOURCE_ID);
+
+create index CALENDAR_OBJECT_REVISIONS_RESOURCE_ID_RESOURCE_NAME_DELETED_REVISION
+  on CALENDAR_OBJECT_REVISIONS(CALENDAR_RESOURCE_ID, RESOURCE_NAME, DELETED, REVISION);
+
+create index CALENDAR_OBJECT_REVISIONS_RESOURCE_ID_REVISION
+  on CALENDAR_OBJECT_REVISIONS(CALENDAR_RESOURCE_ID, REVISION);
+
+
+----------------------------------
+-- AddressBook Object Revisions --
+----------------------------------
+
+create table ADDRESSBOOK_OBJECT_REVISIONS (
+  ADDRESSBOOK_HOME_RESOURCE_ID 			integer			not null references ADDRESSBOOK_HOME,
+  OWNER_HOME_RESOURCE_ID    			integer     	references ADDRESSBOOK_HOME,
+  ADDRESSBOOK_NAME             			varchar(255) 	default null,
+  RESOURCE_NAME                			varchar(255),
+  REVISION                     			integer     	default nextval('REVISION_SEQ') not null,
+  DELETED                      			boolean      	not null
+);
+
+create index ADDRESSBOOK_OBJECT_REVISIONS_HOME_RESOURCE_ID_OWNER_HOME_RESOURCE_ID
+  on ADDRESSBOOK_OBJECT_REVISIONS(ADDRESSBOOK_HOME_RESOURCE_ID, OWNER_HOME_RESOURCE_ID);
+
+create index ADDRESSBOOK_OBJECT_REVISIONS_OWNER_HOME_RESOURCE_ID_RESOURCE_NAME_DELETED_REVISION
+  on ADDRESSBOOK_OBJECT_REVISIONS(OWNER_HOME_RESOURCE_ID, RESOURCE_NAME, DELETED, REVISION);
+
+create index ADDRESSBOOK_OBJECT_REVISIONS_OWNER_HOME_RESOURCE_ID_REVISION
+  on ADDRESSBOOK_OBJECT_REVISIONS(OWNER_HOME_RESOURCE_ID, REVISION);
+
+
+-----------------------------------
+-- Notification Object Revisions --
+-----------------------------------
+
+create table NOTIFICATION_OBJECT_REVISIONS (
+  NOTIFICATION_HOME_RESOURCE_ID integer      not null references NOTIFICATION_HOME on delete cascade,
+  RESOURCE_NAME                 varchar(255),
+  REVISION                      integer      default nextval('REVISION_SEQ') not null,
+  DELETED                       boolean      not null,
+
+  unique(NOTIFICATION_HOME_RESOURCE_ID, RESOURCE_NAME) -- implicit index
+);
+
+create index NOTIFICATION_OBJECT_REVISIONS_RESOURCE_ID_REVISION
+  on NOTIFICATION_OBJECT_REVISIONS(NOTIFICATION_HOME_RESOURCE_ID, REVISION);
+
+
+-------------------------------------------
+-- Apple Push Notification Subscriptions --
+-------------------------------------------
+
+create table APN_SUBSCRIPTIONS (
+  TOKEN                         varchar(255) not null,
+  RESOURCE_KEY                  varchar(255) not null,
+  MODIFIED                      integer      not null,
+  SUBSCRIBER_GUID               varchar(255) not null,
+  USER_AGENT                    varchar(255) default null,
+  IP_ADDR                       varchar(255) default null,
+
+  primary key (TOKEN, RESOURCE_KEY) -- implicit index
+);
+
+create index APN_SUBSCRIPTIONS_RESOURCE_KEY
+   on APN_SUBSCRIPTIONS(RESOURCE_KEY);
+
+   
+-----------------
+-- IMIP Tokens --
+-----------------
+
+create table IMIP_TOKENS (
+  TOKEN                         varchar(255) not null,
+  ORGANIZER                     varchar(255) not null,
+  ATTENDEE                      varchar(255) not null,
+  ICALUID                       varchar(255) not null,
+  ACCESSED                      timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+
+  primary key (ORGANIZER, ATTENDEE, ICALUID) -- implicit index
+);
+
+create index IMIP_TOKENS_TOKEN
+   on IMIP_TOKENS(TOKEN);
+
+   
+----------------
+-- Work Items --
+----------------
+
+create sequence WORKITEM_SEQ;
+
+
+---------------------------
+-- IMIP Inivitation Work --
+---------------------------
+
+create table IMIP_INVITATION_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  FROM_ADDR                     varchar(255) not null,
+  TO_ADDR                       varchar(255) not null,
+  ICALENDAR_TEXT                text         not null
+);
+
+
+-----------------------
+-- IMIP Polling Work --
+-----------------------
+
+create table IMIP_POLLING_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP)
+);
+
+
+---------------------
+-- IMIP Reply Work --
+---------------------
+
+create table IMIP_REPLY_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  ORGANIZER                     varchar(255) not null,
+  ATTENDEE                      varchar(255) not null,
+  ICALENDAR_TEXT                text         not null
+);
+
+
+------------------------
+-- Push Notifications --
+------------------------
+
+create table PUSH_NOTIFICATION_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  PUSH_ID                       varchar(255) not null,
+  PRIORITY                      integer      not null -- 1:low 5:medium 10:high
+);
+
+-----------------
+-- GroupCacher --
+-----------------
+
+create table GROUP_CACHER_POLLING_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP)
+);
+
+
+--------------------------
+-- Object Splitter Work --
+--------------------------
+
+create table CALENDAR_OBJECT_SPLITTER_WORK (
+  WORK_ID                       integer      primary key default nextval('WORKITEM_SEQ') not null, -- implicit index
+  NOT_BEFORE                    timestamp    default timezone('UTC', CURRENT_TIMESTAMP),
+  RESOURCE_ID                   integer      not null references CALENDAR_OBJECT on delete cascade
+);
+
+create index CALENDAR_OBJECT_SPLITTER_WORK_RESOURCE_ID on
+	CALENDAR_OBJECT_SPLITTER_WORK(RESOURCE_ID);
+
+--------------------
+-- Schema Version --
+--------------------
+
+create table CALENDARSERVER (
+  NAME                          varchar(255) primary key, -- implicit index
+  VALUE                         varchar(255)
+);
+
+insert into CALENDARSERVER values ('VERSION', '29');
+insert into CALENDARSERVER values ('CALENDAR-DATAVERSION', '5');
+insert into CALENDARSERVER values ('ADDRESSBOOK-DATAVERSION', '2');
+insert into CALENDARSERVER values ('NOTIFICATION-DATAVERSION', '1');

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_28_to_29.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -18,32 +18,21 @@
 -- Upgrade database schema from VERSION 28 to 29 --
 ---------------------------------------------------
 
-----------------------------------------
--- Change Address Book Object Members --
-----------------------------------------
+-- Sharing notification related updates
 
-alter table ABO_MEMBERS
-	drop ("abo_members_member_id_fkey");
-alter table ABO_MEMBERS
-	drop ("abo_members_group_id_fkey");
-alter table ABO_MEMBERS
-	add ("REVISION" integer default nextval('REVISION_SEQ') not null);
-alter table ABO_MEMBERS
-	add ("REMOVED" boolean default false not null);
-alter table ABO_MEMBERS
-	 drop ("abo_members_pkey");
-alter table ABO_MEMBERS
-	 add ("abo_members_pkey" primary key ("GROUP_ID", "MEMBER_ID", "REVISION"));
+alter table NOTIFICATION_HOME
+ add ("DATAVERSION" integer default 0 not null);
 
-------------------------------------------
--- Change Address Book Object Revisions --
-------------------------------------------
-	
-alter table ADDRESSBOOK_OBJECT_REVISIONS
-	add ("OBJECT_RESOURCE_ID" integer default 0);
+alter table NOTIFICATION
+  rename column XML_TYPE to NOTIFICATION_TYPE;
+alter table NOTIFICATION
+  rename column XML_DATA to NOTIFICATION_DATA;
 
---------------------
--- Update version --
---------------------
+  -- Sharing enumeration updates
+insert into CALENDAR_BIND_MODE (DESCRIPTION, ID) values ('indirect', 4);
 
+insert into CALENDAR_BIND_STATUS (DESCRIPTION, ID) values ('deleted', 4);
+
+-- Now update the version
 update CALENDARSERVER set VALUE = '29' where NAME = 'VERSION';
+insert into CALENDARSERVER (NAME, VALUE) values ('NOTIFICATION-DATAVERSION', '1');

Added: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_29_to_30.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_29_to_30.sql	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/oracle-dialect/upgrade_from_29_to_30.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,49 @@
+----
+-- Copyright (c) 2012-2013 Apple Inc. All rights reserved.
+--
+-- Licensed under the Apache License, Version 2.0 (the "License");
+-- you may not use this file except in compliance with the License.
+-- You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+----
+
+---------------------------------------------------
+-- Upgrade database schema from VERSION 29 to 30 --
+---------------------------------------------------
+
+----------------------------------------
+-- Change Address Book Object Members --
+----------------------------------------
+
+alter table ABO_MEMBERS
+	drop ("abo_members_member_id_fkey");
+alter table ABO_MEMBERS
+	drop ("abo_members_group_id_fkey");
+alter table ABO_MEMBERS
+	add ("REVISION" integer default nextval('REVISION_SEQ') not null);
+alter table ABO_MEMBERS
+	add ("REMOVED" boolean default false not null);
+alter table ABO_MEMBERS
+	 drop ("abo_members_pkey");
+alter table ABO_MEMBERS
+	 add ("abo_members_pkey" primary key ("GROUP_ID", "MEMBER_ID", "REVISION"));
+
+------------------------------------------
+-- Change Address Book Object Revisions --
+------------------------------------------
+	
+alter table ADDRESSBOOK_OBJECT_REVISIONS
+	add ("OBJECT_RESOURCE_ID" integer default 0);
+
+--------------------
+-- Update version --
+--------------------
+
+update CALENDARSERVER set VALUE = '30' where NAME = 'VERSION';

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_28_to_29.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -18,27 +18,21 @@
 -- Upgrade database schema from VERSION 28 to 29 --
 ---------------------------------------------------
 
-----------------------------------------
--- Change Address Book Object Members --
-----------------------------------------
+-- Sharing notification related updates
 
-alter table ABO_MEMBERS
-	drop constraint	abo_members_member_id_fkey,
-	drop constraint	abo_members_group_id_fkey,
-	add column	REVISION		integer      default nextval('REVISION_SEQ') not null,
-	add column	REMOVED         boolean      default false not null,
-	drop constraint abo_members_pkey,
-	add constraint abo_members_pkey primary key(GROUP_ID, MEMBER_ID, REVISION);
+alter table NOTIFICATION_HOME
+  add column DATAVERSION integer default 0 not null;
 
-------------------------------------------
--- Change Address Book Object Revisions --
-------------------------------------------
-	
-alter table ADDRESSBOOK_OBJECT_REVISIONS
-	add column OBJECT_RESOURCE_ID integer default 0;
-	
---------------------
--- Update version --
---------------------
+alter table NOTIFICATION
+  rename column XML_TYPE to NOTIFICATION_TYPE;
+alter table NOTIFICATION
+  rename column XML_DATA to NOTIFICATION_DATA;
 
+-- Sharing enumeration updates
+insert into CALENDAR_BIND_MODE values (4, 'indirect');
+
+insert into CALENDAR_BIND_STATUS values (4, 'deleted');
+
+-- Now update the version
 update CALENDARSERVER set VALUE = '29' where NAME = 'VERSION';
+insert into CALENDARSERVER values ('NOTIFICATION-DATAVERSION', '1');

Added: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_29_to_30.sql
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_29_to_30.sql	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_schema/upgrades/postgres-dialect/upgrade_from_29_to_30.sql	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,44 @@
+----
+-- Copyright (c) 2012-2013 Apple Inc. All rights reserved.
+--
+-- Licensed under the Apache License, Version 2.0 (the "License");
+-- you may not use this file except in compliance with the License.
+-- You may obtain a copy of the License at
+--
+-- http://www.apache.org/licenses/LICENSE-2.0
+--
+-- Unless required by applicable law or agreed to in writing, software
+-- distributed under the License is distributed on an "AS IS" BASIS,
+-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+-- See the License for the specific language governing permissions and
+-- limitations under the License.
+----
+
+---------------------------------------------------
+-- Upgrade database schema from VERSION 29 to 30 --
+---------------------------------------------------
+
+----------------------------------------
+-- Change Address Book Object Members --
+----------------------------------------
+
+alter table ABO_MEMBERS
+	drop constraint	abo_members_member_id_fkey,
+	drop constraint	abo_members_group_id_fkey,
+	add column	REVISION		integer      default nextval('REVISION_SEQ') not null,
+	add column	REMOVED         boolean      default false not null,
+	drop constraint abo_members_pkey,
+	add constraint abo_members_pkey primary key(GROUP_ID, MEMBER_ID, REVISION);
+
+------------------------------------------
+-- Change Address Book Object Revisions --
+------------------------------------------
+	
+alter table ADDRESSBOOK_OBJECT_REVISIONS
+	add column OBJECT_RESOURCE_ID integer default 0;
+	
+--------------------
+-- Update version --
+--------------------
+
+update CALENDARSERVER set VALUE = '30' where NAME = 'VERSION';

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_tables.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_tables.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/sql_tables.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -142,6 +142,7 @@
 _BIND_STATUS_ACCEPTED = _bindStatus('accepted')
 _BIND_STATUS_DECLINED = _bindStatus('declined')
 _BIND_STATUS_INVALID = _bindStatus('invalid')
+_BIND_STATUS_DELETED = _bindStatus('deleted')
 
 
 _transpValues = _schemaConstants(
@@ -173,6 +174,7 @@
 _BIND_MODE_READ = _bindMode('read')
 _BIND_MODE_WRITE = _bindMode('write')
 _BIND_MODE_DIRECT = _bindMode('direct')
+_BIND_MODE_INDIRECT = _bindMode('indirect')
 
 
 _addressBookObjectKind = _schemaConstants(

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/test/util.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/test/util.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/test/util.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -707,7 +707,36 @@
                      .calendarObjectWithName(name)))
 
 
+    def addressbookHomeUnderTest(self, txn=None, name="home1"):
+        """
+        Get the addressbook home detailed by C{requirements['home1']}.
+        """
+        if txn is None:
+            txn = self.transactionUnderTest()
+        return txn.addressbookHomeWithUID(name)
 
+
+    @inlineCallbacks
+    def addressbookUnderTest(self, txn=None, name="addressbook", home="home1"):
+        """
+        Get the addressbook detailed by C{requirements['home1']['addressbook']}.
+        """
+        returnValue((yield
+            (yield self.addressbookHomeUnderTest(txn=txn, name=home)).addressbookWithName(name))
+        )
+
+
+    @inlineCallbacks
+    def addressbookObjectUnderTest(self, txn=None, name="1.vcf", addressbook_name="addressbook", home="home1"):
+        """
+        Get the addressbook detailed by
+        C{requirements['home1']['addressbook']['1.vcf']}.
+        """
+        returnValue((yield (yield self.addressbookUnderTest(txn=txn, name=addressbook_name, home=home))
+                    .addressbookObjectWithName(name)))
+
+
+
 class StubNotifierFactory(object):
     """
     For testing push notifications without an XMPP server.
@@ -726,7 +755,7 @@
         return "/%s/%s/%s/" % (prefix, self.hostname, id)
 
 
-    def send(self, prefix, id, txn, priority): 
+    def send(self, prefix, id, txn, priority):
         self.history.append((self.pushKeyForId(prefix, id), priority))
 
 

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrade.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrade.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrade.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -414,6 +414,34 @@
 
 
 
+class UpgradeDatabaseNotificationDataStep(_UpgradeDatabaseDataStep):
+    """
+    Checks and upgrades the database data. This assumes there are a bunch of
+    upgrade python modules that we can execute against the database to
+    accomplish the upgrade.
+
+    @ivar sqlStore: The store to operate on.
+
+    @type sqlStore: L{txdav.idav.IDataStore}
+    """
+
+    def __init__(self, sqlStore, **kwargs):
+        """
+        Initialize the service.
+
+        @param sqlStore: The store to operate on. Can be C{None} when doing unit tests.
+        @param service:  Wrapped service. Can be C{None} when doing unit tests.
+        """
+        super(UpgradeDatabaseNotificationDataStep, self).__init__(sqlStore, **kwargs)
+
+        self.versionKey = "NOTIFICATION-DATAVERSION"
+        self.versionDescriptor = "notification data"
+        self.upgradeFilePrefix = "notification_"
+        self.upgradeFileSuffix = ".py"
+        self.defaultKeyValue = 0
+
+
+
 class UpgradeDatabaseOtherStep(UpgradeDatabaseCoreStep):
     """
     Do any other upgrade behaviors once all the schema, data, file migration upgraders

Copied: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/notification_upgrade_from_0_to_1.py (from rev 12017, CalendarServer/trunk/txdav/common/datastore/upgrade/sql/upgrades/notification_upgrade_from_0_to_1.py)
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/notification_upgrade_from_0_to_1.py	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/notification_upgrade_from_0_to_1.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,165 @@
+# -*- test-case-name: txdav.common.datastore.upgrade.sql.test -*-
+##
+# Copyright (c) 2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from twisted.internet.defer import inlineCallbacks
+
+from twistedcaldav import caldavxml, customxml
+from twistedcaldav.config import config
+
+from txdav.common.datastore.sql_tables import schema, _BIND_STATUS_INVITED
+from txdav.common.datastore.upgrade.sql.upgrades.util import updateNotificationDataVersion, \
+    doToEachHomeNotAtVersion
+from txdav.xml import element
+from txdav.xml.parser import WebDAVDocument
+from twistedcaldav.sharing import invitationBindStatusFromXMLMap, \
+    invitationBindModeFromXMLMap
+
+"""
+Data upgrade from database version 0 to 1
+"""
+
+UPGRADE_TO_VERSION = 1
+
+ at inlineCallbacks
+def doUpgrade(sqlStore):
+    """
+    Do the required upgrade steps.
+    """
+    yield updateNotificationHomes(sqlStore, config.UpgradeHomePrefix)
+
+    # Don't do remaining upgrade if we are only process a subset of the homes
+    if not config.UpgradeHomePrefix:
+        # Always bump the DB value
+        yield updateNotificationDataVersion(sqlStore, UPGRADE_TO_VERSION)
+
+
+
+ at inlineCallbacks
+def updateNotificationHomes(sqlStore, prefix=None):
+    """
+    For each calendar home, update the associated properties on the home or its owned calendars.
+    """
+
+    yield doToEachHomeNotAtVersion(sqlStore, schema.NOTIFICATION_HOME, UPGRADE_TO_VERSION, updateNotificationHome, "Update Notification Home", filterOwnerUID=prefix)
+
+
+
+ at inlineCallbacks
+def updateNotificationHome(txn, homeResourceID):
+    """
+    For this notification home, update the associated child resources.
+    """
+
+    home = yield txn.notificationsWithResourceID(homeResourceID)
+    notifications = (yield home.notificationObjects())
+    for notification in notifications:
+        yield updateNotification(txn, notification)
+
+
+
+ at inlineCallbacks
+def updateNotification(txn, notification):
+    """
+    For this notification home, update the associated child resources.
+    """
+
+    # Convert the type value to JSON
+    xmltype = WebDAVDocument.fromString(notification.notificationType()).root_element
+    shared_type = "calendar"
+    if xmltype.children[0].qname() == customxml.InviteNotification.qname():
+        jsontype = {"notification-type": "invite-notification"}
+        if "shared-type" in xmltype.children[0].attributes:
+            shared_type = xmltype.children[0].attributes["shared-type"]
+        jsontype["shared-type"] = shared_type
+    elif xmltype.children[0].qname() == customxml.InviteReply.qname():
+        jsontype = {"notification-type": "invite-reply"}
+
+    # Convert the data value to JSON
+    xmldata = (yield notification.notificationData())
+    xmldata = WebDAVDocument.fromString(xmldata).root_element
+
+    def _extract_UID(uri):
+        if uri.startswith("urn:uuid:"):
+            return uri[len("urn:uuid:"):]
+        elif uri[0] == "/":
+            return uri.rstrip("/").split("/")[-1]
+        elif uri.startswith("mailto:"):
+            return uri[7:].split("@")[0]
+        else:
+            return ""
+
+    if xmldata.childOfType(customxml.InviteNotification) is not None:
+        ntype = xmldata.childOfType(customxml.InviteNotification)
+        dtstamp = str(xmldata.childOfType(customxml.DTStamp))
+        owner = _extract_UID(str(ntype.childOfType(customxml.Organizer).childOfType(element.HRef)))
+        sharee = _extract_UID(str(ntype.childOfType(element.HRef)))
+        uid = str(ntype.childOfType(customxml.UID))
+        for xml in invitationBindStatusFromXMLMap.keys():
+            if ntype.childOfType(xml) is not None:
+                state = invitationBindStatusFromXMLMap[xml]
+                break
+        else:
+            state = _BIND_STATUS_INVITED
+        mode = invitationBindModeFromXMLMap[type(ntype.childOfType(customxml.InviteAccess).children[0])]
+        name = str(ntype.childOfType(customxml.HostURL).childOfType(element.HRef)).rstrip("/").split("/")[-1]
+        summary = str(ntype.childOfType(customxml.InviteSummary))
+
+        jsondata = {
+            "notification-type": "invite-notification",
+            "shared-type": shared_type,
+            "dtstamp": dtstamp,
+            "owner": owner,
+            "sharee": sharee,
+            "uid": uid,
+            "status": state,
+            "access": mode,
+            "name": name,
+            "summary": summary,
+        }
+        if ntype.childOfType(caldavxml.SupportedCalendarComponentSet):
+            comps = [child.attributes["name"] for child in ntype.childOfType(caldavxml.SupportedCalendarComponentSet).children]
+            jsondata["supported-components"] = ",".join(comps)
+
+    elif xmldata.childOfType(customxml.InviteReply) is not None:
+        ntype = xmldata.childOfType(customxml.InviteReply)
+        dtstamp = str(xmldata.childOfType(customxml.DTStamp))
+        sharee = _extract_UID(str(ntype.childOfType(element.HRef)))
+        for xml in invitationBindStatusFromXMLMap.keys():
+            if ntype.childOfType(xml) is not None:
+                state = invitationBindStatusFromXMLMap[xml]
+                break
+        else:
+            state = _BIND_STATUS_INVITED
+        name = str(ntype.childOfType(customxml.HostURL).childOfType(element.HRef)).rstrip("/").split("/")[-1]
+        inreplyto = str(ntype.childOfType(customxml.InReplyTo))
+        summary = str(ntype.childOfType(customxml.InviteSummary)) if ntype.childOfType(customxml.InviteSummary) is not None else ""
+
+        owner = str(ntype.childOfType(customxml.HostURL).childOfType(element.HRef)).rstrip("/").split("/")[-2]
+
+        jsondata = {
+            "notification-type": "invite-reply",
+            "shared-type": shared_type,
+            "dtstamp": dtstamp,
+            "owner": owner,
+            "sharee": sharee,
+            "status": state,
+            "name": name,
+            "in-reply-to": inreplyto,
+            "summary": summary,
+        }
+
+    yield notification.setData(notification.uid(), jsontype, jsondata)

Copied: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/test/test_notification_upgrade_from_0_to_1.py (from rev 12017, CalendarServer/trunk/txdav/common/datastore/upgrade/sql/upgrades/test/test_notification_upgrade_from_0_to_1.py)
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/test/test_notification_upgrade_from_0_to_1.py	                        (rev 0)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/test/test_notification_upgrade_from_0_to_1.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -0,0 +1,194 @@
+##
+# Copyright (c) 2013 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from twext.enterprise.dal.syntax import Update
+
+from twisted.internet.defer import inlineCallbacks
+
+from txdav.caldav.datastore.test.util import CommonStoreTests
+from txdav.common.datastore.sql_tables import _BIND_STATUS_INVITED, \
+    _BIND_MODE_WRITE, _BIND_STATUS_ACCEPTED, _BIND_MODE_READ
+from txdav.common.datastore.upgrade.sql.upgrades.notification_upgrade_from_0_to_1 import doUpgrade
+
+"""
+Tests for L{txdav.common.datastore.upgrade.sql.upgrade}.
+"""
+
+class Upgrade_from_0_to_1(CommonStoreTests):
+    """
+    Tests for notification upgrade.
+    """
+
+    @inlineCallbacks
+    def test_upgrade_invite(self):
+
+        data = (
+            (
+                "uid1",
+                """<?xml version='1.0' encoding='UTF-8'?>
+<CS:notification xmlns:CS='http://calendarserver.org/ns/'>
+    <CS:invite-notification shared-type='calendar'/>
+</CS:notification>
+""",
+                {
+                    "notification-type": "invite-notification",
+                    "shared-type": "calendar",
+                },
+                """<?xml version='1.0' encoding='UTF-8'?>
+<notification xmlns='http://calendarserver.org/ns/'>
+  <dtstamp>20131113T153109Z</dtstamp>
+  <invite-notification shared-type='calendar'>
+    <uid>uid1</uid>
+    <href xmlns='DAV:'>urn:uuid:user02</href>
+    <invite-noresponse/>
+    <access>
+      <read-write/>
+    </access>
+    <hosturl>
+      <href xmlns='DAV:'>/calendars/__uids__/user01/calendar</href>
+    </hosturl>
+    <organizer>
+      <href xmlns='DAV:'>urn:uuid:user01</href>
+      <common-name>User 01</common-name>
+    </organizer>
+    <summary>Shared</summary>
+    <supported-calendar-component-set xmlns='urn:ietf:params:xml:ns:caldav'>
+      <comp name='VEVENT'/>
+      <comp name='VTODO'/>
+    </supported-calendar-component-set>
+  </invite-notification>
+</notification>
+""",
+                {
+                    "notification-type": "invite-notification",
+                    "shared-type": "calendar",
+                    "dtstamp": "20131113T153109Z",
+                    "owner": "user01",
+                    "sharee": "user02",
+                    "uid": "uid1",
+                    "status": _BIND_STATUS_INVITED,
+                    "access": _BIND_MODE_WRITE,
+                    "name": "calendar",
+                    "summary": "Shared",
+                    "supported-components": "VEVENT,VTODO",
+                },
+            ),
+            (
+                "uid2",
+                """<?xml version='1.0' encoding='UTF-8'?>
+<CS:notification xmlns:CS='http://calendarserver.org/ns/'>
+    <CS:invite-notification shared-type='addressbook'/>
+</CS:notification>
+""",
+                {
+                    "notification-type": "invite-notification",
+                    "shared-type": "addressbook",
+                },
+                """<?xml version='1.0' encoding='UTF-8'?>
+<notification xmlns='http://calendarserver.org/ns/'>
+  <dtstamp>20131113T153110Z</dtstamp>
+  <invite-notification shared-type='addressbook'>
+    <uid>uid2</uid>
+    <href xmlns='DAV:'>/principals/users/user02/</href>
+    <invite-accepted/>
+    <access>
+      <read/>
+    </access>
+    <hosturl>
+      <href xmlns='DAV:'>/addressbooks/__uids__/user01/addressbook/</href>
+    </hosturl>
+    <organizer>
+      <href xmlns='DAV:'>/principals/users/user01/</href>
+      <common-name>User 01</common-name>
+    </organizer>
+    <summary>Shared 2</summary>
+  </invite-notification>
+</notification>
+""",
+                {
+                    "notification-type": "invite-notification",
+                    "shared-type": "addressbook",
+                    "dtstamp": "20131113T153110Z",
+                    "owner": "user01",
+                    "sharee": "user02",
+                    "uid": "uid2",
+                    "status": _BIND_STATUS_ACCEPTED,
+                    "access": _BIND_MODE_READ,
+                    "name": "addressbook",
+                    "summary": "Shared 2",
+                },
+            ),
+            (
+                "uid3",
+                """<?xml version='1.0' encoding='UTF-8'?>
+<CS:notification xmlns:CS='http://calendarserver.org/ns/'>
+    <CS:invite-reply/>
+</CS:notification>
+""",
+                {
+                    "notification-type": "invite-reply",
+                },
+                """<?xml version='1.0' encoding='UTF-8'?>
+<notification xmlns='http://calendarserver.org/ns/'>
+  <dtstamp>20131113T153111Z</dtstamp>
+  <invite-reply shared-type='calendar'>
+    <href xmlns='DAV:'>mailto:user02 at example.com</href>
+    <invite-accepted/>
+    <hosturl>
+      <href xmlns='DAV:'>/calendars/__uids__/user01/calendar</href>
+    </hosturl>
+    <in-reply-to>uid1</in-reply-to>
+  </invite-reply>
+</notification>
+""",
+                {
+                    "notification-type": "invite-reply",
+                    "shared-type": "calendar",
+                    "dtstamp": "20131113T153111Z",
+                    "owner": "user01",
+                    "sharee": "user02",
+                    "status": _BIND_STATUS_ACCEPTED,
+                    "name": "calendar",
+                    "in-reply-to": "uid1",
+                    "summary": "",
+                },
+            ),
+        )
+
+        for uid, notificationtype, _ignore_jtype, notificationdata, _ignore_jdata in data:
+            notifications = yield self.transactionUnderTest().notificationsWithUID("user01")
+            yield notifications.writeNotificationObject(uid, notificationtype, notificationdata)
+
+        # Force data version to previous
+        nh = notifications._homeSchema
+        yield Update(
+            {nh.DATAVERSION: 0},
+            Where=None,
+        ).on(self.transactionUnderTest())
+
+        yield self.commit()
+        yield doUpgrade(self._sqlCalendarStore)
+
+        notifications = yield self.transactionUnderTest().notificationsWithUID("user01")
+        version = (yield notifications.dataVersion())
+        self.assertEqual(version, 1)
+
+        for uid, _ignore_notificationtype, jtype, _ignore_notificationdata, jdata in data:
+            notification = (yield notifications.notificationObjectWithUID(uid))
+            self.assertTrue(notification is not None, msg="Failed {uid}".format(uid=uid))
+            self.assertEqual(notification.notificationType(), jtype, msg="Failed {uid}".format(uid=uid))
+            data = (yield notification.notificationData())
+            self.assertEqual(data, jdata, msg="Failed {uid}".format(uid=uid))

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/util.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/util.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/datastore/upgrade/sql/upgrades/util.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -128,6 +128,11 @@
 
 
 
+def updateNotificationDataVersion(store, version):
+    return _updateDataVersion(store, "NOTIFICATION-DATAVERSION", version)
+
+
+
 @inlineCallbacks
 def doToEachHomeNotAtVersion(store, homeSchema, version, doIt, logStr, filterOwnerUID=None):
     """

Modified: CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/inotifications.py
===================================================================
--- CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/inotifications.py	2013-12-18 22:48:34 UTC (rev 12131)
+++ CalendarServer/branches/users/gaya/sharedgroupfixes/txdav/common/inotifications.py	2013-12-19 01:14:42 UTC (rev 12132)
@@ -72,10 +72,10 @@
             object exists.
         """
 
-    def writeNotificationObject(uid, xmltype, xmldata): #@NoSelf
+    def writeNotificationObject(uid, notificationtype, notificationdata): #@NoSelf
         """
         Write a notification with the given C{uid} in this notification
-        collection from the given C{xmldata} with given C{xmltype}.  If a
+        collection from the given C{notificationdata} with given C{notificationtype}.  If a
         L{INotificationObject} with the same uid already exists in this
         L{INotificationCollection}, it will be overwritten.
 
@@ -83,18 +83,12 @@
             written.
         @type uid: C{str}
 
-        @param xmltype: the node within the notification payload, emptied of
-            its children, to indicate the type of notification and fill out the
-            C{CS:notificationtype} property.
+        @param notificationtype: the type of notification as a C{dict}.
 
-        @type xmltype: an instance of
-            L{txdav.xml.base.WebDAVElement},
-            most likely a subclass like L{twistedcaldav.customxml.InviteReply},
-            L{twistedcaldav.customxml.InviteRemove}, etc.
+        @type notificationtype: C{dict}
 
-        @param xmldata: the serialized representation of the C{CS:notification}
-            node.
-        @type xmldata: C{str}
+        @param notificationdata: the representation of the notification data as a C{dict}.
+        @type notificationdata: C{dict}
         """
 
     def removeNotificationObjectWithName(name): #@NoSelf
@@ -142,23 +136,23 @@
     An notification object describes an XML notification.
     """
 
-    def setData(uid, xmltype, xmldata, inserting=False): #@NoSelf
+    def setData(uid, notificationtype, notificationdata, inserting=False): #@NoSelf
         """
-        Rewrite this notification object to match the given C{xmltype} and
-        C{xmldata}. C{xmldata} must have the same UID as this notification object.
+        Rewrite this notification object to match the given C{notificationtype} and
+        C{notificationdata}. C{notificationdata} must have the same UID as this notification object.
 
-        @param xmltype: a string.
-        @param xmldata: a string.
+        @param notificationtype: a string.
+        @param notificationdata: a string.
         @raise InvalidObjectResourceError: if the given
-            C{xmltype} or C{xmldata} is not a valid for
+            C{notificationtype} or C{notificationdata} is not a valid for
             an notification object.
         """
 
-    def xmldata(): #@NoSelf
+    def notificationData(): #@NoSelf
         """
         Retrieve the notification data for this notification object.
 
-        @return: a string.
+        @return: a C{dict}.
         """
 
     def uid(): #@NoSelf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20140312/990cfa7e/attachment.html>


More information about the calendarserver-changes mailing list