Skip to content

refactor (plugins): Read plugins configs from a manifest file instead of client settings - #21368

Merged
gustavotrott merged 15 commits into
bigbluebutton:v3.0.x-releasefrom
GuiLeme:new-server-side-architecture
Oct 14, 2024
Merged

gustavotrott merged 15 commits into
bigbluebutton:v3.0.x-releasefrom
GuiLeme:new-server-side-architecture

Conversation

@GuiLeme

@GuiLeme GuiLeme commented Oct 4, 2024 •

Copy link
Copy Markdown
Contributor

What does this PR do?

It changes the plugin loading flow to be from URL parameter pointing to a manifest.json file instead of the previous plugin settings, this will lay the grounds to create a new server-side component for plugins, which will later on be better explained (following PRs).

See demo of a sample plugin useMeeting as an example of how one can load a plugin now:

demo_manifest.mp4

So in the video, one can see that the following plugin parameters have been given:

pluginsManifests=[{url:"http://172.17.0.1:4701/manifest.json", checksum="<sha256 of the file>"}]

Parameter pluginsManifests is a list of the manifest.json URLs and its file checksum (which can be omitted, if that's the case, then it will pass that verification - one can obtain it with the command sha256sum manifest.json) and the meta_pluginSettingsUserInformation is a meta parameter that indicates what is going to be replaced in the manifest.json template strings.

{
  "requiredSdkVersion": "~0.0.59",
  "name": "sampleUseMeeting",
  "javascriptEntrypointIntegrity": "aad1db35f0b1aa1072936d9977fa3cb7",
  "javascriptEntrypointUrl": "http://127.0.0.1:4701/static/SampleUseMeeting.js",
  "localesBaseUrl": "https://cdn.dominio.com/pluginabc/",
  "eventPersistence": {
      "isEnabled": true,
      "maximumPayloadSizeInBytes": 1024,
      "rateLimiting": {
          "messagesAllowedPerSecond": 10,
          "messagesAllowedPerMinute": 20
      }
  }
}

One can also test it with the new plugin lms-user-information, this would require the following URL parameter when testing in a dev server:

pluginsManifests=[{url:"http://172.17.0.1:4701/manifest.json", checksum="<sha256 of the file>"}]
meta_pluginSettingsUserInformation=https://localhost:9000/api/users

See the manifest of lms-user-information (there are some fields that will not be part of the official lms-user-information, they are there just to test if everything will be in place - that's the case for the data-channel, which is currently used as a matter of testing, as well observed in the logs):

{
  "requiredSdkVersion": "~0.0.59",
  "name": "lmsUserInformation",
  "javascriptEntrypointUrl": "http://127.0.0.1:4701/static/LmsUserInformation.js",
  "localesBaseUrl": "https://cdn.dominio.com/pluginabc/",
  "eventPersistence": {
      "isEnabled": true,
      "maximumPayloadSizeInBytes": 1024,
      "rateLimiting": {
          "messagesAllowedPerSecond": 10,
          "messagesAllowedPerMinute": 20
      }
  },
  "dataChannels": [
      {
          "name": "goldStars",
          "pushPermission": ["moderator", "presenter"],
          "replaceOrDeletePermission": ["creator", "moderator"]
      }
  ],
  "remoteDataSources": [
      {
          "name": "allUsers",
          "url": "${meta_pluginSettingsUserInformation}",
          "fetchMode": "onMeetingCreate",
          "permissions": ["moderator", "viewer"]
      }
  ]
}

(P.S.: The error logs in the console are just happening due to the development mode of the plugin, when built, this will not happen)

Motivation

The LMS integration.

How to test

Just run the plugin, and send a create call with the URL parameters mentioned here. This will allow you to see the log of the loaded plugin (in our case, the lms-user-information) and the log of the data-channel. If you want to see the star and all the extensible areas, there's the need to run the server-side of this plugin:

In the root of the plugin, just run:

cd server-side/
docker-compose up -d

It needs the docker-compose command as well as the docker itself.

More

Closely related to PR: https://github.com/bigbluebutton/plugin-lms-user-information/pull/1

… plugins from a URL parameter of manifest.json until the pluginLoader component of the client.
@coderabbitai

This comment was marked as off-topic.

@antobinary antobinary added this to the Release 3.0 milestone Oct 4, 2024

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 32

🧹 Outside diff range and nitpick comments (33)
bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts (2)

3-8: LGTM: Query definition is correct with minor suggestions.

The PLUGIN_CONFIGURATION_QUERY is well-structured and aligns with the PR objectives. It correctly retrieves the name and javascriptEntrypointUrl from the plugin field.

Some minor suggestions for improvement:

  1. Consider removing the trailing comma after javascriptEntrypointUrl, for consistency.
  2. Standardize the indentation to either 2 or 4 spaces throughout the query.

Here's a suggested refinement:

 const PLUGIN_CONFIGURATION_QUERY = gql`query PluginConfigurationQuery {
   plugin {
-    name,
-    javascriptEntrypointUrl,
+    name
+    javascriptEntrypointUrl
   }  
 }`;

1-10: Overall assessment: Well-implemented GraphQL query for plugin configuration.

This new file introduces a GraphQL query that aligns well with the PR objectives. It retrieves the necessary information (name and JavaScript entrypoint URL) for the new plugin loading mechanism. The implementation is clean and follows good practices, with only minor suggestions for improvement in formatting.

The query supports the described change in the plugin loading flow, where plugins are now loaded based on a URL parameter pointing to a manifest.json file. This implementation will facilitate the development of server-side components for plugins as mentioned in the PR objectives.

As the plugin system evolves, consider the following architectural advice:

  1. Ensure that error handling is implemented when using this query, in case the plugin configuration is not available or malformed.
  2. As more plugin-related queries are added, consider grouping them in a dedicated plugins GraphQL module for better organization.
  3. Think about versioning the GraphQL schema to allow for future extensions of the plugin configuration without breaking existing implementations.
bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (2)

7-10: LGTM! Consider adding JSDoc comments.

The PluginConfigFromGraphql interface is well-defined and aligns with the PR objectives. It provides a clear structure for plugin configuration data, likely fetched via GraphQL.

Consider adding JSDoc comments to provide more context about the interface and its properties. For example:

/**
 * Represents the configuration for a plugin fetched via GraphQL.
 */
export interface PluginConfigFromGraphql {
  /** The URL of the JavaScript entry point for the plugin */
  javascriptEntrypointUrl: string;
  /** The name of the plugin */
  name: string;
}

12-14: LGTM! Consider adding JSDoc comments.

The PluginsEngineManagerProps interface is well-defined and aligns with the PR objectives. It provides a flexible structure for passing plugin configurations to a PluginsEngineManager component.

Consider adding JSDoc comments to provide more context about the interface and its property. For example:

/**
 * Props for the PluginsEngineManager component.
 */
export interface PluginsEngineManagerProps {
  /** An array of plugin configurations or undefined if no plugins are configured */
  pluginConfig: PluginConfigFromGraphql[] | undefined;
}
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (2)

1-8: LGTM! Consider clarifying table type.

The table configuration looks good. The custom_name "plugin" will be useful for GraphQL queries.

Consider adding a comment to clarify if v_plugin is a view or a table, as the "v_" prefix suggests it might be a view.


9-18: LGTM! Consider adding a descriptive comment.

The select permissions for the bbb_client role are well-defined, providing access to necessary columns (javascriptEntrypointUrl and name) while ensuring data isolation through the meetingId filter.

Consider adding a descriptive comment to explain the purpose of these permissions. For example:

comment: "Allows BigBlueButton clients to access plugin information for their specific meeting."
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/LiveMeeting.scala (1)

Line range hint 1-30: Consider architectural implications of adding plugin support

The addition of the plugins parameter to the LiveMeeting class represents a significant change in how the system handles plugins. This change aligns with the PR objectives but may have broader implications:

  1. Architecture: Consider whether this change adheres to the existing architectural patterns of the system. Does it maintain separation of concerns?

  2. Scalability: As more plugins are added, how will this affect the LiveMeeting class? Consider if there's a need for a separate plugin management system to avoid bloating this class.

  3. Testability: Ensure that this change doesn't make the LiveMeeting class harder to test. Consider if mock PluginModel objects will be easy to create for testing purposes.

  4. Documentation: It might be beneficial to add class-level documentation explaining the role of plugins in the LiveMeeting context.

  5. Future-proofing: Consider if this approach will be flexible enough for future plugin-related features mentioned in the PR objectives, such as server-side components for plugins.

Would you like assistance in drafting documentation or considering alternative architectural approaches for plugin management?

bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (1)

Line range hint 13-48: Consider enhancing error handling and cleanup

While the current implementation is functional, consider the following improvements:

  1. Error handling: Add a try-catch block around the script creation and appending process to handle any unexpected errors.
  2. Cleanup: Implement a cleanup function in the useEffect hook to remove the created elements when the component unmounts.

Here's a suggested implementation:

useEffect(() => {
  if (!plugin || !containerRef) {
    return;
  }

  const div = document.createElement('div');
  div.id = uuid;
  const script = document.createElement('script');

  const cleanup = () => {
    div.remove();
    script.remove();
  };

  try {
    containerRef.current?.appendChild(div);

    script.onload = () => {
      setNumberOfLoadedPlugins((current) => current + 1);
      setLastLoadedPlugin(script);
      logger.info({
        logCode: 'plugin_loaded',
      }, `Loaded plugin ${plugin.name}`);
    };
    script.onerror = (error) => {
      logger.error({
        logCode: 'plugin_load_error',
        extraInfo: {
          pluginName: plugin.name,
          pluginUrl: plugin.url,
          error: error.toString(),
        },
      }, `Error when loading plugin ${plugin.name}`);
      cleanup();
    };
    script.src = plugin.url;
    script.setAttribute('uuid', div.id);
    script.setAttribute('pluginName', plugin.name);
    if (plugin.checksum) {
      script.setAttribute('integrity', plugin.checksum);
    }
    document.head.appendChild(script);
  } catch (error) {
    logger.error({
      logCode: 'plugin_load_unexpected_error',
      extraInfo: {
        pluginName: plugin.name,
        error: error.toString(),
      },
    }, `Unexpected error when loading plugin ${plugin.name}`);
    cleanup();
  }

  return cleanup;
}, [plugin, containerRef]);

This implementation adds a cleanup function, enhances error logging, and ensures that resources are properly cleaned up in case of errors or when the component unmounts.

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

Removed views are still in use in the codebase

The verification process found that some of the removed views are still being referenced in the codebase, which may lead to breaking changes:

  • bbb-graphql-server/metadata/actions.graphql:
    • breakoutRoom
    • caption
    • chat
    • externalVideo
    • layout
    • meeting
    • poll
    • sharedNotes
    • timer
    • user

Please address these usages to prevent potential issues caused by the removal of these views.

🔗 Analysis chain

Line range hint 1-27: Verify the intentionality and impact of extensive view removals.

The removal of numerous public view inclusions represents a significant change to the database schema or GraphQL API. While this simplifies the schema, it may have far-reaching implications:

  1. Potential breaking changes: Existing GraphQL queries or resolvers that depend on these views may no longer function.
  2. Data access limitations: The removal of these views might restrict access to previously available data.

Please confirm that this extensive removal aligns with the intended scope of the PR. If it does, consider the following actions:

  1. Update the PR description to explicitly mention this major restructuring.
  2. Provide a migration guide for users of the affected views.
  3. Update any related documentation to reflect these changes.

To assess the impact, run the following script to check for usage of the removed views in the codebase:

This script will help identify potential areas of the codebase that may need updates due to the removal of these views.

Also applies to: 29-65


Let's address the syntax error in your shell script and ensure it runs correctly. Please use the following corrected script:

[/run_scripts]

Please run this corrected script to check for usage of the removed views. Once you have the output, provide it here so we can continue the verification process.


Let's resolve the issue with the shell script by updating it to correctly handle GraphQL files. Please use the following revised script:

[/run_scripts]

Please run this corrected script and provide the output so we can continue the verification process.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of removed views in the codebase

# Get a list of removed view names
removed_views=$(grep -oP '(?<=public_v_).*(?=\.yaml)' bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml | sed 's/_/./g')

# Search for usage of removed views in the codebase
echo "Searching for usage of removed views..."
for view in $removed_views; do
  echo "Checking usage of $view:"
  rg -i "$view" --type ts --type js --type graphql
  echo "---"
done

Length of output: 1884


Script:

#!/bin/bash
# Description: Check for usage of removed views in the codebase

# Get a list of removed view names
removed_views=$(grep -oP '(?<=public_v_).*(?=\.yaml)' bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml | sed 's/_/./g')

# Search for usage of removed views in the codebase
echo "Searching for usage of removed views..."
for view in $removed_views; do
  echo "Checking usage of $view:"
  rg -i "$view" --type ts --type js --type graphql
  echo "---"
done

Length of output: 15419


Script:

#!/bin/bash
# Description: Check for usage of removed views in the codebase

# Get a list of removed view names
removed_views=$(grep -oP '(?<=public_v_).*(?=\.yaml)' bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml | sed 's/_/./g')

# Search for usage of removed views in the codebase
echo "Searching for usage of removed views..."
for view in $removed_views; do
  echo "Checking usage of $view:"
  rg -i "$view" --type ts --type js -g "*.graphql" -g "*.gql"
  echo "---"
done

Length of output: 23794

bigbluebutton-html5/imports/ui/components/plugins-engine/manager.tsx (4)

2-2: LGTM! Consider grouping related imports.

The changes to the import statements look good. Removing useMemo and adding PluginsEngineManagerProps align with the component's updated implementation.

Consider grouping related imports together for better readability. For example, you could move the PluginsEngineManagerProps import next to other React-related imports.

Also applies to: 12-12


25-25: Good improvements in state management!

The changes in props and state management look good:

  1. Using pluginConfig from props instead of a global variable improves component encapsulation.
  2. Introducing effectivePluginsConfig state allows for dynamic updates.
  3. Replacing loadedPlugins with numberOfLoadedPlugins provides more precise tracking of the loading process.

Consider adding a comment explaining the purpose of effectivePluginsConfig for better code documentation.

Also applies to: 30-31


33-44: Good use of useEffect for dynamic updates!

The new useEffect hook effectively replaces the previous useMemo implementation, allowing for dynamic updates of effectivePluginsConfig when pluginConfig changes. The mapping logic, including UUID generation, looks correct.

Consider extracting the mapping logic into a separate function for better readability and testability. For example:

const mapToEffectiveConfig = (config) => ({
  ...config,
  name: config.name,
  url: config.javascriptEntrypointUrl,
  uuid: uuidLib.v4(),
});

useEffect(() => {
  setEffectivePluginsConfig(pluginConfig?.map(mapToEffectiveConfig));
}, [pluginConfig]);

Line range hint 66-75: Good job updating the rendering logic!

The changes in the rendering logic correctly use the new effectivePluginsConfig state and setNumberOfLoadedPlugins function, aligning with the earlier updates to state management and prop usage. The use of optional chaining is a good practice for safe access.

Consider adding a fallback rendering in case effectivePluginsConfig is undefined:

{effectivePluginsConfig?.map((effectivePluginConfig: EffectivePluginConfig) => (
  // ... existing code
)) || <div>No plugins configured</div>}

This would provide a better user experience when no plugins are configured.

bbb-common-message/src/main/scala/org/bigbluebutton/common2/domain/Meeting2x.scala (1)

90-90: Add documentation for the new pluginProp field

Consider adding a comment or ScalaDoc to explain the purpose and expected content of the pluginProp field. This will help other developers understand how to use this new property correctly.

Example documentation:

/**
 * @param pluginProp A map containing plugin-related properties.
 *                   Keys are expected to be plugin identifiers,
 *                   and values can be any reference type containing plugin configuration.
 */
bbb-common-web/src/main/java/org/bigbluebutton/api/ApiParams.java (1)

76-76: LGTM! Consider adding a brief comment for clarity.

The addition of the PLUGINS constant aligns well with the PR objectives and follows the existing coding conventions. It's correctly implemented as a public static final String, consistent with other API parameters in this class.

Consider adding a brief comment above the constant to describe its purpose, similar to other constants in this file. For example:

// Param to specify URLs of plugin manifest.json files
public static final String PLUGINS = "plugins";

This would enhance code readability and maintain consistency with the documentation style of other constants in this class.

bigbluebutton-html5/imports/ui/components/app/component.jsx (2)

265-265: LGTM: PluginsEngineManager updated with pluginConfig prop

The addition of the pluginConfig prop to the PluginsEngineManager component is in line with the PR objectives for the new plugin loading mechanism.

Consider adding prop type validation for pluginConfig to improve type safety and documentation. You can add it to the propTypes object like this:

const propTypes = {
  // ... existing prop types
  pluginConfig: PropTypes.object, // Adjust the type as needed
};

No existing tests found for plugin loading

The changes to add support for the new plugin configuration lack corresponding tests to verify that the pluginConfig prop is correctly passed and handled by the PluginsEngineManager. It's recommended to add or update tests to cover these changes.

🔗 Analysis chain

Line range hint 253-265: Overall changes look good, consider additional testing

The changes to add support for the new plugin configuration are minimal and well-aligned with the PR objectives. The implementation is non-intrusive and shouldn't affect existing functionality.

To ensure the new plugin loading mechanism works as expected, consider adding or updating tests for the following:

  1. Verify that the pluginConfig prop is correctly passed to the PluginsEngineManager.
  2. Test the PluginsEngineManager with various pluginConfig values to ensure it handles different configurations correctly.
  3. Integration tests to verify that plugins are loaded correctly using the new URL parameter mechanism.

You can use the following script to check for existing tests related to plugin loading:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing tests related to plugin loading
echo "Searching for existing plugin loading tests..."
rg --type js --type jsx 'test|describe|it.*plugin' ./bigbluebutton-html5/imports/ui/components/

Length of output: 228


Script:

#!/bin/bash
# Search for existing tests related to plugin loading in .js and .jsx files
echo "Searching for existing plugin loading tests..."
rg 'test|describe|it.*plugin' --glob '*.js' --glob '*.jsx' ./bigbluebutton-html5/imports/ui/components/

Length of output: 38491

bbb-common-web/src/main/scala/org/bigbluebutton/api2/BbbWebApiGWApp.scala (3)

170-171: LGTM: New parameters added to createMeeting method

The addition of plugins and overrideClientSettings parameters to the createMeeting method signature aligns with the PR objectives. This change enables the new plugin loading mechanism and allows for client settings override.

Consider adding documentation comments for these new parameters to explain their purpose and expected values.


Line range hint 268-281: LGTM: New parameters incorporated into DefaultProps

The plugins and overrideClientSettings parameters are correctly added to the DefaultProps object construction, ensuring they are passed along in the meeting creation process.

Consider adding a comment explaining the purpose of these new parameters in the DefaultProps object, especially if they introduce new behavior in the meeting creation process.


Line range hint 1-424: Summary: Successfully implemented new plugin loading mechanism

The changes in this file successfully implement the new plugin loading mechanism as described in the PR objectives. The createMeeting method has been updated to accept plugin data and client settings override, which are then incorporated into the meeting creation process.

Key changes:

  1. Added import for java.util
  2. Updated createMeeting method signature with new parameters
  3. Incorporated new parameters into DefaultProps object

These modifications provide a solid foundation for the server-side component of plugins, which will be elaborated upon in future pull requests.

As you continue to develop the plugin system, consider the following:

  1. Ensure proper validation of plugin data to maintain system security and stability.
  2. Document the expected structure and content of the plugins map for future developers and plugin creators.
  3. Implement appropriate error handling for cases where invalid plugin data is provided.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala (1)

Line range hint 1-1000: Consider refactoring MeetingActor for improved maintainability

While the current change is small and focused, the overall structure of the MeetingActor class raises some concerns:

  1. Single Responsibility Principle: The class handles a wide variety of tasks, from user management to presentation control. Consider breaking it down into smaller, more focused components.

  2. Cognitive Complexity: The large number of message handlers in the receive method makes the class difficult to understand and maintain. Consider grouping related handlers into separate traits or classes.

  3. Testability: The complexity of this class likely makes it challenging to test thoroughly. Smaller, more focused components would be easier to test in isolation.

  4. Error Handling: With so many responsibilities, ensure that error handling is consistent and robust throughout the class.

Consider the following refactoring strategies:

  1. Extract related message handlers into separate traits (e.g., UserManagementHandlers, PresentationHandlers, etc.) and mix them into the MeetingActor.
  2. Use the Command pattern to encapsulate message handling logic, allowing for easier testing and maintenance.
  3. Implement a state machine to manage the meeting lifecycle, improving the clarity of the actor's behavior.

Example of extracting handlers into a trait:

trait UserManagementHandlers { this: MeetingActor =>
  def handleUserJoinMeetingReqMsg(msg: UserJoinMeetingReqMsg, state: MeetingState2x): MeetingState2x = {
    // Existing implementation
  }

  def handleUserLeaveReqMsg(msg: UserLeaveReqMsg, state: MeetingState2x): MeetingState2x = {
    // Existing implementation
  }

  // Other user management related handlers
}

class MeetingActor extends BaseMeetingActor with UserManagementHandlers with PresentationHandlers // ...

This refactoring would significantly improve the maintainability and testability of the MeetingActor class.

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

1967-1973: LGTM! Consider adding an index for performance.

The plugin table structure is well-defined with appropriate primary and foreign key constraints. This design allows for multiple plugins per meeting while maintaining data integrity.

Consider adding an index on the name column to improve query performance when searching for specific plugins:

CREATE INDEX idx_plugin_name ON plugin(name);

1975-1975: LGTM! Consider enhancing the view for more utility.

The v_plugin view provides a simple way to access all plugin data. This is a good starting point for querying plugin information.

Consider enhancing the view to provide more utility. For example, you could join it with the meeting table to include meeting-related information or add calculated fields that might be useful for common queries:

CREATE OR REPLACE VIEW v_plugin AS
SELECT p.*, m.name AS meeting_name, m.createdAt AS meeting_created_at
FROM plugin p
JOIN meeting m ON p.meetingId = m.meetingId;

Line range hint 1979-2015: LGTM! Well-structured data model with performance considerations.

The pluginDataChannelEntry table and related objects are well-designed, with several notable features:

  1. Use of UUID for unique identifiers.
  2. Flexible data storage using jsonb for payloads.
  3. Composite primary key and multiple indexes for query performance.
  4. A view that filters and orders data based on user roles and permissions.

Consider the following enhancements:

  1. Add a comment explaining the purpose of the uuid-ossp extension:
-- Enable UUID generation for unique identifiers
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
  1. Consider using ON CONFLICT clause for upsert operations:
INSERT INTO pluginDataChannelEntry (...)
ON CONFLICT (meetingId, pluginName, channelName, entryId, subChannelName)
DO UPDATE SET
  payloadJson = EXCLUDED.payloadJson,
  -- Update other fields as needed
  1. In the view, consider adding a LIMIT clause or implementing pagination to prevent potential performance issues with large datasets:
CREATE OR REPLACE VIEW "v_pluginDataChannelEntry" AS
SELECT ...
FROM ...
WHERE ...
ORDER BY m."createdAt"
LIMIT 1000; -- Adjust the limit as needed
  1. Consider adding a trigger to automatically set the deletedAt timestamp when soft-deleting entries, if that's a requirement of your application.

Given the potential for this table to grow large, consider implementing a partitioning strategy based on meetingId or createdAt to improve query performance and data management for long-running or high-volume systems.


Line range hint 1965-2015: Overall, these changes provide a solid foundation for plugin management.

The additions to the schema introduce a flexible and performant structure for managing plugins and their associated data channels. This new functionality appears to be a significant enhancement to the BigBlueButton system, allowing for greater extensibility and customization.

Key points:

  1. The plugin table provides a simple way to associate plugins with meetings.
  2. The pluginDataChannelEntry table offers a flexible data storage solution with performance optimizations.
  3. The views provide convenient and secure access to the plugin data.

These changes lay the groundwork for robust plugin support, which could greatly enhance the functionality and adaptability of the BigBlueButton platform.

As this feature develops, consider the following architectural considerations:

  1. Implement a caching strategy for frequently accessed plugin data to reduce database load.
  2. Develop a clear API for plugins to interact with this data layer, ensuring consistency and security.
  3. Plan for data archiving or cleanup processes, especially for the pluginDataChannelEntry table, which may grow large over time.
  4. Consider implementing event-driven mechanisms (e.g., triggers or message queues) to notify relevant parts of the system about plugin data changes.
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala (1)

58-58: Handle potential JSON parsing errors

When parsing JSON in createPluginModelFromJson, it's important to handle scenarios where parsing might fail due to malformed JSON. Currently, the code silently defaults to an empty map, which might mask issues with the input data. Consider adding logging or error handling to address this.

Example:

def createPluginModelFromJson(jsonString: String): PluginModel = {
  val pluginsResult = JsonUtil.fromJson[Map[String, Plugin]](jsonString)
  pluginsResult match {
    case Some(plugins) => new PluginModel(plugins)
    case None =>
      // Log the error or throw an exception
      // Logger.warn("Failed to parse plugins JSON")
      new PluginModel()
  }
}
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (1)

36-37: Use proper logging instead of println.

Using println for logging may not integrate with the application's logging framework and can lead to inconsistent log management. Consider replacing println statements with the appropriate logging methods (e.g., logger.warn or logger.error) to ensure consistent and configurable logging.

Apply this diff to update the logging statements:

- println(s"No permission to delete (reset) in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
+ logger.warn(s"No permission to delete (reset) in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")

- println(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
+ logger.warn(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")

- println(s"Plugin '${msg.body.pluginName}' not found.")
+ logger.warn(s"Plugin '${msg.body.pluginName}' not found.")

Also applies to: 45-45, 47-47

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (1)

35-36: Use a logging framework instead of println for error messages

Currently, println is used to log error messages. It's recommended to use a logging framework for better control over logging levels and outputs.

Consider replacing println statements with a proper logging mechanism, such as SLF4J or Logback.

Also applies to: 48-48, 50-50

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (3)

45-45: Replace println with a proper logging mechanism

Using println for logging is discouraged in production code. Consider using a logging framework (e.g., SLF4J, Log4j) to handle logging, which provides better control over log levels and outputs.


45-45: Use a logging framework instead of println statements

Using println for error messages is not recommended in production code. Replace println with a logging framework to improve logging consistency and control.

Suggested change:

Import the logging library and replace println with appropriate logging methods.

+import org.slf4j.LoggerFactory

 trait PluginDataChannelReplaceEntryMsgHdlr extends HandlerHelpers {
+  private val logger = LoggerFactory.getLogger(classOf[PluginDataChannelReplaceEntryMsgHdlr])

   def handle(msg: PluginDataChannelReplaceEntryMsg, state: MeetingState2x, liveMeeting: LiveMeeting): Unit = {
     // existing code...
     if (!hasPermission.contains(true)) {
-      println(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
+      logger.warn(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
     } else {
       // existing code...
     }
     // existing code...
-    case None => println(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
+    case None => logger.warn(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
   }
+  case None =>
+    logger.warn(s"Plugin '${msg.body.pluginName}' not found.")
 }

Also applies to: 56-57


24-42: Handle None cases explicitly for better clarity

Currently, if dc.replaceOrDeletePermission is None, hasPermission becomes None, and the user is denied permission by default. To enhance code clarity, consider providing an explicit default permission.

Suggested change:

Modify the code to handle the None case explicitly:

-          val hasPermission = for {
-            replaceOrDeletePermission <- dc.replaceOrDeletePermission
-          } yield {
-            replaceOrDeletePermission.toLowerCase match {
+          val hasPermission = dc.replaceOrDeletePermission match {
+            case Some(permission) =>
+              permission.toLowerCase match {
                 // existing cases...
+              }
+            case None =>
+              false // or true, depending on the intended default behavior
           }

This makes the default permission behavior explicit and improves code readability.

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

13-13: Unused import getPlugins can be removed.

The import statement for org.bigbluebutton.core.models.PluginModel.getPlugins is not used within the provided code. Removing unused imports helps keep the codebase clean and reduces potential confusion.

Apply this diff to remove the unused import:

-import org.bigbluebutton.core.models.PluginModel.getPlugins
bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (1)

407-407: Fix spacing in exception message

There is a missing space in the exception message, resulting in a concatenated sentence. The message currently reads:

"For url " + manifestUrl + "there is no name field configured."

It should read:

"For url " + manifestUrl + " there is no name field configured."

Apply this fix:

-            throw new NoSuchFieldException("For url " + manifestUrl + "there is no name field configured.");
+            throw new NoSuchFieldException("For url " + manifestUrl + " there is no name field configured.");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a1ef524 and 1ea9642.

📒 Files selected for processing (27)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PluginDAO.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/LiveMeeting.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/core/running/RunningMeeting.scala (3 hunks)
  • bbb-common-message/src/main/scala/org/bigbluebutton/common2/domain/Meeting2x.scala (2 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ApiParams.java (1 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (7 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (2 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/domain/Meeting.java (5 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api2/IBbbWebApiGWApp.java (1 hunks)
  • bbb-common-web/src/main/scala/org/bigbluebutton/api2/BbbWebApiGWApp.scala (3 hunks)
  • bbb-graphql-server/bbb_schema.sql (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml (1 hunks)
  • bigbluebutton-html5/client/meetingClient.jsx (2 hunks)
  • bigbluebutton-html5/imports/ui/components/app/component.jsx (2 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (2 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/loader/types.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/manager.tsx (5 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/styles.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/styles.ts
🔇 Additional comments (34)
bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts (2)

1-1: LGTM: Import statement is correct.

The import of gql from '@apollo/client' is appropriate for defining GraphQL queries.


10-10: LGTM: Export statement is correct.

The default export of PLUGIN_CONFIGURATION_QUERY is appropriate and follows common practices. This allows for easy import and use of the query in other parts of the application.

bigbluebutton-html5/imports/ui/components/plugins-engine/loader/types.ts (1)

6-6: Approve the change to state management for loaded plugins count.

The modification from loadedPlugins: React.MutableRefObject<number> to setNumberOfLoadedPlugins: React.Dispatch<React.SetStateAction<number>> represents an improvement in state management. This change aligns with React's recommended practices for handling component state.

Consider the following implications:

  1. The component using this interface will need to be updated to use the useState hook for managing the number of loaded plugins.
  2. This change allows for more predictable updates and re-renders when the number of loaded plugins changes.
  3. Ensure that all components consuming the PluginLoaderManagerProps are updated to work with the new state setter function.

To verify the impact of this change, let's search for usages of the PluginLoaderManagerProps interface:

✅ Verification successful

The change to state management for the loaded plugins count is verified and approved.

  • The PluginLoaderManagerProps interface is only used within types.ts and manager.tsx.
  • No additional components are affected by this change.
  • Ensure that manager.tsx properly utilizes the setNumberOfLoadedPlugins state setter.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of PluginLoaderManagerProps
rg --type typescript "PluginLoaderManagerProps" -A 10

Length of output: 88


Script:

#!/bin/bash
# Search for usages of PluginLoaderManagerProps in TypeScript files
rg "PluginLoaderManagerProps" --glob "*.ts" --glob "*.tsx" -A 10

Length of output: 2422

bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (1)

7-14: Verify usage of new interfaces in the codebase.

The new interfaces PluginConfigFromGraphql and PluginsEngineManagerProps are well-defined and support the new plugin loading mechanism. To ensure proper integration, it's important to verify their usage across the codebase.

Run the following script to check for usage of the new interfaces:

Please review the results to ensure that the new interfaces are being used appropriately throughout the codebase.

✅ Verification successful

Re-run usage checks with corrected file types.

Please execute the following updated script to verify the usage of the new interfaces in the codebase:


Re-run usage checks with corrected file patterns.

Please execute the following updated script to verify the usage of the new interfaces in the codebase:


Verification successful: New interfaces are utilized appropriately.

  • PluginsEngineManagerProps is used in manager.tsx.
  • PluginConfigFromGraphql is used in types.ts and manager.tsx.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of new interfaces in the codebase

# Test: Search for usage of PluginConfigFromGraphql
echo "Searching for usage of PluginConfigFromGraphql:"
rg --type typescript "PluginConfigFromGraphql" -g '!types.ts'

# Test: Search for usage of PluginsEngineManagerProps
echo "Searching for usage of PluginsEngineManagerProps:"
rg --type typescript "PluginsEngineManagerProps" -g '!types.ts'

# Test: Search for potential places where these interfaces should be used
echo "Searching for potential usage locations:"
rg --type typescript "pluginConfig|PluginsEngineManager"

Length of output: 594


Script:

#!/bin/bash
# Description: Check for usage of new interfaces in the codebase

# Test: Search for usage of PluginConfigFromGraphql
echo "Searching for usage of PluginConfigFromGraphql:"
rg --type ts --type tsx "PluginConfigFromGraphql" -g '!types.ts'

# Test: Search for usage of PluginsEngineManagerProps
echo "Searching for usage of PluginsEngineManagerProps:"
rg --type ts --type tsx "PluginsEngineManagerProps" -g '!types.ts'

# Test: Search for potential places where these interfaces should be used
echo "Searching for potential usage locations:"
rg --type ts --type tsx "pluginConfig|PluginsEngineManager"

Length of output: 582


Script:

#!/bin/bash
# Description: Check for usage of new interfaces in the codebase using explicit file patterns

# Test: Search for usage of PluginConfigFromGraphql
echo "Searching for usage of PluginConfigFromGraphql:"
rg "PluginConfigFromGraphql" -g "*.ts" -g "*.tsx" --glob '!types.ts'

# Test: Search for usage of PluginsEngineManagerProps
echo "Searching for usage of PluginsEngineManagerProps:"
rg "PluginsEngineManagerProps" -g "*.ts" -g "*.tsx" --glob '!types.ts'

# Test: Search for potential places where these interfaces should be used
echo "Searching for potential usage locations:"
rg "pluginConfig|PluginsEngineManager" -g "*.ts" -g "*.tsx"

Length of output: 2156

bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (2)

25-25: State update approach improved

The change from directly incrementing a ref to using a functional state update with setNumberOfLoadedPlugins is a good improvement. This approach is more in line with React's state management best practices and ensures that the state updates are properly queued and batched by React.


8-11: Prop signature updated: Verify usage in parent components

The loadedPlugins prop has been replaced with setNumberOfLoadedPlugins. This change improves the state management approach by using a setter function instead of a mutable ref.

To ensure this change doesn't break any existing functionality, let's verify the usage of this component:

✅ Verification successful

Verified: loadedPlugins prop successfully replaced with setNumberOfLoadedPlugins

The loadedPlugins prop has been successfully removed and replaced with setNumberOfLoadedPlugins. All parent components have been updated accordingly, ensuring consistent state management.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usages of PluginLoaderManager and its props

# Search for PluginLoaderManager usage
echo "Searching for PluginLoaderManager usage:"
rg --type typescript --type tsx "PluginLoaderManager" -C 5

# Search for loadedPlugins prop (old version)
echo "\nSearching for loadedPlugins prop (should be removed):"
rg --type typescript --type tsx "loadedPlugins\s*[:=]" -C 5

# Search for setNumberOfLoadedPlugins (new version)
echo "\nSearching for setNumberOfLoadedPlugins prop (should be added):"
rg --type typescript --type tsx "setNumberOfLoadedPlugins\s*[:=]" -C 5

Length of output: 649


Script:

#!/bin/bash
# Description: Check for usages of PluginLoaderManager and its props

# Search for PluginLoaderManager usage
echo "Searching for PluginLoaderManager usage:"
rg "PluginLoaderManager" -g "*.ts" -g "*.tsx" -C 5

# Search for loadedPlugins prop (old version)
echo "\nSearching for loadedPlugins prop (should be removed):"
rg "loadedPlugins\s*[:=]" -g "*.ts" -g "*.tsx" -C 5

# Search for setNumberOfLoadedPlugins prop (new version)
echo "\nSearching for setNumberOfLoadedPlugins prop (should be added):"
rg "setNumberOfLoadedPlugins\s*[:=]" -g "*.ts" -g "*.tsx" -C 5

Length of output: 6812

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

28-28: Addition of plugin view aligns with PR objectives.

The inclusion of public_v_plugin.yaml is consistent with the PR's goal of modifying the plugin loading mechanism. This change supports the development of a server-side component for plugins as mentioned in the PR objectives.

To ensure proper implementation, please verify that the public_v_plugin.yaml file contains the necessary fields to support the new plugin loading mechanism, particularly the ability to specify plugins via URL parameters.

Run the following script to check the contents of the new plugin view:

#!/bin/bash
# Description: Check contents of the new plugin view

echo "Contents of public_v_plugin.yaml:"
cat bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml

echo "\nChecking for URL-related fields:"
grep -i "url" bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml

This will help ensure that the new view supports the URL-based plugin loading mechanism described in the PR objectives.


Line range hint 1-65: Recommend comprehensive testing and documentation updates.

Given the extensive changes to the database schema or GraphQL API, it's crucial to ensure that these modifications don't introduce unintended consequences or breaking changes.

Please consider the following recommendations:

  1. Comprehensive testing:

    • Update and run all existing unit and integration tests.
    • Create new tests to cover the modified plugin functionality.
    • Perform thorough end-to-end testing of the BigBlueButton platform to ensure no regressions.
  2. Documentation updates:

    • Update API documentation to reflect the removed views and the new plugin view.
    • Provide migration guides for users who may be affected by the removed views.
    • Update any developer guides or tutorials that reference the changed schema.
  3. Performance impact:

    • Assess the performance impact of these changes, particularly in terms of query complexity and response times.

To assist with documentation updates, run the following script to generate a list of changed views:

#!/bin/bash
# Description: Generate a list of changed views for documentation updates

echo "Removed views:"
grep -oP '(?<=public_v_).*(?=\.yaml)' bbb-graphql-server/metadata/databases/BigBlueButton/tables/tables.yaml | sed 's/^/- /'

echo "\nAdded views:"
echo "- plugin"

echo "\nChecking for existing documentation files:"
fd -e md -e rst | rg -i "api|schema|database|graphql"

This script will help identify documentation files that may need updates based on the schema changes.

bigbluebutton-html5/client/meetingClient.jsx (4)

34-35: LGTM: New imports for plugin configuration.

The new imports for createUseSubscription and PLUGIN_CONFIGURATION_QUERY are correctly added and align with the PR objectives of implementing a new plugin loading mechanism.


Line range hint 1-78: Overall assessment: Implementation aligns with PR objectives.

The changes in this file successfully implement the new plugin loading mechanism as described in the PR objectives. The new imports, subscription creation, and prop passing to the Base component all contribute to this new functionality.

A few points to address:

  1. Clarify the purpose of the identity function in the createUseSubscription call.
  2. Verify that the Base component is prepared to handle the new pluginConfig prop.

Once these points are addressed, the implementation looks solid and ready for integration.


72-72: LGTM: Passing plugin configuration to Base component. Verification needed.

The pluginConfig is now correctly passed to the Base component, which aligns with the PR objectives of modifying the plugin loading mechanism.

To ensure full compatibility, please verify that the Base component is prepared to receive and utilize this new pluginConfig prop.

Let's verify the Base component implementation:

#!/bin/bash
# Description: Check the Base component implementation for pluginConfig prop usage
rg --type javascript -A 10 "function Base.*props" imports/startup/client/
rg --type javascript "pluginConfig.*props" imports/startup/client/

65-67: LGTM: New subscription for plugin configuration. Clarification needed.

The new subscription for plugin configuration is correctly implemented using createUseSubscription with PLUGIN_CONFIGURATION_QUERY. This aligns with the PR objectives.

However, could you please clarify the purpose of the arrow function (obj) => obj passed as the second argument to createUseSubscription? It appears to be an identity function, but its necessity is not immediately clear.

To verify the usage of createUseSubscription, let's check its implementation:

bigbluebutton-html5/imports/ui/components/plugins-engine/manager.tsx (3)

21-21: Great job on improving type safety!

The updated component signature with PluginsEngineManagerProps enhances type checking and improves the overall robustness of the component.


49-52: LGTM! Logging update is consistent with state changes.

The update to the logging statement correctly uses the new numberOfLoadedPlugins state variable, maintaining consistency with the earlier state management changes.


Line range hint 1-101: Overall, great improvements to plugin management!

The changes in this file significantly enhance the flexibility and robustness of the plugin management system. The shift from global configuration to prop-based configuration, along with the introduction of more granular state management, aligns well with the PR objectives of facilitating plugin loading via URL parameters.

A few general suggestions for further improvement:

  1. Consider adding more comprehensive error handling, especially for cases where plugin loading might fail.
  2. It might be beneficial to add some comments explaining the overall flow of the plugin loading process, as it's quite complex.
  3. Consider implementing a loading state to provide feedback to users while plugins are being loaded.

Great work on this refactoring!

bbb-common-message/src/main/scala/org/bigbluebutton/common2/domain/Meeting2x.scala (1)

90-90: LGTM: Change aligns with PR objectives

The addition of the pluginProp field aligns well with the PR objectives of introducing a new plugin loading mechanism. This flexible Map structure allows for storing various plugin-related data, which can be populated from URL parameters as described in the PR summary.

bigbluebutton-html5/imports/ui/components/app/component.jsx (1)

253-253: LGTM: Addition of pluginConfig prop

The addition of pluginConfig to the destructured props is consistent with the PR objectives for implementing a new plugin loading mechanism.

bbb-common-web/src/main/scala/org/bigbluebutton/api2/BbbWebApiGWApp.scala (1)

21-22: LGTM: New import added for Java util package

The addition of the java.util import is appropriate, given the new plugins parameter in the createMeeting method that uses util.Map.

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

176-176: Ensure plugin persistence is handled correctly

The addition of PluginModel.persistPluginsForClient(liveMeeting.plugins, props.meetingProp.intId) is consistent with the PR objectives of changing the flow of loading a plugin to a parameter of URL pointing to manifest.json. This line persists the plugins for the client after the meeting is inserted into the database.

However, consider the following points:

  1. Ensure that PluginModel.persistPluginsForClient method is properly implemented to handle potential errors or exceptions.
  2. Verify that this addition doesn't introduce any performance issues, especially for meetings with a large number of plugins.
  3. Consider adding appropriate logging for this operation to aid in debugging and monitoring.

To verify the implementation and usage of PluginModel.persistPluginsForClient, run the following script:

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala (7)

6-9: Definition of RateLimiting is clear and correct

The RateLimiting case class correctly defines the rate limiting parameters.


11-15: Definition of EventPersistence is well-structured

The EventPersistence case class accurately encapsulates event persistence settings.


17-21: DataChannel case class is properly defined

The fields in DataChannel are appropriately named and typed.


23-28: RemoteDataSource case class is correctly specified

The RemoteDataSource class effectively represents remote data source configurations.


30-38: PluginManifestContent aggregates plugin properties effectively

The PluginManifestContent case class consolidates all necessary plugin attributes.


40-43: PluginManifest case class is concise and appropriate

The structure of PluginManifest aligns with its intended use.


45-47: Plugin case class is simple and sufficient

The Plugin case class correctly wraps the manifest.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (1)

20-47: Overall, the updated logic enhances code clarity and maintainability.

The refactored code effectively utilizes PluginModel to access plugin data, replacing the previous configuration-based approach. The use of pattern matching improves readability, and the permission-checking logic is well-structured.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (1)

19-42: Permission checking logic is correctly implemented.

The updated code effectively retrieves the plugin and data channel, and it accurately checks user permissions based on the replaceOrDeletePermission setting in the data channel's manifest. The use of pattern matching and Option handling enhances code readability and robustness.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (1)

6-6: Import statements updated appropriately

The added imports for PluginModel, Roles, and Users2x are necessary for the new logic and are appropriately included.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/RunningMeeting.scala (4)

52-52: Update LiveMeeting constructor calls in other parts of the codebase.

The LiveMeeting class constructor now includes an additional plugins parameter. Ensure that all other instantiations of LiveMeeting throughout the codebase are updated to include this new parameter to prevent compilation errors or runtime issues.

Run the following script to find other usages of LiveMeeting construction:

#!/bin/bash
# Description: Find all instantiations of LiveMeeting.

# Test: Search for 'new LiveMeeting' across the codebase. Expect: All instantiations include the 'plugins' parameter.
rg --type scala 'new LiveMeeting\(' -A 2

3-4: Ensure Jackson dependencies are declared and compatible.

The addition of Jackson's ObjectMapper and DefaultScalaModule imports indicates JSON processing capabilities. Verify that the appropriate versions of com.fasterxml.jackson.core:jackson-databind and com.fasterxml.jackson.module:jackson-module-scala are declared in your project's dependencies and are compatible with each other. Incompatible versions might lead to runtime issues.

To confirm the presence and compatibility of Jackson dependencies, run the following script:

#!/bin/bash
# Description: Check for Jackson dependencies in build files.

# Test: Search for dependency declarations in build.sbt or pom.xml files. Expect: Correct versions of jackson-databind and jackson-module-scala are declared.
rg --type "sbt" --type "xml" 'jackson-(databind|module-scala)' -A 2

52-52: Check for potential side effects when adding plugins to LiveMeeting.

Passing plugins to LiveMeeting may introduce side effects if the LiveMeeting class uses plugins in ways that affect existing functionality. Ensure that the addition of plugins does not adversely impact current operations.

Consider reviewing the LiveMeeting class to assess how plugins are utilized.

#!/bin/bash
# Description: Review the usage of 'plugins' within LiveMeeting.

# Test: Retrieve the code for LiveMeeting. Expect: Understand how 'plugins' are used.
rg --type scala 'class LiveMeeting' -A 50

28-28: ⚠️ Potential issue

Verify the correctness of props.pluginProp serialization.

The plugins variable is initialized using PluginModel.createPluginModelFromJson with objectMapper.writeValueAsString(props.pluginProp). This seems like props.pluginProp is already an object, and you're converting it to a JSON string just to deserialize it again. This could be unnecessary serialization and deserialization.

Consider passing props.pluginProp directly if possible, or clarify why this conversion is necessary.

-private val plugins = PluginModel.createPluginModelFromJson(objectMapper.writeValueAsString(props.pluginProp))
+private val plugins = PluginModel.createPluginModelFromJson(props.pluginProp)

To check the type of props.pluginProp and ensure that it's compatible, run:

✅ Verification successful

Serialization Correctness Verified

The serialization of props.pluginProp to a JSON string is necessary because PluginModel.createPluginModelFromJson requires a String parameter. The current implementation correctly serializes the Map before deserialization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the type of props.pluginProp and its usage.

# Test: Search for the definition of pluginProp. Expect: Understand its type and whether it's already in the desired format.
rg --type scala 'def pluginProp' -A 5

Length of output: 2853


Script:

#!/bin/bash
# Description: Locate the definition and type of props.pluginProp.

# Search for pluginProp definitions in Scala files, looking for val, var, or within case classes
rg --type scala '(val|var|case class).*pluginProp' -A 5

Length of output: 875


Script:

#!/bin/bash
# Description: Locate the definition of DefaultProps and the pluginProp member.

# Search for the DefaultProps class definition in Scala files
rg --type scala 'class DefaultProps' -A 10

# Within the DefaultProps class, search for the pluginProp member
rg --type scala 'DefaultProps' -A 50 | rg 'pluginProp'

Length of output: 1747


Script:

#!/bin/bash
# Description: Locate the definition of PluginModel.createPluginModelFromJson to determine its parameter types.

# Search for the createPluginModelFromJson method definition in Scala files
rg --type scala 'def createPluginModelFromJson' -A 5

Length of output: 788

bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (1)

800-800: Verify that listOfPlugins is handled correctly when empty

The method .withPluginManifestUrls(listOfPlugins) is being called with listOfPlugins. Ensure that the Meeting class's withPluginManifestUrls method correctly handles cases where listOfPlugins is empty. This will prevent potential issues if no plugins are specified.

Please confirm that withPluginManifestUrls can handle an empty list without throwing exceptions or causing unintended behavior.

@antobinary

Copy link
Copy Markdown
Member

What kind of documentation do we need for this? Seems to me the create will remain the same, only need to adjust the plugins' docs, right?
image

@gustavotrott

Copy link
Copy Markdown
Contributor

Is it a good idea to use meta_ as a prefix for plugin placeholders? Since this prefix is already used for other settings, it might pose a vulnerability by allowing plugins to access unintended settings—like adding a placeholder to a URL parameter. This could enable a plugin to receive the value of a setting not specifically meant for it.

I believe plugin placeholder parameters should have a dedicated prefix to ensure plugins can't fetch information not explicitly passed to them, avoiding potential vulnerabilities. Maybe even including the plugin's name in the prefix would ensure the plugin only receives parameters intended for it.

In my opinion, the placeholder ${meta_pluginSettingsUserInformation} should become ${lmsUserInformation_allUsersUrl}.
And the URL param should become ?plugindata-lmsUserInformation_allUsersUrl=https://bbb.test

What do you think, @GuiLeme, @TiagoJacobs, @antobinary?

@TiagoJacobs

TiagoJacobs commented Oct 7, 2024 •

Copy link
Copy Markdown
Member

Hello @gustavotrott - as the plugin is enabled on meeting creation (along with the meta parameters), this is not a problem, the same person who sends the meta parameter, is the person who enables the plugin.

Given that the manifest file will be clear about the meta-parameters required by the plugin, it's safe in my opinion.

Also, the idea of using meta parameters is to make it compatible with current moodle plugin (and bbb sub plugins).

@TiagoJacobs

TiagoJacobs commented Oct 7, 2024 •

Copy link
Copy Markdown
Member

BTW, we need to allow the admin to specify a checksum for the manifest (we discussed it in hackweek, but didn't implemented).

This ensures that the manifest file reviewed by the admin is the same that will be provided by the plugin.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (18)
bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (2)

7-10: LGTM! Consider adding JSDoc comments for clarity.

The new PluginConfigFromGraphql interface looks good and aligns with the PR objectives. It correctly represents the configuration received from a GraphQL query for plugins.

Consider adding JSDoc comments to explain the purpose of this interface and its properties, especially javascriptEntrypointUrl. This will improve code documentation and maintainability. For example:

/**
 * Represents the plugin configuration received from a GraphQL query.
 */
export interface PluginConfigFromGraphql {
  /** The URL of the JavaScript entry point for the plugin */
  javascriptEntrypointUrl: string;
  /** The name of the plugin */
  name: string;
}

12-14: LGTM! Consider adding JSDoc comments and using a more specific type.

The new PluginsEngineManagerProps interface looks good and aligns with the PR objectives. It correctly represents the props for a PluginsEngineManager component.

  1. Consider adding JSDoc comments to explain the purpose of this interface and its property.
  2. Instead of using undefined, consider using null or an empty array as the alternative to PluginConfigFromGraphql[]. This can make the usage of the prop more consistent and easier to handle.

Here's an example of how you could improve it:

/**
 * Props for the PluginsEngineManager component.
 */
export interface PluginsEngineManagerProps {
  /** 
   * Configuration for plugins. 
   * An empty array if no plugins are configured.
   */
  pluginConfig: PluginConfigFromGraphql[];
}

This change would require the parent component to always pass an array, even if it's empty, which can lead to more predictable behavior.

bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (2)

1-8: Clarify the nature of v_plugin and consider adding comments for future customization.

The v_ prefix in the table name suggests this might be a view rather than a table. Please clarify whether v_plugin is indeed a view or a table.

Additionally, consider adding comments to explain the purpose of this entity and any plans for future customization of the empty configurations (column_config, custom_column_names, custom_root_fields).


9-19: Add a descriptive comment for the bbb_client role.

The bbb_client role's permissions are well-defined, but the purpose of this role is not explicitly stated. Consider adding a comment to explain the role's intended use and any specific scenarios where it applies. This will improve maintainability and help other developers understand the role's purpose.

Example:

comment: "Allows BigBlueButton clients to access essential plugin information for their specific meeting."
bbb-common-web/src/main/java/org/bigbluebutton/api/domain/PluginsManifest.java (2)

1-5: Remove unused import

The java.util.Vector import is not used in this class. It's good practice to remove unused imports to keep the code clean and prevent potential confusion.

Apply this diff to remove the unused import:

 package org.bigbluebutton.api.domain;
 
-import java.util.Vector;
 
 public class PluginsManifest {

20-34: LGTM: Well-implemented getter and setter methods

The getter and setter methods for url and checksum are correctly implemented, providing proper encapsulation for the private fields. The method names follow Java conventions for getters and setters.

Consider using Lombok to reduce boilerplate code. Lombok can automatically generate getters, setters, and constructors, making the code more concise and easier to maintain. If Lombok is already used in the project, you could refactor the class as follows:

import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class PluginsManifest {
    private String url = "";
    private String checksum = "";

    public PluginsManifest(String url) {
        this.url = url;
    }
}

This refactoring would eliminate the need for explicit getter and setter methods, making the code more concise while maintaining the same functionality.

bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (1)

Line range hint 1-51: Consider adding a comment explaining the Subresource Integrity (SRI) check

The changes in this file are well-implemented and improve the overall quality of the code. To further enhance maintainability, consider adding a brief comment above the integrity attribute setting to explain the purpose of the SRI check. This would be helpful for future maintainers who might not be familiar with this security feature.

Example:

// Set the integrity attribute for Subresource Integrity (SRI) check
// This allows the browser to verify the integrity of the loaded script
if (plugin.pluginJavascriptChecksum) {
  script.setAttribute('integrity', plugin.pluginJavascriptChecksum);
}
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (1)

20-22: LGTM: Improved plugin retrieval logic.

The change to use PluginModel.getPluginByName is a good improvement. It provides a more direct and type-safe way to retrieve plugins.

Consider adding more context to the error message in the None case:

-case None => println(s"Plugin '${msg.body.pluginName}' not found.")
+case None => println(s"Plugin '${msg.body.pluginName}' not found for meeting '${meetingId}'.")

This will make debugging easier by providing the meeting context.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (2)

19-22: LGTM: Improved plugin retrieval logic

The new implementation using PluginModel.getPluginByName and pattern matching is a clear improvement. It aligns with the PR objectives and provides better error handling.

Consider using a logging framework instead of println for error messages. This would allow for better log management and consistency across the application. For example:

case None => logger.warn(s"Plugin '${msg.body.pluginName}' not found.")

48-48: Suggestion: Use proper logging framework

Replace println with a proper logging framework for consistency and better log management. For example:

case None => logger.warn(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")

This change will ensure that error messages are properly captured and can be managed more effectively in a production environment.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (2)

21-42: LGTM with a minor suggestion: Improved data channel retrieval and permission checking.

The new implementation provides a more structured and flexible approach to permission checking. The use of pattern matching improves readability and maintainability.

Consider adding an explicit error case for when replaceOrDeletePermission is not defined in the data channel. This would improve error handling and make the code more robust:

val hasPermission = dc.replaceOrDeletePermission match {
  case Some(permission) => permission.toLowerCase match {
    // ... (existing cases)
  }
  case None => 
    println(s"Replace or delete permission not defined for data channel '${msg.body.channelName}' in plugin '${msg.body.pluginName}'.")
    false
}

Line range hint 1-60: Overall, good improvements with one main point to address.

The changes in this file significantly improve the structure and flexibility of plugin and data channel handling. The new implementation provides better organization, more direct plugin retrieval, and more flexible permission checking.

The main point to address is:

  1. Replace println statements with proper logging using a logging framework.

Additionally, consider the minor suggestion for improving error handling in the permission checking logic.

These changes will enhance the robustness and maintainability of the code.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/MeetingDAO.scala (1)

89-89: LGTM: Updated insert method to include plugin functionality

The changes to the insert method align with the PR objectives:

  1. The new pluginProps parameter allows passing plugin properties during meeting insertion.
  2. The added line PluginModel.persistPluginsForClient(pluginProps, meetingProps.meetingProp.intId) persists the plugin data for the meeting.

These modifications successfully implement the new plugin loading mechanism as described in the PR objectives.

Consider refactoring the insert method for improved readability and maintainability:

  1. Extract the creation of MeetingDbModel into a separate method.
  2. Group related insert operations (e.g., chat, user policies, lock settings) into logical methods.

This refactoring would make the code more modular and easier to maintain in the future.

Also applies to: 152-152

bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (2)

350-380: Well-implemented placeholder replacement method

The replaceMetaParametersIntoManifestTemplate method effectively replaces placeholders in the manifest template with corresponding metadata values. It correctly handles variable validation and uses Matcher.quoteReplacement to prevent regex interpretation of replacement strings.

Consider adding a check for null or empty manifestContent at the beginning of the method to improve robustness.

 public String replaceMetaParametersIntoManifestTemplate(String manifestContent, Map<String, String> metadata)
         throws NoSuchFieldException {
+    if (manifestContent == null || manifestContent.isEmpty()) {
+        throw new IllegalArgumentException("manifestContent cannot be null or empty");
+    }
     // Rest of the method implementation...
 }

381-447: Comprehensive plugin manifest processing method

The requestPluginManifests method effectively fetches and processes plugin manifests. It handles exceptions for each plugin separately, implements checksum validation, and uses the replaceMetaParametersIntoManifestTemplate method appropriately.

Suggestions for improvement:

  1. Use a parameterized type for the return Map to improve type safety.
  2. Consider using try-with-resources for the BufferedReader to ensure proper resource management.
  3. The checksum comparison could be made case-insensitive to avoid potential issues.

Here's a refactored version addressing these points:

- public Map<String, Object> requestPluginManifests(Meeting m) {
+ public Map<String, Map<String, Object>> requestPluginManifests(Meeting m) {
-   Map<String, Object> urlContents = new HashMap<>();
+   Map<String, Map<String, Object>> urlContents = new HashMap<>();
    Map<String, String> metadata = m.getMetadata();

    for (PluginsManifest pluginsManifest : m.getPluginsManifests()) {
      try {
        String urlString = pluginsManifest.getUrl();
        URL url = new URL(urlString);
-       BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
-       StringBuilder content = new StringBuilder();
-       String inputLine;
-       while ((inputLine = in.readLine()) != null) {
-         content.append(inputLine).append("\n");
-       }
-       in.close();
+       StringBuilder content = new StringBuilder();
+       try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
+         String inputLine;
+         while ((inputLine = in.readLine()) != null) {
+           content.append(inputLine).append("\n");
+         }
+       }

        // Parse the JSON content
        JsonNode jsonNode = objectMapper.readTree(content.toString());

        // Validate checksum if any:
        String checksum = pluginsManifest.getChecksum();
        if (jsonNode.has("checksum") || !StringUtils.isEmpty(checksum)) {
-         if (!checksum.equals(jsonNode.get("checksum").asText())) {
+         if (!checksum.equalsIgnoreCase(jsonNode.get("checksum").asText())) {
            log.info("Plugin checksum mismatch for {}. Manifest.json returned {} and URL parameter input was {}",
              pluginsManifest.getUrl(),
              jsonNode.get("checksum").asText(),
              checksum
            );
            log.info("Plugin {} is not going to be loaded",
              pluginsManifest.getUrl()
            );
            continue;
          }
        }

        // Rest of the method implementation...
      } catch(Exception e) {
        log.error("Failed with the following plugin manifest URL: {}. Error: {} therefore this plugin will not load",
                pluginsManifest.getUrl(), e);
      }
    }
    return urlContents;
  }
bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (2)

433-458: Overall implementation looks good, but consider adding URL validation

The new processPluginsManifestsParams method is well-structured and handles JSON parsing errors appropriately. However, consider adding URL validation to ensure the provided URLs are well-formed.

Consider adding URL validation:

 String url = pluginsManifestJsonObj.get("url").getAsString();
+if (!isValidUrl(url)) {
+    log.warn("Invalid URL provided for plugin manifest: {}", url);
+    continue;
+}
 PluginsManifest newPlugin = new PluginsManifest(url);

You'll need to implement the isValidUrl method or use a library like Apache Commons Validator.

Add a comment explaining the purpose of this method at the beginning:

/**
 * Processes the plugins manifests from the meeting parameters.
 * Each manifest should contain a URL pointing to the manifest file and an optional checksum.
 *
 * @param params The meeting parameters
 * @return A list of PluginsManifest objects
 */
private ArrayList<PluginsManifest> processPluginsManifestsParams(Map<String, String> params) {
    // ... existing code ...
}

568-570: Integration of plugin manifests processing looks good

The addition of plugin manifests processing is well-integrated into the existing processCreateParams method. It's a minimal and focused change that enhances the functionality without disrupting the existing logic.

Consider adding a brief comment to explain the purpose of this new line:

+ // Process and retrieve plugin manifests from the meeting parameters
 ArrayList<PluginsManifest> listOfPluginsManifests = processPluginsManifestsParams(params);
bbb-graphql-server/bbb_schema.sql (1)

1976-1976: View v_plugin created

A simple view v_plugin is created, selecting all columns from the plugin table. This is a straightforward way to expose the plugin data.

Consider:

  1. If you don't need all columns in the view, it's generally better to explicitly list the needed columns for better performance and maintainability.
  2. If this view is intended for read-only purposes, you might want to add WITH (security_barrier) for additional security.

Consider modifying the view creation to explicitly list columns and add a security barrier:

CREATE VIEW "v_plugin" WITH (security_barrier) AS 
SELECT "meetingId", "name", "javascriptEntrypointUrl", "pluginJavascriptChecksum"
FROM "plugin";
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1ea9642 and 04a5a9d.

📒 Files selected for processing (19)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/MeetingDAO.scala (3 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PluginDAO.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.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/core/running/RunningMeeting.scala (2 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ApiParams.java (1 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (6 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (4 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/domain/Meeting.java (5 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/domain/PluginsManifest.java (1 hunks)
  • bbb-graphql-server/bbb_schema.sql (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (3 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/MeetingActor.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/running/RunningMeeting.scala
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ApiParams.java
  • bbb-common-web/src/main/java/org/bigbluebutton/api/domain/Meeting.java
  • bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts
🧰 Additional context used
🔇 Additional comments (31)
bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (1)

Line range hint 1-24: Overall, the changes look good and align with the PR objectives.

The new interfaces and updated property in this file support the new plugin loading mechanism described in the PR summary. They provide better type safety and more descriptive naming for plugin-related configurations.

To further improve the code:

  1. Consider adding JSDoc comments to all interfaces and properties for better documentation.
  2. Ensure that these changes are consistently applied across the codebase, updating any related code or documentation as necessary.
  3. If not already done, consider adding unit tests to verify the correct usage of these interfaces in the application.
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (1)

20-29: ⚠️ Potential issue

Consider consolidating duplicate roles or clarify their distinct purposes.

The bbb_client_not_in_meeting role has identical permissions to the bbb_client role. This duplication was previously flagged in a past review and remains an issue.

To address this:

  1. If these roles serve different purposes, add comments to explain their distinct use cases.
  2. If the roles are truly identical, consider consolidating them into a single role to simplify permission management.

Example of adding clarifying comments:

- role: bbb_client
  comment: "For clients currently in a meeting"
- role: bbb_client_not_in_meeting
  comment: "For clients authenticating but not yet in a meeting"

If consolidation is appropriate, remove one of the role entries and update references throughout the codebase.

bbb-common-web/src/main/java/org/bigbluebutton/api/domain/PluginsManifest.java (3)

7-8: LGTM: Well-defined class fields

The private fields url and checksum are well-defined and initialized to empty strings, which is a good practice to prevent null pointer exceptions.


9-18: LGTM: Well-implemented constructors

The two constructors provide flexibility in object creation:

  1. PluginsManifest(String url, String checksum): Allows setting both url and checksum.
  2. PluginsManifest(String url): Allows setting only url, leaving checksum as an empty string.

Both constructors correctly initialize the fields, maintaining consistency with the field declarations.


1-35: Overall assessment: Well-structured class with room for minor improvements

The PluginsManifest class is well-designed and implements the basic functionality required for managing plugin manifests. It provides proper encapsulation of the url and checksum fields, along with flexible constructors for object creation.

Key points:

  1. The class structure is clear and follows Java conventions.
  2. Field initialization prevents null pointer exceptions.
  3. Getter and setter methods provide proper encapsulation.

Suggestions for improvement:

  1. Remove the unused java.util.Vector import.
  2. Consider using Lombok to reduce boilerplate code if it's already part of the project.

These minor improvements would enhance code cleanliness and maintainability without affecting the core functionality of the class.

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

5-10: LGTM: Case class structure is appropriate

The PluginDbModel case class is well-defined with all necessary fields. The addition of pluginJavascriptChecksum is a good security measure to ensure the integrity of the plugin's JavaScript.


21-32: Add explicit return type to the insert method

For better code clarity and maintainability, it's recommended to specify the return type of public methods in Scala.

Please add an explicit return type to the insert method. For example, if DatabaseConnection.enqueue returns a Future[Int], update the method signature as follows:

def insert(meetingId: String, name: String, javascriptEntrypointUrl: String, pluginJavascriptChecksum: String): Future[Int] = {
  // ... existing implementation ...
}

Ensure that the return type matches the actual type returned by DatabaseConnection.enqueue.


1-33: Overall assessment: Good changes with minor improvements needed

The addition of the pluginJavascriptChecksum field enhances the security of the plugin system. The changes are generally well-implemented, but there are two minor issues to address:

  1. The composite primary key definition needs to be corrected.
  2. The insert method should have an explicit return type.

Once these issues are resolved, the code will be more robust and maintainable.


12-18: ⚠️ Potential issue

Fix the composite primary key definition

The current primary key definition is incorrect. Marking multiple columns with O.PrimaryKey does not create a composite primary key in Slick. Only the last O.PrimaryKey annotation takes effect.

To correctly define a composite primary key on both meetingId and name, apply this diff:

 class PluginDbTableDef(tag: Tag) extends Table[PluginDbModel](tag, None, "plugin") {
-  val meetingId = column[String]("meetingId", O.PrimaryKey)
-  val name = column[String]("name", O.PrimaryKey)
+  val meetingId = column[String]("meetingId")
+  val name = column[String]("name")
   val javascriptEntrypointUrl = column[String]("javascriptEntrypointUrl")
   val pluginJavascriptChecksum = column[String]("pluginJavascriptChecksum")
+  def pk = primaryKey("plugin_pk", (meetingId, name))
   override def * = (meetingId, name, javascriptEntrypointUrl, pluginJavascriptChecksum) <> (PluginDbModel.tupled, PluginDbModel.unapply)
 }
bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (3)

9-9: Approved: Improved state management for loaded plugins count

The change from loadedPlugins to setNumberOfLoadedPlugins indicates a shift from a ref-based approach to a state updater function. This is a good practice as it ensures better reactivity and consistency in managing the count of loaded plugins.


25-25: Approved: Reliable plugin count update using functional state update

The change to use setNumberOfLoadedPlugins((current) => current + 1) is a significant improvement. By using a functional update, we ensure that the increment is always based on the latest state, avoiding potential race conditions in concurrent updates. This change enhances the reliability of the plugin loading count.


43-44: Approved: Enhanced security with Subresource Integrity (SRI) check

The change from plugin.checksum to plugin.pluginJavascriptChecksum and setting it as the 'integrity' attribute is a significant security improvement. This enables Subresource Integrity (SRI) checks, allowing the browser to verify that the file fetched matches the expected hash. This protects against CDN compromises or other scenarios where the plugin script might be tampered with.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (4)

7-7: LGTM: Import change is appropriate.

The addition of PluginModel to the import statement is consistent with its usage in the updated code.


22-23: LGTM: Improved data channel retrieval.

The new pattern matching for finding the data channel within the plugin enhances type safety and error handling. The use of getOrElse(List()) is a good defensive programming practice.


38-43: LGTM: Data channel reset logic is correct.

The call to PluginDataChannelEntryDAO.reset is implemented correctly, with all necessary parameters being passed.


24-33: ⚠️ Potential issue

Handle the case when replaceOrDeletePermission is None.

This issue was identified in a previous review and remains unaddressed. Currently, if dc.replaceOrDeletePermission is None, the hasPermission variable will also be None, and the permission check hasPermission.contains(true) will fail, denying access.

Consider handling the None case explicitly to reflect the intended behavior. Here's a suggested improvement:

 val hasPermission = for {
   replaceOrDeletePermission <- dc.replaceOrDeletePermission
 } yield {
   replaceOrDeletePermission.toLowerCase match {
     case "all"       => true
     case "moderator" => user.role == Roles.MODERATOR_ROLE
     case "presenter" => user.presenter
     case _           => false
   }
 }

+val permissionGranted = hasPermission.getOrElse(false) // Default to false if not specified
+
-if (!hasPermission.contains(true)) {
+if (!permissionGranted) {
   println(s"No permission to delete (reset) in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
 } else {
   // Proceed with reset
 }

This change provides a default permission when replaceOrDeletePermission is not specified, improving the robustness of the permission checking logic.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (2)

6-6: LGTM: Import addition is appropriate

The addition of PluginModel to the imports is consistent with its usage in the updated implementation. This change supports the transition from using ClientSettings to PluginModel for plugin management.


Line range hint 1-54: Overall assessment: Improved plugin handling with room for refinement

The changes to PluginDataChannelPushEntryMsgHdlr successfully implement the new plugin loading mechanism as described in the PR objectives. The code structure has been improved, and the logic for handling plugins and data channels is more direct and clear.

Key improvements:

  1. Direct use of PluginModel for plugin retrieval.
  2. Clearer error handling for missing plugins and data channels.
  3. More structured approach to permission checking.

Suggestions for further improvement:

  1. Implement a proper logging framework throughout the file.
  2. Refactor the permission checking logic for better type safety and clarity.
  3. Consider adding more comprehensive error handling and user feedback mechanisms.

These changes represent a significant step forward in the plugin management system, aligning well with the goals of the pull request.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (4)

6-6: LGTM: Import statement added correctly.

The addition of PluginModel to the import statement is consistent with its usage in the updated code.


19-20: LGTM: Improved plugin retrieval logic.

The use of PluginModel.getPluginByName simplifies the plugin retrieval process, making it more direct and maintainable.


44-44: Replace println statements with proper logging.

As mentioned in a previous review, using println for logging is not suitable for production environments. It doesn't provide log level control and can lead to inconsistent logging practices.

Please refer to the previous review comment for detailed instructions on how to replace these println statements with proper logging using a logging framework.

Also applies to: 54-54, 56-56


46-52: LGTM: Correct implementation of database delete operation.

The use of PluginDataChannelEntryDAO.delete for performing the database delete operation is correct and consistent with the overall changes in the file.

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

6-6: LGTM: New import for PluginModel

The addition of the PluginModel import aligns with the PR objectives of integrating plugin functionality into the meeting creation process.


Line range hint 1-232: Summary: Successfully implemented plugin integration in MeetingDAO

The changes in this file effectively implement the new plugin loading mechanism as described in the PR objectives. The modifications are minimal and focused, integrating plugin functionality into the meeting creation process without disrupting the existing code structure.

Key points:

  1. The new import and parameter addition allow for passing plugin properties during meeting insertion.
  2. The persistence of plugin data is handled at the end of the insert method, ensuring that plugin information is stored alongside other meeting data.

These changes support the development of a server-side component for plugins, as mentioned in the PR objectives. The implementation appears to be correct, secure, and consistent with the existing codebase.

To ensure the changes are working as expected, please verify the following:

  1. The PluginModel.persistPluginsForClient method is implemented correctly and handles the persistence of plugin data.
  2. The pluginProps parameter is properly populated when calling the insert method from other parts of the application.
bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (3)

Line range hint 23-35: New imports added for enhanced functionality

The new imports (URL, JsonNode, ObjectMapper, Matcher, and Pattern) are appropriate for the added JSON processing and URL handling capabilities. These additions support the new plugin management features.


448-459: Appropriate integration of plugin manifest processing

The modification to the createMeeting method correctly integrates the new plugin manifest functionality. The addition of requestPluginManifests(m) and setting the plugins for the meeting object is done in a non-disruptive manner, maintaining the existing flow of the method.


Line range hint 1-1176: Summary of changes: Enhanced plugin management functionality

The modifications to MeetingService.java significantly improve the plugin management capabilities of the system. Key changes include:

  1. Addition of new methods replaceMetaParametersIntoManifestTemplate and requestPluginManifests for handling plugin manifests.
  2. Integration of plugin manifest processing into the createMeeting method.
  3. New imports to support JSON processing and URL handling.

These changes enhance the flexibility and extensibility of the meeting service by allowing dynamic loading and processing of plugin manifests. The implementation is generally well-done, with only minor suggestions for improvement in error handling and type safety.

Overall, these changes represent a positive evolution of the codebase, improving its ability to manage plugins in a more dynamic and configurable manner.

bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (1)

821-821: Plugin manifests successfully integrated into Meeting object

The addition of .withPluginManifests(listOfPluginsManifests) to the Meeting builder call successfully completes the integration of plugin manifests into the Meeting object. This change is consistent with the existing builder pattern and enhances the Meeting object with the new plugin manifest information.

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

1965-1966: New section for plugin tables added

This comment indicates the start of a new section for plugin-related tables. It's a good practice to organize the schema with clear sections.


1967-1974: New plugin table created

The plugin table is being created with the following structure:

  • meetingId: varchar(100)
  • name: varchar(100)
  • javascriptEntrypointUrl: varchar(500)
  • pluginJavascriptChecksum: varchar(500)

The table has a composite primary key (meetingId, name) and a foreign key constraint on meetingId referencing the meeting table.

Considerations:

  1. The javascriptEntrypointUrl and pluginJavascriptChecksum fields are quite large (500 characters). Ensure this is necessary for your use case.
  2. Consider adding an index on the name column if you expect to query plugins by name frequently.

1965-1976: Summary of plugin-related changes

The additions to the schema introduce a new plugin table and a corresponding view v_plugin. These changes appear to be part of a larger feature for plugin management in the BigBlueButton system. The structure is consistent with the existing schema design and provides the necessary components for managing plugins.

Key points:

  1. The plugin table has a composite primary key and a foreign key relationship with the meeting table.
  2. The javascriptEntrypointUrl and pluginJavascriptChecksum fields are quite large (500 characters), which should be reviewed to ensure this size is necessary.
  3. Consider adding an index on the name column of the plugin table if frequent queries by plugin name are expected.
  4. The v_plugin view could be optimized by explicitly listing needed columns and adding a security barrier.

Overall, these changes provide a solid foundation for plugin management within the system.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (13)
bbb-graphql-server/bbb_schema.sql (13)

Line range hint 1-22: LGTM! Consider optimizing the remove_emojis function.

The initial extensions and functions look good. The immutable_lower_unaccent function is well-designed for consistent text comparisons. For the remove_emojis function, consider using a more comprehensive regex pattern to cover a wider range of emoji Unicode blocks for better accuracy.

You could update the remove_emojis function with a more comprehensive regex:

CREATE OR REPLACE FUNCTION remove_emojis(text) RETURNS text AS $$
DECLARE
    input_string ALIAS FOR $1;
    output_string text;
BEGIN
    output_string := regexp_replace(input_string, '[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F1E0}-\u{1F1FF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]', '', 'g');
    RETURN output_string;
END;
$$ LANGUAGE plpgsql IMMUTABLE;

This pattern covers most emoji Unicode blocks, providing more thorough emoji removal.


Line range hint 24-226: LGTM! Consider standardizing timestamp column names.

The meeting tables structure is well-designed with appropriate relationships, indexes, and use of generated columns. The trigger for automatically calculating recordedTimeInSeconds is a good practice.

For consistency, consider standardizing the naming convention for timestamp columns. For example:

  • In the meeting table, you have createdTime (bigint) and createdAt (timestamp).
  • In other tables, you use startedAt, stoppedAt, etc.

Standardizing these could improve readability and maintainability. For example:

ALTER TABLE "meeting" RENAME COLUMN "createdTime" TO "createdAtMillis";
ALTER TABLE "meeting" RENAME COLUMN "endedAt" TO "endedAtTimestamp";
-- Apply similar changes to other timestamp columns for consistency

This change would make it clear which columns are storing milliseconds and which are storing timestamps.


Line range hint 228-735: LGTM! Consider optimizing indexes and partitioning for large-scale deployments.

The user tables structure is comprehensive and well-designed. The use of generated columns, appropriate indexes, and triggers for complex logic is commendable.

For potential improvements in performance and maintainability, consider:

  1. Partitioning: For large-scale deployments, consider partitioning the user table by meetingId. This can significantly improve query performance and manageability.
CREATE TABLE "user" (
    -- existing columns
) PARTITION BY LIST ("meetingId");
  1. Index optimization: Analyze query patterns and consider creating composite indexes for frequently used combinations. For example:
CREATE INDEX "idx_user_meeting_role_current" ON "user" ("meetingId", "role") WHERE "currentlyInMeeting" IS TRUE;
  1. Archiving strategy: Implement an archiving strategy for historical data to keep the active tables lean. This could involve moving data to separate archive tables after a certain period.

  2. Consider using BRIN indexes for timestamp columns in large tables, which can be more efficient for time-series data:

CREATE INDEX "idx_user_registeredAt_brin" ON "user" USING BRIN ("registeredAt");

These suggestions aim to enhance performance and maintainability as the system scales.


Line range hint 737-889: LGTM! Consider adding a constraint for chat message ordering.

The chat tables structure is well-designed with appropriate relationships, indexes, and triggers. The use of views for different chat scenarios (public, private) is a good practice for query simplification.

To enhance data integrity, consider adding a constraint to ensure proper ordering of chat messages. You could add a sequence number column to the chat_message table:

ALTER TABLE "chat_message" ADD COLUMN "sequenceNumber" BIGINT;

CREATE SEQUENCE "chat_message_seq";

ALTER TABLE "chat_message" ALTER COLUMN "sequenceNumber" SET DEFAULT nextval('chat_message_seq');

ALTER TABLE "chat_message" ADD CONSTRAINT "chat_message_sequence_check" 
    CHECK ("sequenceNumber" > (
        SELECT COALESCE(MAX("sequenceNumber"), 0) 
        FROM "chat_message" cm2 
        WHERE cm2."chatId" = "chat_message"."chatId" 
        AND cm2."meetingId" = "chat_message"."meetingId" 
        AND cm2."createdAt" <= "chat_message"."createdAt"
    ));

This ensures that messages within a chat are always in the correct order, even if there are slight discrepancies in the createdAt timestamps.


Line range hint 891-1196: LGTM! Consider adding a materialized view for current presentation state.

The presentation and annotation tables structure is well-designed with appropriate relationships, indexes, and triggers. The use of triggers to update user permissions is a good practice for maintaining data consistency.

To potentially improve query performance, especially for frequently accessed current presentation state, consider creating a materialized view:

CREATE MATERIALIZED VIEW "mv_current_presentation_state" AS
SELECT 
    p."meetingId",
    p."presentationId",
    p."name" AS "presentationName",
    pg."pageId",
    pg."num" AS "pageNumber",
    pg."current" AS "isCurrentPage",
    pg."xOffset",
    pg."yOffset",
    pg."widthRatio",
    pg."heightRatio"
FROM "pres_presentation" p
JOIN "pres_page" pg ON p."presentationId" = pg."presentationId"
WHERE p."current" = true;

CREATE UNIQUE INDEX ON "mv_current_presentation_state" ("meetingId");

-- Create a function to refresh the materialized view
CREATE OR REPLACE FUNCTION refresh_current_presentation_state()
RETURNS TRIGGER AS $$
BEGIN
    REFRESH MATERIALIZED VIEW CONCURRENTLY "mv_current_presentation_state";
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Create triggers to refresh the materialized view
CREATE TRIGGER refresh_current_presentation_state_trigger
AFTER INSERT OR UPDATE OR DELETE ON "pres_presentation"
FOR EACH STATEMENT EXECUTE FUNCTION refresh_current_presentation_state();

CREATE TRIGGER refresh_current_presentation_state_page_trigger
AFTER INSERT OR UPDATE OR DELETE ON "pres_page"
FOR EACH STATEMENT EXECUTE FUNCTION refresh_current_presentation_state();

This materialized view can significantly improve query performance for clients frequently requesting the current presentation state, as it pre-computes the join between pres_presentation and pres_page.


Line range hint 1198-1284: LGTM! Consider adding a constraint for poll option uniqueness.

The poll tables structure is well-designed with appropriate relationships and indexes. The views for poll responses and user participation provide useful aggregations for easy querying of poll results.

To enhance data integrity, consider adding a constraint to ensure that poll options are unique within a poll:

ALTER TABLE "poll_option" 
ADD CONSTRAINT "unique_poll_option" UNIQUE ("pollId", "optionDesc");

This constraint prevents duplicate options within the same poll, which could lead to confusion in results.

Additionally, you might want to add a check constraint to ensure that the optionId starts from a specific number (e.g., 1) and is consecutive within each poll:

ALTER TABLE "poll_option"
ADD CONSTRAINT "check_option_id_range" 
CHECK ("optionId" > 0 AND "optionId" <= (
    SELECT COUNT(*) 
    FROM "poll_option" po2 
    WHERE po2."pollId" = "poll_option"."pollId"
));

This ensures that option IDs are always valid and consecutive within each poll.


Line range hint 1286-1330: LGTM! Consider adding a history table for external videos and screenshares.

The external video and screenshare tables are well-structured with appropriate indexes, including partial indexes for current items. The views for current external videos and screenshares simplify querying for active items.

To improve data management and enable historical analysis, consider adding history tables for both external videos and screenshares:

CREATE TABLE "externalVideo_history" (
    "historyId" SERIAL PRIMARY KEY,
    "externalVideoId" varchar(100),
    "meetingId" varchar(100),
    "externalVideoUrl" varchar(500),
    "startedSharingAt" timestamp with time zone,
    "stoppedSharingAt" timestamp with time zone,
    "playerPlaybackRate" numeric,
    "playerCurrentTime" numeric,
    "playerPlaying" boolean,
    "changedAt" timestamp with time zone DEFAULT current_timestamp,
    FOREIGN KEY ("meetingId") REFERENCES "meeting"("meetingId") ON DELETE CASCADE
);

CREATE TABLE "screenshare_history" (
    "historyId" SERIAL PRIMARY KEY,
    "screenshareId" varchar(50),
    "meetingId" varchar(100),
    "voiceConf" varchar(50),
    "screenshareConf" varchar(50),
    "contentType" varchar(50),
    "stream" varchar(100),
    "vidWidth" integer,
    "vidHeight" integer,
    "hasAudio" boolean,
    "startedAt" timestamp with time zone,
    "stoppedAt" timestamp with time zone,
    "changedAt" timestamp with time zone DEFAULT current_timestamp,
    FOREIGN KEY ("meetingId") REFERENCES "meeting"("meetingId") ON DELETE CASCADE
);

Then, create triggers to populate these history tables whenever the main tables are updated:

CREATE OR REPLACE FUNCTION log_externalVideo_changes()
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO "externalVideo_history" 
    SELECT nextval('externalVideo_history_historyId_seq'), OLD.*;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER externalVideo_history_trigger
AFTER UPDATE ON "externalVideo"
FOR EACH ROW EXECUTE FUNCTION log_externalVideo_changes();

-- Create a similar trigger for the screenshare table

This approach allows you to maintain a full history of changes to external videos and screenshares, which can be useful for auditing and analysis purposes.


Line range hint 1332-1364: LGTM! Consider adding constraints for data consistency.

The timer table structure is well-designed with a generated column for timestamp conversion. The view provides useful logic for determining if the timer is running.

To enhance data consistency, consider adding the following constraints:

  1. Ensure that time and accumulated are non-negative:
ALTER TABLE "timer"
ADD CONSTRAINT "check_time_non_negative" CHECK ("time" >= 0),
ADD CONSTRAINT "check_accumulated_non_negative" CHECK ("accumulated" >= 0);
  1. Ensure that startedOn is 0 when the timer is not running:
ALTER TABLE "timer"
ADD CONSTRAINT "check_startedOn_consistency" 
CHECK (("running" = false AND "startedOn" = 0) OR ("running" = true AND "startedOn" > 0));
  1. Add a trigger to ensure that accumulated is updated when the timer is stopped:
CREATE OR REPLACE FUNCTION update_timer_accumulated()
RETURNS TRIGGER AS $$
BEGIN
    IF OLD.running = true AND NEW.running = false THEN
        NEW.accumulated := NEW.accumulated + (EXTRACT(EPOCH FROM NOW()) * 1000 - OLD.startedOn);
        NEW.startedOn := 0;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER timer_stop_trigger
BEFORE UPDATE ON "timer"
FOR EACH ROW
WHEN (OLD.running = true AND NEW.running = false)
EXECUTE FUNCTION update_timer_accumulated();

These additions will help maintain data consistency and prevent invalid states in the timer table.


Line range hint 1366-1533: LGTM! Consider adding a materialized view for active breakout rooms.

The breakout room tables structure is well-designed with appropriate relationships, generated columns, and triggers for maintaining data consistency. The views provide useful aggregations of breakout room data.

To potentially improve query performance for frequently accessed active breakout room data, consider creating a materialized view:

CREATE MATERIALIZED VIEW "mv_active_breakout_rooms" AS
SELECT 
    br."parentMeetingId",
    br."breakoutRoomId",
    br."externalId",
    br."sequence",
    br."name",
    br."shortName",
    br."freeJoin",
    br."startedAt",
    br."durationInSeconds",
    COUNT(bru."userId") AS "assignedUsersCount",
    SUM(CASE WHEN bru."joinedAt" IS NOT NULL THEN 1 ELSE 0 END) AS "joinedUsersCount"
FROM "breakoutRoom" br
LEFT JOIN "breakoutRoom_user" bru ON br."breakoutRoomId" = bru."breakoutRoomId"
WHERE br."endedAt" IS NULL
GROUP BY br."parentMeetingId", br."breakoutRoomId", br."externalId", br."sequence", br."name", br."shortName", br."freeJoin", br."startedAt", br."durationInSeconds";

CREATE UNIQUE INDEX ON "mv_active_breakout_rooms" ("parentMeetingId", "breakoutRoomId");

-- Create a function to refresh the materialized view
CREATE OR REPLACE FUNCTION refresh_active_breakout_rooms()
RETURNS TRIGGER AS $$
BEGIN
    REFRESH MATERIALIZED VIEW CONCURRENTLY "mv_active_breakout_rooms";
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

-- Create triggers to refresh the materialized view
CREATE TRIGGER refresh_active_breakout_rooms_trigger
AFTER INSERT OR UPDATE OR DELETE ON "breakoutRoom"
FOR EACH STATEMENT EXECUTE FUNCTION refresh_active_breakout_rooms();

CREATE TRIGGER refresh_active_breakout_rooms_user_trigger
AFTER INSERT OR UPDATE OR DELETE ON "breakoutRoom_user"
FOR EACH STATEMENT EXECUTE FUNCTION refresh_active_breakout_rooms();

This materialized view can significantly improve query performance for clients frequently requesting active breakout room information, as it pre-computes the join between breakoutRoom and breakoutRoom_user and provides aggregated user counts.


Line range hint 1535-1584: LGTM! Consider adding version control for shared notes content.

The shared notes tables structure is well-designed with appropriate relationships and indexes. The views provide useful aggregations of shared notes data.

To enhance data integrity and enable better version control of shared notes, consider implementing a more robust revision system:

  1. Add a content column to the sharedNotes table to store the current content:
ALTER TABLE "sharedNotes"
ADD COLUMN "content" TEXT;
  1. Modify the sharedNotes_rev table to store full content snapshots instead of just changesets:
ALTER TABLE "sharedNotes_rev"
ADD COLUMN "content" TEXT,
ALTER COLUMN "changeset" DROP NOT NULL;
  1. Create a trigger to update the sharedNotes content when a new revision is added:
CREATE OR REPLACE FUNCTION update_shared_notes_content()
RETURNS TRIGGER AS $$
BEGIN
    UPDATE "sharedNotes"
    SET "content" = NEW."content"
    WHERE "meetingId" = NEW."meetingId" AND "sharedNotesExtId" = NEW."sharedNotesExtId";
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_shared_notes_content_trigger
AFTER INSERT ON "sharedNotes_rev"
FOR EACH ROW
EXECUTE FUNCTION update_shared_notes_content();
  1. Add a function to retrieve the content at a specific revision:
CREATE OR REPLACE FUNCTION get_shared_notes_content_at_revision(
    p_meetingId VARCHAR(100),
    p_sharedNotesExtId VARCHAR(25),
    p_rev INTEGER
)
RETURNS TEXT AS $$
DECLARE
    v_content TEXT;
BEGIN
    SELECT "content" INTO v_content
    FROM "sharedNotes_rev"
    WHERE "meetingId" = p_meetingId
    AND "sharedNotesExtId" = p_sharedNotesExtId
    AND "rev" <= p_rev
    ORDER BY "rev" DESC
    LIMIT 1;

    RETURN v_content;
END;
$$ LANGUAGE plpgsql;

These changes will provide a more robust version control system for shared notes, allowing easy access to the current content and historical versions.


Line range hint 1586-1659: LGTM! Consider implementing caption text compression for large datasets.

The caption tables structure is well-designed with appropriate relationships, indexes, and triggers. The views provide useful access to caption data.

For large-scale systems with extensive caption data, consider implementing text compression to reduce storage requirements and potentially improve query performance:

  1. Add a compressed caption text column:
ALTER TABLE "caption"
ADD COLUMN "captionTextCompressed" BYTEA;
  1. Create functions for compression and decompression:
CREATE OR REPLACE FUNCTION compress_text(text) RETURNS BYTEA AS $$
    SELECT pg_catalog.compress($1, 'pglz')
$$ LANGUAGE SQL IMMUTABLE STRICT;

CREATE OR REPLACE FUNCTION decompress_text(BYTEA) RETURNS TEXT AS $$
    SELECT pg_catalog.uncompress($1)
$$ LANGUAGE SQL IMMUTABLE STRICT;
  1. Create a trigger to automatically compress caption text on insert or update:
CREATE OR REPLACE FUNCTION compress_caption_text()
RETURNS TRIGGER AS $$
BEGIN
    NEW."captionTextCompressed" = compress_text(NEW."captionText");
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER compress_caption_text_trigger
BEFORE INSERT OR UPDATE OF "captionText" ON "caption"
FOR EACH ROW EXECUTE FUNCTION compress_caption_text();
  1. Update the view to use the decompressed text:
CREATE OR REPLACE VIEW "v_caption" AS
SELECT 
    "captionId",
    "meetingId",
    "captionType",
    "userId",
    "locale",
    decompress_text("captionTextCompressed") AS "captionText",
    "createdAt"
FROM "caption"
WHERE "createdAt" > current_timestamp - INTERVAL '5 seconds';

This approach can significantly reduce storage requirements for large caption datasets while maintaining query performance through indexes on other columns.


Line range hint 1661-1677: LGTM! Consider using a JSONB column for more flexible layout settings.

The layout table structure is well-designed for storing current layout information for meetings. The view provides straightforward access to layout data.

To allow for more flexibility in storing layout settings and to accommodate future changes without altering the table structure, consider using a JSONB column for additional layout settings:

  1. Add a JSONB column to the layout table:
ALTER TABLE "layout"
ADD COLUMN "additionalSettings" JSONB;
  1. Update the view to include the new column:
CREATE OR REPLACE VIEW "v_layout" AS
SELECT 
    "meetingId",
    "currentLayoutType",
    "presentationMinimized",
    "cameraDockIsResizing",
    "cameraDockPlacement",
    "cameraDockAspectRatio",
    "cameraWithFocus",
    "propagateLayout",
    "updatedAt",
    "additionalSettings"
FROM "layout";
  1. Create a function to easily update or add new settings:
CREATE OR REPLACE FUNCTION update_layout_setting(
    p_meetingId VARCHAR(100),
    p_key TEXT,
    p_value JSONB
)
RETURNS VOID AS $$
BEGIN
    UPDATE "layout"
    SET "additionalSettings" = COALESCE("additionalSettings", '{}'::JSONB) || jsonb_build_object(p_key, p_value)
    WHERE "meetingId" = p_meetingId;
END;
$$ LANGUAGE plpgsql;

This approach allows you to add new layout settings without changing the table structure, providing more flexibility for future enhancements.


Line range hint 1679-1734: LGTM! Consider implementing a notification archiving strategy for improved performance.

The notification table structure is well-designed with appropriate indexes and a view that filters notifications based on user roles and creation time.

For improved scalability and performance, especially in systems with a high volume of notifications, consider implementing a notification archiving strategy:

  1. Create an archive table for old notifications:
CREATE TABLE "notification_archive" (
    -- Same structure as the "notification" table
) PARTITION BY RANGE ("createdAt");

-- Create partitions as needed, e.g.:
CREATE TABLE "notification_archive_y2023m01" PARTITION OF "notification_archive"
    FOR VALUES FROM ('2023-01-01') TO ('2023-02-01');
  1. Create a function to move old notifications to the archive:
CREATE OR REPLACE FUNCTION archive_old_notifications()
RETURNS INTEGER AS $$
DECLARE
    v_archived_count INTEGER;
BEGIN
    WITH moved_rows AS (
        DELETE FROM "notification"
        WHERE "createdAt" < (CURRENT_DATE - INTERVAL '30 days')
        RETURNING *
    )
    INSERT INTO "notification_archive"
    SELECT * FROM moved_rows;

    GET DIAGNOSTICS v_archived_count = ROW_COUNT;
    RETURN v_archived_count;
END;
$$ LANGUAGE plpgsql;
  1. Create a scheduled job to run the archiving function periodically:
-- This requires the pg_cron extension
CREATE EXTENSION IF NOT EXISTS pg_cron;

SELECT cron.schedule('0 1 * * *', $$
    SELECT archive_old_notifications();
$$);
  1. Update the view to union current and archived notifications when necessary:
CREATE OR REPLACE VIEW "v_notification" AS
SELECT -- your existing SELECT clause
FROM "notification" n
-- your existing JOIN and WHERE clauses
UNION ALL
SELECT -- your existing SELECT clause
FROM "notification_archive" n
-- your

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**

<details>
<summary>📥 Commits</summary>

Files that changed from the base of the PR and between 04a5a9da9f8dff5be36e8c7102e846286104c62a and f375d4d3aa5ca0ed52e60bea65d1b2f5367d218d.

</details>

<details>
<summary>📒 Files selected for processing (8)</summary>

* akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PluginDAO.scala (1 hunks)
* akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala (1 hunks)
* bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (6 hunks)
* bbb-graphql-server/bbb_schema.sql (1 hunks)
* bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (1 hunks)
* bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (3 hunks)
* bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts (1 hunks)
* bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (5)</summary>

* akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala
* bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml
* bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx
* bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts
* bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts

</details>

<details>
<summary>🧰 Additional context used</summary>





</details>

<details>
<summary>🔇 Additional comments (3)</summary><blockquote>

<details>
<summary>akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PluginDAO.scala (3)</summary><blockquote>

`5-10`: **LGTM: Case class definition looks good**

The `PluginDbModel` case class is well-structured and includes all necessary fields, including the new `javascriptEntrypointChecksum`. This addition enhances the model's ability to verify the integrity of the JavaScript entry point.

---

`12-18`: _:warning: Potential issue_

**Fix the composite primary key definition**

The current table definition incorrectly defines the primary key. Both `meetingId` and `name` columns are marked individually with `O.PrimaryKey`, which doesn't create a composite primary key in Slick. This issue was previously identified and needs to be addressed.


To correctly define a composite primary key on both `meetingId` and `name`, apply the following changes:

```diff
 class PluginDbTableDef(tag: Tag) extends Table[PluginDbModel](tag, None, "plugin") {
-  val meetingId = column[String]("meetingId", O.PrimaryKey)
-  val name = column[String]("name", O.PrimaryKey)
+  val meetingId = column[String]("meetingId")
+  val name = column[String]("name")
   val javascriptEntrypointUrl = column[String]("javascriptEntrypointUrl")
   val javascriptEntrypointChecksum = column[String]("javascriptEntrypointChecksum")
+  def pk = primaryKey("plugin_pk", (meetingId, name))
   override def * = (meetingId, name, javascriptEntrypointUrl, javascriptEntrypointChecksum) <> (PluginDbModel.tupled, PluginDbModel.unapply)
 }

This change ensures that meetingId and name form a composite primary key as intended.


21-21: ⚠️ Potential issue

Specify return type for the insert method

The insert method still lacks an explicit return type. As mentioned in a previous review, it's a best practice in Scala to declare return types for public methods to enhance code readability and maintainability.

Please specify the return type of the insert method. For example:

def insert(meetingId: String, name: String, javascriptEntrypointUrl: String, javascriptEntrypointChecksum: String): Future[Int] = {

Ensure that the return type matches the actual type returned by DatabaseConnection.enqueue.

@gustavotrott gustavotrott changed the title feat(html5,akka,graphql-server,plugins,bigbluebutton-web): Change flow of loading a plugin to a parameter of URL pointing to manifest.json refactor (plugins): Read plugins configs from a manifest file instead of client settings Oct 10, 2024
…st.json to be sha256 and renamed javascriptEntrypointChecksum to javascriptEntrypointIntegrity

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (7)
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (2)

1-8: Clarify table type and enhance documentation

  1. The v_ prefix in the table name v_plugin suggests this might be a view rather than a table. Please clarify whether this is indeed a view or a regular table.

  2. Consider adding comments to explain the purpose of this table/view and its role in the plugin system. This will improve documentation and make it easier for other developers to understand the schema.

  3. The empty column_config, custom_column_names, and custom_root_fields configurations might represent missed opportunities for customization. If there are specific requirements or constraints for these fields, consider documenting them here.


10-19: Add explanatory comment for bbb_client role permissions

Consider adding a comment to explain the purpose of the bbb_client role and its permissions. This will improve documentation and make it easier for other developers to understand the access control logic. For example:

comment: "Allows BigBlueButton clients to access essential plugin information for their specific meeting."
bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (2)

354-384: LGTM! Consider adding input validation.

The implementation of replaceMetaParametersIntoManifestTemplate is well-structured and efficient. It correctly handles the replacement of placeholders with metadata values, including proper error handling for malformed inputs.

Consider adding input validation at the beginning of the method to check if manifestContent or metadata is null or empty. This would prevent potential NullPointerExceptions and improve the robustness of the method.

public String replaceMetaParametersIntoManifestTemplate(String manifestContent, Map<String, String> metadata)
        throws NoSuchFieldException {
+   if (manifestContent == null || manifestContent.isEmpty() || metadata == null || metadata.isEmpty()) {
+       throw new IllegalArgumentException("manifestContent and metadata must not be null or empty");
+   }
    // Rest of the method implementation...
}

110-111: LGTM! Consider lazy initialization for ObjectMapper.

The addition of ObjectMapper as a class member is a good practice for performance reasons. However, consider using lazy initialization to ensure the ObjectMapper is only created when needed:

- ObjectMapper objectMapper = new ObjectMapper();
+ private ObjectMapper objectMapper;
+ 
+ private ObjectMapper getObjectMapper() {
+     if (objectMapper == null) {
+         objectMapper = new ObjectMapper();
+     }
+     return objectMapper;
+ }

This approach ensures that the ObjectMapper is only created when it's first used, which can be beneficial in scenarios where it might not always be needed.

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

Line range hint 26-220: LGTM: Meeting tables are well-structured with appropriate relationships.

The meeting tables cover various aspects of BigBlueButton meetings, including core information, breakouts, recording policies, and client settings. The use of generated columns for timestamps (e.g., createdAt and ended) is a good practice for consistency and ease of querying.

Consider adding an index on the endedAt column of the meeting table to optimize queries filtering on meeting end time:

CREATE INDEX idx_meeting_endedAt ON meeting(endedAt);

This index could improve performance for queries that filter or sort based on the meeting end time, which is likely a common operation in the BigBlueButton system.


Line range hint 222-626: LGTM: User tables and views are comprehensive and well-structured.

The user-related tables and views provide a rich set of data about users in the BigBlueButton system. The use of generated columns (e.g., isDialIn, isModerator) and appropriate indexes is good for query performance and data consistency.

Consider adding a partial index on the user table for active users to potentially improve query performance:

CREATE INDEX idx_user_active ON user(meetingId, userId) 
WHERE currentlyInMeeting = true AND expired = false AND loggedOut = false;

This index could optimize queries that frequently filter for active users in a meeting, which is likely a common operation in the BigBlueButton system.


Line range hint 836-1236: LGTM: Presentation and annotation tables are well-designed with good permission management.

The presentation, page, and annotation tables provide a comprehensive structure for handling presentation functionality in BigBlueButton. The use of triggers for updating user drawing permissions is a good approach for maintaining consistency.

Consider adding a partial index on the pres_annotation table for the current presentation to potentially improve query performance:

CREATE INDEX idx_pres_annotation_current ON pres_annotation(pageId, userId)
WHERE pageId IN (
    SELECT pp.pageId 
    FROM pres_presentation p
    JOIN pres_page pp ON p.presentationId = pp.presentationId
    WHERE p.current = true AND pp.current = true
);

This index could optimize queries that frequently access annotations for the current presentation and page, which is likely a common operation during active presentations.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f375d4d and a590d15.

📒 Files selected for processing (7)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PluginDAO.scala (1 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (6 hunks)
  • bbb-graphql-server/bbb_schema.sql (1 hunks)
  • bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx (3 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts (1 hunks)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • bigbluebutton-html5/imports/ui/components/plugins-engine/loader/manager.tsx
  • bigbluebutton-html5/imports/ui/components/plugins-engine/query.ts
  • bigbluebutton-html5/imports/ui/components/plugins-engine/types.ts
🧰 Additional context used
🔇 Additional comments (12)
bbb-graphql-server/metadata/databases/BigBlueButton/tables/public_v_plugin.yaml (1)

20-29: ⚠️ Potential issue

Consolidate duplicate roles

The bbb_client_not_in_meeting role has identical permissions to the bbb_client role. This duplication is unnecessary and could lead to maintenance issues. As mentioned in a previous review comment, consider the following options:

  1. If these roles serve different purposes, add comments to explain their distinct use cases.
  2. If the permissions should differ, adjust them accordingly.
  3. If the roles are truly identical, consolidate them into a single role to simplify permission management.

Given that both roles have the same permissions and filters, it's recommended to consolidate them into a single role, such as bbb_client, unless there's a specific reason for the separation that isn't apparent from the configuration.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/db/PluginDAO.scala (1)

5-10: LGTM: Case class updated with integrity field

The PluginDbModel case class has been correctly updated to include the new javascriptEntrypointIntegrity field. This addition enhances the security of the plugin system by allowing integrity checks on the JavaScript entrypoint.

bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (2)

459-460: LGTM! Plugin manifest integration looks good.

The changes to the createMeeting method successfully integrate the new plugin manifest functionality. The requestPluginManifests(m) call is appropriately placed, and the result is correctly set to the meeting object.


546-546: LGTM! Plugin information correctly propagated.

The addition of m.getPlugins() to the gw.createMeeting() call ensures that the plugin information is correctly propagated to the gateway. This change aligns well with the previous modifications related to plugin manifests.

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

Line range hint 1-24: LGTM: Initial setup and helper functions are well-defined.

The creation of the unaccent extension and the two helper functions (immutable_lower_unaccent and remove_emojis) are appropriate for text processing in the BigBlueButton system. These functions will be useful for consistent text handling and sorting throughout the database.


Line range hint 628-834: LGTM: Chat tables and views are well-structured with good real-time features.

The chat-related tables and views provide a comprehensive structure for handling chat functionality in BigBlueButton. The use of triggers for updating typing indicators is a good approach for maintaining real-time information.

The design allows for efficient querying of chat messages and user statuses, which is crucial for a smooth chat experience in video conferencing systems.


Line range hint 1238-1334: LGTM: Poll tables and views are well-structured for efficient data handling.

The poll-related tables and views provide a comprehensive structure for handling polling functionality in BigBlueButton. The design allows for efficient storage and retrieval of poll data, options, and responses.

The views created (v_poll_response, v_poll_user, v_poll, v_poll_option, and v_poll_user_current) offer various perspectives on the poll data, which should cater to different querying needs in the application.


Line range hint 1336-1659: LGTM: Additional feature tables are well-designed to support various BigBlueButton functionalities.

The tables and views for external video, screenshare, timer, and breakout rooms are well-structured to support these features in BigBlueButton. The use of views to represent current status (e.g., v_externalVideo, v_screenshare, v_timer) is a good approach for querying active instances of these features.

The breakout room tables and associated triggers provide a robust structure for managing breakout sessions, including user assignments and status tracking. The set_last_room function is a clever way to maintain the latest room information for users.


Line range hint 1661-1724: LGTM: Shared notes tables and views are well-structured for collaborative note-taking.

The shared notes tables (sharedNotes, sharedNotes_rev, sharedNotes_session) and associated views provide a comprehensive structure for handling collaborative note-taking in BigBlueButton. The design allows for efficient storage and retrieval of shared notes data, revisions, and user sessions.

The views created (v_sharedNotes_diff, v_sharedNotes, v_sharedNotes_session) offer various perspectives on the shared notes data, which should facilitate different querying needs in the application, such as retrieving the latest revisions or active user sessions.


Line range hint 1726-1860: LGTM: Caption and layout tables are well-designed with good management features.

The caption and layout tables provide a solid structure for handling these features in BigBlueButton. The caption tables (caption_locale and caption) allow for efficient storage and retrieval of caption data, while the layout table supports various layout configurations.

The use of triggers (e.g., update_caption_locale_owner_func) for managing caption locale data is a good approach for maintaining data consistency. The views (v_caption, v_caption_activeLocales) offer useful perspectives on the caption data, which should facilitate different querying needs in the application.


Line range hint 1965-2007: LGTM: New plugin tables and views are well-structured to support plugin functionality.

The newly added plugin-related tables (plugin and pluginDataChannelEntry) and associated views provide a solid foundation for supporting plugin functionality in BigBlueButton. This addition aligns with the PR objectives of introducing a new plugin loading mechanism.

The pluginDataChannelEntry table, in particular, offers a flexible structure for storing various types of plugin data with its payloadJson column and role-based access control (toRoles and toUserIds). The v_pluginDataChannelEntry view provides a convenient way to access plugin data while respecting access controls.

This new structure should facilitate the development of server-side components for plugins, as mentioned in the PR objectives.


Line range hint 1-2007: Overall, the database schema is well-designed and comprehensive.

This SQL schema file provides a robust and well-structured database design for the BigBlueButton platform. It covers all major aspects of the system, including meetings, users, chats, presentations, polls, and various other features. The use of views, triggers, and generated columns throughout the schema promotes data consistency and query efficiency.

The newly added plugin-related tables (plugin and pluginDataChannelEntry) and associated views align well with the PR objectives of introducing a new plugin loading mechanism. These additions provide a flexible foundation for supporting plugin functionality, including data storage and role-based access control.

To further improve the schema:

  1. Consider regularly reviewing and optimizing indexes based on query patterns and performance metrics.
  2. As the plugin functionality evolves, you may need to revisit the plugin-related tables to ensure they continue to meet the system's needs.
  3. Consider implementing a versioning system for the schema to facilitate future updates and migrations.

Great job on maintaining and expanding this comprehensive database schema for BigBlueButton!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (2)

354-384: Good implementation with room for minor improvement

The replaceMetaParametersIntoManifestTemplate function is well-implemented. It effectively replaces metadata parameters in the manifest template using regex, and includes proper error handling for malformed or missing metadata.

A minor suggestion for improvement:

Consider extracting the regex pattern "\\$\\{(\\w+)}" into a constant at the class level. This would improve readability and allow for easy modification if the pattern needs to change in the future.

+ private static final Pattern METADATA_PATTERN = Pattern.compile("\\$\\{(\\w+)}");

 public String replaceMetaParametersIntoManifestTemplate(String manifestContent, Map<String, String> metadata)
         throws NoSuchFieldException {
-    Pattern pattern = Pattern.compile("\\$\\{(\\w+)}");
-    Matcher matcher = pattern.matcher(manifestContent);
+    Matcher matcher = METADATA_PATTERN.matcher(manifestContent);

385-449: Well-implemented function with opportunities for refinement

The requestPluginManifests function effectively fetches and processes plugin manifests. It includes proper resource management, checksum validation, and error handling. However, there are a few areas where it could be improved:

  1. Consider extracting the manifest fetching and processing logic into separate methods to improve readability and maintainability.

  2. The error handling could be more specific. Instead of catching a general Exception, catch and handle specific exceptions that might occur (e.g., IOException, JsonParseException).

  3. The checksum validation logic could be extracted into a separate method for better modularity.

Here's a sketch of how you might refactor this:

private Map<String, Object> fetchAndProcessManifest(PluginsManifest pluginsManifest, Map<String, String> metadata) throws IOException, NoSuchFieldException {
    String urlString = pluginsManifest.getUrl();
    String content = fetchManifestContent(urlString);
    
    if (!validateChecksum(content, pluginsManifest.getChecksum())) {
        log.error("Checksum mismatch for plugin manifest: {}", urlString);
        return null;
    }
    
    JsonNode jsonNode = objectMapper.readTree(content);
    String name = extractName(jsonNode, urlString);
    
    String processedContent = replaceMetaParametersIntoManifestTemplate(content, metadata);
    Map<String, Object> mappedContent = objectMapper.readValue(processedContent, new TypeReference<>() {});
    
    Map<String, Object> manifestObject = new HashMap<>();
    manifestObject.put("url", urlString);
    manifestObject.put("content", mappedContent);
    
    Map<String, Object> manifestWrapper = new HashMap<>();
    manifestWrapper.put("manifest", manifestObject);
    
    return Map.of(name, manifestWrapper);
}

private String fetchManifestContent(String urlString) throws IOException {
    URL url = new URL(urlString);
    StringBuilder content = new StringBuilder();
    try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            content.append(inputLine).append("\n");
        }
    }
    return content.toString();
}

private boolean validateChecksum(String content, String paramChecksum) {
    if (StringUtils.isEmpty(paramChecksum)) {
        return true;
    }
    String hash = DigestUtils.sha256Hex(content);
    return paramChecksum.equals(hash);
}

private String extractName(JsonNode jsonNode, String urlString) throws NoSuchFieldException {
    if (jsonNode.has("name")) {
        return jsonNode.get("name").asText();
    }
    throw new NoSuchFieldException("For url " + urlString + " there is no name field configured.");
}

This refactoring would make the main requestPluginManifests method more concise and easier to understand.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala (1)

35-44: Validate Essential Security Fields in PluginManifestContent

While javascriptEntrypointIntegrity is optional in the data model, it's crucial for ensuring the integrity of loaded scripts.

Consider adding validation logic during plugin loading to ensure that security-critical fields are present, and enforce policies requiring these fields for enhanced security.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a590d15 and 72adc94.

📒 Files selected for processing (2)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/models/Plugins.scala (1 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (6 hunks)
🧰 Additional context used
🔇 Additional comments (1)
bbb-common-web/src/main/java/org/bigbluebutton/api/MeetingService.java (1)

450-461: Appropriate integration of plugin manifest functionality

The addition of requestPluginManifests(m) and setting the plugins for the meeting object is a well-placed enhancement to the createMeeting function. This change effectively integrates the new plugin manifest functionality into the meeting creation process.

The modification is concise and fits well within the existing structure of the method. It enhances the meeting's capabilities by incorporating plugin information at the time of creation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (7)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginHdlrHelpers.scala (2)

8-16: LGTM with suggestion: Consider simplifying the return type.

The checkPermission method correctly handles the specified permission types and uses appropriate Scala features like pattern matching and by-name parameters. However, returning a List[Boolean] might be confusing for callers expecting a single boolean result.

Consider refactoring the method to return a single Boolean instead of List[Boolean]. This could be done by using permissionType.exists(...) instead of permissionType.map(...). For example:

def checkPermission(user: UserState, permissionType: List[String], creatorCheck: => Boolean = false): Boolean = {
  permissionType.exists(_.toLowerCase match {
    case "all"       => true
    case "moderator" => user.role == Roles.MODERATOR_ROLE
    case "presenter" => user.presenter
    case "creator"   => creatorCheck
    case _           => false
  })
}

This change would make the method's purpose clearer and easier to use.


1-27: Overall: Well-structured and functional, with room for minor improvements.

The PluginHdlrHelpers object provides useful functionality for plugin permission checking. The code is well-organized and uses appropriate Scala features. Consider implementing the suggested improvements for error handling and return type simplification to enhance robustness and usability.

As this file introduces new functionality for plugin management, ensure that it aligns with the overall architecture of the BigBlueButton platform. Consider the following:

  1. Documentation: Add scaladoc comments to the object and methods to explain their purpose and usage.
  2. Testing: Ensure comprehensive unit tests are in place for both methods, covering various scenarios including edge cases.
  3. Consistency: Verify that the permission checking logic aligns with the platform's overall security model.

These considerations will help maintain the quality and maintainability of the codebase as the plugin system evolves.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (1)

24-25: Simplify permission check condition.

The current permission check can be simplified. Consider changing:

if (!hasPermission.contains(true)) {

to:

if (!hasPermission) {

This assumes that checkPermission returns a Boolean instead of an Option[Boolean]. If it does return an Option, consider modifying the helper function to return a Boolean directly for cleaner usage.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (1)

20-23: LGTM: Improved plugin and data channel validation.

The refactoring to use PluginModel.getPluginByName and direct manifest access for data channel validation is a good improvement. It simplifies the code and aligns with the model-based approach.

Consider adding error logging for the case when a plugin is not found, as it might help with debugging in production environments.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (1)

20-22: Improved plugin retrieval logic

The new approach using PluginModel.getPluginByName is more direct and aligns well with a model-based approach. This change enhances code readability and maintainability.

Consider using getOrElse(List.empty) instead of getOrElse(List()) for better Scala idioms:

p.manifest.content.dataChannels.getOrElse(List.empty).find(dc => dc.name == msg.body.channelName) match {
bbb-common-message/src/main/scala/org/bigbluebutton/common2/msgs/PluginMsgs.scala (1)

Line range hint 41-46: LGTM with a minor suggestion: Consider reordering fields for consistency

The modification to PluginDataChannelDeleteEntryMsgBody to extend PluginDataChannelReplaceOrDeleteBaseBody is a good refactoring. It improves code organization and type safety without changing functionality.

However, for better readability and consistency, consider reordering the fields to match the order in the trait and the PluginDataChannelReplaceEntryMsgBody class:

case class PluginDataChannelDeleteEntryMsgBody(
  pluginName: String,
  channelName: String,
  subChannelName: String,
  entryId: String
) extends PluginDataChannelReplaceOrDeleteBaseBody

This minor change would make the codebase more uniform and easier to maintain.

bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (1)

430-459: LGTM! Consider adding null checks for better robustness.

The implementation of processPluginsManifestsParams looks good. It correctly processes the JSON array of plugin manifests and handles potential JSON syntax errors.

Consider adding null checks for pluginsManifestParams and pluginsManifestsJsonElement to improve robustness. For example:

 String pluginsManifestParams = params.get(ApiParams.PLUGINS_MANIFESTS);
-if (!StringUtils.isEmpty(pluginsManifestParams)) {
+if (pluginsManifestParams != null && !pluginsManifestParams.isEmpty()) {
     try {
         JsonElement pluginsManifestsJsonElement = new Gson().fromJson(pluginsManifestParams, JsonElement.class);
-        if(pluginsManifestsJsonElement != null && pluginsManifestsJsonElement.isJsonArray()) {
+        if (pluginsManifestsJsonElement != null && pluginsManifestsJsonElement.isJsonArray()) {
             // ... rest of the code ...
         }
     } catch (JsonSyntaxException err) {
         log.error("Error in pluginsManifests URL parameter's json structure.");
     }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 3951cf6 and 1c3c11a.

📒 Files selected for processing (7)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (2 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginHdlrHelpers.scala (1 hunks)
  • bbb-common-message/src/main/scala/org/bigbluebutton/common2/msgs/PluginMsgs.scala (3 hunks)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (4 hunks)
🧰 Additional context used
🔇 Additional comments (19)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginHdlrHelpers.scala (2)

3-5: LGTM: Import statements are appropriate and concise.

The import statements are relevant to the functionality of the PluginHdlrHelpers object and there are no unused imports.


17-26: LGTM with suggestions: Consider error handling and performance optimization.

The defaultCreatorCheck method correctly implements the creator check functionality. However, there are a few areas for potential improvement:

  1. Error Handling: The method doesn't handle potential exceptions from the database operation. Consider adding try-catch blocks or using Scala's Option or Either for better error handling.

  2. Performance: If this method is called frequently, consider caching the results or optimizing the database query.

Here's a suggestion for improving error handling:

import scala.util.Try

def defaultCreatorCheck[T <: PluginDataChannelReplaceOrDeleteBaseBody](meetingId: String, msgBody: T, userId: String): Boolean = {
  Try {
    PluginDataChannelEntryDAO.getEntryCreator(
      meetingId,
      msgBody.pluginName,
      msgBody.channelName,
      msgBody.subChannelName,
      msgBody.entryId
    )
  }.toOption.contains(userId)
}

This version will return false if there's any exception during the database operation, which might be safer than throwing an unhandled exception.

To assess the potential performance impact, let's check how frequently this method is called:

If the method is called frequently, consider discussing caching strategies with the team.

✅ Verification successful

Performance Impact Assessment: Verified Low Frequency of defaultCreatorCheck Calls

The defaultCreatorCheck method is invoked in the following locations:

  • PluginDataChannelReplaceEntryMsgHdlr.scala
  • PluginDataChannelDeleteEntryMsgHdlr.scala

With only two usages, the performance impact is minimal. Therefore, caching or further performance optimizations may not be necessary at this time.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to defaultCreatorCheck
rg "defaultCreatorCheck" --type scala

Length of output: 1101

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (3)

5-5: LGTM: Import changes align with the new plugin management approach.

The addition of PluginModel and removal of ClientSettings are consistent with the transition from a configuration-based to a model-based approach for plugin management, as described in the PR objectives.

Also applies to: 8-8


21-39: LGTM: Improved plugin and data channel handling.

The new implementation using PluginModel.getPluginByName and pattern matching for plugin and data channel existence checks is more robust and aligns well with the model-based approach. The error messages are also more specific and informative, which will aid in debugging and logging.


Line range hint 1-43: Overall, the changes represent a significant improvement in plugin management.

The transition to a model-based approach for plugin handling, improved error messages, and more robust structure align well with the PR objectives. The code is now more maintainable and provides better debugging information.

Consider addressing the permission checking logic as suggested in the previous comment to ensure all cases are handled correctly.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (4)

4-4: LGTM: New imports align with implementation changes.

The added imports for PluginModel and checkPermission are consistent with the new implementation approach for plugin handling and permission checking.

Also applies to: 7-7


20-22: LGTM: Improved plugin and data channel retrieval logic.

The new implementation using PluginModel.getPluginByName and nested match statements provides a more direct and readable approach to accessing plugin information. This change aligns well with the refactoring goals mentioned in the PR objectives.


28-37: LGTM: Data insertion logic remains correct.

The implementation for inserting data into PluginDataChannelEntryDAO is unchanged and correctly placed within the permission check. This ensures that data is only inserted when the user has the appropriate permissions.


Line range hint 1-44: Overall, the changes align well with the PR objectives.

The refactoring of the PluginDataChannelPushEntryMsgHdlr trait successfully implements the new approach for plugin management using PluginModel instead of ClientSettings. This change enhances the flexibility and maintainability of the plugin system.

Key improvements:

  1. Direct access to plugin information using PluginModel.
  2. Simplified permission checking logic.
  3. Better error handling with nested match statements.

Suggestions for further improvement:

  1. Simplify the permission check condition.
  2. Replace println statements with a proper logging framework.

These changes contribute positively to the overall goal of refactoring the plugin loading mechanism and preparing for future server-side plugin components.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (4)

4-4: LGTM: Import changes align with refactoring.

The new imports for PluginHdlrHelpers methods and PluginModel are consistent with the refactoring of the handle method, supporting the transition to a model-based approach for plugin management.

Also applies to: 7-7


24-29: Improved permission checking, but logging needs update.

The new permission checking logic using checkPermission and defaultCreatorCheck is a good improvement, providing more flexibility and clarity.

However, the use of println for logging persists. As mentioned in a previous review:

Replace println statements with proper logging. Using a logging framework provides better control and consistency. Consider using SLF4J or the application's preferred logging solution.

Example:

import org.slf4j.LoggerFactory
private val logger = LoggerFactory.getLogger(getClass)

// Replace println with:
logger.warn(s"No permission to delete in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")

30-36: LGTM: Proper use of PluginDataChannelEntryDAO for data deletion.

The implementation of PluginDataChannelEntryDAO.delete is a good addition, aligning with the database-backed approach for managing plugin data. The method parameters cover all necessary information for precise deletion of entries.


38-38: Replace println with proper logging for error cases.

While the error messages provide clear information, the use of println for logging persists. As mentioned earlier:

Replace println statements with proper logging. Using a logging framework provides better control and consistency. Consider using SLF4J or the application's preferred logging solution.

Example:

import org.slf4j.LoggerFactory
private val logger = LoggerFactory.getLogger(getClass)

// Replace println with:
logger.warn(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
logger.warn(s"Plugin '${msg.body.pluginName}' not found.")

Also applies to: 40-40

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (2)

4-4: Improved code organization with new imports

The addition of PluginHdlrHelpers and PluginModel imports suggests a move towards more modular and reusable code. This change enhances the overall structure and maintainability of the plugin management system.

Also applies to: 7-7


30-37: Improved data replacement logic

The use of PluginDataChannelEntryDAO.replace for data replacement indicates a move towards a more structured and consistent data access approach. This change enhances the overall architecture of the plugin system.

bbb-common-message/src/main/scala/org/bigbluebutton/common2/msgs/PluginMsgs.scala (3)

11-16: LGTM: Well-structured trait for plugin data channel operations

The new PluginDataChannelReplaceOrDeleteBaseBody trait is a good addition. It encapsulates common properties used in plugin data channel operations, promoting code reuse and maintaining consistency across related message types. The naming convention follows Scala best practices.


31-37: LGTM: Appropriate use of the new trait

The modification to PluginDataChannelReplaceEntryMsgBody to extend PluginDataChannelReplaceOrDeleteBaseBody is a good refactoring. It improves code organization and type safety without changing functionality. This change aligns well with the new abstraction introduced by the trait.


Line range hint 1-46: Summary: Effective refactoring for improved code organization

The changes in this file introduce a new trait PluginDataChannelReplaceOrDeleteBaseBody and modify two existing case classes (PluginDataChannelReplaceEntryMsgBody and PluginDataChannelDeleteEntryMsgBody) to extend this trait. This refactoring:

  1. Improves code organization by extracting common fields into a shared trait.
  2. Enhances type safety by providing a common interface for related message types.
  3. Promotes code reuse and consistency across plugin data channel operations.

These changes align with good software engineering practices and should make the codebase more maintainable. The functionality remains unchanged, focusing solely on structural improvements.

bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (1)

569-571: LGTM! Good integration of plugin manifests processing.

The changes to the processCreateParams method effectively integrate the new plugin manifests processing. The processPluginsManifestsParams method is called appropriately, and the result is correctly passed to the Meeting object during construction.

Also applies to: 822-822

Comment on lines +27 to +28
if (!hasPermission.contains(true)) {
println(s"No permission to delete (reset) in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve permission check logic.

The current permission check if (!hasPermission.contains(true)) might not handle all cases correctly. If hasPermission is None, this condition will evaluate to true, denying permission by default.

Consider updating the logic to handle the None case explicitly:

val permissionGranted = hasPermission.getOrElse(false)
if (!permissionGranted) {
  println(s"No permission to delete (reset) in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
} else {
  // Proceed with reset
}

This change ensures that permission is denied by default if hasPermission is None, while maintaining the existing behavior for Some(true) and Some(false) cases.

case Some(dc) =>
val hasPermission = checkPermission(user, dc.pushPermission)
if (!hasPermission.contains(true)) {
println(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace println with a proper logging framework.

Using println for error logging is not recommended in a production environment. Consider using a proper logging framework like Scala Logging or SLF4J. This will provide better control over log levels, formatting, and output destinations.

Example using Scala Logging:

import com.typesafe.scalalogging.Logger

private val logger = Logger(getClass)

// Replace println statements with:
logger.error(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
logger.error(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
logger.error(s"Plugin '${msg.body.pluginName}' not found.")

This change will improve error tracking and debugging capabilities.

Also applies to: 39-39, 41-41

Comment on lines +24 to +29
val hasPermission = checkPermission(user, dc.replaceOrDeletePermission, defaultCreatorCheck(
meetingId, msg.body, msg.header.userId))

if (!pluginsConfig.contains(msg.body.pluginName)) {
println(s"Plugin '${msg.body.pluginName}' not found.")
} else if (!pluginsConfig(msg.body.pluginName).dataChannels.contains(msg.body.channelName)) {
println(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
} else {
val hasPermission = for {
replaceOrDeletePermission <- pluginsConfig(msg.body.pluginName).dataChannels(msg.body.channelName).replaceOrDeletePermission
} yield {
replaceOrDeletePermission.toLowerCase match {
case "all" => true
case "moderator" => user.role == Roles.MODERATOR_ROLE
case "presenter" => user.presenter
case "creator" => {
val creatorUserId = PluginDataChannelEntryDAO.getEntryCreator(
meetingId,
msg.body.pluginName,
msg.body.channelName,
msg.body.subChannelName,
msg.body.entryId
)
creatorUserId == msg.header.userId
}
case _ => false
if (!hasPermission.contains(true)) {
println(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
} else {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improved permission checking logic

The new permission checking logic using checkPermission and defaultCreatorCheck is more concise and modular. This change improves code readability and maintainability.

Consider replacing the println statement with a proper logging mechanism for better error tracking and consistency with best practices:

if (!hasPermission.contains(true)) {
  logger.warn(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
} else {
  // ... existing code ...
}

JsonUtils.mapToJson(msg.body.payloadJson),
)
}
case None => println(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling and logging

While the error messages are now more specific and informative, using println for error logging is not ideal for production code. Consider replacing these with proper logging statements for better error tracking and consistency with best practices.

Replace the println statements with logger calls:

case None => logger.warn(s"Data channel '${msg.body.channelName}' not found in plugin '${msg.body.pluginName}'.")
// ...
case None => logger.warn(s"Plugin '${msg.body.pluginName}' not found.")

Also applies to: 41-41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (1)

12-28: Approve refactoring with suggestions for further improvements

The refactoring of the handle method is a significant improvement. The use of dataChannelCheckingLogic and checkPermission enhances the code structure and readability. However, there are a few areas where further improvements can be made:

  1. Error logging: The use of println for error logging is still present. Consider replacing it with a proper logging framework as suggested in previous comments.

  2. Permission checking: While simplified, the permission check can be further improved. Consider using pattern matching or a more idiomatic Scala approach.

Here's a suggested improvement for the permission check:

checkPermission(user, dc.pushPermission) match {
  case Some(true) =>
    PluginDataChannelEntryDAO.insert(
      meetingId,
      msg.body.pluginName,
      msg.body.channelName,
      msg.body.subChannelName,
      msg.header.userId,
      msg.body.payloadJson,
      msg.body.toRoles,
      msg.body.toUserIds
    )
  case _ =>
    logger.warn(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
}

This approach simplifies the logic and prepares for proper error logging.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginHdlrHelpers.scala (1)

9-17: Add logging for unrecognized permission types in checkPermission

Currently, unrecognized permission types are silently ignored by returning false. It would be helpful to log a warning when an unrecognized permission type is encountered to aid in debugging and monitoring.

Apply this diff to add logging:

First, import the logging framework and define the logger:

import org.slf4j.LoggerFactory

object PluginHdlrHelpers {
  private val log = LoggerFactory.getLogger(getClass)
  // existing code...
}

Then, update the default case in the checkPermission method:

      case _ =>
+       log.warn(s"Unrecognized permission type: '${permissionType}' for user: ${user.intId}")
        false
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1c3c11a and 9692639.

📒 Files selected for processing (5)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (1 hunks)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginHdlrHelpers.scala (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelDeleteEntryMsgHdlr.scala
  • akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelReplaceEntryMsgHdlr.scala
🧰 Additional context used
🔇 Additional comments (5)
akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelResetMsgHdlr.scala (3)

4-4: LGTM: Import of helper functions.

The addition of this import statement is appropriate for the refactoring of the handle method. It brings in the necessary helper functions checkPermission and dataChannelCheckingLogic from PluginHdlrHelpers.


12-25: LGTM: Refactored implementation of handle method.

The refactoring of the handle method improves code clarity and aligns with the described changes in the AI-generated summary. The use of dataChannelCheckingLogic and checkPermission functions encapsulates complex logic, making the code more readable and maintainable.

The reset operation using PluginDataChannelEntryDAO.reset is appropriate for the model-based approach mentioned in the PR objectives.


15-17: ⚠️ Potential issue

Improve permission check logic to handle None case.

The current permission check if (!hasPermission.contains(true)) doesn't explicitly handle the case when hasPermission is None. This could lead to unintended behavior.

Consider updating the logic to handle the None case explicitly:

val permissionGranted = hasPermission.getOrElse(false)
if (!permissionGranted) {
  println(s"No permission to delete (reset) in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")
} else {
  // Proceed with reset
}

This change ensures that permission is denied by default if hasPermission is None, while maintaining the existing behavior for Some(true) and Some(false) cases.

akka-bbb-apps/src/main/scala/org/bigbluebutton/core/apps/plugin/PluginDataChannelPushEntryMsgHdlr.scala (2)

4-4: LGTM: Import changes align with refactoring

The new import brings in helper functions from PluginHdlrHelpers, which are used in the refactored handle method. This change aligns with the suggested refactoring from past review comments and improves the overall structure of the code.


15-15: ⚠️ Potential issue

Replace println with a proper logging framework

Using println for error logging is not recommended in a production environment. As suggested in previous comments, consider using a proper logging framework like Scala Logging or SLF4J. This will provide better control over log levels, formatting, and output destinations.

Example using Scala Logging:

import com.typesafe.scalalogging.Logger

private val logger = Logger(getClass)

// Replace println with:
logger.warn(s"No permission to write in plugin: '${msg.body.pluginName}', data channel: '${msg.body.channelName}'.")

This change will improve error tracking and debugging capabilities.

Comment on lines +32 to +47
val pluginsDisabled: Boolean = liveMeeting.props.meetingProp.disabledFeatures.contains("plugins")
val meetingId = liveMeeting.props.meetingProp.intId

for {
_ <- if (!pluginsDisabled) Some(()) else None
user <- Users2x.findWithIntId(liveMeeting.users2x, userId)
} yield {
PluginModel.getPluginByName(liveMeeting.plugins, pluginName) match {
case Some(p) =>
p.manifest.content.dataChannels.getOrElse(List()).find(dc => dc.name == channelName) match {
case Some(dc) =>
caseSomeDataChannelAndPlugin(user, dc, meetingId)
case None => println(s"Data channel '${channelName}' not found in plugin '${pluginName}'.")
}
case None => println(s"Plugin '${pluginName}' not found.")
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace println statements with proper logging

Using println for error messages is not recommended in production code. Replace println with a logging framework to handle log messages appropriately and to control log levels.

First, import the logging framework and define the logger (if not already done):

import org.slf4j.LoggerFactory

object PluginHdlrHelpers {
  private val log = LoggerFactory.getLogger(getClass)
  // existing code...
}

Then, apply this diff to replace println statements with log.warn:

              case None =>
-               println(s"Data channel '${channelName}' not found in plugin '${pluginName}'.")
+               log.warn(s"Data channel '${channelName}' not found in plugin '${pluginName}'.")

            case None =>
-             println(s"Plugin '${pluginName}' not found.")
+             log.warn(s"Plugin '${pluginName}' not found.")

Comment on lines +19 to +27
val creatorUserId = PluginDataChannelEntryDAO.getEntryCreator(
meetingId,
msgBody.pluginName,
msgBody.channelName,
msgBody.subChannelName,
msgBody.entryId
)
creatorUserId == userId
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure null safety in defaultCreatorCheck to prevent potential NullPointerException

If PluginDataChannelEntryDAO.getEntryCreator returns null, comparing it directly with userId could lead to a NullPointerException. It's safer to handle potential null values explicitly.

Apply this diff to add null safety:

 def defaultCreatorCheck[T <: PluginDataChannelReplaceOrDeleteBaseBody](meetingId: String, msgBody: T, userId: String): Boolean = {
   val creatorUserId = PluginDataChannelEntryDAO.getEntryCreator(
     meetingId,
     msgBody.pluginName,
     msgBody.channelName,
     msgBody.subChannelName,
     msgBody.entryId
   )
-  creatorUserId == userId
+  Option(creatorUserId).contains(userId)
 }
📝 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.

Suggested change
val creatorUserId = PluginDataChannelEntryDAO.getEntryCreator(
meetingId,
msgBody.pluginName,
msgBody.channelName,
msgBody.subChannelName,
msgBody.entryId
)
creatorUserId == userId
}
val creatorUserId = PluginDataChannelEntryDAO.getEntryCreator(
meetingId,
msgBody.pluginName,
msgBody.channelName,
msgBody.subChannelName,
msgBody.entryId
)
Option(creatorUserId).contains(userId)
}

gustavotrott and others added 4 commits October 14, 2024 14:34
it is useful when the application that requires authorization wants to inject user information to the request
it can be an integration with a third party applicaton and it will require to receive user-external-is and meeting-external-id
it can also validate if the requester is moderator or presenter, so now it includes user-is-moderator and user-is-presenter headers
e.g pluginsManifests=[{url: "https://plugin_manifest.json"}]
it will be merged with the parameters received through /create?pluginsManifests=
Add config `pluginsManifests` and new headers to `/checkGraphqlAuthorization`

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (4)
bigbluebutton-web/grails-app/conf/spring/resources.xml (1)

Line range hint 236-237: Update documentation for TURN/STUN server configuration.

The comment indicates that the import statement for turn-stun-servers.xml has been moved to resources.groovy. This change allows for overlay configuration of TURN/STUN servers.

Please ensure that the documentation is updated to reflect this change in the configuration process for TURN/STUN servers. This will help maintain clear and accurate documentation for developers and administrators working with BigBlueButton.

bigbluebutton-web/grails-app/conf/bigbluebutton.properties (3)

477-477: Consider updating documentation and adding deprecation warnings for allowDuplicateExtUserid

The comment suggests replacing allowDuplicateExtUserid with maxUserConcurrentAccesses. However, allowDuplicateExtUserid is still present and set to true. To avoid confusion:

  1. Update the documentation to clearly explain the relationship between these properties.
  2. Consider adding deprecation warnings for allowDuplicateExtUserid in the code that uses this property.
  3. Provide migration guidelines for users to transition from allowDuplicateExtUserid to maxUserConcurrentAccesses.

478-480: Approve addition of pluginsManifests property with security recommendations

The addition of the pluginsManifests property aligns with the PR objectives to read plugin configs from manifest files. This change enhances the flexibility of the plugin system. However, consider the following security recommendations:

  1. Implement URL validation and sanitation for the manifest URLs to prevent potential security vulnerabilities (e.g., SSRF attacks).
  2. Add a comment explaining the expected format of the JSON array and any restrictions on the URLs (e.g., HTTPS only, allowed domains).
  3. Consider implementing a mechanism to verify the integrity of the manifest files, such as checksum validation or digital signatures.

Line range hint 1-480: Consider additional updates to support the new plugin system

The changes made to introduce the pluginsManifests property are appropriate and align with the PR objectives. To further enhance the plugin system integration, consider the following suggestions:

  1. Review other properties in this file to identify any that might need updates or additions to support the new plugin system (e.g., plugin-specific timeouts, resource limits).
  2. Add a section with comments explaining the overall plugin system architecture and how it integrates with the rest of the BigBlueButton platform.
  3. Include examples of how to configure pluginsManifests for common use cases to help users understand the new feature.
  4. Consider adding properties to control plugin behavior globally (e.g., enablePlugins, maxPluginsPerMeeting).

These additions would provide a more comprehensive configuration setup for the new plugin system and improve its maintainability and usability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9692639 and ac956c7.

📒 Files selected for processing (4)
  • bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (6 hunks)
  • bigbluebutton-web/grails-app/conf/bigbluebutton.properties (1 hunks)
  • bigbluebutton-web/grails-app/conf/spring/resources.xml (1 hunks)
  • bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ConnectionController.groovy (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
bigbluebutton-web/grails-app/conf/spring/resources.xml (1)

204-204: LGTM: New property for plugin manifests added.

The addition of the pluginsManifests property to the paramsProcessorUtil bean aligns with the PR objectives of reading plugin configs from a manifest file. This change supports the new plugin loading mechanism.

To ensure this change is properly integrated, please verify that the pluginsManifests property is correctly defined in the corresponding configuration file (likely application.properties or application.yml). Run the following command to check:

bbb-common-web/src/main/java/org/bigbluebutton/api/ParamsProcessorUtil.java (1)

Line range hint 1-1649: Overall assessment of plugin manifest integration

The changes introduced in this file successfully implement support for plugin manifests in BigBlueButton. The new functionality is well-integrated into the existing code structure, particularly in the meeting creation process. The implementation includes processing of plugin manifests from both default configuration and API parameters, which provides flexibility in how plugins can be specified.

Key points:

  1. A new method processPluginsManifests has been added to handle JSON parsing of plugin manifests.
  2. The processCreateParams method has been updated to incorporate plugin manifests into meeting creation.
  3. A new property defaultPluginsManifests has been added to store default plugin configurations.

While the implementation is solid, there are opportunities for minor improvements in error handling, input validation, and code documentation. These suggestions have been provided in the individual review comments.

The changes are approved with the suggested minor improvements. This feature will enhance BigBlueButton's extensibility by allowing easier integration of plugins.

bigbluebutton-web/grails-app/controllers/org/bigbluebutton/web/controllers/ConnectionController.groovy (1)

80-85: ⚠️ Potential issue

Verify exposure of sensitive user information in response headers

The added response headers include User-External-Id, User-Name, User-Is-Moderator, and User-Is-Presenter. Exposing user-specific details in HTTP headers can have security implications, such as leaking Personally Identifiable Information (PII) or aiding in user enumeration attacks.

Please ensure that:

  • It is necessary to include these user details in the response headers.
  • Appropriate security measures are in place to protect this information.
  • Compliance with privacy policies and regulations is maintained.

Consider removing sensitive information from headers or using alternative methods to relay necessary data securely.

private boolean defaultAllowModsToUnmuteUsers = false;
private boolean defaultAllowModsToEjectCameras = false;
private String defaultDisabledFeatures;
private String defaultPluginsManifests;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

New property for default plugin manifests

A new property defaultPluginsManifests has been added to the class, along with its setter method. This addition supports the new plugin manifest functionality. The implementation looks correct, but there are a few suggestions:

  1. Consider adding a JavaDoc comment to explain the purpose and format of this property.
  2. The setter method could benefit from input validation.

Consider applying these changes:

+    /**
+     * Stores the default plugin manifests in JSON format.
+     * This string should contain an array of objects, each with a 'url' and optional 'checksum' field.
+     */
     private String defaultPluginsManifests;

     // ... (other code)

     public void setPluginsManifests(String pluginsManifests) {
+        if (pluginsManifests == null) {
+            throw new IllegalArgumentException("pluginsManifests cannot be null");
+        }
         this.defaultPluginsManifests = pluginsManifests;
     }

These changes improve documentation and add basic input validation to the setter method.

Also applies to: 1623-1625

Comment on lines +576 to +589
// Parse Plugins Manifests from config and param
ArrayList<PluginsManifest> listOfPluginsManifests = new ArrayList<PluginsManifest>();
//Process plugins from config
if(defaultPluginsManifests != null && !defaultPluginsManifests.isEmpty()) {
ArrayList<PluginsManifest> pluginsManifestsFromConfig = processPluginsManifests(defaultPluginsManifests);
listOfPluginsManifests.addAll(pluginsManifestsFromConfig);
}
//Process plugins from /create param
String pluginsManifestsParam = params.get(ApiParams.PLUGINS_MANIFESTS);
if (!StringUtils.isEmpty(pluginsManifestsParam)) {
ArrayList<PluginsManifest> pluginsManifestsFromParam = processPluginsManifests(pluginsManifestsParam);
listOfPluginsManifests.addAll(pluginsManifestsFromParam);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Integration of plugin manifests in meeting creation

The changes in the processCreateParams method integrate the new plugin manifest functionality. Here are some observations:

  1. The method now processes plugins from both the config and the /create param.
  2. It uses the new processPluginsManifests method to handle the plugin manifests.
  3. The resulting list of plugin manifests is stored in listOfPluginsManifests.

The implementation looks correct, but there are a few suggestions for improvement:

  1. Consider adding a comment to explain the purpose of processing plugins from both config and param.
  2. The variable name pluginsManifestsFromConfig might be misleading as it's not clear if it's from a config file or a default value.

Consider applying these changes:

+    // Process plugin manifests from both default configuration and create API parameters
     ArrayList<PluginsManifest> listOfPluginsManifests = new ArrayList<PluginsManifest>();
-    //Process plugins from config
+    // Process plugins from default configuration
     if(defaultPluginsManifests != null && !defaultPluginsManifests.isEmpty()) {
-        ArrayList<PluginsManifest> pluginsManifestsFromConfig = processPluginsManifests(defaultPluginsManifests);
-        listOfPluginsManifests.addAll(pluginsManifestsFromConfig);
+        listOfPluginsManifests.addAll(processPluginsManifests(defaultPluginsManifests));
     }
-    //Process plugins from /create param
+    // Process plugins from /create API parameter
     String pluginsManifestsParam = params.get(ApiParams.PLUGINS_MANIFESTS);
     if (!StringUtils.isEmpty(pluginsManifestsParam)) {
-        ArrayList<PluginsManifest> pluginsManifestsFromParam = processPluginsManifests(pluginsManifestsParam);
-        listOfPluginsManifests.addAll(pluginsManifestsFromParam);
+        listOfPluginsManifests.addAll(processPluginsManifests(pluginsManifestsParam));
     }

These changes improve code readability and reduce unnecessary variable declarations.

📝 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.

Suggested change
// Parse Plugins Manifests from config and param
ArrayList<PluginsManifest> listOfPluginsManifests = new ArrayList<PluginsManifest>();
//Process plugins from config
if(defaultPluginsManifests != null && !defaultPluginsManifests.isEmpty()) {
ArrayList<PluginsManifest> pluginsManifestsFromConfig = processPluginsManifests(defaultPluginsManifests);
listOfPluginsManifests.addAll(pluginsManifestsFromConfig);
}
//Process plugins from /create param
String pluginsManifestsParam = params.get(ApiParams.PLUGINS_MANIFESTS);
if (!StringUtils.isEmpty(pluginsManifestsParam)) {
ArrayList<PluginsManifest> pluginsManifestsFromParam = processPluginsManifests(pluginsManifestsParam);
listOfPluginsManifests.addAll(pluginsManifestsFromParam);
}
// Process plugin manifests from both default configuration and create API parameters
ArrayList<PluginsManifest> listOfPluginsManifests = new ArrayList<PluginsManifest>();
// Process plugins from default configuration
if(defaultPluginsManifests != null && !defaultPluginsManifests.isEmpty()) {
listOfPluginsManifests.addAll(processPluginsManifests(defaultPluginsManifests));
}
// Process plugins from /create API parameter
String pluginsManifestsParam = params.get(ApiParams.PLUGINS_MANIFESTS);
if (!StringUtils.isEmpty(pluginsManifestsParam)) {
listOfPluginsManifests.addAll(processPluginsManifests(pluginsManifestsParam));
}

Comment on lines +431 to +456
private ArrayList<PluginsManifest> processPluginsManifests(String pluginsManifestsParam) {
ArrayList<PluginsManifest> pluginsManifests = new ArrayList<PluginsManifest>();
JsonElement pluginsManifestsJsonElement = new Gson().fromJson(pluginsManifestsParam, JsonElement.class);
try {
if (pluginsManifestsJsonElement != null && pluginsManifestsJsonElement.isJsonArray()) {
JsonArray pluginsManifestsJson = pluginsManifestsJsonElement.getAsJsonArray();
for (JsonElement pluginsManifestJson : pluginsManifestsJson) {
if (pluginsManifestJson.isJsonObject()) {
JsonObject pluginsManifestJsonObj = pluginsManifestJson.getAsJsonObject();
if (pluginsManifestJsonObj.has("url")) {
String url = pluginsManifestJsonObj.get("url").getAsString();
PluginsManifest newPlugin = new PluginsManifest(url);
if (pluginsManifestJsonObj.has("checksum")) {
newPlugin.setChecksum(pluginsManifestJsonObj.get("checksum").getAsString());
}
pluginsManifests.add(newPlugin);
}
}
}
}
} catch(JsonSyntaxException err){
log.error("Error in pluginsManifests URL parameter's json structure.");
}

return pluginsManifests;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

New method to process plugin manifests

The new processPluginsManifests method has been added to handle the processing of plugin manifests. This method takes a JSON string as input and returns an ArrayList of PluginsManifest objects. Here are some observations:

  1. The method uses Gson for JSON parsing, which is a good choice for JSON handling in Java.
  2. It includes error handling for JSON syntax issues.
  3. The method extracts the URL and optional checksum for each plugin manifest.

While the implementation looks solid, there are a few suggestions for improvement:

  1. Consider adding input validation to check if pluginsManifestsParam is null or empty before processing.
  2. The error logging could be more informative by including the actual error message from the exception.

Consider applying these changes:

 private ArrayList<PluginsManifest> processPluginsManifests(String pluginsManifestsParam) {
     ArrayList<PluginsManifest> pluginsManifests = new ArrayList<PluginsManifest>();
+    if (StringUtils.isEmpty(pluginsManifestsParam)) {
+        return pluginsManifests;
+    }
     JsonElement pluginsManifestsJsonElement = new Gson().fromJson(pluginsManifestsParam, JsonElement.class);
     try {
         if (pluginsManifestsJsonElement != null && pluginsManifestsJsonElement.isJsonArray()) {
             JsonArray pluginsManifestsJson = pluginsManifestsJsonElement.getAsJsonArray();
             for (JsonElement pluginsManifestJson : pluginsManifestsJson) {
                 if (pluginsManifestJson.isJsonObject()) {
                     JsonObject pluginsManifestJsonObj = pluginsManifestJson.getAsJsonObject();
                     if (pluginsManifestJsonObj.has("url")) {
                         String url = pluginsManifestJsonObj.get("url").getAsString();
                         PluginsManifest newPlugin = new PluginsManifest(url);
                         if (pluginsManifestJsonObj.has("checksum")) {
                             newPlugin.setChecksum(pluginsManifestJsonObj.get("checksum").getAsString());
                         }
                         pluginsManifests.add(newPlugin);
                     }
                 }
             }
         }
-    } catch(JsonSyntaxException err){
-        log.error("Error in pluginsManifests URL parameter's json structure.");
+    } catch(JsonSyntaxException err) {
+        log.error("Error in pluginsManifests URL parameter's json structure: {}", err.getMessage());
     }
     return pluginsManifests;
 }

These changes will improve the robustness and error reporting of the method.

📝 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.

Suggested change
private ArrayList<PluginsManifest> processPluginsManifests(String pluginsManifestsParam) {
ArrayList<PluginsManifest> pluginsManifests = new ArrayList<PluginsManifest>();
JsonElement pluginsManifestsJsonElement = new Gson().fromJson(pluginsManifestsParam, JsonElement.class);
try {
if (pluginsManifestsJsonElement != null && pluginsManifestsJsonElement.isJsonArray()) {
JsonArray pluginsManifestsJson = pluginsManifestsJsonElement.getAsJsonArray();
for (JsonElement pluginsManifestJson : pluginsManifestsJson) {
if (pluginsManifestJson.isJsonObject()) {
JsonObject pluginsManifestJsonObj = pluginsManifestJson.getAsJsonObject();
if (pluginsManifestJsonObj.has("url")) {
String url = pluginsManifestJsonObj.get("url").getAsString();
PluginsManifest newPlugin = new PluginsManifest(url);
if (pluginsManifestJsonObj.has("checksum")) {
newPlugin.setChecksum(pluginsManifestJsonObj.get("checksum").getAsString());
}
pluginsManifests.add(newPlugin);
}
}
}
}
} catch(JsonSyntaxException err){
log.error("Error in pluginsManifests URL parameter's json structure.");
}
return pluginsManifests;
}
private ArrayList<PluginsManifest> processPluginsManifests(String pluginsManifestsParam) {
ArrayList<PluginsManifest> pluginsManifests = new ArrayList<PluginsManifest>();
if (StringUtils.isEmpty(pluginsManifestsParam)) {
return pluginsManifests;
}
JsonElement pluginsManifestsJsonElement = new Gson().fromJson(pluginsManifestsParam, JsonElement.class);
try {
if (pluginsManifestsJsonElement != null && pluginsManifestsJsonElement.isJsonArray()) {
JsonArray pluginsManifestsJson = pluginsManifestsJsonElement.getAsJsonArray();
for (JsonElement pluginsManifestJson : pluginsManifestsJson) {
if (pluginsManifestJson.isJsonObject()) {
JsonObject pluginsManifestJsonObj = pluginsManifestJson.getAsJsonObject();
if (pluginsManifestJsonObj.has("url")) {
String url = pluginsManifestJsonObj.get("url").getAsString();
PluginsManifest newPlugin = new PluginsManifest(url);
if (pluginsManifestJsonObj.has("checksum")) {
newPlugin.setChecksum(pluginsManifestJsonObj.get("checksum").getAsString());
}
pluginsManifests.add(newPlugin);
}
}
}
}
} catch(JsonSyntaxException err) {
log.error("Error in pluginsManifests URL parameter's json structure: {}", err.getMessage());
}
return pluginsManifests;
}

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@sonarqubecloud

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

Automated tests Summary

✅ All the CI tests have passed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants