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

Lambda to allow gif types #1143

Merged

Conversation

NiallJoeMaher
Copy link
Contributor

@NiallJoeMaher NiallJoeMaher commented Oct 17, 2024

✨ Codu Pull Request 💻

Fixs #998

Pull Request details

  • Add a conditional check for gifs to ensure they aren't converted to webp
  • General cleanup of avatar resize lambda

Any Breaking changes

  • None

Also some general lambda cleanup
@NiallJoeMaher NiallJoeMaher requested a review from a team as a code owner October 17, 2024 19:39
Copy link

vercel bot commented Oct 17, 2024

@NiallJoeMaher is attempting to deploy a commit to the Codú Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 17, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request includes modifications to two AWS Lambda functions, avatarResize/index.js and uploadResize/index.js, that utilize the Sharp library for image processing and interact with S3. Key changes involve variable renaming for clarity, adjustments to image resizing logic, enhancements for handling GIF formats, and updates to metadata management and file naming conventions.

Changes

File Path Change Summary
cdk/lambdas/avatarResize/index.js - Removed console logs
- Renamed metadata to s3Metadata
- Updated resizing condition
- Simplified Sharp instantiation
- Updated metadata for PutObjectCommand
cdk/lambdas/uploadResize/index.js - Added check for GIF format
- Updated resizing logic for GIFs and other formats
- Adjusted naming conventions for resized images
- Set content type based on image format

Possibly related PRs

  • Add lambda function for image resizing #946: The changes in this PR involve modifications to the same avatarResize/index.js file, specifically related to image processing and S3 interactions, which directly connects to the updates made in the main PR.

🐰 In the meadow where images play,
A resize dance, hip-hip-hooray!
With GIFs and formats all in line,
S3 smiles, everything's fine!
Sharp and swift, the changes gleam,
A rabbit's joy, a coder's dream! 🌟


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 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.

@NiallJoeMaher NiallJoeMaher changed the title Update to allow gif types Lambda to allow gif types Oct 17, 2024
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: 5

🧹 Outside diff range and nitpick comments (1)
cdk/lambdas/avatarResize/index.js (1)

Line range hint 1-69: Missing implementation for GIF handling

While the code changes improve clarity and consistency, the main objective of the PR to "implement a conditional check that prevents GIF files from being converted to the WebP format" is not addressed in this file. Consider adding logic to skip processing for GIF files.

Here's a suggested implementation to handle GIF files:

 const imageBuffer = Buffer.concat(await stream.toArray());

+ // Check if the file is a GIF
+ if (contentType === 'image/gif') {
+   console.log('GIF file detected. Skipping resize operation.');
+   return {
+     statusCode: 200,
+     body: JSON.stringify({ message: "GIF file. Skipping resize." }),
+   };
+ }

 // Resize the image
 const resizedImageBuffer = await sharp(imageBuffer)
   .resize({ width: 220, height: 220, fit: "cover" })
   .toBuffer();

This change will prevent GIF files from being resized, addressing the PR's main objective. Would you like me to implement this change or create a GitHub issue to track this task?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a30156b and 546f976.

📒 Files selected for processing (2)
  • cdk/lambdas/avatarResize/index.js (3 hunks)
  • cdk/lambdas/uploadResize/index.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (5)
cdk/lambdas/avatarResize/index.js (4)

22-22: Improved variable naming for clarity

The change from metadata to s3Metadata enhances code readability by explicitly indicating the source of the metadata. This aligns well with the PR's objective of general cleanup and improved code quality.


25-25: Consistent use of renamed variable

The condition has been updated to use s3Metadata, maintaining consistency with the earlier variable renaming. This change preserves the existing logic while improving code clarity.


40-40: Code structure and simplification improvements

  1. The added blank line (line 40) enhances readability by clearly separating logical sections of the code.
  2. The simplification of the Sharp object creation (line 46) makes the code more concise without changing its functionality.

Both changes contribute to the overall code cleanup objective of the PR.

Also applies to: 46-48


56-56: Consistent metadata handling

The use of s3Metadata in the PutObjectCommand ensures consistency with the earlier variable renaming. This change maintains the existing functionality of preserving all original metadata and adding the resized flag, while improving overall code consistency.

cdk/lambdas/uploadResize/index.js (1)

65-66: ⚠️ Potential issue

Ensure proper handling of animated GIFs during resizing.

The sharp library does not automatically handle animated GIFs correctly. By default, when processing GIFs, sharp only processes the first frame, which means animated GIFs will lose their animation after resizing. To preserve the animation across all frames, you need to specify the animated option in your sharp operations.

Consider modifying your code to handle animated GIFs properly:

-const imageMetadata = await sharp(imageRaw).metadata();
+const imageMetadata = await sharp(imageRaw, { animated: true }).metadata();
 const isGif = imageMetadata.format === "gif";

