ical.py 15 KB

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