1
0

ical.py 12 KB

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