Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create example event when a user logs in for the first time #6648

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions REUSE.toml
Original file line number Diff line number Diff line change
@@ -29,6 +29,12 @@ precedence = "aggregate"
SPDX-FileCopyrightText = "2020 Nextcloud GmbH and Nextcloud contributors"
SPDX-License-Identifier = "AGPL-3.0-or-later"

[[annotations]]
path = ["tests/assets/ics/example-events/custom-event-expected.ics", "tests/assets/ics/example-events/custom-event.ics", "tests/assets/ics/example-events/custom-event-with-attendees.ics"]
precedence = "aggregate"
SPDX-FileCopyrightText = "2025 Nextcloud GmbH and Nextcloud contributors"
SPDX-License-Identifier = "AGPL-3.0-or-later"

[[annotations]]
path = ["screenshots/2.0/change-view.png", "screenshots/2.0/date-picker.png", "screenshots/2.0/edit-calendar-properties.png", "screenshots/2.0/event-editor-attendees.png", "screenshots/2.0/event-editor-details-categories.jpg", "screenshots/2.0/event-editor-details.png", "screenshots/2.0/event-editor-reminders.png", "screenshots/2.0/event-editor-repeat-day-of-month.png", "screenshots/2.0/event-editor-repeat-last-thursday.png", "screenshots/2.0/freebusy.png", "screenshots/2.0/month-view.png", "screenshots/2.0/new-calendar-selector.png", "screenshots/2.0/public-sharing-embed.png", "screenshots/2.0/public-sharing.png", "screenshots/2.0/share-calendar-publicly-embed-link.png", "screenshots/2.0/share-calendar-user.png", "screenshots/2.0/simple-event-popover.png", "screenshots/2.0/week-view.png"]
precedence = "aggregate"
3 changes: 3 additions & 0 deletions appinfo/info.xml
Original file line number Diff line number Diff line change
@@ -47,6 +47,9 @@
<background-jobs>
<job>OCA\Calendar\BackgroundJob\CleanUpOutdatedBookingsJob</job>
</background-jobs>
<settings>
<admin>OCA\Calendar\Settings\ExampleEventSettings</admin>
</settings>
<navigations>
<navigation>
<id>calendar</id>
3 changes: 3 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
@@ -12,6 +12,7 @@
use OCA\Calendar\Listener\AppointmentBookedListener;
use OCA\Calendar\Listener\CalendarReferenceListener;
use OCA\Calendar\Listener\UserDeletedListener;
use OCA\Calendar\Listener\UserFirstLoginListener;
use OCA\Calendar\Notification\Notifier;
use OCA\Calendar\Profile\AppointmentsAction;
use OCA\Calendar\Reference\ReferenceProvider;
@@ -22,6 +23,7 @@
use OCP\Collaboration\Reference\RenderReferenceEvent;
use OCP\ServerVersion;
use OCP\User\Events\UserDeletedEvent;
use OCP\User\Events\UserFirstTimeLoggedInEvent;
use OCP\Util;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
@@ -53,6 +55,7 @@ public function register(IRegistrationContext $context): void {
$context->registerEventListener(BeforeAppointmentBookedEvent::class, AppointmentBookedListener::class);
$context->registerEventListener(UserDeletedEvent::class, UserDeletedListener::class);
$context->registerEventListener(RenderReferenceEvent::class, CalendarReferenceListener::class);
$context->registerEventListener(UserFirstTimeLoggedInEvent::class, UserFirstLoginListener::class);

$context->registerNotifierService(Notifier::class);
}
49 changes: 49 additions & 0 deletions lib/Controller/ExampleEventController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Calendar\Controller;

use OCA\Calendar\AppInfo\Application;
use OCA\Calendar\Http\JsonResponse;
use OCA\Calendar\Service\ExampleEventService;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\FrontpageRoute;
use OCP\IRequest;

class ExampleEventController extends Controller {
public function __construct(
IRequest $request,
private readonly ExampleEventService $exampleEventService,
) {
parent::__construct(Application::APP_ID, $request);
}

#[FrontpageRoute(verb: 'POST', url: '/v1/exampleEvent/enable')]
public function setCreateExampleEvent(bool $enable): JSONResponse {
$this->exampleEventService->setCreateExampleEvent($enable);
return JsonResponse::success([]);
}

#[FrontpageRoute(verb: 'POST', url: '/v1/exampleEvent/event')]
public function uploadExampleEvent(string $ics): JSONResponse {
if (!$this->exampleEventService->shouldCreateExampleEvent()) {
return JSONResponse::fail([], Http::STATUS_FORBIDDEN);
}

$this->exampleEventService->saveCustomExampleEvent($ics);
return JsonResponse::success([]);
}

#[FrontpageRoute(verb: 'DELETE', url: '/v1/exampleEvent/event')]
public function deleteExampleEvent(): JSONResponse {
$this->exampleEventService->deleteCustomExampleEvent();
return JsonResponse::success([]);
}
}
56 changes: 56 additions & 0 deletions lib/Listener/UserFirstLoginListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Calendar\Listener;

