integrate Dav app with Calendar API

Signed-off-by: Georg Ehrke <developer@georgehrke.com>
pull/6840/head
Georg Ehrke 9 years ago
parent 556b2a2b6f
commit fa416e031b
No known key found for this signature in database
GPG Key ID: 9D98FD9380A1CB43
  1. 8
      apps/dav/appinfo/app.php
  2. 17
      apps/dav/lib/AppInfo/Application.php
  3. 165
      apps/dav/lib/CalDAV/CalDavBackend.php
  4. 119
      apps/dav/lib/CalDAV/CalendarImpl.php
  5. 71
      apps/dav/lib/CalDAV/CalendarManager.php
  6. 109
      apps/dav/tests/unit/CalDAV/CalDavBackendTest.php
  7. 126
      apps/dav/tests/unit/CalDAV/CalendarImplTest.php
  8. 81
      apps/dav/tests/unit/CalDAV/CalendarManagerTest.php

@ -55,3 +55,11 @@ $cm->register(function() use ($cm, $app) {
$app->setupContactsProvider($cm, $user->getUID());
}
});
$calendarManager = \OC::$server->getCalendarManager();
$calendarManager->register(function() use ($calendarManager, $app) {
$user = \OC::$server->getUserSession()->getUser();
if ($user !== null) {
$app->setupCalendarProvider($calendarManager, $user->getUID());
}
});

