ical.py 12 KB

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