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(notification): 🔔 API for "Remind me later" #10079

Merged
merged 6 commits into from
Aug 3, 2023
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
4 changes: 4 additions & 0 deletions appinfo/routes/routesChatController.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@
['name' => 'Chat#deleteMessage', 'url' => '/api/{apiVersion}/chat/{token}/{messageId}', 'verb' => 'DELETE', 'requirements' => $requirementsWithMessageId],
/** @see \OCA\Talk\Controller\ChatController::getMessageContext() */
['name' => 'Chat#getMessageContext', 'url' => '/api/{apiVersion}/chat/{token}/{messageId}/context', 'verb' => 'GET', 'requirements' => $requirementsWithMessageId],
/** @see \OCA\Talk\Controller\ChatController::remindLater() */
['name' => 'Chat#remindLater', 'url' => '/api/{apiVersion}/chat/{token}/{messageId}/reminder', 'verb' => 'POST', 'requirements' => $requirementsWithMessageId],
/** @see \OCA\Talk\Controller\ChatController::dismissReminder() */
['name' => 'Chat#dismissReminder', 'url' => '/api/{apiVersion}/chat/{token}/{messageId}/reminder', 'verb' => 'DELETE', 'requirements' => $requirementsWithMessageId],
/** @see \OCA\Talk\Controller\ChatController::setReadMarker() */
['name' => 'Chat#setReadMarker', 'url' => '/api/{apiVersion}/chat/{token}/read', 'verb' => 'POST', 'requirements' => $requirements],
/** @see \OCA\Talk\Controller\ChatController::markUnread() */
Expand Down
3 changes: 2 additions & 1 deletion docs/capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,4 +122,5 @@
* `config => chat => typing-privacy` - User defined numeric value to enable 1 or disable 0 the typing indicator to other users
* `typing-privacy` - Support toggle typing privacy

