Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PE-95] chore: gif image support for all editors #6219

Merged
merged 1 commit into from
Dec 18, 2024

Conversation

aaryan610
Copy link
Collaborator

@aaryan610 aaryan610 commented Dec 18, 2024

Description

This PR adds gif support for all editors.

Type of Change

  • Feature (non-breaking change which adds functionality)

Summary by CodeRabbit

  • New Features

    • Expanded allowed file types for asset uploads to include "image/gif" and "image/jpg".
    • Introduced constants for accepted file MIME types and extensions to streamline file validation.
  • Bug Fixes

    • Improved validation logic for file uploads, ensuring broader compatibility with image formats.
  • Chores

    • Updated components to utilize new constants for accepted file types, enhancing maintainability.

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

This pull request introduces enhancements to asset management across multiple files, focusing on expanding file type support to include GIF images. The changes span backend API views, frontend configuration, and validation utilities. The modifications allow GIF uploads for user avatars, workspace logos, project covers, and other asset types while maintaining existing validation and handling logic. The updates centralize file type configurations and ensure consistent validation across different components of the application.

Changes

File Change Summary
apiserver/plane/app/views/asset/v2.py Updated UserAssetsV2Endpoint and WorkspaceFileAssetEndpoint to include "image/gif" in allowed file types
apiserver/plane/space/views/asset.py Added "image/jpg" and "image/gif" to EntityAssetEndpoint allowed file types
packages/editor/src/core/constants/config.ts Added ACCEPTED_FILE_MIME_TYPES and ACCEPTED_FILE_EXTENSIONS constants including GIF and JPG
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx Updated file input accept attribute to use dynamic file extensions
packages/editor/src/core/plugins/image/utils/validate-file.ts Modified file validation to use centralized MIME types and updated error message

Possibly related PRs

Suggested labels

🧹chore, ⚙️backend

Suggested reviewers

  • SatishGandham
  • pablohashescobar

Poem

🐰 A rabbit's tale of pixels bright,
GIFs dancing with newfound might,
From backend to frontend, types expand,
File uploads now have a broader brand!
Code hops forward, nimble and free 🎉

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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
Contributor

@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: 2

🧹 Nitpick comments (2)
packages/editor/src/core/plugins/image/utils/validate-file.ts (1)

17-18: Consider making the error message dynamic based on accepted types.

While the validation logic is correct, the error message is hardcoded. Consider deriving it from ACCEPTED_FILE_MIME_TYPES to ensure it stays in sync with supported formats.

Here's a suggested improvement:

  if (!ACCEPTED_FILE_MIME_TYPES.includes(file.type)) {
-   alert("Invalid file type. Please select a JPEG, JPG, PNG, WEBP or GIF file.");
+   const supportedFormats = ACCEPTED_FILE_MIME_TYPES
+     .map(type => type.split('/')[1].toUpperCase())
+     .join(', ');
+   alert(`Invalid file type. Please select a ${supportedFormats} file.`);
    return false;
  }
apiserver/plane/app/views/asset/v2.py (1)

129-135: Consider security implications of GIF file support.

While adding GIF support enhances functionality, please ensure:

  1. Frontend sanitizes GIF files before rendering to prevent XSS attacks
  2. Consider implementing file content validation to detect malicious GIF payloads
  3. Consider adding a maximum file dimension limit for GIF files to prevent DOS attacks

Would you like me to provide implementation examples for these security measures?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e33bae2 and 3b86793.

📒 Files selected for processing (5)
  • apiserver/plane/app/views/asset/v2.py (1 hunks)
  • apiserver/plane/space/views/asset.py (1 hunks)
  • packages/editor/src/core/constants/config.ts (1 hunks)
  • packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (2 hunks)
  • packages/editor/src/core/plugins/image/utils/validate-file.ts (2 hunks)
🔇 Additional comments (3)
packages/editor/src/core/constants/config.ts (1)

9-10: LGTM! Clean implementation of file type configuration.

The centralized configuration of MIME types and dynamic generation of file extensions is well-structured and maintainable. The implementation follows the DRY principle and makes it easy to add or modify supported file types in the future.

packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)

5-6: LGTM! Verify GIF upload functionality end-to-end.

The implementation correctly uses the centralized file extensions configuration for the file input. The component's existing upload handling should work seamlessly with GIF files as it's format-agnostic.

Let's verify the GIF support implementation across the codebase:

Also applies to: 171-171

✅ Verification successful

Let me gather more specific information about the file extensions and MIME types configuration.


Based on the gathered information, I can now provide a final response:

GIF support is properly implemented across the codebase

The implementation correctly supports GIF files:

  • Frontend config defines GIF in ACCEPTED_FILE_MIME_TYPES array as "image/gif" and automatically maps it to file extension
  • Backend settings include "image/gif" in ATTACHMENT_MIME_TYPES list
  • Asset upload endpoint explicitly allows GIF files in the allowed types: "image/gif" is included in the allowed_types list
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify GIF support implementation across the codebase

# Check if GIF support is consistently implemented across relevant files
echo "Checking for GIF support consistency..."

