Repository navigation
gql-server: Allow users to edit and delete chat messages (backend portion) - #21330
gustavotrott merged 3 commits into
Conversation
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.
This comment was marked as off-topic.
This comment was marked as off-topic.
There was a problem hiding this comment.
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
throwErrorIfInvalidInputensures 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_permissionsfor thebbb_clientrole are focused and consistent with the PR objectives. By includingdeletedAtandeditedAtcolumns, 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:
- Maintain the existing structure of the configuration file.
- Do not introduce any apparent security issues, as they only affect read permissions.
- Are minimal, which is good for maintainability.
Consider the following for future improvements:
- Implement a mechanism to limit the time window for editing or deleting messages, as mentioned in the PR objectives for future work.
- Ensure that the frontend appropriately handles the display of edited and deleted messages based on these new fields.
- 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 checkExcellent change from
chat.users.filter(u => u.id == sender.id).length > 0tochat.users.exists(u => u.id == sender.id). This is more efficient asexistsshort-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.idto avoid repeated access:val senderId = sender.id val userIsAParticipant = chat.users.exists(_.id == senderId)This minor optimization could be beneficial if
sender.idis 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
updateGroupChatMessageanddeleteGroupChatMessagehave been successfully implemented in theGroupChatAppobject, 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:
- Update related components: Ensure that other parts of the application that handle chat messages are updated to use these new methods.
- Testing: Add comprehensive unit tests for these new methods to verify their behavior under various scenarios.
- Documentation: Update any relevant documentation to reflect these new capabilities in the chat system.
To fully leverage these new capabilities, you might want to:
- Implement a message history retrieval system for moderators, as mentioned in the PR objectives for future work.
- Consider adding a time limit for editing or deleting messages, also mentioned as future work.
- 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
chatDeleteMessagemutation 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
chatEditMessagemutation 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
EditGroupChatMessageReqMsgandDeleteGroupChatMessageReqMsgcases aligns well with the PR objectives and maintains consistency with existing chat message handling. Good job on using thelogChatMessagemethod, which respects theincludeChatflag.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
buildGroupChatMessageEditedEvtMsglooks 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
buildGroupChatMessageDeletedEvtMsgis 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 addedThe 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 editsThe
update_chat_message_history_trigger_funcfunction 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:
- The function is triggered before an update on the chat_message table.
- It checks if the message content has changed.
- If changed, it inserts a new record into chat_message_history with the old message content.
Consider adding a check for the
editedAtcolumn 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
editedAttimestamp 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 immutablevalUsing
varforchatLocked,chatLockedForUser, andnewStateintroduces mutable state. Consider refactoring the code to use immutablevaland functional constructs to enhance code safety and readability.Example refactor:
- Use
foldLeftor pattern matching to thread the state without mutation.- Pass
chatLockedandchatLockedForUseras parameters or compute them within their usage scope.
65-69: Reconsider ejecting users for permission issuesEjecting 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
buildErrorResponseis implemented to create an appropriate error message format.
15-17: Consider combining related flag variablesThe variables
chatLockedandchatLockedForUserboth 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 theuserIsModeratorvariable for consistencyNow that
userIsModeratoraccurately 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 logicThe 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
📒 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
EditGroupChatMessageReqMsgHdlrandDeleteGroupChatMessageReqMsgHdlrtraits to theGroupChatHdlrsclass 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 validationWith the introduction of message editing and deletion functionality, it's crucial to implement robust access control and validation mechanisms. Please ensure that:
- Only authorized users (message authors or users with appropriate permissions) can edit or delete messages.
- Proper validation is in place for the edited message content.
- There are checks to prevent editing or deleting of messages beyond a certain time limit, if applicable.
- The system handles concurrent edit/delete operations gracefully.
- 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 traitsWhile the addition of
EditGroupChatMessageReqMsgHdlrandDeleteGroupChatMessageReqMsgHdlrtraits is correct, it's important to ensure that their implementations exist and align with the PR objectives. This includes handling the new GraphQL mutations (chatEditMessageandchatDeleteMessage) and interacting with the newchat_message_historydatabase 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.
RedisMessagetype andthrowErrorIfInvalidInputfunction are correctly imported from their respective modules.
5-10: LGTM: Input validation is thorough and appropriate.The use of
throwErrorIfInvalidInputensures that bothchatIdandmessageIdare 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, andbody. This structure aligns with the expected RedisMessage format.
1-30: Overall assessment: Well-implemented with minor improvements suggested.The
buildRedisMessagefunction inchatDeleteMessage.tsis 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:
- Enhance type safety for input parameters.
- Fix the type mismatch in the routing object.
- 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 explicitRedisMessagereturn 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
buildRedisMessagefunction 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:
- Comprehensive input validation
- Clear structure following the RedisMessage type
- Proper use of TypeScript for type safety
Suggested improvements:
- Extract the validation schema to a constant
- Improve type safety when handling session variables
- 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
deletedAtandeditedAtcolumns have been correctly added to theselect_permissionssection for thebbb_clientrole. 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
deletedAtandeditedAtcolumns have been correctly added to theselect_permissionssection for thebbb_clientrole, 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 listThe change from
modMembers.length == 0tomodMembers.isEmptyis a good improvement. It's more idiomatic Scala and potentially more efficient, asisEmptyis an O(1) operation for most collections. This change enhances readability without altering the functionality.
77-77: Improved variable naming for clarityThe change from
gcmtogcMessageis 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 consistencyThe change from
gcstoupdatedGroupChatis 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 objectivesWhile the changes in this file improve code quality through better naming conventions and minor optimizations, they don't directly implement the new
chatEditMessageandchatDeleteMessagemutations mentioned in the PR objectives.Could you please clarify:
- Are the main changes for editing and deleting messages implemented in other files not included in this review?
- 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
chatDeleteMessageandchatEditMessagemutations 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:
- Implement message history retrieval for moderators, as mentioned in the PR objectives.
- Add time limits for editing or deleting messages in a future update.
- 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
buildGroupChatMessageEditedEvtMsgandbuildGroupChatMessageDeletedEvtMsgmethods are well-implemented and consistent with the existing code patterns in theHandlerHelperstrait. 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: NewchatDeleteMessageaction added correctlyThe new
chatDeleteMessageaction 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: NewchatEditMessageaction added correctlyThe new
chatEditMessageaction 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 objectivesThe addition of
chatDeleteMessageandchatEditMessageactions 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
chatCreateWithUseraction 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
EditGroupChatMessageReqMsghas been added consistently with the existing pattern in the file. It correctly uses therouteGenericMsgmethod to handle the message routing.
409-410: LGTM: New case for deleting group chat messages added correctly.The new case for
DeleteGroupChatMessageReqMsghas been implemented consistently with the existing code structure. It properly uses therouteGenericMsgmethod for message routing.
407-410: Overall changes look good and align with PR objectives.The additions for handling
EditGroupChatMessageReqMsgandDeleteGroupChatMessageReqMsgare well-integrated into the existing code structure. They are placed appropriately within the group chat-related section of thematchstatement and follow the established pattern of usingrouteGenericMsgfor message routing.These changes successfully extend the message handling capabilities of the
ReceivedJsonMsgHandlerActorto 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 tableThe 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 viewThe
v_chat_message_privateview has been updated to include the neweditedAtanddeletedAtcolumns. This change ensures that the view reflects the modifications made to thechat_messagetable, maintaining consistency across the schema.This update aligns with the changes made to the
chat_messagetable 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 issueUpdate conditional check after correcting
userIsModeratorAfter fixing the assignment of
userIsModerator, the condition in theifstatement 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 appliedThe condition:
if (!chatDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) {Make sure that
applyPermissionCheckis 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 fromupdateGroupChatMessageEnsure that the
updateGroupChatMessagemethod 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.updateGroupChatMessagecan fail or throw exceptions, and handle them to prevent unexpected crashes.
31-31:⚠️ Potential issueEnsure the user permission checks are accurate after logic fix
With the corrected
userIsModeratorvariable, 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
userIsModeratornow 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 contentChanging the
messagefield toOption[String]in bothChatMessageDbModelandChatMessageDbTableDefcorrectly allows for messages that can beNone(e.g., when a message is deleted). Ensure that all usages ofmessagethroughout the codebase handle theOptiontype appropriately to avoid potentialNonecases leading to runtime errors.Also applies to: 30-30
20-21: Addition ofeditedAtanddeletedAtfields enhances message auditingThe introduction of the
editedAtanddeletedAtfields 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 ininsertSystemMsgIn the
insertSystemMsgmethod, ensure that optional fields likesenderIdandsenderRoleare consistently handled. Currently,senderIdis set toNone, andsenderRoleis also set toNone. This is appropriate for system messages. Just make sure that any code consuming these fields can handleNonevalues without issues.
Line range hint
53-72: Use offorceInsertinstead ofinsertOrUpdateThe switch from
insertOrUpdatetoforceInsertin theinsertmethod changes how new messages are added to the database. Ensure thatforceInsertis the appropriate choice here, especially if there are no conflicting primary keys or unique constraints that need to be considered.Please confirm that
forceInsertis 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 byforceInsert.
43-47: Verify field ordering in table mappingIn the
*projection ofChatMessageDbTableDef, ensure that the order of the fields matches the constructor parameters ofChatMessageDbModel. 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 ofChatMessageDbTableDefmatches the constructor parameters ofChatMessageDbModel, 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.scalaLength 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." fiLength 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
This comment was marked as off-topic.
This comment was marked as off-topic.
There was a problem hiding this comment.
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 recommendationsThe new methods
updateGroupChatMessageanddeleteGroupChatMessagesuccessfully 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:
- Input validation to prevent unexpected behavior with invalid inputs.
- Error handling to gracefully manage potential exceptions from database operations.
- Access control (for
deleteGroupChatMessage) to ensure only authorized users can delete messages.- 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
ChatMessageDbModelcase class align well with the PR objectives. TheOption[String]type for themessagefield 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
insertmethod inChatMessageDAOare appropriate. The use offorceInsertensures that new messages are always inserted, and theSome(...)wrapper for the message field aligns with the newOption[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 methodsAlso applies to: 62-62, 72-75
112-123: LGTM! Consider adding error handling for update failures.The new
updatemethod inChatMessageDAOcorrectly 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
softDeletemethod inChatMessageDAOcorrectly 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
updatemethod, 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
📒 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: NewdeletedByrelationship added correctly.The new object relationship
deletedByis well-configured and aligns with the PR objective of implementing message deletion functionality. It correctly mapsdeletedByUserIdtouserIdwhile maintaining themeetingIdcontext, which is crucial for data integrity and access control.
47-57: LGTM: Select permissions updated to include new columns.The
select_permissionssection has been correctly updated to include the newdeletedAtandeditedAtcolumns. This change aligns with the PR objective of tracking message edits and deletions. TherecipientHasSeencolumn 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
ChatMessageDbTableDefclass correctly reflect the changes made to theChatMessageDbModelcase 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 theinsertmethod.The modifications to the
insertSystemMsgmethod inChatMessageDAOare appropriate and consistent with the changes made to theinsertmethod. The use offorceInsertand theSome(...)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 tableThe following columns have been added to the
chat_messagetable:
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 createdA new
chat_message_historytable has been created to store the history of chat message edits. This table includes:
messageId: References the original message in thechat_messagetable.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 historyA new trigger function
update_chat_message_history_trigger_func()has been created to automatically update thechat_message_historytable when a message is edited. The trigger:
- Checks if the message content has changed.
- If changed, it inserts the old version of the message into the history table.
- The trigger is set to fire BEFORE UPDATE on the
chat_messagetable.This implementation ensures that the message history is automatically maintained without requiring additional application logic.
1127-1129: Updated v_chat_message_private viewThe
v_chat_message_privateview has been updated to include the new columns:
editedAtdeletedByUserIddeletedAtThis 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 implementationThe changes made to the database schema effectively implement the backend portion of allowing users to edit and delete chat messages:
- The
chat_messagetable has been updated with new columns to track edits and deletions.- A new
chat_message_historytable has been created to store the history of message edits.- A trigger function has been implemented to automatically update the message history when edits occur.
- The
v_chat_message_privateview 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.
Automated tests Summary✅ All the CI tests have passed! |
This PR introduces two new mutations for editing and deleting chat messages:
Additionally, three new fields are added to the
chat_messagetype for both public and private chats:A new
chat_message_historytable has been introduced to store previous versions of edited or deleted messages.When a message is deleted, its content is set to
null, and thedeletedAtfield is populated. The client should display the message as"This message was removed".Future work: