xmlutils.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. }
  34. for short, url in NAMESPACES.items():
  35. ET._namespace_map[url] = short
  36. def _pretty_xml(element, level=0):
  37. """Indent an ElementTree ``element`` and its children."""
  38. i = "\n" + level * " "
  39. if len(element):
  40. if not element.text or not element.text.strip():
  41. element.text = i + " "
  42. if not element.tail or not element.tail.strip():
  43. element.tail = i
  44. for sub_element in element:
  45. _pretty_xml(sub_element, level + 1)
  46. # ``sub_element`` is always defined as len(element) > 0
  47. # pylint: disable=W0631
  48. if not sub_element.tail or not sub_element.tail.strip():
  49. sub_element.tail = i
  50. # pylint: enable=W0631
  51. else:
  52. if level and (not element.tail or not element.tail.strip()):
  53. element.tail = i
  54. if not level:
  55. return ET.tostring(element, config.get("encoding", "request"))
  56. def _tag(short_name, local):
  57. """Get XML Clark notation {uri(``short_name``)}``local``."""
  58. return "{%s}%s" % (NAMESPACES[short_name], local)
  59. def _response(code):
  60. """Return full W3C names from HTTP status codes."""
  61. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  62. def name_from_path(path, calendar):
  63. """Return Radicale item name from ``path``."""
  64. calendar_parts = calendar.local_path.strip("/").split("/")
  65. path_parts = path.strip("/").split("/")
  66. return path_parts[-1] if (len(path_parts) - len(calendar_parts)) else None
  67. def delete(path, calendar):
  68. """Read and answer DELETE requests.
  69. Read rfc4918-9.6 for info.
  70. """
  71. # Reading request
  72. calendar.remove(name_from_path(path, calendar))
  73. # Writing answer
  74. multistatus = ET.Element(_tag("D", "multistatus"))
  75. response = ET.Element(_tag("D", "response"))
  76. multistatus.append(response)
  77. href = ET.Element(_tag("D", "href"))
  78. href.text = path
  79. response.append(href)
  80. status = ET.Element(_tag("D", "status"))
  81. status.text = _response(200)
  82. response.append(status)
  83. return _pretty_xml(multistatus)
  84. def propfind(path, xml_request, calendar, depth):
  85. """Read and answer PROPFIND requests.
  86. Read rfc4918-9.1 for info.
  87. """
  88. # Reading request
  89. root = ET.fromstring(xml_request)
  90. prop_element = root.find(_tag("D", "prop"))
  91. props = [prop.tag for prop in prop_element]
  92. # Writing answer
  93. multistatus = ET.Element(_tag("D", "multistatus"))
  94. if calendar:
  95. if depth == "0":
  96. items = [calendar]
  97. else:
  98. # Depth is 1, infinity or not specified
  99. # We limit ourselves to depth == 1
  100. items = [calendar] + calendar.components
  101. else:
  102. items = []
  103. for item in items:
  104. is_calendar = isinstance(item, ical.Calendar)
  105. response = ET.Element(_tag("D", "response"))
  106. multistatus.append(response)
  107. href = ET.Element(_tag("D", "href"))
  108. href.text = path if is_calendar else path + item.name
  109. response.append(href)
  110. propstat = ET.Element(_tag("D", "propstat"))
  111. response.append(propstat)
  112. prop = ET.Element(_tag("D", "prop"))
  113. propstat.append(prop)
  114. for tag in props:
  115. element = ET.Element(tag)
  116. if tag == _tag("D", "resourcetype") and is_calendar:
  117. tag = ET.Element(_tag("C", "calendar"))
  118. element.append(tag)
  119. tag = ET.Element(_tag("D", "collection"))
  120. element.append(tag)
  121. elif tag == _tag("D", "owner"):
  122. if calendar.owner:
  123. element.text = calendar.owner
  124. elif tag == _tag("D", "getcontenttype"):
  125. element.text = "text/calendar"
  126. elif tag == _tag("CS", "getctag") and is_calendar:
  127. element.text = item.etag
  128. elif tag == _tag("D", "getetag"):
  129. element.text = item.etag
  130. elif tag == _tag("D", "displayname") and is_calendar:
  131. element.text = calendar.name
  132. elif tag == _tag("D", "principal-URL"):
  133. # TODO: use a real principal URL, read rfc3744-4.2 for info
  134. tag = ET.Element(_tag("D", "href"))
  135. tag.text = path
  136. element.append(tag)
  137. elif tag in (
  138. _tag("D", "principal-collection-set"),
  139. _tag("C", "calendar-user-address-set"),
  140. _tag("C", "calendar-home-set")):
  141. tag = ET.Element(_tag("D", "href"))
  142. tag.text = path
  143. element.append(tag)
  144. elif tag == _tag("C", "supported-calendar-component-set"):
  145. # This is not a Todo
  146. # pylint: disable=W0511
  147. for component in ("VTODO", "VEVENT", "VJOURNAL"):
  148. comp = ET.Element(_tag("C", "comp"))
  149. comp.set("name", component)
  150. element.append(comp)
  151. # pylint: enable=W0511
  152. elif tag == _tag("D", "current-user-privilege-set"):
  153. privilege = ET.Element(_tag("D", "privilege"))
  154. privilege.append(ET.Element(_tag("D", "all")))
  155. element.append(privilege)
  156. elif tag == _tag("D", "supported-report-set"):
  157. for report_name in (
  158. "principal-property-search", "sync-collection"
  159. "expand-property", "principal-search-property-set"):
  160. supported = ET.Element(_tag("D", "supported-report"))
  161. report_tag = ET.Element(_tag("D", "report"))
  162. report_tag.text = report_name
  163. supported.append(report_tag)
  164. element.append(supported)
  165. prop.append(element)
  166. status = ET.Element(_tag("D", "status"))
  167. status.text = _response(200)
  168. propstat.append(status)
  169. return _pretty_xml(multistatus)
  170. def proppatch(path, xml_request, calendar):
  171. """Read and answer PROPPATCH requests.
  172. Read rfc4918-9.2 for info.
  173. """
  174. # Reading request
  175. root = ET.fromstring(xml_request)
  176. props = []
  177. for action in ("set", "remove"):
  178. action_element = root.find(_tag("D", action))
  179. if action_element is not None:
  180. prop_element = action_element.find(_tag("D", "prop"))
  181. props.extend(prop.tag for prop in prop_element)
  182. # Writing answer
  183. multistatus = ET.Element(_tag("D", "multistatus"))
  184. response = ET.Element(_tag("D", "response"))
  185. multistatus.append(response)
  186. href = ET.Element(_tag("D", "href"))
  187. href.text = path
  188. response.append(href)
  189. propstat = ET.Element(_tag("D", "propstat"))
  190. response.append(propstat)
  191. prop = ET.Element(_tag("D", "prop"))
  192. propstat.append(prop)
  193. for tag in props:
  194. element = ET.Element(tag)
  195. prop.append(element)
  196. status = ET.Element(_tag("D", "status"))
  197. status.text = _response(200)
  198. propstat.append(status)
  199. return _pretty_xml(multistatus)
  200. def put(path, ical_request, calendar):
  201. """Read PUT requests."""
  202. name = name_from_path(path, calendar)
  203. if name in (item.name for item in calendar.items):
  204. # PUT is modifying an existing item
  205. calendar.replace(name, ical_request)
  206. else:
  207. # PUT is adding a new item
  208. calendar.append(name, ical_request)
  209. def report(path, xml_request, calendar):
  210. """Read and answer REPORT requests.
  211. Read rfc3253-3.6 for info.
  212. """
  213. # Reading request
  214. root = ET.fromstring(xml_request)
  215. prop_element = root.find(_tag("D", "prop"))
  216. props = [prop.tag for prop in prop_element]
  217. if calendar:
  218. if root.tag == _tag("C", "calendar-multiget"):
  219. # Read rfc4791-7.9 for info
  220. hreferences = set(
  221. href_element.text for href_element
  222. in root.findall(_tag("D", "href")))
  223. else:
  224. hreferences = (path,)
  225. else:
  226. hreferences = ()
  227. # Writing answer
  228. multistatus = ET.Element(_tag("D", "multistatus"))
  229. for hreference in hreferences:
  230. # Check if the reference is an item or a calendar
  231. name = name_from_path(hreference, calendar)
  232. if name:
  233. # Reference is an item
  234. path = "/".join(hreference.split("/")[:-1]) + "/"
  235. items = (item for item in calendar.items if item.name == name)
  236. else:
  237. # Reference is a calendar
  238. path = hreference
  239. items = calendar.components
  240. for item in items:
  241. response = ET.Element(_tag("D", "response"))
  242. multistatus.append(response)
  243. href = ET.Element(_tag("D", "href"))
  244. href.text = path + item.name
  245. response.append(href)
  246. propstat = ET.Element(_tag("D", "propstat"))
  247. response.append(propstat)
  248. prop = ET.Element(_tag("D", "prop"))
  249. propstat.append(prop)
  250. for tag in props:
  251. element = ET.Element(tag)
  252. if tag == _tag("D", "getetag"):
  253. element.text = item.etag
  254. elif tag == _tag("C", "calendar-data"):
  255. if isinstance(item, (ical.Event, ical.Todo, ical.Journal)):
  256. element.text = ical.serialize(
  257. calendar.headers, calendar.timezones + [item])
  258. prop.append(element)
  259. status = ET.Element(_tag("D", "status"))
  260. status.text = _response(200)
  261. propstat.append(status)
  262. return _pretty_xml(multistatus)