Skip to content

Conversation

@kren-prog
Copy link
Collaborator

@kren-prog kren-prog commented Jun 4, 2025

Description

This PR gathers the results of workspace exploration, such as:

  • Authenticate as an app
  • Authenticate as a user
  • Generate Token to authenticate as a user
  • Send direct messages
  • Create spaces and list spaces

Fixes #100

Type of change

  • New feature (non-breaking change which adds functionality)

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my code
  • I have commented on my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Introduced multiple scripts and helper classes for managing Google Chat spaces and sending messages, including support for both service account and user authentication.
    • Added functionality to create chat spaces, add members, send messages (including direct messages), and list spaces and their members.
    • Provided tools for generating and storing OAuth tokens for both service accounts and user authentication.
    • Enabled user impersonation and admin directory access for advanced workspace operations.
  • Chores

    • Updated environment variable examples to include placeholders for service account and user OAuth credentials.
    • Added new dependencies to support web server, browser launching, and Google API integrations.

@kren-prog kren-prog requested a review from L-Zuluaga June 4, 2025 19:18
@kren-prog kren-prog self-assigned this Jun 4, 2025
Copy link
Member

@L-Zuluaga L-Zuluaga left a comment

Choose a reason for hiding this comment

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

Hi @kren-prog excellent job!

I’ve left some comments and suggestions. Overall, I think it would be better to use more generic values—ideally, the modules using these utilities should be able to pass in the necessary parameters so the utils remain truly generic. Let me know what you think.

Feel free to reach out if there’s anything we should discuss or clarify.

@kren-prog kren-prog force-pushed the workspace-exploration branch from 7e0f8d2 to 947e2ac Compare June 9, 2025 19:07
@coderabbitai
Copy link

coderabbitai bot commented Jun 9, 2025

Walkthrough

This update introduces a comprehensive set of Ruby scripts and helper classes for exploring and managing Google Chat workspaces. It includes methods for authenticating with both user and service account credentials, managing chat spaces, sending messages, listing spaces and members, and handling direct messages. New dependencies and environment variable placeholders are also added.

Changes

File(s) Change Summary
.env.example Added placeholders for SERVICE_ACCOUNT_CREDENTIALS_JSON and USER_OAUTH_CREDENTIALS_JSON.
Gemfile Added gems: webrick, launchy, google-apis-admin_directory_v1.
src/utils/workspace_exploration/find_space_direct_message.rb New script: Find Google Chat DM spaces with/without impersonation, using service account and directory APIs.
src/utils/workspace_exploration/generate_token.rb New script: Generate OAuth token for user authentication via browser and local server.
src/utils/workspace_exploration/google_chat_space_manager.rb New class: Manage spaces via HTTP using service account impersonation; create spaces, add members, send messages.
src/utils/workspace_exploration/list_spaces.rb New script: List spaces and enumerate human members using service account.
src/utils/workspace_exploration/send_dm_to_user_with_user_auth.rb New script: Send direct messages to users using user OAuth authentication.
src/utils/workspace_exploration/send_message_with_user_auth.rb New script: Send messages to spaces using user OAuth authentication.
src/utils/workspace_exploration/use_space_manager.rb New example: Demonstrates GoogleChatSpaceManager usage for space creation, member addition, and messaging.
src/utils/workspace_helpers/generate_token.rb New script: Generate/store OAuth token using client credentials from environment variable.
src/utils/workspace_helpers/google_chat_explorer.rb New class: Explore spaces/members, find DMs, with service account and impersonation support.
src/utils/workspace_helpers/google_chat_messenger_as_user.rb New class: Send messages/DMs as a user using OAuth credentials.
src/utils/workspace_helpers/google_chat_space_request_manager.rb New class: Manage spaces via HTTP with service account impersonation (similar to above manager).

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Script
    participant GoogleAPI
    participant Browser

    User->>Script: Run token generation script
    Script->>Browser: Open OAuth consent URL
    User->>Browser: Grant permission
    Browser->>Script: Redirect with auth code (localhost server)
    Script->>GoogleAPI: Exchange code for token
    Script->>User: Store and confirm token
