ical.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. # -*- coding: utf-8 -*-
  2. #
  3. # This file is part of Radicale Server - Calendar Server
  4. # Copyright © 2008-2011 Guillaume Ayoub
  5. # Copyright © 2008 Nicolas Kandel
  6. # Copyright © 2008 Pascal Halter
  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 calendar classes.
  22. Define the main classes of a calendar as seen from the server.
  23. """
  24. import os
  25. import posixpath
  26. import uuid
  27. from contextlib import contextmanager
  28. def serialize(headers=(), items=()):
  29. """Return an iCal text corresponding to given ``headers`` and ``items``."""
  30. lines = ["BEGIN:VCALENDAR"]
  31. for part in (headers, items):
  32. if part:
  33. lines.append("\n".join(item.text for item in part))
  34. lines.append("END:VCALENDAR\n")
  35. return "\n".join(lines)
  36. def unfold(text):
  37. """Unfold multi-lines attributes.
  38. Read rfc5545-3.1 for info.
  39. """
  40. lines = []
  41. for line in text.splitlines():
  42. if lines and (line.startswith(" ") or line.startswith("\t")):
  43. lines[-1] += line[1:]
  44. else:
  45. lines.append(line)
  46. return lines
  47. class Item(object):
  48. """Internal iCal item."""
  49. def __init__(self, text, name=None):
  50. """Initialize object from ``text`` and different ``kwargs``."""
  51. self.text = text
  52. self._name = name
  53. # We must synchronize the name in the text and in the object.
  54. # An item must have a name, determined in order by:
  55. #
  56. # - the ``name`` parameter
  57. # - the ``X-RADICALE-NAME`` iCal property (for Events, Todos, Journals)
  58. # - the ``UID`` iCal property (for Events, Todos, Journals)
  59. # - the ``TZID`` iCal property (for Timezones)
  60. if not self._name:
  61. for line in unfold(self.text):
  62. if line.startswith("X-RADICALE-NAME:"):
  63. self._name = line.replace("X-RADICALE-NAME:", "").strip()
  64. break
  65. elif line.startswith("TZID:"):
  66. self._name = line.replace("TZID:", "").strip()
  67. break
  68. elif line.startswith("UID:"):
  69. self._name = line.replace("UID:", "").strip()
  70. # Do not break, a ``X-RADICALE-NAME`` can appear next
  71. if self._name:
  72. if "\nX-RADICALE-NAME:" in text:
  73. for line in unfold(self.text):
  74. if line.startswith("X-RADICALE-NAME:"):
  75. self.text = self.text.replace(
  76. line, "X-RADICALE-NAME:%s" % self._name)
  77. else:
  78. self.text = self.text.replace(
  79. "\nUID:", "\nX-RADICALE-NAME:%s\nUID:" % self._name)
  80. else:
  81. self._name = str(uuid.uuid4())
  82. self.text = self.text.replace(
  83. "\nEND:", "\nUID:%s\nEND:" % self._name)
  84. @property
  85. def etag(self):
  86. """Item etag.
  87. Etag is mainly used to know if an item has changed.
  88. """
  89. return '"%s"' % hash(self.text)
  90. @property
  91. def name(self):
  92. """Item name.
  93. Name is mainly used to give an URL to the item.
  94. """
  95. return self._name
  96. class Header(Item):
  97. """Internal header class."""
  98. class Event(Item):
  99. """Internal event class."""
  100. tag = "VEVENT"
  101. class Todo(Item):
  102. """Internal todo class."""
  103. # This is not a TODO!
  104. # pylint: disable=W0511
  105. tag = "VTODO"
  106. # pylint: enable=W0511
  107. class Journal(Item):
  108. """Internal journal class."""
  109. tag = "VJOURNAL"
  110. class Timezone(Item):
  111. """Internal timezone class."""
  112. tag = "VTIMEZONE"
  113. class Calendar(object):
  114. """Internal calendar class.
  115. This class must be overridden and replaced by a storage backend.
  116. """
  117. tag = "VCALENDAR"
  118. def __init__(self, path, principal=False):
  119. """Initialize the calendar.
  120. ``path`` must be the normalized relative path of the calendar, using
  121. the slash as the folder delimiter, with no leading nor trailing slash.
  122. """
  123. self.encoding = "utf-8"
  124. split_path = path.split("/")
  125. self.path = path if path != '.' else ''
  126. if principal and split_path and self.is_collection(self.path):
  127. # Already existing principal calendar
  128. self.owner = split_path[0]
  129. elif len(split_path) > 1:
  130. # URL with at least one folder
  131. self.owner = split_path[0]
  132. else:
  133. self.owner = None
  134. self.is_principal = principal
  135. @classmethod
  136. def from_path(cls, path, depth="infinite", include_container=True):
  137. """Return a list of calendars and items under the given ``path``.
  138. If ``depth`` is "0", only the actual object under ``path`` is
  139. returned. Otherwise, also sub-items are appended to the result. If
  140. ``include_container`` is ``True`` (the default), the containing object
  141. is included in the result.
  142. The ``path`` is relative.
  143. """
  144. # First do normpath and then strip, to prevent access to FOLDER/../
  145. sane_path = posixpath.normpath(path.replace(os.sep, "/")).strip("/")
  146. attributes = sane_path.split("/")
  147. if not attributes:
  148. return None
  149. if not (cls.is_item("/".join(attributes)) or path.endswith("/")):
  150. attributes.pop()
  151. result = []
  152. path = "/".join(attributes)
  153. principal = len(attributes) <= 1
  154. if cls.is_collection(path):
  155. if depth == "0":
  156. result.append(cls(path, principal))
  157. else:
  158. if include_container:
  159. result.append(cls(path, principal))
  160. for child in cls.children(path):
  161. result.append(child)
  162. else:
  163. if depth == "0":
  164. result.append(cls(path))
  165. else:
  166. calendar = cls(path, principal)
  167. if include_container:
  168. result.append(calendar)
  169. result.extend(calendar.components)
  170. return result
  171. def save(self, text):
  172. """Save the text into the calendar."""
  173. raise NotImplemented
  174. def delete(self):
  175. """Delete the calendar."""
  176. raise NotImplemented
  177. @property
  178. def text(self):
  179. """Calendar as plain text."""
  180. raise NotImplemented
  181. @classmethod
  182. def children(cls, path):
  183. """Yield the children of the collection at local ``path``."""
  184. raise NotImplemented
  185. @classmethod
  186. def is_collection(cls, path):
  187. """Return ``True`` if relative ``path`` is a collection."""
  188. raise NotImplemented
  189. @classmethod
  190. def is_item(cls, path):
  191. """Return ``True`` if relative ``path`` is a collection item."""
  192. raise NotImplemented
  193. @property
  194. def last_modified(self):
  195. """Get the last time the calendar has been modified.
  196. The date is formatted according to rfc1123-5.2.14.
  197. """
  198. raise NotImplemented
  199. @property
  200. @contextmanager
  201. def props(self):
  202. """Get the calendar properties."""
  203. raise NotImplemented
  204. def is_vcalendar(self, path):
  205. """Return ``True`` if there is a VCALENDAR under relative ``path``."""
  206. return self.text.startswith('BEGIN:VCALENDAR')
  207. @staticmethod
  208. def _parse(text, item_types, name=None):
  209. """Find items with type in ``item_types`` in ``text``.
  210. If ``name`` is given, give this name to new items in ``text``.
  211. Return a list of items.
  212. """
  213. item_tags = {}
  214. for item_type in item_types:
  215. item_tags[item_type.tag] = item_type
  216. items = {}
  217. lines = unfold(text)
  218. in_item = False
  219. for line in lines:
  220. if line.startswith("BEGIN:") and not in_item:
  221. item_tag = line.replace("BEGIN:", "").strip()
  222. if item_tag in item_tags:
  223. in_item = True
  224. item_lines = []
  225. if in_item:
  226. item_lines.append(line)
  227. if line.startswith("END:%s" % item_tag):
  228. in_item = False
  229. item_type = item_tags[item_tag]
  230. item_text = "\n".join(item_lines)
  231. item_name = None if item_tag == "VTIMEZONE" else name
  232. item = item_type(item_text, item_name)
  233. if item.name in items:
  234. text = "\n".join((item.text, items[item.name].text))
  235. items[item.name] = item_type(text, item.name)
  236. else:
  237. items[item.name] = item
  238. return list(items.values())
  239. def get_item(self, name):
  240. """Get calendar item called ``name``."""
  241. for item in self.items:
  242. if item.name == name:
  243. return item
  244. def append(self, name, text):
  245. """Append items from ``text`` to calendar.
  246. If ``name`` is given, give this name to new items in ``text``.
  247. """
  248. items = self.items
  249. for new_item in self._parse(
  250. text, (Timezone, Event, Todo, Journal), name):
  251. if new_item.name not in (item.name for item in items):
  252. items.append(new_item)
  253. self.write(items=items)
  254. def remove(self, name):
  255. """Remove object named ``name`` from calendar."""
  256. components = [
  257. component for component in self.components
  258. if component.name != name]
  259. items = self.timezones + components
  260. self.write(items=items)
  261. def replace(self, name, text):
  262. """Replace content by ``text`` in objet named ``name`` in calendar."""
  263. self.remove(name)
  264. self.append(name, text)
  265. def write(self, headers=None, items=None):
  266. """Write calendar with given parameters."""
  267. headers = headers or self.headers or (
  268. Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
  269. Header("VERSION:2.0"))
  270. items = items if items is not None else self.items
  271. text = serialize(headers, items)
  272. self.save(text)
  273. @property
  274. def etag(self):
  275. """Etag from calendar."""
  276. return '"%s"' % hash(self.text)
  277. @property
  278. def name(self):
  279. """Calendar name."""
  280. with self.props as props:
  281. return props.get('D:displayname',
  282. self.path.split(os.path.sep)[-1])
  283. @property
  284. def headers(self):
  285. """Find headers items in calendar."""
  286. header_lines = []
  287. lines = unfold(self.text)
  288. for line in lines:
  289. if line.startswith("PRODID:"):
  290. header_lines.append(Header(line))
  291. for line in lines:
  292. if line.startswith("VERSION:"):
  293. header_lines.append(Header(line))
  294. return header_lines
  295. @property
  296. def items(self):
  297. """Get list of all items in calendar."""
  298. return self._parse(self.text, (Event, Todo, Journal, Timezone))
  299. @property
  300. def components(self):
  301. """Get list of all components in calendar."""
  302. return self._parse(self.text, (Event, Todo, Journal))
  303. @property
  304. def events(self):
  305. """Get list of ``Event`` items in calendar."""
  306. return self._parse(self.text, (Event,))
  307. @property
  308. def todos(self):
  309. """Get list of ``Todo`` items in calendar."""
  310. return self._parse(self.text, (Todo,))
  311. @property
  312. def journals(self):
  313. """Get list of ``Journal`` items in calendar."""
  314. return self._parse(self.text, (Journal,))
  315. @property
  316. def timezones(self):
  317. """Get list of ``Timezome`` items in calendar."""
  318. return self._parse(self.text, (Timezone,))
  319. @property
  320. def owner_url(self):
  321. """Get the calendar URL according to its owner."""
  322. if self.owner:
  323. return "/%s/" % self.owner
  324. else:
  325. return None
  326. @property
  327. def url(self):
  328. """Get the standard calendar URL."""
  329. return "/%s/" % self.path