@ -29,13 +29,15 @@ use OC\AppFramework\Utility\SimpleContainer;
use OCA\DAV\CalDAV\Activity\Backend;
use OCA\DAV\CalDAV\Activity\Provider\Event;
use OCA\DAV\CalDAV\BirthdayService;
use OCA\DAV\CalDAV\CalendarManager;
use OCA\DAV\Capabilities;
use OCA\DAV\CardDAV\ContactsManager;
use OCA\DAV\CardDAV\PhotoCache;
use OCA\DAV\CardDAV\SyncService;
use OCA\DAV\HookManager;
use \OCP\AppFramework\App;
use OCP\Contacts\IManager;
use OCP\Contacts\IManager as IContactsManager;
use OCP\Calendar\IManager as ICalendarManager;
use OCP\IUser;
use Symfony\Component\EventDispatcher\GenericEvent;
@ -63,16 +65,25 @@ class Application extends App {
}
/**
* @param IManager $contactsManager
* @param IContactsManager $contactsManager
* @param string $userID
*/
public function setupContactsProvider(IManager $contactsManager, $userID) {
public function setupContactsProvider(IContactsManager $contactsManager, $userID) {
/** @var ContactsManager $cm */
$cm = $this->getContainer()->query(ContactsManager::class);
$urlGenerator = $this->getContainer()->getServer()->getURLGenerator();
$cm->setupContactsProvider($contactsManager, $userID, $urlGenerator);
}
/**
* @param ICalendarManager $calendarManager
* @param string $userId
*/
public function setupCalendarProvider(ICalendarManager $calendarManager, $userId) {
$cm = $this->getContainer()->query(CalendarManager::class);
$cm->setupCalendarProvider($calendarManager, $userId);
}
public function registerHooks() {
/** @var HookManager $hm */
$hm = $this->getContainer()->query(HookManager::class);

@ -51,8 +51,12 @@ use Sabre\DAV\Exception\Forbidden;
use Sabre\DAV\Exception\NotFound;
use Sabre\DAV\PropPatch;
use Sabre\HTTP\URLUtil;
use Sabre\VObject\Component;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;
use Sabre\VObject\Component\VTimeZone;
use Sabre\VObject\DateTimeParser;
use Sabre\VObject\Property;
use Sabre\VObject\Reader;
use Sabre\VObject\Recur\EventIterator;
use Sabre\Uri;
@ -1344,6 +1348,167 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
return $result;
}
/**
* used for Nextcloud's calendar API
*
* @param array $calendarInfo
* @param string $pattern
* @param array $searchProperties
* @param array $options
* @param integer|null $limit
* @param integer|null $offset
*
* @return array
*/
public function search(array $calendarInfo, $pattern, array $searchProperties,
array $options, $limit, $offset) {
$outerQuery = $this->db->getQueryBuilder();
$innerQuery = $this->db->getQueryBuilder();
$innerQuery->selectDistinct('op.objectid')
->from($this->dbObjectPropertiesTable, 'op')
->andWhere($innerQuery->expr()->eq('op.calendarid',
$outerQuery->createNamedParameter($calendarInfo['id'])));
// only return public items for shared calendars for now
if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
}
$or = $innerQuery->expr()->orX();
foreach($searchProperties as $searchProperty) {
$or->add($innerQuery->expr()->eq('op.name',
$outerQuery->createNamedParameter($searchProperty)));
}
$innerQuery->andWhere($or);
// TODO - add component-type
if ($pattern !== '') {
$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
$outerQuery->createNamedParameter('%' .
$this->db->escapeLikeParameter($pattern) . '%')));
}
$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
->from('calendarobjects', 'c');
if (isset($options['timerange'])) {
if (isset($options['timerange']['start'])) {
$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
}
if (isset($options['timerange']['end'])) {
$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
}
}
$outerQuery->andWhere($outerQuery->expr()->in('c.id',
$outerQuery->createFunction($innerQuery->getSQL())));
if ($offset) {
$outerQuery->setFirstResult($offset);
}
if ($limit) {
$outerQuery->setMaxResults($limit);
}
$result = $outerQuery->execute();
$calendarObjects = $result->fetchAll();
return array_map(function($o) {
$calendarData = Reader::read($o['calendardata']);
$comps = $calendarData->getComponents();
$objects = [];
$timezones = [];
foreach($comps as $comp) {
if ($comp instanceof VTimeZone) {
$timezones[] = $comp;
} else {
$objects[] = $comp;
}
}
return [
'id' => $o['id'],
'type' => $o['componenttype'],
'uid' => $o['uid'],
'uri' => $o['uri'],
'objects' => array_map(function($c) {
return $this->transformSearchData($c);
}, $objects),
'timezones' => array_map(function($c) {
return $this->transformSearchData($c);
}, $timezones),
];
}, $calendarObjects);
}
/**
* @param Component $comp
* @return array
*/
private function transformSearchData(Component $comp) {
$data = [];
/** @var Component[] $subComponents */
$subComponents = $comp->getComponents();
/** @var Property[] $properties */
$properties = array_filter($comp->children(), function($c) {
return $c instanceof Property;
});
$validationRules = $comp->getValidationRules();
foreach($subComponents as $subComponent) {
$name = $subComponent->name;
if (!isset($data[$name])) {
$data[$name] = [];
}
$data[$name][] = $this->transformSearchData($subComponent);
}
foreach($properties as $property) {
$name = $property->name;
if (!isset($validationRules[$name])) {
$validationRules[$name] = '*';
}
$rule = $validationRules[$property->name];
if ($rule === '+' || $rule === '*') { // multiple
if (!isset($data[$name])) {
$data[$name] = [];
}
$data[$name][] = $this->transformSearchProperty($property);
} else { // once
$data[$name] = $this->transformSearchProperty($property);
}
}
return $data;
}
/**
* @param Property $prop
* @return array
*/
private function transformSearchProperty(Property $prop) {
// No need to check Date, as it extends DateTime
if ($prop instanceof Property\ICalendar\DateTime) {
$value = $prop->getDateTime();
} else {
$value = $prop->getValue();
}
return [
$value,
$prop->parameters()
];
}
/**
* Searches through all of a users calendars and calendar objects to find
* an object with a specific UID.

@ -0,0 +1,119 @@
<?php
/**
* @copyright 2017, Georg Ehrke <oc.list@georgehrke.com>
*
* @author Georg Ehrke <oc.list@georgehrke.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\DAV\CalDAV;
use OCP\Constants;
use OCP\Calendar\ICalendar;
class CalendarImpl implements ICalendar {
/** @var CalDavBackend */
private $backend;
/** @var Calendar */
private $calendar;
/** @var array */
private $calendarInfo;
/**
* CalendarImpl constructor.
*
* @param Calendar $calendar
* @param array $calendarInfo
* @param CalDavBackend $backend
*/
public function __construct(Calendar $calendar, array $calendarInfo,
CalDavBackend $backend) {
$this->calendar = $calendar;
$this->calendarInfo = $calendarInfo;
$this->backend = $backend;
}
/**
* @return string defining the technical unique key
* @since 13.0.0
*/
public function getKey() {
return $this->calendarInfo['id'];
}
/**
* In comparison to getKey() this function returns a human readable (maybe translated) name
* @return null|string
* @since 13.0.0
*/
public function getDisplayName() {
return $this->calendarInfo['{DAV:}displayname'];
}
/**
* Calendar color
* @return null|string
* @since 13.0.0
*/
public function getDisplayColor() {
return $this->calendarInfo['{http://apple.com/ns/ical/}calendar-color'];
}
/**
* @param string $pattern which should match within the $searchProperties
* @param array $searchProperties defines the properties within the query pattern should match
* @param array $options - optional parameters:
* ['timerange' => ['start' => new DateTime(...), 'end' => new DateTime(...)]]
* @param integer|null $limit - limit number of search results
* @param integer|null $offset - offset for paging of search results
* @return array an array of events/journals/todos which are arrays of key-value-pairs
* @since 13.0.0
*/
public function search($pattern, array $searchProperties=[], array $options=[], $limit=null, $offset=null) {
return $this->backend->search($this->calendarInfo, $pattern,
$searchProperties, $options, $limit, $offset);
}
/**
* @return integer build up using \OCP\Constants
* @since 13.0.0
*/
public function getPermissions() {
$permissions = $this->calendar->getACL();
$result = 0;
foreach ($permissions as $permission) {
switch($permission['privilege']) {
case '{DAV:}read':
$result |= Constants::PERMISSION_READ;
break;
case '{DAV:}write':
$result |= Constants::PERMISSION_CREATE;
$result |= Constants::PERMISSION_UPDATE;
break;
case '{DAV:}all':
$result |= Constants::PERMISSION_ALL;
break;
}
}
return $result;
}
}