Loading
sequenceDiagram
    participant Admin
    participant SpaceManager
    participant GoogleChatAPI

    Admin->>SpaceManager: Create space with display name
    SpaceManager->>GoogleChatAPI: POST /v1/spaces (with impersonation)
    GoogleChatAPI-->>SpaceManager: Return space info
    SpaceManager->>GoogleChatAPI: Add member by email
    GoogleChatAPI-->>SpaceManager: Confirm member added
    SpaceManager->>GoogleChatAPI: Send message to space
    GoogleChatAPI-->>SpaceManager: Confirm message sent
Loading
sequenceDiagram
    participant User
    participant MessengerAsUser
    participant GoogleChatAPI

    User->>MessengerAsUser: Send DM to target email
    MessengerAsUser->>GoogleChatAPI: Find DM space with target
    GoogleChatAPI-->>MessengerAsUser: Return DM space ID
    MessengerAsUser->>GoogleChatAPI: Send message to DM space
    GoogleChatAPI-->>MessengerAsUser: Confirm message sent
Loading

Assessment against linked issues

Objective Addressed Explanation
Compile results of Google Chat App Workspace Exploration (#100)
Include basic methods for using API with user and app authentication (#100)
Provide implementation for managing Workspace via HTTP due to API inconsistencies (#100)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Poem

In the warren of code, new scripts now appear,
For Chat spaces and DMs, the path is made clear.
With tokens and helpers, and managers too,
The workspace explored—so much rabbits can do!
🐇✨
Hop, hop, hooray—Google Chat, lead the way!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 25

♻️ Duplicate comments (7)
src/utils/workspace_exploration/use_space_manager.rb (1)

13-13: ⚠️ Potential issue

Fix path separator for cross-platform compatibility.

The hard-coded file path uses Windows-style backslashes which will not work on Unix-like systems. Use forward slashes or File.join for cross-platform compatibility.

-  service_account_file: 'src\utils\credentials-podnation.json',
+  service_account_file: 'src/utils/credentials-podnation.json',

Or better yet, use environment variables:

-  service_account_file: 'src\utils\credentials-podnation.json',
+  service_account_file: ENV['SERVICE_ACCOUNT_CREDENTIALS_JSON'],
src/utils/workspace_exploration/send_dm_to_user_with_user_auth.rb (1)

15-15: Address the hardcoded credentials path as previously discussed.

This hardcoded path should be replaced with environment variables or secrets management as mentioned in the previous review comment.

src/utils/workspace_exploration/generate_token.rb (1)

21-21: Address the hardcoded credentials path as previously discussed.

This should use environment variables or secrets management instead of a hardcoded path.

src/utils/workspace_exploration/list_spaces.rb (1)

11-11: Use environment variable for service account file path.

As mentioned in previous reviews, the hard-coded credential file path should be replaced with an environment variable or configuration parameter for better security and flexibility.

src/utils/workspace_exploration/find_space_direct_message.rb (3)

17-17: Use environment variables for sensitive configuration.

As noted in previous reviews, the service account credentials should be provided as environment variables or secrets rather than hard-coded file paths for better security.


19-19: Use placeholder values for configuration.

As suggested in previous reviews, use placeholder values like 'IMPERSONATION_EMAIL_HERE' instead of real email addresses to make the script more reusable.


21-21: Use more descriptive placeholder names.

Previous reviews suggested using more descriptive names like DESTINATION_EMAIL, RECIPIENT_EMAIL, or DM_TO with placeholder values.

🧹 Nitpick comments (9)
Gemfile (1)

50-54: Consider adding version constraints for new gems.

While the gem additions are appropriate for the Google Chat functionality, consider specifying version constraints to ensure reproducible builds and prevent potential breaking changes from future gem updates.

-gem 'webrick'
-gem 'launchy'
-gem 'google-apis-admin_directory_v1'
+gem 'webrick', '~> 1.8'
+gem 'launchy', '~> 2.5'
+gem 'google-apis-admin_directory_v1', '~> 0.47'
src/utils/workspace_exploration/use_space_manager.rb (1)

21-21: Make member email configurable.

Hard-coded email addresses reduce the reusability of this example script. Consider making it configurable through environment variables or command-line arguments.

-manager.add_member(space_name: space_name, user_email: 'service@podnation.co')
+manager.add_member(space_name: space_name, user_email: ENV['MEMBER_EMAIL'] || 'service@podnation.co')
src/utils/workspace_exploration/send_message_with_user_auth.rb (1)

34-35: Make space ID and message configurable.

Hard-coded space ID and message text limit the script's reusability. Consider accepting these as command-line arguments or environment variables.

-space = 'spaces/hIfcX8AAAAE'
-text = 'Hello from my bot with user authentication👋'
+space = ARGV[0] || ENV['CHAT_SPACE_ID'] || 'spaces/hIfcX8AAAAE'
+text = ARGV[1] || ENV['MESSAGE_TEXT'] || 'Hello from my bot with user authentication👋'
src/utils/workspace_exploration/send_dm_to_user_with_user_auth.rb (1)

47-47: Fix grammatical error in output message.

-  puts "Message sended to #{to_email} #{space_id}"
+  puts "Message sent to #{to_email} #{space_id}"
src/utils/workspace_helpers/google_chat_space_request_manager.rb (1)

15-15: Consider renaming class to match filename convention.

The class name GoogleChatSpaceManager doesn't follow the typical Ruby convention where google_chat_space_request_manager.rb would contain GoogleChatSpaceRequestManager.

-class GoogleChatSpaceManager
+class GoogleChatSpaceRequestManager
src/utils/workspace_helpers/google_chat_messenger_as_user.rb (2)

16-18: Consider making constants configurable.

The hard-coded constants TOKEN_PATH, USER_ID, and SCOPE limit flexibility. Consider accepting these as constructor parameters or loading from environment variables to improve reusability across different environments.

-  TOKEN_PATH = 'token.yaml'
-  USER_ID = 'default'
-  SCOPE = 'https://www.googleapis.com/auth/chat.messages'
+  DEFAULT_TOKEN_PATH = 'token.yaml'
+  DEFAULT_USER_ID = 'default'
+  DEFAULT_SCOPE = 'https://www.googleapis.com/auth/chat.messages'

-  def initialize(user_oauth_credentials:)
+  def initialize(user_oauth_credentials:, token_path: DEFAULT_TOKEN_PATH, user_id: DEFAULT_USER_ID, scope: DEFAULT_SCOPE)
     @user_oauth_credentials = user_oauth_credentials
+    @token_path = token_path
+    @user_id = user_id
+    @scope = scope

50-51: Use instance variables for configurability.

The authorized_client method uses hard-coded TOKEN_PATH instead of the instance variable pattern suggested earlier.

-    FileUtils.mkdir_p(File.dirname(TOKEN_PATH))
-    token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH)
+    FileUtils.mkdir_p(File.dirname(@token_path))
+    token_store = Google::Auth::Stores::FileTokenStore.new(file: @token_path)
src/utils/workspace_helpers/google_chat_explorer.rb (2)

7-9: Enhance class documentation for better maintainability.

The class comment could be more comprehensive, including usage examples, parameter descriptions, and potential exceptions that may be raised.

Consider expanding the documentation:

-# This class serves as an implementation for managing spaces in Google Chat workspace
-# using Google Chat API with service account credentials and impersonation when is needed
-#
+# GoogleChatExplorer provides comprehensive Google Chat workspace management capabilities.
+#
+# This class handles:
+# - Service account authentication with optional user impersonation
+# - Google Chat API operations (spaces, members, direct messages)
+# - Directory API integration for user lookups
+#
+# @example Basic usage
+#   explorer = GoogleChatExplorer.new(
+#     service_account_credentials: credentials_json,
+#     impersonated_user: 'user@example.com',
+#     impersonated_admin_user: 'admin@example.com'
+#   )
+#   spaces = explorer.list_spaces
+#
+# @raise [ArgumentError] When admin impersonation is required but not provided

21-25: Consider adding parameter validation in the constructor.

Adding validation for required parameters would provide better error messages and fail-fast behavior.

 def initialize(service_account_credentials:, impersonated_user: nil, impersonated_admin_user: nil)
+  raise ArgumentError, 'Service account credentials cannot be nil' if service_account_credentials.nil?
+  raise ArgumentError, 'Service account credentials cannot be empty' if service_account_credentials.strip.empty?
+  
   @service_account_credentials = service_account_credentials
   @impersonated_user = impersonated_user
   @impersonated_admin_user = impersonated_admin_user
 end
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 06791f5 and 947e2ac.

⛔ Files ignored due to path filters (1)
  • Gemfile.lock is excluded by !**/*.lock
📒 Files selected for processing (13)
  • .env.example (1 hunks)
  • Gemfile (1 hunks)
  • src/utils/workspace_exploration/find_space_direct_message.rb (1 hunks)
  • src/utils/workspace_exploration/generate_token.rb (1 hunks)
  • src/utils/workspace_exploration/google_chat_space_manager.rb (1 hunks)
  • src/utils/workspace_exploration/list_spaces.rb (1 hunks)
  • src/utils/workspace_exploration/send_dm_to_user_with_user_auth.rb (1 hunks)
  • src/utils/workspace_exploration/send_message_with_user_auth.rb (1 hunks)
  • src/utils/workspace_exploration/use_space_manager.rb (1 hunks)
  • src/utils/workspace_helpers/generate_token.rb (1 hunks)
  • src/utils/workspace_helpers/google_chat_explorer.rb (1 hunks)
  • src/utils/workspace_helpers/google_chat_messenger_as_user.rb (1 hunks)
  • src/utils/workspace_helpers/google_chat_space_request_manager.rb (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
src/utils/workspace_exploration/use_space_manager.rb (1)
src/utils/workspace_exploration/google_chat_space_manager.rb (3)
  • create_space (29-41)
  • add_member (43-53)
  • send_message (55-67)
src/utils/workspace_helpers/generate_token.rb (3)
src/utils/workspace_helpers/google_chat_space_request_manager.rb (1)
  • freeze (15-93)
src/utils/workspace_helpers/google_chat_explorer.rb (1)
  • freeze (10-109)
src/utils/workspace_helpers/google_chat_messenger_as_user.rb (1)
  • load_client_id (43-47)
src/utils/workspace_exploration/generate_token.rb (2)
src/utils/workspace_exploration/google_chat_space_manager.rb (1)
  • freeze (16-87)
src/utils/workspace_exploration/send_dm_to_user_with_user_auth.rb (1)
  • load_client_id (20-24)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Tests
🔇 Additional comments (6)
.env.example (1)

59-60: LGTM! Environment variables properly added for Google Chat authentication.

The new environment variables SERVICE_ACCOUNT_CREDENTIALS_JSON and USER_OAUTH_CREDENTIALS_JSON are well-named and appropriately placed to support the Google Chat workspace exploration functionality.

src/utils/workspace_exploration/send_message_with_user_auth.rb (2)

14-24: Excellent OAuth implementation with proper error handling.

The OAuth flow is correctly implemented with appropriate token storage and clear error messaging when credentials are missing. The error message guides users to run the authorization script first.


26-32: Clean Google Chat API integration.

The message sending implementation properly uses the Google Chat API with correct service initialization and message construction.

src/utils/workspace_helpers/generate_token.rb (1)

9-10: Approve the environment variable approach.

Using environment variables with dotenv/load is a better security practice compared to hardcoded credential paths in the exploration scripts.

src/utils/workspace_helpers/google_chat_explorer.rb (2)

101-108: LGTM! Clean implementation of member filtering.

The method effectively filters out bot members and provides a clean data structure for human members. The use of safe navigation (&.) and clear mapping logic is well-implemented.


11-19: Well-structured scope definitions.

The constant definitions for API scopes are properly organized and use appropriate Google API scopes for the intended functionality.

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.

Add workspace exploration results

3 participants