## 18
## 17.1
* `remind-me-later` - Support for "Remind me later" for chat messages exists
32 changes: 32 additions & 0 deletions docs/chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,38 @@ See [OCP\RichObjectStrings\Definitions](https://github.com/nextcloud/server/blob
The parent message is the object of the deleted message with the replaced text "Message deleted by you".
This message should **NOT** be displayed to the user but instead be used to remove the original message from any cache/storage of the device.

## Remind me later

* Required capability: `remind-me-later`
* Method: `POST`
* Endpoint: `/chat/{token}/{messageId}/reminder`
* Data:

| field | type | Description |
|-------------|------|-----------------------------------------------------------------------------------------------------------------------------------------------------|
| `timestamp` | int | Timestamp when the notification should be triggered. Preferable options for 6pm today, 8am tomorrow, Saturday 8am and Monday 8am should be offered. |

* Response:
- Status code:
+ `201 Created`
+ `401 Unauthorized` when the user is not logged in
+ `404 Not Found` When the message could not be found in the room
+ `404 Not Found` When the room could not be found for the participant,
or the participant is a guest.

## Delete reminder notification

* Required capability: `remind-me-later`
* Method: `DELETE`
* Endpoint: `/chat/{token}/{messageId}/reminder`

* Response:
- Status code:
+ `200 OK`
+ `401 Unauthorized` when the user is not logged in
+ `404 Not Found` When the message could not be found in the room
+ `404 Not Found` When the room could not be found for the participant,
or the participant is a guest.

## Mark chat as read

Expand Down
97 changes: 97 additions & 0 deletions lib/BackgroundJob/ChatMessageReminder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php

declare(strict_types=1);

/*
* @copyright Copyright (c) 2023 Joas Schilling <[email protected]>
*
* @author Joas Schilling <[email protected]>
*
* @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\Talk\BackgroundJob;

use OCA\Talk\AppInfo\Application;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\BackgroundJob\Job;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
use OCP\Notification\IManager;
use Psr\Log\LoggerInterface;

class ChatMessageReminder extends Job {
public function __construct(
ITimeFactory $time,
protected IDBConnection $connection,
protected IManager $notificationManager,
protected LoggerInterface $logger,
) {
parent::__construct($time);
}

public function start(IJobList $jobList): void {
$timeUntilExecution = $this->argument['execute-after'] - $this->time->getTime();

if ($timeUntilExecution <= 0) {
parent::start($jobList);
$jobList->remove($this, $this->argument);
} elseif ($timeUntilExecution > 900) {
// Execution is quite far in the future. In order to not check the
// job too often, we update it's test time to be closer to the execution
$this->setLastRunCloseToExecutionTime(
$this->argument['execute-after'],
$this->argument['token'],
$this->argument['user'],
$this->argument['message_id'],
);
}
}

/**
* @psalm-param array{token: string, message_id: string, message_actor_type: string, message_actor_id: string, user: string, execute-after: int} $argument
*/
protected function run($argument): void {
$notification = $this->notificationManager->createNotification();
$notification->setApp(Application::APP_ID)
->setUser($argument['user'])
->setObject('reminder', $argument['token'])
->setDateTime($this->time->getDateTime('@' . $this->argument['execute-after']))
->setSubject('reminder', [
'token' => $argument['token'],
'message' => $argument['message_id'],
'userType' => $argument['message_actor_type'],
'userId' => $argument['message_actor_id'],
])
->setMessage('reminder', [
'commentId' => $argument['message_id'],
]);
$this->notificationManager->notify($notification);
}

protected function setLastRunCloseToExecutionTime(int $timestamp, string $token, string $userId, string $message): void {
$query = $this->connection->getQueryBuilder();

$query->update('jobs')
->set('last_run', $query->createNamedParameter($timestamp, IQueryBuilder::PARAM_INT))
->where($query->expr()->eq('id', $query->createNamedParameter($this->getId(), IQueryBuilder::PARAM_INT)));
$query->executeStatement();

$this->logger->debug('Updated chat message reminder last_run to ' . $timestamp . ' for token "' . $token . '" user "' . $userId . '" message ' . $message);
}
}
1 change: 1 addition & 0 deletions lib/Capabilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ public function getCapabilities(): array {
'single-conversation-status',
'chat-keep-notifications',
'typing-privacy',
'remind-me-later',
],
'config' => [
'attachments' => [
Expand Down
26 changes: 26 additions & 0 deletions lib/Chat/ChatManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
use DateInterval;
use OC\Memcache\ArrayCache;
use OC\Memcache\NullCache;
use OCA\Talk\AppInfo\Application;
use OCA\Talk\BackgroundJob\ChatMessageReminder;
use OCA\Talk\Events\ChatEvent;
use OCA\Talk\Events\ChatParticipantEvent;
use OCA\Talk\Exceptions\ParticipantNotFoundException;
Expand All @@ -41,6 +43,7 @@
use OCA\Talk\Share\RoomShareProvider;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\BackgroundJob\IJobList;
use OCP\Collaboration\Reference\IReferenceManager;
use OCP\Comments\IComment;
use OCP\Comments\ICommentsManager;
Expand Down Expand Up @@ -101,6 +104,7 @@ public function __construct(
protected ITimeFactory $timeFactory,
protected AttachmentService $attachmentService,
protected IReferenceManager $referenceManager,
protected IJobList $jobList,
) {
$this->cache = $cacheFactory->createDistributed('talk/lastmsgid');
$this->unreadCountCache = $cacheFactory->createDistributed('talk/unreadcount');
Expand Down Expand Up @@ -720,6 +724,28 @@ public function getMessagesById(Room $chat, array $commentIds): array {
return $comments;
}

public function queueRemindLaterBackgroundJob(Room $chat, IComment $comment, Attendee $attendee, int $timestamp): void {
$this->jobList->add(ChatMessageReminder::class, [
'execute-after' => $timestamp,
'token' => $chat->getToken(),
'message_id' => $comment->getId(),
'message_actor_type' => $comment->getActorType(),
'message_actor_id' => $comment->getActorId(),
'user' => $attendee->getActorId(),
]);
}

public function dismissReminderNotification(Room $chat, IComment $comment, Attendee $attendee): void {
$notification = $this->notificationManager->createNotification();
$notification->setApp(Application::APP_ID)
->setUser($attendee->getActorId())
->setObject('reminder', $chat->getToken())
->setMessage('reminder', [
'commentId' => $comment->getId(),
]);
$this->notificationManager->markProcessed($notification);
}

/**
* Search for comments with a given content
*
Expand Down
1 change: 1 addition & 0 deletions lib/Chat/Notifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ public function removePendingNotificationsForRoom(Room $chat, bool $chatOnly = f

$objectTypes = [
'chat',
'reminder',
];
if (!$chatOnly) {
$objectTypes = [
Expand Down
42 changes: 42 additions & 0 deletions lib/Controller/ChatController.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use OCA\Talk\Chat\ReactionManager;
use OCA\Talk\GuestManager;
use OCA\Talk\MatterbridgeManager;
use OCA\Talk\Middleware\Attribute\RequireLoggedInParticipant;
use OCA\Talk\Middleware\Attribute\RequireModeratorOrNoLobby;
use OCA\Talk\Middleware\Attribute\RequireModeratorParticipant;
use OCA\Talk\Middleware\Attribute\RequireParticipant;
Expand All @@ -51,6 +52,7 @@
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\Attribute\PublicPage;
use OCP\AppFramework\Http\Attribute\UserRateLimit;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\Collaboration\AutoComplete\IManager;
Expand Down Expand Up @@ -683,6 +685,46 @@ public function deleteMessage(int $messageId): DataResponse {
return $response;
}

#[NoAdminRequired]
#[RequireModeratorOrNoLobby]
#[RequireLoggedInParticipant]
#[UserRateLimit(limit: 60, period: 3600)]
public function remindLater(int $messageId, int $timestamp): DataResponse {
try {
$message = $this->chatManager->getComment($this->room, (string) $messageId);
} catch (NotFoundException) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}

$this->chatManager->queueRemindLaterBackgroundJob(
$this->room,
$message,
$this->participant->getAttendee(),
$timestamp
);

return new DataResponse([], Http::STATUS_CREATED);
}

#[NoAdminRequired]
#[RequireModeratorOrNoLobby]
#[RequireLoggedInParticipant]
public function dismissReminder(int $messageId): DataResponse {
try {
$message = $this->chatManager->getComment($this->room, (string) $messageId);
} catch (NotFoundException) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}

$this->chatManager->dismissReminderNotification(
$this->room,
$message,
$this->participant->getAttendee()
);

return new DataResponse([], Http::STATUS_OK);
}

#[NoAdminRequired]
#[RequireModeratorParticipant]
#[RequireReadWriteConversation]
Expand Down
Loading
Loading