Skip to content

gql-server: Allow users to edit and delete chat messages (backend portion) - #21330

Merged
gustavotrott merged 3 commits into
bigbluebutton:v3.0.x-releasefrom
gustavotrott:gql-chat-edit-delete-chat_msg
Oct 2, 2024
Merged

gustavotrott merged 3 commits into
bigbluebutton:v3.0.x-releasefrom
gustavotrott:gql-chat-edit-delete-chat_msg

Conversation

@gustavotrott

@gustavotrott gustavotrott commented Oct 2, 2024 •

Copy link
Copy Markdown
Contributor

This PR introduces two new mutations for editing and deleting chat messages:

mutation($chatId: String!, $messageId: String!, $chatMessageInMarkdownFormat: String!) {
  chatEditMessage(chatId: $chatId, messageId: $messageId, chatMessageInMarkdownFormat: $chatMessageInMarkdownFormat)
}
mutation($chatId: String!, $messageId: String!) {
  chatDeleteMessage(chatId: $chatId, messageId: $messageId)
}

Additionally, three new fields are added to the chat_message type for both public and private chats:

subscription {
  chat_message_public {
    editedAt
    deletedAt
    deletedBy {
      name
    }
  }
}
subscription {
  chat_message_public {
    editedAt
    deletedAt
    deletedBy {
      name
    }
  }
}

A new chat_message_history table has been introduced to store previous versions of edited or deleted messages.

When a message is deleted, its content is set to null, and the deletedAt field is populated. The client should display the message as "This message was removed".

Future work:

  • Message history: While message history is being stored, it is not yet retrievable. In this version, moderators cannot view previous versions of edited or deleted messages. This feature will be added in future PRs.
  • Time limits: Currently, message owners can edit and delete their messages at any time, and moderators can delete any message. A future config will introduce time limits (e.g., 5 minutes) for editing or deleting messages.

It introduces the mutations:
chatEditMessage
chatDeleteMessage

The type chat_message receive two new fields:
updatedAt
deletedAt

A new table chat_message_history was introduced to store the previous version of an edited or deleted message.

When removed the message is not deleted, but the content become null and deletedAt populated. So the idea is to show "This message was removed" in the client.
@gustavotrott gustavotrott added this to the Release 3.0 milestone Oct 2, 2024
@coderabbitai

This comment was marked as off-topic.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 19

🧹 Outside diff range and nitpick comments (18)
bbb-graphql-actions/src/actions/chatEditMessage.ts (2)

5-11: LGTM: Input validation is comprehensive and well-implemented.

The use of throwErrorIfInvalidInput ensures that all required fields are present and of the correct type. This is crucial for maintaining data integrity and preventing runtime errors.

Consider extracting the validation schema to a constant for improved readability:

const EDIT_MESSAGE_SCHEMA = [
  {name: 'chatId', type: 'string', required: true},
  {name: 'messageId', type: 'string', required: true},
  {name: 'chatMessageInMarkdownFormat', type: 'string', required: true},
];

throwErrorIfInvalidInput(input, EDIT_MESSAGE_SCHEMA);

This change would make the validation requirements more visible and easier to maintain.


31-32: LGTM: Return statement correctly assembles the Redis message.

The return statement properly combines all components of the Redis message, adhering to the RedisMessage type.

For consistency with modern JavaScript/TypeScript practices, consider using object property shorthand:

return { eventName, routing, header, body };

This change makes the code slightly more concise while maintaining readability.

bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml (1)

Line range hint 1-50: Overall impact of changes is minimal and aligned with PR objectives.

The additions to the select_permissions for the bbb_client role are focused and consistent with the PR objectives. By including deletedAt and editedAt columns, clients will now be able to track message edits and deletions, which is essential for the new chat message editing and deleting functionality.

These changes:

  1. Maintain the existing structure of the configuration file.
  2. Do not introduce any apparent security issues, as they only affect read permissions.
  3. Are minimal, which is good for maintainability.

Consider the following for future improvements:

  1. Implement a mechanism to limit the time window for editing or deleting messages, as mentioned in the PR objectives for future work.
  2. Ensure that the frontend appropriately handles the display of edited and deleted messages based on these new fields.
  3. Plan for the implementation of message history retrieval for moderators, as mentioned in the PR objectives.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageMsgHdlr.scala (1)

62-62: Optimized user participation check

Excellent change from chat.users.filter(u => u.id == sender.id).length > 0 to chat.users.exists(u => u.id == sender.id). This is more efficient as exists short-circuits once a match is found, potentially improving performance for large chat groups. It's also more idiomatic Scala and improves readability.

For even better performance, consider extracting sender.id to avoid repeated access:

val senderId = sender.id
val userIsAParticipant = chat.users.exists(_.id == senderId)

This minor optimization could be beneficial if sender.id is a computed property rather than a simple field access.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChat.scala (1)

46-58: Overall, the changes align well with the PR objectives and existing codebase structure.

