Skip to content

Linkedin pdf support #755

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

Open
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

polylina
Copy link

@polylina polylina commented May 26, 2025

What kind of change does this PR introduce?

This PR adds support for uploading PDFs in Linkedin posts.

Why was this change needed?

The rationale can be found in this closed issue: #593. It allows posting whole presentations as parts of marketing stories.

Other information:

The change was not discussed, it was only requested by the company I work for. There are no plans on expanding it, as the client is happy with the result, but they thought that it would be a good idea to have this change in the official repository.

Checklist:

Put a "X" in the boxes below to indicate you have followed the checklist;

  • I have read the CONTRIBUTING guide.
  • I checked that there were not similar issues or PRs already open for this.
  • This PR fixes just ONE issue (do not include multiple issues or types of change in the same PR) For example, don't try and fix a UI issue and include new dependencies in the same PR.

Summary by CodeRabbit

  • New Features

    • Added support for uploading PDF files alongside images and videos.
    • PDFs can now be previewed with dynamically generated thumbnail images.
    • PDF files display a PDF icon and generate thumbnail previews in media galleries and previews.
  • Bug Fixes

    • Improved file validation to support PDF uploads with appropriate size limits.
  • Chores

    • Added the pdfjs-dist library as a dependency for PDF thumbnail generation.
  • Style

    • Enhanced media components to consistently display PDF files with icons and thumbnails.

Copy link

vercel bot commented May 26, 2025

@polylina is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented May 26, 2025

Walkthrough

The changes introduce support for PDF files across the frontend and backend. PDF uploads are now allowed, PDF thumbnails are generated and displayed in the UI, and backend validation and upload logic are updated to handle PDFs. A new utility for generating PDF thumbnails is added, and the pdfjs-dist library is included as a dependency.

Changes

File(s) Change Summary
apps/frontend/next.config.js Added swcMinify: false to Next.js config.
apps/frontend/src/components/media/media.component.tsx Enabled PDF uploads, PDF icon rendering, and automatic PDF thumbnail generation in media components.
libraries/helpers/src/utils/pdf-thumbnails.ts Added new utility function createPDFThumbnails for generating PDF page thumbnails using pdfjs-dist.
libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts Refactored upload/post logic to support PDFs, including dynamic endpoint selection and content-type handling.
libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts Added name property to MediaContent type and fixed syntax in AuthTokenDetails.
libraries/nestjs-libraries/src/upload/custom.upload.validation.ts Allowed PDF files in upload validation and set max size to 10MB for PDFs.
libraries/react-shared-libraries/src/helpers/video.or.image.tsx Enhanced VideoOrImage component to handle PDFs and generate thumbnails client-side.
package.json Added pdfjs-dist dependency.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant PDFJS

    User->>Frontend: Uploads PDF file
    Frontend->>Backend: Sends PDF file
    Backend->>Backend: Validates file (accepts PDF, max 10MB)
    Backend-->>Frontend: Stores and returns media info
    Frontend->>Frontend: Updates media list
    Frontend->>PDFJS: Calls createPDFThumbnails()
    PDFJS-->>Frontend: Generates thumbnail for PDF
    Frontend-->>User: Displays PDF icon/thumbnail in media list
Loading

Poem

In the warren, PDFs now hop in,
With thumbnails sprouting, let previews begin!
Images, videos, and now docs too,
Rabbits code onward, with something new.
Thanks to pdfjs, our burrow’s complete,
All media together, a digital treat! 🐇📄✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/frontend/next.config.js

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:163:49)

apps/frontend/src/components/media/media.component.tsx

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:163:49)

libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts

