xmlutils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008-2011 Guillaume Ayoub
  5. # Copyright © 2008 Nicolas Kandel
  6. # Copyright © 2008 Pascal Halter
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. XML and iCal requests manager.
  22. Note that all these functions need to receive unicode objects for full
  23. iCal requests (PUT) and string objects with charset correctly defined
  24. in them for XML requests (all but PUT).
  25. """
  26. import xml.etree.ElementTree as ET
  27. from radicale import client, config, ical
  28. NAMESPACES = {
  29. "C": "urn:ietf:params:xml:ns:caldav",
  30. "D": "DAV:",
  31. "CS": "http://calendarserver.org/ns/",
  32. "ICAL": "http://apple.com/ns/ical/"}
  33. for short, url in NAMESPACES.items():
  34. ET._namespace_map[url] = "" if short == "D" else short
  35. def _pretty_xml(element, level=0):
  36. """Indent an ElementTree ``element`` and its children."""
  37. i = "\n" + level * " "
  38. if len(element):
  39. if not element.text or not element.text.strip():
  40. element.text = i + " "
  41. if not element.tail or not element.tail.strip():
  42. element.tail = i
  43. for sub_element in element:
  44. _pretty_xml(sub_element, level + 1)
  45. # ``sub_element`` is always defined as len(element) > 0
  46. # pylint: disable=W0631
  47. if not sub_element.tail or not sub_element.tail.strip():
  48. sub_element.tail = i
  49. # pylint: enable=W0631
  50. else:
  51. if level and (not element.tail or not element.tail.strip()):
  52. element.tail = i
  53. if not level:
  54. return ET.tostring(element, config.get("encoding", "request"))
  55. def _tag(short_name, local):
  56. """Get XML Clark notation {uri(``short_name``)}``local``."""
  57. return "{%s}%s" % (NAMESPACES[short_name], local)
  58. def _response(code):
  59. """Return full W3C names from HTTP status codes."""
  60. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  61. def name_from_path(path, calendar):
  62. """Return Radicale item name from ``path``."""
  63. calendar_parts = calendar.local_path.strip("/").split("/")
  64. path_parts = path.strip("/").split("/")
  65. return path_parts[-1] if (len(path_parts) - len(calendar_parts)) else None
  66. def delete(path, calendar):
  67. """Read and answer DELETE requests.
  68. Read rfc4918-9.6 for info.
  69. """
  70. # Reading request
  71. calendar.remove(name_from_path(path, calendar))
  72. # Writing answer
  73. multistatus = ET.Element(_tag("D", "multistatus"))
  74. response = ET.Element(_tag("D", "response"))
  75. multistatus.append(response)
  76. href = ET.Element(_tag("D", "href"))
  77. href.text = path
  78. response.append(href)
  79. status = ET.Element(_tag("D", "status"))
  80. status.text = _response(200)
  81. response.append(status)
  82. return _pretty_xml(multistatus)
  83. def propfind(path, xml_request, calendar, depth):
  84. """Read and answer PROPFIND requests.
  85. Read rfc4918-9.1 for info.
  86. """
  87. # Reading request
  88. root = ET.fromstring(xml_request)
  89. prop_element = root.find(_tag("D", "prop"))
  90. props = [prop.tag for prop in prop_element]
  91. # Writing answer
  92. multistatus = ET.Element(_tag("D", "multistatus"))
  93. if calendar:
  94. if depth == "0":
  95. items = [calendar]
  96. else:
  97. # Depth is 1, infinity or not specified
  98. # We limit ourselves to depth == 1
  99. items = [calendar] + calendar.components
  100. else:
  101. items = []
  102. for item in items:
  103. is_calendar = isinstance(item, ical.Calendar)
  104. response = ET.Element(_tag("D", "response"))
  105. multistatus.append(response)
  106. href = ET.Element(_tag("D", "href"))
  107. href.text = path if is_calendar else path + item.name
  108. response.append(href)
  109. propstat = ET.Element(_tag("D", "propstat"))
  110. response.append(propstat)
  111. prop = ET.Element(_tag("D", "prop"))
  112. propstat.append(prop)
  113. for tag in props:
  114. element = ET.Element(tag)
  115. if tag == _tag("D", "resourcetype") and is_calendar:
  116. tag = ET.Element(_tag("C", "calendar"))
  117. element.append(tag)
  118. tag = ET.Element(_tag("D", "collection"))
  119. element.append(tag)
  120. elif tag == _tag("D", "owner"):
  121. if calendar.owner:
  122. element.text = calendar.owner
  123. elif tag == _tag("D", "getcontenttype"):
  124. element.text = "text/calendar"
  125. elif tag == _tag("CS", "getctag") and is_calendar:
  126. element.text = item.etag
  127. elif tag == _tag("D", "getetag"):
  128. element.text = item.etag
  129. elif tag == _tag("D", "displayname") and is_calendar:
  130. element.text = calendar.name
  131. elif tag == _tag("D", "principal-URL"):
  132. # TODO: use a real principal URL, read rfc3744-4.2 for info
  133. tag = ET.Element(_tag("D", "href"))
  134. tag.text = path
  135. element.append(tag)
  136. elif tag in (
  137. _tag("D", "principal-collection-set"),
  138. _tag("C", "calendar-user-address-set"),
  139. _tag("C", "calendar-home-set")):
  140. tag = ET.Element(_tag("D", "href"))
  141. tag.text = path
  142. element.append(tag)
  143. elif tag == _tag("C", "supported-calendar-component-set"):
  144. # This is not a Todo
  145. # pylint: disable=W0511
  146. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  147. comp = ET.Element(_tag("C", "comp"))
  148. comp.set("name", component)
  149. element.append(comp)
  150. # pylint: enable=W0511
  151. elif tag == _tag("D", "current-user-privilege-set"):
  152. privilege = ET.Element(_tag("D", "privilege"))
  153. privilege.append(ET.Element(_tag("D", "all")))
  154. element.append(privilege)
  155. elif tag == _tag("D", "supported-report-set"):
  156. for report_name in (
  157. "principal-property-search", "sync-collection"
  158. "expand-property", "principal-search-property-set"):
  159. supported = ET.Element(_tag("D", "supported-report"))
  160. report_tag = ET.Element(_tag("D", "report"))
  161. report_tag.text = report_name
  162. supported.append(report_tag)
  163. element.append(supported)
  164. prop.append(element)
  165. status = ET.Element(_tag("D", "status"))
  166. status.text = _response(200)
  167. propstat.append(status)
  168. return _pretty_xml(multistatus)
  169. def proppatch(path, xml_request, calendar):
  170. """Read and answer PROPPATCH requests.
  171. Read rfc4918-9.2 for info.
  172. """
  173. # Reading request
  174. root = ET.fromstring(xml_request)
  175. props = []
  176. for action in ("set", "remove"):
  177. action_element = root.find(_tag("D", action))
  178. if action_element is not None:
  179. prop_element = action_element.find(_tag("D", "prop"))
  180. props.extend(prop.tag for prop in prop_element)
  181. # Writing answer
  182. multistatus = ET.Element(_tag("D", "multistatus"))
  183. response = ET.Element(_tag("D", "response"))
  184. multistatus.append(response)
  185. href = ET.Element(_tag("D", "href"))
  186. href.text = path
  187. response.append(href)
  188. propstat = ET.Element(_tag("D", "propstat"))
  189. response.append(propstat)
  190. prop = ET.Element(_tag("D", "prop"))
  191. propstat.append(prop)
  192. for tag in props:
  193. element = ET.Element(tag)
  194. prop.append(element)
  195. status = ET.Element(_tag("D", "status"))
  196. status.text = _response(200)
  197. propstat.append(status)
  198. return _pretty_xml(multistatus)
  199. def put(path, ical_request, calendar):
  200. """Read PUT requests."""
  201. name = name_from_path(path, calendar)
  202. if name in (item.name for item in calendar.items):
  203. # PUT is modifying an existing item
  204. calendar.replace(name, ical_request)
  205. else:
  206. # PUT is adding a new item
  207. calendar.append(name, ical_request)
  208. def report(path, xml_request, calendar):
  209. """Read and answer REPORT requests.
  210. Read rfc3253-3.6 for info.
  211. """
  212. # Reading request
  213. root = ET.fromstring(xml_request)
  214. prop_element = root.find(_tag("D", "prop"))
  215. props = [prop.tag for prop in prop_element]
  216. if calendar:
  217. if root.tag == _tag("C", "calendar-multiget"):
  218. # Read rfc4791-7.9 for info
  219. hreferences = set(
  220. href_element.text for href_element
  221. in root.findall(_tag("D", "href")))
  222. else:
  223. hreferences = (path,)
  224. else:
  225. hreferences = ()
  226. # Writing answer
  227. multistatus = ET.Element(_tag("D", "multistatus"))
  228. for hreference in hreferences:
  229. # Check if the reference is an item or a calendar
  230. name = name_from_path(hreference, calendar)
  231. if name:
  232. # Reference is an item
  233. path = "/".join(hreference.split("/")[:-1]) + "/"
  234. items = (item for item in calendar.items if item.name == name)
  235. else:
  236. # Reference is a calendar
  237. path = hreference
  238. items = calendar.components
  239. for item in items:
  240. response = ET.Element(_tag("D", "response"))
  241. multistatus.append(response)
  242. href = ET.Element(_tag("D", "href"))
  243. href.text = path + item.name
  244. response.append(href)
  245. propstat = ET.Element(_tag("D", "propstat"))
  246. response.append(propstat)
  247. prop = ET.Element(_tag("D", "prop"))
  248. propstat.append(prop)
  249. for tag in props:
  250. element = ET.Element(tag)
  251. if tag == _tag("D", "getetag"):
  252. element.text = item.etag
  253. elif tag == _tag("C", "calendar-data"):
  254. if isinstance(item, (ical.Event, ical.Todo, ical.Journal)):
  255. element.text = ical.serialize(
  256. calendar.headers, calendar.timezones + [item])
  257. prop.append(element)
  258. status = ET.Element(_tag("D", "status"))
  259. status.text = _response(200)
  260. propstat.append(status)
  261. return _pretty_xml(multistatus)