Skip to content
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
9 changes: 9 additions & 0 deletions appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,15 @@
'token' => '^[a-z0-9]{4,30}$',
],
],
[
'name' => 'Chat#shareObjectToChat',
'url' => '/api/{apiVersion}/chat/{token}/share',
'verb' => 'POST',
'requirements' => [
'apiVersion' => 'v1',
'token' => '^[a-z0-9]{4,30}$',
],
],

/**
* Conversation (Room)
Expand Down
1 change: 1 addition & 0 deletions docs/capabilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,4 @@ title: Capabilities

## 12.0
* `delete-messages` - Allows to delete chat messages up to 6 hours for your own messages or when being a moderator. On deleting the message text will be replaced and a follow up system message will make sure clients and users update it in their cache and storage.
* `rich-object-sharing` - Rich objects can be shared to chats. See [OCP\RichObjectStrings\Definitions](https://github.com/nextcloud/server/blob/master/lib/public/RichObjectStrings/Definitions.php) for more details on supported rich objects and required data.
34 changes: 34 additions & 0 deletions docs/chat.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,40 @@ Base endpoint is: `/ocs/v2.php/apps/spreed/api/v1`
- Data:
The full message array of the new message, as defined in [Receive chat messages of a conversation](#receive-chat-messages-of-a-conversation)

## Share a rich object to the chat

See [OCP\RichObjectStrings\Definitions](https://github.com/nextcloud/server/blob/master/lib/public/RichObjectStrings/Definitions.php) for more details on supported rich objects and required data.

* Required capability: `rich-object-sharing`
* Method: `POST`
* Endpoint: `/chat/{token}/share`
* Data:

field | type | Description
------|------|------------
`objectType` | string | The object type
`objectId` | string | The object id
`metaData` | string | JSON encoded array of the rich objects data
`actorDisplayName` | string | Guest display name (ignored for logged in users)
`referenceId` | string | A reference string to be able to identify the message again in a "get messages" request, should be a random sha256 (only available with `chat-reference-id` capability)

* Response:
- Status code:
+ `201 Created`
+ `400 Bad Request` In case the meta data is invalid
+ `403 Forbidden` When the conversation is read-only
+ `404 Not Found` When the conversation could not be found for the participant
+ `412 Precondition Failed` When the lobby is active and the user is not a moderator
+ `413 Payload Too Large` When the message was longer than the allowed limit of 32000 characters (or 1000 until Nextcloud 16.0.1, check the `spreed => config => chat => max-length` capability for the limit)

- Header:

field | type | Description
------|------|------------
`X-Chat-Last-Common-Read` | int | ID of the last message read by every user that has read privacy set to public. When the user themself has it set to private the value the header is not set (only available with `chat-read-status` capability)

- Data:
The full message array of the new message, as defined in [Receive chat messages of a conversation](#receive-chat-messages-of-a-conversation)

## Deleting a chat message

Expand Down
1 change: 1 addition & 0 deletions lib/Capabilities.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ public function getCapabilities(): array {
'phonebook-search',
'raise-hand',
'room-description',
'rich-object-sharing',
],
'config' => [
'attachments' => [
Expand Down
5 changes: 4 additions & 1 deletion lib/Chat/ChatManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,10 @@ public function addSystemMessage(
$comment->setMessage($message, self::MAX_CHAT_LENGTH);
$comment->setCreationDateTime($creationDateTime);
if ($referenceId !== null) {
$comment->setReferenceId($referenceId);
$referenceId = trim(substr($referenceId, 0, 40));
if ($referenceId !== '') {
$comment->setReferenceId($referenceId);
}
}
if ($parentId !== null) {
$comment->setParentId((string) $parentId);
Expand Down
4 changes: 4 additions & 0 deletions lib/Chat/Parser/SystemMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,10 @@ public function parseMessage(Message $chatMessage): void {
$parsedMessage = $this->l->t('You shared a file which is no longer available');
}
}
} elseif ($message === 'object_shared') {
$parsedParameters['object'] = $parameters['metaData'];
$parsedMessage = '{object}';
$chatMessage->setMessageType('comment');
} elseif ($message === 'matterbridge_config_added') {
$parsedMessage = $this->l->t('{actor} set up Matterbridge to synchronize this conversation with other chats.');
if ($currentUserIsActor) {
Expand Down
146 changes: 112 additions & 34 deletions lib/Controller/ChatController.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@
use OCP\IL10N;
use OCP\IRequest;
use OCP\IUserManager;
use OCP\RichObjectStrings\InvalidObjectExeption;
use OCP\RichObjectStrings\IValidator;
use OCP\User\Events\UserLiveStatusEvent;
use OCP\UserStatus\IManager as IUserStatusManager;
use OCP\UserStatus\IUserStatus;
Expand Down Expand Up @@ -108,6 +110,9 @@ class ChatController extends AEnvironmentAwareController {
/** @var IEventDispatcher */
protected $eventDispatcher;

