ical.py 12 KB

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