ical.py 16 KB

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