The new methods updateGroupChatMessage and deleteGroupChatMessage have been successfully implemented in the GroupChatApp object, allowing for the editing and deletion of chat messages as per the PR objectives. These additions integrate well with the existing codebase and follow established patterns.

However, to ensure full integration and functionality, consider the following:

  1. Update related components: Ensure that other parts of the application that handle chat messages are updated to use these new methods.
  2. Testing: Add comprehensive unit tests for these new methods to verify their behavior under various scenarios.
  3. Documentation: Update any relevant documentation to reflect these new capabilities in the chat system.

To fully leverage these new capabilities, you might want to:

  1. Implement a message history retrieval system for moderators, as mentioned in the PR objectives for future work.
  2. Consider adding a time limit for editing or deleting messages, also mentioned as future work.
  3. Ensure that the frontend is updated to support these new backend capabilities, providing a seamless user experience for editing and deleting messages.
bbb-graphql-server/metadata/actions.graphql (2)

98-103: LGTM with a minor suggestion.

The chatDeleteMessage mutation is well-defined and aligns with the PR objectives. The parameter types and return type are appropriate for the operation.

Consider adding a brief description comment above the mutation to explain its purpose and any side effects, such as:

# Deletes a specific message from a chat. Returns true if successful, false otherwise.
# Note: This action cannot be undone, and the message will be moved to chat_message_history.
type Mutation {
  chatDeleteMessage(
    chatId: String!
    messageId: String!
  ): Boolean
}

105-111: LGTM with a minor suggestion.

The chatEditMessage mutation is well-defined and aligns with the PR objectives. The parameter types and return type are appropriate for the operation.

Consider adding a brief description comment above the mutation to explain its purpose and any side effects, such as:

# Edits a specific message in a chat. Returns true if successful, false otherwise.
# Note: The original message will be preserved in chat_message_history.
type Mutation {
  chatEditMessage(
    chatId: String!
    messageId: String!
    chatMessageInMarkdownFormat: String!
  ): Boolean
}
akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/AnalyticsActor.scala (1)

138-139: LGTM! Consider grouping chat-related cases for better readability.

The addition of EditGroupChatMessageReqMsg and DeleteGroupChatMessageReqMsg cases aligns well with the PR objectives and maintains consistency with existing chat message handling. Good job on using the logChatMessage method, which respects the includeChat flag.

To improve code organization and readability, consider grouping all chat-related cases together. This could make it easier to maintain and understand the chat-specific message handling in the future.

Here's a suggestion for grouping chat-related cases:

// Group Chats
case m: SendGroupChatMessageMsg => logChatMessage(msg)
case m: EditGroupChatMessageReqMsg => logChatMessage(msg)
case m: DeleteGroupChatMessageReqMsg => logChatMessage(msg)
case m: GroupChatMessageBroadcastEvtMsg => logChatMessage(msg)
case m: GetGroupChatMsgsReqMsg => logChatMessage(msg)
case m: GetGroupChatMsgsRespMsg => logChatMessage(msg)
case m: CreateGroupChatReqMsg => logChatMessage(msg)
case m: SetGroupChatLastSeenReqMsg => logChatMessage(msg)
case m: SetGroupChatVisibleReqMsg => logChatMessage(msg)
case m: GroupChatCreatedEvtMsg => logChatMessage(msg)
case m: GetGroupChatsReqMsg => logChatMessage(msg)
case m: GetGroupChatsRespMsg => logChatMessage(msg)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/HandlerHelpers.scala (2)

312-319: LGTM! Consider adding a comment for consistency.

The implementation of buildGroupChatMessageEditedEvtMsg looks good and aligns with the PR objectives. It correctly constructs the event message for edited chat messages.

For consistency with other methods in this trait, consider adding a brief comment describing the purpose of this method, e.g.:

// Builds an event message when a group chat message is edited
def buildGroupChatMessageEditedEvtMsg(meetingId: String, chatId: String, userId: String, msg: GroupChatMessage): BbbCommonEnvCoreMsg = {
  // ... (existing implementation)
}

321-328: LGTM! Consider adding a comment for consistency.

The implementation of buildGroupChatMessageDeletedEvtMsg is correct and aligns with the PR objectives. It properly constructs the event message for deleted chat messages.

For consistency with other methods in this trait, consider adding a brief comment describing the purpose of this method, e.g.:

// Builds an event message when a group chat message is deleted
def buildGroupChatMessageDeletedEvtMsg(meetingId: String, chatId: String, userId: String, messageId: String): BbbCommonEnvCoreMsg = {
  // ... (existing implementation)
}
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1)

708-713: LGTM! Consider adding logging for consistency.

The new message handlers for editing and deleting group chat messages are implemented correctly and consistently with other handlers in the file. Good job on updating the state and user activity.

For consistency with other message handlers, consider adding debug logging statements to these new handlers. This would help with troubleshooting and monitoring.