Oops! Something went wrong! :(

ESLint: 8.57.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@eslint/eslintrc' imported from /eslint.config.mjs
at Object.getPackageJSONURL (node:internal/modules/package_json_reader:255:9)
at packageResolve (node:internal/modules/esm/resolve:767:81)
at moduleResolve (node:internal/modules/esm/resolve:853:18)
at defaultResolve (node:internal/modules/esm/resolve:983:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:799:12)
at #cachedDefaultResolve (node:internal/modules/esm/loader:723:25)
at ModuleLoader.resolve (node:internal/modules/esm/loader:706:38)
at ModuleLoader.getModuleJobForImport (node:internal/modules/esm/loader:307:38)
at #link (node:internal/modules/esm/module_job:163:49)

  • 4 others
✨ 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.
    • 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: 7

🧹 Nitpick comments (6)
libraries/helpers/src/utils/pdf-thumbnails.ts (4)

15-15: Use a more specific type instead of any for the worker.

Consider using the proper type from pdfjs-dist for better type safety.

-  let worker: any = null;
+  let worker: pdfjsLib.PDFWorker | null = null;

27-29: Remove redundant pdfjsLib check.

The pdfjsLib check on line 27 is redundant since it's guaranteed to exist after the dynamic import on line 10.

-  if (!pdfjsLib) {
-    throw Error('pdf.js failed to load. Check data-pdfjs-src attribute.');
-  }

31-34: Improve type safety for the forEach callback parameter.

Replace the inline type annotation with a proper type definition.

-  nodesArray.forEach(function (element: {
-    getAttribute: (arg0: string) => any;
-    src: string;
-  }) {
+  nodesArray.forEach(function (element: HTMLImageElement) {

9-91: Consider adding progress tracking and error callbacks.

The function processes all PDFs asynchronously without providing feedback on progress or completion. Consider:

  1. Returning a Promise that resolves when all thumbnails are generated
  2. Adding optional callbacks for progress and error handling
  3. Implementing a queue system for better performance with many PDFs

Would you like me to provide an enhanced version with better error handling and progress tracking?

apps/frontend/src/components/media/media.component.tsx (1)

602-608: Add alt attribute to PDF preview image.

The img element is missing the required alt attribute for accessibility.

                       <img
                         className="w-full h-full object-cover"
                         data-pdf-thumbnail-file={mediaDirectory.set(
                           media?.path
                         )}
                         src="/icons/pdf.svg"
+                        alt="PDF thumbnail"
                       />
libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (1)

251-256: Consider using consistent Content-Type headers.

While the current implementation works, consider using specific MIME types for all file types for consistency:

  • Videos: video/mp4 instead of application/octet-stream
  • Images: Add appropriate MIME type (e.g., image/jpeg)
          ...(fileName.indexOf('mp4') > -1
-            ? { 'Content-Type': 'application/octet-stream' }
+            ? { 'Content-Type': 'video/mp4' }
            : fileName.indexOf('pdf') > -1
            ? { 'Content-Type': 'application/pdf' }
-            : {}),
+            : { 'Content-Type': lookup(fileName) || 'image/jpeg' }),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1e1834d and 79d41a3.

⛔ Files ignored due to path filters (2)
  • apps/frontend/public/icons/pdf.svg is excluded by !**/*.svg
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • apps/frontend/next.config.js (1 hunks)
  • apps/frontend/src/components/media/media.component.tsx (8 hunks)
  • libraries/helpers/src/utils/pdf-thumbnails.ts (1 hunks)
  • libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (8 hunks)
  • libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts (2 hunks)
  • libraries/nestjs-libraries/src/upload/custom.upload.validation.ts (2 hunks)
  • libraries/react-shared-libraries/src/helpers/video.or.image.tsx (2 hunks)
  • package.json (1 hunks)
🔇 Additional comments (11)
package.json (1)

163-163: LGTM!

The addition of pdfjs-dist dependency is appropriate for implementing PDF thumbnail generation functionality.

apps/frontend/next.config.js (1)

43-43: Verify if disabling SWC minification is necessary.

Disabling minification could increase bundle sizes and impact performance. Was this change necessary to resolve specific compatibility issues with pdfjs-dist or other libraries?

Consider re-enabling minification if the issues have been resolved or exploring alternative solutions like configuring specific exclusions.

libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts (2)

68-68: Good syntax fix!

Adding the semicolon improves code consistency.


106-106:

❓ Verification inconclusive

Verify if the name property should be optional.

The name property is added as a required field. Please verify that all existing code that creates MediaContent objects has been updated to include this property, or consider making it optional (name?: string;) for backward compatibility.

Run the following script to check for MediaContent usage:


🏁 Script executed:

#!/bin/bash
# Description: Search for MediaContent usage to verify if the name property should be optional

# Search for MediaContent object creation patterns
rg -A 5 "MediaContent" --type ts --type tsx | grep -E "(type:|url:|path:)" -A 3

Length of output: 107


🏁 Script executed:

#!/bin/bash
# Search for all references to the MediaContent interface in TypeScript files
rg -n "MediaContent" --glob "*.ts" --glob "*.tsx"

Length of output: 655


🏁 Script executed:

#!/bin/bash
# Display createSingleMediaContent implementation and its callers to check if `name` is populated

TARGET="libraries/nestjs-libraries/src/integrations/social/threads.provider.ts"

echo "=== createSingleMediaContent implementation ==="
rg -n "createSingleMediaContent" -B5 -A20 "$TARGET"

echo
echo "=== Call site at line ~191 ==="
sed -n '180,220p' "$TARGET"

echo
echo "=== Call site at line ~297 ==="
sed -n '280,330p' "$TARGET"

Length of output: 5352


🏁 Script executed:

#!/bin/bash
# Display the MediaContent type definition and surrounding context
FILE="libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts"
sed -n '80,140p' "$FILE"

Length of output: 1532


🏁 Script executed:

#!/bin/bash
# Search for classes implementing the SocialProvider interface
rg -n "implements SocialProvider" --glob "*.ts"

Length of output: 3020


Validate MediaContent.name Usage for Backward Compatibility

I didn’t find any internal instantiations of MediaContent in this library—both createSingleMediaContent and createCarouselContent only consume the url field. Since MediaContent is now defined as:

export type MediaContent = {
  type: 'image' | 'video';
  url: string;
  path: string;
  name: string;      // ← newly required
};

please confirm one of the following:

  • All external callers constructing PostDetails.media: MediaContent[] (in application code or other libraries) have been updated to supply the name property.
  • Or, if you need to preserve backward compatibility, make name optional:
    - name: string;
    + name?: string;

Locations to review:
libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts (MediaContent definition)
• All consumer code that builds PostDetails.media arrays.

libraries/react-shared-libraries/src/helpers/video.or.image.tsx (1)

32-43: PDF rendering implementation looks good!

The implementation correctly sets up the PDF element with appropriate data attributes for thumbnail generation and uses a PDF icon as a placeholder.

libraries/nestjs-libraries/src/upload/custom.upload.validation.ts (1)

24-27: Well-implemented PDF validation logic!

The changes correctly add PDF support with appropriate MIME type checking and a reasonable 10MB file size limit. The implementation follows the existing pattern and maintains consistency.

Also applies to: 39-42

apps/frontend/src/components/media/media.component.tsx (1)

351-351: Correct implementation of PDF file type support!

The addition of 'application/pdf' to the allowed file types is properly implemented.

Also applies to: 378-378

libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts (4)

202-207: LGTM! Clean implementation of dynamic API type determination.

The logic correctly maps file extensions to LinkedIn API types (videos, documents, images).


341-352: LGTM! Correct handling of PDF files.

The code correctly treats PDFs like videos by using raw buffers instead of image processing with sharp, which wouldn't work for PDF files.


263-284:

✅ Verification successful

Verify if document uploads require finalization.

The finalization logic only runs for videos (line 263), but the URL was updated to support dynamic apiType. Documents/PDFs won't go through this finalization step. Please verify if LinkedIn's API requires finalization for document uploads.


🌐 Web query:

Does LinkedIn API require finalization step for document uploads similar to video uploads?

💡 Result:

Based on the search results, LinkedIn API handles document uploads differently than video uploads. With video uploads, there is a clear finalization step required, while document uploads follow a simpler two-step process.

For document uploads, the process involves:

  1. Initializing the upload by using the initializeUpload action, which registers the upload and provides an upload URL[1].
  2. Uploading the document directly to the provided URL[1].

There is no explicit finalization step mentioned for document uploads in the documentation. Once you upload the document to the provided URL, you receive a 201 status code response indicating success[1].

In contrast, video uploads require a more complex process:

  1. Initializing the upload to register the video and get an upload URL[4][7].
  2. Uploading the video content (which may involve splitting large files into 4MB chunks for files over 200MB)[4][7].
  3. Explicitly finalizing the upload with a separate API call. This step is mandatory for videos, requiring a POST request to the finalizeUpload action with details like the video URN and uploaded part IDs[4].

When creating posts with documents, you simply need to reference the Document URN (obtained after uploading) in your post creation request[2]. This is similar to how images and videos are referenced, but without the additional finalization step that videos require.

This difference likely exists because videos are more complex media types that may need additional processing after upload, such as transcoding or validation, before they can be used on the platform.

Citations:


Document uploads don’t require a finalize step

Verified via LinkedIn’s docs:

  • Documents use a two-step flow (initializeUpload → direct PUT to URL) and return 201 on success.
  • There is no finalizeUpload call for documents.
  • Only video uploads mandate a separate finalizeUpload POST.

The existing conditional block (lines 263–284) correctly applies finalization only to videos. No changes needed for document handling.


354-356:

✅ Verification successful

Ensure the media object includes the name property.

The code now expects m.name to exist on media objects. While the AI summary mentions interface updates, please verify that all media objects passed to this method include the name property to prevent potential runtime errors.

Also applies to: 398-399


🏁 Script executed:

#!/bin/bash
# Description: Verify that the media interface includes the name property and check its usage

# Search for the media interface definition
ast-grep --pattern 'interface $_ {
  $$$
  media?: $_
  $$$
}'

# Search for PostDetails interface that might contain media definition
rg -A 10 "interface PostDetails"

# Check where media objects are created/used
rg -A 5 "\.media\?" 

Length of output: 16704


🏁 Script executed:

#!/bin/bash
# Inspect LinkedIn provider file for media type and usage of m.name

# Show file header to see imports and type definitions
head -n 50 libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts

# Show the section around the media processing logic (lines 300–430)
sed -n '300,430p' libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts

# Find any local type or interface declarations in this file
rg -nE 'export (interface|type)' libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts

# Search for postDetails usage to see where media items originate
rg -n 'postDetails' -n libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts

Length of output: 5889


🏁 Script executed:

#!/bin/bash
# Locate the social integrations interface file
find libraries/nestjs-libraries/src/integrations/social -type f -name "social.integrations.interface.ts"

# Display PostDetails interface and its media property
sed -n '1,200p' libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts | sed -n '1,200p'

Length of output: 3544


Confirmed: MediaContent defines name

The MediaContent type in social.integrations.interface.ts already includes a required name: string field. No further action is needed.

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.

1 participant