Skip to content

Conversation

@vershwal
Copy link
Member

@vershwal vershwal commented Apr 23, 2025

Ref https://linear.app/ghost/issue/AP-982 https://linear.app/ghost/issue/AP-1084

  • Store the image url on the PostEntity in imageUrl. This is easier to work with for a single image
  • Set the imageUrl on the attachment properties
    -- Tested this will many options and setting it to the attachments using Image obj works. By works I mean image correctly shows up on mastodon.
  • Updated /note API to accept an image URL
    -- Verifing the image url
  • Updated /reply API to accept image
    -- Verifing the image url

@coderabbitai
Copy link

coderabbitai bot commented Apr 23, 2025

## Walkthrough

This change introduces support for optional image attachments in both note creation and reply actions within the application. The `GCPStorageService` is now injected into relevant API handlers to enable verification of image URLs. The request schemas for creating notes and replies are extended to accept an optional `imageUrl` field. When an image URL is provided, the service verifies its validity against the Google Cloud Storage bucket before proceeding. If verification fails, a 400 error response is returned. The `Post` entity and related methods are updated to store and handle the optional image URL. The publishing service and types are also modified to include image attachments in the ActivityPub note payloads when applicable. Comprehensive unit tests are added for both the new verification logic and the updated entity creation methods. Additionally, Cucumber feature tests and step definitions are extended to cover scenarios involving image URLs in notes and replies.

## Possibly related PRs

- TryGhost/ActivityPub#533: Introduces the initial integration of Google Cloud Storage, including a new image upload API and emulator setup; the current PR builds upon this by extending usage of the storage service for image URL verification.
- TryGhost/ActivityPub#472: Adds unit tests for `createNote` focusing on content formatting and error handling; related as it modifies the same method extended here to support image URLs.

## Suggested labels

`princi-vershwal-12.ghost.is`

## Suggested reviewers

- allouis

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 81cc8cb and df353bb.

📒 Files selected for processing (4)
  • src/handlers.ts (6 hunks)
  • src/http/api/note.ts (3 hunks)
  • src/post/post.entity.ts (4 hunks)
  • src/post/post.entity.unit.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/post/post.entity.unit.test.ts
  • src/http/api/note.ts
  • src/handlers.ts
  • src/post/post.entity.ts
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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: 0

🧹 Nitpick comments (1)
src/storage/gcloud-storage/gcp-storage.service.ts (1)

113-143: Good implementation, but consider enhancing emulator validation

The implementation of verifyImageUrl properly handles both emulator and production environments with good error handling. However, in emulator mode, it only checks if the URL matches the expected pattern but doesn't verify if the file actually exists.

Consider enhancing the emulator mode to also verify file existence for consistency with production behavior:

async verifyImageUrl(url: string): Promise<boolean> {
    try {
        // Check if we're using the GCS emulator and verify the URL matches the emulator's base URL pattern
        if (this.emulatorHost) {
            const emulatorBaseUrl = `${this.emulatorHost.replace('fake-gcs', 'localhost')}/storage/v1/b/${this.bucketName}`;
-           return url.startsWith(emulatorBaseUrl);
+           if (!url.startsWith(emulatorBaseUrl)) {
+               return false;
+           }
+           
+           // Extract file path from emulator URL and verify existence
+           const filePath = url.split(`${emulatorBaseUrl}/o/`)[1]?.split('?')[0];
+           if (!filePath) {
+               return false;
+           }
+           const decodedPath = decodeURIComponent(filePath);
+           const [exists] = await this.bucket.file(decodedPath).exists();
+           return exists;
        }

        // Rest of the method remains unchanged
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33422a8 and efc4e1a.

📒 Files selected for processing (9)
  • src/app.ts (2 hunks)
  • src/handlers.ts (6 hunks)
  • src/http/api/note.ts (3 hunks)
  • src/post/post.entity.ts (4 hunks)
  • src/post/post.entity.unit.test.ts (1 hunks)
  • src/publishing/service.ts (2 hunks)
  • src/publishing/types.ts (1 hunks)
  • src/storage/gcloud-storage/gcp-storage.service.ts (1 hunks)
  • src/storage/gcloud-storage/gcp-storage.service.unit.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/app.ts (1)
src/http/api/note.ts (1)
  • handleCreateNote (17-70)
src/storage/gcloud-storage/gcp-storage.service.unit.test.ts (1)
src/storage/gcloud-storage/gcp-storage.service.ts (1)
  • GCPStorageService (14-144)
🪛 GitHub Actions: CICD
src/app.ts

[error] 959-1000: Biome formatting check failed: File content differs from formatting output. Please run the formatter to fix code style issues.

🔇 Additional comments (22)
src/publishing/types.ts (1)

106-109: LGTM!

The addition of the imageUrl property to the Note interface is well-documented and properly typed.

src/post/post.entity.unit.test.ts (1)

312-322: Good test coverage for the new image URL feature

This test effectively verifies that the createNote method correctly handles the new imageUrl parameter.

src/publishing/service.ts (2)

8-8: LGTM!

Importing the necessary Image type for attachments.


146-152: Well-implemented conditional image attachment

The implementation correctly handles attaching an image to the note when an image URL is provided, while maintaining backward compatibility by using undefined when no image is present.

However, additional tests would be beneficial to ensure this functionality works correctly.

Could you verify that there are tests covering the image attachment functionality in the publishing service? Consider adding tests that verify the behavior when both with and without an image URL.

src/app.ts (2)

960-962: Good addition of storage service for image URL verification

The injection of gcpStorageService into the createReplyActionHandler enables verification of image URLs in replies. This matches the PR objective of attaching images to replies.


992-994: Good addition of storage service for note creation

Adding gcpStorageService to handleCreateNote enables image URL verification for notes, fulfilling the PR objective of attaching images to notes.

src/storage/gcloud-storage/gcp-storage.service.unit.test.ts (1)

125-214: Comprehensive test coverage for verifyImageUrl method

These tests thoroughly verify the verifyImageUrl functionality in both emulator and production environments with appropriate test cases for:

  • Valid URLs returning true
  • Invalid URLs (wrong bucket, malformed) returning false
  • Error handling returning false
  • File existence checks in production mode

The separation into distinct test suites for emulator and production modes is well-structured and matches the implementation's conditional logic.

src/post/post.entity.ts (2)

327-331: Good implementation of optional image URL in createNote

The method signature has been updated to accept an optional imageUrl parameter and properly converts it to a URL object when provided. This change maintains backward compatibility while adding the new functionality.

Also applies to: 355-355


369-374: Good implementation of optional image URL in createReply

Similar to createNote, the createReply method has been updated to accept an optional imageUrl parameter and properly converts it to a URL object. This implementation is consistent with the createNote method.

Also applies to: 405-405

src/http/api/note.ts (6)

3-9: Good organization of imports

Imports are properly organized and typed, improving code readability and type safety.


14-14: Proper schema validation for imageUrl

Adding Zod validation for the optional imageUrl field ensures that only valid URLs will be accepted. The use of z.string().url() provides built-in URL validation.


17-22: Function signature updated with new dependency

Adding the storageService parameter maintains the function's purpose while enabling image URL verification functionality.


31-40: Good implementation of image URL verification

This code block:

  1. Checks if an image URL is provided
  2. Verifies the URL using the storage service
  3. Returns a meaningful error response if verification fails

This ensures that only valid image URLs from the configured storage bucket can be attached to notes.


44-44: Post creation updated to include image URL

The Post.createNote call now passes the optional imageUrl parameter, connecting the API layer to the entity layer.


50-57: Publishing updated to include image URL

The publishNote function call now includes the image URL in its payload, ensuring that the image attachment is included in the ActivityPub note object when published to the Fediverse.

src/handlers.ts (7)

7-7: LGTM: Image import added to support image attachments

The Image class imported from @fedify/fedify will be used for attaching images to notes and replies.


22-22: LGTM: Required import for image verification

GCPStorageService type import is necessary for the storage service parameter added to the reply handler.


298-298: LGTM: Schema extension for image support

The ReplyActionSchema is properly extended with an optional imageUrl field that includes URL validation.


305-305: LGTM: Added storage service parameter

The storageService parameter is correctly added to the handler for image URL verification.


321-330: LGTM: Image URL verification logic

The implementation properly verifies the image URL if provided and returns an appropriate error response if invalid.


437-442: LGTM: Updated Post creation with imageUrl

The Post.createReply call is correctly updated to include the imageUrl parameter.


451-457: LGTM: Image attachments in Note creation

The Note object correctly includes image attachments when an imageUrl is provided, using the Image class with the URL.

Copy link
Collaborator

@allouis allouis left a comment

Choose a reason for hiding this comment

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

Few comments on the types

static createNote(
account: Account,
noteContent: string,
imageUrl?: string,
Copy link
Collaborator

Choose a reason for hiding this comment

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

This should be a URL

account: Account,
replyContent: string,
inReplyTo: Post,
imageUrl?: string,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Same here should be a URL!

content: note.content,
summary: null,
published: Temporal.Now.instant(),
attachments: note.imageUrl
Copy link
Collaborator

Choose a reason for hiding this comment

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

Did we test with image and both too? What were the results?

@vershwal vershwal merged commit 95dace3 into main Apr 24, 2025
7 checks passed
@vershwal vershwal deleted the attachImage branch April 24, 2025 08:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants