ical.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2016 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. Radicale collection classes.
  20. Define the main classes of a collection as seen from the server.
  21. """
  22. import os
  23. import hashlib
  24. import re
  25. from uuid import uuid4
  26. from random import randint
  27. from contextlib import contextmanager
  28. from . import pathutils
  29. def serialize(tag, headers=(), items=()):
  30. """Return a text corresponding to given collection ``tag``.
  31. The text may have the given ``headers`` and ``items`` added around the
  32. items if needed (ie. for calendars).
  33. """
  34. items = sorted(items, key=lambda x: x.name)
  35. if tag == "VADDRESSBOOK":
  36. lines = [item.text for item in items]
  37. else:
  38. lines = ["BEGIN:%s" % tag]
  39. for part in (headers, items):
  40. if part:
  41. lines.append("\n".join(item.text for item in part))
  42. lines.append("END:%s\n" % tag)
  43. return "\n".join(lines)
  44. def unfold(text):
  45. """Unfold multi-lines attributes.
  46. Read rfc5545-3.1 for info.
  47. """
  48. return re.sub('\r\n( |\t)', '', text).splitlines()
  49. class Item(object):
  50. """Internal iCal item."""
  51. def __init__(self, text, name=None):
  52. """Initialize object from ``text`` and different ``kwargs``."""
  53. self.text = text
  54. self._name = name
  55. # We must synchronize the name in the text and in the object.
  56. # An item must have a name, determined in order by:
  57. #
  58. # - the ``name`` parameter
  59. # - the ``X-RADICALE-NAME`` iCal property (for Events, Todos, Journals)
  60. # - the ``UID`` iCal property (for Events, Todos, Journals)
  61. # - the ``TZID`` iCal property (for Timezones)
  62. if not self._name:
  63. for line in unfold(self.text):
  64. if line.startswith("X-RADICALE-NAME:"):
  65. self._name = line.replace("X-RADICALE-NAME:", "").strip()
  66. break
  67. elif line.startswith("TZID:"):
  68. self._name = line.replace("TZID:", "").strip()
  69. break
  70. elif line.startswith("UID:"):
  71. self._name = line.replace("UID:", "").strip()
  72. # Do not break, a ``X-RADICALE-NAME`` can appear next
  73. if self._name:
  74. # Remove brackets that may have been put by Outlook
  75. self._name = self._name.strip("{}")
  76. if "\nX-RADICALE-NAME:" in text:
  77. for line in unfold(self.text):
  78. if line.startswith("X-RADICALE-NAME:"):
  79. self.text = self.text.replace(
  80. line, "X-RADICALE-NAME:%s" % self._name)
  81. else:
  82. self.text = self.text.replace(
  83. "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name)
  84. else:
  85. # workaround to get unicode on both python2 and 3
  86. self._name = uuid4().hex.encode("ascii").decode("ascii")
  87. self.text = self.text.replace(
  88. "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name)
  89. def __hash__(self):
  90. return hash(self.text)
  91. def __eq__(self, item):
  92. return isinstance(item, Item) and self.text == item.text
  93. @property
  94. def etag(self):
  95. """Item etag.
  96. Etag is mainly used to know if an item has changed.
  97. """
  98. md5 = hashlib.md5()
  99. md5.update(self.text.encode("utf-8"))
  100. return '"%s"' % md5.hexdigest()
  101. @property
  102. def name(self):
  103. """Item name.
  104. Name is mainly used to give an URL to the item.
  105. """
  106. return self._name
  107. class Header(Item):
  108. """Internal header class."""
  109. class Timezone(Item):
  110. """Internal timezone class."""
  111. tag = "VTIMEZONE"
  112. class Component(Item):
  113. """Internal main component of a collection."""
  114. class Event(Component):
  115. """Internal event class."""
  116. tag = "VEVENT"
  117. mimetype = "text/calendar"
  118. class Todo(Component):
  119. """Internal todo class."""
  120. tag = "VTODO" # pylint: disable=W0511
  121. mimetype = "text/calendar"
  122. class Journal(Component):
  123. """Internal journal class."""
  124. tag = "VJOURNAL"
  125. mimetype = "text/calendar"
  126. class Card(Component):
  127. """Internal card class."""
  128. tag = "VCARD"
  129. mimetype = "text/vcard"
  130. class Collection(object):
  131. """Internal collection item.
  132. This class must be overridden and replaced by a storage backend.
  133. """
  134. def __init__(self, path, principal=False):
  135. """Initialize the collection.
  136. ``path`` must be the normalized relative path of the collection, using
  137. the slash as the folder delimiter, with no leading nor trailing slash.
  138. """
  139. self.encoding = "utf-8"
  140. # path should already be sanitized
  141. self.path = pathutils.sanitize_path(path).strip("/")
  142. split_path = self.path.split("/")
  143. if principal and split_path and self.is_node(self.path):
  144. # Already existing principal collection
  145. self.owner = split_path[0]
  146. elif len(split_path) > 1:
  147. # URL with at least one folder
  148. self.owner = split_path[0]
  149. else:
  150. self.owner = None
  151. self.is_principal = principal
  152. self._items = None
  153. @classmethod
  154. def from_path(cls, path, depth="1", include_container=True):
  155. """Return a list of collections and items under the given ``path``.
  156. If ``depth`` is "0", only the actual object under ``path`` is
  157. returned.
  158. If ``depth`` is anything but "0", it is considered as "1" and direct
  159. children are included in the result. If ``include_container`` is
  160. ``True`` (the default), the containing object is included in the
  161. result.
  162. The ``path`` is relative.
  163. """
  164. # path == None means wrong URL
  165. if path is None:
  166. return []
  167. # path should already be sanitized
  168. sane_path = pathutils.sanitize_path(path).strip("/")
  169. attributes = sane_path.split("/")
  170. if not attributes:
  171. return []
  172. # Try to guess if the path leads to a collection or an item
  173. if (cls.is_leaf("/".join(attributes[:-1])) or not
  174. path.endswith(("/", "/caldav", "/carddav"))):
  175. attributes.pop()
  176. result = []
  177. path = "/".join(attributes)
  178. principal = len(attributes) <= 1
  179. if cls.is_node(path):
  180. if depth == "0":
  181. result.append(cls(path, principal))
  182. else:
  183. if include_container:
  184. result.append(cls(path, principal))
  185. for child in cls.children(path):
  186. result.append(child)
  187. else:
  188. if depth == "0":
  189. result.append(cls(path))
  190. else:
  191. collection = cls(path, principal)
  192. if include_container:
  193. result.append(collection)
  194. result.extend(collection.components)
  195. return result
  196. def save(self, text):
  197. """Save the text into the collection."""
  198. raise NotImplementedError
  199. def delete(self):
  200. """Delete the collection."""
  201. raise NotImplementedError
  202. @property
  203. def text(self):
  204. """Collection as plain text."""
  205. raise NotImplementedError
  206. @classmethod
  207. def children(cls, path):
  208. """Yield the children of the collection at local ``path``."""
  209. raise NotImplementedError
  210. @classmethod
  211. def is_node(cls, path):
  212. """Return ``True`` if relative ``path`` is a node.
  213. A node is a WebDAV collection whose members are other collections.
  214. """
  215. raise NotImplementedError
  216. @classmethod
  217. def is_leaf(cls, path):
  218. """Return ``True`` if relative ``path`` is a leaf.
  219. A leaf is a WebDAV collection whose members are not collections.
  220. """
  221. raise NotImplementedError
  222. @property
  223. def last_modified(self):
  224. """Get the last time the collection has been modified.
  225. The date is formatted according to rfc1123-5.2.14.
  226. """
  227. raise NotImplementedError
  228. @property
  229. @contextmanager
  230. def props(self):
  231. """Get the collection properties."""
  232. raise NotImplementedError
  233. @property
  234. def exists(self):
  235. """``True`` if the collection exists on the storage, else ``False``."""
  236. return self.is_node(self.path) or self.is_leaf(self.path)
  237. @staticmethod
  238. def _parse(text, item_types, name=None):
  239. """Find items with type in ``item_types`` in ``text``.
  240. If ``name`` is given, give this name to new items in ``text``.
  241. Return a dict of items.
  242. """
  243. item_tags = {}
  244. for item_type in item_types:
  245. item_tags[item_type.tag] = item_type
  246. items = {}
  247. lines = unfold(text)
  248. in_item = False
  249. for line in lines:
  250. if line.startswith("BEGIN:") and not in_item:
  251. item_tag = line.replace("BEGIN:", "").strip()
  252. if item_tag in item_tags:
  253. in_item = True
  254. item_lines = []
  255. if in_item:
  256. item_lines.append(line)
  257. if line.startswith("END:%s" % item_tag):
  258. in_item = False
  259. item_type = item_tags[item_tag]
  260. item_text = "\n".join(item_lines)
  261. item_name = None if item_tag == "VTIMEZONE" else name
  262. item = item_type(item_text, item_name)
  263. if item.name in items:
  264. text = "\n".join((item.text, items[item.name].text))
  265. items[item.name] = item_type(text, item.name)
  266. else:
  267. items[item.name] = item
  268. return items
  269. def append(self, name, text):
  270. """Append items from ``text`` to collection.
  271. If ``name`` is given, give this name to new items in ``text``.
  272. """
  273. new_items = self._parse(
  274. text, (Timezone, Event, Todo, Journal, Card), name)
  275. for new_item in new_items.values():
  276. if new_item.name not in self.items:
  277. self.items[new_item.name] = new_item
  278. self.write()
  279. def remove(self, name):
  280. """Remove object named ``name`` from collection."""
  281. if name in self.items:
  282. del self.items[name]
  283. self.write()
  284. def replace(self, name, text):
  285. """Replace content by ``text`` in collection objet called ``name``."""
  286. self.remove(name)
  287. self.append(name, text)
  288. def write(self):
  289. """Write collection with given parameters."""
  290. text = serialize(self.tag, self.headers, self.items.values())
  291. self.save(text)
  292. def set_mimetype(self, mimetype):
  293. """Set the mimetype of the collection."""
  294. with self.props as props:
  295. if "tag" not in props:
  296. if mimetype == "text/vcard":
  297. props["tag"] = "VADDRESSBOOK"
  298. else:
  299. props["tag"] = "VCALENDAR"
  300. @property
  301. def tag(self):
  302. """Type of the collection."""
  303. with self.props as props:
  304. if "tag" not in props:
  305. try:
  306. tag = open(self.path).readlines()[0][6:].rstrip()
  307. except IOError:
  308. if self.path.endswith((".vcf", "/carddav")):
  309. props["tag"] = "VADDRESSBOOK"
  310. else:
  311. props["tag"] = "VCALENDAR"
  312. else:
  313. if tag in ("VADDRESSBOOK", "VCARD"):
  314. props["tag"] = "VADDRESSBOOK"
  315. else:
  316. props["tag"] = "VCALENDAR"
  317. return props["tag"]
  318. @property
  319. def mimetype(self):
  320. """Mimetype of the collection."""
  321. if self.tag == "VADDRESSBOOK":
  322. return "text/vcard"
  323. elif self.tag == "VCALENDAR":
  324. return "text/calendar"
  325. @property
  326. def resource_type(self):
  327. """Resource type of the collection."""
  328. if self.tag == "VADDRESSBOOK":
  329. return "addressbook"
  330. elif self.tag == "VCALENDAR":
  331. return "calendar"
  332. @property
  333. def etag(self):
  334. """Etag from collection."""
  335. md5 = hashlib.md5()
  336. md5.update(self.text.encode("utf-8"))
  337. return '"%s"' % md5.hexdigest()
  338. @property
  339. def name(self):
  340. """Collection name."""
  341. with self.props as props:
  342. return props.get("D:displayname", self.path.split(os.path.sep)[-1])
  343. @property
  344. def color(self):
  345. """Collection color."""
  346. with self.props as props:
  347. if "ICAL:calendar-color" not in props:
  348. props["ICAL:calendar-color"] = "#%x" % randint(0, 255 ** 3 - 1)
  349. return props["ICAL:calendar-color"]
  350. @property
  351. def headers(self):
  352. """Find headers items in collection."""
  353. header_lines = []
  354. lines = unfold(self.text)[1:]
  355. for line in lines:
  356. if line.startswith(("BEGIN:", "END:")):
  357. break
  358. header_lines.append(Header(line))
  359. return header_lines or (
  360. Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
  361. Header("VERSION:%s" % self.version))
  362. @property
  363. def items(self):
  364. """Get list of all items in collection."""
  365. if self._items is None:
  366. self._items = self._parse(
  367. self.text, (Event, Todo, Journal, Card, Timezone))
  368. return self._items
  369. @property
  370. def timezones(self):
  371. """Get list of all timezones in collection."""
  372. return [
  373. item for item in self.items.values() if item.tag == Timezone.tag]
  374. @property
  375. def components(self):
  376. """Get list of all components in collection."""
  377. tags = [item_type.tag for item_type in (Event, Todo, Journal, Card)]
  378. return [item for item in self.items.values() if item.tag in tags]
  379. @property
  380. def owner_url(self):
  381. """Get the collection URL according to its owner."""
  382. return "/%s/" % self.owner if self.owner else None
  383. @property
  384. def url(self):
  385. """Get the standard collection URL."""
  386. return "%s/" % self.path
  387. @property
  388. def version(self):
  389. """Get the version of the collection type."""
  390. return "3.0" if self.tag == "VADDRESSBOOK" else "2.0"