xmlutils.py 12 KB

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