xmlutils.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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 datetime import datetime, timedelta, timezone
  29. from urllib.parse import unquote, urlparse
  30. import vobject
  31. from . import client, storage
  32. NAMESPACES = {
  33. "C": "urn:ietf:params:xml:ns:caldav",
  34. "CR": "urn:ietf:params:xml:ns:carddav",
  35. "D": "DAV:",
  36. "CS": "http://calendarserver.org/ns/",
  37. "ICAL": "http://apple.com/ns/ical/",
  38. "ME": "http://me.com/_namespace/"}
  39. NAMESPACES_REV = {}
  40. for short, url in NAMESPACES.items():
  41. NAMESPACES_REV[url] = short
  42. ET.register_namespace("" if short == "D" else short, url)
  43. CLARK_TAG_REGEX = re.compile(r"""
  44. { # {
  45. (?P<namespace>[^}]*) # namespace URL
  46. } # }
  47. (?P<tag>.*) # short tag name
  48. """, re.VERBOSE)
  49. def _pretty_xml(element, level=0):
  50. """Indent an ElementTree ``element`` and its children."""
  51. i = "\n" + level * " "
  52. if len(element):
  53. if not element.text or not element.text.strip():
  54. element.text = i + " "
  55. if not element.tail or not element.tail.strip():
  56. element.tail = i
  57. for sub_element in element:
  58. _pretty_xml(sub_element, level + 1)
  59. # ``sub_element`` is always defined as len(element) > 0
  60. # pylint: disable=W0631
  61. if not sub_element.tail or not sub_element.tail.strip():
  62. sub_element.tail = i
  63. # pylint: enable=W0631
  64. else:
  65. if level and (not element.tail or not element.tail.strip()):
  66. element.tail = i
  67. if not level:
  68. return '<?xml version="1.0"?>\n%s' % ET.tostring(element, "unicode")
  69. def _tag(short_name, local):
  70. """Get XML Clark notation {uri(``short_name``)}``local``."""
  71. return "{%s}%s" % (NAMESPACES[short_name], local)
  72. def _tag_from_clark(name):
  73. """Get a human-readable variant of the XML Clark notation tag ``name``.
  74. For a given name using the XML Clark notation, return a human-readable
  75. variant of the tag name for known namespaces. Otherwise, return the name as
  76. is.
  77. """
  78. match = CLARK_TAG_REGEX.match(name)
  79. if match and match.group("namespace") in NAMESPACES_REV:
  80. args = {
  81. "ns": NAMESPACES_REV[match.group("namespace")],
  82. "tag": match.group("tag")}
  83. return "%(ns)s:%(tag)s" % args
  84. return name
  85. def _response(code):
  86. """Return full W3C names from HTTP status codes."""
  87. return "HTTP/1.1 %i %s" % (code, client.responses[code])
  88. def _href(collection, href):
  89. """Return prefixed href."""
  90. return "%s%s" % (
  91. collection.configuration.get("server", "base_prefix"),
  92. href.lstrip("/"))
  93. def _date_to_datetime(date_):
  94. """Transform a date to a UTC datetime.
  95. If date_ is a datetime without timezone, return as UTC datetime. If date_
  96. is already a datetime with timezone, return as is.
  97. """
  98. if not isinstance(date_, datetime):
  99. date_ = datetime.combine(date_, datetime.min.time())
  100. if not date_.tzinfo:
  101. date_ = date_.replace(tzinfo=timezone.utc)
  102. return date_
  103. def _comp_match(item, filter_, scope="collection"):
  104. """Check whether the ``item`` matches the comp ``filter_``.
  105. If ``scope`` is ``"collection"``, the filter is applied on the
  106. item's collection. Otherwise, it's applied on the item.
  107. See rfc4791-9.7.1.
  108. """
  109. filter_length = len(filter_)
  110. if scope == "collection":
  111. tag = item.collection.get_meta("tag")
  112. else:
  113. for component in item.components():
  114. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  115. tag = component.name
  116. break
  117. else:
  118. return False
  119. if filter_length == 0:
  120. # Point #1 of rfc4791-9.7.1
  121. return filter_.get("name") == tag
  122. else:
  123. if filter_length == 1:
  124. if filter_[0].tag == _tag("C", "is-not-defined"):
  125. # Point #2 of rfc4791-9.7.1
  126. return filter_.get("name") != tag
  127. if filter_[0].tag == _tag("C", "time-range"):
  128. # Point #3 of rfc4791-9.7.1
  129. if not _time_range_match(item.item, filter_[0], tag):
  130. return False
  131. filter_ = filter_[1:]
  132. # Point #4 of rfc4791-9.7.1
  133. return all(
  134. _prop_match(item, child) if child.tag == _tag("C", "prop-filter")
  135. else _comp_match(item, child, scope="component")
  136. for child in filter_)
  137. def _prop_match(item, filter_):
  138. """Check whether the ``item`` matches the prop ``filter_``.
  139. See rfc4791-9.7.2 and rfc6352-10.5.1.
  140. """
  141. filter_length = len(filter_)
  142. if item.collection.get_meta("tag") == "VCALENDAR":
  143. for component in item.components():
  144. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  145. vobject_item = component
  146. else:
  147. vobject_item = item.item
  148. if filter_length == 0:
  149. # Point #1 of rfc4791-9.7.2
  150. return filter_.get("name").lower() in vobject_item.contents
  151. else:
  152. name = filter_.get("name").lower()
  153. if filter_length == 1:
  154. if filter_[0].tag == _tag("C", "is-not-defined"):
  155. # Point #2 of rfc4791-9.7.2
  156. return name not in vobject_item.contents
  157. if filter_[0].tag == _tag("C", "time-range"):
  158. # Point #3 of rfc4791-9.7.2
  159. if not _time_range_match(vobject_item, filter_[0], name):
  160. return False
  161. filter_ = filter_[1:]
  162. elif filter_[0].tag == _tag("C", "text-match"):
  163. # Point #4 of rfc4791-9.7.2
  164. if not _text_match(vobject_item, filter_[0], name):
  165. return False
  166. filter_ = filter_[1:]
  167. return all(
  168. _param_filter_match(vobject_item, param_filter, name)
  169. for param_filter in filter_)
  170. def _time_range_match(vobject_item, filter_, child_name):
  171. """Check whether the ``item`` matches the time-range ``filter_``.
  172. See rfc4791-9.9.
  173. """
  174. start = filter_.get("start")
  175. end = filter_.get("end")
  176. if not start and not end:
  177. return False
  178. if start:
  179. start = datetime.strptime(start, "%Y%m%dT%H%M%SZ")
  180. else:
  181. start = datetime.min
  182. if end:
  183. end = datetime.strptime(end, "%Y%m%dT%H%M%SZ")
  184. else:
  185. end = datetime.max
  186. start = start.replace(tzinfo=timezone.utc)
  187. end = end.replace(tzinfo=timezone.utc)
  188. child = getattr(vobject_item, child_name.lower())
  189. # Comments give the lines in the tables of the specification
  190. if child_name == "VEVENT":
  191. # TODO: check if there's a timezone
  192. dtstart = child.dtstart.value
  193. if child.rruleset:
  194. dtstarts = child.getrruleset(addRDate=True)
  195. else:
  196. dtstarts = (dtstart,)
  197. dtend = getattr(child, "dtend", None)
  198. if dtend is not None:
  199. dtend = dtend.value
  200. original_duration = (dtend - dtstart).total_seconds()
  201. dtend = _date_to_datetime(dtend)
  202. duration = getattr(child, "duration", None)
  203. if duration is not None:
  204. original_duration = duration = duration.value
  205. for dtstart in dtstarts:
  206. dtstart_is_datetime = isinstance(dtstart, datetime)
  207. dtstart = _date_to_datetime(dtstart)
  208. if dtstart > end:
  209. break
  210. if dtend is not None:
  211. # Line 1
  212. dtend = dtstart + timedelta(seconds=original_duration)
  213. if start < dtend and end > dtstart:
  214. return True
  215. elif duration is not None:
  216. if original_duration is None:
  217. original_duration = duration.seconds
  218. if duration.seconds > 0:
  219. # Line 2
  220. if start < dtstart + duration and end > dtstart:
  221. return True
  222. elif start <= dtstart and end > dtstart:
  223. # Line 3
  224. return True
  225. elif dtstart_is_datetime:
  226. # Line 4
  227. if start <= dtstart and end > dtstart:
  228. return True
  229. elif start < dtstart + timedelta(days=1) and end > dtstart:
  230. # Line 5
  231. return True
  232. elif child_name == "VTODO":
  233. dtstart = getattr(child, "dtstart", None)
  234. duration = getattr(child, "duration", None)
  235. due = getattr(child, "due", None)
  236. completed = getattr(child, "completed", None)
  237. created = getattr(child, "created", None)
  238. if dtstart is not None:
  239. dtstart = _date_to_datetime(dtstart.value)
  240. if duration is not None:
  241. duration = duration.value
  242. if due is not None:
  243. due = _date_to_datetime(due.value)
  244. if dtstart is not None:
  245. original_duration = (due - dtstart).total_seconds()
  246. if completed is not None:
  247. completed = _date_to_datetime(completed.value)
  248. if created is not None:
  249. created = _date_to_datetime(created.value)
  250. original_duration = (completed - created).total_seconds()
  251. elif created is not None:
  252. created = _date_to_datetime(created.value)
  253. if child.rruleset:
  254. reference_dates = child.getrruleset(addRDate=True)
  255. else:
  256. if dtstart is not None:
  257. reference_dates = (dtstart,)
  258. elif due is not None:
  259. reference_dates = (due,)
  260. elif completed is not None:
  261. reference_dates = (completed,)
  262. elif created is not None:
  263. reference_dates = (created,)
  264. else:
  265. # Line 8
  266. return True
  267. for reference_date in reference_dates:
  268. reference_date = _date_to_datetime(reference_date)
  269. if reference_date > end:
  270. break
  271. if dtstart is not None and duration is not None:
  272. # Line 1
  273. if start <= reference_date + duration and (
  274. end > reference_date or
  275. end >= reference_date + duration):
  276. return True
  277. elif dtstart is not None and due is not None:
  278. # Line 2
  279. due = reference_date + timedelta(seconds=original_duration)
  280. if (start < due or start <= reference_date) and (
  281. end > reference_date or end >= due):
  282. return True
  283. elif dtstart is not None:
  284. if start <= reference_date and end > reference_date:
  285. return True
  286. elif due is not None:
  287. # Line 4
  288. if start < reference_date and end >= reference_date:
  289. return True
  290. elif completed is not None and created is not None:
  291. # Line 5
  292. completed = reference_date + timedelta(
  293. seconds=original_duration)
  294. if (start <= reference_date or start <= completed) and (
  295. end >= reference_date or end >= completed):
  296. return True
  297. elif completed is not None:
  298. # Line 6
  299. if start <= reference_date and end >= reference_date:
  300. return True
  301. elif created is not None:
  302. # Line 7
  303. if end > reference_date:
  304. return True
  305. elif child_name == "VJOURNAL":
  306. dtstart = getattr(child, "dtstart", None)
  307. if dtstart is not None:
  308. dtstart = dtstart.value
  309. if child.rruleset:
  310. dtstarts = child.getrruleset(addRDate=True)
  311. else:
  312. dtstarts = (dtstart,)
  313. for dtstart in dtstarts:
  314. dtstart_is_datetime = isinstance(dtstart, datetime)
  315. dtstart = _date_to_datetime(dtstart)
  316. if dtstart > end:
  317. break
  318. if dtstart_is_datetime:
  319. # Line 1
  320. if start <= dtstart and end > dtstart:
  321. return True
  322. elif start < dtstart + timedelta(days=1) and end > dtstart:
  323. # Line 2
  324. return True
  325. return False
  326. def _text_match(vobject_item, filter_, child_name, attrib_name=None):
  327. """Check whether the ``item`` matches the text-match ``filter_``.
  328. See rfc4791-9.7.5.
  329. """
  330. # TODO: collations are not supported, but the default ones needed
  331. # for DAV servers are actually pretty useless. Texts are lowered to
  332. # be case-insensitive, almost as the "i;ascii-casemap" value.
  333. match = next(filter_.itertext()).lower()
  334. children = getattr(vobject_item, "%s_list" % child_name, [])
  335. if attrib_name:
  336. condition = any(
  337. match in attrib.lower() for child in children
  338. for attrib in child.params.get(attrib_name, []))
  339. else:
  340. condition = any(match in child.value.lower() for child in children)
  341. if filter_.get("negate-condition") == "yes":
  342. return not condition
  343. else:
  344. return condition
  345. def _param_filter_match(vobject_item, filter_, parent_name):
  346. """Check whether the ``item`` matches the param-filter ``filter_``.
  347. See rfc4791-9.7.3.
  348. """
  349. name = filter_.get("name")
  350. children = getattr(vobject_item, "%s_list" % parent_name, [])
  351. condition = any(name in child.params for child in children)
  352. if len(filter_):
  353. if filter_[0].tag == _tag("C", "text-match"):
  354. return condition and _text_match(
  355. vobject_item, filter_[0], parent_name, name)
  356. elif filter_[0].tag == _tag("C", "is-not-defined"):
  357. return not condition
  358. else:
  359. return condition
  360. def name_from_path(path, collection):
  361. """Return Radicale item name from ``path``."""
  362. collection_parts = collection.path.strip("/").split("/")
  363. path_parts = path.strip("/").split("/")
  364. if (len(path_parts) - len(collection_parts)):
  365. return path_parts[-1]
  366. def props_from_request(root, actions=("set", "remove")):
  367. """Return a list of properties as a dictionary."""
  368. result = OrderedDict()
  369. if root:
  370. if not hasattr(root, "tag"):
  371. root = ET.fromstring(root.encode("utf8"))
  372. else:
  373. return result
  374. for action in actions:
  375. action_element = root.find(_tag("D", action))
  376. if action_element is not None:
  377. break
  378. else:
  379. action_element = root
  380. prop_element = action_element.find(_tag("D", "prop"))
  381. if prop_element is not None:
  382. for prop in prop_element:
  383. if prop.tag == _tag("D", "resourcetype"):
  384. for resource_type in prop:
  385. if resource_type.tag == _tag("C", "calendar"):
  386. result["tag"] = "VCALENDAR"
  387. break
  388. elif resource_type.tag == _tag("CR", "addressbook"):
  389. result["tag"] = "VADDRESSBOOK"
  390. break
  391. elif prop.tag == _tag("C", "supported-calendar-component-set"):
  392. result[_tag_from_clark(prop.tag)] = ",".join(
  393. supported_comp.attrib["name"]
  394. for supported_comp in prop
  395. if supported_comp.tag == _tag("C", "comp"))
  396. else:
  397. result[_tag_from_clark(prop.tag)] = prop.text
  398. return result
  399. def delete(path, collection):
  400. """Read and answer DELETE requests.
  401. Read rfc4918-9.6 for info.
  402. """
  403. # Reading request
  404. if collection.path == path.strip("/"):
  405. # Delete the whole collection
  406. collection.delete()
  407. else:
  408. # Remove an item from the collection
  409. collection.delete(name_from_path(path, collection))
  410. # Writing answer
  411. multistatus = ET.Element(_tag("D", "multistatus"))
  412. response = ET.Element(_tag("D", "response"))
  413. multistatus.append(response)
  414. href = ET.Element(_tag("D", "href"))
  415. href.text = _href(collection, path)
  416. response.append(href)
  417. status = ET.Element(_tag("D", "status"))
  418. status.text = _response(200)
  419. response.append(status)
  420. return _pretty_xml(multistatus)
  421. def propfind(path, xml_request, read_collections, write_collections,
  422. user=None):
  423. """Read and answer PROPFIND requests.
  424. Read rfc4918-9.1 for info.
  425. The collections parameter is a list of collections that are to be included
  426. in the output.
  427. """
  428. # Reading request
  429. if xml_request:
  430. root = ET.fromstring(xml_request.encode("utf8"))
  431. props = [prop.tag for prop in root.find(_tag("D", "prop"))]
  432. else:
  433. props = [_tag("D", "getcontenttype"),
  434. _tag("D", "resourcetype"),
  435. _tag("D", "displayname"),
  436. _tag("D", "owner"),
  437. _tag("D", "getetag"),
  438. _tag("ICAL", "calendar-color"),
  439. _tag("CS", "getctag")]
  440. # Writing answer
  441. multistatus = ET.Element(_tag("D", "multistatus"))
  442. collections = []
  443. for collection in write_collections:
  444. collections.append(collection)
  445. response = _propfind_response(
  446. path, collection, props, user, write=True)
  447. multistatus.append(response)
  448. for collection in read_collections:
  449. if collection in collections:
  450. continue
  451. response = _propfind_response(
  452. path, collection, props, user, write=False)
  453. multistatus.append(response)
  454. return _pretty_xml(multistatus)
  455. def _propfind_response(path, item, props, user, write=False):
  456. """Build and return a PROPFIND response."""
  457. # TODO: fix this
  458. is_collection = hasattr(item, "list")
  459. if is_collection:
  460. is_leaf = bool(item.list())
  461. collection = item
  462. else:
  463. collection = item.collection
  464. response = ET.Element(_tag("D", "response"))
  465. href = ET.Element(_tag("D", "href"))
  466. if is_collection:
  467. uri = item.path
  468. else:
  469. # TODO: fix this
  470. if path.split("/")[-1] == item.href:
  471. # Happening when depth is 0
  472. uri = path
  473. else:
  474. # Happening when depth is 1
  475. uri = "/".join((path, item.href))
  476. # TODO: fix this
  477. href.text = _href(collection, uri.replace("//", "/"))
  478. response.append(href)
  479. propstat404 = ET.Element(_tag("D", "propstat"))
  480. propstat200 = ET.Element(_tag("D", "propstat"))
  481. response.append(propstat200)
  482. prop200 = ET.Element(_tag("D", "prop"))
  483. propstat200.append(prop200)
  484. prop404 = ET.Element(_tag("D", "prop"))
  485. propstat404.append(prop404)
  486. for tag in props:
  487. element = ET.Element(tag)
  488. is404 = False
  489. if tag == _tag("D", "getetag"):
  490. element.text = item.etag
  491. elif tag == _tag("D", "principal-URL"):
  492. tag = ET.Element(_tag("D", "href"))
  493. tag.text = _href(collection, path)
  494. element.append(tag)
  495. elif tag == _tag("D", "getlastmodified"):
  496. element.text = item.last_modified
  497. elif tag in (_tag("D", "principal-collection-set"),
  498. _tag("C", "calendar-user-address-set"),
  499. _tag("CR", "addressbook-home-set"),
  500. _tag("C", "calendar-home-set")):
  501. tag = ET.Element(_tag("D", "href"))
  502. tag.text = _href(collection, path)
  503. element.append(tag)
  504. elif tag == _tag("C", "supported-calendar-component-set"):
  505. # This is not a Todo
  506. # pylint: disable=W0511
  507. human_tag = _tag_from_clark(tag)
  508. if is_collection and is_leaf:
  509. meta = item.get_meta(human_tag)
  510. if meta:
  511. components = meta.split(",")
  512. else:
  513. components = ("VTODO", "VEVENT", "VJOURNAL")
  514. for component in components:
  515. comp = ET.Element(_tag("C", "comp"))
  516. comp.set("name", component)
  517. element.append(comp)
  518. else:
  519. is404 = True
  520. # pylint: enable=W0511
  521. elif tag == _tag("D", "current-user-principal") and user:
  522. tag = ET.Element(_tag("D", "href"))
  523. tag.text = _href(collection, "/%s/" % user)
  524. element.append(tag)
  525. elif tag == _tag("D", "current-user-privilege-set"):
  526. privilege = ET.Element(_tag("D", "privilege"))
  527. if write:
  528. privilege.append(ET.Element(_tag("D", "all")))
  529. privilege.append(ET.Element(_tag("D", "write")))
  530. privilege.append(ET.Element(_tag("D", "write-properties")))
  531. privilege.append(ET.Element(_tag("D", "write-content")))
  532. privilege.append(ET.Element(_tag("D", "read")))
  533. element.append(privilege)
  534. elif tag == _tag("D", "supported-report-set"):
  535. for report_name in (
  536. "principal-property-search", "sync-collection",
  537. "expand-property", "principal-search-property-set"):
  538. supported = ET.Element(_tag("D", "supported-report"))
  539. report_tag = ET.Element(_tag("D", "report"))
  540. report_tag.text = report_name
  541. supported.append(report_tag)
  542. element.append(supported)
  543. elif is_collection:
  544. if tag == _tag("D", "getcontenttype"):
  545. item_tag = item.get_meta("tag")
  546. if item_tag:
  547. element.text = storage.MIMETYPES[item_tag]
  548. else:
  549. is404 = True
  550. elif tag == _tag("D", "resourcetype"):
  551. if item.is_principal:
  552. tag = ET.Element(_tag("D", "principal"))
  553. element.append(tag)
  554. item_tag = item.get_meta("tag")
  555. if is_leaf or item_tag:
  556. # 2nd case happens when the collection is not stored yet,
  557. # but the resource type is guessed
  558. if item.get_meta("tag") == "VADDRESSBOOK":
  559. tag = ET.Element(_tag("CR", "addressbook"))
  560. element.append(tag)
  561. elif item.get_meta("tag") == "VCALENDAR":
  562. tag = ET.Element(_tag("C", "calendar"))
  563. element.append(tag)
  564. tag = ET.Element(_tag("D", "collection"))
  565. element.append(tag)
  566. elif is_leaf:
  567. if tag == _tag("D", "owner") and item.owner:
  568. element.text = "/%s/" % item.owner
  569. elif tag == _tag("CS", "getctag"):
  570. element.text = item.etag
  571. elif tag == _tag("C", "calendar-timezone"):
  572. timezones = set()
  573. for href, _ in item.list():
  574. event = item.get(href)
  575. if "vtimezone" in event.contents:
  576. for timezone_ in event.vtimezone_list:
  577. timezones.add(timezone_)
  578. timezone_collection = vobject.iCalendar()
  579. for timezone_ in timezones:
  580. timezone_collection.add(timezone_)
  581. element.text = timezone_collection.serialize()
  582. elif tag == _tag("D", "displayname"):
  583. element.text = item.get_meta("D:displayname") or item.path
  584. elif tag == _tag("ICAL", "calendar-color"):
  585. element.text = item.get_meta("ICAL:calendar-color")
  586. else:
  587. human_tag = _tag_from_clark(tag)
  588. meta = item.get_meta(human_tag)
  589. if meta:
  590. element.text = meta
  591. else:
  592. is404 = True
  593. else:
  594. is404 = True
  595. # Not for collections
  596. elif tag == _tag("D", "getcontenttype"):
  597. name = item.name.lower()
  598. mimetype = "text/vcard" if name == "vcard" else "text/calendar"
  599. element.text = "%s; component=%s" % (mimetype, name)
  600. elif tag == _tag("D", "resourcetype"):
  601. # resourcetype must be returned empty for non-collection elements
  602. pass
  603. elif tag == _tag("D", "getcontentlength"):
  604. encoding = collection.configuration.get("encoding", "request")
  605. element.text = str(len(item.serialize().encode(encoding)))
  606. else:
  607. is404 = True
  608. if is404:
  609. prop404.append(element)
  610. else:
  611. prop200.append(element)
  612. status200 = ET.Element(_tag("D", "status"))
  613. status200.text = _response(200)
  614. propstat200.append(status200)
  615. status404 = ET.Element(_tag("D", "status"))
  616. status404.text = _response(404)
  617. propstat404.append(status404)
  618. if len(prop404):
  619. response.append(propstat404)
  620. return response
  621. def _add_propstat_to(element, tag, status_number):
  622. """Add a PROPSTAT response structure to an element.
  623. The PROPSTAT answer structure is defined in rfc4918-9.1. It is added to the
  624. given ``element``, for the following ``tag`` with the given
  625. ``status_number``.
  626. """
  627. propstat = ET.Element(_tag("D", "propstat"))
  628. element.append(propstat)
  629. prop = ET.Element(_tag("D", "prop"))
  630. propstat.append(prop)
  631. if "{" in tag:
  632. clark_tag = tag
  633. else:
  634. clark_tag = _tag(*tag.split(":", 1))
  635. prop_tag = ET.Element(clark_tag)
  636. prop.append(prop_tag)
  637. status = ET.Element(_tag("D", "status"))
  638. status.text = _response(status_number)
  639. propstat.append(status)
  640. def proppatch(path, xml_request, collection):
  641. """Read and answer PROPPATCH requests.
  642. Read rfc4918-9.2 for info.
  643. """
  644. # Reading request
  645. root = ET.fromstring(xml_request.encode("utf8"))
  646. props_to_set = props_from_request(root, actions=("set",))
  647. props_to_remove = props_from_request(root, actions=("remove",))
  648. # Writing answer
  649. multistatus = ET.Element(_tag("D", "multistatus"))
  650. response = ET.Element(_tag("D", "response"))
  651. multistatus.append(response)
  652. href = ET.Element(_tag("D", "href"))
  653. href.text = _href(collection, path)
  654. response.append(href)
  655. for short_name, value in props_to_set.items():
  656. collection.set_meta(short_name, value)
  657. _add_propstat_to(response, short_name, 200)
  658. for short_name in props_to_remove:
  659. collection.set_meta(short_name, '')
  660. _add_propstat_to(response, short_name, 200)
  661. return _pretty_xml(multistatus)
  662. def report(path, xml_request, collection):
  663. """Read and answer REPORT requests.
  664. Read rfc3253-3.6 for info.
  665. """
  666. # Reading request
  667. root = ET.fromstring(xml_request.encode("utf8"))
  668. prop_element = root.find(_tag("D", "prop"))
  669. props = (
  670. [prop.tag for prop in prop_element]
  671. if prop_element is not None else [])
  672. if collection:
  673. if root.tag in (_tag("C", "calendar-multiget"),
  674. _tag("CR", "addressbook-multiget")):
  675. # Read rfc4791-7.9 for info
  676. base_prefix = collection.configuration.get("server", "base_prefix")
  677. hreferences = set()
  678. for href_element in root.findall(_tag("D", "href")):
  679. href_path = unquote(urlparse(href_element.text).path)
  680. if href_path.startswith(base_prefix):
  681. hreferences.add(href_path[len(base_prefix) - 1:])
  682. else:
  683. hreferences = (path,)
  684. filters = (
  685. root.findall(".//%s" % _tag("C", "filter")) +
  686. root.findall(".//%s" % _tag("CR", "filter")))
  687. else:
  688. hreferences = filters = ()
  689. # Writing answer
  690. multistatus = ET.Element(_tag("D", "multistatus"))
  691. for hreference in hreferences:
  692. # Check if the reference is an item or a collection
  693. name = name_from_path(hreference, collection)
  694. if name:
  695. # Reference is an item
  696. path = "/".join(hreference.split("/")[:-1]) + "/"
  697. item = collection.get(name)
  698. if item is None:
  699. multistatus.append(
  700. _item_response(hreference, found_item=False))
  701. continue
  702. items = [item]
  703. else:
  704. # Reference is a collection
  705. path = hreference
  706. items = [collection.get(href) for href, etag in collection.list()]
  707. for item in items:
  708. if filters:
  709. match = (
  710. _comp_match if collection.get_meta("tag") == "VCALENDAR"
  711. else _prop_match)
  712. if not all(match(item, filter_[0]) for filter_ in filters):
  713. continue
  714. found_props = []
  715. not_found_props = []
  716. for tag in props:
  717. element = ET.Element(tag)
  718. if tag == _tag("D", "getetag"):
  719. element.text = item.etag
  720. found_props.append(element)
  721. elif tag == _tag("D", "getcontenttype"):
  722. name = item.name.lower()
  723. mimetype = (
  724. "text/vcard" if name == "vcard" else "text/calendar")
  725. element.text = "%s; component=%s" % (mimetype, name)
  726. found_props.append(element)
  727. elif tag in (_tag("C", "calendar-data"),
  728. _tag("CR", "address-data")):
  729. element.text = item.serialize()
  730. found_props.append(element)
  731. else:
  732. not_found_props.append(element)
  733. # TODO: fix this
  734. if hreference.split("/")[-1] == item.href:
  735. # Happening when depth is 0
  736. uri = hreference
  737. else:
  738. # Happening when depth is 1
  739. uri = posixpath.join(hreference, item.href)
  740. multistatus.append(_item_response(
  741. uri, found_props=found_props,
  742. not_found_props=not_found_props, found_item=True))
  743. return _pretty_xml(multistatus)
  744. def _item_response(href, found_props=(), not_found_props=(), found_item=True):
  745. response = ET.Element(_tag("D", "response"))
  746. href_tag = ET.Element(_tag("D", "href"))
  747. href_tag.text = href
  748. response.append(href_tag)
  749. if found_item:
  750. if found_props:
  751. propstat = ET.Element(_tag("D", "propstat"))
  752. status = ET.Element(_tag("D", "status"))
  753. status.text = _response(200)
  754. prop = ET.Element(_tag("D", "prop"))
  755. for p in found_props:
  756. prop.append(p)
  757. propstat.append(prop)
  758. propstat.append(status)
  759. response.append(propstat)
  760. if not_found_props:
  761. propstat = ET.Element(_tag("D", "propstat"))
  762. status = ET.Element(_tag("D", "status"))
  763. status.text = _response(404)
  764. prop = ET.Element(_tag("D", "prop"))
  765. for p in not_found_props:
  766. prop.append(p)
  767. propstat.append(prop)
  768. propstat.append(status)
  769. response.append(propstat)
  770. else:
  771. status = ET.Element(_tag("D", "status"))
  772. status.text = _response(404)
  773. response.append(status)
  774. return response