And update the resizeImage function:

 const resizeImage = async (buffer, size) => {
-  const resizedImage = sharp(buffer).resize({
+  const resizedImage = sharp(buffer, { animated: isGif }).resize({
     width: size.maxWidth,
     height: size.maxHeight,
     fit: "inside",
     withoutEnlargement: false,
   });

   if (isGif) {
-    return resizedImage.gif().toBuffer();
+    return resizedImage
+      .gif({ reoptimise: false })
+      .toBuffer();
   } else {
     return resizedImage.webp({ quality: 80 }).toBuffer();
   }
 };

This ensures that all frames of an animated GIF are processed and the animation is preserved after resizing.

: key;

await s3.send(
new PutObjectCommand({
Bucket: bucket,
Key: resizedKey,
Body: resizedImage,
ContentType: isGif ? "image/gif" : "image/webp",
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

Set appropriate Content-Encoding header for WebP images.

When serving WebP images, it's beneficial to include the Content-Encoding header to ensure proper handling by clients and proxies that support WebP compression.

Modify the PutObjectCommand parameters:

 await s3.send(
   new PutObjectCommand({
     Bucket: bucket,
     Key: resizedKey,
     Body: resizedImage,
     ContentType: isGif ? "image/gif" : "image/webp",
+    ContentEncoding: isGif ? undefined : "webp",
   }),
 );

This addition helps improve compatibility and performance with clients that support WebP.

📝 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
ContentType: isGif ? "image/gif" : "image/webp",
ContentType: isGif ? "image/gif" : "image/webp",
ContentEncoding: isGif ? undefined : "webp",

🛠️ Refactor suggestion

Set the correct Cache-Control header for optimized content delivery.

Setting appropriate cache headers can improve the performance of your application by enabling clients and intermediaries to cache the resized images. This reduces load on your server and decreases image load times for users.

Add the CacheControl parameter to your PutObjectCommand:

 await s3.send(
   new PutObjectCommand({
     Bucket: bucket,
     Key: resizedKey,
     Body: resizedImage,
     ContentType: isGif ? "image/gif" : "image/webp",
+    CacheControl: "max-age=31536000, public",
   }),
 );

This sets the cache to expire after one year (31536000 seconds), which is appropriate for versioned files that won't change.

📝 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
ContentType: isGif ? "image/gif" : "image/webp",
ContentType: isGif ? "image/gif" : "image/webp",
CacheControl: "max-age=31536000, public",

cdk/lambdas/uploadResize/index.js Outdated Show resolved Hide resolved
Comment on lines +89 to +92
? key.replace(
/(\.[\w\d_-]+)$/i,
`_${size.suffix}${isGif ? ".gif" : ".webp"}`,
)
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

⚠️ Potential issue

Use the Node.js path module for reliable file extension handling.

The regular expression used to replace the file extension may not handle all possible file names correctly, such as those without an extension or with multiple dots in their names. Using the built-in path module provides a more robust solution for handling file paths and extensions.

Modify your code to use the path module:

+const path = require("path");
...
 const resizedKey = size.suffix
   ? key.replace(
-      /(\.[\w\d_-]+)$/i,
-      `_${size.suffix}${isGif ? ".gif" : ".webp"}`,
+      path.extname(key),
+      `_${size.suffix}${isGif ? ".gif" : ".webp"}`
     )
   : key;

This change ensures that the file extension is accurately identified and replaced, regardless of the file name format.

Committable suggestion was skipped due to low confidence.

Comment on lines 77 to 81
if (isGif) {
return resizedImage.gif().toBuffer();
} else {
return resizedImage.webp({ quality: 80 }).toBuffer();
}
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

Optimize image processing by reusing the resizedImage instance.

Instead of calling .toBuffer() directly after formatting, you can chain the output format method and call .toBuffer() once. However, since resizedImage is already an instance returned by sharp(buffer).resize(), you can streamline the code.

Simplify the return statements:

 if (isGif) {
-  return resizedImage
-    .gif({ reoptimise: false })
-    .toBuffer();
+  resizedImage.gif({ reoptimise: false });
 } else {
   return resizedImage.webp({ quality: 80 }).toBuffer();
 }
+return resizedImage.toBuffer();

Alternatively, you can write:

+const formatOptions = isGif ? { reoptimise: false } : { quality: 80 };
+const formatMethod = isGif ? 'gif' : 'webp';
+resizedImage[formatMethod](formatOptions);
+return resizedImage.toBuffer();

This approach reduces code duplication and makes the code more maintainable.

Committable suggestion was skipped due to low confidence.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@NiallJoeMaher NiallJoeMaher merged commit 556ae96 into codu-code:develop Oct 17, 2024
2 of 4 checks passed
@NiallJoeMaher NiallJoeMaher deleted the bugfix/fix-gifs-in-resize-lambda branch October 17, 2024 19:45
@JohnAllenTech
Copy link
Contributor

Nice @NiallJoeMaher

Does this mean we can have gifs for avatars now?

@NiallJoeMaher
Copy link
Contributor Author

Nice @NiallJoeMaher

Does this mean we can have gifs for avatars now?

I didn't enable it on this one it was for articles and discussions. But... We can get that working easily with the same logic 😂

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.

2 participants