ical.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. from uuid import uuid4
  27. from random import randint
  28. from contextlib import contextmanager
  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. if tag == "VADDRESSBOOK":
  35. lines = [item.text for item in items]
  36. else:
  37. lines = ["BEGIN:%s" % tag]
  38. for part in (headers, items):
  39. if part:
  40. lines.append("\n".join(item.text for item in part))
  41. lines.append("END:%s\n" % tag)
  42. return "\n".join(lines)
  43. def unfold(text):
  44. """Unfold multi-lines attributes.
  45. Read rfc5545-3.1 for info.
  46. """
  47. lines = []
  48. for line in text.splitlines():
  49. if lines and (line.startswith(" ") or line.startswith("\t")):
  50. lines[-1] += line[1:]
  51. else:
  52. lines.append(line)
  53. return lines
  54. class Item(object):
  55. """Internal iCal item."""
  56. def __init__(self, text, name=None):
  57. """Initialize object from ``text`` and different ``kwargs``."""
  58. self.text = text
  59. self._name = name
  60. # We must synchronize the name in the text and in the object.
  61. # An item must have a name, determined in order by:
  62. #
  63. # - the ``name`` parameter
  64. # - the ``X-RADICALE-NAME`` iCal property (for Events, Todos, Journals)
  65. # - the ``UID`` iCal property (for Events, Todos, Journals)
  66. # - the ``TZID`` iCal property (for Timezones)
  67. if not self._name:
  68. for line in unfold(self.text):
  69. if line.startswith("X-RADICALE-NAME:"):
  70. self._name = line.replace("X-RADICALE-NAME:", "").strip()
  71. break
  72. elif line.startswith("TZID:"):
  73. self._name = line.replace("TZID:", "").strip()
  74. break
  75. elif line.startswith("UID:"):
  76. self._name = line.replace("UID:", "").strip()
  77. # Do not break, a ``X-RADICALE-NAME`` can appear next
  78. if self._name:
  79. # Remove brackets that may have been put by Outlook
  80. self._name = self._name.strip("{}")
  81. if "\nX-RADICALE-NAME:" in text:
  82. for line in unfold(self.text):
  83. if line.startswith("X-RADICALE-NAME:"):
  84. self.text = self.text.replace(
  85. line, "X-RADICALE-NAME:%s" % self._name)
  86. else:
  87. self.text = self.text.replace(
  88. "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name)
  89. else:
  90. self._name = str(uuid4())
  91. self.text = self.text.replace(
  92. "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name)
  93. def __hash__(self):
  94. return hash(self.text)
  95. def __eq__(self, item):
  96. return isinstance(item, Item) and self.text == item.text
  97. @property
  98. def etag(self):
  99. """Item etag.
  100. Etag is mainly used to know if an item has changed.
  101. """
  102. return '"%s"' % hash(self)
  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. split_path = path.split("/")
  143. self.path = path if path != "." else ""
  144. if principal and split_path and self.is_node(self.path):
  145. # Already existing principal collection
  146. self.owner = split_path[0]
  147. elif len(split_path) > 1:
  148. # URL with at least one folder
  149. self.owner = split_path[0]
  150. else:
  151. self.owner = None
  152. self.is_principal = principal
  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. # First do normpath and then strip, to prevent access to FOLDER/../
  168. sane_path = posixpath.normpath(path.replace(os.sep, "/")).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 list 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 list(items.values())
  269. def get_item(self, name):
  270. """Get collection item called ``name``."""
  271. for item in self.items:
  272. if item.name == name:
  273. return item
  274. def append(self, name, text):
  275. """Append items from ``text`` to collection.
  276. If ``name`` is given, give this name to new items in ``text``.
  277. """
  278. items = self.items
  279. for new_item in self._parse(
  280. text, (Timezone, Event, Todo, Journal, Card), name):
  281. if new_item.name not in (item.name for item in items):
  282. items.append(new_item)
  283. self.write(items=items)
  284. def remove(self, name):
  285. """Remove object named ``name`` from collection."""
  286. components = [
  287. component for component in self.components
  288. if component.name != name]
  289. items = self.timezones + components
  290. self.write(items=items)
  291. def replace(self, name, text):
  292. """Replace content by ``text`` in collection objet called ``name``."""
  293. self.remove(name)
  294. self.append(name, text)
  295. def write(self, headers=None, items=None):
  296. """Write collection with given parameters."""
  297. headers = headers or self.headers or (
  298. Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
  299. Header("VERSION:%s" % self.version))
  300. items = items if items is not None else self.items
  301. text = serialize(self.tag, headers, items)
  302. self.save(text)
  303. def set_mimetype(self, mimetype):
  304. """Set the mimetype of the collection."""
  305. with self.props as props:
  306. if "tag" not in props:
  307. if mimetype == "text/vcard":
  308. props["tag"] = "VADDRESSBOOK"
  309. else:
  310. props["tag"] = "VCALENDAR"
  311. @property
  312. def tag(self):
  313. """Type of the collection."""
  314. with self.props as props:
  315. if "tag" not in props:
  316. try:
  317. tag = open(self.path).readlines()[0][6:].rstrip()
  318. except IOError:
  319. if self.path.endswith((".vcf", "/carddav")):
  320. props["tag"] = "VADDRESSBOOK"
  321. else:
  322. props["tag"] = "VCALENDAR"
  323. else:
  324. if tag in ("VADDRESSBOOK", "VCARD"):
  325. props["tag"] = "VADDRESSBOOK"
  326. else:
  327. props["tag"] = "VCALENDAR"
  328. return props["tag"]
  329. @property
  330. def mimetype(self):
  331. """Mimetype of the collection."""
  332. if self.tag == "VADDRESSBOOK":
  333. return "text/vcard"
  334. elif self.tag == "VCALENDAR":
  335. return "text/calendar"
  336. @property
  337. def resource_type(self):
  338. """Resource type of the collection."""
  339. if self.tag == "VADDRESSBOOK":
  340. return "addressbook"
  341. elif self.tag == "VCALENDAR":
  342. return "calendar"
  343. @property
  344. def etag(self):
  345. """Etag from collection."""
  346. return '"%s"' % hash(self.text)
  347. @property
  348. def name(self):
  349. """Collection name."""
  350. with self.props as props:
  351. return props.get("D:displayname", self.path.split(os.path.sep)[-1])
  352. @property
  353. def color(self):
  354. """Collection color."""
  355. with self.props as props:
  356. if "A:calendar-color" not in props:
  357. props["A:calendar-color"] = "#%x" % randint(0, 255 ** 3 - 1)
  358. return props["A:calendar-color"]
  359. @property
  360. def headers(self):
  361. """Find headers items in collection."""
  362. header_lines = []
  363. lines = unfold(self.text)
  364. for header in ("PRODID", "VERSION"):
  365. for line in lines:
  366. if line.startswith("%s:" % header):
  367. header_lines.append(Header(line))
  368. break
  369. return header_lines
  370. @property
  371. def items(self):
  372. """Get list of all items in collection."""
  373. return self._parse(self.text, (Event, Todo, Journal, Card, Timezone))
  374. @property
  375. def components(self):
  376. """Get list of all components in collection."""
  377. return self._parse(self.text, (Event, Todo, Journal, Card))
  378. @property
  379. def events(self):
  380. """Get list of ``Event`` items in calendar."""
  381. return self._parse(self.text, (Event,))
  382. @property
  383. def todos(self):
  384. """Get list of ``Todo`` items in calendar."""
  385. return self._parse(self.text, (Todo,))
  386. @property
  387. def journals(self):
  388. """Get list of ``Journal`` items in calendar."""
  389. return self._parse(self.text, (Journal,))
  390. @property
  391. def timezones(self):
  392. """Get list of ``Timezone`` items in calendar."""
  393. return self._parse(self.text, (Timezone,))
  394. @property
  395. def cards(self):
  396. """Get list of ``Card`` items in address book."""
  397. return self._parse(self.text, (Card,))
  398. @property
  399. def owner_url(self):
  400. """Get the collection URL according to its owner."""
  401. return "/%s/" % self.owner if self.owner else None
  402. @property
  403. def url(self):
  404. """Get the standard collection URL."""
  405. return "%s/" % self.path
  406. @property
  407. def version(self):
  408. """Get the version of the collection type."""
  409. return "3.0" if self.tag == "VADDRESSBOOK" else "2.0"