# Search for MIME type definitions and file type validations
rg -i "image/(gif|jpeg|jpg|png|webp)" --type ts --type tsx --type py

# Search for file extension references
rg -i "\.(gif|jpeg|jpg|png|webp)" --type ts --type tsx --type py

# Search for potential file type validation in backend
rg -i "allowed_types|accepted.*types|mime.*types" --type py

Length of output: 1076


Script:

#!/bin/bash
# Check the centralized config for accepted file extensions
echo "Checking ACCEPTED_FILE_EXTENSIONS in config..."
fd "config.ts" --type f --exec cat {}

# Check ATTACHMENT_MIME_TYPES configuration
echo -e "\nChecking ATTACHMENT_MIME_TYPES in settings..."
cat apiserver/plane/settings/common.py

# Check asset upload view implementations
echo -e "\nChecking asset upload implementations..."
cat apiserver/plane/space/views/asset.py

Length of output: 38520

apiserver/plane/app/views/asset/v2.py (1)

129-135: Verify S3Storage compatibility with GIF files.

While the code changes look good, we should verify that the S3Storage implementation properly handles GIF files, especially for generating presigned URLs and handling metadata.

✅ Verification successful

Let me check the complete S3Storage implementation to ensure there's no file type specific handling that might affect GIF files.


Let me try a different approach to check the S3Storage implementation.


S3Storage implementation is compatible with GIF files

The S3Storage implementation is file type agnostic and handles all file types uniformly:

  • Content-Type is passed through as-is in generate_presigned_post
  • No special handling or restrictions for any file types in URL generation
  • File metadata operations are type-independent
  • Both presigned URLs and posts properly preserve the mime type
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check S3Storage implementation for GIF handling

# Search for S3Storage implementation and verify file type handling
rg -A 10 "def generate_presigned" 
rg -A 10 "def generate_presigned_post"

Length of output: 2389


Script:

#!/bin/bash
# Get the complete S3Storage class implementation
ast-grep --pattern 'class S3Storage {
  $$$
}'

# Also check for any GIF-specific handling in the storage module
rg -i "gif" apiserver/plane/settings/storage.py

Length of output: 96


Script:

#!/bin/bash
# Get the complete content of the storage file
cat apiserver/plane/settings/storage.py

# Also check if there are any file type specific handlers in the codebase
rg -i "content[_-]type.*gif" 

Length of output: 5682

Comment on lines +89 to +95
allowed_types = [
"image/jpeg",
"image/png",
"image/webp",
"image/jpg",
"image/gif",
]
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update error message to reflect all allowed image types.

The error message only mentions JPEG and PNG files, but the allowed_types list includes WEBP, JPG, and GIF. This inconsistency could confuse users.

Apply this diff to update the error message:

if type not in allowed_types:
    return Response(
        {
-            "error": "Invalid file type. Only JPEG and PNG files are allowed.",
+            "error": "Invalid file type. Only JPEG, PNG, WEBP, JPG, and GIF files are allowed.",
            "status": False,
        },
        status=status.HTTP_400_BAD_REQUEST,
    )

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +129 to +135
allowed_types = [
"image/jpeg",
"image/png",
"image/webp",
"image/jpg",
"image/gif",
]
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Update error message in UserAssetsV2Endpoint to reflect all allowed image types.

The error message only mentions JPEG and PNG files, but the allowed_types list includes WEBP, JPG, and GIF.

Apply this diff to update the error message:

if type not in allowed_types:
    return Response(
        {
-            "error": "Invalid file type. Only JPEG and PNG files are allowed.",
+            "error": "Invalid file type. Only JPEG, PNG, WEBP, JPG, and GIF files are allowed.",
            "status": False,
        },
        status=status.HTTP_400_BAD_REQUEST,
    )

Committable suggestion skipped: line range outside the PR's diff.

@pushya22 pushya22 merged commit 5773c2b into preview Dec 18, 2024
10 of 13 checks passed
@pushya22 pushya22 deleted the chore/editor-gif-support branch December 18, 2024 07:47
Copy link
Contributor

@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: 1

🔭 Outside diff range comments (2)
apiserver/plane/space/views/asset.py (2)

Line range hint 99-104: Update error message to reflect all allowed file types.

The error message only mentions JPEG and PNG files, but the allowed types now include WEBP, JPG, and GIF formats.

Here's the suggested fix:

-                    "error": "Invalid file type. Only JPEG and PNG files are allowed.",
+                    "error": "Invalid file type. Only JPEG, JPG, PNG, WEBP, and GIF files are allowed.",

Centralization of file type configuration is indeed needed

The search results confirm that there are multiple locations where the same file type validations are duplicated:

  • In apiserver/plane/space/views/asset.py
  • Multiple times in apiserver/plane/app/views/asset/v2.py
  • In packages/editor/src/core/constants/config.ts
  • A more comprehensive list exists in apiserver/plane/settings/common.py

Specific issues:

  • Duplicate allowed_types definitions in multiple asset views
  • The error message mentions only "JPEG and PNG" but the list includes more formats
  • The common settings file has a more complete list that should be used as the source of truth
