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

fix: Emit notification on mentions #3960

Merged
merged 1 commit into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,7 @@

['name' => 'TemplateField#extractFields', 'url' => '/api/v1/template/fields/extract/{fileId}', 'verb' => 'GET'],
['name' => 'TemplateField#fillFields', 'url' => '/api/v1/template/fields/fill/{fileId}', 'verb' => 'POST'],

['name' => 'Mention#mention', 'url' => '/api/v1/mention/{fileId}', 'verb' => 'POST'],
],
];
2 changes: 2 additions & 0 deletions composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
'OCA\\Richdocuments\\Controller\\DocumentController' => $baseDir . '/../lib/Controller/DocumentController.php',
'OCA\\Richdocuments\\Controller\\DocumentTrait' => $baseDir . '/../lib/Controller/DocumentTrait.php',
'OCA\\Richdocuments\\Controller\\FederationController' => $baseDir . '/../lib/Controller/FederationController.php',
'OCA\\Richdocuments\\Controller\\MentionController' => $baseDir . '/../lib/Controller/MentionController.php',
'OCA\\Richdocuments\\Controller\\OCSController' => $baseDir . '/../lib/Controller/OCSController.php',
'OCA\\Richdocuments\\Controller\\SettingsController' => $baseDir . '/../lib/Controller/SettingsController.php',
'OCA\\Richdocuments\\Controller\\TargetController' => $baseDir . '/../lib/Controller/TargetController.php',
Expand Down Expand Up @@ -59,6 +60,7 @@
'OCA\\Richdocuments\\Migration\\Version30709Date20201111104147' => $baseDir . '/../lib/Migration/Version30709Date20201111104147.php',
'OCA\\Richdocuments\\Migration\\Version30717Date20210310164901' => $baseDir . '/../lib/Migration/Version30717Date20210310164901.php',
'OCA\\Richdocuments\\Migration\\Version50200Date20211220212457' => $baseDir . '/../lib/Migration/Version50200Date20211220212457.php',
'OCA\\Richdocuments\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php',
'OCA\\Richdocuments\\PermissionManager' => $baseDir . '/../lib/PermissionManager.php',
'OCA\\Richdocuments\\Preview\\EMF' => $baseDir . '/../lib/Preview/EMF.php',
'OCA\\Richdocuments\\Preview\\MSExcel' => $baseDir . '/../lib/Preview/MSExcel.php',
Expand Down
2 changes: 2 additions & 0 deletions composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class ComposerStaticInitRichdocuments
'OCA\\Richdocuments\\Controller\\DocumentController' => __DIR__ . '/..' . '/../lib/Controller/DocumentController.php',
'OCA\\Richdocuments\\Controller\\DocumentTrait' => __DIR__ . '/..' . '/../lib/Controller/DocumentTrait.php',
'OCA\\Richdocuments\\Controller\\FederationController' => __DIR__ . '/..' . '/../lib/Controller/FederationController.php',
'OCA\\Richdocuments\\Controller\\MentionController' => __DIR__ . '/..' . '/../lib/Controller/MentionController.php',
'OCA\\Richdocuments\\Controller\\OCSController' => __DIR__ . '/..' . '/../lib/Controller/OCSController.php',
'OCA\\Richdocuments\\Controller\\SettingsController' => __DIR__ . '/..' . '/../lib/Controller/SettingsController.php',
'OCA\\Richdocuments\\Controller\\TargetController' => __DIR__ . '/..' . '/../lib/Controller/TargetController.php',
Expand Down Expand Up @@ -92,6 +93,7 @@ class ComposerStaticInitRichdocuments
'OCA\\Richdocuments\\Migration\\Version30709Date20201111104147' => __DIR__ . '/..' . '/../lib/Migration/Version30709Date20201111104147.php',
'OCA\\Richdocuments\\Migration\\Version30717Date20210310164901' => __DIR__ . '/..' . '/../lib/Migration/Version30717Date20210310164901.php',
'OCA\\Richdocuments\\Migration\\Version50200Date20211220212457' => __DIR__ . '/..' . '/../lib/Migration/Version50200Date20211220212457.php',
'OCA\\Richdocuments\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php',
'OCA\\Richdocuments\\PermissionManager' => __DIR__ . '/..' . '/../lib/PermissionManager.php',
'OCA\\Richdocuments\\Preview\\EMF' => __DIR__ . '/..' . '/../lib/Preview/EMF.php',
'OCA\\Richdocuments\\Preview\\MSExcel' => __DIR__ . '/..' . '/../lib/Preview/MSExcel.php',
Expand Down
2 changes: 2 additions & 0 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use OCA\Richdocuments\Listener\RegisterTemplateFileCreatorListener;
use OCA\Richdocuments\Listener\ShareLinkListener;
use OCA\Richdocuments\Middleware\WOPIMiddleware;
use OCA\Richdocuments\Notification\Notifier;
use OCA\Richdocuments\Preview\EMF;
use OCA\Richdocuments\Preview\MSExcel;
use OCA\Richdocuments\Preview\MSWord;
Expand Down Expand Up @@ -80,6 +81,7 @@ public function register(IRegistrationContext $context): void {
$context->registerPreviewProvider(OOXML::class, OOXML::MIMETYPE_REGEX);
$context->registerPreviewProvider(OpenDocument::class, OpenDocument::MIMETYPE_REGEX);
$context->registerPreviewProvider(Pdf::class, Pdf::MIMETYPE_REGEX);
$context->registerNotifierService(Notifier::class);
}

