ical.py 15 KB

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