Repository navigation
graphql-server: Add support for chat message Reactions (backend portion) - #21349
gustavotrott merged 3 commits into
Conversation
It introduces the graphql prop `reactions` to the type `chat_message_public` and `chat_message_private`. It also add two mutations `chatSendMessageReaction` and `chatDeleteMessageReaction`.
WalkthroughThis pull request introduces new functionalities for managing group chat message reactions within a meeting context. It adds two traits: Changes
Possibly related PRs
Suggested reviewers
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 17
🧹 Outside diff range and nitpick comments (16)
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_reaction.yaml (1)
1-8: LGTM! Consider adding column descriptions.The table configuration looks good. The use of a custom name without the 'v_' prefix is a good practice for GraphQL naming.
Consider adding descriptions for the columns in the
column_configsection to improve documentation and GraphQL schema introspection.bbb-graphql-actions/src/actions/chatSendMessageReaction.ts (1)
15-16: Consider using explicit type assertions instead ofas String.While the current implementation works, it's generally better to use more explicit type assertions in TypeScript. Consider changing
as Stringtoas stringfor better type safety and consistency with TypeScript conventions.Here's the suggested change:
const routing = { - meetingId: sessionVariables['x-hasura-meetingid'] as String, - userId: sessionVariables['x-hasura-userid'] as String + meetingId: sessionVariables['x-hasura-meetingid'] as string, + userId: sessionVariables['x-hasura-userid'] as string };🧰 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)
Line range hint
1-49: Summary: New array relationship successfully integratedThe changes in this file are minimal and focused, adding only the new
reactionsarray relationship to thev_chat_message_publictable configuration. This addition complements the existing structure without disrupting the current object relationships or select permissions.The new relationship aligns well with the PR objectives of supporting chat message reactions. It provides a clear link between chat messages and their associated reactions, which should facilitate the implementation of the described GraphQL fields and mutations for sending and retrieving message reactions.
As the project evolves, consider the following architectural points:
- Ensure that appropriate indexes are in place on the
meetingIdandmessageIdcolumns in both tables to optimize the performance of joins when querying reactions.- If the number of reactions per message could potentially be large, consider implementing pagination for the reactions array to manage response sizes and improve query performance.
- As new features are added, regularly review the select permissions to ensure they remain appropriate and secure.
bbb-graphql-server/metadata/actions.graphql (1)
147-153: LGTM: chatSendMessageReaction mutation is well-definedThe
chatSendMessageReactionmutation is correctly implemented with appropriate parameters (chatId, messageId, reactionEmoji) and return type (Boolean). This aligns well with the PR objective of adding support for sending chat message reactions.For consistency, consider adding a brief comment above each mutation to describe its purpose, similar to other mutations in this file. For example:
# Mutation to send a reaction to a chat message type Mutation { chatSendMessageReaction( chatId: String! messageId: String! reactionEmoji: String! ): Boolean }This would improve documentation and maintain consistency with other mutations in the file.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core2/AnalyticsActor.scala (1)
Line range hint
141-152: Remove duplicate case statement forDeleteGroupChatMessageReqMsg.The case statement for
DeleteGroupChatMessageReqMsgappears three times consecutively. This is likely an unintentional duplication.Please remove the duplicate entries. The corrected code should look like this:
- case m: DeleteGroupChatMessageReqMsg => logChatMessage(msg) - case m: DeleteGroupChatMessageReqMsg => logChatMessage(msg) - case m: DeleteGroupChatMessageReqMsg => 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)Apart from this duplication issue, the changes look good and align with the PR objectives of adding support for chat message reactions.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/HandlerHelpers.scala (1)
339-346: LGTM: Well-implemented method for building deleted group chat message reaction eventThe
buildGroupChatMessageReactionDeletedEvtMsgmethod is correctly implemented and follows the established pattern for building event messages in this codebase. It properly constructs the routing, envelope, header, and body for the deleted group chat message reaction event.Consider extracting the common parts of
buildGroupChatMessageReactionSentEvtMsgandbuildGroupChatMessageReactionDeletedEvtMsginto a private helper method to reduce code duplication. For example:private def buildGroupChatMessageReactionEvtMsg( eventName: String, meetingId: String, userId: String, chatId: String, messageId: String, reactionEmoji: String ): BbbCommonEnvCoreMsg = { val routing = Routing.addMsgToClientRouting(MessageTypes.BROADCAST_TO_MEETING, meetingId, userId) val envelope = BbbCoreEnvelope(eventName, routing) val header = BbbClientMsgHeader(eventName, meetingId, userId) val body = GroupChatMessageReactionEvtMsgBody(chatId, messageId, reactionEmoji) val event = GroupChatMessageReactionEvtMsg(header, body) BbbCommonEnvCoreMsg(envelope, event) }Then, you can simplify both methods:
def buildGroupChatMessageReactionSentEvtMsg(meetingId: String, userId: String, chatId: String, messageId: String, reactionEmoji: String): BbbCommonEnvCoreMsg = buildGroupChatMessageReactionEvtMsg(GroupChatMessageReactionSentEvtMsg.NAME, meetingId, userId, chatId, messageId, reactionEmoji) def buildGroupChatMessageReactionDeletedEvtMsg(meetingId: String, userId: String, chatId: String, messageId: String, reactionEmoji: String): BbbCommonEnvCoreMsg = buildGroupChatMessageReactionEvtMsg(GroupChatMessageReactionDeletedEvtMsg.NAME, meetingId, userId, chatId, messageId, reactionEmoji)This refactoring would improve code reusability and make it easier to maintain in the future.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/pubsub/senders/ReceivedJsonMsgHandlerActor.scala (1)
413-416: LGTM! Consider grouping related message handlers.The new cases for handling group chat message reactions are correctly implemented and follow the established patterns in the file. Good job!
To improve code organization, consider grouping all group chat related message handlers together. You could move these new cases next to other group chat handlers like
SendGroupChatMessageMsgandGetGroupChatsReqMsg. This would enhance readability and make it easier to maintain related functionality.akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (2)
714-719: LGTM! Consider adding comments for clarity.The new cases for handling group chat message reactions are implemented correctly and consistently with other similar message handlers. They update the state and the user's last activity as expected.
For consistency with other parts of the code, consider adding brief comments explaining the purpose of these new message handlers. For example:
+ // Handle sending a reaction to a group chat message case m: SendGroupChatMessageReactionReqMsg => state = groupChatApp.handle(m, state, liveMeeting, msgBus) updateUserLastActivity(m.header.userId) + // Handle deleting a reaction from a group chat message case m: DeleteGroupChatMessageReactionReqMsg => state = groupChatApp.handle(m, state, liveMeeting, msgBus) updateUserLastActivity(m.header.userId)
Line range hint
1-719: Consider refactoring for improved maintainabilityWhile the new changes are implemented correctly and consistently with the existing code, the
receivefunction is quite large and handles many different concerns. This could potentially make the code harder to maintain and understand as it grows.Consider refactoring the
receivefunction to improve code organization and maintainability. Here are a few suggestions:
Group related message handlers into separate methods. For example:
private def handleUserMessages(msg: Any): Unit = { msg match { case m: UserJoinMeetingReqMsg => // ... case m: UserLeaveReqMsg => // ... // ... other user-related messages } }Use a pattern matching cascade instead of a single large match expression:
def receive = handleUserMessages orElse handleChatMessages orElse handlePresentationMessages // ...Consider using the command pattern or a message handler registry to make it easier to add new message types without modifying this central
receivefunction.These refactoring suggestions aim to make the code more modular and easier to maintain as new features are added.
bbb-graphql-server/bbb_schema.sql (2)
1138-1146: LGTM! Consider adding an additional index.The table structure for
chat_message_reactionlooks good. It maintains data integrity through foreign key relationships and prevents duplicate reactions with its composite primary key.Consider adding an additional index on
(meetingId, userId, createdAt)to optimize queries that might fetch a user's recent reactions across multiple messages:CREATE INDEX idx_chat_message_reaction_user_recent ON chat_message_reaction(meetingId, userId, createdAt);This index could improve performance for queries that retrieve a user's recent reactions, which might be useful for displaying reaction history or analyzing user engagement.
1150-1150: View creation looks good. Consider adding a comment for clarity.The view
v_chat_message_reactionis correctly defined, providing a simple way to access chat message reaction data.Consider adding a comment to explain the purpose of the view:
-- View to access chat message reactions data CREATE OR REPLACE VIEW "v_chat_message_reaction" AS SELECT * FROM "chat_message_reaction";This comment would help other developers understand the intent behind this view at a glance.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageReactionDAO.scala (2)
25-25: Specify return types for public methodsIt's good practice to explicitly specify return types for public methods
insertanddeleteto enhance code readability and maintainability.Specify the return type as
Unitif the methods do not return a meaningful value, or use the appropriate SlickDBIOActiontype if you intend to chain actions or handle results.Example:
-def insert(meetingId: String, messageId: String, userId: String, reactionEmoji: String) = { +def insert(meetingId: String, messageId: String, userId: String, reactionEmoji: String): Unit = {Also applies to: 39-39
41-46: Combine filters for improved readabilityYou can combine multiple filter conditions into a single
filtercall using logical operators. This can make the code more concise and easier to read.Apply this diff to combine the filters:
TableQuery[ChatMessageReactionDbTableDef] - .filter(_.meetingId === meetingId) - .filter(_.messageId === messageId) - .filter(_.userId === userId) - .filter(_.reactionEmoji === reactionEmoji) + .filter(row => + row.meetingId === meetingId && + row.messageId === messageId && + row.userId === userId && + row.reactionEmoji === reactionEmoji + )akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageReactionReqMsgHdlr.scala (2)
20-20: Use immutable variable fornewStateThe variable
newStateis declared as a mutablevarbut is not modified within the method. To adhere to functional programming best practices and improve code immutability, consider changing it to an immutableval.Apply this diff:
-var newState = state +val newState = state
61-61: Ensure proper logging when ejecting a userWhen ejecting a user with
PermissionCheck.ejectUserForFailedPermission, it's important to log this action for audit trails and debugging purposes. Ensure that there is adequate logging to capture the reason and context of the ejection.akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReactionReqMsgHdlr.scala (1)
22-25: Handle missing user or group chat gracefullyThe for-comprehension skips execution if
userorgroupChatis not found. Consider handling the cases where either the user or the group chat is missing by providing appropriate logging or feedback, which can aid in debugging and improve user experience.For example, you could log a warning if the user or group chat is not found:
Users2x.findWithIntId(liveMeeting.users2x, msg.header.userId) match { case Some(user) => state.groupChats.find(msg.body.chatId) match { case Some(groupChat) => // Existing logic case None => // Handle missing group chat log.warning(s"Group chat with ID \${msg.body.chatId} not found.") } case None => // Handle missing user log.warning(s"User with ID \${msg.header.userId} not found.") }
📜 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/DeleteGroupChatMessageReactionReqMsgHdlr.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/SendGroupChatMessageReactionReqMsgHdlr.scala (1 hunks)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/ChatMessageReactionDAO.scala (1 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/chatDeleteMessageReaction.ts (1 hunks)
- bbb-graphql-actions/src/actions/chatSendMessageReaction.ts (1 hunks)
- bbb-graphql-server/bbb_schema.sql (1 hunks)
- bbb-graphql-server/metadata/actions.graphql (2 hunks)
- bbb-graphql-server/metadata/actions.yaml (2 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 (1 hunks)
- bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_reaction.yaml (1 hunks)
- bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml (1 hunks)
🧰 Additional context used
🪛 Biome
bbb-graphql-actions/src/actions/chatDeleteMessageReaction.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)
bbb-graphql-actions/src/actions/chatSendMessageReaction.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 (28)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/GroupChatHdlrs.scala (1)
14-15: LGTM! The changes align well with the PR objectives.The addition of
SendGroupChatMessageReactionReqMsgHdlrandDeleteGroupChatMessageReactionReqMsgHdlrtraits to theGroupChatHdlrsclass is consistent with the existing code structure and naming conventions. These new traits directly support the PR's goal of adding functionality for sending and deleting chat message reactions.The changes appear to maintain the Single Responsibility Principle, with each trait likely handling a specific action related to message reactions. This approach should facilitate easy maintenance and potential future extensions to the reaction system.
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_reaction.yaml (3)
9-19: LGTM! Object relationship is well-defined.The 'user' relationship is correctly configured, linking the reaction to a user within the context of a specific meeting. This design ensures proper scoping of reactions.
1-33: Overall, the implementation aligns well with the PR objectives.The YAML file successfully defines the structure and permissions for the chat message reaction feature. Here are the key points to address:
- Consider adding column descriptions in the
column_configsection for better documentation.- Verify the intention behind allowing aggregations and the empty query/subscription root fields.
- Consider adding the 'messageId' column to the allowed columns list if available.
These minor improvements will enhance the robustness and clarity of the implementation.
20-33: LGTM with suggestions for improvement.The select permissions for 'bbb_client' are well-defined and align with the PR objectives. The filter on 'meetingId' ensures proper data isolation between meetings.
Please verify the following:
- Is allowing aggregations intentional? If so, consider documenting the use case.
- The empty query and subscription root fields might limit GraphQL operations. Confirm if this is intended or if they should include specific fields.
To assist with verification, you can run the following script:
Consider adding the 'messageId' column to the allowed columns list if it's available. This would allow clients to associate reactions with specific messages more easily.
bbb-graphql-actions/src/actions/chatSendMessageReaction.ts (3)
1-2: LGTM: Imports are appropriate and concise.The imports are relevant to the file's functionality, importing necessary types and validation functions.
4-32: LGTM: Function structure and logic are sound.The
buildRedisMessagefunction is well-structured and aligns with the PR objectives. It properly validates input, constructs the necessary components (eventName, routing, header, body), and returns a well-formed Redis message for chat message reactions.🧰 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)
1-32: Overall assessment: Well-implemented functionality with minor improvements suggested.The
chatSendMessageReaction.tsfile successfully implements the functionality for sending chat message reactions, aligning with the PR objectives. The code is well-structured, includes proper input validation, and constructs the Redis message correctly. The suggested improvements are minor and relate to TypeScript best practices. Once these small changes are applied, the file will be in excellent shape.🧰 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-actions/src/actions/chatDeleteMessageReaction.ts (4)
1-2: LGTM: Imports are appropriate and correctly structured.The import statements are concise and import the necessary types and functions for this module.
4-11: LGTM: Function signature and input validation are well-implemented.The function signature is clear and uses appropriate types. The input validation is thorough, ensuring that all required fields are present and of the correct type.
13-32: LGTM: Redis message construction is correct and aligns with PR objectives.The function correctly constructs the Redis message with the required eventName, routing, header, and body. This implementation supports the PR objective of adding functionality for deleting chat message reactions.
🧰 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)
1-32: Overall, the implementation is well-structured and meets the PR objectives.The
buildRedisMessagefunction correctly implements the logic for deleting chat message reactions, aligning with the PR's goal of enhancing chat functionality. The code is clear, concise, and follows good practices for input validation and message construction.Minor improvements have been suggested for type consistency. Once addressed, this implementation will be ready for integration.
🧰 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)
39-49: LGTM! The new array relationship for reactions is well-structured.The addition of the
reactionsarray relationship aligns perfectly with the PR objectives of adding support for chat message reactions. The manual configuration correctly maps themeetingIdandmessageIdfields to thev_chat_message_reactiontable, which should allow for efficient querying of reactions associated with each chat message.Let's verify the existence and structure of the
v_chat_message_reactiontable:This script will help ensure that the referenced
v_chat_message_reactiontable is properly defined in the GraphQL server configuration.bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_private.yaml (1)
39-49: LGTM! The new array relationship for reactions is well-defined.The addition of the
reactionsarray relationship aligns with the PR objective of introducing support for chat message reactions. The manual configuration correctly maps themeetingIdandmessageIdcolumns between thev_chat_message_privateandv_chat_message_reactiontables.Let's verify the existence of the remote table and its columns:
bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml (2)
10-10: Approve the addition of chat message reaction schemaThe inclusion of
public_v_chat_message_reaction.yamlaligns well with the PR objective of adding support for chat message reactions. This is a positive change that introduces the necessary schema for the new feature.To ensure the completeness of this change, please run the following script to verify the contents of the new YAML file:
#!/bin/bash # Description: Verify the contents of the new chat message reaction YAML file # Check if the file exists if [ -f "bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_reaction.yaml" ]; then echo "Contents of public_v_chat_message_reaction.yaml:" cat "bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_chat_message_reaction.yaml" else echo "Error: public_v_chat_message_reaction.yaml not found" fiThis script will display the contents of the new YAML file, allowing you to verify that it contains the expected schema for chat message reactions.
Line range hint
1-9: Verify the intentional removal of multiple YAML file inclusionsI noticed that several YAML file inclusions have been removed, including those related to breakout rooms, captions, and other features. These removals don't seem directly related to the PR objective of adding support for chat message reactions. Could you please clarify if these removals are intentional and part of a larger refactoring effort? If not, they should be reverted to avoid breaking existing functionality.
To help verify the impact of these removals, you can run the following script:
This script will search for references to the removed YAML files in other YAML, TypeScript, and JavaScript files, which can help identify potential issues caused by their removal.
Also applies to: 11-66
✅ Verification successful
Verified: No additional references found for removed YAML files
The removed YAML file inclusions do not appear to be referenced elsewhere in the codebase. This suggests that their removal is intentional and should not impact existing functionality.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for references to removed YAML files in the codebase # List of removed YAML files removed_files=( "public_v_breakoutRoom.yaml" "public_v_breakoutRoom_assignedUser.yaml" "public_v_breakoutRoom_participant.yaml" "public_v_breakoutRoom_user.yaml" "public_v_caption.yaml" "public_v_caption_activeLocales.yaml" "public_v_layout.yaml" ) # Search for references to removed files for file in "${removed_files[@]}"; do echo "Searching for references to $file:" rg "$file" --type yaml --type typescript --type javascript echo doneLength of output: 1420
Script:
#!/bin/bash # Description: Check for references to removed YAML files in the codebase # List of removed YAML files removed_files=( "public_v_breakoutRoom.yaml" "public_v_breakoutRoom_assignedUser.yaml" "public_v_breakoutRoom_participant.yaml" "public_v_breakoutRoom_user.yaml" "public_v_caption.yaml" "public_v_caption_activeLocales.yaml" "public_v_layout.yaml" "public_v_chat_message_reaction.yaml" ) # Search for references to removed files for file in "${removed_files[@]}"; do echo "Searching for references to $file:" rg "$file" --type yaml --type js --type ts echo doneLength of output: 3154
bbb-graphql-server/metadata/actions.graphql (2)
112-118: LGTM: chatDeleteMessageReaction mutation is well-definedThe
chatDeleteMessageReactionmutation is correctly implemented with appropriate parameters (chatId, messageId, reactionEmoji) and return type (Boolean). This aligns well with the PR objective of adding support for deleting chat message reactions.
112-118: Overall: Excellent additions that align with PR objectivesThe new mutations
chatDeleteMessageReactionandchatSendMessageReactionare well-implemented and directly support the PR objective of adding backend support for chat message reactions. These additions are minimal, focused, and consistent with the existing schema structure, which is excellent for maintainability and integration.The mutations provide the necessary operations for managing chat message reactions (sending and deleting), fulfilling the requirements outlined in the PR objectives. Great job on implementing these changes in a clean and coherent manner!
Also applies to: 147-153
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/HandlerHelpers.scala (2)
330-337: LGTM: Well-implemented method for building group chat message reaction eventThe
buildGroupChatMessageReactionSentEvtMsgmethod is correctly implemented and follows the established pattern for building event messages in this codebase. It properly constructs the routing, envelope, header, and body for the group chat message reaction event.
330-346: Overall assessment: Good implementation of group chat message reaction eventsThe new methods
buildGroupChatMessageReactionSentEvtMsgandbuildGroupChatMessageReactionDeletedEvtMsgare well-implemented and align with the PR objectives of adding support for chat message reactions. They follow the existing patterns in the codebase and should integrate seamlessly with the rest of the system.To further improve the code, consider the refactoring suggestion to reduce duplication between these two methods. This would enhance maintainability and make it easier to add similar methods in the future if needed.
bbb-graphql-server/metadata/actions.yaml (3)
104-109: LGTM: New actionchatDeleteMessageReactionadded correctlyThe new action
chatDeleteMessageReactionhas been added with the correct structure, matching the existing pattern in the file. It uses the same synchronous handler and permissions as other actions, which is consistent with the overall design.
134-139: LGTM: New actionchatSendMessageReactionadded correctlyThe new action
chatSendMessageReactionhas been added with the correct structure, matching the existing pattern in the file. It uses the same synchronous handler and permissions as other actions, which is consistent with the overall design.
Line range hint
104-139: Verify completeness of chat reaction actionsThe new actions
chatDeleteMessageReactionandchatSendMessageReactionhave been correctly added and are consistent with the existing structure. They align well with the PR objectives for adding support for chat message reactions.To ensure completeness, please consider the following:
- Are there any other actions related to chat messages that might need updates to support reactions?
- Are there any additional actions needed for managing reactions, such as updating or listing reactions?
To help verify the completeness of the changes, you can run the following script to check for any other chat-related actions that might need updates:
This script will help identify any other chat-related actions that might need to be considered for the reaction feature.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/pubsub/senders/ReceivedJsonMsgHandlerActor.scala (1)
413-416: Summary: New group chat reaction handlers successfully implemented.These changes successfully add support for sending and deleting group chat message reactions, as outlined in the PR objectives. The implementation is consistent with the existing code structure and follows established patterns in the
ReceivedJsonMsgHandlerActorclass.To ensure these changes are properly integrated, please verify that the corresponding message classes (
SendGroupChatMessageReactionReqMsgandDeleteGroupChatMessageReactionReqMsg) are defined and that the necessary handling logic is implemented in the appropriate handler classes. You can use the following script to check for the existence of these classes:✅ Verification successful
Verified: Group chat reaction handlers are properly implemented.
All necessary message classes and their corresponding handlers are present and correctly integrated into the
ReceivedJsonMsgHandlerActorclass. The implementation aligns with the PR objectives and follows the established codebase patterns.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for the existence of new message classes echo "Searching for SendGroupChatMessageReactionReqMsg:" rg "case class SendGroupChatMessageReactionReqMsg" --type scala echo "Searching for DeleteGroupChatMessageReactionReqMsg:" rg "case class DeleteGroupChatMessageReactionReqMsg" --type scala # Check for handler implementations echo "Searching for handlers:" rg "def handle\(msg: (SendGroupChatMessageReactionReqMsg|DeleteGroupChatMessageReactionReqMsg)\)" --type scalaLength of output: 1367
Script:
#!/bin/bash # Search for 'routeGenericMsg' invocations for the new message classes echo "Searching for 'routeGenericMsg' invocations for SendGroupChatMessageReactionReqMsg:" rg "routeGenericMsg\[SendGroupChatMessageReactionReqMsg\]" --type scala echo "Searching for 'routeGenericMsg' invocations for DeleteGroupChatMessageReactionReqMsg:" rg "routeGenericMsg\[DeleteGroupChatMessageReactionReqMsg\]" --type scala # Search for any alternative handler implementations or usages of the message classes echo "Searching for alternative handler implementations for SendGroupChatMessageReactionReqMsg and DeleteGroupChatMessageReactionReqMsg:" rg "(SendGroupChatMessageReactionReqMsg|DeleteGroupChatMessageReactionReqMsg)" --type scala | rg "handle|process|manage"Length of output: 1789
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1)
Line range hint
1-719: Summary: Changes look good, with suggestions for future improvementsThe new additions for handling group chat message reactions have been implemented correctly and consistently with the existing code patterns. The changes fulfill the PR objectives of introducing new GraphQL fields and mutations for sending and deleting chat message reactions.
Key points:
- The new message handlers are properly integrated into the
receivefunction.- State updates and user activity tracking are handled correctly.
- The changes are consistent with the existing code style and structure.
Suggestions for future improvements:
- Add brief comments to the new message handlers for clarity.
- Consider refactoring the large
receivefunction to improve maintainability.Overall, the changes are approved and ready to be merged, with the suggested improvements to be considered for future refactoring efforts.
bbb-graphql-server/bbb_schema.sql (2)
1147-1148: Indexes look good and will improve query performance.The two indexes created for the
chat_message_reactiontable are well-designed:
chat_message_reaction_meeting_message_idxon (meetingId, messageId)chat_message_reaction_meeting_message_idx_revon (messageId, meetingId)These indexes will enhance query performance for lookups by meetingId and messageId in various scenarios.
1138-1151: Changes successfully implement chat message reactions as per PR objectives.The additions to the schema effectively implement support for chat message reactions, aligning well with the PR objectives. Key points:
- A new
chat_message_reactiontable is created with appropriate foreign key relationships.- Indexes are in place to support efficient querying.
- A view
v_chat_message_reactionis provided for easy data access.These changes provide a solid foundation for the backend portion of the chat message reactions feature.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageReactionReqMsgHdlr.scala (1)
48-48:⚠️ Potential issueEnsure
applyPermissionCheckis defined and accessibleThe condition
!(applyPermissionCheck && chatLocked)usesapplyPermissionCheck, but it's not defined within this scope. Ensure thatapplyPermissionCheckis properly defined and accessible in this context to avoid runtime errors.Run the following script to verify the definition of
applyPermissionCheck:akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReactionReqMsgHdlr.scala (1)
61-61: Ensure consistent use of error handling methodsThe method
PermissionCheck.ejectUserForFailedPermissionis used to eject a user with a reason. Verify that this aligns with the application's error-handling policies and that the user receives appropriate feedback upon being ejected.Run the following script to confirm consistent usage of
ejectUserForFailedPermission:✅ Verification successful
Consistent Use of
ejectUserForFailedPermissionVerifiedAll instances of
PermissionCheck.ejectUserForFailedPermissionare used consistently and provide meaningful reasons, aligning with the application's error-handling policies. No issues were found.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Search for all usages of ejectUserForFailedPermission to ensure consistency. # Test: Find all instances of ejectUserForFailedPermission. rg --type scala -A 3 'PermissionCheck\.ejectUserForFailedPermission\(' # Expected Result: All usages follow a consistent pattern and provide meaningful reasons.Length of output: 58561
| with SendGroupChatMessageReactionReqMsgHdlr | ||
| with DeleteGroupChatMessageReactionReqMsgHdlr |
There was a problem hiding this comment.
💡 Codebase verification
Missing implementations for reaction-related traits
The traits SendGroupChatMessageReactionReqMsgHdlr and DeleteGroupChatMessageReactionReqMsgHdlr are mixed into GroupChatHdlrs.scala but their implementations could not be found in the codebase. This may lead to runtime issues when handling group chat message reactions.
🔗 Analysis chain
Verify implementation of new reaction-related traits
While the addition of these traits aligns well with the PR objectives, it would be beneficial to verify the implementation of SendGroupChatMessageReactionReqMsgHdlr and DeleteGroupChatMessageReactionReqMsgHdlr to ensure they fully meet the requirements outlined in the PR objectives, including:
- Handling the necessary parameters (chat ID, message ID, emoji) for sending and deleting reactions.
- Properly integrating with the public and private subscriptions for retrieving message reactions.
- Ensuring the correct data (creation time, emoji, user name) is captured and transmitted for each reaction.
To assist with this verification, you can run the following script to locate and display the implementations of these traits:
This will help ensure that the new functionality is correctly implemented according to the PR objectives.
To ensure that SendGroupChatMessageReactionReqMsgHdlr and DeleteGroupChatMessageReactionReqMsgHdlr are properly defined and implemented, please run the following script to locate their trait declarations:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Locate and display the implementations of the new reaction-related traits
echo "Searching for SendGroupChatMessageReactionReqMsgHdlr implementation:"
ast-grep --lang scala --pattern 'trait SendGroupChatMessageReactionReqMsgHdlr { $$$$ }'
echo "\nSearching for DeleteGroupChatMessageReactionReqMsgHdlr implementation:"
ast-grep --lang scala --pattern 'trait DeleteGroupChatMessageReactionReqMsgHdlr { $$$$ }'
Length of output: 483
Script:
#!/bin/bash
# Description: Locate and display the declarations of the new reaction-related traits
echo "Searching for SendGroupChatMessageReactionReqMsgHdlr trait declaration:"
ast-grep --lang scala --pattern 'trait SendGroupChatMessageReactionReqMsgHdlr { $$$$ }'
echo "\nSearching for DeleteGroupChatMessageReactionReqMsgHdlr trait declaration:"
ast-grep --lang scala --pattern 'trait DeleteGroupChatMessageReactionReqMsgHdlr { $$$$ }'
Length of output: 495
| meetingId: sessionVariables['x-hasura-meetingid'] as String, | ||
| userId: sessionVariables['x-hasura-userid'] as String |
There was a problem hiding this comment.
Fix: Use 'string' instead of 'String' for type assertions.
The static analysis tool Biome correctly identified the use of 'String' instead of 'string' for type assertions. This change will improve type consistency and adhere to TypeScript best practices.
Please apply the following fix:
const routing = {
- meetingId: sessionVariables['x-hasura-meetingid'] as String,
- userId: sessionVariables['x-hasura-userid'] as String
+ meetingId: sessionVariables['x-hasura-meetingid'] as string,
+ userId: sessionVariables['x-hasura-userid'] as string
};📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| meetingId: sessionVariables['x-hasura-meetingid'] as String, | |
| userId: sessionVariables['x-hasura-userid'] as String | |
| meetingId: sessionVariables['x-hasura-meetingid'] as string, | |
| userId: sessionVariables['x-hasura-userid'] as string |
🧰 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)
| meetingId: sessionVariables['x-hasura-meetingid'] as String, | ||
| userId: sessionVariables['x-hasura-userid'] as String |
There was a problem hiding this comment.
Replace as String with as string for consistency.
The use of as String is not consistent with TypeScript best practices. It's recommended to use lowercase primitives.
Apply this diff to fix the issue:
- meetingId: sessionVariables['x-hasura-meetingid'] as String,
- userId: sessionVariables['x-hasura-userid'] as String
+ meetingId: sessionVariables['x-hasura-meetingid'] as string,
+ userId: sessionVariables['x-hasura-userid'] as string📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| meetingId: sessionVariables['x-hasura-meetingid'] as String, | |
| userId: sessionVariables['x-hasura-userid'] as String | |
| meetingId: sessionVariables['x-hasura-meetingid'] as string, | |
| userId: sessionVariables['x-hasura-userid'] as string |
🧰 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)
| createdAt = new java.sql.Timestamp(System.currentTimeMillis()) | ||
| ) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider using database-generated timestamp for createdAt
Setting createdAt using System.currentTimeMillis() relies on the server's clock and timezone, which might lead to inconsistencies if the application runs on multiple servers or if the server's time is incorrect. To ensure consistency, consider having the database generate the timestamp.
Apply this diff to allow the database to handle the createdAt timestamp:
- createdAt = new java.sql.Timestamp(System.currentTimeMillis())
+ createdAt = null // The database will set the timestamp automaticallyAnd modify the database table definition to set a default value for createdAt:
ALTER TABLE chat_message_reaction
ALTER COLUMN "createdAt" SET DEFAULT CURRENT_TIMESTAMP;| val messageId = column[String]("messageId", O.PrimaryKey) | ||
| val userId = column[String]("userId", O.PrimaryKey) | ||
| val reactionEmoji = column[String]("reactionEmoji", O.PrimaryKey) |
There was a problem hiding this comment.
Define composite primary key using primaryKey method
Currently, each of the columns messageId, userId, and reactionEmoji is marked individually with O.PrimaryKey. In Slick, to define a composite primary key consisting of multiple columns, you should use the primaryKey method instead. Marking multiple columns individually as primary keys does not create a composite key.
Apply this diff to define the composite primary key correctly:
val messageId = column[String]("messageId")
val userId = column[String]("userId")
val reactionEmoji = column[String]("reactionEmoji")
+def pk = primaryKey("pk_chat_message_reaction", (messageId, userId, reactionEmoji))📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| val messageId = column[String]("messageId", O.PrimaryKey) | |
| val userId = column[String]("userId", O.PrimaryKey) | |
| val reactionEmoji = column[String]("reactionEmoji", O.PrimaryKey) | |
| val messageId = column[String]("messageId") | |
| val userId = column[String]("userId") | |
| val reactionEmoji = column[String]("reactionEmoji") | |
| def pk = primaryKey("pk_chat_message_reaction", (messageId, userId, reactionEmoji)) |
| val userIsModerator = user.role != Roles.MODERATOR_ROLE | ||
|
|
There was a problem hiding this comment.
Incorrect moderator status check—Logical error in userIsModerator assignment
The variable userIsModerator is assigned using user.role != Roles.MODERATOR_ROLE, which evaluates to true when the user is not a moderator. This contradicts the variable name userIsModerator and may cause logical errors in subsequent conditions. It should be assigned as user.role == Roles.MODERATOR_ROLE. Please review the subsequent conditions that use userIsModerator to ensure they function correctly after this change.
Apply this diff to correct the assignment:
- val userIsModerator = user.role != Roles.MODERATOR_ROLE
+ val userIsModerator = user.role == Roles.MODERATOR_ROLE📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| val userIsModerator = user.role != Roles.MODERATOR_ROLE | |
| val userIsModerator = user.role == Roles.MODERATOR_ROLE | |
| object SendGroupChatMessageReactionReqMsg { val NAME = "SendGroupChatMessageReactionReqMsg" } | ||
| case class SendGroupChatMessageReactionReqMsg(header: BbbClientMsgHeader, body: SendGroupChatMessageReactionReqMsgBody) extends StandardMsg | ||
| case class SendGroupChatMessageReactionReqMsgBody(chatId: String, messageId: String, reactionEmoji: String) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider including the user ID in SendGroupChatMessageReactionReqMsgBody
Currently, SendGroupChatMessageReactionReqMsgBody includes chatId, messageId, and reactionEmoji, but it might be beneficial to include the userId of the sender. This addition can enhance clarity and ensure that the server accurately identifies the source of the reaction, especially in cases where the header may not provide sufficient user information.
| object GroupChatMessageReactionSentEvtMsg { val NAME = "GroupChatMessageReactionSentEvtMsg" } | ||
| case class GroupChatMessageReactionSentEvtMsg(header: BbbClientMsgHeader, body: GroupChatMessageReactionSentEvtMsgBody) extends BbbCoreMsg | ||
| case class GroupChatMessageReactionSentEvtMsgBody(chatId: String, messageId: String, reactionEmoji: String) |
There was a problem hiding this comment.
Include sender information in GroupChatMessageReactionSentEvtMsgBody
The event message GroupChatMessageReactionSentEvtMsgBody lacks the userId of the user who sent the reaction. Including this information is important so that clients receiving this event know which user reacted to the message.
| object DeleteGroupChatMessageReactionReqMsg { val NAME = "DeleteGroupChatMessageReactionReqMsg" } | ||
| case class DeleteGroupChatMessageReactionReqMsg(header: BbbClientMsgHeader, body: DeleteGroupChatMessageReactionReqMsgBody) extends StandardMsg | ||
| case class DeleteGroupChatMessageReactionReqMsgBody(chatId: String, messageId: String, reactionEmoji: String) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider including the user ID in DeleteGroupChatMessageReactionReqMsgBody
Including the userId in DeleteGroupChatMessageReactionReqMsgBody can help identify who is requesting the deletion of a reaction. This can be crucial for permission checks and auditing purposes.
| object GroupChatMessageReactionDeletedEvtMsg { val NAME = "GroupChatMessageReactionDeletedEvtMsg" } | ||
| case class GroupChatMessageReactionDeletedEvtMsg(header: BbbClientMsgHeader, body: GroupChatMessageReactionDeletedEvtMsgBody) extends BbbCoreMsg | ||
| case class GroupChatMessageReactionDeletedEvtMsgBody(chatId: String, messageId: String, reactionEmoji: String) |
There was a problem hiding this comment.
Include user information in GroupChatMessageReactionDeletedEvtMsgBody
The event message GroupChatMessageReactionDeletedEvtMsgBody should include the userId of the user whose reaction was deleted. This is especially important if reactions can be deleted by users other than the one who originally sent them, such as moderators or administrators.
|
There was a problem hiding this comment.
Actionable comments posted: 8
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReactionReqMsgHdlr.scala (1 hunks)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageReactionReqMsgHdlr.scala (1 hunks)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala
🔇 Additional comments (6)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/SendGroupChatMessageReactionReqMsgHdlr.scala (4)
1-11: LGTM: Imports and file structureThe package declaration, imports, and overall file structure are well-organized and appropriate for the functionality being implemented.
12-15: LGTM: Trait declaration and method signatureThe trait
SendGroupChatMessageReactionReqMsgHdlris well-defined, extendingHandlerHelpersand using a self-type annotation. Thehandlemethod signature is clear and includes all necessary parameters.
1-65: Overall assessment: Functional but needs refinementThe
SendGroupChatMessageReactionReqMsgHdlrtrait implements the core functionality for handling group chat message reactions. While the logic is generally correct, there are several areas for improvement:
- Refactor the
handlemethod into smaller, more focused methods for better readability and maintainability.- Implement input validation for the
reactionEmojito prevent potential security issues.- Replace mutable variables with immutable alternatives where possible.
- Improve error handling, especially for cases where messages or users are not found.
- Fix the logical error in the
userIsModeratorassignment.These refinements will enhance the code's quality, security, and maintainability. Despite these suggestions, the overall structure and approach are sound.
53-60:⚠️ Potential issueSecurity: Validate reaction emoji before processing
While the logic for handling reactions is correct, there's a potential security risk:
- The
reactionEmojiis not validated before being used or stored. This could lead to injection attacks or storage of invalid data.Add validation for the
reactionEmojibefore processing:def isValidEmoji(emoji: String): Boolean = { // Implement emoji validation logic } if (isValidEmoji(msg.body.reactionEmoji)) { val event = buildGroupChatMessageReactionSentEvtMsg(...) bus.outGW.send(event) ChatMessageReactionDAO.insert(...) } else { log.warning(s"Invalid emoji reaction: ${msg.body.reactionEmoji}") // Consider sending an error message back to the client }This change will help prevent potential security issues and ensure data integrity.
To verify the current usage of
reactionEmoji, run:akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/groupchats/DeleteGroupChatMessageReactionReqMsgHdlr.scala (2)
1-13: LGTM: Imports and trait declaration look goodThe imports are appropriate for the functionality being implemented, and the trait structure is correct. The
DeleteGroupChatMessageReactionReqMsgHdlrtrait extendsHandlerHelpersand is mixed in withGroupChatHdlrs, which seems appropriate for its purpose.
1-65: Overall assessment: Good implementation with room for improvementsThe
DeleteGroupChatMessageReactionReqMsgHdlrtrait provides a solid implementation for handling the deletion of group chat message reactions. The logic flow is generally correct and covers various scenarios and permission checks.However, there are a few areas that need attention:
- Replace mutable variables with immutable ones where possible.
- Fix the logical error in the moderator status check.
- Address the undefined
applyPermissionCheckvariable.- Simplify some complex logic, such as the moderator identification in private chats.
- Add comments to explain complex conditions for better readability.
After addressing these issues, the code will be more robust, maintainable, and aligned with Scala best practices. Great job overall on implementing this complex functionality!
| if (!userIsModerator && user.locked) { | ||
| val permissions = MeetingStatus2x.getPermissions(liveMeeting.status) | ||
| if (groupChat.access == GroupChatAccess.PRIVATE) { | ||
| val modMembers = groupChat.users.filter(cu => Users2x.findWithIntId(liveMeeting.users2x, cu.id) match { | ||
| case Some(user) => user.role == Roles.MODERATOR_ROLE | ||
| case None => false | ||
| }) | ||
| // don't lock private chats that involve a moderator | ||
| if (modMembers.isEmpty) { | ||
| chatLocked = permissions.disablePrivChat | ||
| } | ||
| } else { | ||
| chatLocked = permissions.disablePubChat | ||
| } | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Suggestion: Improve readability of permission checks
The permission checking logic is correct but could be more concise. Consider extracting the moderator check into a separate function and simplifying the nested if statements. For example:
def hasModerator(groupChat: GroupChat): Boolean = {
groupChat.users.exists(cu =>
Users2x.findWithIntId(liveMeeting.users2x, cu.id).exists(_.role == Roles.MODERATOR_ROLE)
)
}
val permissions = MeetingStatus2x.getPermissions(liveMeeting.status)
chatLocked = if (groupChat.access == GroupChatAccess.PRIVATE) {
!hasModerator(groupChat) && permissions.disablePrivChat
} else {
permissions.disablePubChat
}This refactoring would make the code more readable and easier to maintain.
| if (!chatDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) { | ||
| for { | ||
| gcMessage <- groupChat.msgs.find(gcm => gcm.id == msg.body.messageId) | ||
| } yield { | ||
| val chatIsPrivate = groupChat.access == GroupChatAccess.PRIVATE | ||
| val userIsAParticipant = groupChat.users.exists(u => u.id == user.intId) | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Suggestion: Improve readability and error handling
- Consider combining the conditions for better readability:
if (!chatDisabled && !chatLocked && !chatLockedForUser) {
// Existing logic
}- Add error handling for the case when the message is not found:
groupChat.msgs.find(gcm => gcm.id == msg.body.messageId) match {
case Some(gcMessage) =>
// Existing logic
case None =>
log.warning(s"Message ${msg.body.messageId} not found in chat ${msg.body.chatId}")
// Consider sending an error message back to the client
}These changes will improve code readability and robustness.
| def handle(msg: SendGroupChatMessageReactionReqMsg, state: MeetingState2x, liveMeeting: LiveMeeting, bus: MessageBus): Unit = { | ||
| val chatDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("chat") | ||
| var chatLocked: Boolean = false | ||
| var chatLockedForUser: Boolean = false | ||
|
|
||
| for { | ||
| user <- Users2x.findWithIntId(liveMeeting.users2x, msg.header.userId) | ||
| groupChat <- state.groupChats.find(msg.body.chatId) | ||
| } yield { | ||
| if (groupChat.access == GroupChatAccess.PUBLIC && user.userLockSettings.disablePublicChat && user.role != Roles.MODERATOR_ROLE) { | ||
| chatLockedForUser = true | ||
| } | ||
|
|
||
| val userIsModerator = user.role != Roles.MODERATOR_ROLE | ||
|
|
||
| if (!userIsModerator && user.locked) { | ||
| val permissions = MeetingStatus2x.getPermissions(liveMeeting.status) | ||
| if (groupChat.access == GroupChatAccess.PRIVATE) { | ||
| val modMembers = groupChat.users.filter(cu => Users2x.findWithIntId(liveMeeting.users2x, cu.id) match { | ||
| case Some(user) => user.role == Roles.MODERATOR_ROLE | ||
| case None => false | ||
| }) | ||
| // don't lock private chats that involve a moderator | ||
| if (modMembers.isEmpty) { | ||
| chatLocked = permissions.disablePrivChat | ||
| } | ||
| } else { | ||
| chatLocked = permissions.disablePubChat | ||
| } | ||
| } | ||
|
|
||
| if (!chatDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) { | ||
| for { | ||
| gcMessage <- groupChat.msgs.find(gcm => gcm.id == msg.body.messageId) | ||
| } yield { | ||
| val chatIsPrivate = groupChat.access == GroupChatAccess.PRIVATE | ||
| val userIsAParticipant = groupChat.users.exists(u => u.id == user.intId) | ||
|
|
||
| if ((chatIsPrivate && userIsAParticipant) || !chatIsPrivate) { | ||
| val event = buildGroupChatMessageReactionSentEvtMsg(liveMeeting.props.meetingProp.intId, msg.header.userId, msg.body.chatId, gcMessage.id, msg.body.reactionEmoji) | ||
| bus.outGW.send(event) | ||
| ChatMessageReactionDAO.insert(liveMeeting.props.meetingProp.intId, gcMessage.id, msg.header.userId, msg.body.reactionEmoji) | ||
| } else { | ||
| val reason = "User isn't a participant of the chat" | ||
| PermissionCheck.ejectUserForFailedPermission(msg.header.meetingId, msg.header.userId, reason, bus.outGW, liveMeeting) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Refactor: Improve overall structure of the handle method
The handle method, while functional, is quite long and contains nested logic that may affect readability and maintainability. Consider the following improvements:
-
Extract complex logic into smaller, well-named helper methods. For example:
isUserAllowedToReact(user: User2x, groupChat: GroupChat): BooleansendReactionEvent(user: User2x, groupChat: GroupChat, message: GroupChatMessage, reaction: String): Unit
-
Use early returns to reduce nesting and improve readability:
if (chatDisabled || chatLocked || chatLockedForUser) return
// Rest of the logic- Consider using the
Eithermonad for better error handling throughout the method.
These changes will make the code more modular, easier to understand, and maintain.
| val chatDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("chat") | ||
| var chatLocked: Boolean = false | ||
| var chatLockedForUser: Boolean = false | ||
|
|
||
| for { | ||
| user <- Users2x.findWithIntId(liveMeeting.users2x, msg.header.userId) | ||
| groupChat <- state.groupChats.find(msg.body.chatId) | ||
| } yield { | ||
| if (groupChat.access == GroupChatAccess.PUBLIC && user.userLockSettings.disablePublicChat && user.role != Roles.MODERATOR_ROLE) { | ||
| chatLockedForUser = true | ||
| } | ||
|
|
||
| val userIsModerator = user.role != Roles.MODERATOR_ROLE | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Refactor: Improve variable declarations and fix logical error
-
Consider using immutable variables instead of
varforchatLockedandchatLockedForUser. This aligns better with functional programming principles. -
There's a logical error in the
userIsModeratorassignment:
-val userIsModerator = user.role != Roles.MODERATOR_ROLE
+val userIsModerator = user.role == Roles.MODERATOR_ROLE- The pattern matching for user and group chat retrieval looks good, but consider handling the case where either is not found.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| val chatDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("chat") | |
| var chatLocked: Boolean = false | |
| var chatLockedForUser: Boolean = false | |
| for { | |
| user <- Users2x.findWithIntId(liveMeeting.users2x, msg.header.userId) | |
| groupChat <- state.groupChats.find(msg.body.chatId) | |
| } yield { | |
| if (groupChat.access == GroupChatAccess.PUBLIC && user.userLockSettings.disablePublicChat && user.role != Roles.MODERATOR_ROLE) { | |
| chatLockedForUser = true | |
| } | |
| val userIsModerator = user.role != Roles.MODERATOR_ROLE | |
| val chatDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("chat") | |
| val chatLocked: Boolean = false | |
| val chatLockedForUser: Boolean = false | |
| for { | |
| user <- Users2x.findWithIntId(liveMeeting.users2x, msg.header.userId) | |
| groupChat <- state.groupChats.find(msg.body.chatId) | |
| } yield { | |
| if (groupChat.access == GroupChatAccess.PUBLIC && user.userLockSettings.disablePublicChat && user.role != Roles.MODERATOR_ROLE) { | |
| chatLockedForUser = true | |
| } | |
| val userIsModerator = user.role == Roles.MODERATOR_ROLE | |
| def handle(msg: DeleteGroupChatMessageReactionReqMsg, state: MeetingState2x, liveMeeting: LiveMeeting, bus: MessageBus): Unit = { | ||
| val chatDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("chat") | ||
| var chatLocked: Boolean = false | ||
| var chatLockedForUser: Boolean = false | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion
Consider using immutable variables
As mentioned in a previous review, it's generally better to use immutable variables (val) in Scala instead of mutable ones (var). Consider refactoring chatLocked and chatLockedForUser to be computed when needed, rather than initialized as mutable variables. This can improve code safety and adhere better to functional programming principles.
For example:
def handle(msg: DeleteGroupChatMessageReactionReqMsg, state: MeetingState2x, liveMeeting: LiveMeeting, bus: MessageBus): Unit = {
val chatDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("chat")
for {
user <- Users2x.findWithIntId(liveMeeting.users2x, msg.header.userId)
groupChat <- state.groupChats.find(msg.body.chatId)
} yield {
val chatLockedForUser = groupChat.access == GroupChatAccess.PUBLIC &&
user.userLockSettings.disablePublicChat &&
user.role != Roles.MODERATOR_ROLE
// Compute chatLocked when needed
// ...
}
}This approach eliminates the need for mutable variables and can make the code more readable and maintainable.
| val modMembers = groupChat.users.filter(cu => Users2x.findWithIntId(liveMeeting.users2x, cu.id) match { | ||
| case Some(user) => user.role == Roles.MODERATOR_ROLE | ||
| case None => false | ||
| }) |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Simplify moderator identification in private chats
The current method of identifying moderators in private chats can be simplified. Instead of using a match expression, you can use exists with a predicate. This would make the code more concise and idiomatic Scala.
Consider refactoring as follows:
val modMembers = groupChat.users.filter { cu =>
Users2x.findWithIntId(liveMeeting.users2x, cu.id).exists(_.role == Roles.MODERATOR_ROLE)
}This change eliminates the need for the match expression and makes the intent clearer.
| } | ||
| } | ||
|
|
||
| if (!chatDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) { |
There was a problem hiding this comment.
Address undefined variable and improve readability
There are two issues to address in this line:
-
The variable
applyPermissionCheckis undefined. Ensure that this variable is properly defined or passed into the method. -
The condition is complex and could benefit from a comment explaining its purpose.
Consider refactoring as follows:
// Proceed if chat is enabled, not locked (if permission check applies), and not locked for this specific user
if (!chatDisabled && !(applyPermissionCheck && chatLocked) && !chatLockedForUser) {
// ... existing code ...
}Also, make sure to define or pass in the applyPermissionCheck variable before using it in this condition.
| chatLockedForUser = true | ||
| } | ||
|
|
||
| val userIsModerator = user.role != Roles.MODERATOR_ROLE |
There was a problem hiding this comment.
Fix logical error in moderator status check
There's a logical error in the assignment of userIsModerator. Currently, it's set to true when the user is not a moderator, which contradicts the variable name. This issue was identified in a previous review.
Please correct the assignment as follows:
- val userIsModerator = user.role != Roles.MODERATOR_ROLE
+ val userIsModerator = user.role == Roles.MODERATOR_ROLEAfter making this change, please review all subsequent conditions that use userIsModerator to ensure they still function as intended.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| val userIsModerator = user.role != Roles.MODERATOR_ROLE | |
| val userIsModerator = user.role == Roles.MODERATOR_ROLE |
Automated tests Summary✅ All the CI tests have passed! |




Introduces graphql fields and mutations to send/delete chat message reactions!
{ "data": { "chat_message_public": [ { "message": "hello", "reactions": [ { "createdAt": "2024-10-03T17:19:49.854+00:00", "reactionEmoji": "😐", "user": { "name": "teacher 1" } }, { "createdAt": "2024-10-03T17:20:10.984+00:00", "reactionEmoji": "😐", "user": { "name": "student 2" } }, { "createdAt": "2024-10-03T17:20:33.292+00:00", "reactionEmoji": "👏", "user": { "name": "student 1" } } ] } ] } }