public function boot(IBootContext $context): void {
Expand Down
66 changes: 66 additions & 0 deletions lib/Controller/MentionController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Richdocuments\Controller;

use OCA\Richdocuments\AppInfo\Application;
use OCA\Richdocuments\Notification\Notifier;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\UserRateLimit;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Files\IRootFolder;
use OCP\IRequest;
use OCP\Notification\IManager;

class MentionController extends Controller {
public function __construct(
$appName,
IRequest $request,
private IRootFolder $rootFolder,
private IManager $manager,
private ITimeFactory $timeFactory,
private ?string $userId,
) {
parent::__construct($appName, $request);
}

#[NoAdminRequired]
#[UserRateLimit(limit: 5, period: 120)]
public function mention(int $fileId, string $mention): DataResponse {
$userFolder = $this->rootFolder->getUserFolder($this->userId);
$file = $userFolder->getFirstNodeById($fileId);
if ($file === null) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}

$userFolder = $this->rootFolder->getUserFolder($mention);
$file = $userFolder->getFirstNodeById($fileId);
if ($file === null) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}

$notification = $this->manager->createNotification();
$notification->setUser($mention)
->setApp(Application::APPNAME)
->setSubject(Notifier::TYPE_MENTIONED, [
Notifier::SUBJECT_MENTIONED_SOURCE_USER => $this->userId,
Notifier::SUBJECT_MENTIONED_TARGET_USER => $mention,
])
->setObject('file', (string)$fileId);

if ($this->manager->getCount($notification) === 0) {
$notification->setDateTime(\DateTime::createFromImmutable($this->timeFactory->now()));
$this->manager->notify($notification);
return new DataResponse([], Http::STATUS_OK);

}

return new DataResponse([], Http::STATUS_NOT_FOUND);
}
}
112 changes: 112 additions & 0 deletions lib/Notification/Notifier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php
/**
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

declare(strict_types=1);

namespace OCA\Richdocuments\Notification;

use InvalidArgumentException;
use OC\User\NoUserException;
use OCA\Richdocuments\AppInfo\Application;
use OCP\Files\IRootFolder;
use OCP\Files\NotPermittedException;
use OCP\IURLGenerator;
use OCP\IUserManager;
use OCP\L10N\IFactory;
use OCP\Notification\INotification;
use OCP\Notification\INotifier;

class Notifier implements INotifier {
public const TYPE_MENTIONED = 'mentioned';
public const SUBJECT_MENTIONED_SOURCE_USER = 'sourceUser';
public const SUBJECT_MENTIONED_TARGET_USER = 'targetUser';

public function __construct(
private IFactory $factory,
private IUserManager $userManager,
private IURLGenerator $urlGenerator,
private IRootFolder $rootFolder,
) {
}

public function getID(): string {
return 'richdocuments';
}

public function getName(): string {
return 'Office';
}

public function prepare(INotification $notification, string $languageCode): INotification {
if ($notification->getApp() !== Application::APPNAME) {
throw new InvalidArgumentException('Application should be text instead of ' . $notification->getApp());
}

$l = $this->factory->get(Application::APPNAME, $languageCode);

switch ($notification->getSubject()) {
case self::TYPE_MENTIONED:
$parameters = $notification->getSubjectParameters();
$sourceUser = $parameters[self::SUBJECT_MENTIONED_SOURCE_USER];
$sourceUserDisplayName = $this->userManager->getDisplayName($sourceUser);
$targetUser = $notification->getUser();
$fileId = (int)$notification->getObjectId();

if ($sourceUserDisplayName === null) {
throw new InvalidArgumentException();
}

try {
$userFolder = $this->rootFolder->getUserFolder($targetUser);
} catch (NotPermittedException|NoUserException $e) {
throw new InvalidArgumentException();
}
$node = $userFolder->getFirstNodeById($fileId);

if ($node === null) {
throw new InvalidArgumentException();
}

$fileLink = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $node->getId()]);

$notification->setRichSubject($l->t('{user} has mentioned you in {node}'), [
'user' => [
'type' => 'user',
'id' => $sourceUser,
'name' => $sourceUserDisplayName,
],
'node' => [
'type' => 'file',
'id' => (string)$node->getId(),
'name' => $node->getName(),
'path' => $userFolder->getRelativePath($node->getPath()) ?? '',
'link' => $fileLink,
],
]);
break;
default:
throw new InvalidArgumentException();
}
$notification->setIcon($this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('text', 'app-dark.svg')));
$notification->setLink($fileLink);
$this->setParsedSubjectFromRichSubject($notification);
return $notification;
}

protected function setParsedSubjectFromRichSubject(INotification $notification): void {
$placeholders = $replacements = [];
foreach ($notification->getRichSubjectParameters() as $placeholder => $parameter) {
$placeholders[] = '{' . $placeholder . '}';
if ($parameter['type'] === 'file') {
$replacements[] = $parameter['path'];
} else {
$replacements[] = $parameter['name'];
}
}

$notification->setParsedSubject(str_replace($placeholders, $replacements, $notification->getRichSubject()));
}
}
39 changes: 24 additions & 15 deletions src/mixins/uiMention.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,33 @@ import { getNextcloudUrl } from '../helpers/url.js'

export default {
methods: {
async uiMention(search) {
let users = []
async uiMention({ type, text, username }) {
if (type === 'autocomplete') {
let users = []

if (Config.get('userId') !== null) {
try {
const result = await axios.get(generateOcsUrl('core/autocomplete/get'), {
params: { search },
})
users = result.data.ocs.data
} catch (e) { }
}
if (Config.get('userId') !== null) {
try {
const result = await axios.get(generateOcsUrl('core/autocomplete/get'), {
params: { search: text },
})
users = result.data.ocs.data
} catch (e) {
}
}

const list = users.map((user) => {
const profile = window.location.protocol + '//' + getNextcloudUrl() + '/index.php/u/' + user.id
return { username: user.label, profile }
})
const list = users.map((user) => {
const profile = window.location.protocol + '//' + getNextcloudUrl() + '/index.php/u/' + user.id
return {
username: user.label,
profile,
}
})

this.sendPostMessage('Action_Mention', { list })
this.sendPostMessage('Action_Mention', { list })
}
if (type === 'selected') {
await axios.post(generateOcsUrl(`apps/richdocuments/api/v1/mention/${this.fileid}`), { mention: username })
}
},
},
}
4 changes: 1 addition & 3 deletions src/view/Office.vue
Original file line number Diff line number Diff line change
Expand Up @@ -431,9 +431,7 @@ export default {
})
break
case 'UI_Mention':
if (parsed.args.type === 'autocomplete') {
this.uiMention(parsed.args.text)
}
this.uiMention(parsed.args)
break
case 'UI_CreateFile':
FilesAppIntegration.createNewFile(args.DocumentType)
Expand Down
Loading