use OCA\Calendar\Exception\ServiceException;
use OCA\Calendar\Service\ExampleEventService;
use OCA\Calendar\Service\NextcloudVersionService;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\User\Events\UserFirstTimeLoggedInEvent;
use Psr\Log\LoggerInterface;

/** @template-implements IEventListener<UserFirstTimeLoggedInEvent> */
class UserFirstLoginListener implements IEventListener {
public function __construct(
private readonly ExampleEventService $exampleEventService,
private readonly LoggerInterface $logger,
private readonly NextcloudVersionService $versionService,
) {
}

public function handle(Event $event): void {
if (!($event instanceof UserFirstTimeLoggedInEvent)) {
return;
}

// TODO: drop condition once we only support Nextcloud >= 31
if (!$this->versionService->is31OrAbove()) {
return;
}

if (!$this->exampleEventService->shouldCreateExampleEvent()) {
return;
}

$userId = $event->getUser()->getUID();
try {
$this->exampleEventService->createExampleEvent($userId);
} catch (ServiceException $e) {
$this->logger->error(
"Failed to create example event for user $userId: " . $e->getMessage(),
[
'exception' => $e,
'userId' => $userId,
],
);
}
}
}
177 changes: 177 additions & 0 deletions lib/Service/ExampleEventService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Calendar\Service;

use OCA\Calendar\AppInfo\Application;
use OCA\Calendar\Exception\ServiceException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Calendar\ICreateFromString;
use OCP\Calendar\IManager as ICalendarManager;
use OCP\Files\IAppData;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\IAppConfig;
use OCP\Security\ISecureRandom;
use Sabre\VObject\Component\VCalendar;
use Sabre\VObject\Component\VEvent;

class ExampleEventService {
private const FOLDER_NAME = 'example_event';
private const FILE_NAME = 'example_event.ics';
private const ENABLE_CONFIG_KEY = 'create_example_event';

public function __construct(
private readonly ICalendarManager $calendarManager,
private readonly ISecureRandom $random,
private readonly ITimeFactory $time,
private readonly IAppData $appData,
private readonly IAppConfig $appConfig,
) {
}

public function createExampleEvent(string $userId): void {
$calendars = $this->calendarManager->getCalendarsForPrincipal("principals/users/$userId");
if ($calendars === []) {
throw new ServiceException("User $userId has no calendars");
}

/** @var ICreateFromString $firstCalendar */
$firstCalendar = $calendars[0];

$customIcs = $this->getCustomExampleEvent();
if ($customIcs === null) {
$this->createDefaultEvent($firstCalendar);
return;
}

// TODO: parsing should be handled inside OCP
try {
$vCalendar = \Sabre\VObject\Reader::read($customIcs);
if (!($vCalendar instanceof VCalendar)) {
throw new ServiceException('Custom event does not contain a VCALENDAR component');
}

/** @var VEvent|null $vEvent */
$vEvent = $vCalendar->getBaseComponent('VEVENT');
if ($vEvent === null) {
throw new ServiceException('Custom event does not contain a VEVENT component');
}
} catch (\Exception $e) {
throw new ServiceException('Failed to parse custom event: ' . $e->getMessage(), 0, $e);
}

$uid = $this->random->generate(32, ISecureRandom::CHAR_ALPHANUMERIC);
$vEvent->UID = $uid;
$vEvent->DTSTART = $this->getStartDate();
$vEvent->DTEND = $this->getEndDate();
$vEvent->remove('ORGANIZER');
$vEvent->remove('ATTENDEE');
$firstCalendar->createFromString("$uid.ics", $vCalendar->serialize());
}

private function getStartDate(): \DateTimeInterface {
return $this->time->now()
->add(new \DateInterval('P7D'))
->setTime(10, 00);
}

private function getEndDate(): \DateTimeInterface {
return $this->time->now()
->add(new \DateInterval('P7D'))
->setTime(11, 00);
}

private function createDefaultEvent(ICreateFromString $calendar): void {
$defaultDescription = <<<EOF
Welcome to Nextcloud Calendar!

This is a sample event - explore the flexibility of planning with Nextcloud Calendar by making any edits you want!

With Nextcloud Calendar, you can:
- Create, edit, and manage events effortlessly.
- Create multiple calendars and share them with teammates, friends, or family.
- Check availability and display your busy times to others.
- Seamlessly integrate with apps and devices via CalDAV.
- Customize your experience: schedule recurring events, adjust notifications and other settings.
EOF;

st3iny marked this conversation as resolved.
Show resolved Hide resolved
$eventBuilder = $this->calendarManager->createEventBuilder();
$eventBuilder->setSummary('Example event - open me!');
$eventBuilder->setDescription($defaultDescription);
$eventBuilder->setStartDate($this->getStartDate());
$eventBuilder->setEndDate($this->getEndDate());
$eventBuilder->createInCalendar($calendar);
}

/**
* @return string|null The ics of the custom example event or null if no custom event was uploaded.
* @throws ServiceException If reading the custom ics file fails.
*/
private function getCustomExampleEvent(): ?string {
try {
$folder = $this->appData->getFolder(self::FOLDER_NAME);
$icsFile = $folder->getFile(self::FILE_NAME);
} catch (NotFoundException $e) {
return null;
}

try {
return $icsFile->getContent();
} catch (NotFoundException|NotPermittedException $e) {
throw new ServiceException(
'Failed to read custom example event',
0,
$e,
);
}
}

public function saveCustomExampleEvent(string $ics): void {
try {
$folder = $this->appData->getFolder(self::FOLDER_NAME);
} catch (NotFoundException $e) {
$folder = $this->appData->newFolder(self::FOLDER_NAME);
}

try {
$existingFile = $folder->getFile(self::FILE_NAME);
$existingFile->putContent($ics);
} catch (NotFoundException $e) {
$folder->newFile(self::FILE_NAME, $ics);
}
}

public function deleteCustomExampleEvent(): void {
try {
$folder = $this->appData->getFolder(self::FOLDER_NAME);
$file = $folder->getFile(self::FILE_NAME);
} catch (NotFoundException $e) {
return;
}

$file->delete();
}

public function hasCustomExampleEvent(): bool {
try {
return $this->getCustomExampleEvent() !== null;
} catch (ServiceException $e) {
return false;
}
}

public function setCreateExampleEvent(bool $enable) {
$this->appConfig->setValueBool(Application::APP_ID, self::ENABLE_CONFIG_KEY, $enable);
}

public function shouldCreateExampleEvent(): bool {
return $this->appConfig->getValueBool(Application::APP_ID, self::ENABLE_CONFIG_KEY, true);
}
}
41 changes: 41 additions & 0 deletions lib/Service/NextcloudVersionService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Calendar\Service;

