ical.py 15 KB

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