/** @var IValidator */
protected $richObjectValidator;

/** @var IL10N */
private $l;

Expand All @@ -129,6 +134,7 @@ public function __construct(string $appName,
ISearchResult $searchResult,
ITimeFactory $timeFactory,
IEventDispatcher $eventDispatcher,
IValidator $richObjectValidator,
IL10N $l) {
parent::__construct($appName, $request);

Expand All @@ -148,9 +154,58 @@ public function __construct(string $appName,
$this->searchResult = $searchResult;
$this->timeFactory = $timeFactory;
$this->eventDispatcher = $eventDispatcher;
$this->richObjectValidator = $richObjectValidator;
$this->l = $l;
}

protected function getActorInfo(string $actorDisplayName = ''): array {
if ($this->userId === null) {
$actorType = Attendee::ACTOR_GUESTS;
$sessionId = $this->session->getSessionForRoom($this->room->getToken());
// The character limit for actorId is 64, but the spreed-session is
// 256 characters long, so it has to be hashed to get an ID that
// fits (except if there is no session, as the actorId should be
// empty in that case but sha1('') would generate a hash too
// instead of returning an empty string).
$actorId = $sessionId ? sha1($sessionId) : 'failed-to-get-session';

if ($sessionId && $actorDisplayName) {
$this->guestManager->updateName($this->room, $this->participant, $actorDisplayName);
}
} else {
$actorType = Attendee::ACTOR_USERS;
$actorId = $this->userId;
}

return [$actorType, $actorId];
}

public function parseCommentToResponse(IComment $comment, Message $parentMessage = null): DataResponse {
$chatMessage = $this->messageParser->createMessage($this->room, $this->participant, $comment, $this->l);
$this->messageParser->parseMessage($chatMessage);

if (!$chatMessage->getVisibility()) {
$response = new DataResponse([], Http::STATUS_CREATED);
if ($this->participant->getAttendee()->getReadPrivacy() === Participant::PRIVACY_PUBLIC) {
$response->addHeader('X-Chat-Last-Common-Read', $this->chatManager->getLastCommonReadMessage($this->room));
}
return $response;
}

$this->participantService->updateLastReadMessage($this->participant, (int) $comment->getId());

$data = $chatMessage->toArray();
if ($parentMessage instanceof Message) {
$data['parent'] = $parentMessage->toArray();
}

$response = new DataResponse($data, Http::STATUS_CREATED);
if ($this->participant->getAttendee()->getReadPrivacy() === Participant::PRIVACY_PUBLIC) {
$response->addHeader('X-Chat-Last-Common-Read', $this->chatManager->getLastCommonReadMessage($this->room));
}
return $response;
}

/**
* @PublicPage
* @RequireParticipant
Expand All @@ -171,24 +226,7 @@ public function __construct(string $appName,
* found".
*/
public function sendMessage(string $message, string $actorDisplayName = '', string $referenceId = '', int $replyTo = 0): DataResponse {
if ($this->userId === null) {
$actorType = Attendee::ACTOR_GUESTS;
$sessionId = $this->session->getSessionForRoom($this->room->getToken());
// The character limit for actorId is 64, but the spreed-session is
// 256 characters long, so it has to be hashed to get an ID that
// fits (except if there is no session, as the actorId should be
// empty in that case but sha1('') would generate a hash too
// instead of returning an empty string).
$actorId = $sessionId ? sha1($sessionId) : 'failed-to-get-session';

if ($sessionId && $actorDisplayName) {
$this->guestManager->updateName($this->room, $this->participant, $actorDisplayName);
}
} else {
$actorType = Attendee::ACTOR_USERS;
$actorId = $this->userId;
}

[$actorType, $actorId] = $this->getActorInfo($actorDisplayName);
if (!$actorId) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
Expand Down Expand Up @@ -220,29 +258,69 @@ public function sendMessage(string $message, string $actorDisplayName = '', stri
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}

$chatMessage = $this->messageParser->createMessage($this->room, $this->participant, $comment, $this->l);
$this->messageParser->parseMessage($chatMessage);
return $this->parseCommentToResponse($comment, $parentMessage);
}

if (!$chatMessage->getVisibility()) {
$response = new DataResponse([], Http::STATUS_CREATED);
if ($this->participant->getAttendee()->getReadPrivacy() === Participant::PRIVACY_PUBLIC) {
$response->addHeader('X-Chat-Last-Common-Read', $this->chatManager->getLastCommonReadMessage($this->room));
}
return $response;
/**
* @PublicPage
* @RequireParticipant
* @RequireReadWriteConversation
* @RequireModeratorOrNoLobby
*
* Sends a rich-object to the given room.
*
* The author and timestamp are automatically set to the current user/guest
* and time.
*
* @param string $objectType
* @param string $objectId
* @param string $metaData
* @param string $actorDisplayName
* @param string $referenceId
* @return DataResponse the status code is "201 Created" if successful, and
* "404 Not found" if the room or session for a guest user was not
* found".
*/
public function shareObjectToChat(string $objectType, string $objectId, string $metaData = '', string $actorDisplayName = '', string $referenceId = ''): DataResponse {
[$actorType, $actorId] = $this->getActorInfo($actorDisplayName);
if (!$actorId) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}

$this->participantService->updateLastReadMessage($this->participant, (int) $comment->getId());
$data = $metaData !== '' ? json_decode($metaData, true) : [];
if (!is_array($data)) {
$data = [];
}
$data['type'] = $objectType;
$data['id'] = $objectId;

$data = $chatMessage->toArray();
if ($parentMessage instanceof Message) {
$data['parent'] = $parentMessage->toArray();
try {
$this->richObjectValidator->validate('{object}', ['object' => $data]);
} catch (InvalidObjectExeption $e) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}

$response = new DataResponse($data, Http::STATUS_CREATED);
if ($this->participant->getAttendee()->getReadPrivacy() === Participant::PRIVACY_PUBLIC) {
$response->addHeader('X-Chat-Last-Common-Read', $this->chatManager->getLastCommonReadMessage($this->room));
$this->participantService->ensureOneToOneRoomIsFilled($this->room);
$creationDateTime = $this->timeFactory->getDateTime('now', new \DateTimeZone('UTC'));

$message = json_encode([
'message' => 'object_shared',
'parameters' => [
'objectType' => $objectType,
'objectId' => $objectId,
'metaData' => $data,
],
]);

try {
$comment = $this->chatManager->addSystemMessage($this->room, $actorType, $actorId, $message, $creationDateTime, true, $referenceId);
} catch (MessageTooLongException $e) {
return new DataResponse([], Http::STATUS_REQUEST_ENTITY_TOO_LARGE);
} catch (\Exception $e) {
return new DataResponse([], Http::STATUS_BAD_REQUEST);
}
return $response;

return $this->parseCommentToResponse($comment);
}

/**
Expand Down
30 changes: 30 additions & 0 deletions tests/integration/features/bootstrap/FeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -1102,6 +1102,36 @@ public function userSendsMessageToRoom($user, $message, $identifier, $statusCode
}
}

/**
* @Then /^user "([^"]*)" shares rich-object "([^"]*)" "([^"]*)" '([^']*)' to room "([^"]*)" with (\d+)(?: \((v(1|2|3))\))?$/
*
* @param string $user
* @param string $type
* @param string $id
* @param string $metaData
* @param string $identifier
* @param string $statusCode
* @param string $apiVersion
*/
public function userSharesRichObjectToRoom($user, $type, $id, $metaData, $identifier, $statusCode, $apiVersion = 'v1') {
$this->setCurrentUser($user);
$this->sendRequest(
'POST', '/apps/spreed/api/' . $apiVersion . '/chat/' . self::$identifierToToken[$identifier] . '/share',
new TableNode([
['objectType', $type],
['objectId', $id],
['metaData', $metaData],
])
);
$this->assertStatusCode($this->response, $statusCode);
sleep(1); // make sure Postgres manages the order of the messages

$response = $this->getDataFromResponse($this->response);
if (isset($response['id'])) {
self::$messages['shared::' . $type . '::' . $id] = $response['id'];
}
}

/**
* @Then /^user "([^"]*)" deletes message "([^"]*)" from room "([^"]*)" with (\d+)(?: \((v(1|2|3))\))?$/
*
Expand Down
20 changes: 20 additions & 0 deletions tests/integration/features/chat/rich-object-share.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Feature: chat/public
Background:
Given user "participant1" exists

Scenario: Share a rich object to a chat
Given user "participant1" creates room "public room"
| roomType | 3 |
| roomName | room |
When user "participant1" shares rich-object "call" "R4nd0mT0k3n" '{"name":"Another room","call-type":"group"}' to room "public room" with 201 (v1)
Then user "participant1" sees the following messages in room "public room" with 200
| room | actorType | actorId | actorDisplayName | message | messageParameters |
| public room | users | participant1 | participant1-displayname | {object} | {"actor":{"type":"user","id":"participant1","name":"participant1-displayname"},"object":{"name":"Another room","call-type":"group","type":"call","id":"R4nd0mT0k3n"}} |


Scenario: Share an invalid rich object to a chat
Given user "participant1" creates room "public room"
| roomType | 3 |
| roomName | room |
When user "participant1" shares rich-object "call" "R4nd0mT0k3n" '{"MISSINGname":"Another room","call-type":"group"}' to room "public room" with 400 (v1)
Then user "participant1" sees the following messages in room "public room" with 200
1 change: 1 addition & 0 deletions tests/php/CapabilitiesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ public function setUp(): void {
'phonebook-search',
'raise-hand',
'room-description',
'rich-object-sharing',
];
}

Expand Down
Loading