Example logging statement:

log.debug(s"Handling ${m.getClass.getSimpleName} for user ${m.header.userId}")
bbb-graphql-server/bbb_schema.sql (2)

1040-1052: New chat_message_history table added

The new chat_message_history table has been added to store the history of edited messages. This aligns with the PR objectives and provides a way to track message versions.

The table structure includes:

  • messageId (references chat_message)
  • meetingId
  • messageVersionSequence
  • message
  • senderId
  • createdAt
  • movedToHistoryAt

This design allows for efficient tracking of message edits.

Consider adding a foreign key constraint on (meetingId, senderId) referencing the user table to ensure data integrity:

FOREIGN KEY ("meetingId", "senderId") REFERENCES "user"("meetingId","userId") ON DELETE SET NULL

1054-1073: New trigger function for tracking message edits

The update_chat_message_history_trigger_func function and its associated trigger have been added to track message edits. This implementation aligns with the PR objectives and efficiently manages the history of edited messages.

Key points:

  1. The function is triggered before an update on the chat_message table.
  2. It checks if the message content has changed.
  3. If changed, it inserts a new record into chat_message_history with the old message content.

Consider adding a check for the editedAt column to ensure it's updated when a message is edited:

IF NEW."message" IS DISTINCT FROM OLD."message" THEN
    NEW."editedAt" := current_timestamp;
    insert into "chat_message_history"...
END IF;

This ensures that the editedAt timestamp is always set when a message is edited.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReqMsgHdlr.scala (3)

16-19: Avoid mutable variables by using immutable val

Using var for chatLocked, chatLockedForUser, and newState introduces mutable state. Consider refactoring the code to use immutable val and functional constructs to enhance code safety and readability.

Example refactor:

  • Use foldLeft or pattern matching to thread the state without mutation.
  • Pass chatLocked and chatLockedForUser as parameters or compute them within their usage scope.

65-69: Reconsider ejecting users for permission issues

Ejecting a user from the meeting for lacking permission to delete a message might be too harsh. Instead, consider sending an error response or notification indicating that the action is not permitted.

Apply this diff to send an error response:

-         PermissionCheck.ejectUserForFailedPermission(msg.header.meetingId, msg.header.userId, reason, bus.outGW, liveMeeting)
+         val errorMsg = buildErrorResponse(msg.header.meetingId, msg.header.userId, reason)
+         bus.outGW.send(errorMsg)

Please ensure that buildErrorResponse is implemented to create an appropriate error message format.


15-17: Consider combining related flag variables

The variables chatLocked and chatLockedForUser both indicate some form of chat restriction. Consider combining them into a single variable or a case class that represents the chat's lock status for clearer code semantics.

Example:

case class ChatLockStatus(isLocked: Boolean, isLockedForUser: Boolean)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/EditGroupChatMessageReqMsgHdlr.scala (2)

25-27: Use the userIsModerator variable for consistency

Now that userIsModerator accurately represents whether the user is a moderator, use this variable in your conditionals for better readability and consistency.

Apply this diff:

-if (groupChat.access == GroupChatAccess.PUBLIC && user.userLockSettings.disablePublicChat && user.role != Roles.MODERATOR_ROLE) {
+if (groupChat.access == GroupChatAccess.PUBLIC && user.userLockSettings.disablePublicChat && !userIsModerator) {

51-55: Simplify and clarify conditional logic

The nested conditional statements can be complex to read and maintain. Consider simplifying the logic or extracting conditions into well-named variables or methods for better readability.

For example:

val canEditMessage = (chatIsPrivate && userIsAParticipant || !chatIsPrivate) && userIsOwner

if (canEditMessage) {
  // proceed with editing
} else {
  // handle permission errors
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d4d23cc and 8dd48b5.

📒 Files selected for processing (18)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReqMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/EditGroupChatMessageReqMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChat.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChatHdlrs.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageMsgHdlr.scala (3 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala (5 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/pubsub/senders/ReceivedJsonMsgHandlerActor.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/HandlerHelpers.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/AnalyticsActor.scala (1 hunks)
  • bbb-common-message/src/main/scala/org/bigbluebutton/common2/msgs/GroupChatMsg.scala (1 hunks)
  • bbb-graphql-actions/src/actions/chatDeleteMessage.ts (1 hunks)
  • bbb-graphql-actions/src/actions/chatEditMessage.ts (1 hunks)
  • bbb-graphql-server/bbb_schema.sql (3 hunks)
  • bbb-graphql-server/metadata/actions.graphql (1 hunks)
  • bbb-graphql-server/metadata/actions.yaml (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_private.yaml (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml (2 hunks)
🧰 Additional context used
🪛 Biome
bbb-graphql-actions/src/actions/chatDeleteMessage.ts

[error] 14-14: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)


[error] 15-15: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)

bbb-graphql-actions/src/actions/chatEditMessage.ts

[error] 15-15: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)


[error] 16-16: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)

🔇 Additional comments (34)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChatHdlrs.scala (3)

12-13: LGTM! The new traits are well-integrated.

The addition of EditGroupChatMessageReqMsgHdlr and DeleteGroupChatMessageReqMsgHdlr traits to the GroupChatHdlrs class aligns well with the PR objectives. These new handlers extend the functionality to support editing and deleting chat messages, which is consistent with the overall purpose of the class.

The changes are minimal and focused, maintaining the existing structure and following the established pattern of composing multiple traits. This approach adheres to the single responsibility principle and promotes modularity.


12-13: Ensure proper access control and validation

With the introduction of message editing and deletion functionality, it's crucial to implement robust access control and validation mechanisms. Please ensure that:

  1. Only authorized users (message authors or users with appropriate permissions) can edit or delete messages.
  2. Proper validation is in place for the edited message content.
  3. There are checks to prevent editing or deleting of messages beyond a certain time limit, if applicable.
  4. The system handles concurrent edit/delete operations gracefully.
  5. All actions are properly logged for auditing purposes.

While these concerns may be addressed in the trait implementations, it's important to verify their presence and effectiveness.

To help verify these security measures, please run the following script:


12-13: Verify implementation of new traits

While the addition of EditGroupChatMessageReqMsgHdlr and DeleteGroupChatMessageReqMsgHdlr traits is correct, it's important to ensure that their implementations exist and align with the PR objectives. This includes handling the new GraphQL mutations (chatEditMessage and chatDeleteMessage) and interacting with the new chat_message_history database table.

To verify the implementation of these new traits, please run the following script:

bbb-graphql-actions/src/actions/chatDeleteMessage.ts (4)

1-2: LGTM: Import statements are appropriate.

The import statements are concise and relevant to the function's requirements. RedisMessage type and throwErrorIfInvalidInput function are correctly imported from their respective modules.


5-10: LGTM: Input validation is thorough and appropriate.

The use of throwErrorIfInvalidInput ensures that both chatId and messageId are present and of the correct type (string). This validation step helps prevent runtime errors and improves the function's robustness.


29-29: LGTM: Return statement is correct and complete.

The return statement correctly includes all necessary components of the RedisMessage: eventName, routing, header, and body. This structure aligns with the expected RedisMessage format.


1-30: Overall assessment: Well-implemented with minor improvements suggested.

The buildRedisMessage function in chatDeleteMessage.ts is well-structured and fulfills its purpose of creating a Redis message for deleting chat messages. It includes proper input validation, constructs the message correctly, and returns the expected structure.

Suggested improvements:

  1. Enhance type safety for input parameters.
  2. Fix the type mismatch in the routing object.
  3. Extract the event name into a constant for better maintainability.

These changes will further improve the robustness and maintainability of the code. Great job overall!

🧰 Tools
🪛 Biome

[error] 14-14: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)


[error] 15-15: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)

bbb-graphql-actions/src/actions/chatEditMessage.ts (3)

1-4: LGTM: Imports and function signature are well-defined.

The imports are appropriate for the function's purpose, and the function signature is well-structured. Using Record<string, unknown> for input parameters provides flexibility, while the explicit RedisMessage return type promotes type safety.


19-29: LGTM: Header and body objects are well-structured.

The header and body objects contain all the necessary information for editing a chat message. The structure is clear and aligns well with the purpose of the function. The direct use of input properties in the body object is safe due to the prior input validation.


1-32: Overall assessment: Well-implemented function with minor improvement suggestions.

The buildRedisMessage function effectively constructs a Redis message for editing chat messages, aligning well with the PR objectives. It includes proper input validation, constructs the necessary components (event name, routing, header, and body), and returns a well-structured message.

Key strengths:

  1. Comprehensive input validation
  2. Clear structure following the RedisMessage type
  3. Proper use of TypeScript for type safety

Suggested improvements:

  1. Extract the validation schema to a constant
  2. Improve type safety when handling session variables
  3. Use object property shorthand in the return statement

These changes will further enhance the code's robustness and maintainability. Great job overall!

🧰 Tools
🪛 Biome

[error] 15-15: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)


[error] 16-16: Don't use 'String' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'string' instead

(lint/complexity/noBannedTypes)

bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml (1)

37-37: New columns added to select permissions for bbb_client role.

The deletedAt and editedAt columns have been correctly added to the select_permissions section for the bbb_client role. This change aligns with the PR objectives to introduce functionality for editing and deleting chat messages.

To ensure these are the only changes made to this file and that they are consistent with the existing structure, let's run the following verification:

This script will help us confirm that only the intended changes were made and that the new columns are positioned correctly within the file structure.

Also applies to: 46-46

✅ Verification successful

Verification Successful: Only the expected columns were added.

The deletedAt and editedAt columns have been correctly added to the select_permissions section for the bbb_client role, and no unexpected changes were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify changes in the YAML file

