ical.py 14 KB

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