use OCP\ServerVersion;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;

class NextcloudVersionService {
private ?ServerVersion $serverVersion;

public function __construct(
private readonly ContainerInterface $container,
) {
}

private function getMajorVersion(): int {
if ($this->serverVersion === null) {
// ServerVersion was added in 31, but we don't care about older versions anyway
try {
/** @var ServerVersion $serverVersion */
$this->serverVersion = $this->container->get(ServerVersion::class);
} catch (ContainerExceptionInterface $e) {
return 0;
}
}

return $this->serverVersion->getMajorVersion();
}

public function is31OrAbove(): bool {
return $this->getMajorVersion() >= 31;
}
}
Loading

Unchanged files with check annotations Beta

<template #icon>
<CalendarMinus :size="20" />
</template>
<template>

Check warning on line 71 in src/components/AppNavigation/CalendarList.vue

GitHub Actions / NPM lint

`<template>` require directive
<div v-if="!isPublic">
<draggable v-model="sortedCalendars.hidden"
:disabled="disableDragging"
</NcAppNavigationItem>
<!-- The header slot must be placed here, otherwise vuedraggable adds undefined as item to the array -->
<template>

Check warning on line 93 in src/components/AppNavigation/CalendarList.vue

GitHub Actions / NPM lint

`<template>` require directive
<CalendarListItemLoadingPlaceholder v-if="loadingCalendars" />
</template>
</div>
/**
* Function to filter results in NcSelect
*
* @param {object} option

Check warning on line 105 in src/components/AppNavigation/EditCalendarModal/SharingSearch.vue

GitHub Actions / NPM lint

Missing JSDoc @param "option" description
* @param {string} label

Check warning on line 106 in src/components/AppNavigation/EditCalendarModal/SharingSearch.vue

GitHub Actions / NPM lint

Missing JSDoc @param "label" description
* @param {string} search

Check warning on line 107 in src/components/AppNavigation/EditCalendarModal/SharingSearch.vue

GitHub Actions / NPM lint

Missing JSDoc @param "search" description
*/
filterResults(option, label, search) {
return true
type: Boolean,
default: false,
},
url: {

Check warning on line 66 in src/components/CalendarGrid.vue

GitHub Actions / NPM lint

Prop 'url' requires default value to be set
type: String,
required: false,
},
/**
* FullCalendar Plugins
*
* @return {(PluginDef)[]}

Check warning on line 161 in src/components/CalendarGrid.vue

GitHub Actions / NPM lint

The type 'PluginDef' is undefined
*/
plugins() {
return [
type: String,
required: true,
},
scheduleStatus: {

Check warning on line 57 in src/components/Editor/AvatarParticipationStatus.vue

GitHub Actions / NPM lint

Prop 'scheduleStatus' requires default value to be set
type: String,
required: false,
},
},
computed: {
/**
* @return {icon: object, fillColor: string|undefined, text: string}

Check warning on line 92 in src/components/Editor/AvatarParticipationStatus.vue

GitHub Actions / NPM lint

Syntax error in type: icon: object, fillColor: string|undefined, text: string
*/
status() {
const acceptedIcon = {
:style="{ 'background-color': value.color }" />
</div>
</template>
<template>

Check warning on line 22 in src/components/Editor/CalendarPickerHeader.vue

GitHub Actions / NPM lint

`<template>` require directive
<NcActionButton v-for="calendar in calendars"
:key="calendar.id"
:close-after-click="true"