1
0

xmlutils.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2015 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. XML and iCal requests manager.
  20. Note that all these functions need to receive unicode objects for full
  21. iCal requests (PUT) and string objects with charset correctly defined
  22. in them for XML requests (all but PUT).
  23. """
  24. import posixpath
  25. import re
  26. import xml.etree.ElementTree as ET
  27. from collections import OrderedDict
  28. from urllib.parse import unquote, urlparse
  29. import vobject
  30. from . import client, storage
  31. NAMESPACES = {
  32. "C": "urn:ietf:params:xml:ns:caldav",
  33. "CR": "urn:ietf:params:xml:ns:carddav",
  34. "D": "DAV:",
  35. "CS": "http://calendarserver.org/ns/",
  36. "ICAL": "http://apple.com/ns/ical/",
  37. "ME": "http://me.com/_namespace/"}
  38. NAMESPACES_REV = {}
  39. for short, url in NAMESPACES.items():
  40. NAMESPACES_REV[url] = short
  41. ET.register_namespace("" if short == "D" else short, url)
  42. CLARK_TAG_REGEX = re.compile(r"""
  43. { # {
  44. (?P<namespace>[^}]*) # namespace URL
  45. } # }
  46. (?P<tag>.*) # short tag name
  47. """, re.VERBOSE)
  48. def _pretty_xml(element, level=0):
  49. """Indent an ElementTree ``element`` and its children."""
  50. i = "\n" + level * " "
  51. if len(element):
  52. if not element.text or not element.text.strip():
  53. element.text = i + " "
  54. if not element.tail or not element.tail.strip():
  55. element.tail = i
  56. for sub_element in element:
  57. _pretty_xml(sub_element, level + 1)
  58. # ``sub_element`` is always defined as len(element) > 0
  59. # pylint: disable=W0631
  60. if not sub_element.tail or not sub_element.tail.strip():
  61. sub_element.tail = i
  62. # pylint: enable=W0631
  63. else:
  64. if level and (not element.tail or not element.tail.strip()):
  65. element.tail = i
  66. if not level:
  67. return '<?xml version="1.0"?>\n%s' % ET.tostring(element, "unicode")
  68. def _tag(short_name, local):
  69. """Get XML Clark notation {uri(``short_name``)}``local``."""
  70. return "{%s}%s" % (NAMESPACES[short_name], local)
  71. def _tag_from_clark(name):
  72. """Get a human-readable variant of the XML Clark notation tag ``name``.
  73. For a given name using the XML Clark notation, return a human-readable
  74. variant of the tag name for known namespaces. Otherwise, return the name as
  75. is.
  76. """
  77. match = CLARK_TAG_REGEX.match(name)
  78. if match and match.group("namespace") in NAMESPACES_REV:
  79. args = {
  80. "ns": NAMESPACES_REV[match.group("namespace")],
  81. "tag": match.group("tag")}
  82. return "%(ns)s:%(tag)s" % args
  83. return name
  84. def _response(code):
  85. """Return full W3C names from HTTP status codes."""
  86. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  87. def _href(collection, href):
  88. """Return prefixed href."""
  89. return "%s%s" % (
  90. collection.configuration.get("server", "base_prefix"),
  91. href.lstrip("/"))
  92. def _comp_match(item, filter_, scope="collection"):
  93. """Check whether the ``item`` matches the comp ``filter_``.
  94. If ``scope`` is ``"collection"``, the filter is applied on the
  95. item's collection. Otherwise, it's applied on the item.
  96. See rfc4791-9.7.1.
  97. """
  98. filter_length = len(filter_)
  99. if scope == "collection":
  100. tag = item.collection.get_meta("tag")
  101. else:
  102. for component in item.components():
  103. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  104. tag = component.name
  105. break
  106. else:
  107. return False
  108. if filter_length == 0:
  109. # Point #1 of rfc4791-9.7.1
  110. return filter_.get("name") == tag
  111. else:
  112. if filter_length == 1:
  113. if filter_[0].tag == _tag("C", "is-not-defined"):
  114. # Point #2 of rfc4791-9.7.1
  115. return filter_.get("name") != tag
  116. if filter_[0].tag == _tag("C", "time-range"):
  117. # Point #3 of rfc4791-9.7.1
  118. if not _time_range_match(item, filter_):
  119. return False
  120. filter_.remove(filter_[0])
  121. # Point #4 of rfc4791-9.7.1
  122. return all(
  123. _prop_match(item, child) if child.tag == _tag("C", "prop-filter")
  124. else _comp_match(item, child, scope="component")
  125. for child in filter_)
  126. def _prop_match(item, filter_):
  127. """Check whether the ``item`` matches the prop ``filter_``.
  128. See rfc4791-9.7.2 and rfc6352-10.5.1.
  129. """
  130. filter_length = len(filter_)
  131. if item.collection.get_meta("tag") == "VCALENDAR":
  132. for component in item.components():
  133. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  134. vobject_item = component
  135. else:
  136. vobject_item = item.item
  137. if filter_length == 0:
  138. # Point #1 of rfc4791-9.7.2
  139. return filter_.get("name").lower() in vobject_item.contents
  140. else:
  141. name = filter_.get("name").lower()
  142. if filter_length == 1:
  143. if filter_[0].tag == _tag("C", "is-not-defined"):
  144. # Point #2 of rfc4791-9.7.2
  145. return name not in vobject_item.contents
  146. if filter_[0].tag == _tag("C", "time-range"):
  147. # Point #3 of rfc4791-9.7.2
  148. if not _time_range_match(item, filter_[0]):
  149. return False
  150. filter_.remove(filter_[0])
  151. elif filter_[0].tag == _tag("C", "text-match"):
  152. # Point #4 of rfc4791-9.7.2
  153. if not _text_match(vobject_item, filter_[0], name):
  154. return False
  155. filter_.remove(filter_[0])
  156. return all(
  157. _param_filter_match(vobject_item, param_filter, name)
  158. for param_filter in filter_)
  159. def _time_range_match(item, filter_):
  160. """Check whether the ``item`` matches the time-range ``filter_``.
  161. See rfc4791-9.9.
  162. """
  163. # TODO: implement this
  164. return True
  165. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  166. """Check whether the ``item`` matches the text-match ``filter_``.
  167. See rfc4791-9.7.5.
  168. """
  169. # TODO: collations are not supported, but the default ones needed
  170. # for DAV servers are actually pretty useless. Texts are lowered to
  171. # be case-insensitive, almost as the "i;ascii-casemap" value.
  172. match = next(filter_.itertext()).lower()
  173. children = getattr(vobject_item, "%s_list" % child_name, [])
  174. if attrib_name:
  175. condition = any(
  176. match in attrib.lower() for child in children
  177. for attrib in child.params.get(attrib_name, []))
  178. else:
  179. condition = any(match in child.value.lower() for child in children)
  180. if filter_.get("negate-condition") == "yes":
  181. return not condition
  182. else:
  183. return condition
  184. def _param_filter_match(vobject_item, filter_, parent_name):
  185. """Check whether the ``item`` matches the param-filter ``filter_``.
  186. See rfc4791-9.7.3.
  187. """
  188. name = filter_.get("name")
  189. children = getattr(vobject_item, "%s_list" % parent_name, [])
  190. condition = any(name in child.params for child in children)
  191. if len(filter_):
  192. if filter_[0].tag == _tag("C", "text-match"):
  193. return condition and _text_match(
  194. vobject_item, filter_[0], parent_name, name)
  195. elif filter_[0].tag == _tag("C", "is-not-defined"):
  196. return not condition
  197. else:
  198. return condition
  199. def name_from_path(path, collection):
  200. """Return Radicale item name from ``path``."""
  201. collection_parts = collection.path.strip("/").split("/")
  202. path_parts = path.strip("/").split("/")
  203. if (len(path_parts) - len(collection_parts)):
  204. return path_parts[-1]
  205. def props_from_request(root, actions=("set", "remove")):
  206. """Return a list of properties as a dictionary."""
  207. result = OrderedDict()
  208. if root:
  209. if not hasattr(root, "tag"):
  210. root = ET.fromstring(root.encode("utf8"))
  211. else:
  212. return result
  213. for action in actions:
  214. action_element = root.find(_tag("D", action))
  215. if action_element is not None:
  216. break
  217. else:
  218. action_element = root
  219. prop_element = action_element.find(_tag("D", "prop"))
  220. if prop_element is not None:
  221. for prop in prop_element:
  222. if prop.tag == _tag("D", "resourcetype"):
  223. for resource_type in prop:
  224. if resource_type.tag == _tag("C", "calendar"):
  225. result["tag"] = "VCALENDAR"
  226. break
  227. elif resource_type.tag == _tag("CR", "addressbook"):
  228. result["tag"] = "VADDRESSBOOK"
  229. break
  230. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  231. result[_tag_from_clark(prop.tag)] = ",".join(
  232. supported_comp.attrib["name"]
  233. for supported_comp in prop
  234. if supported_comp.tag == _tag("C", "comp"))
  235. else:
  236. result[_tag_from_clark(prop.tag)] = prop.text
  237. return result
  238. def delete(path, collection):
  239. """Read and answer DELETE requests.
  240. Read rfc4918-9.6 for info.
  241. """
  242. # Reading request
  243. if collection.path == path.strip("/"):
  244. # Delete the whole collection
  245. collection.delete()
  246. else:
  247. # Remove an item from the collection
  248. collection.delete(name_from_path(path, collection))
  249. # Writing answer
  250. multistatus = ET.Element(_tag("D", "multistatus"))
  251. response = ET.Element(_tag("D", "response"))
  252. multistatus.append(response)
  253. href = ET.Element(_tag("D", "href"))
  254. href.text = _href(collection, path)
  255. response.append(href)
  256. status = ET.Element(_tag("D", "status"))
  257. status.text = _response(200)
  258. response.append(status)
  259. return _pretty_xml(multistatus)
  260. def propfind(path, xml_request, read_collections, write_collections,
  261. user=None):
  262. """Read and answer PROPFIND requests.
  263. Read rfc4918-9.1 for info.
  264. The collections parameter is a list of collections that are to be included
  265. in the output.
  266. """
  267. # Reading request
  268. if xml_request:
  269. root = ET.fromstring(xml_request.encode("utf8"))
  270. props = [prop.tag for prop in root.find(_tag("D", "prop"))]
  271. else:
  272. props = [_tag("D", "getcontenttype"),
  273. _tag("D", "resourcetype"),
  274. _tag("D", "displayname"),
  275. _tag("D", "owner"),
  276. _tag("D", "getetag"),
  277. _tag("ICAL", "calendar-color"),
  278. _tag("CS", "getctag")]
  279. # Writing answer
  280. multistatus = ET.Element(_tag("D", "multistatus"))
  281. collections = []
  282. for collection in write_collections:
  283. collections.append(collection)
  284. response = _propfind_response(
  285. path, collection, props, user, write=True)
  286. multistatus.append(response)
  287. for collection in read_collections:
  288. if collection in collections:
  289. continue
  290. response = _propfind_response(
  291. path, collection, props, user, write=False)
  292. multistatus.append(response)
  293. return _pretty_xml(multistatus)
  294. def _propfind_response(path, item, props, user, write=False):
  295. """Build and return a PROPFIND response."""
  296. # TODO: fix this
  297. is_collection = hasattr(item, "list")
  298. if is_collection:
  299. is_leaf = bool(item.list())
  300. collection = item
  301. else:
  302. collection = item.collection
  303. response = ET.Element(_tag("D", "response"))
  304. href = ET.Element(_tag("D", "href"))
  305. if is_collection:
  306. uri = item.path
  307. else:
  308. # TODO: fix this
  309. if path.split("/")[-1] == item.href:
  310. # Happening when depth is 0
  311. uri = path
  312. else:
  313. # Happening when depth is 1
  314. uri = "/".join((path, item.href))
  315. # TODO: fix this
  316. href.text = _href(collection, uri.replace("//", "/"))
  317. response.append(href)
  318. propstat404 = ET.Element(_tag("D", "propstat"))
  319. propstat200 = ET.Element(_tag("D", "propstat"))
  320. response.append(propstat200)
  321. prop200 = ET.Element(_tag("D", "prop"))
  322. propstat200.append(prop200)
  323. prop404 = ET.Element(_tag("D", "prop"))
  324. propstat404.append(prop404)
  325. for tag in props:
  326. element = ET.Element(tag)
  327. is404 = False
  328. if tag == _tag("D", "getetag"):
  329. element.text = item.etag
  330. elif tag == _tag("D", "principal-URL"):
  331. tag = ET.Element(_tag("D", "href"))
  332. tag.text = _href(collection, path)
  333. element.append(tag)
  334. elif tag == _tag("D", "getlastmodified"):
  335. element.text = item.last_modified
  336. elif tag in (_tag("D", "principal-collection-set"),
  337. _tag("C", "calendar-user-address-set"),
  338. _tag("CR", "addressbook-home-set"),
  339. _tag("C", "calendar-home-set")):
  340. tag = ET.Element(_tag("D", "href"))
  341. tag.text = _href(collection, path)
  342. element.append(tag)
  343. elif tag == _tag("C", "supported-calendar-component-set"):
  344. # This is not a Todo
  345. # pylint: disable=W0511
  346. human_tag = _tag_from_clark(tag)
  347. if is_collection and is_leaf:
  348. meta = item.get_meta(human_tag)
  349. if meta:
  350. components = meta.split(",")
  351. else:
  352. components = ("VTODO", "VEVENT", "VJOURNAL")
  353. for component in components:
  354. comp = ET.Element(_tag("C", "comp"))
  355. comp.set("name", component)
  356. element.append(comp)
  357. else:
  358. is404 = True
  359. # pylint: enable=W0511
  360. elif tag == _tag("D", "current-user-principal") and user:
  361. tag = ET.Element(_tag("D", "href"))
  362. tag.text = _href(collection, "/%s/" % user)
  363. element.append(tag)
  364. elif tag == _tag("D", "current-user-privilege-set"):
  365. privilege = ET.Element(_tag("D", "privilege"))
  366. if write:
  367. privilege.append(ET.Element(_tag("D", "all")))
  368. privilege.append(ET.Element(_tag("D", "write")))
  369. privilege.append(ET.Element(_tag("D", "write-properties")))
  370. privilege.append(ET.Element(_tag("D", "write-content")))
  371. privilege.append(ET.Element(_tag("D", "read")))
  372. element.append(privilege)
  373. elif tag == _tag("D", "supported-report-set"):
  374. for report_name in (
  375. "principal-property-search", "sync-collection",
  376. "expand-property", "principal-search-property-set"):
  377. supported = ET.Element(_tag("D", "supported-report"))
  378. report_tag = ET.Element(_tag("D", "report"))
  379. report_tag.text = report_name
  380. supported.append(report_tag)
  381. element.append(supported)
  382. elif is_collection:
  383. if tag == _tag("D", "getcontenttype"):
  384. item_tag = item.get_meta("tag")
  385. if item_tag:
  386. element.text = storage.MIMETYPES[item_tag]
  387. else:
  388. is404 = True
  389. elif tag == _tag("D", "resourcetype"):
  390. if item.is_principal:
  391. tag = ET.Element(_tag("D", "principal"))
  392. element.append(tag)
  393. item_tag = item.get_meta("tag")
  394. if is_leaf or item_tag:
  395. # 2nd case happens when the collection is not stored yet,
  396. # but the resource type is guessed
  397. if item.get_meta("tag") == "VADDRESSBOOK":
  398. tag = ET.Element(_tag("CR", "addressbook"))
  399. element.append(tag)
  400. elif item.get_meta("tag") == "VCALENDAR":
  401. tag = ET.Element(_tag("C", "calendar"))
  402. element.append(tag)
  403. tag = ET.Element(_tag("D", "collection"))
  404. element.append(tag)
  405. elif is_leaf:
  406. if tag == _tag("D", "owner") and item.owner:
  407. element.text = "/%s/" % item.owner
  408. elif tag == _tag("CS", "getctag"):
  409. element.text = item.etag
  410. elif tag == _tag("C", "calendar-timezone"):
  411. timezones = set()
  412. for href, _ in item.list():
  413. event = item.get(href)
  414. if "vtimezone" in event.contents:
  415. for timezone in event.vtimezone_list:
  416. timezones.add(timezone)
  417. collection = vobject.iCalendar()
  418. for timezone in timezones:
  419. collection.add(timezone)
  420. element.text = collection.serialize()
  421. elif tag == _tag("D", "displayname"):
  422. element.text = item.get_meta("D:displayname") or item.path
  423. elif tag == _tag("ICAL", "calendar-color"):
  424. element.text = item.get_meta("ICAL:calendar-color")
  425. else:
  426. human_tag = _tag_from_clark(tag)
  427. meta = item.get_meta(human_tag)
  428. if meta:
  429. element.text = meta
  430. else:
  431. is404 = True
  432. else:
  433. is404 = True
  434. # Not for collections
  435. elif tag == _tag("D", "getcontenttype"):
  436. name = item.name.lower()
  437. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  438. element.text = "%s; component=%s" % (mimetype, name)
  439. elif tag == _tag("D", "resourcetype"):
  440. # resourcetype must be returned empty for non-collection elements
  441. pass
  442. elif tag == _tag("D", "getcontentlength"):
  443. encoding = collection.configuration.get("encoding", "request")
  444. element.text = str(len(item.serialize().encode(encoding)))
  445. else:
  446. is404 = True
  447. if is404:
  448. prop404.append(element)
  449. else:
  450. prop200.append(element)
  451. status200 = ET.Element(_tag("D", "status"))
  452. status200.text = _response(200)
  453. propstat200.append(status200)
  454. status404 = ET.Element(_tag("D", "status"))
  455. status404.text = _response(404)
  456. propstat404.append(status404)
  457. if len(prop404):
  458. response.append(propstat404)
  459. return response
  460. def _add_propstat_to(element, tag, status_number):
  461. """Add a PROPSTAT response structure to an element.
  462. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  463. given ``element``, for the following ``tag`` with the given
  464. ``status_number``.
  465. """
  466. propstat = ET.Element(_tag("D", "propstat"))
  467. element.append(propstat)
  468. prop = ET.Element(_tag("D", "prop"))
  469. propstat.append(prop)
  470. if "{" in tag:
  471. clark_tag = tag
  472. else:
  473. clark_tag = _tag(*tag.split(":", 1))
  474. prop_tag = ET.Element(clark_tag)
  475. prop.append(prop_tag)
  476. status = ET.Element(_tag("D", "status"))
  477. status.text = _response(status_number)
  478. propstat.append(status)
  479. def proppatch(path, xml_request, collection):
  480. """Read and answer PROPPATCH requests.
  481. Read rfc4918-9.2 for info.
  482. """
  483. # Reading request
  484. root = ET.fromstring(xml_request.encode("utf8"))
  485. props_to_set = props_from_request(root, actions=("set",))
  486. props_to_remove = props_from_request(root, actions=("remove",))
  487. # Writing answer
  488. multistatus = ET.Element(_tag("D", "multistatus"))
  489. response = ET.Element(_tag("D", "response"))
  490. multistatus.append(response)
  491. href = ET.Element(_tag("D", "href"))
  492. href.text = _href(collection, path)
  493. response.append(href)
  494. for short_name, value in props_to_set.items():
  495. collection.set_meta(short_name, value)
  496. _add_propstat_to(response, short_name, 200)
  497. for short_name in props_to_remove:
  498. collection.set_meta(short_name, '')
  499. _add_propstat_to(response, short_name, 200)
  500. return _pretty_xml(multistatus)
  501. def report(path, xml_request, collection):
  502. """Read and answer REPORT requests.
  503. Read rfc3253-3.6 for info.
  504. """
  505. # Reading request
  506. root = ET.fromstring(xml_request.encode("utf8"))
  507. prop_element = root.find(_tag("D", "prop"))
  508. props = (
  509. [prop.tag for prop in prop_element]
  510. if prop_element is not None else [])
  511. if collection:
  512. if root.tag in (_tag("C", "calendar-multiget"),
  513. _tag("CR", "addressbook-multiget")):
  514. # Read rfc4791-7.9 for info
  515. base_prefix = collection.configuration.get("server", "base_prefix")
  516. hreferences = set()
  517. for href_element in root.findall(_tag("D", "href")):
  518. href_path = unquote(urlparse(href_element.text).path)
  519. if href_path.startswith(base_prefix):
  520. hreferences.add(href_path[len(base_prefix) - 1:])
  521. else:
  522. hreferences = (path,)
  523. filters = (
  524. root.findall(".//%s" % _tag("C", "filter")) +
  525. root.findall(".//%s" % _tag("CR", "filter")))
  526. else:
  527. hreferences = filters = ()
  528. # Writing answer
  529. multistatus = ET.Element(_tag("D", "multistatus"))
  530. for hreference in hreferences:
  531. # Check if the reference is an item or a collection
  532. name = name_from_path(hreference, collection)
  533. if name:
  534. # Reference is an item
  535. path = "/".join(hreference.split("/")[:-1]) + "/"
  536. item = collection.get(name)
  537. if item is None:
  538. multistatus.append(
  539. _item_response(hreference, found_item=False))
  540. continue
  541. items = [item]
  542. else:
  543. # Reference is a collection
  544. path = hreference
  545. items = [collection.get(href) for href, etag in collection.list()]
  546. for item in items:
  547. if filters:
  548. match = (
  549. _comp_match if collection.get_meta("tag") == "VCALENDAR"
  550. else _prop_match)
  551. if not all(match(item, filter_[0]) for filter_ in filters):
  552. continue
  553. found_props = []
  554. not_found_props = []
  555. for tag in props:
  556. element = ET.Element(tag)
  557. if tag == _tag("D", "getetag"):
  558. element.text = item.etag
  559. found_props.append(element)
  560. elif tag == _tag("D", "getcontenttype"):
  561. name = item.name.lower()
  562. mimetype = (
  563. "text/vcard" if name == "vcard" else "text/calendar")
  564. element.text = "%s; component=%s" % (mimetype, name)
  565. found_props.append(element)
  566. elif tag in (_tag("C", "calendar-data"),
  567. _tag("CR", "address-data")):
  568. element.text = item.serialize()
  569. found_props.append(element)
  570. else:
  571. not_found_props.append(element)
  572. # TODO: fix this
  573. if hreference.split("/")[-1] == item.href:
  574. # Happening when depth is 0
  575. uri = hreference
  576. else:
  577. # Happening when depth is 1
  578. uri = posixpath.join(hreference, item.href)
  579. multistatus.append(_item_response(
  580. uri, found_props=found_props,
  581. not_found_props=not_found_props, found_item=True))
  582. return _pretty_xml(multistatus)
  583. def _item_response(href, found_props=(), not_found_props=(), found_item=True):
  584. response = ET.Element(_tag("D", "response"))
  585. href_tag = ET.Element(_tag("D", "href"))
  586. href_tag.text = href
  587. response.append(href_tag)
  588. if found_item:
  589. if found_props:
  590. propstat = ET.Element(_tag("D", "propstat"))
  591. status = ET.Element(_tag("D", "status"))
  592. status.text = _response(200)
  593. prop = ET.Element(_tag("D", "prop"))
  594. for p in found_props:
  595. prop.append(p)
  596. propstat.append(prop)
  597. propstat.append(status)
  598. response.append(propstat)
  599. if not_found_props:
  600. propstat = ET.Element(_tag("D", "propstat"))
  601. status = ET.Element(_tag("D", "status"))
  602. status.text = _response(404)
  603. prop = ET.Element(_tag("D", "prop"))
  604. for p in not_found_props:
  605. prop.append(p)
  606. propstat.append(prop)
  607. propstat.append(status)
  608. response.append(propstat)
  609. else:
  610. status = ET.Element(_tag("D", "status"))
  611. status.text = _response(404)
  612. response.append(status)
  613. return response