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

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

<h3>Log Message</h3>
<pre>Checkpoint: cross-pod managed attachments.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServerbranchesuserscdaboocrosspodsharingtxdavcaldavdatastoresql_externalpy">CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/caldav/datastore/sql_external.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingconduitpy">CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/conduit.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingrequestpy">CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/request.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingresourcepy">CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/resource.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingtesttest_conduitpy">CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/test_conduit.py</a></li>
<li><a href="#CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingtestutilpy">CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/util.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServerbranchesuserscdaboocrosspodsharingtxdavcaldavdatastoresql_externalpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/caldav/datastore/sql_external.py (12189 => 12190)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/caldav/datastore/sql_external.py        2013-12-23 16:36:11 UTC (rev 12189)
+++ CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/caldav/datastore/sql_external.py        2013-12-23 16:38:46 UTC (rev 12190)
</span><span class="lines">@@ -18,7 +18,7 @@
</span><span class="cx"> SQL backend for CalDAV storage when resources are external.
</span><span class="cx"> &quot;&quot;&quot;
</span><span class="cx"> 
</span><del>-from twisted.internet.defer import succeed
</del><ins>+from twisted.internet.defer import succeed, inlineCallbacks, returnValue
</ins><span class="cx"> 
</span><span class="cx"> from twext.python.log import Logger
</span><span class="cx"> 
</span><span class="lines">@@ -179,4 +179,39 @@
</span><span class="cx">         raise AssertionError(&quot;CalendarObjectExternal: not supported&quot;)
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+    @inlineCallbacks
+    def addAttachment(self, rids, content_type, filename, stream):
+        result = yield self._txn.store().conduit.send_add_attachment(self, rids, content_type, filename, stream)
+        managedID, location = result
+        returnValue((ManagedAttachmentExternal(str(managedID)), str(location),))
+
+
+    @inlineCallbacks
+    def updateAttachment(self, managed_id, content_type, filename, stream):
+        result = yield self._txn.store().conduit.send_update_attachment(self, managed_id, content_type, filename, stream)
+        managedID, location = result
+        returnValue((ManagedAttachmentExternal(str(managedID)), str(location),))
+
+
+    @inlineCallbacks
+    def removeAttachment(self, rids, managed_id):
+        yield self._txn.store().conduit.send_remove_attachment(self, rids, managed_id)
+        returnValue(None)
+
+
+
+class ManagedAttachmentExternal(object):
+    &quot;&quot;&quot;
+    Fake managed attachment object returned from L{CalendarObjectExternal.addAttachment} and
+    L{CalendarObjectExternal.updateAttachment}.
+    &quot;&quot;&quot;
+
+    def __init__(self, managedID):
+        self._managedID = managedID
+
+
+    def managedID(self):
+        return self._managedID
+
+
</ins><span class="cx"> CalendarExternal._objectResourceClass = CalendarObjectExternal
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingconduitpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/conduit.py (12189 => 12190)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/conduit.py        2013-12-23 16:36:11 UTC (rev 12189)
+++ CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/conduit.py        2013-12-23 16:38:46 UTC (rev 12190)
</span><span class="lines">@@ -108,9 +108,9 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><del>-    def sendRequest(self, txn, recipient, data):
</del><ins>+    def sendRequest(self, txn, recipient, data, stream=None, streamType=None):
</ins><span class="cx"> 
</span><del>-        request = self.conduitRequestClass(recipient.server(), data)
</del><ins>+        request = self.conduitRequestClass(recipient.server(), data, stream, streamType)
</ins><span class="cx">         try:
</span><span class="cx">             response = (yield request.doRequest(txn))
</span><span class="cx">         except Exception as e:
</span><span class="lines">@@ -137,7 +137,7 @@
</span><span class="cx">             result = {&quot;result&quot;: &quot;ok&quot;}
</span><span class="cx">             returnValue(result)
</span><span class="cx"> 
</span><del>-        method = &quot;recv_{}&quot;.format(action)
</del><ins>+        method = &quot;recv_{}&quot;.format(action.replace(&quot;-&quot;, &quot;_&quot;))
</ins><span class="cx">         if not hasattr(self, method):
</span><span class="cx">             log.error(&quot;Unsupported action: {action}&quot;, action=action)
</span><span class="cx">             raise FailedCrossPodRequestError(&quot;Unsupported action: {}&quot;.format(action))
</span><span class="lines">@@ -379,6 +379,184 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     #
</span><ins>+    # Managed attachment related apis
+    #
+
+    @inlineCallbacks
+    def send_add_attachment(self, objectResource, rids, content_type, filename, stream):
+        &quot;&quot;&quot;
+        Managed attachment addAttachment call.
+
+        @param objectResource: child resource having an attachment added
+        @type objectResource: L{CalendarObject}
+        @param rids: list of recurrence ids
+        @type rids: C{list}
+        @param content_type: content type of attachment data
+        @type content_type: L{MimeType}
+        @param filename: name of attachment
+        @type filename: C{str}
+        @param stream: attachment data stream
+        @type stream: L{IStream}
+        &quot;&quot;&quot;
+
+        actionName = &quot;add-attachment&quot;
+        shareeView = objectResource._parentCollection
+        action, recipient = self._send(actionName, shareeView, objectResource)
+        action[&quot;rids&quot;] = rids
+        action[&quot;filename&quot;] = filename
+        result = yield self.sendRequest(shareeView._txn, recipient, action, stream, content_type)
+        if result[&quot;result&quot;] == &quot;ok&quot;:
+            returnValue(result[&quot;value&quot;])
+        elif result[&quot;result&quot;] == &quot;exception&quot;:
+            raise namedClass(result[&quot;class&quot;])(result[&quot;message&quot;])
+
+
+    @inlineCallbacks
+    def recv_add_attachment(self, txn, message):
+        &quot;&quot;&quot;
+        Process an addAttachment cross-pod message. Message arguments as per L{send_add_attachment}.
+
+        @param message: message arguments
+        @type message: C{dict}
+        &quot;&quot;&quot;
+
+        actionName = &quot;add-attachment&quot;
+        _ignore_shareeView, objectResource = yield self._recv(txn, message, actionName)
+        try:
+            attachment, location = yield objectResource.addAttachment(
+                message[&quot;rids&quot;],
+                message[&quot;streamType&quot;],
+                message[&quot;filename&quot;],
+                message[&quot;stream&quot;],
+            )
+        except Exception as e:
+            returnValue({
+                &quot;result&quot;: &quot;exception&quot;,
+                &quot;class&quot;: &quot;.&quot;.join((e.__class__.__module__, e.__class__.__name__,)),
+                &quot;message&quot;: str(e),
+            })
+
+        returnValue({
+            &quot;result&quot;: &quot;ok&quot;,
+            &quot;value&quot;: (attachment.managedID(), location,),
+        })
+
+
+    @inlineCallbacks
+    def send_update_attachment(self, objectResource, managed_id, content_type, filename, stream):
+        &quot;&quot;&quot;
+        Managed attachment updateAttachment call.
+
+        @param objectResource: child resource having an attachment added
+        @type objectResource: L{CalendarObject}
+        @param managed_id: managed-id to update
+        @type managed_id: C{str}
+        @param content_type: content type of attachment data
+        @type content_type: L{MimeType}
+        @param filename: name of attachment
+        @type filename: C{str}
+        @param stream: attachment data stream
+        @type stream: L{IStream}
+        &quot;&quot;&quot;
+
+        actionName = &quot;update-attachment&quot;
+        shareeView = objectResource._parentCollection
+        action, recipient = self._send(actionName, shareeView, objectResource)
+        action[&quot;managedID&quot;] = managed_id
+        action[&quot;filename&quot;] = filename
+        result = yield self.sendRequest(shareeView._txn, recipient, action, stream, content_type)
+        if result[&quot;result&quot;] == &quot;ok&quot;:
+            returnValue(result[&quot;value&quot;])
+        elif result[&quot;result&quot;] == &quot;exception&quot;:
+            raise namedClass(result[&quot;class&quot;])(result[&quot;message&quot;])
+
+
+    @inlineCallbacks
+    def recv_update_attachment(self, txn, message):
+        &quot;&quot;&quot;
+        Process an updateAttachment cross-pod message. Message arguments as per L{send_update_attachment}.
+
+        @param message: message arguments
+        @type message: C{dict}
+        &quot;&quot;&quot;
+
+        actionName = &quot;update-attachment&quot;
+        _ignore_shareeView, objectResource = yield self._recv(txn, message, actionName)
+        try:
+            attachment, location = yield objectResource.updateAttachment(
+                message[&quot;managedID&quot;],
+                message[&quot;streamType&quot;],
+                message[&quot;filename&quot;],
+                message[&quot;stream&quot;],
+            )
+        except Exception as e:
+            returnValue({
+                &quot;result&quot;: &quot;exception&quot;,
+                &quot;class&quot;: &quot;.&quot;.join((e.__class__.__module__, e.__class__.__name__,)),
+                &quot;message&quot;: str(e),
+            })
+
+        returnValue({
+            &quot;result&quot;: &quot;ok&quot;,
+            &quot;value&quot;: (attachment.managedID(), location,),
+        })
+
+
+    @inlineCallbacks
+    def send_remove_attachment(self, objectResource, rids, managed_id):
+        &quot;&quot;&quot;
+        Managed attachment removeAttachment call.
+
+        @param objectResource: child resource having an attachment added
+        @type objectResource: L{CalendarObject}
+        @param rids: list of recurrence ids
+        @type rids: C{list}
+        @param managed_id: managed-id to update
+        @type managed_id: C{str}
+        &quot;&quot;&quot;
+
+        actionName = &quot;remove-attachment&quot;
+        shareeView = objectResource._parentCollection
+        action, recipient = self._send(actionName, shareeView, objectResource)
+        action[&quot;rids&quot;] = rids
+        action[&quot;managedID&quot;] = managed_id
+        result = yield self.sendRequest(shareeView._txn, recipient, action)
+        if result[&quot;result&quot;] == &quot;ok&quot;:
+            returnValue(result[&quot;value&quot;])
+        elif result[&quot;result&quot;] == &quot;exception&quot;:
+            raise namedClass(result[&quot;class&quot;])(result[&quot;message&quot;])
+
+
+    @inlineCallbacks
+    def recv_remove_attachment(self, txn, message):
+        &quot;&quot;&quot;
+        Process an removeAttachment cross-pod message. Message arguments as per L{send_remove_attachment}.
+
+        @param message: message arguments
+        @type message: C{dict}
+        &quot;&quot;&quot;
+
+        actionName = &quot;remove-attachment&quot;
+        _ignore_shareeView, objectResource = yield self._recv(txn, message, actionName)
+        try:
+            yield objectResource.removeAttachment(
+                message[&quot;rids&quot;],
+                message[&quot;managedID&quot;],
+            )
+        except Exception as e:
+            returnValue({
+                &quot;result&quot;: &quot;exception&quot;,
+                &quot;class&quot;: &quot;.&quot;.join((e.__class__.__module__, e.__class__.__name__,)),
+                &quot;message&quot;: str(e),
+            })
+
+        returnValue({
+            &quot;result&quot;: &quot;ok&quot;,
+            &quot;value&quot;: None,
+        })
+
+
+    #
</ins><span class="cx">     # Sharer data access related apis
</span><span class="cx">     #
</span><span class="cx"> 
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingrequestpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/request.py (12189 => 12190)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/request.py        2013-12-23 16:36:11 UTC (rev 12189)
+++ CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/request.py        2013-12-23 16:38:46 UTC (rev 12190)
</span><span class="lines">@@ -34,6 +34,7 @@
</span><span class="cx"> from twistedcaldav.util import utf8String
</span><span class="cx"> 
</span><span class="cx"> from cStringIO import StringIO
</span><ins>+import base64
</ins><span class="cx"> import json
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="lines">@@ -42,11 +43,17 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> class ConduitRequest(object):
</span><ins>+    &quot;&quot;&quot;
+    An HTTP request between pods. This is typically used to send and receive JSON data. However,
+    for attachments, we need to send the actual attachment data as the request body, so in that
+    case the JSON data is sent in an HTTP header.
+    &quot;&quot;&quot;
</ins><span class="cx"> 
</span><del>-    def __init__(self, server, data):
-
</del><ins>+    def __init__(self, server, data, stream=None, stream_type=None):
</ins><span class="cx">         self.server = server
</span><span class="cx">         self.data = json.dumps(data)
</span><ins>+        self.stream = stream
+        self.streamType = stream_type
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -102,11 +109,15 @@
</span><span class="cx"> 
</span><span class="cx">         # We need to play a trick with the request stream as we can only read it once. So we
</span><span class="cx">         # read it, store the value in a MemoryStream, and replace the request's stream with that,
</span><del>-        # so the data can be read again.
-        data = (yield allDataFromStream(request.stream))
-        iostr.write(data)
-        request.stream = MemoryStream(data if data is not None else &quot;&quot;)
-        request.stream.doStartReading = None
</del><ins>+        # so the data can be read again. Note if we are sending an attachment, we won't log
+        # the attachment data as we do not want to read it all into memory.
+        if self.stream is None:
+            data = (yield allDataFromStream(request.stream))
+            iostr.write(data)
+            request.stream = MemoryStream(data if data is not None else &quot;&quot;)
+            request.stream.doStartReading = None
+        else:
+            iostr.write(&quot;&lt;&lt;Stream Type: {}&gt;&gt;\n&quot;.format(self.streamType))
</ins><span class="cx"> 
</span><span class="cx">         iostr.write(&quot;\n\n&gt;&gt;&gt;&gt; Request end\n&quot;)
</span><span class="cx">         returnValue(iostr.getvalue())
</span><span class="lines">@@ -155,7 +166,12 @@
</span><span class="cx"> 
</span><span class="cx">         headers = Headers()
</span><span class="cx">         headers.setHeader(&quot;Host&quot;, utf8String(host + &quot;:{}&quot;.format(port)))
</span><del>-        headers.setHeader(&quot;Content-Type&quot;, MimeType(&quot;application&quot;, &quot;json&quot;, params={&quot;charset&quot;: &quot;utf-8&quot;, }))
</del><ins>+        if self.streamType:
+            # For attachments we put the base64-encoded JSON data into a header
+            headers.setHeader(&quot;Content-Type&quot;, self.streamType)
+            headers.addRawHeader(&quot;XPOD&quot;, base64.b64encode(self.data))
+        else:
+            headers.setHeader(&quot;Content-Type&quot;, MimeType(&quot;application&quot;, &quot;json&quot;, params={&quot;charset&quot;: &quot;utf-8&quot;, }))
</ins><span class="cx">         headers.setHeader(&quot;User-Agent&quot;, &quot;CalendarServer/{}&quot;.format(version))
</span><span class="cx">         headers.addRawHeader(*self.server.secretHeader())
</span><span class="cx"> 
</span><span class="lines">@@ -165,7 +181,7 @@
</span><span class="cx">         ep = GAIEndpoint(reactor, host, port, _configuredClientContextFactory() if ssl else None)
</span><span class="cx">         proto = (yield ep.connect(f))
</span><span class="cx"> 
</span><del>-        request = ClientRequest(&quot;POST&quot;, path, headers, self.data)
</del><ins>+        request = ClientRequest(&quot;POST&quot;, path, headers, self.stream if self.stream is not None else self.data)
</ins><span class="cx"> 
</span><span class="cx">         if accountingEnabledForCategory(&quot;xPod&quot;):
</span><span class="cx">             self.loggedRequest = yield self.logRequest(request)
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingresourcepy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/resource.py (12189 => 12190)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/resource.py        2013-12-23 16:36:11 UTC (rev 12189)
+++ CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/resource.py        2013-12-23 16:38:46 UTC (rev 12190)
</span><span class="lines">@@ -14,8 +14,6 @@
</span><span class="cx"> # limitations under the License.
</span><span class="cx"> ##
</span><span class="cx"> 
</span><del>-import json
-
</del><span class="cx"> from twext.web2 import responsecode
</span><span class="cx"> from twext.web2.dav.noneprops import NonePropertyStore
</span><span class="cx"> from twext.web2.dav.util import allDataFromStream
</span><span class="lines">@@ -34,6 +32,9 @@
</span><span class="cx"> from txdav.caldav.datastore.scheduling.ischedule.localservers import Servers
</span><span class="cx"> from txdav.common.datastore.podding.conduit import FailedCrossPodRequestError
</span><span class="cx"> 
</span><ins>+import base64
+import json
+
</ins><span class="cx"> __all__ = [
</span><span class="cx">     &quot;ConduitResource&quot;,
</span><span class="cx"> ]
</span><span class="lines">@@ -125,20 +126,33 @@
</span><span class="cx">             self.log.error(&quot;Invalid shared secret header in cross-pod request&quot;)
</span><span class="cx">             raise HTTPError(StatusResponse(responsecode.FORBIDDEN, &quot;Not authorized to make this request&quot;))
</span><span class="cx"> 
</span><del>-        # Check content first
</del><ins>+        # Look for XPOD header
+        xpod = request.headers.getRawHeaders(&quot;XPOD&quot;)
</ins><span class="cx">         contentType = request.headers.getHeader(&quot;content-type&quot;)
</span><ins>+        if xpod is not None:
+            # Attachments are sent in the request body with the JSON data in a header. We
+            # decode the header and add the request.stream as an attribute of the JSON object.
+            xpod = xpod[0]
+            try:
+                j = json.loads(base64.b64decode(xpod))
+            except (TypeError, ValueError) as e:
+                self.log.error(&quot;Invalid JSON header in request: {ex}\n{xpod}&quot;, ex=e, xpod=xpod)
+                raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, &quot;Invalid JSON header in request: {}\n{}&quot;.format(e, xpod)))
+            j[&quot;stream&quot;] = request.stream
+            j[&quot;streamType&quot;] = contentType
+        else:
+            # Check content first
+            if &quot;{}/{}&quot;.format(contentType.mediaType, contentType.mediaSubtype) != &quot;application/json&quot;:
+                self.log.error(&quot;MIME type {mime} not allowed in request&quot;, mime=contentType)
+                raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, &quot;MIME type {} not allowed in request&quot;.format(contentType)))
</ins><span class="cx"> 
</span><del>-        if &quot;{}/{}&quot;.format(contentType.mediaType, contentType.mediaSubtype) != &quot;application/json&quot;:
-            self.log.error(&quot;MIME type {mime} not allowed in request&quot;, mime=contentType)
-            raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, &quot;MIME type {} not allowed in request&quot;.format(contentType)))
</del><ins>+            body = (yield allDataFromStream(request.stream))
+            try:
+                j = json.loads(body)
+            except ValueError as e:
+                self.log.error(&quot;Invalid JSON data in request: {ex}\n{body}&quot;, ex=e, body=body)
+                raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, &quot;Invalid JSON data in request: {}\n{}&quot;.format(e, body)))
</ins><span class="cx"> 
</span><del>-        body = (yield allDataFromStream(request.stream))
-        try:
-            j = json.loads(body)
-        except ValueError as e:
-            self.log.error(&quot;Invalid JSON data in request: {ex}\n{body}&quot;, ex=e, body=body)
-            raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, &quot;Invalid JSON data in request: {}\n{}&quot;.format(e, body)))
-
</del><span class="cx">         # Log extended item
</span><span class="cx">         if not hasattr(request, &quot;extendedLogItems&quot;):
</span><span class="cx">             request.extendedLogItems = {}
</span></span></pre></div>
<a id="CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingtesttest_conduitpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/test_conduit.py (12189 => 12190)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/test_conduit.py        2013-12-23 16:36:11 UTC (rev 12189)
+++ CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/test_conduit.py        2013-12-23 16:38:46 UTC (rev 12190)
</span><span class="lines">@@ -18,6 +18,9 @@
</span><span class="cx"> from pycalendar.period import Period
</span><span class="cx"> 
</span><span class="cx"> from twext.python.clsprop import classproperty
</span><ins>+import twext.web2.dav.test.util
+from twext.web2.http_headers import MimeType
+from twext.web2.stream import MemoryStream
</ins><span class="cx"> 
</span><span class="cx"> from twisted.internet.defer import inlineCallbacks, succeed, returnValue
</span><span class="cx"> 
</span><span class="lines">@@ -28,6 +31,8 @@
</span><span class="cx"> from txdav.caldav.datastore.query.filter import Filter
</span><span class="cx"> from txdav.caldav.datastore.scheduling.freebusy import generateFreeBusyInfo
</span><span class="cx"> from txdav.caldav.datastore.scheduling.ischedule.localservers import Servers, Server
</span><ins>+from txdav.caldav.datastore.sql import ManagedAttachment
+from txdav.caldav.datastore.test.common import CaptureProtocol
</ins><span class="cx"> from txdav.caldav.datastore.test.util import buildCalendarStore, \
</span><span class="cx">     TestCalendarStoreDirectoryRecord
</span><span class="cx"> from txdav.common.datastore.podding.conduit import PoddingConduit, \
</span><span class="lines">@@ -41,7 +46,6 @@
</span><span class="cx">     ObjectResourceNameNotAllowedError
</span><span class="cx"> from txdav.common.idirectoryservice import DirectoryRecordNotFoundError
</span><span class="cx"> 
</span><del>-import twext.web2.dav.test.util
</del><span class="cx"> 
</span><span class="cx"> class TestConduit (CommonCommonTests, twext.web2.dav.test.util.TestCase):
</span><span class="cx"> 
</span><span class="lines">@@ -967,3 +971,112 @@
</span><span class="cx">         self.assertEqual(len(fbinfo[1]), 0)
</span><span class="cx">         self.assertEqual(len(fbinfo[2]), 0)
</span><span class="cx">         yield self.otherCommit()
</span><ins>+
+
+    def attachmentToString(self, attachment):
+        &quot;&quot;&quot;
+        Convenience to convert an L{IAttachment} to a string.
+
+        @param attachment: an L{IAttachment} provider to convert into a string.
+
+        @return: a L{Deferred} that fires with the contents of the attachment.
+
+        @rtype: L{Deferred} firing C{bytes}
+        &quot;&quot;&quot;
+        capture = CaptureProtocol()
+        attachment.retrieve(capture)
+        return capture.deferred
+
+
+    @inlineCallbacks
+    def test_add_attachment(self):
+        &quot;&quot;&quot;
+        Test that action=add-attachment works.
+        &quot;&quot;&quot;
+
+        yield self.createShare(&quot;user01&quot;, &quot;puser01&quot;)
+
+        calendar1 = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        object1 = yield  calendar1.createCalendarObjectWithName(&quot;1.ics&quot;, Component.fromString(self.caldata1))
+        resourceID = object1.id()
+        yield self.commit()
+
+        shared_object = yield self.calendarObjectUnderTest(txn=self.newOtherTransaction(), home=&quot;puser01&quot;, calendar_name=&quot;shared-calendar&quot;, name=&quot;1.ics&quot;)
+        attachment, location = yield shared_object.addAttachment(None, MimeType.fromString(&quot;text/plain&quot;), &quot;test.txt&quot;, MemoryStream(&quot;Here is some text.&quot;))
+        managedID = attachment.managedID()
+        from txdav.caldav.datastore.sql_external import ManagedAttachmentExternal
+        self.assertTrue(isinstance(attachment, ManagedAttachmentExternal))
+        self.assertTrue(&quot;user01/attachments/test&quot; in location)
+        yield self.otherCommit()
+
+        cobjs = yield ManagedAttachment.referencesTo(self.transactionUnderTest(), managedID)
+        self.assertEqual(cobjs, set((resourceID,)))
+        attachment = yield ManagedAttachment.load(self.transactionUnderTest(), resourceID, managedID)
+        self.assertEqual(attachment.name(), &quot;test.txt&quot;)
+        data = yield self.attachmentToString(attachment)
+        self.assertEqual(data, &quot;Here is some text.&quot;)
+        yield self.commit()
+
+
+    @inlineCallbacks
+    def test_update_attachment(self):
+        &quot;&quot;&quot;
+        Test that action=update-attachment works.
+        &quot;&quot;&quot;
+
+        yield self.createShare(&quot;user01&quot;, &quot;puser01&quot;)
+
+        calendar1 = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        yield  calendar1.createCalendarObjectWithName(&quot;1.ics&quot;, Component.fromString(self.caldata1))
+        yield self.commit()
+
+        object1 = yield self.calendarObjectUnderTest(home=&quot;user01&quot;, calendar_name=&quot;calendar&quot;, name=&quot;1.ics&quot;)
+        resourceID = object1.id()
+        attachment, _ignore_location = yield object1.addAttachment(None, MimeType.fromString(&quot;text/plain&quot;), &quot;test.txt&quot;, MemoryStream(&quot;Here is some text.&quot;))
+        managedID = attachment.managedID()
+        yield self.commit()
+
+        shared_object = yield self.calendarObjectUnderTest(txn=self.newOtherTransaction(), home=&quot;puser01&quot;, calendar_name=&quot;shared-calendar&quot;, name=&quot;1.ics&quot;)
+        attachment, location = yield shared_object.updateAttachment(managedID, MimeType.fromString(&quot;text/plain&quot;), &quot;test.txt&quot;, MemoryStream(&quot;Here is some more text.&quot;))
+        managedID = attachment.managedID()
+        from txdav.caldav.datastore.sql_external import ManagedAttachmentExternal
+        self.assertTrue(isinstance(attachment, ManagedAttachmentExternal))
+        self.assertTrue(&quot;user01/attachments/test&quot; in location)
+        yield self.otherCommit()
+
+        cobjs = yield ManagedAttachment.referencesTo(self.transactionUnderTest(), managedID)
+        self.assertEqual(cobjs, set((resourceID,)))
+        attachment = yield ManagedAttachment.load(self.transactionUnderTest(), resourceID, managedID)
+        self.assertEqual(attachment.name(), &quot;test.txt&quot;)
+        data = yield self.attachmentToString(attachment)
+        self.assertEqual(data, &quot;Here is some more text.&quot;)
+        yield self.commit()
+
+
+    @inlineCallbacks
+    def test_remove_attachment(self):
+        &quot;&quot;&quot;
+        Test that action=remove-attachment works.
+        &quot;&quot;&quot;
+
+        yield self.createShare(&quot;user01&quot;, &quot;puser01&quot;)
+
+        calendar1 = yield self.calendarUnderTest(home=&quot;user01&quot;, name=&quot;calendar&quot;)
+        yield  calendar1.createCalendarObjectWithName(&quot;1.ics&quot;, Component.fromString(self.caldata1))
+        yield self.commit()
+
+        object1 = yield self.calendarObjectUnderTest(home=&quot;user01&quot;, calendar_name=&quot;calendar&quot;, name=&quot;1.ics&quot;)
+        resourceID = object1.id()
+        attachment, _ignore_location = yield object1.addAttachment(None, MimeType.fromString(&quot;text/plain&quot;), &quot;test.txt&quot;, MemoryStream(&quot;Here is some text.&quot;))
+        managedID = attachment.managedID()
+        yield self.commit()
+
+        shared_object = yield self.calendarObjectUnderTest(txn=self.newOtherTransaction(), home=&quot;puser01&quot;, calendar_name=&quot;shared-calendar&quot;, name=&quot;1.ics&quot;)
+        yield shared_object.removeAttachment(None, managedID)
+        yield self.otherCommit()
+
+        cobjs = yield ManagedAttachment.referencesTo(self.transactionUnderTest(), managedID)
+        self.assertEqual(cobjs, set())
+        attachment = yield ManagedAttachment.load(self.transactionUnderTest(), resourceID, managedID)
+        self.assertTrue(attachment is None)
+        yield self.commit()
</ins></span></pre></div>
<a id="CalendarServerbranchesuserscdaboocrosspodsharingtxdavcommondatastorepoddingtestutilpy"></a>
<div class="modfile"><h4>Modified: CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/util.py (12189 => 12190)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/util.py        2013-12-23 16:36:11 UTC (rev 12189)
+++ CalendarServer/branches/users/cdaboo/cross-pod-sharing/txdav/common/datastore/podding/test/util.py        2013-12-23 16:38:46 UTC (rev 12190)
</span><span class="lines">@@ -51,10 +51,12 @@
</span><span class="cx">         cls.storeMap[server.details()] = store
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-    def __init__(self, server, data):
</del><ins>+    def __init__(self, server, data, stream=None, stream_type=None):
</ins><span class="cx"> 
</span><span class="cx">         self.server = server
</span><span class="cx">         self.data = json.dumps(data)
</span><ins>+        self.stream = stream
+        self.streamType = stream_type
</ins><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx">     @inlineCallbacks
</span><span class="lines">@@ -80,7 +82,11 @@
</span><span class="cx">         &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">         store = self.storeMap[self.server.details()]
</span><del>-        result = yield store.conduit.processRequest(json.loads(self.data))
</del><ins>+        j = json.loads(self.data)
+        if self.stream is not None:
+            j[&quot;stream&quot;] = self.stream
+            j[&quot;streamType&quot;] = self.streamType
+        result = yield store.conduit.processRequest(j)
</ins><span class="cx">         result = json.dumps(result)
</span><span class="cx">         returnValue(result)
</span><span class="cx"> 
</span></span></pre>
</div>
</div>

</body>
</html>