ical.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. self.path = os.path.join(FOLDER, path.replace("/", os.sep))
  135. if principal and split_path and os.path.isdir(self.path):
  136. # Already existing principal calendar
  137. self.owner = split_path[0]
  138. elif len(split_path) > 1:
  139. # URL with at least one folder
  140. self.owner = split_path[0]
  141. else:
  142. self.owner = None
  143. self.local_path = path if path != '.' else ''
  144. self.is_principal = principal
  145. @classmethod
  146. def from_path(cls, path, depth="infinite", include_container=True):
  147. """Return a list of calendars and items under the given ``path``.
  148. If ``depth`` is "0", only the actual object under ``path`` is
  149. returned. Otherwise, also sub-items are appended to the result. If
  150. ``include_container`` is ``True`` (the default), the containing object
  151. is included in the result.
  152. The ``path`` is relative to the storage folder.
  153. """
  154. # First do normpath and then strip, to prevent access to FOLDER/../
  155. attributes = posixpath.normpath(path).strip("/").split("/")
  156. if not attributes:
  157. return None
  158. if not (os.path.isfile(os.path.join(FOLDER, *attributes)) or
  159. path.endswith("/")):
  160. attributes.pop()
  161. result = []
  162. path = "/".join(attributes)
  163. abs_path = os.path.join(FOLDER, path.replace("/", os.sep))
  164. if os.path.isdir(abs_path):
  165. if depth == "0":
  166. result.append(cls(path, principal=True))
  167. else:
  168. if include_container:
  169. result.append(cls(path, principal=True))
  170. try:
  171. for filename in next(os.walk(abs_path))[2]:
  172. if cls.is_vcalendar(os.path.join(abs_path, filename)):
  173. result.append(cls(os.path.join(path, filename)))
  174. except StopIteration:
  175. # Directory does not exist yet
  176. pass
  177. else:
  178. if depth == "0":
  179. result.append(cls(path))
  180. else:
  181. calendar = cls(path, principal=True)
  182. if include_container:
  183. result.append(calendar)
  184. result.extend(calendar.components)
  185. return result
  186. @staticmethod
  187. def is_vcalendar(path):
  188. """Return ``True`` if there is a VCALENDAR file under ``path``."""
  189. with open(path) as stream:
  190. return 'BEGIN:VCALENDAR' == stream.read(15)
  191. @staticmethod
  192. def _parse(text, item_types, name=None):
  193. """Find items with type in ``item_types`` in ``text``.
  194. If ``name`` is given, give this name to new items in ``text``.
  195. Return a list of items.
  196. """
  197. item_tags = {}
  198. for item_type in item_types:
  199. item_tags[item_type.tag] = item_type
  200. items = []
  201. lines = unfold(text)
  202. in_item = False
  203. for line in lines:
  204. if line.startswith("BEGIN:") and not in_item:
  205. item_tag = line.replace("BEGIN:", "").strip()
  206. if item_tag in item_tags:
  207. in_item = True
  208. item_lines = []
  209. if in_item:
  210. item_lines.append(line)
  211. if line.startswith("END:%s" % item_tag):
  212. in_item = False
  213. item_type = item_tags[item_tag]
  214. item_text = "\n".join(item_lines)
  215. item_name = None if item_tag == "VTIMEZONE" else name
  216. items.append(item_type(item_text, item_name))
  217. return items
  218. def get_item(self, name):
  219. """Get calendar item called ``name``."""
  220. for item in self.items:
  221. if item.name == name:
  222. return item
  223. def append(self, name, text):
  224. """Append items from ``text`` to calendar.
  225. If ``name`` is given, give this name to new items in ``text``.
  226. """
  227. items = self.items
  228. for new_item in self._parse(
  229. text, (Timezone, Event, Todo, Journal), name):
  230. if new_item.name not in (item.name for item in items):
  231. items.append(new_item)
  232. self.write(items=items)
  233. def remove(self, name):
  234. """Remove object named ``name`` from calendar."""
  235. components = [
  236. component for component in self.components
  237. if component.name != name]
  238. items = self.timezones + components
  239. self.write(items=items)
  240. def replace(self, name, text):
  241. """Replace content by ``text`` in objet named ``name`` in calendar."""
  242. self.remove(name)
  243. self.append(name, text)
  244. def write(self, headers=None, items=None):
  245. """Write calendar with given parameters."""
  246. headers = headers or self.headers or (
  247. Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
  248. Header("VERSION:2.0"))
  249. items = items if items is not None else self.items
  250. self._create_dirs(self.path)
  251. text = serialize(headers, items)
  252. return open(self.path, "w").write(text)
  253. @staticmethod
  254. def _create_dirs(path):
  255. """Create folder if absent."""
  256. if not os.path.exists(os.path.dirname(path)):
  257. os.makedirs(os.path.dirname(path))
  258. @property
  259. def etag(self):
  260. """Etag from calendar."""
  261. return '"%s"' % hash(self.text)
  262. @property
  263. def name(self):
  264. """Calendar name."""
  265. with self.props as props:
  266. return props.get('D:displayname',
  267. self.path.split(os.path.sep)[-1])
  268. @property
  269. def text(self):
  270. """Calendar as plain text."""
  271. try:
  272. return open(self.path).read()
  273. except IOError:
  274. return ""
  275. @property
  276. def headers(self):
  277. """Find headers items in calendar."""
  278. header_lines = []
  279. lines = unfold(self.text)
  280. for line in lines:
  281. if line.startswith("PRODID:"):
  282. header_lines.append(Header(line))
  283. for line in lines:
  284. if line.startswith("VERSION:"):
  285. header_lines.append(Header(line))
  286. return header_lines
  287. @property
  288. def items(self):
  289. """Get list of all items in calendar."""
  290. return self._parse(self.text, (Event, Todo, Journal, Timezone))
  291. @property
  292. def components(self):
  293. """Get list of all components in calendar."""
  294. return self._parse(self.text, (Event, Todo, Journal))
  295. @property
  296. def events(self):
  297. """Get list of ``Event`` items in calendar."""
  298. return self._parse(self.text, (Event,))
  299. @property
  300. def todos(self):
  301. """Get list of ``Todo`` items in calendar."""
  302. return self._parse(self.text, (Todo,))
  303. @property
  304. def journals(self):
  305. """Get list of ``Journal`` items in calendar."""
  306. return self._parse(self.text, (Journal,))
  307. @property
  308. def timezones(self):
  309. """Get list of ``Timezome`` items in calendar."""
  310. return self._parse(self.text, (Timezone,))
  311. @property
  312. def last_modified(self):
  313. """Get the last time the calendar has been modified.
  314. The date is formatted according to rfc1123-5.2.14.
  315. """
  316. # Create calendar if needed
  317. if not os.path.exists(self.path):
  318. self.write()
  319. modification_time = time.gmtime(os.path.getmtime(self.path))
  320. return time.strftime("%a, %d %b %Y %H:%M:%S +0000", modification_time)
  321. @property
  322. @contextmanager
  323. def props(self):
  324. """Get the calendar properties."""
  325. props_path = self.path + '.props'
  326. # On enter
  327. properties = {}
  328. if os.path.exists(props_path):
  329. with open(props_path) as prop_file:
  330. properties.update(json.load(prop_file))
  331. yield properties
  332. # On exit
  333. self._create_dirs(props_path)
  334. with open(props_path, 'w') as prop_file:
  335. json.dump(properties, prop_file)
  336. @property
  337. def owner_url(self):
  338. """Get the calendar URL according to its owner."""
  339. if self.owner:
  340. return "/%s/" % self.owner
  341. else:
  342. return None
  343. @property
  344. def url(self):
  345. """Get the standard calendar URL."""
  346. return "/%s/" % self.local_path