ical.py 16 KB

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