[CalendarServer-changes] [14140] CalendarServer/trunk
source_changes at macosforge.org
source_changes at macosforge.org
Thu Nov 6 17:50:02 PST 2014
Revision: 14140
http://trac.calendarserver.org//changeset/14140
Author: sagen at apple.com
Date: 2014-11-06 17:50:02 -0800 (Thu, 06 Nov 2014)
Log Message:
-----------
First pass at import tool, only non-scheduled events supported so far
Modified Paths:
--------------
CalendarServer/trunk/setup.py
CalendarServer/trunk/support/Apple.make
CalendarServer/trunk/twistedcaldav/ical.py
CalendarServer/trunk/twistedcaldav/storebridge.py
Added Paths:
-----------
CalendarServer/trunk/calendarserver/tools/importer.py
CalendarServer/trunk/calendarserver/tools/test/test_importer.py
Added: CalendarServer/trunk/calendarserver/tools/importer.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/importer.py (rev 0)
+++ CalendarServer/trunk/calendarserver/tools/importer.py 2014-11-07 01:50:02 UTC (rev 14140)
@@ -0,0 +1,319 @@
+#!/usr/bin/env python
+# -*- test-case-name: calendarserver.tools.test.test_importer -*-
+##
+# Copyright (c) 2014 Apple Inc. All rights reserved.
+#
+# 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.
+##
+
+"""
+This tool imports calendar data
+
+This tool requires access to the calendar server's configuration and data
+storage; it does not operate by talking to the server via the network. It
+therefore does not apply any of the access restrictions that the server would.
+"""
+
+from __future__ import print_function
+
+import os
+import sys
+import uuid
+
+from calendarserver.tools.cmdline import utilityMain, WorkerService
+from twext.python.log import Logger
+from twisted.internet.defer import inlineCallbacks
+from twisted.python.text import wordWrap
+from twisted.python.usage import Options, UsageError
+from twistedcaldav import customxml
+from twistedcaldav.ical import Component
+from twistedcaldav.stdconfig import DEFAULT_CONFIG_FILE
+from txdav.base.propertystore.base import PropertyName
+from txdav.common.icommondatastore import UIDExistsError
+from txdav.xml import element as davxml
+
+
+log = Logger()
+
+
+
+def usage(e=None):
+ if e:
+ print(e)
+ print("")
+ try:
+ ImportOptions().opt_help()
+ except SystemExit:
+ pass
+ if e:
+ sys.exit(64)
+ else:
+ sys.exit(0)
+
+
+description = '\n'.join(
+ wordWrap(
+ """
+ Usage: calendarserver_import [options] [input specifiers]\n
+ """ + __doc__,
+ int(os.environ.get('COLUMNS', '80'))
+ )
+)
+
+
+
+class ImportException(Exception):
+ """
+ An error occurred during import
+ """
+
+
+class ImportOptions(Options):
+ """
+ Command-line options for 'calendarserver_import'
+ """
+
+ synopsis = description
+
+ optFlags = [
+ ['debug', 'D', "Debug logging."],
+ ]
+
+ optParameters = [
+ ['config', 'f', DEFAULT_CONFIG_FILE, "Specify caldavd.plist configuration path."],
+ ]
+
+ def __init__(self):
+ super(ImportOptions, self).__init__()
+ self.inputName = '-'
+
+
+ def opt_input(self, filename):
+ """
+ Specify input file path (default: '-', meaning stdin).
+ """
+ self.inputName = filename
+
+ opt_i = opt_input
+
+
+ def openInput(self):
+ """
+ Open the appropriate input file based on the '--input' option.
+ """
+ if self.inputName == '-':
+ return sys.stdin
+ else:
+ return open(self.inputName, 'r')
+
+
+# These could probably live on the collection class:
+
+def setCollectionPropertyValue(collection, element, value):
+ collectionProperties = collection.properties()
+ collectionProperties[PropertyName.fromElement(element)] = (
+ element.fromString(value)
+ )
+
+
+def getCollectionPropertyValue(collection, element):
+ collectionProperties = collection.properties()
+ name = PropertyName.fromElement(element)
+ if name in collectionProperties:
+ return str(collectionProperties[name])
+ else:
+ return None
+
+#
+
+
+ at inlineCallbacks
+def importCollectionComponent(store, component):
+ """
+ Import a component representing a collection (e.g. VCALENDAR) into the
+ store.
+
+ The homeUID and collection resource name the component will be imported
+ into is derived from the SOURCE property on the VCALENDAR (which must
+ be present). The code assumes it will be a URI with slash-separated parts
+ with the penultimate part specifying the homeUID and the last part
+ specifying the calendar resource name. The NAME property will be used
+ to set the DAV:display-name, while the COLOR property will be used to set
+ calendar-color.
+
+ Subcomponents (e.g. VEVENTs) are grouped into resources by UID. Objects
+ which have a UID already in use within the home will be skipped.
+
+ @param store: The db store to add the component to
+ @type store: L{IDataStore}
+ @param component: The component to store
+ @type component: L{twistedcaldav.ical.Component}
+ """
+
+ sourceURI = component.propertyValue("SOURCE")
+ if not sourceURI:
+ raise ImportException("Calendar is missing SOURCE property")
+
+ ownerUID, collectionResourceName = sourceURI.strip("/").split("/")[-2:]
+
+ dir = store.directoryService()
+ record = yield dir.recordWithUID(ownerUID)
+ if not record:
+ raise ImportException("{} is not in the directory".format(ownerUID))
+
+ # Set properties on the collection
+ txn = store.newTransaction()
+ home = yield txn.calendarHomeWithUID(ownerUID, create=True)
+ collection = yield home.childWithName(collectionResourceName)
+ if not collection:
+ collection = yield home.createChildWithName(collectionResourceName)
+ for propertyName, element in (
+ ("NAME", davxml.DisplayName),
+ ("COLOR", customxml.CalendarColor),
+ ):
+ value = component.propertyValue(propertyName)
+ if value is not None:
+ setCollectionPropertyValue(collection, element, value)
+ yield txn.commit()
+
+ # Populate the collection; NB we use a txn for each object, and we might
+ # want to batch them?
+ groupedComponents = Component.componentsFromComponent(component)
+ for groupedComponent in groupedComponents:
+ resourceName = "{}.ics".format(str(uuid.uuid4()))
+ try:
+ yield storeComponentInHomeAndCalendar(
+ store, groupedComponent, ownerUID, collectionResourceName, resourceName
+ )
+ except UIDExistsError:
+ # That event is already in the home
+ print(
+ "Skipping since UID already exists: {uid}".format(
+ uid=groupedComponent.propertyValue("UID")
+ )
+ )
+ except Exception, e:
+ print(
+ "Failed to import due to: {error}\n{comp}".format(
+ error=e,
+ comp=groupedComponent
+ )
+ )
+
+
+ at inlineCallbacks
+def storeComponentInHomeAndCalendar(
+ store, component, homeUID, collectionResourceName, objectResourceName
+):
+ """
+ Add a component to the store as an objectResource
+
+ If the calendar home does not yet exist for homeUID it will be created.
+ If the collection by the name collectionResourceName does not yet exist
+ it will be created.
+
+ @param store: The db store to add the component to
+ @type store: L{IDataStore}
+ @param component: The component to store
+ @type component: L{twistedcaldav.ical.Component}
+ @param homeUID: uid of the home collection
+ @type collectionResourceName: C{str}
+ @param collectionResourceName: name of the collection resource
+ @type collectionResourceName: C{str}
+ @param objectResourceName: name of the objectresource
+ @type objectResourceName: C{str}
+
+ """
+ txn = store.newTransaction()
+ home = yield txn.calendarHomeWithUID(homeUID, create=True)
+ collection = yield home.childWithName(collectionResourceName)
+ if not collection:
+ collection = yield home.createChildWithName(collectionResourceName)
+
+ yield collection.createObjectResourceWithName(objectResourceName, component)
+ yield txn.commit()
+
+
+
+class ImporterService(WorkerService, object):
+ """
+ Service which runs, imports the data, then stops the reactor.
+ """
+
+ def __init__(self, store, options, input, reactor, config):
+ super(ImporterService, self).__init__(store)
+ self.options = options
+ self.input = input
+ self.reactor = reactor
+ self.config = config
+ self._directory = self.store.directoryService()
+
+
+ @inlineCallbacks
+ def doWork(self):
+ """
+ Do the export, stopping the reactor when done.
+ """
+ try:
+ component = Component.allFromStream(self.input)
+ self.input.close()
+ yield importCollectionComponent(self.store, component)
+ except:
+ log.failure("doWork()")
+
+
+ def directoryService(self):
+ """
+ Get an appropriate directory service.
+ """
+ return self._directory
+
+
+ def stopService(self):
+ """
+ Stop the service. Nothing to do; everything should be finished by this
+ time.
+ """
+ # TODO: stopping this service mid-import should really stop the import
+ # loop, but this is not implemented because nothing will actually do it
+ # except hitting ^C (which also calls reactor.stop(), so that will exit
+ # anyway).
+
+
+
+def main(argv=sys.argv, stderr=sys.stderr, reactor=None):
+ """
+ Do the import.
+ """
+ if reactor is None:
+ from twisted.internet import reactor
+
+ options = ImportOptions()
+ try:
+ options.parseOptions(argv[1:])
+ except UsageError, e:
+ usage(e)
+
+ try:
+ input = options.openInput()
+ except IOError, e:
+ stderr.write("Unable to open input file for reading: %s\n" %
+ (e))
+ sys.exit(1)
+
+
+ def makeService(store):
+ from twistedcaldav.config import config
+ return ImporterService(store, options, input, reactor, config)
+
+ utilityMain(options["config"], makeService, reactor, verbose=options["debug"])
Property changes on: CalendarServer/trunk/calendarserver/tools/importer.py
___________________________________________________________________
Added: svn:executable
+ *
Added: CalendarServer/trunk/calendarserver/tools/test/test_importer.py
===================================================================
--- CalendarServer/trunk/calendarserver/tools/test/test_importer.py (rev 0)
+++ CalendarServer/trunk/calendarserver/tools/test/test_importer.py 2014-11-07 01:50:02 UTC (rev 14140)
@@ -0,0 +1,189 @@
+##
+# Copyright (c) 2014 Apple Inc. All rights reserved.
+#
+# 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.
+##
+
+"""
+Unit tests for L{calendarsever.tools.importer}.
+"""
+
+from calendarserver.tools.importer import importCollectionComponent, ImportException
+from twisted.internet.defer import inlineCallbacks
+from twistedcaldav import customxml
+from twistedcaldav.ical import Component
+from twistedcaldav.test.util import StoreTestCase
+from txdav.xml import element as davxml
+from txdav.base.propertystore.base import PropertyName
+
+
+DATA_MISSING_SOURCE = """BEGIN:VCALENDAR
+CALSCALE:GREGORIAN
+PRODID:-//Apple Computer\, Inc//iCal 2.0//EN
+VERSION:2.0
+END:VCALENDAR
+"""
+
+DATA_NO_SCHEDULING = """BEGIN:VCALENDAR
+VERSION:2.0
+NAME:Sample Import Calendar
+COLOR:#0E61B9FF
+SOURCE;VALUE=URI:http://example.com/calendars/__uids__/user01/calendar/
+PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
+BEGIN:VEVENT
+UID:5CE3B280-DBC9-4E8E-B0B2-996754020E5F
+DTSTART;TZID=America/Los_Angeles:20141108T093000
+DTEND;TZID=America/Los_Angeles:20141108T103000
+CREATED:20141106T192546Z
+DTSTAMP:20141106T192546Z
+RRULE:FREQ=DAILY
+SEQUENCE:0
+SUMMARY:repeating event
+TRANSP:OPAQUE
+END:VEVENT
+BEGIN:VEVENT
+UID:5CE3B280-DBC9-4E8E-B0B2-996754020E5F
+RECURRENCE-ID;TZID=America/Los_Angeles:20141111T093000
+DTSTART;TZID=America/Los_Angeles:20141111T110000
+DTEND;TZID=America/Los_Angeles:20141111T120000
+CREATED:20141106T192546Z
+DTSTAMP:20141106T192546Z
+SEQUENCE:0
+SUMMARY:repeating event
+TRANSP:OPAQUE
+END:VEVENT
+BEGIN:VEVENT
+UID:F6342D53-7D5E-4B5E-9E0A-F0A08977AFE5
+DTSTART;TZID=America/Los_Angeles:20141108T080000
+DTEND;TZID=America/Los_Angeles:20141108T091500
+CREATED:20141104T205338Z
+DTSTAMP:20141104T205338Z
+SEQUENCE:0
+SUMMARY:simple event
+TRANSP:OPAQUE
+END:VEVENT
+END:VCALENDAR
+"""
+
+DATA_NO_SCHEDULING_REIMPORT = """BEGIN:VCALENDAR
+VERSION:2.0
+NAME:Sample Import Calendar Reimported
+COLOR:#FFFFFFFF
+SOURCE;VALUE=URI:http://example.com/calendars/__uids__/user01/calendar/
+PRODID:-//CALENDARSERVER.ORG//NONSGML Version 1//EN
+BEGIN:VEVENT
+UID:5CE3B280-DBC9-4E8E-B0B2-996754020E5F
+DTSTART;TZID=America/Los_Angeles:20141108T093000
+DTEND;TZID=America/Los_Angeles:20141108T103000
+CREATED:20141106T192546Z
+DTSTAMP:20141106T192546Z
+RRULE:FREQ=DAILY
+SEQUENCE:0
+SUMMARY:repeating event
+TRANSP:OPAQUE
+END:VEVENT
+BEGIN:VEVENT
+UID:5CE3B280-DBC9-4E8E-B0B2-996754020E5F
+RECURRENCE-ID;TZID=America/Los_Angeles:20141111T093000
+DTSTART;TZID=America/Los_Angeles:20141111T110000
+DTEND;TZID=America/Los_Angeles:20141111T120000
+CREATED:20141106T192546Z
+DTSTAMP:20141106T192546Z
+SEQUENCE:0
+SUMMARY:repeating event
+TRANSP:OPAQUE
+END:VEVENT
+BEGIN:VEVENT
+UID:CB194340-9B3C-40B1-B4E2-062FDB7C8829
+DTSTART;TZID=America/Los_Angeles:20141108T080000
+DTEND;TZID=America/Los_Angeles:20141108T091500
+CREATED:20141104T205338Z
+DTSTAMP:20141104T205338Z
+SEQUENCE:0
+SUMMARY:new event
+TRANSP:OPAQUE
+END:VEVENT
+END:VCALENDAR
+"""
+
+
+class ImportTests(StoreTestCase):
+ """
+ Tests for importing data to a live store.
+ """
+
+ @inlineCallbacks
+ def test_ImportComponentMissingSource(self):
+
+ component = Component.allFromString(DATA_MISSING_SOURCE)
+ try:
+ yield importCollectionComponent(self.store, component)
+ except ImportException:
+ pass
+ else:
+ self.fail("Did not raise ImportException")
+
+
+ @inlineCallbacks
+ def test_ImportComponentNoScheduling(self):
+
+ component = Component.allFromString(DATA_NO_SCHEDULING)
+ yield importCollectionComponent(self.store, component)
+
+ txn = self.store.newTransaction()
+ home = yield txn.calendarHomeWithUID(u"user01")
+ collection = yield home.childWithName(u"calendar")
+
+ # Verify properties have been set
+ collectionProperties = collection.properties()
+ for element, value in (
+ (davxml.DisplayName, "Sample Import Calendar"),
+ (customxml.CalendarColor, "#0E61B9FF"),
+ ):
+ self.assertEquals(
+ value,
+ collectionProperties[PropertyName.fromElement(element)]
+ )
+
+ # Verify child objects
+ objects = yield collection.listObjectResources()
+ self.assertEquals(len(objects), 2)
+
+ yield txn.commit()
+
+ # Reimport different component into same collection
+
+ component = Component.allFromString(DATA_NO_SCHEDULING_REIMPORT)
+
+ yield importCollectionComponent(self.store, component)
+
+ txn = self.store.newTransaction()
+ home = yield txn.calendarHomeWithUID(u"user01")
+ collection = yield home.childWithName(u"calendar")
+
+ # Verify properties have been changed
+ collectionProperties = collection.properties()
+ for element, value in (
+ (davxml.DisplayName, "Sample Import Calendar Reimported"),
+ (customxml.CalendarColor, "#FFFFFFFF"),
+ ):
+ self.assertEquals(
+ value,
+ collectionProperties[PropertyName.fromElement(element)]
+ )
+
+ # Verify child objects (should be 3 now)
+ objects = yield collection.listObjectResources()
+ self.assertEquals(len(objects), 3)
+
+ yield txn.commit()
Modified: CalendarServer/trunk/setup.py
===================================================================
--- CalendarServer/trunk/setup.py 2014-11-06 21:51:03 UTC (rev 14139)
+++ CalendarServer/trunk/setup.py 2014-11-07 01:50:02 UTC (rev 14140)
@@ -175,6 +175,9 @@
"icalendar_validate":
("calendarserver.tools.validcalendardata", "main"),
+ "import":
+ ("calendarserver.tools.importer", "main"),
+
"manage_principals":
("calendarserver.tools.principals", "main"),
Modified: CalendarServer/trunk/support/Apple.make
===================================================================
--- CalendarServer/trunk/support/Apple.make 2014-11-06 21:51:03 UTC (rev 14139)
+++ CalendarServer/trunk/support/Apple.make 2014-11-07 01:50:02 UTC (rev 14140)
@@ -151,6 +151,7 @@
calendarserver_command_gateway \
calendarserver_diagnose \
calendarserver_export \
+ calendarserver_import \
calendarserver_manage_principals \
calendarserver_purge_attachments \
calendarserver_purge_events \
Modified: CalendarServer/trunk/twistedcaldav/ical.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/ical.py 2014-11-06 21:51:03 UTC (rev 14139)
+++ CalendarServer/trunk/twistedcaldav/ical.py 2014-11-07 01:50:02 UTC (rev 14140)
@@ -29,6 +29,7 @@
]
import codecs
+import collections
from difflib import unified_diff
import heapq
import itertools
@@ -70,6 +71,7 @@
allowedSchedulingComponents = allowedStoreComponents + ("VFREEBUSY",)
allowedComponents = allowedSchedulingComponents + ("VTIMEZONE",)
+
def _updateAllowedComponents(allowed):
global allowedStoreComponents, allowedSchedulingComponents, allowedComponents
allowedStoreComponents = allowed
@@ -163,6 +165,7 @@
minDateTime = DateTime(1900, 1, 1, 0, 0, 0, tzid=Timezone(utc=True))
maxDateTime = DateTime(2100, 1, 1, 0, 0, 0, tzid=Timezone(utc=True))
+
class InvalidICalendarDataError(ValueError):
pass
@@ -509,6 +512,68 @@
@classmethod
+ def componentsFromData(cls, data, format):
+ """
+ Need to split a single VCALENDAR in text form into separate ones based
+ on UID with the appropriate VTIEMZONES included.
+ """
+
+ # Split into components by UID and TZID
+ try:
+ vcal = cls.fromString(data, format)
+ except InvalidICalendarDataError:
+ return None
+
+ return cls.componentsFromComponent(vcal)
+
+
+ @classmethod
+ def componentsFromComponent(cls, sourceComponent):
+ """
+ Need to split a single VCALENDAR in Component form into separate ones
+ based on UID with the appropriate VTIEMZONES included.
+ """
+
+ results = []
+
+ by_uid = collections.OrderedDict()
+ by_tzid = {}
+ for subcomponent in sourceComponent.subcomponents():
+ if subcomponent.name() == "VTIMEZONE":
+ by_tzid[subcomponent.propertyValue("TZID")] = subcomponent
+ else:
+ by_uid.setdefault(subcomponent.propertyValue("UID"), []).append(subcomponent)
+
+ # Re-constitute as separate VCALENDAR objects
+ for components in by_uid.values():
+
+ newvcal = cls("VCALENDAR")
+ newvcal.addProperty(Property("VERSION", "2.0"))
+ newvcal.addProperty(Property("PRODID", sourceComponent.propertyValue("PRODID")))
+
+ # Get the set of TZIDs and include them
+ tzids = set()
+ for component in components:
+ tzids.update(component.timezoneIDs())
+ for tzid in tzids:
+ try:
+ tz = by_tzid[tzid]
+ newvcal.addComponent(tz.duplicate())
+ except KeyError:
+ # We ignore the error and generate invalid ics which someone will
+ # complain about at some point
+ pass
+
+ # Now add each component
+ for component in components:
+ newvcal.addComponent(component.duplicate())
+
+ results.append(newvcal)
+
+ return results
+
+
+ @classmethod
def newCalendar(cls):
"""
Create and return an empty C{VCALENDAR} component.
Modified: CalendarServer/trunk/twistedcaldav/storebridge.py
===================================================================
--- CalendarServer/trunk/twistedcaldav/storebridge.py 2014-11-06 21:51:03 UTC (rev 14139)
+++ CalendarServer/trunk/twistedcaldav/storebridge.py 2014-11-07 01:50:02 UTC (rev 14140)
@@ -15,7 +15,6 @@
# limitations under the License.
##
-import collections
import hashlib
import time
from urlparse import urlsplit, urljoin
@@ -36,7 +35,7 @@
from twistedcaldav.config import config
from twistedcaldav.customxml import calendarserver_namespace
from twistedcaldav.ical import (
- Component as VCalendar, Property as VProperty, InvalidICalendarDataError,
+ Component as VCalendar, Property as VProperty,
iCalendarProductID, Component
)
from twistedcaldav.instance import (
@@ -1174,52 +1173,9 @@
Need to split a single VCALENDAR into separate ones based on UID with the
appropriate VTIEMZONES included.
"""
+ return Component.componentsFromData(data, format)
- results = []
- # Split into components by UID and TZID
- try:
- vcal = VCalendar.fromString(data, format)
- except InvalidICalendarDataError:
- return None
-
- by_uid = collections.OrderedDict()
- by_tzid = {}
- for subcomponent in vcal.subcomponents():
- if subcomponent.name() == "VTIMEZONE":
- by_tzid[subcomponent.propertyValue("TZID")] = subcomponent
- else:
- by_uid.setdefault(subcomponent.propertyValue("UID"), []).append(subcomponent)
-
- # Re-constitute as separate VCALENDAR objects
- for components in by_uid.values():
-
- newvcal = VCalendar("VCALENDAR")
- newvcal.addProperty(VProperty("VERSION", "2.0"))
- newvcal.addProperty(VProperty("PRODID", vcal.propertyValue("PRODID")))
-
- # Get the set of TZIDs and include them
- tzids = set()
- for component in components:
- tzids.update(component.timezoneIDs())
- for tzid in tzids:
- try:
- tz = by_tzid[tzid]
- newvcal.addComponent(tz.duplicate())
- except KeyError:
- # We ignore the error and generate invalid ics which someone will
- # complain about at some point
- pass
-
- # Now add each component
- for component in components:
- newvcal.addComponent(component.duplicate())
-
- results.append(newvcal)
-
- return results
-
-
@classmethod
def resourceSuffix(cls):
return ".ics"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.macosforge.org/pipermail/calendarserver-changes/attachments/20141106/c24885d4/attachment-0001.html>
More information about the calendarserver-changes
mailing list