ical.py 13 KB

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