xmlutils.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2015 Guillaume Ayoub
  5. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. Helper functions for XML.
  21. """
  22. import copy
  23. import xml.etree.ElementTree as ET
  24. from collections import OrderedDict
  25. from http import client
  26. from typing import Dict, Mapping, Optional
  27. from urllib.parse import quote
  28. from radicale import item, pathutils
  29. MIMETYPES: Mapping[str, str] = {
  30. "VADDRESSBOOK": "text/vcard",
  31. "VCALENDAR": "text/calendar",
  32. "VSUBSCRIBED": "text/calendar"}
  33. OBJECT_MIMETYPES: Mapping[str, str] = {
  34. "VCARD": "text/vcard",
  35. "VLIST": "text/x-vlist",
  36. "VCALENDAR": "text/calendar"}
  37. NAMESPACES: Mapping[str, str] = {
  38. "C": "urn:ietf:params:xml:ns:caldav",
  39. "CR": "urn:ietf:params:xml:ns:carddav",
  40. "D": "DAV:",
  41. "CS": "http://calendarserver.org/ns/",
  42. "ICAL": "http://apple.com/ns/ical/",
  43. "ME": "http://me.com/_namespace/",
  44. "RADICALE": "http://radicale.org/ns/"}
  45. NAMESPACES_REV: Mapping[str, str] = {v: k for k, v in NAMESPACES.items()}
  46. for short, url in NAMESPACES.items():
  47. ET.register_namespace("" if short == "D" else short, url)
  48. def pretty_xml(element: ET.Element) -> str:
  49. """Indent an ElementTree ``element`` and its children."""
  50. def pretty_xml_recursive(element: ET.Element, level: int) -> None:
  51. indent = "\n" + level * " "
  52. if len(element) > 0:
  53. if not (element.text or "").strip():
  54. element.text = indent + " "
  55. if not (element.tail or "").strip():
  56. element.tail = indent
  57. for sub_element in element:
  58. pretty_xml_recursive(sub_element, level + 1)
  59. if not (sub_element.tail or "").strip():
  60. sub_element.tail = indent
  61. elif level > 0 and not (element.tail or "").strip():
  62. element.tail = indent
  63. element = copy.deepcopy(element)
  64. pretty_xml_recursive(element, 0)
  65. return '<?xml version="1.0"?>\n%s' % ET.tostring(element, "unicode")
  66. def make_clark(human_tag: str) -> str:
  67. """Get XML Clark notation from human tag ``human_tag``.
  68. If ``human_tag`` is already in XML Clark notation it is returned as-is.
  69. """
  70. if human_tag.startswith("{"):
  71. ns, tag = human_tag[len("{"):].split("}", maxsplit=1)
  72. if not ns or not tag:
  73. raise ValueError("Invalid XML tag: %r" % human_tag)
  74. return human_tag
  75. ns_prefix, tag = human_tag.split(":", maxsplit=1)
  76. if not ns_prefix or not tag:
  77. raise ValueError("Invalid XML tag: %r" % human_tag)
  78. ns = NAMESPACES.get(ns_prefix, "")
  79. if not ns:
  80. raise ValueError("Unknown XML namespace prefix: %r" % human_tag)
  81. return "{%s}%s" % (ns, tag)
  82. def make_human_tag(clark_tag: str) -> str:
  83. """Replace known namespaces in XML Clark notation ``clark_tag`` with
  84. prefix.
  85. If the namespace is not in ``NAMESPACES`` the tag is returned as-is.
  86. """
  87. if not clark_tag.startswith("{"):
  88. ns_prefix, tag = clark_tag.split(":", maxsplit=1)
  89. if not ns_prefix or not tag:
  90. raise ValueError("Invalid XML tag: %r" % clark_tag)
  91. if ns_prefix not in NAMESPACES:
  92. raise ValueError("Unknown XML namespace prefix: %r" % clark_tag)
  93. return clark_tag
  94. ns, tag = clark_tag[len("{"):].split("}", maxsplit=1)
  95. if not ns or not tag:
  96. raise ValueError("Invalid XML tag: %r" % clark_tag)
  97. ns_prefix = NAMESPACES_REV.get(ns, "")
  98. if ns_prefix:
  99. return "%s:%s" % (ns_prefix, tag)
  100. return clark_tag
  101. def make_response(code: int) -> str:
  102. """Return full W3C names from HTTP status codes."""
  103. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  104. def make_href(base_prefix: str, href: str) -> str:
  105. """Return prefixed href."""
  106. assert href == pathutils.sanitize_path(href)
  107. return quote("%s%s" % (base_prefix, href))
  108. def webdav_error(human_tag: str) -> ET.Element:
  109. """Generate XML error message."""
  110. root = ET.Element(make_clark("D:error"))
  111. root.append(ET.Element(make_clark(human_tag)))
  112. return root
  113. def get_content_type(item: "item.Item", encoding: str) -> str:
  114. """Get the content-type of an item with charset and component parameters.
  115. """
  116. mimetype = OBJECT_MIMETYPES[item.name]
  117. tag = item.component_name
  118. content_type = "%s;charset=%s" % (mimetype, encoding)
  119. if tag:
  120. content_type += ";component=%s" % tag
  121. return content_type
  122. def props_from_request(xml_request: Optional[ET.Element]
  123. ) -> Dict[str, Optional[str]]:
  124. """Return a list of properties as a dictionary.
  125. Properties that should be removed are set to `None`.
  126. """
  127. result: OrderedDict = OrderedDict()
  128. if xml_request is None:
  129. return result
  130. # Requests can contain multipe <D:set> and <D:remove> elements.
  131. # Each of these elements must contain exactly one <D:prop> element which
  132. # can contain multpile properties.
  133. # The order of the elements in the document must be respected.
  134. props = []
  135. for element in xml_request:
  136. if element.tag in (make_clark("D:set"), make_clark("D:remove")):
  137. for prop in element.findall("./%s/*" % make_clark("D:prop")):
  138. props.append((element.tag == make_clark("D:set"), prop))
  139. for is_set, prop in props:
  140. key = make_human_tag(prop.tag)
  141. value = None
  142. if prop.tag == make_clark("D:resourcetype"):
  143. key = "tag"
  144. if is_set:
  145. for resource_type in prop:
  146. if resource_type.tag == make_clark("C:calendar"):
  147. value = "VCALENDAR"
  148. break
  149. if resource_type.tag == make_clark("CS:subscribed"):
  150. value = "VSUBSCRIBED"
  151. break
  152. if resource_type.tag == make_clark("CR:addressbook"):
  153. value = "VADDRESSBOOK"
  154. break
  155. elif prop.tag == make_clark("C:supported-calendar-component-set"):
  156. if is_set:
  157. value = ",".join(
  158. supported_comp.attrib["name"] for supported_comp in prop
  159. if supported_comp.tag == make_clark("C:comp"))
  160. elif is_set:
  161. value = prop.text or ""
  162. result[key] = value
  163. result.move_to_end(key)
  164. return result