@ -0,0 +1,71 @@
<?php
/**
* @copyright 2017, Georg Ehrke <oc.list@georgehrke.com>
*
* @author Georg Ehrke <oc.list@georgehrke.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\DAV\CalDAV;
use OCP\Calendar\IManager;
use OCP\IL10N;
class CalendarManager {
/** @var CalDavBackend */
private $backend;
/** @var IL10N */
private $l10n;
/**
* CalendarManager constructor.
*
* @param CalDavBackend $backend
* @param IL10N $l10n
*/
public function __construct(CalDavBackend $backend, IL10N $l10n) {
$this->backend = $backend;
$this->l10n = $l10n;
}
/**
* @param IManager $cm
* @param string $userId
*/
public function setupCalendarProvider(IManager $cm, $userId) {
$calendars = $this->backend->getCalendarsForUser("principals/users/$userId");
$this->register($cm, $calendars);
}
/**
* @param IManager $cm
* @param array $calendars
*/
private function register(IManager $cm, array $calendars) {
foreach($calendars as $calendarInfo) {
$calendar = new Calendar($this->backend, $calendarInfo, $this->l10n);
$cm->registerCalendar(new CalendarImpl(
$calendar,
$calendarInfo,
$this->backend
));
}
}
}

@ -721,4 +721,113 @@ EOD;
]);
$this->assertEquals(count($search5), 0);
}
/**
* @dataProvider searchDataProvider
*/
public function testSearch($isShared, $count) {
$calendarId = $this->createTestCalendar();
$uris = [];
$calData = [];
$uris[] = static::getUniqueID('calobj');
$calData[] = <<<EOD
BEGIN:VCALENDAR
VERSION:2.0
PRODID:Nextcloud Calendar
BEGIN:VEVENT
CREATED;VALUE=DATE-TIME:20130910T125139Z
UID:47d15e3ec8-1
LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z
DTSTAMP;VALUE=DATE-TIME:20130910T125139Z
SUMMARY:Test Event
DTSTART;VALUE=DATE-TIME:20130912T130000Z
DTEND;VALUE=DATE-TIME:20130912T140000Z
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR
EOD;
$uris[] = static::getUniqueID('calobj');
$calData[] = <<<EOD
BEGIN:VCALENDAR
VERSION:2.0
PRODID:Nextcloud Calendar
BEGIN:VEVENT
CREATED;VALUE=DATE-TIME:20130910T125139Z
UID:47d15e3ec8-2
LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z
DTSTAMP;VALUE=DATE-TIME:20130910T125139Z
SUMMARY:123
LOCATION:Test
DTSTART;VALUE=DATE-TIME:20130912T130000Z
DTEND;VALUE=DATE-TIME:20130912T140000Z
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR
EOD;
$uris[] = static::getUniqueID('calobj');
$calData[] = <<<EOD
BEGIN:VCALENDAR
VERSION:2.0
PRODID:Nextcloud Calendar
BEGIN:VEVENT
CREATED;VALUE=DATE-TIME:20130910T125139Z
UID:47d15e3ec8-3
LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z
DTSTAMP;VALUE=DATE-TIME:20130910T125139Z
SUMMARY:123
ATTENDEE;CN=test:mailto:foo@bar.com
DTSTART;VALUE=DATE-TIME:20130912T130000Z
DTEND;VALUE=DATE-TIME:20130912T140000Z
CLASS:PRIVATE
END:VEVENT
END:VCALENDAR
EOD;
$uris[] = static::getUniqueID('calobj');
$calData[] = <<<EOD
BEGIN:VCALENDAR
VERSION:2.0
PRODID:Nextcloud Calendar
BEGIN:VEVENT
CREATED;VALUE=DATE-TIME:20130910T125139Z
UID:47d15e3ec8-4
LAST-MODIFIED;VALUE=DATE-TIME:20130910T125139Z
DTSTAMP;VALUE=DATE-TIME:20130910T125139Z
SUMMARY:123
ATTENDEE;CN=foobar:mailto:test@bar.com
DTSTART;VALUE=DATE-TIME:20130912T130000Z
DTEND;VALUE=DATE-TIME:20130912T140000Z
CLASS:CONFIDENTIAL
END:VEVENT
END:VCALENDAR
EOD;
$uriCount = count($uris);
for ($i=0; $i < $uriCount; $i++) {
$this->backend->createCalendarObject($calendarId,
$uris[$i], $calData[$i]);
}
$calendarInfo = [
'id' => $calendarId,
'principaluri' => 'user1',
'{http://owncloud.org/ns}owner-principal' => $isShared ? 'user2' : 'user1',
];
$result = $this->backend->search($calendarInfo, 'Test',
['SUMMARY', 'LOCATION', 'ATTENDEE'], [], null, null);
$this->assertCount($count, $result);
}
public function searchDataProvider() {
return [
[false, 4],
[true, 2],
];
}
}

