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

ytdl.js #60

Closed
wants to merge 2 commits into from
Closed

ytdl.js #60

wants to merge 2 commits into from

Conversation

naxordeve
Copy link

@naxordeve naxordeve commented Feb 16, 2025

Updated ytdl (song) download to uses tubidy.cool fast platform to download audios along with it's video 2

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • The "song" command now downloads audio from Tubidy. It searches and retrieves the best matching result based on your input, ensuring a smoother download process.
  • Documentation

    • Updated the command description to reflect the new audio source.

Updated ytdl (song) download to uses tubidy.cool fast platform to download audios along with it's video 2
Copy link

coderabbitai bot commented Feb 16, 2025

Walkthrough

The changes update the "song" command in the assets/plugins/ytdl.js file. The previous implementation that downloaded audio from YouTube via the ytsdl function has been entirely replaced. The new implementation now builds a search URL with the user input to query the Tubidy API, fetches the first result if available, and then downloads the corresponding audio file. The command description is updated accordingly.

Changes

File Change Summary
assets/plugins/ytdl.js Replaced the YouTube-based "song" command implementation with a new Tubidy-based approach. The new code builds a Tubidy search URL, fetches results, retrieves the audio link, and sends the audio back. Updated command description from "Download audio from youtube" to "Download audio from Tubidy."

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant S as Song Command (ytdl.js)
    participant T as Tubidy API

    U->>S: Sends "song <query>" command
    S->>T: Requests search results with query
    alt Results available
        T-->>S: Returns first result (link, title)
        S->>T: Requests audio using the result link
        T-->>S: Returns audio file
        S->>U: Sends download message & audio file
    else No results found
        T-->>S: Returns empty response
        S->>U: Sends no results message
    end
Loading

Poem

Oh, code renegade with a twist so snazzy,
The "song" command's revamped—no way it's lazy!
Tubidy's the new jam, cutting in with flair,
While YouTube gets benched, left gasping for air.
Like Deadpool in a suit, breaking all the molds,
Our code now sings with style and bold!
🎶 Hack on, you marvelous mischief-maker!

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.

assets/plugins/ytdl.js

