caldav-0.4.0/0000755000076600000240000000000012516226324013216 5ustar cyrilstaff00000000000000caldav-0.4.0/caldav/0000755000076600000240000000000012516226324014450 5ustar cyrilstaff00000000000000caldav-0.4.0/caldav/__init__.py0000644000076600000240000000044512506772024016566 0ustar cyrilstaff00000000000000#!/usr/bin/env python from .davclient import DAVClient from .objects import * import logging # Silence notification of no default logging handler log = logging.getLogger("caldav") class NullHandler(logging.Handler): def emit(self, record): pass log.addHandler(NullHandler()) caldav-0.4.0/caldav/davclient.py0000644000076600000240000001766512516226026017011 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- import requests import logging from caldav.lib.python_utilities import isPython3, to_unicode, to_wire if isPython3(): from urllib import parse from urllib.parse import unquote else: from urlparse import unquote, urlparse as parse import re from lxml import etree from caldav.lib import error from caldav.lib.url import URL from caldav.objects import Principal log = logging.getLogger('caldav') class DAVResponse: """ This class is a response from a DAV request. It is instantiated from the DAVClient class. End users of the library should not need to know anything about this class. Since we often get XML responses, it tries to parse it into `self.tree` """ raw = "" reason = "" tree = None headers = {} status = 0 def __init__(self, response): self.raw = response.content self.headers = response.headers self.status = response.status_code self.reason = response.reason log.debug("response headers: " + str(self.headers)) log.debug("response status: " + str(self.status)) log.debug("raw response: " + str(self.raw)) try: self.tree = etree.XML(self.raw) except: self.tree = None class DAVClient: """ Basic client for webdav, uses the requests lib; gives access to low-level operations towards the caldav server. Unless you have special needs, you should probably care most about the __init__ and principal methods. """ proxy = None url = None def __init__(self, url, proxy=None, username=None, password=None, auth=None, ssl_verify_cert=True): """ Sets up a HTTPConnection object towards the server in the url. Parameters: * url: A fully qualified url: `scheme://user:pass@hostname:port` * proxy: A string defining a proxy server: `hostname:port` * username and password should be passed as arguments or in the URL * auth and ssl_verify_cert is passed to requests.request. ** ssl_verify_cert can be the path of a CA-bundle or False. """ log.debug("url: " + str(url)) self.url = URL.objectify(url) # Prepare proxy info if proxy is not None: self.proxy = proxy if re.match('^.*://', proxy) is None: # requests library expects the proxy url to have a scheme self.proxy = self.url.scheme + '://' + proxy # add a port is one is not specified # TODO: this will break if using basic auth and embedding # username:password in the proxy URL p = self.proxy.split(":") if len(p) == 2: self.proxy += ':8080' log.debug("init - proxy: %s" % (self.proxy)) # Build global headers self.headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "text/xml", "Accept": "text/xml"} if self.url.username is not None: username = unquote(self.url.username) password = unquote(self.url.password) self.username = username self.password = password self.auth = auth ## TODO: it's possible to force through a specific auth method here, but no test code for this. self.ssl_verify_cert = ssl_verify_cert self.url = self.url.unauth() log.debug("self.url: " + str(url)) def principal(self): """ Convenience method, it gives a bit more object-oriented feel to write client.principal() than Principal(client). This method returns a :class:`caldav.Principal` object, with higher-level methods for dealing with the principals calendars. """ return Principal(self) def propfind(self, url=None, props="", depth=0): """ Send a propfind request. Parameters: * url: url for the root of the propfind. * props = (xml request), properties we want * depth: maximum recursion depth Returns * DAVResponse """ return self.request(url or self.url, "PROPFIND", props, {'Depth': str(depth)}) def proppatch(self, url, body, dummy=None): """ Send a proppatch request. Parameters: * url: url for the root of the propfind. * body: XML propertyupdate request * dummy: compatibility parameter Returns * DAVResponse """ return self.request(url, "PROPPATCH", body) def report(self, url, query="", depth=0): """ Send a report request. Parameters: * url: url for the root of the propfind. * query: XML request * depth: maximum recursion depth Returns * DAVResponse """ return self.request(url, "REPORT", query, {'Depth': str(depth), "Content-Type": "application/xml; charset=\"utf-8\""}) def mkcol(self, url, body, dummy=None): """ Send a mkcol request. Parameters: * url: url for the root of the mkcol * body: XML request * dummy: compatibility parameter Returns * DAVResponse """ return self.request(url, "MKCOL", body) def mkcalendar(self, url, body="", dummy=None): """ Send a mkcalendar request. Parameters: * url: url for the root of the mkcalendar * body: XML request * dummy: compatibility parameter Returns * DAVResponse """ return self.request(url, "MKCALENDAR", body) def put(self, url, body, headers={}): """ Send a put request. """ return self.request(url, "PUT", body, headers) def delete(self, url): """ Send a delete request. """ return self.request(url, "DELETE") def request(self, url, method="GET", body="", headers={}): """ Actually sends the request """ # objectify the url url = URL.objectify(url) proxies = None if self.proxy is not None: proxies = {url.scheme: self.proxy} log.debug("using proxy - %s" % (proxies)) # ensure that url is a unicode string url = str(url) combined_headers = self.headers combined_headers.update(headers) if body is None or body == "" and "Content-Type" in combined_headers: del combined_headers["Content-Type"] log.debug("sending request - method={0}, url={1}, headers={2}\nbody:\n{3}".format(method, url, combined_headers, body)) auth = None if self.auth is None and self.username is not None: auth = requests.auth.HTTPDigestAuth(self.username, self.password) else: auth = self.auth r = requests.request(method, url, data=to_wire(body), headers=combined_headers, proxies=proxies, auth=auth, verify=self.ssl_verify_cert) response = DAVResponse(r) ## If server supports BasicAuth and not DigestAuth, let's try again: if response.status == 401 and self.auth is None and auth is not None: auth = requests.auth.HTTPBasicAuth(self.username, self.password) r = requests.request(method, url, data=to_wire(body), headers=combined_headers, proxies=proxies, auth=auth, verify=self.ssl_verify_cert) response = DAVResponse(r) # this is an error condition the application wants to know if response.status == requests.codes.forbidden or \ response.status == requests.codes.unauthorized: ex = error.AuthorizationError() ex.url = url ex.reason = response.reason raise ex ## let's save the auth object and remove the user/pass information if not self.auth and auth: self.auth = auth del self.username del self.password return response caldav-0.4.0/caldav/elements/0000755000076600000240000000000012516226324016264 5ustar cyrilstaff00000000000000caldav-0.4.0/caldav/elements/__init__.py0000644000076600000240000000006212306107420020363 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- caldav-0.4.0/caldav/elements/base.py0000644000076600000240000000370512506772024017557 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- from lxml import etree from caldav.lib.namespace import nsmap from caldav.lib.python_utilities import isPython3, to_unicode class BaseElement(object): children = None tag = None value = None attributes = None def __init__(self, name=None, value=None): self.children = [] self.attributes = {} value = to_unicode(value) self.value = None if name is not None: self.attributes['name'] = name if value is not None: self.value = value def __add__(self, other): return self.append(other) def __str__(self): utf8 = etree.tostring(self.xmlelement(), encoding="utf-8", xml_declaration=True, pretty_print=True) if isPython3(): return str(utf8, 'utf-8') return utf8 def xmlelement(self): root = etree.Element(self.tag, nsmap=nsmap) if self.value is not None: root.text = self.value if len(self.attributes) > 0: for k in list(self.attributes.keys()): root.set(k, self.attributes[k]) self.xmlchildren(root) return root def xmlchildren(self, root): for c in self.children: root.append(c.xmlelement()) def append(self, element): try: iter(element) self.children.extend(element) except TypeError: self.children.append(element) return self class NamedBaseElement(BaseElement): def __init__(self, name=None): super(NamedBaseElement, self).__init__(name=name) def xmlelement(self): if self.attributes.get('name') is None: raise Exception("name attribute must be defined") return super(NamedBaseElement, self).xmlelement() class ValuedBaseElement(BaseElement): def __init__(self, value=None): super(ValuedBaseElement, self).__init__(value=value) caldav-0.4.0/caldav/elements/cdav.py0000644000076600000240000000604112516226026017553 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- from caldav.lib.namespace import ns from .base import BaseElement, NamedBaseElement, ValuedBaseElement ## Operations class CalendarQuery(BaseElement): tag = ns("C", "calendar-query") class FreeBusyQuery(BaseElement): tag = ns("C", "free-busy-query") class Mkcalendar(BaseElement): tag = ns("D", "mkcalendar") ## Filters class Filter(BaseElement): tag = ns("C", "filter") class CompFilter(NamedBaseElement): tag = ns("C", "comp-filter") class PropFilter(NamedBaseElement): tag = ns("C", "prop-filter") class ParamFilter(NamedBaseElement): tag = ns("C", "param-filter") ## Conditions class TextMatch(ValuedBaseElement): tag = ns("C", "text-match") def __init__(self, value, collation="i;octet", negate=False): super(TextMatch, self).__init__(value=value) self.attributes['collation'] = collation self.attributes['negate-condition'] = "no" if negate: self.attributes['negate-condition'] = "yes" class TimeRange(BaseElement): tag = ns("C", "time-range") def __init__(self, start=None, end=None): super(TimeRange, self).__init__() if start is not None: self.attributes['start'] = \ start.strftime("%Y%m%dT%H%M%SZ") if end is not None: self.attributes['end'] = end.strftime("%Y%m%dT%H%M%SZ") class NotDefined(BaseElement): tag = ns("C", "is-not-defined") ## Components / Data class CalendarData(BaseElement): tag = ns("C", "calendar-data") class Expand(BaseElement): tag = ns("C", "expand") def __init__(self, start, end=None): super(Expand, self).__init__() self.attributes['start'] = start.strftime("%Y%m%dT%H%M%SZ") if end is not None: self.attributes['end'] = end.strftime("%Y%m%dT%H%M%SZ") class Comp(NamedBaseElement): tag = ns("C", "comp") class CalendarCollection(BaseElement): tag = ns("C", "calendar-collection") ## Properties class CalendarHomeSet(BaseElement): tag = ns("C", "calendar-home-set") # calendar resource type, see rfc4791, sec. 4.2 class Calendar(BaseElement): tag = ns("C", "calendar") class CalendarDescription(ValuedBaseElement): tag = ns("C", "calendar-description") class CalendarTimeZone(ValuedBaseElement): tag = ns("C", "calendar-timezone") class SupportedCalendarComponentSet(ValuedBaseElement): tag = ns("C", "supported-calendar-component-set") class SupportedCalendarData(ValuedBaseElement): tag = ns("C", "supported-calendar-data") class MaxResourceSize(ValuedBaseElement): tag = ns("C", "max-resource-size") class MinDateTime(ValuedBaseElement): tag = ns("C", "min-date-time") class MaxDateTime(ValuedBaseElement): tag = ns("C", "max-date-time") class MaxInstances(ValuedBaseElement): tag = ns("C", "max-instances") class MaxAttendeesPerInstance(ValuedBaseElement): tag = ns("C", "max-attendees-per-instance") class SupportedCalendarComponentSet(BaseElement): tag = ns("C", "supported-calendar-component-set") caldav-0.4.0/caldav/elements/dav.py0000644000076600000240000000171112506772024017412 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- from caldav.lib.namespace import ns from .base import BaseElement, ValuedBaseElement ## Operations class Propfind(BaseElement): tag = ns("D", "propfind") class PropertyUpdate(BaseElement): tag = ns("D", "propertyupdate") class Mkcol(BaseElement): tag = ns("D", "mkcol") ## Filters ## Conditions ## Components / Data class Prop(BaseElement): tag = ns("D", "prop") class Collection(BaseElement): tag = ns("D", "collection") class Set(BaseElement): tag = ns("D", "set") ## Properties class ResourceType(BaseElement): tag = ns("D", "resourcetype") class DisplayName(ValuedBaseElement): tag = ns("D", "displayname") class Href(BaseElement): tag = ns("D", "href") class Response(BaseElement): tag = ns("D", "response") class Status(BaseElement): tag = ns("D", "status") class CurrentUserPrincipal(BaseElement): tag = ns("D", "current-user-principal") caldav-0.4.0/caldav/lib/0000755000076600000240000000000012516226324015216 5ustar cyrilstaff00000000000000caldav-0.4.0/caldav/lib/__init__.py0000644000076600000240000000000012306107420017305 0ustar cyrilstaff00000000000000caldav-0.4.0/caldav/lib/error.py0000644000076600000240000000175012516226026016723 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- class AuthorizationError(Exception): """ The client encountered an HTTP 403 error and is passing it on to the user. The url property will contain the url in question, the reason property will contain the excuse the server sent. """ url = None reason = "PHP at work[tm]" def __str__(self): return "AuthorizationError at '%s', reason '%s'" % \ (self.url, self.reason) class PropsetError(Exception): pass class PropfindError(Exception): pass class ReportError(Exception): pass class MkcolError(Exception): pass class MkcalendarError(Exception): pass class PutError(Exception): pass class DeleteError(Exception): pass class NotFoundError(Exception): pass exception_by_method = {} for method in ('delete', 'put', 'mkcalendar', 'mkcol', 'report', 'propset', 'propfind'): exception_by_method[method] = locals()[method[0].upper() + method[1:] + 'Error'] caldav-0.4.0/caldav/lib/namespace.py0000644000076600000240000000077712306107420017527 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- ## nsmap2 is ref https://bitbucket.org/cyrilrbt/caldav/issue/29/centos59-minifix ## This looks wrong - should think more about it at a later stage. ## -- Tobias Brox, 2014-02-16 nsmap = { "D": "DAV", "C": "urn:ietf:params:xml:ns:caldav", } nsmap2 = { "D": "DAV:", "C": "urn:ietf:params:xml:ns:caldav", } def ns(prefix, tag=None): name = "{%s}" % nsmap2[prefix] if tag is not None: name = "%s%s" % (name, tag) return name caldav-0.4.0/caldav/lib/python_utilities.py0000644000076600000240000000134212506772024021206 0ustar cyrilstaff00000000000000import sys from six import string_types def isPython3(): return sys.version_info >= (3, 0) def to_wire(text): if text and isinstance(text, string_types) and isPython3(): text = bytes(text, 'utf-8') elif not isPython3(): text = to_unicode(text).encode('utf-8') return text def to_local(text): if text and not isinstance(text, string_types): text = text.decode('utf-8') return text def to_str(text): if text and not isinstance(text, string_types): text = text.decode('utf-8') return text def to_unicode(text): if text and isinstance(text, string_types) and not isPython3() and not isinstance(text, unicode): text = unicode(text, 'utf-8') return text caldav-0.4.0/caldav/lib/url.py0000644000076600000240000001425112506772024016377 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- from caldav.lib.python_utilities import isPython3, to_unicode if isPython3(): from urllib import parse from urllib.parse import ParseResult, SplitResult, urlparse, unquote else: from urlparse import urlparse as parse from urlparse import ParseResult, SplitResult from urlparse import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if not isPython3() and type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's used internally in the library, end users should not need to know anything about this class. All methods that accept URLs can be fed either with an URL object, a string or an urlparse.ParsedURL object. Addresses may be one out of three: 1) a path relative to the DAV-root, i.e. "someuser/calendar" may refer to "http://my.davical-server.example.com/caldav.php/someuser/calendar". 2) an absolute path, i.e. "/caldav.php/someuser/calendar" 3) a fully qualified URL, i.e. "http://someuser:somepass@my.davical-server.example.com/caldav.php/someuser/calendar". Remark that hostname, port, user, pass is typically given when instantiating the DAVClient object and cannot be overridden later. As of 2013-11, some methods in the caldav library expected strings and some expected urlParseResult objects, some expected fully qualified URLs and most expected absolute paths. The purpose of this class is to ensure consistency and at the same time maintaining backward compatibility. Basically, all methods should accept any kind of URL. """ def __init__(self, url): if isinstance(url, ParseResult) or isinstance(url, SplitResult): self.url_parsed = url self.url_raw = None else: self.url_raw = url self.url_parsed = None def __bool__(self): if self.url_raw or self.url_parsed: return True else: return False def __ne__(self, other): return not self == other def __eq__(self, other): if str(self) == str(other): return True ## The URLs could have insignificant differences me = self.canonical() if hasattr(other, 'canonical'): other = other.canonical() return str(me) == str(other) ## TODO: better naming? Will return url if url is already an URL ## object, else will instantiate a new URL object @classmethod def objectify(self, url): if url is None: return None if isinstance(url, URL): return url else: return URL(url) ## To deal with all kind of methods/properties in the ParseResult ## class def __getattr__(self, attr): if self.url_parsed is None: self.url_parsed = urlparse(self.url_raw) if hasattr(self.url_parsed, attr): return getattr(self.url_parsed, attr) else: return getattr(self.__unicode__(), attr) ## returns the url in text format def __str__(self): if isPython3(): return self.__unicode__() return self.__unicode__().encode('utf-8') ## returns the url in text format def __unicode__(self): if self.url_raw is None: self.url_raw = self.url_parsed.geturl() if isinstance(self.url_raw, str): return to_unicode(self.url_raw) else: return to_unicode(str(self.url_raw)) def __repr__(self): return "URL(%s)" % str(self) def strip_trailing_slash(self): if str(self)[-1] == '/': return URL.objectify(str(self)[:-1]) else: return self def is_auth(self): return self.username is not None def unauth(self): if not self.is_auth(): return self return URL.objectify(ParseResult( self.scheme, '%s:%s' % (self.hostname, self.port or {'https': 443, 'http': 80}[self.scheme]), self.path.replace('//', '/'), self.params, self.query, self.fragment)) def canonical(self): """ a canonical URL ... remove authentication details, make sure there are no double slashes, and to make sure the URL is always the same, run it through the urlparser """ url = self.unauth() ## this is actually already done in the unauth method ... if '//' in url.path: raise NotImplementedError("remove the double slashes") ## This looks like a noop - but it may have the side effect ## that urlparser be run (actually not - unauth ensures we ## have an urlParseResult object) url.scheme ## make sure to delete the string version url.url_raw = None return url def join(self, path): """ assumes this object is the base URL or base path. If the path is relative, it should be appended to the base. If the path is absolute, it should be added to the connection details of self. If the path already contains connection details and the connection details differ from self, raise an error. """ pathAsString = str(path) if not path or not pathAsString: return self path = URL.objectify(path) if ( (path.scheme and self.scheme and path.scheme != self.scheme) or (path.hostname and self.hostname and path.hostname != self.hostname) or (path.port and self.port and path.port != self.port) ): raise ValueError("%s can't be joined with %s" % (self, path)) if path.path[0] == '/': ret_path = uc2utf8(path.path) else: sep = "/" if self.path.endswith("/"): sep = "" ret_path = "%s%s%s" % (self.path, sep, uc2utf8(path.path)) return URL(ParseResult( self.scheme or path.scheme, self.netloc or path.netloc, ret_path, path.params, path.query, path.fragment)) def make(url): """Backward compatibility""" return URL.objectify(url) caldav-0.4.0/caldav/lib/vcal.py0000644000076600000240000000070012506772024016514 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- import re from caldav.lib.python_utilities import to_local def fix(event): fixed = re.sub('COMPLETED:(\d+)\s', 'COMPLETED:\g<1>T120000Z', to_local(event)) #The following line fixes a data bug in some Google Calendar events fixed = re.sub('CREATED:00001231T000000Z', 'CREATED:19700101T000000Z', fixed) fixed = re.sub(r"\\+('\")", r"\1", fixed) return fixed caldav-0.4.0/caldav/objects.py0000644000076600000240000006410512516226026016460 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- """ A "DAV object" is anything we get from the caldav server or push into the caldav server, notably principal, calendars and calendar events. """ import vobject import io import uuid import re import datetime from lxml import etree from caldav.lib import error, vcal, url from caldav.lib.url import URL from caldav.elements import dav, cdav from caldav.lib.python_utilities import to_unicode class DAVObject(object): """ Base class for all DAV objects. Can be instantiated by a client and an absolute or relative URL, or from the parent object. """ id = None url = None client = None parent = None name = None def __init__(self, client=None, url=None, parent=None, name=None, id=None, **extra): """ Default constructor. Parameters: * client: A DAVClient instance * url: The url for this object. May be a full URL or a relative URL. * parent: The parent object - used when creating objects * name: A displayname * id: The resource id (UID for an Event) """ if client is None and parent is not None: client = parent.client self.client = client self.parent = parent self.name = name self.id = id self.extra_init_options = extra ## url may be a path relative to the caldav root if client and url: self.url = client.url.join(url) else: self.url = URL.objectify(url) @property def canonical_url(self): return str(self.url.unauth()) def children(self, type=None): """ List children, using a propfind (resourcetype) on the parent object, at depth = 1. """ c = [] depth = 1 properties = {} props = [dav.ResourceType(), ] response = self._query_properties(props, depth) properties = self._handle_prop_response(response=response, props=props, type=type, what='tag') for path in list(properties.keys()): resource_type = properties[path][dav.ResourceType.tag] if resource_type == type or type is None: ## TODO: investigate the RFCs thoroughly - why does a "get ## members of this collection"-request also return the collection URL itself? ## And why is the strip_trailing_slash-method needed? The collection URL ## should always end with a slash according to RFC 2518, section 5.2. if self.url.strip_trailing_slash() != self.url.join(path).strip_trailing_slash(): c.append((self.url.join(path), resource_type)) return c def _query_properties(self, props=[], depth=0): """ This is an internal method for doing a propfind query. It's a result of code-refactoring work, attempting to consolidate similar-looking code into a common method. """ root = None # build the propfind request if len(props) > 0: prop = dav.Prop() + props root = dav.Propfind() + prop return self._query(root, depth) def _query(self, root=None, depth=0, query_method='propfind', url=None, expected_return_value=None): """ This is an internal method for doing a query. It's a result of code-refactoring work, attempting to consolidate similar-looking code into a common method. """ if url is None: url = self.url body = "" if root: body = etree.tostring(root.xmlelement(), encoding="utf-8", xml_declaration=True) ret = getattr(self.client, query_method)( url, body, depth) if ret.status == 404: raise error.NotFoundError(ret.raw) if ( (expected_return_value is not None and ret.status != expected_return_value) or ret.status >= 400): raise error.exception_by_method[query_method](ret.raw) return ret def _handle_prop_response(self, response, props=[], type=None, what='text'): """ Internal method to massage an XML response into a dict. (This method is a result of some code refactoring work, attempting to consolidate similar-looking code) """ properties = {} # All items should be in a element for r in response.tree.findall('.//' + dav.Response.tag): status = r.find('.//' + dav.Status.tag) if not status.text.endswith('200 OK'): if status.text.endswith('404 Not Found'): ## Silently ignoring the 404 ## (we should probably spit out some debug logging here) continue raise error.ReportError(response.raw) ## TODO: may be wrong error class href = r.find('.//' + dav.Href.tag).text properties[href] = {} for p in props: t = r.find(".//" + p.tag) if len(list(t)) > 0: if type is not None: val = t.find(".//" + type) else: val = t.find(".//*") if val is not None: val = getattr(val, what) else: val = None else: val = t.text properties[href][p.tag] = val return properties def get_properties(self, props=[], depth=0): """ Get properties (PROPFIND) for this object. Works only for properties, that don't have complex types. Parameters: * props = [dav.ResourceType(), dav.DisplayName(), ...] Returns: * {proptag: value, ...} """ rc = None response = self._query_properties(props, depth) properties = self._handle_prop_response(response, props) path = self.url.path exchange_path = self.url.path + '/' if path in list(properties.keys()): rc = properties[path] elif exchange_path in list(properties.keys()): rc = properties[exchange_path] else: raise Exception("The CalDAV server you are using has " "a problem with path handling.") return rc def set_properties(self, props=[]): """ Set properties (PROPPATCH) for this object. Parameters: * props = [dav.DisplayName('name'), ...] Returns: * self """ prop = dav.Prop() + props set = dav.Set() + prop root = dav.PropertyUpdate() + set r = self._query(root, query_method='proppatch') statuses = r.tree.findall(".//" + dav.Status.tag) for s in statuses: if not s.text.endswith("200 OK"): raise error.PropsetError(r.raw) return self def save(self): """ Save the object. This is an abstract method, that all classes derived .from DAVObject implement. Returns: * self """ raise NotImplementedError() def delete(self): """ Delete the object. """ if self.url is not None: r = self.client.delete(self.url) #TODO: find out why we get 404 if r.status not in (200, 204, 404): raise error.DeleteError(r.raw) def __str__(self): return str(self.url) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.url) class CalendarSet(DAVObject): def calendars(self): """ List all calendar collections in this set. Returns: * [Calendar(), ...] """ cals = [] data = self.children(cdav.Calendar.tag) for c_url, c_type in data: cals.append(Calendar(self.client, c_url, parent=self)) return cals def make_calendar(self, name=None, cal_id=None, supported_calendar_component_set=None): """ Utility method for creating a new calendar. Parameters: * name: the name of the new calendar * cal_id: the uuid of the new calendar * supported_calendar_component_set: what kind of objects (EVENT, VTODO, VFREEBUSY, VJOURNAL) the calendar should handle. Should be set to ['VTODO'] when creating a task list in Zimbra - in most other cases the default will be OK. Returns: * Calendar(...)-object """ return Calendar(self.client, name=name, parent=self, id=cal_id, supported_calendar_component_set=supported_calendar_component_set).save() def calendar(self, name=None, cal_id=None): """ The calendar method will return a calendar object. It will not initiate any communication with the server. Parameters: * name: return the calendar with this name * cal_id: return the calendar with this calendar id Returns: * Calendar(...)-object """ return Calendar(self.client, name=name, parent = self, url = self.url.join(cal_id), id=cal_id) class Principal(DAVObject): """ This class represents a DAV Principal. It doesn't do much, except keep track of the URLs for the calendar-home-set, etc. """ def __init__(self, client=None, url=None): """ Returns a Principal. Parameters: * client: a DAVClient() oject * url: Deprecated - for backwards compatibility purposes only. If url is not given, deduct principal path as well as calendar home set path from doing propfinds. """ self.client = client self._calendar_home_set = None ## backwards compatibility. if url is not None: self.url = client.url.join(URL.objectify(url)) else: self.url = self.client.url cup = self.get_properties([dav.CurrentUserPrincipal()]) self.url = self.client.url.join(URL.objectify(cup['{DAV:}current-user-principal'])) def make_calendar(self, name=None, cal_id=None, supported_calendar_component_set=None): """ Convenience method, bypasses the self.calendar_home_set object. See CalendarSet.make_calendar for details. """ return self.calendar_home_set.make_calendar(name, cal_id, supported_calendar_component_set=supported_calendar_component_set) def calendar(self, name=None, cal_id=None): """ The calendar method will return a calendar object. It will not initiate any communication with the server. """ return self.calendar_home_set.calendar(name, cal_id) @property def calendar_home_set(self): if not self._calendar_home_set: chs = self.get_properties([cdav.CalendarHomeSet()]) self.calendar_home_set = chs['{urn:ietf:params:xml:ns:caldav}calendar-home-set'] return self._calendar_home_set @calendar_home_set.setter def calendar_home_set(self, url): if isinstance(url, CalendarSet): self._calendar_home_set = url return sanitized_url = URL.objectify(url) if sanitized_url.hostname and sanitized_url.hostname != self.client.url.hostname: ## icloud (and others?) having a load balanced system, where each principal resides on one named host self.client.url = sanitized_url self._calendar_home_set = CalendarSet(self.client, self.client.url.join(sanitized_url)) def calendars(self): """ Return the principials calendars """ return self.calendar_home_set.calendars() class Calendar(DAVObject): """ The `Calendar` object is used to represent a calendar collection. Refer to the RFC for details: http://www.ietf.org/rfc/rfc4791.txt """ def _create(self, name, id=None, supported_calendar_component_set=None): """ Create a new calendar with display name `name` in `parent`. """ if id is None: id = str(uuid.uuid1()) self.id = id path = self.parent.url.join(id) self.url = path ## TODO: mkcalendar seems to ignore the body on most servers? ## at least the name doesn't get set this way. ## zimbra gives 500 (!) if body is omitted ... cal = cdav.CalendarCollection() coll = dav.Collection() + cal type = dav.ResourceType() + coll prop = dav.Prop() + [type,] if name: display_name = dav.DisplayName(name) prop += [display_name,] if supported_calendar_component_set: sccs = cdav.SupportedCalendarComponentSet() for scc in supported_calendar_component_set: sccs += cdav.Comp(scc) prop += sccs set = dav.Set() + prop mkcol = cdav.Mkcalendar() + set r = self._query(root=mkcol, query_method='mkcalendar', url=path, expected_return_value=201) if name: try: self.set_properties([display_name]) except: self.delete() raise ## Special hack for Zimbra! The calendar we've made exists at ## the specified URL, and we can do operations like ls, even ## PUT an event to the calendar. Zimbra will enforce that the ## event uuid matches the event url, and return either 201 or ## 302 - but alas, try to do a GET towards the event and we ## get 404! But turn around and replace the calendar ID with ## the calendar name in the URL and hey ... it works! ## TODO: write test cases for calendars with non-trivial ## names and calendars with names already matching existing ## calendar urls and ensure they pass. zimbra_url = self.parent.url.join(name) try: ret = self.client.request(zimbra_url) if ret.status == 404: raise error.NotFoundError ## insane server self.url = zimbra_url except error.NotFoundError: ## sane server pass def add_event(self, ical): """ Add a new event to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Event(self.client, data = ical, parent = self).save() def add_todo(self, ical): """ Add a new task to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Todo(self.client, data=ical, parent=self).save() def add_journal(self, ical): """ Add a new journal entry to the calendar, with the given ical. Parameters: * ical - ical object (text) """ return Journal(self.client, data=ical, parent=self).save() def save(self): """ The save method for a calendar is only used to create it, for now. We know we have to create it when we don't have a url. Returns: * self """ if self.url is None: self._create(name=self.name, id=self.id, **self.extra_init_options) if not self.url.endswith('/'): self.url = URL.objectify(str(self.url) + '/') return self def date_search(self, start, end=None): """ Search events by date in the calendar. Recurring events are expanded if they are occuring during the specified time frame and if an end timestamp is given. Parameters: * start = datetime.today(). * end = same as above. Returns: * [Event(), ...] """ matches = [] # build the request ## Some servers will raise an error if we send the expand flag ## but don't set any end-date - expand doesn't make much sense ## if we have one recurring event describing an indefinite ## series of events. Hence, if the end date is not set, we ## skip asking for expanded events. if end: data = cdav.CalendarData() + cdav.Expand(start, end) else: data = cdav.CalendarData() prop = dav.Prop() + data range = cdav.TimeRange(start, end) vevent = cdav.CompFilter("VEVENT") + range vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') results = self._handle_prop_response(response=response, props=[cdav.CalendarData()]) for r in results: matches.append( Event(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return matches def freebusy_request(self, start, end): """ Search the calendar, but return only the free/busy information. Parameters: * start = datetime.today(). * end = same as above. Returns: * [FreeBusy(), ...] """ root = cdav.FreeBusyQuery() + [ cdav.TimeRange(start, end) ] response = self._query(root, 1, 'report') return FreeBusy(self, response.raw) def journals(self): """ fetches a list of journal entries. """ def todos(self, sort_key='due', include_completed=False): """ fetches a list of todo events. Parameters: * sort_key: use this field in the VTODO for sorting (lower case string, i.e. 'priority'). * include_completed: boolean - by default, only pending tasks are listed """ ## ref https://www.ietf.org/rfc/rfc4791.txt, section 7.8.9 matches = [] # build the request data = cdav.CalendarData() prop = dav.Prop() + data if not include_completed: vnotcompleted = cdav.TextMatch('COMPLETED', negate=True) vnotcancelled = cdav.TextMatch('CANCELLED', negate=True) vstatus = cdav.PropFilter('STATUS') + vnotcancelled + vnotcompleted vnocompletedate = cdav.PropFilter('COMPLETED') + cdav.NotDefined() vtodo = cdav.CompFilter("VTODO") + vnocompletedate + vstatus else: vtodo = cdav.CompFilter("VTODO") vcalendar = cdav.CompFilter("VCALENDAR") + vtodo filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') results = self._handle_prop_response(response=response, props=[cdav.CalendarData()]) for r in results: matches.append( Todo(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) def sort_key_func(x): val = getattr(x.instance.vtodo, sort_key, None) if not val: return None val = val.value if hasattr(val, 'strftime'): return val.strftime('%F%H%M%S') return val if sort_key: matches.sort(key=sort_key_func) return matches def event_by_url(self, href, data=None): """ Returns the event with the given URL """ return Event(url=href, data=data, parent=self).load() def event_by_uid(self, uid): """ Get one event from the calendar. Parameters: * uid: the event uid Returns: * Event() or None """ data = cdav.CalendarData() prop = dav.Prop() + data match = cdav.TextMatch(uid) propf = cdav.PropFilter("UID") + match vevent = cdav.CompFilter("VEVENT") + propf vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, 'report') if response.status == 404: raise error.NotFoundError(response.raw) elif response.status == 400: raise error.ReportError(response.raw) r = response.tree.find(".//" + dav.Response.tag) if r is not None: href = r.find(".//" + dav.Href.tag).text data = r.find(".//" + cdav.CalendarData.tag).text return Event(self.client, url=URL.objectify(href), data=data, parent=self) else: raise error.NotFoundError(response.raw) ## alias for backward compatibility event = event_by_uid def events(self): """ List all events from the calendar. Returns: * [Event(), ...] """ all = [] data = cdav.CalendarData() prop = dav.Prop() + data vevent = cdav.CompFilter("VEVENT") vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, query_method='report') results = self._handle_prop_response(response, props=[cdav.CalendarData()]) for r in results: all.append(Event(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return all def journals(self): """ List all journals from the calendar. Returns: * [Journal(), ...] """ ## TODO: this is basically a copy of events() - can we do more ## refactoring and consolidation here? Maybe it's wrong to do ## separate methods for journals, todos and events? all = [] data = cdav.CalendarData() prop = dav.Prop() + data vevent = cdav.CompFilter("VJOURNAL") vcalendar = cdav.CompFilter("VCALENDAR") + vevent filter = cdav.Filter() + vcalendar root = cdav.CalendarQuery() + [prop, filter] response = self._query(root, 1, query_method='report') results = self._handle_prop_response(response, props=[cdav.CalendarData()]) for r in results: all.append(Journal(self.client, url=self.url.join(r), data=results[r][cdav.CalendarData.tag], parent=self)) return all class CalendarObjectResource(DAVObject): """ Ref RFC 4791, section 4.1, a "Calendar Object Resource" can be an event, a todo-item, a journal entry, a free/busy entry, etc. """ _instance = None _data = None def __init__(self, client=None, url=None, data=None, parent=None, id=None): """ CalendarObjectResource has an additional parameter for its constructor: * data = "...", vCal data for the event """ DAVObject.__init__(self, client=client, url=url, parent=parent, id=id) if data is not None: self.data = data def load(self): """ Load the object from the caldav server. """ r = self.client.request(self.url) if r.status == 404: raise error.NotFoundError(r.raw) self.data = vcal.fix(r.raw) return self def _create(self, data, id=None, path=None): if id is None and path is not None and str(path).endswith('.ics'): id = re.search('(/|^)([^/]*).ics',str(path)).group(2) elif id is None: for obj in ('vevent', 'vtodo', 'vjournal', 'vfreebusy'): if hasattr(self.instance, obj): id = getattr(self.instance, obj).uid.value break if path is None: path = id + ".ics" path = self.parent.url.join(path) r = self.client.put(path, data, {"Content-Type": 'text/calendar; charset="utf-8"'}) if r.status == 302: path = [x[1] for x in r.headers if x[0]=='location'][0] elif not (r.status in (204, 201)): raise error.PutError(r.raw) self.url = URL.objectify(path) self.id = id def save(self): """ Save the object, can be used for creation and update. Returns: * self """ if self._instance is not None: path = self.url.path if self.url else None self._create(self._instance.serialize(), self.id, path) return self def __str__(self): return "%s: %s" % (self.__class__.__name__, self.url) def _set_data(self, data): self._data = vcal.fix(data) self._instance = vobject.readOne(io.StringIO(to_unicode(self._data))) return self def _get_data(self): return self._data data = property(_get_data, _set_data, doc="vCal representation of the object") def _set_instance(self, inst): self._instance = inst self._data = inst.serialize() return self def _get_instance(self): return self._instance instance = property(_get_instance, _set_instance, doc="vobject instance of the object") class Event(CalendarObjectResource): """ The `Event` object is used to represent an event (VEVENT). """ pass class Journal(CalendarObjectResource): """ The `Journal` object is used to represent a journal entry (VJOURNAL). """ pass class FreeBusy(CalendarObjectResource): """ The `FreeBusy` object is used to represent a freebusy response from the server. """ def __init__(self, parent, data): """ A freebusy response object has no URL or ID (TODO: reconsider the class hierarchy? most of the inheritated methods are moot and will fail?). Raw response can be accessed through self.data, instantiated vobject as self.instance. """ CalendarObjectResource.__init__(self, client=parent.client, url=None, data=data, parent=parent, id=None) class Todo(CalendarObjectResource): """ The `Todo` object is used to represent a todo item (VTODO). """ def complete(self, completion_timestamp=None): """ Marks the task as completed. Parameters: * completion_timestamp - datetime object. Defaults to datetime.datetime.now(). """ if not completion_timestamp: completion_timestamp = datetime.datetime.now() self.instance.vtodo.status.value = 'COMPLETED' self.instance.vtodo.add('completed').value = completion_timestamp self.save() caldav-0.4.0/caldav.egg-info/0000755000076600000240000000000012516226324016142 5ustar cyrilstaff00000000000000caldav-0.4.0/caldav.egg-info/dependency_links.txt0000644000076600000240000000000112516226324022210 0ustar cyrilstaff00000000000000 caldav-0.4.0/caldav.egg-info/not-zip-safe0000644000076600000240000000000112306107451020364 0ustar cyrilstaff00000000000000 caldav-0.4.0/caldav.egg-info/PKG-INFO0000644000076600000240000000124612516226324017242 0ustar cyrilstaff00000000000000Metadata-Version: 1.1 Name: caldav Version: 0.4.0 Summary: CalDAV (RFC4791) client library Home-page: http://bitbucket.org/cyrilrbt/caldav Author: Cyril Robert Author-email: cyril@hippie.io License: GPL Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Office/Business :: Scheduling Classifier: Topic :: Software Development :: Libraries :: Python Modules caldav-0.4.0/caldav.egg-info/requires.txt0000644000076600000240000000005012516226324020535 0ustar cyrilstaff00000000000000vobject lxml nose coverage requests six caldav-0.4.0/caldav.egg-info/SOURCES.txt0000644000076600000240000000115212516226324020025 0ustar cyrilstaff00000000000000COPYING.APACHE COPYING.GPL MANIFEST.in setup.cfg setup.py caldav/__init__.py caldav/davclient.py caldav/objects.py caldav.egg-info/PKG-INFO caldav.egg-info/SOURCES.txt caldav.egg-info/dependency_links.txt caldav.egg-info/not-zip-safe caldav.egg-info/requires.txt caldav.egg-info/top_level.txt caldav/elements/__init__.py caldav/elements/base.py caldav/elements/cdav.py caldav/elements/dav.py caldav/lib/__init__.py caldav/lib/error.py caldav/lib/namespace.py caldav/lib/python_utilities.py caldav/lib/url.py caldav/lib/vcal.py tests/__init__.py tests/_test_absolute.py tests/conf.py tests/proxy.py tests/test_caldav.pycaldav-0.4.0/caldav.egg-info/top_level.txt0000644000076600000240000000001512516226324020670 0ustar cyrilstaff00000000000000caldav tests caldav-0.4.0/COPYING.APACHE0000644000076600000240000002613612306107420015171 0ustar cyrilstaff00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. caldav-0.4.0/COPYING.GPL0000644000076600000240000010451312306107420014666 0ustar cyrilstaff00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program 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 program 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 this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . caldav-0.4.0/MANIFEST.in0000644000076600000240000000002212306107420014736 0ustar cyrilstaff00000000000000include COPYING.* caldav-0.4.0/PKG-INFO0000644000076600000240000000124612516226324014316 0ustar cyrilstaff00000000000000Metadata-Version: 1.1 Name: caldav Version: 0.4.0 Summary: CalDAV (RFC4791) client library Home-page: http://bitbucket.org/cyrilrbt/caldav Author: Cyril Robert Author-email: cyril@hippie.io License: GPL Description: UNKNOWN Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: License :: OSI Approved :: Apache Software License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Topic :: Office/Business :: Scheduling Classifier: Topic :: Software Development :: Libraries :: Python Modules caldav-0.4.0/setup.cfg0000644000076600000240000000032312516226324015035 0ustar cyrilstaff00000000000000[nosetests] detailed-errors = 1 with-coverage = 1 cover-package = caldav [build_sphinx] source-dir = docs/source build-dir = docs/build all_files = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 caldav-0.4.0/setup.py0000755000076600000240000000223212516226026014731 0ustar cyrilstaff00000000000000# -*- encoding: utf-8 -*- from setuptools import setup, find_packages version = '0.4.0' if __name__ == '__main__': setup( name='caldav', version=version, description="CalDAV (RFC4791) client library", classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General " "Public License (GPL)", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Office/Business :: Scheduling", "Topic :: Software Development :: Libraries " ":: Python Modules"], keywords='', author='Cyril Robert', author_email='cyril@hippie.io', url='http://bitbucket.org/cyrilrbt/caldav', license='GPL', packages=find_packages(exclude="tests"), include_package_data=True, zip_safe=False, install_requires=['vobject', 'lxml', 'nose', 'coverage', 'requests', 'six'], ) caldav-0.4.0/tests/0000755000076600000240000000000012516226324014360 5ustar cyrilstaff00000000000000caldav-0.4.0/tests/__init__.py0000644000076600000240000000000012306107420016447 0ustar cyrilstaff00000000000000caldav-0.4.0/tests/_test_absolute.py0000644000076600000240000000241212306107420017735 0ustar cyrilstaff00000000000000# encoding: utf-8 import datetime import caldav class TestRadicale(object): SUMMARIES = set(('Godspeed You! Black Emperor at ' 'Cirque Royal / Koninklijk Circus', 'Standard - GBA')) DTSTART = set((datetime.datetime(2011, 3, 4, 20, 0), datetime.datetime(2011, 1, 15, 20, 0))) def setup(self): URL = 'http://localhost:8080/nicoe/perso/' self.client = caldav.DAVClient(URL) self.calendar = caldav.objects.Calendar(self.client, URL) def test_eventslist(self): events = self.calendar.events() assert len(events) == 2 summaries, dtstart = set(), set() for event in events: event.load() vobj = event.instance summaries.add(vobj.vevent.summary.value) dtstart.add(vobj.vevent.dtstart.value) assert summaries == self.SUMMARIES assert dtstart == self.DTSTART class TestTryton(object): def setup(self): URL = 'http://admin:admin@localhost:9080/caldav/Calendars/Test' self.client = caldav.DAVClient(URL) self.calendar = caldav.objects.Calendar(self.client, URL) def test_eventslist(self): events = self.calendar.events() assert len(events) == 1 caldav-0.4.0/tests/conf.py0000644000076600000240000000210212516226026015651 0ustar cyrilstaff00000000000000 #!/usr/bin/env python # -*- encoding: utf-8 -*- try: from .conf_private import caldav_servers except ImportError: caldav_servers = [] # caldav_servers.append({"url": "http://sogo1:sogo1@sogo-demo.inverse.ca:80/SOGo/dav/", "principal_url": "http://sogo-demo.inverse.ca:80/SOGo/dav/sogo1/", "backwards_compatibility_url": "http://sogo1:sogo1@sogo-demo.inverse.ca:80/SOGo/dav/sogo1/Calendar/"}) # caldav_servers.append({"url": "https://sogo1:sogo1@sogo-demo.inverse.ca:443/SOGo/dav/sogo1/Calendar/"}) caldav_servers.append({"url": "http://baikal.tobixen.no:80/cal.php/", "username": "testlogin", "password": "testing123", "principal_url": "http://baikal.tobixen.no:80/cal.php/principals/testlogin/", "backwards_compatibility_url": "http://testlogin:testing123@baikal.tobixen.no:80/cal.php/calendars/testlogin/"}) #caldav_servers.append({"url": "http://veryveryveeeeerylongusernametest:thispasswordismaybenotlongenoughbutmaybemaybemaybeitislongenoughafterallhowlongdoesatoolongpasswordneedtobeiwonder@baikal.tobixen.no/cal.php"}) proxy = "127.0.0.1:8080" proxy_noport = "127.0.0.1" caldav-0.4.0/tests/proxy.py0000644000076600000240000002644312506772024016126 0ustar cyrilstaff00000000000000#!/usr/bin/python from caldav.lib.python_utilities import to_wire, to_local __doc__ = """Tiny HTTP Proxy. This module implements GET, HEAD, POST, PUT and DELETE methods on BaseHTTPServer, and behaves as an HTTP proxy. The CONNECT method is also implemented experimentally, but has not been tested yet. Any help will be greatly appreciated. SUZUKI Hisao 2009/11/23 - Modified by Mitko Haralanov * Added very simple FTP file retrieval * Added custom logging methods * Added code to make this a standalone application """ __version__ = "0.3.1" from caldav.lib.python_utilities import isPython3 if isPython3(): from urllib import parse from urllib.parse import urlparse, urlunparse from http.server import BaseHTTPRequestHandler, HTTPServer from socketserver import ThreadingMixIn else: from urlparse import urlparse as parse from urlparse import urlparse, urlunparse from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer from SocketServer import ThreadingMixIn import select import socket import logging import logging.handlers import getopt import sys import os import signal import threading from types import FrameType, CodeType from time import sleep import ftplib DEFAULT_LOG_FILENAME = "proxy.log" class ProxyHandler (BaseHTTPRequestHandler): __base = BaseHTTPRequestHandler __base_handle = __base.handle server_version = "TinyHTTPProxy/" + __version__ rbufsize = 0 # self.rfile Be unbuffered def handle(self): (ip, port) = self.client_address self.server.logger.log (logging.INFO, "Request from '%s'", ip) if hasattr(self, 'allowed_clients') and ip not in self.allowed_clients: self.raw_requestline = self.rfile.readline() if self.parse_request(): self.send_error(403) else: self.__base_handle() def _connect_to(self, netloc, soc): i = netloc.find(':') if i >= 0: host_port = netloc[:i], int(netloc[i+1:]) else: host_port = netloc, 80 self.server.logger.log (logging.INFO, "connect to %s:%d", host_port[0], host_port[1]) try: soc.connect(host_port) except socket.error as arg: try: msg = arg[1] except: msg = arg self.send_error(404, msg) return 0 return 1 def do_CONNECT(self): soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if self._connect_to(self.path, soc): self.log_request(200) self.wfile.write(self.protocol_version + " 200 Connection established\r\n") self.wfile.write("Proxy-agent: %s\r\n" % self.version_string()) self.wfile.write("\r\n") self._read_write(soc, 300) finally: soc.close() self.connection.close() def do_GET(self): (scm, netloc, path, params, query, fragment) = urlparse( self.path, 'http') if scm not in ('http', 'ftp') or fragment or not netloc: self.send_error(400, "bad url %s" % self.path) return soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if scm == 'http': if self._connect_to(netloc, soc): self.log_request() soc.send(to_wire("%s %s %s\r\n" % (self.command, urlunparse(('', '', path, params, query, '')), self.request_version))) self.headers['Connection'] = 'close' del self.headers['Proxy-Connection'] for key_val in list(self.headers.items()): soc.send(to_wire("%s: %s\r\n" % key_val)) soc.send(to_wire("\r\n")) self._read_write(soc) elif scm == 'ftp': # fish out user and password information i = netloc.find ('@') if i >= 0: login_info, netloc = netloc[:i], netloc[i+1:] try: user, passwd = login_info.split (':', 1) except ValueError: user, passwd = "anonymous", None else: user, passwd ="anonymous", None self.log_request () try: ftp = ftplib.FTP (netloc) ftp.login (user, passwd) if self.command == "GET": ftp.retrbinary ("RETR %s"%path, self.connection.send) ftp.quit () except Exception as e: self.server.logger.log (logging.WARNING, "FTP Exception: %s", e) finally: soc.close() self.connection.close() def _read_write(self, soc, max_idling=20, local=False): iw = [self.connection, soc] local_data = "" ow = [] count = 0 while 1: count += 1 (ins, _, exs) = select.select(iw, ow, iw, 1) if exs: break if ins: for i in ins: if i is soc: out = self.connection else: out = soc data = i.recv(8192) if data: if local: local_data += data else: out.send(data) count = 0 if count == max_idling: break if local: return to_local(local_data) return None do_HEAD = do_GET do_POST = do_GET do_PUT = do_GET do_DELETE = do_GET do_PROPFIND = do_GET def log_message (self, format, *args): self.server.logger.log (logging.INFO, "%s %s", self.address_string (), format % args) def log_error (self, format, *args): self.server.logger.log (logging.ERROR, "%s %s", self.address_string (), format % args) class ThreadingHTTPServer (ThreadingMixIn, HTTPServer): def __init__ (self, server_address, RequestHandlerClass, logger=None): HTTPServer.__init__ (self, server_address, RequestHandlerClass) self.logger = logger class NonThreadingHTTPServer (HTTPServer): def __init__ (self, server_address, RequestHandlerClass, logger=None): HTTPServer.__init__ (self, server_address, RequestHandlerClass) self.logger = logger def logSetup (filename, log_size, daemon): logger = logging.getLogger ("TinyHTTPProxy") logger.setLevel (logging.INFO) if not filename: if not daemon: # display to the screen handler = logging.StreamHandler () else: handler = logging.handlers.RotatingFileHandler (DEFAULT_LOG_FILENAME, maxBytes=(log_size*(1<<20)), backupCount=5) else: handler = logging.handlers.RotatingFileHandler (filename, maxBytes=(log_size*(1<<20)), backupCount=5) fmt = logging.Formatter ("[%(asctime)-12s.%(msecs)03d] " "%(levelname)-8s {%(name)s %(threadName)s}" " %(message)s", "%Y-%m-%d %H:%M:%S") handler.setFormatter (fmt) logger.addHandler (handler) return logger def usage (msg=None): if msg: print(msg) print(sys.argv[0], "[-p port] [-l logfile] [-dh] [allowed_client_name ...]]") print() print(" -p - Port to bind to") print(" -l - Path to logfile. If not specified, STDOUT is used") print(" -d - Run in the background") print() def handler (signo, frame): while frame and isinstance (frame, FrameType): if frame.f_code and isinstance (frame.f_code, CodeType): if "run_event" in frame.f_code.co_varnames: frame.f_locals["run_event"].set () return frame = frame.f_back def daemonize (logger): class DevNull (object): def __init__ (self): self.fd = os.open ("/dev/null", os.O_WRONLY) def write (self, *args, **kwargs): return 0 def read (self, *args, **kwargs): return 0 def fileno (self): return self.fd def close (self): os.close (self.fd) class ErrorLog: def __init__ (self, obj): self.obj = obj def write (self, string): self.obj.log (logging.ERROR, string) def read (self, *args, **kwargs): return 0 def close (self): pass if os.fork () != 0: ## allow the child pid to instanciate the server ## class sleep (1) sys.exit (0) os.setsid () fd = os.open ('/dev/null', os.O_RDONLY) if fd != 0: os.dup2 (fd, 0) os.close (fd) null = DevNull () log = ErrorLog (logger) sys.stdout = null sys.stderr = log sys.stdin = null fd = os.open ('/dev/null', os.O_WRONLY) #if fd != 1: os.dup2 (fd, 1) os.dup2 (sys.stdout.fileno (), 1) if fd != 2: os.dup2 (fd, 2) if fd not in (1, 2): os.close (fd) def main (): logfile = None daemon = False max_log_size = 20 port = 8080 allowed = [] run_event = threading.Event () local_hostname = socket.gethostname () try: opts, args = getopt.getopt (sys.argv[1:], "l:dhp:", []) except getopt.GetoptError as e: usage (str (e)) return 1 for opt, value in opts: if opt == "-p": port = int (value) if opt == "-l": logfile = value if opt == "-d": daemon = not daemon if opt == "-h": usage () return 0 # setup the log file logger = logSetup (logfile, max_log_size, daemon) if daemon: daemonize (logger) signal.signal (signal.SIGINT, handler) if args: allowed = [] for name in args: client = socket.gethostbyname(name) allowed.append(client) logger.log (logging.INFO, "Accept: %s (%s)" % (client, name)) ProxyHandler.allowed_clients = allowed else: logger.log (logging.INFO, "Any clients will be served...") server_address = (socket.gethostbyname (local_hostname), port) ProxyHandler.protocol = "HTTP/1.0" httpd = ThreadingHTTPServer (server_address, ProxyHandler, logger) sa = httpd.socket.getsockname () print("Servering HTTP on", sa[0], "port", sa[1]) req_count = 0 while not run_event.isSet (): try: httpd.handle_request () req_count += 1 if req_count == 1000: logger.log (logging.INFO, "Number of active threads: %s", threading.activeCount ()) req_count = 0 except select.error as e: if e[0] == 4 and run_event.isSet (): pass else: logger.log (logging.CRITICAL, "Errno: %d - %s", e[0], e[1]) logger.log (logging.INFO, "Server shutdown") return 0 if __name__ == '__main__': sys.exit (main ()) caldav-0.4.0/tests/test_caldav.py0000644000076600000240000007237612516226026017241 0ustar cyrilstaff00000000000000#!/usr/bin/env python # -*- encoding: utf-8 -*- from datetime import datetime from caldav.lib.python_utilities import isPython3 if isPython3(): from urllib import parse from urllib.parse import urlparse else: from urlparse import urlparse as parse from urlparse import urlparse import logging import threading import time from nose.tools import assert_equal, assert_not_equal, assert_raises from .conf import caldav_servers, proxy, proxy_noport from .proxy import ProxyHandler, NonThreadingHTTPServer from caldav.davclient import DAVClient from caldav.objects import Principal, Calendar, Event, DAVObject, CalendarSet, FreeBusy from caldav.lib.url import URL from caldav.lib import url from caldav.lib import error from caldav.lib.namespace import ns from caldav.elements import dav, cdav from caldav.lib.python_utilities import to_local, to_str log = logging.getLogger("caldav") class NullHandler(logging.Handler): def emit(self, record): logging.debug(record) log.addHandler(NullHandler()) ev1 = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VEVENT UID:20010712T182145Z-123401@example.com DTSTAMP:20060712T182145Z DTSTART:20060714T170000Z DTEND:20060715T040000Z SUMMARY:Bastille Day Party END:VEVENT END:VCALENDAR """ ev2 = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VEVENT UID:20010712T182145Z-123401@example.com DTSTAMP:20070712T182145Z DTSTART:20070714T170000Z DTEND:20070715T040000Z SUMMARY:Bastille Day Party +1year END:VEVENT END:VCALENDAR """ ## example from http://www.rfc-editor.org/rfc/rfc5545.txt evr = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VEVENT UID:19970901T130000Z-123403@example.com DTSTAMP:19970901T130000Z DTSTART;VALUE=DATE:19971102 SUMMARY:Our Blissful Anniversary TRANSP:TRANSPARENT CLASS:CONFIDENTIAL CATEGORIES:ANNIVERSARY,PERSONAL,SPECIAL OCCASION RRULE:FREQ=YEARLY END:VEVENT END:VCALENDAR""" ## example from http://www.rfc-editor.org/rfc/rfc5545.txt todo = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VTODO UID:20070313T123432Z-456553@example.com DTSTAMP:20070313T123432Z DUE;VALUE=DATE:20070501 SUMMARY:Submit Quebec Income Tax Return for 2006 CLASS:CONFIDENTIAL CATEGORIES:FAMILY,FINANCE STATUS:NEEDS-ACTION END:VTODO END:VCALENDAR""" ## example from RFC2445, 4.6.2 todo2 = """BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VTODO UID:19970901T130000Z-123404@host.com DTSTAMP:19970901T130000Z DTSTART:19970415T133000Z DUE:19970416T045959Z SUMMARY:1996 Income Tax Preparation CLASS:CONFIDENTIAL CATEGORIES:FAMILY,FINANCE PRIORITY:2 STATUS:NEEDS-ACTION END:VTODO END:VCALENDAR""" todo3 = """ BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VTODO UID:19970901T130000Z-123405@host.com DTSTAMP:19970901T130000Z DTSTART:19970415T133000Z DUE:19970516T045959Z SUMMARY:1996 Income Tax Preparation CLASS:CONFIDENTIAL CATEGORIES:FAMILY,FINANCE PRIORITY:1 STATUS:NEEDS-ACTION END:VTODO END:VCALENDAR""" ## example from http://www.kanzaki.com/docs/ical/vjournal.html journal1 = """ BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VJOURNAL UID:19970901T130000Z-123405@host.com DTSTAMP:19970901T1300Z DTSTART;VALUE=DATE:19970317 SUMMARY:Staff meeting minutes DESCRIPTION:1. Staff meeting: Participants include Joe\, Lisa and Bob. Aurora project plans were reviewed. There is currently no budget reserves for this project. Lisa will escalate to management. Next meeting on Tuesday.\n 2. Telephone Conference: ABC Corp. sales representative called to discuss new printer. Promised to get us a demo by Friday.\n 3. Henry Miller (Handsoff Insurance): Car was totaled by tree. Is looking into a loaner car. 654-2323 (tel). END:VJOURNAL END:VCALENDAR """ journal2 = """ BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VJOURNAL UID:19970901T130000Z-123405@host.com DTSTAMP:19970901T130000Z DTSTART;VALUE=DATE:19970317 SUMMARY:Staff meeting minutes DESCRIPTION:1. Staff meeting: Participants include Joe\, Lisa and Bob. Aurora project plans were reviewed. There is currently no budget reserves for this project. Lisa will escalate to management. Next meeting on Tuesday.\n 2. Telephone Conference: ABC Corp. sales representative called to discuss new printer. Promised to get us a demo by Friday.\n 3. Henry Miller (Handsoff Insurance): Car was totaled by tree. Is looking into a loaner car. 654-2323 (tel). END:VJOURNAL END:VCALENDAR """ testcal_id = "pythoncaldav-test" testcal_id2 = "pythoncaldav-test2" class RepeatedFunctionalTestsBaseClass(object): """ This is a class with functional tests (tests that goes through basic functionality and actively communicates with third parties) that we want to repeat for all configured caldav_servers. (what a truely ugly name for this class - any better ideas?) NOTE: this tests relies heavily on the assumption that we can create calendars on the remote caldav server, but the RFC says ... Support for MKCALENDAR on the server is only RECOMMENDED and not REQUIRED because some calendar stores only support one calendar per user (or principal), and those are typically pre-created for each account. However, iCloud is the only server where I have been denied creating a calendar. Creating a calendar through the WebUI works, and creating an event through the library fails, so I don't think the problem is lack of MKCALENDAR support. """ def setup(self): logging.debug("############## test setup") self.conn_params = self.server_params.copy() for x in list(self.conn_params.keys()): if not x in ('url', 'proxy', 'username', 'password', 'ssl_verify_cert'): self.conn_params.pop(x) self.caldav = DAVClient(**self.conn_params) self.principal = self.caldav.principal() ## tear down old test calendars, in case teardown wasn't properly ## executed last time tests were run self._teardown() logging.debug("############## test setup done") def teardown(self): logging.debug("############## test teardown") self._teardown() logging.debug("############## test teardown done") def _teardown(self): for combos in (('Yep', testcal_id), ('Yep', testcal_id2), ('Yølp', testcal_id), ('Yep', 'Yep'), ('Yølp', 'Yølp')): try: cal = self.principal.calendar(name="Yep", cal_id=testcal_id) cal.delete() except: pass def testPropfind(self): """ Test of the propfind methods. (This is sort of redundant, since this is implicitly run by the setup) """ ## first a raw xml propfind to the root URL foo = self.caldav.propfind(self.principal.url, props=""" """) assert('resourcetype' in to_local(foo.raw)) ## next, the internal _query_properties, returning an xml tree ... foo2 = self.principal._query_properties([dav.Status(),]) assert('resourcetype' in to_local(foo.raw)) ## TODO: more advanced asserts def testGetCalendarHomeSet(self): chs = self.principal.get_properties([cdav.CalendarHomeSet()]) assert '{urn:ietf:params:xml:ns:caldav}calendar-home-set' in chs def testGetCalendars(self): assert_not_equal(len(self.principal.calendars()), 0) def testProxy(self): if self.caldav.url.scheme == 'https': logging.info("Skipping %s.testProxy as the TinyHTTPProxy implementation doesn't support https") return server_address = ('127.0.0.1', 8080) proxy_httpd = NonThreadingHTTPServer (server_address, ProxyHandler, logging.getLogger ("TinyHTTPProxy")) threadobj = threading.Thread(target=proxy_httpd.serve_forever) try: threadobj.start() assert(threadobj.is_alive()) conn_params = self.conn_params.copy() conn_params['proxy'] = proxy c = DAVClient(**conn_params) p = c.principal() assert_not_equal(len(p.calendars()), 0) finally: proxy_httpd.shutdown() ## this should not be necessary, but I've observed some failures if threadobj.is_alive(): time.sleep(0.05) assert(not threadobj.is_alive()) threadobj = threading.Thread(target=proxy_httpd.serve_forever) try: threadobj.start() assert(threadobj.is_alive()) conn_params = self.conn_params.copy() conn_params['proxy'] = proxy_noport c = DAVClient(**conn_params) p = c.principal() assert_not_equal(len(p.calendars()), 0) assert(threadobj.is_alive()) finally: proxy_httpd.shutdown() ## this should not be necessary if threadobj.is_alive(): time.sleep(0.05) assert(not threadobj.is_alive()) def testPrincipal(self): collections = self.principal.calendars() if 'principal_url' in self.server_params: assert_equal(self.principal.url, self.server_params['principal_url']) for c in collections: assert_equal(c.__class__.__name__, "Calendar") def testCreateDeleteCalendar(self): c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) assert_not_equal(c.url, None) events = c.events() assert_equal(len(events), 0) events = self.principal.calendar(name="Yep", cal_id=testcal_id).events() ## huh ... we're quite constantly getting out a list with one item, the URL for ## the caldav server. This needs to be investigated, it is surely a bug in our ## code. Anyway, better to ignore it now than to have broken test code. assert_equal(len(events), 0) c.delete() ## verify that calendar does not exist - this breaks with zimbra :-( ## COMPATIBILITY PROBLEM - todo, look more into it if 'zimbra' not in str(c.url): assert_raises(error.NotFoundError, self.principal.calendar(name="Yep", cal_id=testcal_id).events) def testCreateCalendarAndEvent(self): c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) ## add event e1 = c.add_event(ev1) ## c.events() should give a full list of events events = c.events() assert_equal(len(events), 1) ## We should be able to access the calender through the URL c2 = Calendar(client=self.caldav, url=c.url) events2 = c.events() assert_equal(len(events2), 1) assert_equal(events2[0].url, events[0].url) def testCreateJournalListAndJournalEntry(self): """ This test demonstrates the support for journals. * It will create a journal list * It will add some journal entries to it * It will list out all journal entries """ if '/remote.php/caldav' in str(self.caldav.url) or self.caldav.url.path.startswith('/dav/'): ## COMPATIBILITY TODO: read the RFC. sabredav/owncloud: ## got the error: "This calendar only supports VEVENT, ## VTODO. We found a VJOURNAL". Should probably learn ## that some other way. (why doesn't make_calendar break? ## what does the RFC say on that?) Same with zimbra, ## though different error. return c = self.principal.make_calendar(name="Yep", cal_id=testcal_id, supported_calendar_component_set=['VJOURNAL']) #j1 = c.add_journal(journal1) ## vobjects breaks here j1 = c.add_journal(journal2) journals = c.journals() assert_equal(len(journals), 1) todos = c.todos() events = c.events() assert_equal(todos + events, []) def testCreateTaskListAndTodo(self): """ This test demonstrates the support for task lists. * It will create a "task list" * It will add some tasks to it * It will list out all pending tasks, sorted by due date * It will list out all pending tasks, sorted by priority * It will complete a task * It will delete a task """ ## For all servers I've tested against except Zimbra, it's ## possible to create a calendar and add todo-items to it. ## Zimbra has separate calendars and task lists, and it's not ## allowed to put TODO-tasks into the calendar. We need to ## tell Zimbra that the new "calendar" is a task list. This ## is done though the supported_calendar_compontent_set ## property - hence the extra parameter here: c = self.principal.make_calendar(name="Yep", cal_id=testcal_id, supported_calendar_component_set=['VTODO']) ## add todo-item t1 = c.add_todo(todo) ## c.todos() should give a full list of todo items todos = c.todos() assert_equal(len(todos), 1) ## c.events() should NOT return todo-items events = c.events() assert_equal(len(events), 0) t2 = c.add_todo(todo2) t3 = c.add_todo(todo3) todos = c.todos() assert_equal(len(todos), 3) uids = lambda lst: [x.instance.vtodo.uid for x in lst] assert_equal(uids(todos), uids([t2, t3, t1])) todos = c.todos(sort_key='priority') pri = lambda lst: [x.instance.vtodo.priority.value for x in lst if hasattr(x.instance.vtodo, 'priority')] assert_equal(pri(todos), pri([t3, t2])) t3.complete() todos = c.todos() assert_equal(len(todos), 2) todos = c.todos(include_completed=True) assert_equal(len(todos), 3) t2.delete() todos = c.todos(include_completed=True) assert_equal(len(todos), 2) def testUtf8Event(self): c = self.principal.make_calendar(name="Yølp", cal_id=testcal_id) ## add event e1 = c.add_event(ev1.replace("Bastille Day Party", "Bringebærsyltetøyfestival")) events = c.events() todos = c.todos() assert_equal(len(todos), 0) ## COMPATIBILITY PROBLEM - todo, look more into it if not 'zimbra' in str(c.url): assert_equal(len(events), 1) def testUnicodeEvent(self): c = self.principal.make_calendar(name="Yølp", cal_id=testcal_id) ## add event e1 = c.add_event(to_str(ev1.replace("Bastille Day Party", "Bringebærsyltetøyfestival"))) ## c.events() should give a full list of events events = c.events() ## COMPATIBILITY PROBLEM - todo, look more into it if not 'zimbra' in str(c.url): assert_equal(len(events), 1) def testSetCalendarProperties(self): c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) assert_not_equal(c.url, None) props = c.get_properties([dav.DisplayName(),]) assert_equal("Yep", props[dav.DisplayName.tag]) ## Creating a new calendar with different ID but with existing name - fails on zimbra only. ## This is OK to fail. if 'zimbra' in str(c.url): assert_raises(Exception, self.principal.make_calendar, "Yep", testcal_id2) c.set_properties([dav.DisplayName("hooray"),]) props = c.get_properties([dav.DisplayName(),]) assert_equal(props[dav.DisplayName.tag], "hooray") ## Creating a new calendar with different ID and old name - should never fail cc = self.principal.make_calendar(name="Yep", cal_id=testcal_id2).save() assert_not_equal(cc.url, None) cc.delete() def testLookupEvent(self): """ Makes sure we can add events and look them up by URL and ID """ ## Create calendar c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) assert_not_equal(c.url, None) ## add event e1 = c.add_event(ev1) assert_not_equal(e1.url, None) ## Verify that we can look it up, both by URL and by ID e2 = c.event_by_url(e1.url) e3 = c.event_by_uid("20010712T182145Z-123401@example.com") assert_equal(e2.instance.vevent.uid, e1.instance.vevent.uid) assert_equal(e3.instance.vevent.uid, e1.instance.vevent.uid) ## Knowing the URL of an event, we should be able to get to it ## without going through a calendar object e4 = Event(client=self.caldav, url=e1.url) e4.load() assert_equal(e4.instance.vevent.uid, e1.instance.vevent.uid) def testDeleteEvent(self): """ Makes sure we can add events and delete them """ ## Create calendar c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) assert_not_equal(c.url, None) ## add event e1 = c.add_event(ev1) assert_not_equal(e1.url, None) ## delete event e1.delete() ## Verify that we can't look it up, both by URL and by ID assert_raises(error.NotFoundError, c.event_by_url, e1.url) assert_raises(error.NotFoundError, c.event_by_uid, "20010712T182145Z-123401@example.com") def testDateSearchAndFreeBusy(self): """ Verifies that date search works with a non-recurring event Also verifies that it's possible to change a date of a non-recurring event """ ## Create calendar, add event ... c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) assert_not_equal(c.url, None) e = c.add_event(ev1) ## .. and search for it. r = c.date_search(datetime(2006,7,13,17,00,00), datetime(2006,7,15,17,00,00)) assert_equal(e.instance.vevent.uid, r[0].instance.vevent.uid) assert_equal(len(r), 1) ## ev2 is same UID, but one year ahead. ## The timestamp should change. e.data = ev2 e.save() r = c.date_search(datetime(2006,7,13,17,00,00), datetime(2006,7,15,17,00,00)) assert_equal(len(r), 0) r = c.date_search(datetime(2007,7,13,17,00,00), datetime(2007,7,15,17,00,00)) assert_equal(len(r), 1) ## date search without closing date should also find it r = c.date_search(datetime(2007,7,13,17,00,00)) assert_equal(len(r), 1) ## Lets try a freebusy request as well ## except for on my own DAViCal, it returns 500 Internal Server Error for me. Should look more into that. TODO. if 'calendar.bekkenstenveien53c.oslo' in str(self.caldav.url): return freebusy = c.freebusy_request(datetime(2007,7,13,17,00,00), datetime(2007,7,15,17,00,00)) ## TODO: assert something more complex on the return object assert(isinstance(freebusy, FreeBusy)) assert(freebusy.instance.vfreebusy) def testRecurringDateSearch(self): """ This is more sanity testing of the server side than testing of the library per se. How will it behave if we serve it a recurring event? """ c = self.principal.make_calendar(name="Yep", cal_id=testcal_id) ## evr is a yearly event starting at 1997-02-11 e = c.add_event(evr) r = c.date_search(datetime(2008,11,1,17,00,00), datetime(2008,11,3,17,00,00)) assert_equal(len(r), 1) assert_equal(r[0].data.count("END:VEVENT"), 1) r = c.date_search(datetime(2008,11,1,17,00,00), datetime(2009,11,3,17,00,00)) assert_equal(len(r), 1) ## So much for standards ... seems like different servers ## behaves differently ## COMPATIBILITY PROBLEMS - look into it if "RRULE" in r[0].data and not "BEGIN:STANDARD" in r[0].data: assert_equal(r[0].data.count("END:VEVENT"), 1) else: assert_equal(r[0].data.count("END:VEVENT"), 2) ## The recurring events should not be expanded when using the ## events() method r = c.events() assert_equal(len(r), 1) def testBackwardCompatibility(self): """ Tobias Brox has done some API changes - but this thing should still be backward compatible. """ if not 'backwards_compatibility_url' in self.server_params: return caldav = DAVClient(self.server_params['backwards_compatibility_url']) principal = Principal(caldav, self.server_params['backwards_compatibility_url']) c = Calendar(caldav, name="Yep", parent = principal, id = testcal_id).save() assert_not_equal(c.url, None) c.set_properties([dav.DisplayName("hooray"),]) props = c.get_properties([dav.DisplayName(),]) assert_equal(props[dav.DisplayName.tag], "hooray") cc = Calendar(caldav, name="Yep", parent = principal).save() assert_not_equal(cc.url, None) cc.delete() e = Event(caldav, data = ev1, parent = c).save() assert_not_equal(e.url, None) ee = Event(caldav, url = url.make(e.url), parent = c) ee.load() assert_equal(e.instance.vevent.uid, ee.instance.vevent.uid) r = c.date_search(datetime(2006,7,13,17,00,00), datetime(2006,7,15,17,00,00)) assert_equal(e.instance.vevent.uid, r[0].instance.vevent.uid) assert_equal(len(r), 1) all = c.events() assert_equal(len(all), 1) e2 = Event(caldav, data = ev2, parent = c).save() assert_not_equal(e.url, None) tmp = c.event("20010712T182145Z-123401@example.com") assert_equal(e2.instance.vevent.uid, tmp.instance.vevent.uid) r = c.date_search(datetime(2007,7,13,17,00,00), datetime(2007,7,15,17,00,00)) assert_equal(len(r), 1) e.data = ev2 e.save() r = c.date_search(datetime(2007,7,13,17,00,00), datetime(2007,7,15,17,00,00)) for e in r: print(e.data) assert_equal(len(r), 1) e.instance = e2.instance e.save() r = c.date_search(datetime(2007,7,13,17,00,00), datetime(2007,7,15,17,00,00)) for e in r: print(e.data) assert_equal(len(r), 1) def testObjects(self): ## TODO: description ... what are we trying to test for here? o = DAVObject(self.caldav) assert_raises(Exception, o.save) # We want to run all tests in the above class through all caldav_servers; # and I don't really want to create a custom nose test loader. The # solution here seems to be to generate one child class for each # caldav_url, and inject it into the module namespace. TODO: This is # very hacky. If there are better ways to do it, please let me know. # (maybe a custom nose test loader really would be the better option?) # -- Tobias Brox , 2013-10-10 _servernames = set() for _caldav_server in caldav_servers: # create a unique identifier out of the server domain name _parsed_url = urlparse(_caldav_server['url']) _servername = _parsed_url.hostname.replace('.','_') + str(_parsed_url.port or '') while _servername in _servernames: _servername = _servername + '_' _servernames.add(_servername) # create a classname and a class _classname = 'TestForServer_' + _servername # inject the new class into this namespace vars()[_classname] = type(_classname, (RepeatedFunctionalTestsBaseClass,), {'server_params': _caldav_server}) class TestCalDAV: """ Test class for "pure" unit tests (small internal tests, testing that a small unit of code works as expected, without any third party dependencies) """ def testCalendar(self): """ Principal.calendar() and CalendarSet.calendar() should create Calendar objects without initiating any communication with the server. Calendar.event() should create Event object without initiating any communication with the server. DAVClient.__init__ also doesn't do any communication Principal.__init__ as well, if the principal_url is given Principal.calendar_home_set needs to be set or the server will be queried """ client = DAVClient(url="http://me:hunter2@calendar.example:80/") principal = Principal(client, "http://me:hunter2@calendar.example:80/me/") principal.calendar_home_set = "http://me:hunter2@calendar.example:80/me/calendars/" ## calendar_home_set is actually a CalendarSet object assert(isinstance(principal.calendar_home_set, CalendarSet)) calendar1 = principal.calendar(name="foo", cal_id="bar") calendar2 = principal.calendar_home_set.calendar(name="foo", cal_id="bar") assert_equal(calendar1.url, calendar2.url) assert_equal(calendar1.url, "http://calendar.example:80/me/calendars/bar") ## principal.calendar_home_set can also be set to an object ## This should be noop principal.calendar_home_set = principal.calendar_home_set calendar1 = principal.calendar(name="foo", cal_id="bar") assert_equal(calendar1.url, calendar2.url) ## When building a calendar from a relative URL and a client, the relative URL should be appended to the base URL in the client calendar1 = Calendar(client, 'someoneelse/calendars/main_calendar') calendar2 = Calendar(client, 'http://me:hunter2@calendar.example:80/someoneelse/calendars/main_calendar') assert_equal(calendar1.url, calendar2.url) def testDefaultClient(self): """When no client is given to a DAVObject, but the parent is given, parent.client will be used""" client = DAVClient(url="http://me:hunter2@calendar.example:80/") calhome = CalendarSet(client, "http://me:hunter2@calendar.example:80/me/") calendar = Calendar(parent=calhome) assert_equal(calendar.client, calhome.client) def testURL(self): """Excersising the URL class""" ## 1) URL.objectify should return a valid URL object almost no matter what's thrown in url0 = URL.objectify(None) url0b= URL.objectify("") url1 = URL.objectify("http://foo:bar@www.example.com:8080/caldav.php/?foo=bar") url2 = URL.objectify(url1) url3 = URL.objectify("/bar") url4 = URL.objectify(urlparse(str(url1))) url5 = URL.objectify(urlparse("/bar")) ## 2) __eq__ works well assert_equal(url1, url2) assert_equal(url1, url4) assert_equal(url3, url5) ## 3) str will always return the URL assert_equal(str(url1), "http://foo:bar@www.example.com:8080/caldav.php/?foo=bar") assert_equal(str(url3), "/bar") assert_equal(str(url4), "http://foo:bar@www.example.com:8080/caldav.php/?foo=bar") assert_equal(str(url5), "/bar") ## 4) join method url6 = url1.join(url2) url7 = url1.join(url3) url8 = url1.join(url4) url9 = url1.join(url5) urlA = url1.join("someuser/calendar") urlB = url5.join(url1) assert_equal(url6, url1) assert_equal(url7, "http://foo:bar@www.example.com:8080/bar") assert_equal(url8, url1) assert_equal(url9, url7) assert_equal(urlA, "http://foo:bar@www.example.com:8080/caldav.php/someuser/calendar") assert_equal(urlB, url1) assert_raises(ValueError, url1.join, "http://www.google.com") ## 4b) join method, with URL as input parameter url6 = url1.join(URL.objectify(url2)) url7 = url1.join(URL.objectify(url3)) url8 = url1.join(URL.objectify(url4)) url9 = url1.join(URL.objectify(url5)) urlA = url1.join(URL.objectify("someuser/calendar")) urlB = url5.join(URL.objectify(url1)) url6b= url6.join(url0) url6c= url6.join(url0b) url6d= url6.join(None) for url6alt in (url6b, url6c, url6d): assert_equal(url6, url6alt) assert_equal(url6, url1) assert_equal(url7, "http://foo:bar@www.example.com:8080/bar") assert_equal(url8, url1) assert_equal(url9, url7) assert_equal(urlA, "http://foo:bar@www.example.com:8080/caldav.php/someuser/calendar") assert_equal(urlB, url1) assert_raises(ValueError, url1.join, "http://www.google.com") ## 5) all urlparse methods will work. always. assert_equal(url1.scheme, 'http') assert_equal(url2.path, '/caldav.php/') assert_equal(url7.username, 'foo') assert_equal(url5.path, '/bar') urlC = URL.objectify("https://www.example.com:443/foo") assert_equal(urlC.port, 443) ## 6) is_auth returns True if the URL contains a username. assert_equal(urlC.is_auth(), False) assert_equal(url7.is_auth(), True) ## 7) unauth() strips username/password assert_equal(url7.unauth(), 'http://www.example.com:8080/bar') def testFilters(self): filter = cdav.Filter()\ .append(cdav.CompFilter("VCALENDAR")\ .append(cdav.CompFilter("VEVENT")\ .append(cdav.PropFilter("UID")\ .append([cdav.TextMatch("pouet", negate = True)])))) print(filter) crash = cdav.CompFilter() value = None try: value = str(crash) except: pass if value is not None: raise Exception("This should have crashed")