@ -0,0 +1,126 @@
<?php
/**
* @copyright 2017, Georg Ehrke <oc.list@georgehrke.com>
*
* @author Georg Ehrke <oc.list@georgehrke.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\DAV\Tests\unit\CalDAV;
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\CalDAV\Calendar;
use OCA\DAV\CalDAV\CalendarImpl;
class CalendarImplTest extends \Test\TestCase {
/** @var CalendarImpl */
private $calendarImpl;
/** @var Calendar | \PHPUnit_Framework_MockObject_MockObject */
private $calendar;
/** @var array */
private $calendarInfo;
/** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject */
private $backend;
protected function setUp() {
parent::setUp();
$this->calendar = $this->createMock(Calendar::class);
$this->calendarInfo = [
'id' => 'fancy_id_123',
'{DAV:}displayname' => 'user readable name 123',
'{http://apple.com/ns/ical/}calendar-color' => '#AABBCC',
];
$this->backend = $this->createMock(CalDavBackend::class);
$this->calendarImpl = new CalendarImpl($this->calendar,
$this->calendarInfo, $this->backend);
}
public function testGetKey() {
$this->assertEquals($this->calendarImpl->getKey(), 'fancy_id_123');
}
public function testGetDisplayname() {
$this->assertEquals($this->calendarImpl->getDisplayName(),'user readable name 123');
}
public function testGetDisplayColor() {
$this->assertEquals($this->calendarImpl->getDisplayColor(), '#AABBCC');
}
public function testSearch() {
$this->backend->expects($this->once())
->method('search')
->with($this->calendarInfo, 'abc', ['def'], ['ghi'], 42, 1337)
->will($this->returnValue(['SEARCHRESULTS']));
$result = $this->calendarImpl->search('abc', ['def'], ['ghi'], 42, 1337);
$this->assertEquals($result, ['SEARCHRESULTS']);
}
public function testGetPermissionRead() {
$this->calendar->expects($this->once())
->method('getACL')
->with()
->will($this->returnValue([
['privilege' => '{DAV:}read']
]));
$this->assertEquals(1, $this->calendarImpl->getPermissions());
}
public function testGetPermissionWrite() {
$this->calendar->expects($this->once())
->method('getACL')
->with()
->will($this->returnValue([
['privilege' => '{DAV:}write']
]));
$this->assertEquals(6, $this->calendarImpl->getPermissions());
}
public function testGetPermissionReadWrite() {
$this->calendar->expects($this->once())
->method('getACL')
->with()
->will($this->returnValue([
['privilege' => '{DAV:}read'],
['privilege' => '{DAV:}write']
]));
$this->assertEquals(7, $this->calendarImpl->getPermissions());
}
public function testGetPermissionAll() {
$this->calendar->expects($this->once())
->method('getACL')
->with()
->will($this->returnValue([
['privilege' => '{DAV:}all']
]));
$this->assertEquals(31, $this->calendarImpl->getPermissions());
}
}

