ical.py 9.1 KB

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