1
0
Fork 0
mirror of https://github.com/Kozea/Radicale.git synced 2025-06-26 16:45:52 +00:00
Radicale/radicale/ical.py

501 lines
15 KiB
Python
Raw Normal View History

# This file is part of Radicale Server - Calendar Server
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
2016-03-31 19:57:40 +02:00
# Copyright © 2008-2016 Guillaume Ayoub
#
# This library is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Radicale. If not, see <http://www.gnu.org/licenses/>.
"""
Radicale collection classes.
Define the main classes of a collection as seen from the server.
"""
import hashlib
2016-04-09 22:44:34 +02:00
import os
import posixpath
2014-08-07 17:52:39 +02:00
import re
from contextlib import contextmanager
2016-04-09 22:44:34 +02:00
from random import randint
from uuid import uuid4
2016-04-10 01:36:45 +02:00
import vobject
def serialize(tag, headers=(), items=()):
"""Return a text corresponding to given collection ``tag``.
2011-12-31 13:31:22 +01:00
The text may have the given ``headers`` and ``items`` added around the
items if needed (ie. for calendars).
2011-12-31 13:31:22 +01:00
"""
items = sorted(items, key=lambda x: x.name)
if tag == "VADDRESSBOOK":
2016-04-10 01:36:45 +02:00
lines = [item.text.strip() for item in items]
else:
lines = ["BEGIN:%s" % tag]
for part in (headers, items):
if part:
2016-04-10 01:36:45 +02:00
lines.append("\r\n".join(item.text.strip() for item in part))
lines.append("END:%s" % tag)
lines.append("")
return "\r\n".join(lines)
2016-04-09 22:44:34 +02:00
def sanitize_path(path):
"""Make path absolute with leading slash to prevent access to other data.
Preserve a potential trailing slash.
"""
trailing_slash = "/" if path.endswith("/") else ""
path = posixpath.normpath(path)
new_path = "/"
for part in path.split("/"):
if not part or part in (".", ".."):
continue
new_path = posixpath.join(new_path, part)
trailing_slash = "" if new_path.endswith("/") else trailing_slash
return new_path + trailing_slash
def clean_name(name):
"""Clean an item name by removing slashes and leading/ending brackets."""
# Remove leading and ending brackets that may have been put by Outlook
name = name.strip("{}")
# Remove slashes, mostly unwanted when saving on filesystems
name = name.replace("/", "_")
return name
2011-04-25 20:35:51 +02:00
def unfold(text):
"""Unfold multi-lines attributes.
Read rfc5545-3.1 for info.
"""
2014-08-07 17:52:39 +02:00
return re.sub('\r\n( |\t)', '', text).splitlines()
2011-04-25 20:35:51 +02:00
2015-02-07 16:06:41 +01:00
class Item(object):
"""Internal iCal item."""
def __init__(self, text, name=None):
"""Initialize object from ``text`` and different ``kwargs``."""
2016-04-10 01:36:45 +02:00
self.component = vobject.readOne(text)
self._name = name
2016-04-10 01:36:45 +02:00
if not self.component.name:
# Header
self._name = next(self.component.lines()).name.lower()
return
# We must synchronize the name in the text and in the object.
# An item must have a name, determined in order by:
#
# - the ``name`` parameter
# - the ``X-RADICALE-NAME`` iCal property (for Events, Todos, Journals)
# - the ``UID`` iCal property (for Events, Todos, Journals)
# - the ``TZID`` iCal property (for Timezones)
if not self._name:
2016-04-10 01:36:45 +02:00
for line in self.component.lines():
if line.name in ("X-RADICALE-NAME", "UID", "TZID"):
self._name = line.value
if line.name == "X-RADICALE-NAME":
break
if self._name:
2016-04-09 22:44:34 +02:00
self._name = clean_name(self._name)
else:
2016-04-09 22:44:34 +02:00
self._name = uuid4().hex
2016-04-10 01:36:45 +02:00
if not hasattr(self.component, "x_radicale_name"):
self.component.add("X-RADICALE-NAME")
self.component.x_radicale_name.value = self._name
def __hash__(self):
2013-10-31 14:05:15 +01:00
return hash(self.text)
def __eq__(self, item):
return isinstance(item, Item) and self.text == item.text
@property
def etag(self):
"""Item etag.
Etag is mainly used to know if an item has changed.
2010-02-10 23:52:50 +01:00
"""
2013-10-31 14:05:15 +01:00
md5 = hashlib.md5()
md5.update(self.text.encode("utf-8"))
return '"%s"' % md5.hexdigest()
@property
def name(self):
"""Item name.
Name is mainly used to give an URL to the item.
"""
return self._name
2016-04-10 01:36:45 +02:00
@property
def text(self):
"""Item serialized text."""
return self.component.serialize()
class Header(Item):
"""Internal header class."""
2011-12-31 13:31:22 +01:00
class Timezone(Item):
"""Internal timezone class."""
tag = "VTIMEZONE"
class Component(Item):
"""Internal main component of a collection."""
class Event(Component):
"""Internal event class."""
tag = "VEVENT"
2011-12-31 13:31:22 +01:00
mimetype = "text/calendar"
2011-12-31 13:31:22 +01:00
class Todo(Component):
2010-02-10 23:52:50 +01:00
"""Internal todo class."""
2011-12-31 13:31:22 +01:00
tag = "VTODO" # pylint: disable=W0511
mimetype = "text/calendar"
2010-02-10 23:52:50 +01:00
2011-12-31 13:31:22 +01:00
class Journal(Component):
"""Internal journal class."""
tag = "VJOURNAL"
2011-12-31 13:31:22 +01:00
mimetype = "text/calendar"
2011-12-31 13:31:22 +01:00
class Card(Component):
"""Internal card class."""
tag = "VCARD"
mimetype = "text/vcard"
2010-02-10 23:52:50 +01:00
2011-12-31 13:31:22 +01:00
class Collection(object):
"""Internal collection item.
2012-01-12 02:39:47 +01:00
This class must be overridden and replaced by a storage backend.
"""
def __init__(self, path, principal=False):
2011-12-31 13:31:22 +01:00
"""Initialize the collection.
2011-06-16 10:39:36 +02:00
2011-12-31 13:31:22 +01:00
``path`` must be the normalized relative path of the collection, using
2011-06-16 10:39:36 +02:00
the slash as the folder delimiter, with no leading nor trailing slash.
"""
2010-02-10 23:52:50 +01:00
self.encoding = "utf-8"
# path should already be sanitized
2016-04-09 22:44:34 +02:00
self.path = sanitize_path(path).strip("/")
split_path = self.path.split("/")
if principal and split_path and self.is_node(self.path):
2011-12-31 13:31:22 +01:00
# Already existing principal collection
self.owner = split_path[0]
2011-07-22 15:00:25 +02:00
elif len(split_path) > 1:
# URL with at least one folder
self.owner = split_path[0]
else:
self.owner = None
self.is_principal = principal
2015-02-07 17:26:20 +01:00
self._items = None
@classmethod
def from_path(cls, path, depth="1", include_container=True):
2011-12-31 13:31:22 +01:00
"""Return a list of collections and items under the given ``path``.
2011-06-05 12:52:24 +02:00
If ``depth`` is "0", only the actual object under ``path`` is
returned.
If ``depth`` is anything but "0", it is considered as "1" and direct
children are included in the result. If ``include_container`` is
``True`` (the default), the containing object is included in the
result.
2011-06-05 12:52:24 +02:00
The ``path`` is relative.
"""
# path == None means wrong URL
if path is None:
return []
# path should already be sanitized
2016-04-09 22:44:34 +02:00
sane_path = sanitize_path(path).strip("/")
attributes = sane_path.split("/")
if not attributes:
return []
# Try to guess if the path leads to a collection or an item
2016-04-09 15:11:47 +02:00
if cls.is_leaf("/".join(attributes[:-1])):
attributes.pop()
result = []
path = "/".join(attributes)
principal = len(attributes) <= 1
if cls.is_node(path):
if depth == "0":
result.append(cls(path, principal))
else:
if include_container:
result.append(cls(path, principal))
2012-02-20 16:32:32 +01:00
for child in cls.children(path):
result.append(child)
else:
if depth == "0":
result.append(cls(path))
else:
2011-12-31 13:31:22 +01:00
collection = cls(path, principal)
if include_container:
2011-12-31 13:31:22 +01:00
result.append(collection)
result.extend(collection.components)
return result
2012-01-12 02:39:47 +01:00
def save(self, text):
"""Save the text into the collection."""
raise NotImplementedError
2012-01-12 02:39:47 +01:00
def delete(self):
"""Delete the collection."""
raise NotImplementedError
2012-01-12 02:39:47 +01:00
@property
def text(self):
"""Collection as plain text."""
raise NotImplementedError
2012-01-12 02:39:47 +01:00
@classmethod
def children(cls, path):
"""Yield the children of the collection at local ``path``."""
raise NotImplementedError
@classmethod
def is_node(cls, path):
"""Return ``True`` if relative ``path`` is a node.
A node is a WebDAV collection whose members are other collections.
"""
raise NotImplementedError
@classmethod
def is_leaf(cls, path):
"""Return ``True`` if relative ``path`` is a leaf.
A leaf is a WebDAV collection whose members are not collections.
"""
raise NotImplementedError
2012-01-12 02:39:47 +01:00
@property
def last_modified(self):
"""Get the last time the collection has been modified.
2010-02-10 23:52:50 +01:00
2012-01-12 02:39:47 +01:00
The date is formatted according to rfc1123-5.2.14.
"""
raise NotImplementedError
2012-01-12 02:39:47 +01:00
@property
@contextmanager
def props(self):
"""Get the collection properties."""
raise NotImplementedError
2010-02-10 23:52:50 +01:00
@property
def exists(self):
"""``True`` if the collection exists on the storage, else ``False``."""
return self.is_node(self.path) or self.is_leaf(self.path)
2010-02-10 23:52:50 +01:00
@staticmethod
def _parse(text, item_types, name=None):
"""Find items with type in ``item_types`` in ``text``.
If ``name`` is given, give this name to new items in ``text``.
2010-02-10 23:52:50 +01:00
2016-01-15 10:50:36 +01:00
Return a dict of items.
2010-02-10 23:52:50 +01:00
"""
2016-04-10 01:36:45 +02:00
item_tags = {item_type.tag: item_type for item_type in item_types}
2011-09-04 22:54:13 +02:00
items = {}
2016-04-10 01:36:45 +02:00
root = next(vobject.readComponents(text))
components = (
root.components() if root.name in ("VADDRESSBOOK", "VCALENDAR")
else (root,))
for component in components:
item_name = None if component.name == "VTIMEZONE" else name
item_type = item_tags[component.name]
item = item_type(component.serialize(), item_name)
if item.name in items:
text = "\r\n".join((item.text, items[item.name].text))
items[item.name] = item_type(text, item.name)
else:
items[item.name] = item
2011-09-04 22:54:13 +02:00
return items
2010-02-10 23:52:50 +01:00
def append(self, name, text):
"""Append items from ``text`` to collection.
2010-02-10 23:52:50 +01:00
If ``name`` is given, give this name to new items in ``text``.
2010-02-10 23:52:50 +01:00
"""
2015-02-07 15:39:57 +01:00
new_items = self._parse(
text, (Timezone, Event, Todo, Journal, Card), name)
for new_item in new_items.values():
2015-02-07 17:26:20 +01:00
if new_item.name not in self.items:
2015-12-10 09:46:38 +01:00
self.items[new_item.name] = new_item
2015-02-07 15:39:57 +01:00
self.write()
2010-02-10 23:52:50 +01:00
def remove(self, name):
"""Remove object named ``name`` from collection."""
2015-02-07 17:26:20 +01:00
if name in self.items:
del self.items[name]
2015-02-07 15:39:57 +01:00
self.write()
2010-02-10 23:52:50 +01:00
def replace(self, name, text):
"""Replace content by ``text`` in collection objet called ``name``."""
self.remove(name)
self.append(name, text)
2010-02-10 23:52:50 +01:00
2015-02-07 15:39:57 +01:00
def write(self):
"""Write collection with given parameters."""
2015-02-07 17:26:20 +01:00
text = serialize(self.tag, self.headers, self.items.values())
self.save(text)
2011-06-01 18:59:53 +02:00
def set_mimetype(self, mimetype):
"""Set the mimetype of the collection."""
with self.props as props:
if "tag" not in props:
if mimetype == "text/vcard":
props["tag"] = "VADDRESSBOOK"
else:
props["tag"] = "VCALENDAR"
2011-12-31 13:31:22 +01:00
@property
def tag(self):
"""Type of the collection."""
with self.props as props:
if "tag" not in props:
try:
2012-02-23 16:20:21 +01:00
tag = open(self.path).readlines()[0][6:].rstrip()
2011-12-31 13:31:22 +01:00
except IOError:
if self.path.endswith((".vcf", "/carddav")):
props["tag"] = "VADDRESSBOOK"
else:
props["tag"] = "VCALENDAR"
2012-02-23 16:20:21 +01:00
else:
if tag in ("VADDRESSBOOK", "VCARD"):
props["tag"] = "VADDRESSBOOK"
else:
props["tag"] = "VCALENDAR"
2011-12-31 13:31:22 +01:00
return props["tag"]
@property
def mimetype(self):
"""Mimetype of the collection."""
if self.tag == "VADDRESSBOOK":
return "text/vcard"
elif self.tag == "VCALENDAR":
return "text/calendar"
@property
def resource_type(self):
"""Resource type of the collection."""
if self.tag == "VADDRESSBOOK":
return "addressbook"
elif self.tag == "VCALENDAR":
return "calendar"
@property
def etag(self):
2011-12-31 13:31:22 +01:00
"""Etag from collection."""
2013-10-29 09:30:51 +01:00
md5 = hashlib.md5()
md5.update(self.text.encode("utf-8"))
return '"%s"' % md5.hexdigest()
2010-02-10 23:52:50 +01:00
@property
def name(self):
2011-12-31 13:31:22 +01:00
"""Collection name."""
2011-05-24 17:33:57 +02:00
with self.props as props:
return props.get("D:displayname", self.path.split(os.path.sep)[-1])
@property
def color(self):
"""Collection color."""
with self.props as props:
if "ICAL:calendar-color" not in props:
props["ICAL:calendar-color"] = "#%x" % randint(0, 255 ** 3 - 1)
return props["ICAL:calendar-color"]
2010-02-10 23:52:50 +01:00
@property
def headers(self):
2011-12-31 13:31:22 +01:00
"""Find headers items in collection."""
2010-02-10 23:52:50 +01:00
header_lines = []
lines = unfold(self.text)[1:]
for line in lines:
if line.startswith(("BEGIN:", "END:")):
break
header_lines.append(Header(line))
2010-02-10 23:52:50 +01:00
2015-02-07 15:39:57 +01:00
return header_lines or (
Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
Header("VERSION:%s" % self.version))
@property
def items(self):
"""Get list of all items in collection."""
2015-02-07 17:26:20 +01:00
if self._items is None:
self._items = self._parse(
self.text, (Event, Todo, Journal, Card, Timezone))
return self._items
2010-02-10 23:52:50 +01:00
@property
def timezones(self):
2015-02-07 17:26:20 +01:00
"""Get list of all timezones in collection."""
return [
item for item in self.items.values() if item.tag == Timezone.tag]
@property
2015-02-07 17:26:20 +01:00
def components(self):
"""Get list of all components in collection."""
tags = [item_type.tag for item_type in (Event, Todo, Journal, Card)]
return [item for item in self.items.values() if item.tag in tags]
@property
def owner_url(self):
2011-12-31 13:31:22 +01:00
"""Get the collection URL according to its owner."""
return "/%s/" % self.owner if self.owner else None
@property
def url(self):
2011-12-31 13:31:22 +01:00
"""Get the standard collection URL."""
return "%s/" % self.path
2012-01-04 19:47:34 +01:00
@property
def version(self):
"""Get the version of the collection type."""
return "3.0" if self.tag == "VADDRESSBOOK" else "2.0"