Oops! Something went wrong! :(

ESLint: 9.5.0

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/node_modules/@eslint/js/src/configs/eslint-all' imported from /eslint.config.mjs
Did you mean to import "@eslint/js/src/configs/eslint-all.js"?
at finalizeResolution (node:internal/modules/esm/resolve:257:11)
at moduleResolve (node:internal/modules/esm/resolve:914:10)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

@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

🔭 Outside diff range comments (1)
assets/plugins/ytdl.js (1)

86-111: ⚠️ Potential issue

Security check! 🔒 (Because even mercenaries need protection!)

Hey there, fellow code ninja! Your security is looking about as tight as my spandex suit - which is to say, not tight enough!

Here are some security concerns that need addressing:

  1. You're not validating the content type before sending it to users
  2. No size limits on downloads (my healing factor can handle infinite size, your server can't!)
  3. No validation of the downloaded URLs

Here's a quick fix for content validation:

+        const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB limit
+        const ALLOWED_MIME_TYPES = ['audio/mpeg', 'audio/mp3'];
+
+        // Add before downloading
+        const response = await fetch(buff);
+        const contentType = response.headers.get('content-type');
+        const contentLength = response.headers.get('content-length');
+
+        if (!ALLOWED_MIME_TYPES.includes(contentType)) {
+            return await message.reply("Nice try! But that's not an audio file! 🕵️‍♂️");
+        }
+
+        if (contentLength > MAX_FILE_SIZE) {
+            return await message.reply("Whoa there! That file is bigger than my ego! Try something smaller! 📦");
+        }
🧹 Nitpick comments (2)
assets/plugins/ytdl.js (2)

11-11: Chimichanga alert! 🌯 We've got an unused import here!

Hey there! Your friendly neighborhood Deadpool noticed you're importing yta and ytv from ytdl but never using them. That's like bringing katanas to a pillow fight - totally unnecessary!

-const { yta, ytv } = require("../../lib/ytdl");

86-111: Time for some architectural wisdom! 🏗️

Those hardcoded URLs are like my face - they need some serious restructuring! Let's make this more maintainable!

Consider moving the API URLs to a configuration file:

// config/api.js
module.exports = {
    TUBIDY_API: {
        BASE_URL: 'https://diegoson-naxordeve.hf.space/tubidy',
        SEARCH_ENDPOINT: '/search',
        DOWNLOAD_ENDPOINT: '/dl'
    }
};

Also, how about we add some rate limiting? We don't want to get banned faster than I get kicked out of the X-Men!

Want me to whip up a complete implementation with rate limiting and proper error handling? Just say the word! 🎯

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c60b49 and c262065.

📒 Files selected for processing (1)
  • assets/plugins/ytdl.js (2 hunks)

Comment on lines 101 to 106
let toBuffu = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${toBuffer.link}`;
let get = await fetch(toBuffu);
let toAudio = await get.json();
if (!toAudio.media || !toAudio.media.length) return;
let buff = toAudio.media.find(m => m.type === 'download')?.link;
if (!buff) return;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Maximum effort needed here! 💪 Your error handling is missing in action!

Just like my healing factor, your code needs some regeneration capabilities! You're making another fetch call without any protection!

Let's wrap this bad boy in a try-catch:

-        let toBuffu = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${toBuffer.link}`;
-        let get = await fetch(toBuffu);
-        let toAudio = await get.json();
-        if (!toAudio.media || !toAudio.media.length) return;
-        let buff = toAudio.media.find(m => m.type === 'download')?.link;
-        if (!buff) return;
+        try {
+            const toBuffu = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${encodeURIComponent(toBuffer.link)}`;
+            const get = await fetch(toBuffu);
+            if (!get.ok) throw new Error(`HTTP error! status: ${get.status}`);
+            const toAudio = await get.json();
+            if (!toAudio.media || !toAudio.media.length) {
+                return await message.reply("No audio found! Did someone steal it? 🤔");
+            }
+            const buff = toAudio.media.find(m => m.type === 'download')?.link;
+            if (!buff) {
+                return await message.reply("Found the audio but can't get the download link! Talk about a tease! 😅");
+            }
+        } catch (error) {
+            return await message.reply(`Holy macaroni! Something went wrong: ${error.message}`);
+        }
📝 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
let toBuffu = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${toBuffer.link}`;
let get = await fetch(toBuffu);
let toAudio = await get.json();
if (!toAudio.media || !toAudio.media.length) return;
let buff = toAudio.media.find(m => m.type === 'download')?.link;
if (!buff) return;
try {
const toBuffu = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${encodeURIComponent(toBuffer.link)}`;
const get = await fetch(toBuffu);
if (!get.ok) throw new Error(`HTTP error! status: ${get.status}`);
const toAudio = await get.json();
if (!toAudio.media || !toAudio.media.length) {
return await message.reply("No audio found! Did someone steal it? 🤔");
}
const buff = toAudio.media.find(m => m.type === 'download')?.link;
if (!buff) {
return await message.reply("Found the audio but can't get the download link! Talk about a tease! 😅");
}
} catch (error) {
return await message.reply(`Holy macaroni! Something went wrong: ${error.message}`);
}

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

♻️ Duplicate comments (1)
assets/plugins/ytdl.js (1)

94-97: ⚠️ Potential issue

Time to level up our URL game! 🎮

We're raw-dogging those URLs without any encoding! That's more dangerous than my usual stunts!

Let's make it safer:

-        const findUrl = `https://diegoson-naxordeve.hf.space/tubidy/search?q=${match}`;
+        const findUrl = `https://diegoson-naxordeve.hf.space/tubidy/search?q=${encodeURIComponent(match)}`;
         const search = await fetch(findUrl);
+        if (!search.ok) throw new Error(`Search failed with status: ${search.status}`);
         const dlink = await search.json();
-        if (!dlink || !dlink.length) return await message.reply("Not_found");
+        if (!dlink || !dlink.length) return await message.reply("No results found! Even I couldn't find this one! 🤷‍♂️");
🧰 Tools
🪛 Biome (1.9.4)

[error] 97-97: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 97-97: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)

🧹 Nitpick comments (2)
assets/plugins/ytdl.js (2)

11-11: Chimichangas! We've got an unused import here! 🌯

Hey sugar bear, looks like we're importing yta and ytv from ytdl but never using them! It's like bringing katanas to a pillow fight - totally unnecessary!

Let's slice this line right out:

-const { yta, ytv } = require("../../lib/ytdl");

94-102: Let's talk about that hardcoded API endpoint! 🎯

Using a hardcoded API endpoint is like putting all your chimichangas in one basket! What happens when the service goes down or changes?

Consider:

  1. Moving the API URL to a config file
  2. Adding request timeouts
  3. Implementing rate limiting
  4. Having fallback services

Want me to help set up a proper configuration structure? Just say the word!

🧰 Tools
🪛 Biome (1.9.4)

[error] 97-97: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 97-97: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 98-98: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 101-101: Shouldn't redeclare 'dlink'. Consider to delete it or rename it.

'dlink' is defined here:

(lint/suspicious/noRedeclare)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c262065 and 66ab5bc.

📒 Files selected for processing (1)
  • assets/plugins/ytdl.js (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
assets/plugins/ytdl.js

[error] 97-97: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 97-97: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 98-98: This variable is used before its declaration.

The variable is declared here:

(lint/correctness/noInvalidUseBeforeDeclaration)


[error] 101-101: Shouldn't redeclare 'dlink'. Consider to delete it or rename it.

'dlink' is defined here:

(lint/suspicious/noRedeclare)

Comment on lines +111 to +114
} catch (error) {
console.error(error);
return await message.reply("oops");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Your error handling is as basic as a vanilla ice cream! 🍦

Come on, we can do better than just "oops"! Let's give users something they can actually work with!

-        console.error(error);
-        return await message.reply("oops");
+        console.error('Tubidy download error:', error);
+        return await message.reply(`Holy macaroni! Something went wrong: ${error.message || 'Unknown error'}`);
📝 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
} catch (error) {
console.error(error);
return await message.reply("oops");
}
} catch (error) {
console.error('Tubidy download error:', error);
return await message.reply(`Holy macaroni! Something went wrong: ${error.message || 'Unknown error'}`);
}

Comment on lines +101 to +106
const dlink = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${toBuffer.link}`;
const teres = await fetch(dlink);
const toAudio = await tores.json();
if (!toAudio.media || !toAudio.media.length) return;
const buff = toAudio.media.find(m => m.type === 'download')?.link;
if (!buff) return await message.reply("not found");
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Maximum effort needed here! Variable naming chaos! 🎭

  1. You're redeclaring dlink faster than I can break the fourth wall!
  2. What's a tores? Did you mean teres? Or was it supposed to be toRes? Even my healing factor can't fix these typos!

Let's clean this up:

-        const dlink = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${toBuffer.link}`;
-        const teres = await fetch(dlink);
-        const toAudio = await tores.json();
+        const downloadUrl = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${encodeURIComponent(toBuffer.link)}`;
+        const response = await fetch(downloadUrl);
+        if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
+        const toAudio = await response.json();
📝 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
const dlink = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${toBuffer.link}`;
const teres = await fetch(dlink);
const toAudio = await tores.json();
if (!toAudio.media || !toAudio.media.length) return;
const buff = toAudio.media.find(m => m.type === 'download')?.link;
if (!buff) return await message.reply("not found");
const downloadUrl = `https://diegoson-naxordeve.hf.space/tubidy/dl?url=${encodeURIComponent(toBuffer.link)}`;
const response = await fetch(downloadUrl);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const toAudio = await response.json();
if (!toAudio.media || !toAudio.media.length) return;
const buff = toAudio.media.find(m => m.type === 'download')?.link;
if (!buff) return await message.reply("not found");
🧰 Tools
🪛 Biome (1.9.4)

[error] 101-101: Shouldn't redeclare 'dlink'. Consider to delete it or rename it.

'dlink' is defined here:

(lint/suspicious/noRedeclare)

@naxordeve naxordeve closed this by deleting the head repository Feb 20, 2025
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