1
0

ical.py 15 KB

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