🔗 Analysis chain

Line range hint 89-104: Consider centralizing file type configurations.

Since this file type validation is likely needed across multiple components (as indicated by the AI summary mentioning similar changes in other files), consider:

  1. Moving the allowed types to a central configuration
  2. Creating a shared validation utility

This would ensure consistency and make future updates easier to maintain.

Let's check for similar file type validations across the codebase:


The previous command failed because the --type python flag wasn't supported. Let's try searching without file type filtering and also look for allowed_types definitions to find similar validations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for file type validations
rg -A 2 "image/(jpeg|png|gif|webp)" --type python

Length of output: 82


Script:

#!/bin/bash
# Search for file type validations using ripgrep
rg -A 2 "image/(jpeg|png|gif|webp|jpg)"

# Also search for allowed_types definitions
rg -A 5 "allowed_types.*=.*\[" 

Length of output: 9663

🧹 Nitpick comments (3)
packages/editor/src/core/constants/config.ts (1)

9-10: LGTM! Consider adding type safety.

The implementation is clean and maintainable. The MIME types are standard and correct, and the extension derivation is elegant.

Consider adding type safety with a const assertion or explicit type:

-export const ACCEPTED_FILE_MIME_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"];
+export const ACCEPTED_FILE_MIME_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif"] as const;
packages/editor/src/core/plugins/image/utils/validate-file.ts (1)

17-18: LGTM! Consider i18n for error messages.

The validation logic correctly uses the centralized MIME types constant and provides clear error messages.

Consider extracting the error message to an i18n system for better internationalization support:

-    alert("Invalid file type. Please select a JPEG, JPG, PNG, WEBP or GIF file.");
+    alert(t('errors.invalid_file_type', { types: 'JPEG, JPG, PNG, WEBP or GIF' }));
packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (1)

171-171: LGTM! Consider memoizing the joined extensions.

The implementation correctly uses the centralized file extensions for the input accept attribute.

Consider memoizing the joined extensions to avoid unnecessary string operations on re-renders:

+const acceptedExtensions = useMemo(() => ACCEPTED_FILE_EXTENSIONS.join(','), []);

// ...
-        accept={ACCEPTED_FILE_EXTENSIONS.join(",")}
+        accept={acceptedExtensions}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e33bae2 and 3b86793.

📒 Files selected for processing (5)
  • apiserver/plane/app/views/asset/v2.py (1 hunks)
  • apiserver/plane/space/views/asset.py (1 hunks)
  • packages/editor/src/core/constants/config.ts (1 hunks)
  • packages/editor/src/core/extensions/custom-image/components/image-uploader.tsx (2 hunks)
  • packages/editor/src/core/plugins/image/utils/validate-file.ts (2 hunks)
🔇 Additional comments (2)
apiserver/plane/app/views/asset/v2.py (1)

129-135: Security measures for file uploads look good

The implementation includes proper security measures:

  • File size validation with configurable limits
  • MIME type validation
  • Secure storage using S3Storage
  • Proper permission checks
apiserver/plane/space/views/asset.py (1)

89-95: LGTM on GIF support addition!

The addition of GIF and JPG formats to the allowed types list aligns with the PR objective of adding GIF support across editors.

Comment on lines +129 to +135
allowed_types = [
"image/jpeg",
"image/png",
"image/webp",
"image/jpg",
"image/gif",
]
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Centralize file type configuration and update error messages

  1. The allowed file types list is duplicated across multiple classes (UserAssetsV2Endpoint, WorkspaceFileAssetEndpoint, ProjectAssetEndpoint).
  2. Error messages are inconsistent with the actual allowed types.

Consider these improvements:

  1. Create a central configuration for allowed file types:
# Add to a new file: plane/utils/constants.py
class FileAssetConfig:
    ALLOWED_MIME_TYPES = [
        "image/jpeg",
        "image/png",
        "image/webp",
        "image/jpg",
        "image/gif",
    ]
    
    @classmethod
    def get_human_readable_types(cls):
        return "JPEG, PNG, WebP, and GIF"
  1. Update the endpoints to use the central configuration:
+from plane.utils.constants import FileAssetConfig

 class UserAssetsV2Endpoint(BaseAPIView):
     def post(self, request):
         # ...
-        allowed_types = [
-            "image/jpeg",
-            "image/png",
-            "image/webp",
-            "image/jpg",
-            "image/gif",
-        ]
-        if type not in allowed_types:
+        if type not in FileAssetConfig.ALLOWED_MIME_TYPES:
             return Response(
                 {
-                    "error": "Invalid file type. Only JPEG and PNG files are allowed.",
+                    "error": f"Invalid file type. Only {FileAssetConfig.get_human_readable_types()} files are allowed.",
                     "status": False,
                 },
                 status=status.HTTP_400_BAD_REQUEST,
             )

Apply similar changes to WorkspaceFileAssetEndpoint and ProjectAssetEndpoint classes.

@aaryan610 aaryan610 changed the title chore: gif image support for all editors [PE-95] chore: gif image support for all editors Dec 18, 2024
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.

2 participants