ical.py 9.4 KB

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