ical.py 9.9 KB

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