@ -0,0 +1,81 @@
<?php
/**
* @copyright 2017, Georg Ehrke <oc.list@georgehrke.com>
*
* @author Georg Ehrke <oc.list@georgehrke.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\DAV\Tests\unit\CalDAV;
use OC\Calendar\Manager;
use OCA\DAV\CalDAV\CalDavBackend;
use OCA\DAV\CalDAV\CalendarImpl;
use OCA\DAV\CalDAV\CalendarManager;
use OCP\Calendar\IManager;
use OCP\IL10N;
class CalendarManagerTest extends \Test\TestCase {
/** @var CalDavBackend | \PHPUnit_Framework_MockObject_MockObject */
private $backend;
/** @var IL10N | \PHPUnit_Framework_MockObject_MockObject */
private $l10n;
/** @var CalendarManager */
private $manager;
protected function setUp() {
parent::setUp();
$this->backend = $this->createMock(CalDavBackend::class);
$this->l10n = $this->createMock(IL10N::class);
$this->manager = new CalendarManager($this->backend,
$this->l10n);
}
public function testSetupCalendarProvider() {
$this->backend->expects($this->once())
->method('getCalendarsForUser')
->with('principals/users/user123')
->will($this->returnValue([
['id' => 123, 'uri' => 'blablub1'],
['id' => 456, 'uri' => 'blablub2'],
]));
/** @var IManager | \PHPUnit_Framework_MockObject_MockObject $calendarManager */
$calendarManager = $this->createMock(Manager::class);
$calendarManager->expects($this->at(0))
->method('registerCalendar')
->will($this->returnCallback(function() {
$parameter = func_get_arg(0);
$this->assertInstanceOf(CalendarImpl::class, $parameter);
$this->assertEquals(123, $parameter->getKey());
}));
$calendarManager->expects($this->at(1))
->method('registerCalendar')
->will($this->returnCallback(function() {
$parameter = func_get_arg(0);
$this->assertInstanceOf(CalendarImpl::class, $parameter);
$this->assertEquals(456, $parameter->getKey());
}));
$this->manager->setupCalendarProvider($calendarManager, 'user123');
}
}
Loading…
Cancel
Save