# Test 1: Check if only the specified columns were added
echo "Test 1: Verifying added columns"
diff_output=$(git diff HEAD^ HEAD -- bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml | grep '^\+' | grep -v '^\+\+\+' | grep -v 'deletedAt' | grep -v 'editedAt')
if [ -z "$diff_output" ]; then
    echo "PASS: Only the expected columns were added."
else
    echo "FAIL: Unexpected additions found:"
    echo "$diff_output"
fi

# Test 2: Verify the positioning of the new columns
echo "Test 2: Verifying column positioning"
awk '/select_permissions:/,/filter:/' bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml | grep -n '^ *- '

Length of output: 991

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageMsgHdlr.scala (4)

47-47: Improved condition check for empty moderators list

The change from modMembers.length == 0 to modMembers.isEmpty is a good improvement. It's more idiomatic Scala and potentially more efficient, as isEmpty is an O(1) operation for most collections. This change enhances readability without altering the functionality.


77-77: Improved variable naming for clarity

The change from gcm to gcMessage is a good improvement in variable naming. It makes the code more self-documenting and easier to understand at a glance. This kind of clarity is particularly important in complex methods like this one.


78-78: Improved variable naming for clarity and consistency

The change from gcs to updatedGroupChat is an excellent improvement in variable naming. It clearly describes what the variable represents, making the code more self-documenting. This change is consistently applied across its usage in the method (lines 78 and 87), which is good for maintaining code clarity throughout the function.

Also applies to: 87-87


Line range hint 1-102: Verify alignment with PR objectives

While the changes in this file improve code quality through better naming conventions and minor optimizations, they don't directly implement the new chatEditMessage and chatDeleteMessage mutations mentioned in the PR objectives.

Could you please clarify:

  1. Are the main changes for editing and deleting messages implemented in other files not included in this review?
  2. Was this file refactored as part of the larger changes to support the new features?

To help verify the implementation of the new features, you can run the following script:

This will help locate the main implementations of the new features and any related database changes.

bbb-graphql-server/metadata/actions.graphql (1)

98-111: Summary: New chat mutations successfully implemented.

The addition of chatDeleteMessage and chatEditMessage mutations enhances the chat functionality as intended. These changes align well with the PR objectives and integrate seamlessly with the existing GraphQL schema.

A few points to consider for future improvements:

  1. Implement message history retrieval for moderators, as mentioned in the PR objectives.
  2. Add time limits for editing or deleting messages in a future update.
  3. Consider adding input validation on the server-side to ensure the integrity of the chat messages.

Overall, these changes provide a solid foundation for the new chat editing and deletion features.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/HandlerHelpers.scala (1)

312-329: Changes align well with PR objectives and existing codebase.

The additions of buildGroupChatMessageEditedEvtMsg and buildGroupChatMessageDeletedEvtMsg methods are well-implemented and consistent with the existing code patterns in the HandlerHelpers trait. These changes directly support the PR objectives of allowing users to edit and delete chat messages.

The new methods provide the necessary functionality to generate event messages for edited and deleted chat messages, which will be crucial for updating clients about these actions in real-time. The implementation follows the established patterns in the codebase, ensuring consistency and maintainability.

bbb-graphql-server/metadata/actions.yaml (3)

92-97: LGTM: New chatDeleteMessage action added correctly

The new chatDeleteMessage action has been added with the correct structure, following the existing patterns in the file. The handler URL and permissions are set appropriately.


98-103: LGTM: New chatEditMessage action added correctly

The new chatEditMessage action has been added with the correct structure, following the existing patterns in the file. The handler URL and permissions are set appropriately.


92-103: Summary: New chat actions added, aligning with PR objectives

The addition of chatDeleteMessage and chatEditMessage actions aligns well with the PR objectives of allowing users to edit and delete chat messages. These new actions follow the existing patterns in the file and are correctly structured.

However, please clarify the indentation changes for the chatCreateWithUser action mentioned in the AI-generated summary but not visible in the provided code snippet.

Overall, the changes to this file support the backend portion of the new chat functionality as described in the PR objectives.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/pubsub/senders/ReceivedJsonMsgHandlerActor.scala (3)

407-408: LGTM: New case for editing group chat messages added correctly.

The new case for EditGroupChatMessageReqMsg has been added consistently with the existing pattern in the file. It correctly uses the routeGenericMsg method to handle the message routing.


409-410: LGTM: New case for deleting group chat messages added correctly.

The new case for DeleteGroupChatMessageReqMsg has been implemented consistently with the existing code structure. It properly uses the routeGenericMsg method for message routing.


407-410: Overall changes look good and align with PR objectives.

The additions for handling EditGroupChatMessageReqMsg and DeleteGroupChatMessageReqMsg are well-integrated into the existing code structure. They are placed appropriately within the group chat-related section of the match statement and follow the established pattern of using routeGenericMsg for message routing.

These changes successfully extend the message handling capabilities of the ReceivedJsonMsgHandlerActor to support the new features for editing and deleting chat messages, as outlined in the PR objectives.

bbb-graphql-server/bbb_schema.sql (2)

1000-1002: New columns added to chat_message table

The following columns have been added to the chat_message table:

  • editedAt: Timestamp to track when a message was edited.
  • deletedAt: Timestamp to track when a message was deleted.

These additions align with the PR objectives and will allow for tracking message edits and deletions.


1126-1127: Updated v_chat_message_private view

The v_chat_message_private view has been updated to include the new editedAt and deletedAt columns. This change ensures that the view reflects the modifications made to the chat_message table, maintaining consistency across the schema.

This update aligns with the changes made to the chat_message table and supports the new functionality for editing and deleting messages.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReqMsgHdlr.scala (2)

31-31: ⚠️ Potential issue

Update conditional check after correcting userIsModerator

After fixing the assignment of userIsModerator, the condition in the if statement should be updated to maintain the original logic, which checks if the user is not a moderator.

Apply this diff to update the condition:

-if (!userIsModerator && user.locked) {
+if (!userIsModerator == false && user.locked) {

Alternatively, simplify the condition:

-if (!userIsModerator && user.locked) {
+if (userIsModerator == false && user.locked) {

Likely invalid or redundant comment.


47-47: Ensure permission checks are consistently applied

The condition:

if (!chatDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) {

Make sure that applyPermissionCheck is properly defined and that all necessary permission checks are consistently applied throughout the method.

Run the following script to verify the usage of applyPermissionCheck:

✅ Verification successful

Permission checks are consistently applied

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `applyPermissionCheck` is properly defined and used.

# Test: Search for the definition and usage of `applyPermissionCheck`.
rg --type scala 'applyPermissionCheck'

Length of output: 1670

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/EditGroupChatMessageReqMsgHdlr.scala (2)

57-58: Handle potential failures from updateGroupChatMessage

Ensure that the updateGroupChatMessage method handles potential errors or exceptions. If it can fail, consider wrapping the call in a try-catch block or handling the failure scenario appropriately.

Check if GroupChatApp.updateGroupChatMessage can fail or throw exceptions, and handle them to prevent unexpected crashes.


31-31: ⚠️ Potential issue

Ensure the user permission checks are accurate after logic fix

With the corrected userIsModerator variable, the condition should check for non-moderator users who are locked. Update the condition to reflect this logic accurately.

Apply this diff to fix the condition:

-if (!userIsModerator && user.locked) {
+if (!userIsModerator && user.locked) {

However, since userIsModerator now correctly reflects if the user is a moderator, the condition remains the same. Just ensure that the logic throughout the method aligns with this change.

Likely invalid or redundant comment.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala (5)

12-12: Proper handling of optional message content

Changing the message field to Option[String] in both ChatMessageDbModel and ChatMessageDbTableDef correctly allows for messages that can be None (e.g., when a message is deleted). Ensure that all usages of message throughout the codebase handle the Option type appropriately to avoid potential None cases leading to runtime errors.

Also applies to: 30-30


20-21: Addition of editedAt and deletedAt fields enhances message auditing

The introduction of the editedAt and deletedAt fields allows for accurate tracking of message edits and deletions. This is beneficial for auditing purposes and improves the transparency of message history.

Also applies to: 40-41, 70-72, 98-99


83-99: Consistent handling of optional fields in insertSystemMsg

In the insertSystemMsg method, ensure that optional fields like senderId and senderRole are consistently handled. Currently, senderId is set to None, and senderRole is also set to None. This is appropriate for system messages. Just make sure that any code consuming these fields can handle None values without issues.


Line range hint 53-72: Use of forceInsert instead of insertOrUpdate

The switch from insertOrUpdate to forceInsert in the insert method changes how new messages are added to the database. Ensure that forceInsert is the appropriate choice here, especially if there are no conflicting primary keys or unique constraints that need to be considered.

Please confirm that forceInsert is suitable in this context and that it doesn't lead to any unintended consequences. You might want to review the database schema to ensure there are no auto-incremented fields or constraints affected by forceInsert.


43-47: Verify field ordering in table mapping

In the * projection of ChatMessageDbTableDef, ensure that the order of the fields matches the constructor parameters of ChatMessageDbModel. Misalignment can lead to data being incorrectly mapped to the model.

It's important to confirm that the field order is consistent. You can verify this by reviewing the case class and the mapping:

✅ Verification successful

Field ordering in table mapping is correct

The order of fields in the * projection of ChatMessageDbTableDef matches the constructor parameters of ChatMessageDbModel, ensuring accurate data mapping.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify field order between ChatMessageDbModel and ChatMessageDbTableDef mapping

# Display the fields in ChatMessageDbModel
ast-grep --lang scala --pattern 'case class ChatMessageDbModel($_$$$)' akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala

# Display the fields in the * projection
rg -A 4 'override def \* =' akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala

Length of output: 537


Script:

#!/bin/bash
# Description: Locate ChatMessageDbModel case class and display its fields

# Search for the file containing ChatMessageDbModel case class
model_file=$(rg 'case class ChatMessageDbModel' --files-with-matches)

# If the file is found, extract the fields
if [ -n "$model_file" ]; then
  echo "Found ChatMessageDbModel in: $model_file"
  ast-grep --lang scala --pattern 'case class ChatMessageDbModel($_$$$)' "$model_file"
else
  echo "ChatMessageDbModel case class not found in the codebase."
fi

Length of output: 604


Script:

#!/bin/bash
# Description: Extract fields from ChatMessageDbModel case class

# Define the file containing ChatMessageDbModel
model_file="akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala"

# Extract the case class definition, accounting for multiline declarations
rg 'case class ChatMessageDbModel' "$model_file" -A 10 | sed -n '/case class ChatMessageDbModel/,/)/p'

Length of output: 639


Script:

#!/bin/bash
# Description: Extract the complete fields from ChatMessageDbModel case class

# Define the file containing ChatMessageDbModel
model_file="akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala"

# Use awk to extract all lines from the case class definition until the closing parenthesis
awk '/case class ChatMessageDbModel/,/\)/' "$model_file"

Length of output: 814

@sonarqubecloud

This comment was marked as off-topic.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChat.scala (1)

46-58: Summary of changes and recommendations

The new methods updateGroupChatMessage and deleteGroupChatMessage successfully implement the core functionality for editing and deleting chat messages as outlined in the PR objectives. However, to enhance the robustness, security, and reliability of these methods, consider implementing the following improvements:

  1. Input validation to prevent unexpected behavior with invalid inputs.
  2. Error handling to gracefully manage potential exceptions from database operations.
  3. Access control (for deleteGroupChatMessage) to ensure only authorized users can delete messages.
  4. Refactor both methods to return Either[String, GroupChats] for better error handling and to provide more informative feedback to the caller.

These enhancements will significantly improve the overall quality and maintainability of the code while aligning with best practices in software development.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala (4)

12-12: LGTM! Consider adding documentation for the new fields.

The changes to the ChatMessageDbModel case class align well with the PR objectives. The Option[String] type for the message field allows for representing deleted messages, and the new fields support tracking edits and deletions.

Consider adding ScalaDoc comments for the new fields to improve code documentation:

/** Timestamp of when the message was last edited, if applicable */
editedAt: Option[java.sql.Timestamp],
/** User ID of the user who deleted the message, if applicable */
deletedByUserId: Option[String],
/** Timestamp of when the message was deleted, if applicable */
deletedAt: Option[java.sql.Timestamp]

Also applies to: 20-22


55-55: LGTM! Consider using a constant for the timestamp.

The changes to the insert method in ChatMessageDAO are appropriate. The use of forceInsert ensures that new messages are always inserted, and the Some(...) wrapper for the message field aligns with the new Option[String] type. The initialization of new fields is correct.

Consider creating a constant for the current timestamp to improve readability and ensure consistency:

val currentTimestamp = new java.sql.Timestamp(System.currentTimeMillis())
// Use currentTimestamp for both createdAt and in other methods

Also applies to: 62-62, 72-75


112-123: LGTM! Consider adding error handling for update failures.

The new update method in ChatMessageDAO correctly implements the chat message editing functionality. The filtering ensures that only the correct message is updated, and the check for non-empty messages prevents updating already deleted messages.

Consider adding error handling to inform the caller when an update fails (e.g., when trying to update an already deleted message). You can modify the method to return the number of affected rows:

def update(meetingId: String, chatId: String, messageId: String, message: String): DBIO[Int] = {
  TableQuery[ChatMessageDbTableDef]
    .filter(_.meetingId === meetingId)
    .filter(_.chatId === chatId)
    .filter(_.messageId === messageId)
    .filter(_.message.nonEmpty)
    .map(msg => (msg.message, msg.editedAt))
    .update((Some(message), Some(new java.sql.Timestamp(System.currentTimeMillis()))))
}

Then, in the calling code, you can check the number of affected rows to determine if the update was successful:

val affectedRows = Await.result(db.run(update(meetingId, chatId, messageId, newMessage)), Duration.Inf)
if (affectedRows == 0) {
  // Handle the case where the message was not updated (e.g., already deleted)
  logger.warn(s"Failed to update message $messageId in chat $chatId")
}

125-136: LGTM! Consider adding error handling for deletion failures.

The new softDelete method in ChatMessageDAO correctly implements the chat message deletion functionality. The filtering ensures that only the correct message is deleted, and the check for non-empty messages prevents deleting already deleted messages.

Similar to the update method, consider adding error handling to inform the caller when a deletion fails. Modify the method to return the number of affected rows:

def softDelete(meetingId: String, chatId: String, messageId: String, deletedByUserId: String): DBIO[Int] = {
  TableQuery[ChatMessageDbTableDef]
    .filter(_.meetingId === meetingId)
    .filter(_.chatId === chatId)
    .filter(_.messageId === messageId)
    .filter(_.message.nonEmpty)
    .map(msg => (msg.message, msg.deletedByUserId, msg.deletedAt))
    .update((None, Some(deletedByUserId), Some(new java.sql.Timestamp(System.currentTimeMillis()))))
}

Then, in the calling code, you can check the number of affected rows to determine if the deletion was successful:

val affectedRows = Await.result(db.run(softDelete(meetingId, chatId, messageId, deletedByUserId)), Duration.Inf)
if (affectedRows == 0) {
  // Handle the case where the message was not deleted (e.g., already deleted)
  logger.warn(s"Failed to delete message $messageId in chat $chatId")
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8dd48b5 and 06b494a.

📒 Files selected for processing (6)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReqMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChat.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala (5 hunks)
  • bbb-graphql-server/bbb_schema.sql (3 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_private.yaml (2 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReqMsgHdlr.scala
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_public.yaml
🔇 Additional comments (9)
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_private.yaml (2)

10-19: LGTM: New deletedBy relationship added correctly.

The new object relationship deletedBy is well-configured and aligns with the PR objective of implementing message deletion functionality. It correctly maps deletedByUserId to userId while maintaining the meetingId context, which is crucial for data integrity and access control.


47-57: LGTM: Select permissions updated to include new columns.

The select_permissions section has been correctly updated to include the new deletedAt and editedAt columns. This change aligns with the PR objective of tracking message edits and deletions. The recipientHasSeen column is retained, maintaining existing functionality. The filter conditions remain unchanged, ensuring proper access control.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageDAO.scala (2)

31-31: LGTM! Table definition changes align with the model updates.

The modifications to the ChatMessageDbTableDef class correctly reflect the changes made to the ChatMessageDbModel case class. The new columns for tracking edits and deletions have been properly added, and the * method has been updated to include all fields in the mapping.

Also applies to: 41-43, 45-49


86-86: LGTM! Changes are consistent with the insert method.

The modifications to the insertSystemMsg method in ChatMessageDAO are appropriate and consistent with the changes made to the insert method. The use of forceInsert and the Some(...) wrapper for the message field are correct.

As mentioned in the previous comment, consider using a constant for the current timestamp to improve readability and ensure consistency across methods.

Also applies to: 93-93, 99-103

bbb-graphql-server/bbb_schema.sql (5)

1000-1003: New columns added to chat_message table

The following columns have been added to the chat_message table:

  • editedAt: Timestamp to track when a message was edited.
  • deletedByUserId: User ID of the person who deleted the message.
  • deletedAt: Timestamp to track when a message was deleted.

These additions align with the PR objectives and will allow tracking of message edits and deletions.


1041-1053: New chat_message_history table created

A new chat_message_history table has been created to store the history of chat message edits. This table includes:

  • messageId: References the original message in the chat_message table.
  • meetingId: The meeting ID.
  • messageVersionSequence: A sequence number for each version of the message.
  • message: The content of the message.
  • senderId: The ID of the user who sent the message.
  • createdAt: Timestamp of when the message was created.
  • movedToHistoryAt: Timestamp of when the message was moved to history.

This table structure allows for efficient tracking of message edit history, which is crucial for the new edit functionality.


1055-1074: Trigger function for updating chat message history

A new trigger function update_chat_message_history_trigger_func() has been created to automatically update the chat_message_history table when a message is edited. The trigger:

  1. Checks if the message content has changed.
  2. If changed, it inserts the old version of the message into the history table.
  3. The trigger is set to fire BEFORE UPDATE on the chat_message table.

This implementation ensures that the message history is automatically maintained without requiring additional application logic.


1127-1129: Updated v_chat_message_private view

The v_chat_message_private view has been updated to include the new columns:

  • editedAt
  • deletedByUserId
  • deletedAt

This change ensures that the view provides access to the new edit and delete information for private chat messages.


Line range hint 1000-1129: Summary of chat message edit and delete functionality implementation

The changes made to the database schema effectively implement the backend portion of allowing users to edit and delete chat messages:

  1. The chat_message table has been updated with new columns to track edits and deletions.
  2. A new chat_message_history table has been created to store the history of message edits.
  3. A trigger function has been implemented to automatically update the message history when edits occur.
  4. The v_chat_message_private view has been updated to include the new edit and delete information.

These changes provide a solid foundation for the new chat edit and delete functionality, aligning well with the PR objectives. The implementation appears to be comprehensive and should support the required features effectively.

@github-actions

github-actions Bot commented Oct 2, 2024

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

@gustavotrott
gustavotrott merged commit 4105271 into bigbluebutton:v3.0.x-release Oct 2, 2024
@coderabbitai coderabbitai Bot mentioned this pull request Dec 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant