ical.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. import uuid
  31. from radicale import config
  32. FOLDER = os.path.expanduser(config.get("storage", "folder"))
  33. # This function overrides the builtin ``open`` function for this module
  34. # pylint: disable=W0622
  35. def open(path, mode="r"):
  36. """Open file at ``path`` with ``mode``, automagically managing encoding."""
  37. return codecs.open(path, mode, config.get("encoding", "stock"))
  38. # pylint: enable=W0622
  39. def serialize(tag, headers=(), items=()):
  40. """Return a collection text corresponding to given ``tag``.
  41. The collection has the given ``headers`` and ``items``.
  42. """
  43. if tag == "VCARD" or (tag == "VADDRESSBOOK" and items and len(items) == 1):
  44. lines = [items[0].text]
  45. else:
  46. lines = ["BEGIN:%s" % tag]
  47. for part in (headers, items):
  48. if part:
  49. lines.append("\n".join(item.text for item in part))
  50. lines.append("END:%s\n" % tag)
  51. return "\n".join(lines)
  52. def unfold(text):
  53. """Unfold multi-lines attributes.
  54. Read rfc5545-3.1 for info.
  55. """
  56. lines = []
  57. for line in text.splitlines():
  58. if lines and (line.startswith(" ") or line.startswith("\t")):
  59. lines[-1] += line[1:]
  60. else:
  61. lines.append(line)
  62. return lines
  63. class Item(object):
  64. """Internal iCal item."""
  65. def __init__(self, text, name=None):
  66. """Initialize object from ``text`` and different ``kwargs``."""
  67. self.text = text
  68. self._name = name
  69. # We must synchronize the name in the text and in the object.
  70. # An item must have a name, determined in order by:
  71. #
  72. # - the ``name`` parameter
  73. # - the ``X-RADICALE-NAME`` iCal property (for Events, Todos, Journals)
  74. # - the ``UID`` iCal property (for Events, Todos, Journals)
  75. # - the ``TZID`` iCal property (for Timezones)
  76. if not self._name:
  77. for line in unfold(self.text):
  78. if line.startswith("X-RADICALE-NAME:"):
  79. self._name = line.replace("X-RADICALE-NAME:", "").strip()
  80. break
  81. elif line.startswith("TZID:"):
  82. self._name = line.replace("TZID:", "").strip()
  83. break
  84. elif line.startswith("UID:"):
  85. self._name = line.replace("UID:", "").strip()
  86. # Do not break, a ``X-RADICALE-NAME`` can appear next
  87. if self._name:
  88. if "\nX-RADICALE-NAME:" in text:
  89. for line in unfold(self.text):
  90. if line.startswith("X-RADICALE-NAME:"):
  91. self.text = self.text.replace(
  92. line, "X-RADICALE-NAME:%s" % self._name)
  93. else:
  94. self.text = self.text.replace(
  95. "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name)
  96. else:
  97. self._name = str(uuid.uuid4())
  98. self.text = self.text.replace(
  99. "\nEND:", "\nX-RADICALE-NAME:%s\nEND:" % self._name)
  100. @property
  101. def etag(self):
  102. """Item etag.
  103. Etag is mainly used to know if an item has changed.
  104. """
  105. return '"%s"' % hash(self.text)
  106. @property
  107. def name(self):
  108. """Item name.
  109. Name is mainly used to give an URL to the item.
  110. """
  111. return self._name
  112. class Header(Item):
  113. """Internal header class."""
  114. class Timezone(Item):
  115. """Internal timezone class."""
  116. tag = "VTIMEZONE"
  117. class Component(Item):
  118. """Internal main component of a collection."""
  119. class Event(Component):
  120. """Internal event class."""
  121. tag = "VEVENT"
  122. mimetype = "text/calendar"
  123. class Todo(Component):
  124. """Internal todo class."""
  125. tag = "VTODO" # pylint: disable=W0511
  126. mimetype = "text/calendar"
  127. class Journal(Component):
  128. """Internal journal class."""
  129. tag = "VJOURNAL"
  130. mimetype = "text/calendar"
  131. class Card(Component):
  132. """Internal card class."""
  133. tag = "VCARD"
  134. mimetype = "text/vcard"
  135. class Collection(object):
  136. """Internal collection item."""
  137. def __init__(self, path, principal=False):
  138. """Initialize the collection.
  139. ``path`` must be the normalized relative path of the collection, using
  140. the slash as the folder delimiter, with no leading nor trailing slash.
  141. """
  142. self.encoding = "utf-8"
  143. split_path = path.split("/")
  144. self.path = os.path.join(FOLDER, path.replace("/", os.sep))
  145. self.props_path = self.path + '.props'
  146. if principal and split_path and os.path.isdir(self.path):
  147. # Already existing principal collection
  148. self.owner = split_path[0]
  149. elif len(split_path) > 1:
  150. # URL with at least one folder
  151. self.owner = split_path[0]
  152. else:
  153. self.owner = None
  154. self.local_path = path if path != '.' else ''
  155. self.is_principal = principal
  156. @classmethod
  157. def from_path(cls, path, depth="infinite", include_container=True):
  158. """Return a list of collections and items under the given ``path``.
  159. If ``depth`` is "0", only the actual object under ``path`` is
  160. returned. Otherwise, also sub-items are appended to the result. If
  161. ``include_container`` is ``True`` (the default), the containing object
  162. is included in the result.
  163. The ``path`` is relative to the storage folder.
  164. """
  165. # First do normpath and then strip, to prevent access to FOLDER/../
  166. sane_path = posixpath.normpath(path.replace(os.sep, "/")).strip("/")
  167. attributes = sane_path.split("/")
  168. if not attributes:
  169. return None
  170. if not (os.path.isfile(os.path.join(FOLDER, *attributes)) or
  171. path.endswith("/")):
  172. attributes.pop()
  173. result = []
  174. path = "/".join(attributes)
  175. abs_path = os.path.join(FOLDER, path.replace("/", os.sep))
  176. principal = len(attributes) <= 1
  177. if os.path.isdir(abs_path):
  178. if depth == "0":
  179. result.append(cls(path, principal))
  180. else:
  181. if include_container:
  182. result.append(cls(path, principal))
  183. try:
  184. for filename in next(os.walk(abs_path))[2]:
  185. if not filename.endswith(".props"):
  186. collection = cls(os.path.join(path, filename))
  187. if collection.exists:
  188. result.append(collection)
  189. except StopIteration:
  190. # Directory does not exist yet
  191. pass
  192. else:
  193. if depth == "0":
  194. result.append(cls(path))
  195. else:
  196. collection = cls(path, principal)
  197. if include_container:
  198. result.append(collection)
  199. result.extend(collection.components)
  200. return result
  201. @property
  202. def exists(self):
  203. """Return ``True`` if there is a collection file exists."""
  204. beginning_string = 'BEGIN:%s' % self.tag
  205. with open(self.path) as stream:
  206. return beginning_string == stream.read(len(beginning_string))
  207. @property
  208. def items(self):
  209. """Get list of all items in collection."""
  210. return self._parse(self.text, (Card, Event, Todo, Journal, Timezone))
  211. @property
  212. def components(self):
  213. """Get list of all components in collection."""
  214. return self._parse(self.text, (Card, Event, Todo, Journal))
  215. @property
  216. def events(self):
  217. """Get list of ``Event`` items in collection."""
  218. return self._parse(self.text, (Event,))
  219. @property
  220. def cards(self):
  221. """Get list of all cards in collection."""
  222. return self._parse(self.text, (Card,))
  223. @property
  224. def todos(self):
  225. """Get list of ``Todo`` items in collection."""
  226. return self._parse(self.text, (Todo,))
  227. @property
  228. def journals(self):
  229. """Get list of ``Journal`` items in collection."""
  230. return self._parse(self.text, (Journal,))
  231. @property
  232. def timezones(self):
  233. """Get list of ``Timezome`` items in collection."""
  234. return self._parse(self.text, (Timezone,))
  235. @staticmethod
  236. def _parse(text, item_types, name=None):
  237. """Find items with type in ``item_types`` in ``text``.
  238. If ``name`` is given, give this name to new items in ``text``.
  239. Return a list of items.
  240. """
  241. item_tags = {}
  242. for item_type in item_types:
  243. item_tags[item_type.tag] = item_type
  244. items = {}
  245. lines = unfold(text)
  246. in_item = False
  247. for line in lines:
  248. if line.startswith("BEGIN:") and not in_item:
  249. item_tag = line.replace("BEGIN:", "").strip()
  250. if item_tag in item_tags:
  251. in_item = True
  252. item_lines = []
  253. if in_item:
  254. item_lines.append(line)
  255. if line.startswith("END:%s" % item_tag):
  256. in_item = False
  257. item_type = item_tags[item_tag]
  258. item_text = "\n".join(item_lines)
  259. item_name = None if item_tag == "VTIMEZONE" else name
  260. item = item_type(item_text, item_name)
  261. if item.name in items:
  262. text = "\n".join((item.text, items[item.name].text))
  263. items[item.name] = item_type(text, item.name)
  264. else:
  265. items[item.name] = item
  266. return list(items.values())
  267. def get_item(self, name):
  268. """Get calendar item called ``name``."""
  269. for item in self.items:
  270. if item.name == name:
  271. return item
  272. def append(self, name, text):
  273. """Append items from ``text`` to calendar.
  274. If ``name`` is given, give this name to new items in ``text``.
  275. """
  276. items = self.items
  277. for new_item in self._parse(
  278. text, (Timezone, Event, Todo, Journal, Card), name):
  279. if new_item.name not in (item.name for item in items):
  280. items.append(new_item)
  281. self.write(items=items)
  282. def delete(self):
  283. """Delete the calendar."""
  284. os.remove(self.path)
  285. os.remove(self.props_path)
  286. def remove(self, name):
  287. """Remove object named ``name`` from calendar."""
  288. components = [
  289. component for component in self.components
  290. if component.name != name]
  291. items = self.timezones + components
  292. self.write(items=items)
  293. def replace(self, name, text):
  294. """Replace content by ``text`` in objet named ``name`` in calendar."""
  295. self.remove(name)
  296. self.append(name, text)
  297. def write(self, headers=None, items=None):
  298. """Write calendar with given parameters."""
  299. headers = headers or self.headers or (
  300. Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
  301. Header("VERSION:%s" % self.version))
  302. items = items if items is not None else self.items
  303. self._create_dirs(self.path)
  304. text = serialize(self.tag, headers, items)
  305. return open(self.path, "w").write(text)
  306. def set_mimetype(self, mimetype):
  307. """Set the mimetype of the collection."""
  308. with self.props as props:
  309. if "tag" not in props:
  310. if mimetype == "text/vcard":
  311. props["tag"] = "VADDRESSBOOK"
  312. else:
  313. props["tag"] = "VCALENDAR"
  314. @staticmethod
  315. def _create_dirs(path):
  316. """Create folder if absent."""
  317. if not os.path.exists(os.path.dirname(path)):
  318. os.makedirs(os.path.dirname(path))
  319. @property
  320. def tag(self):
  321. """Type of the collection."""
  322. with self.props as props:
  323. if "tag" not in props:
  324. try:
  325. props["tag"] = open(self.path).readlines()[0][6:].rstrip()
  326. except IOError:
  327. props["tag"] = "VCALENDAR"
  328. return props["tag"]
  329. @property
  330. def mimetype(self):
  331. """Mimetype of the collection."""
  332. if self.tag == "VADDRESSBOOK":
  333. return "text/vcard"
  334. elif self.tag == "VCALENDAR":
  335. return "text/calendar"
  336. @property
  337. def resource_type(self):
  338. """Resource type of the collection."""
  339. if self.tag == "VADDRESSBOOK":
  340. return "addressbook"
  341. elif self.tag == "VCALENDAR":
  342. return "calendar"
  343. @property
  344. def etag(self):
  345. """Etag from collection."""
  346. return '"%s"' % hash(self.text)
  347. @property
  348. def name(self):
  349. """Collection name."""
  350. with self.props as props:
  351. return props.get('D:displayname',
  352. self.path.split(os.path.sep)[-1])
  353. @property
  354. def text(self):
  355. """Collection as plain text."""
  356. try:
  357. return open(self.path).read()
  358. except IOError:
  359. return ""
  360. @property
  361. def headers(self):
  362. """Find headers items in collection."""
  363. header_lines = []
  364. lines = unfold(self.text)
  365. for header in ("PRODID", "VERSION"):
  366. for line in lines:
  367. if line.startswith("%s:" % header):
  368. header_lines.append(Header(line))
  369. break
  370. return header_lines
  371. @property
  372. def last_modified(self):
  373. """Get the last time the collection has been modified.
  374. The date is formatted according to rfc1123-5.2.14.
  375. """
  376. # Create calendar if needed
  377. if not os.path.exists(self.path):
  378. self.write()
  379. modification_time = time.gmtime(os.path.getmtime(self.path))
  380. return time.strftime("%a, %d %b %Y %H:%M:%S +0000", modification_time)
  381. @property
  382. @contextmanager
  383. def props(self):
  384. """Get the collection properties."""
  385. # On enter
  386. properties = {}
  387. if os.path.exists(self.props_path):
  388. with open(self.props_path) as prop_file:
  389. properties.update(json.load(prop_file))
  390. yield properties
  391. # On exit
  392. self._create_dirs(self.props_path)
  393. with open(self.props_path, 'w') as prop_file:
  394. json.dump(properties, prop_file)
  395. @property
  396. def owner_url(self):
  397. """Get the collection URL according to its owner."""
  398. if self.owner:
  399. return "/%s/" % self.owner
  400. else:
  401. return None
  402. @property
  403. def url(self):
  404. """Get the standard collection URL."""
  405. return "/%s/" % self.local_path
  406. @property
  407. def version(self):
  408. """Get the version of the collection type."""
  409. return "3.0" if self.tag == "VADDRESSBOOK" else "2.0"