ical.py 8.1 KB

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