ical.py 13 KB

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