ical.py 8.59 KB
Newer Older
1
# -*- coding: utf-8 -*-
(no author)'s avatar
(no author) committed
2 3
#
# This file is part of Radicale Server - Calendar Server
Guillaume Ayoub's avatar
Guillaume Ayoub committed
4
# Copyright © 2008-2011 Guillaume Ayoub
5 6
# Copyright © 2008 Nicolas Kandel
# Copyright © 2008 Pascal Halter
(no author)'s avatar
(no author) committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# 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/>.

21 22
"""
Radicale calendar classes.
(no author)'s avatar
(no author) committed
23

24
Define the main classes of a calendar as seen from the server.
25

26
"""
(no author)'s avatar
(no author) committed
27

28 29
import os
import codecs
30
import time
(no author)'s avatar
(no author) committed
31

32
from radicale import config
33 34


35 36
FOLDER = os.path.expanduser(config.get("storage", "folder"))
    
37

38
# This function overrides the builtin ``open`` function for this module
39
# pylint: disable=W0622
40 41 42
def open(path, mode="r"):
    """Open file at ``path`` with ``mode``, automagically managing encoding."""
    return codecs.open(path, mode, config.get("encoding", "stock"))
43
# pylint: enable=W0622
(no author)'s avatar
(no author) committed
44 45


46 47 48 49
def serialize(headers=(), items=()):
    """Return an iCal text corresponding to given ``headers`` and ``items``."""
    lines = ["BEGIN:VCALENDAR"]
    for part in (headers, items):
50
        if part:
51 52 53
            lines.append("\n".join(item.text for item in part))
    lines.append("END:VCALENDAR")
    return "\n".join(lines)
54 55


56 57 58 59
class Item(object):
    """Internal iCal item."""
    def __init__(self, text, name=None):
        """Initialize object from ``text`` and different ``kwargs``."""
60
        self.text = text
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
        self._name = name

        # 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 and Todos)
        # - the ``UID`` iCal property (for Events and Todos)
        # - the ``TZID`` iCal property (for Timezones)
        if not self._name:
            for line in self.text.splitlines():
                if line.startswith("X-RADICALE-NAME:"):
                    self._name = line.replace("X-RADICALE-NAME:", "").strip()
                    break
                elif line.startswith("TZID:"):
                    self._name = line.replace("TZID:", "").strip()
                    break
                elif line.startswith("UID:"):
                    self._name = line.replace("UID:", "").strip()
                    # Do not break, a ``X-RADICALE-NAME`` can appear next

        if "\nX-RADICALE-NAME:" in text:
            for line in self.text.splitlines():
                if line.startswith("X-RADICALE-NAME:"):
                    self.text = self.text.replace(
                        line, "X-RADICALE-NAME:%s" % self._name)
        else:
            self.text = self.text.replace(
                "\nUID:", "\nX-RADICALE-NAME:%s\nUID:" % self._name)
90

91 92 93
    @property
    def etag(self):
        """Item etag.
94

95
        Etag is mainly used to know if an item has changed.
96

97 98
        """
        return '"%s"' % hash(self.text)
(no author)'s avatar
(no author) committed
99

100
    @property
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    def name(self):
        """Item name.

        Name is mainly used to give an URL to the item.

        """
        return self._name


class Header(Item):
    """Internal header class."""


class Event(Item):
    """Internal event class."""
    tag = "VEVENT"
(no author)'s avatar
(no author) committed
117

118

119
class Todo(Item):
120 121
    """Internal todo class."""
    # This is not a TODO!
122
    # pylint: disable=W0511
123
    tag = "VTODO"
124
    # pylint: enable=W0511
125

126

127
class Timezone(Item):
128
    """Internal timezone class."""
129 130
    tag = "VTIMEZONE"

131

132 133
class Calendar(object):
    """Internal calendar class."""
134 135
    tag = "VCALENDAR"

136 137 138 139 140 141 142
    def __init__(self, path):
        """Initialize the calendar with ``cal`` and ``user`` parameters."""
        self.encoding = "utf-8"
        self.owner = path.split("/")[0]
        self.path = os.path.join(FOLDER, path.replace("/", os.path.sep))

    @staticmethod
143 144 145 146
    def _parse(text, item_types, name=None):
        """Find items with type in ``item_types`` in ``text`` text.

        If ``name`` is given, give this name to new items in ``text``.
147

148
        Return a list of items.
149 150

        """
151 152 153 154
        item_tags = {}
        for item_type in item_types:
            item_tags[item_type.tag] = item_type

155 156 157 158 159 160
        items = []

        lines = text.splitlines()
        in_item = False

        for line in lines:
161 162 163 164 165
            if line.startswith("BEGIN:") and not in_item:
                item_tag = line.replace("BEGIN:", "").strip()
                if item_tag in item_tags:
                    in_item = True
                    item_lines = []
166 167 168

            if in_item:
                item_lines.append(line)
169 170 171 172 173 174
                if line.startswith("END:%s" % item_tag):
                    in_item = False
                    item_type = item_tags[item_tag]
                    item_text = "\n".join(item_lines)
                    item_name = None if item_tag == "VTIMEZONE" else name
                    items.append(item_type(item_text, item_name))
175 176 177

        return items

178 179 180 181 182 183
    def get_item(self, name):
        """Get calendar item called ``name``."""
        for item in self.items:
            if item.name == name:
                return item

184 185
    def append(self, name, text):
        """Append items from ``text`` to calendar.
186

187
        If ``name`` is given, give this name to new items in ``text``.
188

189 190
        """
        items = self.items
191

192 193 194
        for new_item in self._parse(text, (Timezone, Event, Todo), name):
            if new_item.name not in (item.name for item in items):
                items.append(new_item)
195

196
        self.write(items=items)
197

198 199 200 201
    def remove(self, name):
        """Remove object named ``name`` from calendar."""
        todos = [todo for todo in self.todos if todo.name != name]
        events = [event for event in self.events if event.name != name]
202

203 204
        items = self.timezones + todos + events
        self.write(items=items)
205

206 207 208 209
    def replace(self, name, text):
        """Replace content by ``text`` in objet named ``name`` in calendar."""
        self.remove(name)
        self.append(name, text)
210

211
    def write(self, headers=None, items=None):
212 213 214 215
        """Write calendar with given parameters."""
        headers = headers or self.headers or (
            Header("PRODID:-//Radicale//NONSGML Radicale Server//EN"),
            Header("VERSION:2.0"))
216
        items = items if items is not None else self.items
217 218 219 220

        # Create folder if absent
        if not os.path.exists(os.path.dirname(self.path)):
            os.makedirs(os.path.dirname(self.path))
221
        
222
        text = serialize(headers, items)
223
        return open(self.path, "w").write(text)
(no author)'s avatar
(no author) committed
224

225
    @property
(no author)'s avatar
(no author) committed
226
    def etag(self):
227 228 229
        """Etag from calendar."""
        return '"%s"' % hash(self.text)

230 231 232 233 234
    @property
    def name(self):
        """Calendar name."""
        return self.path.split(os.path.sep)[-1]

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    @property
    def text(self):
        """Calendar as plain text."""
        try:
            return open(self.path).read()
        except IOError:
            return ""

    @property
    def headers(self):
        """Find headers items in calendar."""
        header_lines = []

        lines = self.text.splitlines()
        for line in lines:
            if line.startswith("PRODID:"):
                header_lines.append(Header(line))
        for line in lines:
            if line.startswith("VERSION:"):
                header_lines.append(Header(line))

        return header_lines

258 259 260 261 262
    @property
    def items(self):
        """Get list of all items in calendar."""
        return self._parse(self.text, (Event, Todo, Timezone))

263 264 265
    @property
    def events(self):
        """Get list of ``Event`` items in calendar."""
266
        return self._parse(self.text, (Event,))
267 268 269 270

    @property
    def todos(self):
        """Get list of ``Todo`` items in calendar."""
271
        return self._parse(self.text, (Todo,))
272 273 274 275

    @property
    def timezones(self):
        """Get list of ``Timezome`` items in calendar."""
276
        return self._parse(self.text, (Timezone,))
277 278 279 280 281 282 283 284

    @property
    def last_modified(self):
        """Get the last time the calendar has been modified.

        The date is formatted according to rfc1123-5.2.14.

        """
285 286 287 288
        # Create calendar if needed
        if not os.path.exists(self.path):
            self.write()

289 290
        modification_time = time.gmtime(os.path.getmtime(self.path))
        return time.strftime("%a, %d %b %Y %H:%M:%S +0000", modification_time)