@wizardwarlocks/tubex 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +200 -2
- package/bin/tubex.js +8 -0
- package/package.json +50 -4
- package/src/auth.js +382 -0
- package/src/cli.js +112 -0
- package/src/commands/auth.js +80 -0
- package/src/commands/download.js +101 -0
- package/src/commands/playlists.js +87 -0
- package/src/commands/search.js +50 -0
- package/src/downloader.js +254 -0
- package/src/ui.js +12 -0
- package/src/youtube.js +238 -0
package/src/cli.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { Command, InvalidArgumentError } from "commander";
|
|
2
|
+
import { loadEnvironment } from "./auth.js";
|
|
3
|
+
import { searchVideos } from "./commands/search.js";
|
|
4
|
+
import {
|
|
5
|
+
loginCommand,
|
|
6
|
+
logoutCommand,
|
|
7
|
+
statusCommand,
|
|
8
|
+
} from "./commands/auth.js";
|
|
9
|
+
import {
|
|
10
|
+
listPlaylistsCommand,
|
|
11
|
+
viewPlaylistCommand,
|
|
12
|
+
} from "./commands/playlists.js";
|
|
13
|
+
import { downloadCommand } from "./commands/download.js";
|
|
14
|
+
|
|
15
|
+
const program = new Command();
|
|
16
|
+
|
|
17
|
+
export function run() {
|
|
18
|
+
loadEnvironment();
|
|
19
|
+
|
|
20
|
+
program
|
|
21
|
+
.name("tubex")
|
|
22
|
+
.description("Your YouTube workflow, from the terminal.")
|
|
23
|
+
.version("0.1.0");
|
|
24
|
+
|
|
25
|
+
program
|
|
26
|
+
.command("search <query>")
|
|
27
|
+
.description("Search for videos on YouTube")
|
|
28
|
+
.option(
|
|
29
|
+
"-l, --limit <number>",
|
|
30
|
+
"Number of results to return (1-50)",
|
|
31
|
+
(value) => {
|
|
32
|
+
const parsed = Number(value);
|
|
33
|
+
|
|
34
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 50) {
|
|
35
|
+
throw new InvalidArgumentError(
|
|
36
|
+
"Limit must be an integer between 1 and 50.",
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return parsed;
|
|
41
|
+
},
|
|
42
|
+
10,
|
|
43
|
+
)
|
|
44
|
+
.action(async (query, options) => {
|
|
45
|
+
await searchVideos(query, options);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const auth = program
|
|
49
|
+
.command("auth")
|
|
50
|
+
.description("Manage Google account authentication");
|
|
51
|
+
|
|
52
|
+
auth
|
|
53
|
+
.command("login")
|
|
54
|
+
.description("Authenticate with your Google account")
|
|
55
|
+
.action(async () => {
|
|
56
|
+
await loginCommand();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
auth
|
|
60
|
+
.command("logout")
|
|
61
|
+
.description("Remove stored authentication tokens")
|
|
62
|
+
.action(async () => {
|
|
63
|
+
await logoutCommand();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
auth
|
|
67
|
+
.command("status")
|
|
68
|
+
.description("Display current authentication status")
|
|
69
|
+
.action(async () => {
|
|
70
|
+
await statusCommand();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
program
|
|
74
|
+
.command("playlists")
|
|
75
|
+
.description("List your YouTube playlists")
|
|
76
|
+
.action(async () => {
|
|
77
|
+
await listPlaylistsCommand();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
program
|
|
81
|
+
.command("playlist <playlist-id>")
|
|
82
|
+
.description("View videos inside a playlist")
|
|
83
|
+
.action(async (playlistId) => {
|
|
84
|
+
await viewPlaylistCommand(playlistId);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
program
|
|
88
|
+
.command("download <url>")
|
|
89
|
+
.description("Download a YouTube video")
|
|
90
|
+
.option(
|
|
91
|
+
"-q, --quality <quality>",
|
|
92
|
+
"Video quality (360, 480, 720, 1080, 1440, 2160, best)",
|
|
93
|
+
)
|
|
94
|
+
.option(
|
|
95
|
+
"-f, --format <format>",
|
|
96
|
+
"Video container format (mp4, mkv, webm)",
|
|
97
|
+
)
|
|
98
|
+
.option(
|
|
99
|
+
"-o, --output <path>",
|
|
100
|
+
"Output directory for downloaded files",
|
|
101
|
+
"./downloads",
|
|
102
|
+
)
|
|
103
|
+
.option(
|
|
104
|
+
"-a, --audio-only",
|
|
105
|
+
"Extract and download audio only (mp3)",
|
|
106
|
+
)
|
|
107
|
+
.action(async (url, options) => {
|
|
108
|
+
await downloadCommand(url, options);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
return program.parseAsync();
|
|
112
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { loginWithGoogle, clearTokens, getAuthStatus } from "../auth.js";
|
|
2
|
+
import { colors } from "../ui.js";
|
|
3
|
+
|
|
4
|
+
export async function loginCommand() {
|
|
5
|
+
try {
|
|
6
|
+
await loginWithGoogle();
|
|
7
|
+
console.log(
|
|
8
|
+
colors.green(
|
|
9
|
+
"\nAuthentication successful! Connected Google account to Tubex.",
|
|
10
|
+
),
|
|
11
|
+
);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
if (error.code === "MISSING_OAUTH_CREDENTIALS") {
|
|
14
|
+
console.error(
|
|
15
|
+
`${colors.red("Error:")} Google OAuth credentials are not configured.\n`,
|
|
16
|
+
);
|
|
17
|
+
console.error(colors.yellow("To configure OAuth credentials:"));
|
|
18
|
+
console.error(
|
|
19
|
+
" 1. Go to Google Cloud Console (https://console.cloud.google.com/)",
|
|
20
|
+
);
|
|
21
|
+
console.error(
|
|
22
|
+
' 2. Create an OAuth 2.0 Client ID with application type "Desktop app"',
|
|
23
|
+
);
|
|
24
|
+
console.error(
|
|
25
|
+
" 3. Add credentials to ~/.config/tubex/.env (global) or local .env:",
|
|
26
|
+
);
|
|
27
|
+
console.error(
|
|
28
|
+
` ${colors.cyan("GOOGLE_CLIENT_ID=your_client_id_here")}`,
|
|
29
|
+
);
|
|
30
|
+
console.error(
|
|
31
|
+
` ${colors.cyan("GOOGLE_CLIENT_SECRET=your_client_secret_here")}`,
|
|
32
|
+
);
|
|
33
|
+
console.error(" 4. Or set them in your environment:");
|
|
34
|
+
console.error(
|
|
35
|
+
` ${colors.cyan('export GOOGLE_CLIENT_ID="your_client_id_here"')}`,
|
|
36
|
+
);
|
|
37
|
+
console.error(
|
|
38
|
+
` ${colors.cyan('export GOOGLE_CLIENT_SECRET="your_client_secret_here"')}`,
|
|
39
|
+
);
|
|
40
|
+
} else {
|
|
41
|
+
console.error(`\n${colors.red("Error:")} ${error.message}`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
process.exitCode = 1;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export async function logoutCommand() {
|
|
49
|
+
try {
|
|
50
|
+
const removed = await clearTokens();
|
|
51
|
+
if (removed) {
|
|
52
|
+
console.log(
|
|
53
|
+
colors.green(
|
|
54
|
+
"Successfully logged out. Stored authentication tokens removed.",
|
|
55
|
+
),
|
|
56
|
+
);
|
|
57
|
+
} else {
|
|
58
|
+
console.log(colors.yellow("You are not currently authenticated."));
|
|
59
|
+
}
|
|
60
|
+
} catch (error) {
|
|
61
|
+
console.error(`${colors.red("Error:")} ${error.message}`);
|
|
62
|
+
process.exitCode = 1;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function statusCommand() {
|
|
67
|
+
try {
|
|
68
|
+
console.log(colors.bold("Tubex Authentication\n"));
|
|
69
|
+
const status = await getAuthStatus();
|
|
70
|
+
if (status.authenticated) {
|
|
71
|
+
console.log(`Status: ${colors.green("Authenticated")}`);
|
|
72
|
+
console.log(`Account: ${status.account}`);
|
|
73
|
+
} else {
|
|
74
|
+
console.log(`Status: ${colors.yellow("Not authenticated")}`);
|
|
75
|
+
}
|
|
76
|
+
} catch (error) {
|
|
77
|
+
console.error(`${colors.red("Error:")} ${error.message}`);
|
|
78
|
+
process.exitCode = 1;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import {
|
|
2
|
+
downloadVideo,
|
|
3
|
+
getYtDlpInstallInstructions,
|
|
4
|
+
getFfmpegInstallInstructions,
|
|
5
|
+
} from "../downloader.js";
|
|
6
|
+
import { colors } from "../ui.js";
|
|
7
|
+
|
|
8
|
+
const SUPPORTED_QUALITIES = [
|
|
9
|
+
"360",
|
|
10
|
+
"480",
|
|
11
|
+
"720",
|
|
12
|
+
"1080",
|
|
13
|
+
"1440",
|
|
14
|
+
"2160",
|
|
15
|
+
"best",
|
|
16
|
+
];
|
|
17
|
+
const SUPPORTED_FORMATS = ["mp4", "mkv", "webm"];
|
|
18
|
+
|
|
19
|
+
export function validateDownloadOptions(options = {}) {
|
|
20
|
+
const validated = {
|
|
21
|
+
output: options.output || "./downloads",
|
|
22
|
+
audioOnly: Boolean(options.audioOnly),
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
if (options.quality) {
|
|
26
|
+
const q = String(options.quality).toLowerCase().trim();
|
|
27
|
+
if (!SUPPORTED_QUALITIES.includes(q)) {
|
|
28
|
+
const error = new Error(
|
|
29
|
+
`Invalid quality "${options.quality}". Supported qualities: ${SUPPORTED_QUALITIES.join(", ")}`,
|
|
30
|
+
);
|
|
31
|
+
error.code = "INVALID_OPTION";
|
|
32
|
+
throw error;
|
|
33
|
+
}
|
|
34
|
+
validated.quality = q;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (options.format) {
|
|
38
|
+
const f = String(options.format).toLowerCase().trim();
|
|
39
|
+
if (!SUPPORTED_FORMATS.includes(f)) {
|
|
40
|
+
const error = new Error(
|
|
41
|
+
`Invalid format "${options.format}". Supported formats: ${SUPPORTED_FORMATS.join(", ")}`,
|
|
42
|
+
);
|
|
43
|
+
error.code = "INVALID_OPTION";
|
|
44
|
+
throw error;
|
|
45
|
+
}
|
|
46
|
+
validated.format = f;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (validated.audioOnly) {
|
|
50
|
+
if (validated.quality) {
|
|
51
|
+
const error = new Error(
|
|
52
|
+
"Cannot specify --quality when using --audio-only mode. Audio streams do not have video resolution.",
|
|
53
|
+
);
|
|
54
|
+
error.code = "INVALID_COMBINATION";
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (validated.format) {
|
|
59
|
+
const error = new Error(
|
|
60
|
+
"Cannot specify video --format when using --audio-only mode. Audio is extracted as mp3.",
|
|
61
|
+
);
|
|
62
|
+
error.code = "INVALID_COMBINATION";
|
|
63
|
+
throw error;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return validated;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function downloadCommand(url, options = {}) {
|
|
71
|
+
try {
|
|
72
|
+
const validatedOptions = validateDownloadOptions(options);
|
|
73
|
+
|
|
74
|
+
console.log(colors.cyan(`Preparing download for: ${url}`));
|
|
75
|
+
console.log(`Output: ${colors.bold(validatedOptions.output)}`);
|
|
76
|
+
if (validatedOptions.audioOnly) {
|
|
77
|
+
console.log(`Mode: ${colors.yellow("Audio only (mp3)")}`);
|
|
78
|
+
} else {
|
|
79
|
+
if (validatedOptions.quality) {
|
|
80
|
+
console.log(`Quality: ${colors.bold(validatedOptions.quality)}`);
|
|
81
|
+
}
|
|
82
|
+
if (validatedOptions.format) {
|
|
83
|
+
console.log(`Format: ${colors.bold(validatedOptions.format)}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
console.log("");
|
|
87
|
+
|
|
88
|
+
await downloadVideo(url, validatedOptions);
|
|
89
|
+
console.log(colors.green("\nDownload completed successfully!"));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error.code === "MISSING_YTDLP") {
|
|
92
|
+
console.error(getYtDlpInstallInstructions());
|
|
93
|
+
} else if (error.code === "MISSING_FFMPEG") {
|
|
94
|
+
console.error(getFfmpegInstallInstructions());
|
|
95
|
+
} else {
|
|
96
|
+
console.error(`${colors.red("Error:")} ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
process.exitCode = 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { getUserPlaylists, getPlaylistVideos } from "../youtube.js";
|
|
2
|
+
import { colors } from "../ui.js";
|
|
3
|
+
|
|
4
|
+
export async function listPlaylistsCommand() {
|
|
5
|
+
try {
|
|
6
|
+
console.log(colors.cyan("Fetching your YouTube playlists...\n"));
|
|
7
|
+
const playlists = await getUserPlaylists();
|
|
8
|
+
|
|
9
|
+
if (playlists.length === 0) {
|
|
10
|
+
console.log(colors.yellow("No playlists found for your account."));
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
console.log(
|
|
15
|
+
colors.bold(`Your YouTube Playlists (${playlists.length}):\n`),
|
|
16
|
+
);
|
|
17
|
+
playlists.forEach((playlist, index) => {
|
|
18
|
+
console.log(
|
|
19
|
+
`${colors.green(String(index + 1))}. ${colors.bold(playlist.title)}`,
|
|
20
|
+
);
|
|
21
|
+
console.log(` ${colors.dim("ID:")} ${playlist.id}`);
|
|
22
|
+
console.log(` ${colors.dim("Videos:")} ${playlist.itemCount}`);
|
|
23
|
+
if (playlist.description) {
|
|
24
|
+
console.log(` ${colors.dim("About:")} ${playlist.description}`);
|
|
25
|
+
}
|
|
26
|
+
console.log("");
|
|
27
|
+
});
|
|
28
|
+
} catch (error) {
|
|
29
|
+
handlePlaylistError(error);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function viewPlaylistCommand(playlistId) {
|
|
34
|
+
if (!playlistId || !playlistId.trim()) {
|
|
35
|
+
console.error(`${colors.red("Error:")} Playlist ID cannot be empty.`);
|
|
36
|
+
process.exitCode = 1;
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const cleanId = playlistId.trim();
|
|
41
|
+
|
|
42
|
+
try {
|
|
43
|
+
console.log(colors.cyan(`Fetching videos for playlist "${cleanId}"...\n`));
|
|
44
|
+
const videos = await getPlaylistVideos(cleanId);
|
|
45
|
+
|
|
46
|
+
if (videos.length === 0) {
|
|
47
|
+
console.log(colors.yellow(`Playlist "${cleanId}" is empty.`));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
console.log(colors.bold(`Playlist Videos (${videos.length}):\n`));
|
|
52
|
+
videos.forEach((video, index) => {
|
|
53
|
+
console.log(
|
|
54
|
+
`${colors.green(String(index + 1))}. ${colors.bold(video.title)}`,
|
|
55
|
+
);
|
|
56
|
+
console.log(` ${colors.dim("Channel:")} ${video.channelTitle}`);
|
|
57
|
+
console.log(` ${colors.dim("Video ID:")} ${video.id}`);
|
|
58
|
+
console.log(` ${colors.dim("URL:")} ${colors.cyan(video.url)}\n`);
|
|
59
|
+
});
|
|
60
|
+
} catch (error) {
|
|
61
|
+
handlePlaylistError(error);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function handlePlaylistError(error) {
|
|
66
|
+
if (error.code === "NOT_AUTHENTICATED") {
|
|
67
|
+
console.error(
|
|
68
|
+
`${colors.red("Error:")} You must be authenticated to access playlists.\n`,
|
|
69
|
+
);
|
|
70
|
+
console.error(colors.yellow("Please connect your Google account first:"));
|
|
71
|
+
console.error(` ${colors.cyan("node bin/tubex.js auth login")}`);
|
|
72
|
+
} else if (error.code === "AUTH_REVOKED" || error.code === "AUTH_EXPIRED") {
|
|
73
|
+
console.error(
|
|
74
|
+
`${colors.red("Error:")} Authentication has expired or been revoked.\n`,
|
|
75
|
+
);
|
|
76
|
+
console.error(colors.yellow("Please log in again:"));
|
|
77
|
+
console.error(` ${colors.cyan("node bin/tubex.js auth login")}`);
|
|
78
|
+
} else if (error.code === "NOT_FOUND") {
|
|
79
|
+
console.error(
|
|
80
|
+
`${colors.red("Error:")} Playlist not found. Please verify the playlist ID.`,
|
|
81
|
+
);
|
|
82
|
+
} else {
|
|
83
|
+
console.error(`${colors.red("Error:")} ${error.message}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
process.exitCode = 1;
|
|
87
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { searchYouTube } from "../youtube.js";
|
|
2
|
+
import { colors } from "../ui.js";
|
|
3
|
+
|
|
4
|
+
export async function searchVideos(query, options) {
|
|
5
|
+
if (!query || !query.trim()) {
|
|
6
|
+
console.error(`${colors.red("Error:")} Search query cannot be empty.`);
|
|
7
|
+
process.exitCode = 1;
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const cleanQuery = query.trim();
|
|
12
|
+
|
|
13
|
+
try {
|
|
14
|
+
console.log(colors.cyan(`Searching YouTube for "${cleanQuery}"...\n`));
|
|
15
|
+
const results = await searchYouTube(cleanQuery, options.limit);
|
|
16
|
+
|
|
17
|
+
if (results.length === 0) {
|
|
18
|
+
console.log(colors.yellow(`No videos found for "${cleanQuery}".`));
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
console.log(colors.bold(`Found ${results.length} video(s):\n`));
|
|
23
|
+
results.forEach((video, index) => {
|
|
24
|
+
console.log(
|
|
25
|
+
`${colors.green(String(index + 1))}. ${colors.bold(video.title)}`,
|
|
26
|
+
);
|
|
27
|
+
console.log(` ${colors.dim("Channel:")} ${video.channelTitle}`);
|
|
28
|
+
console.log(` ${colors.dim("Video ID:")} ${video.id}`);
|
|
29
|
+
console.log(` ${colors.dim("URL:")} ${colors.cyan(video.url)}\n`);
|
|
30
|
+
});
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (error.code === "MISSING_API_KEY") {
|
|
33
|
+
console.error(
|
|
34
|
+
`${colors.red("Error:")} YOUTUBE_API_KEY is not configured.\n`,
|
|
35
|
+
);
|
|
36
|
+
console.error(colors.yellow("To configure your API key:"));
|
|
37
|
+
console.error(" 1. Add it to ~/.config/tubex/.env (global):");
|
|
38
|
+
console.error(` ${colors.cyan("YOUTUBE_API_KEY=your_api_key_here")}`);
|
|
39
|
+
console.error(" 2. Or add it to a local .env file in your working directory");
|
|
40
|
+
console.error(" 3. Or set it in your environment:");
|
|
41
|
+
console.error(
|
|
42
|
+
` ${colors.cyan('export YOUTUBE_API_KEY="your_api_key_here"')}`,
|
|
43
|
+
);
|
|
44
|
+
} else {
|
|
45
|
+
console.error(`${colors.red("Error:")} ${error.message}`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
process.exitCode = 1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { execFile, spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { colors } from "./ui.js";
|
|
5
|
+
|
|
6
|
+
export async function isYtDlpAvailable() {
|
|
7
|
+
return new Promise((resolve) => {
|
|
8
|
+
execFile("yt-dlp", ["--version"], (error) => {
|
|
9
|
+
resolve(!error);
|
|
10
|
+
});
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export async function isFfmpegAvailable() {
|
|
15
|
+
return new Promise((resolve) => {
|
|
16
|
+
execFile("ffmpeg", ["-version"], (error) => {
|
|
17
|
+
resolve(!error);
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function isValidYouTubeUrl(urlString) {
|
|
23
|
+
if (!urlString || typeof urlString !== "string") {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
try {
|
|
28
|
+
const parsed = new URL(urlString.trim());
|
|
29
|
+
const hostname = parsed.hostname.toLowerCase().replace(/^www\./, "");
|
|
30
|
+
|
|
31
|
+
if (hostname === "youtube.com" || hostname === "m.youtube.com") {
|
|
32
|
+
if (parsed.pathname === "/watch" && parsed.searchParams.get("v")) {
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
if (parsed.pathname.startsWith("/shorts/") && parsed.pathname.length > 8) {
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
if (parsed.pathname.startsWith("/embed/") && parsed.pathname.length > 7) {
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (hostname === "youtu.be") {
|
|
45
|
+
const videoId = parsed.pathname.slice(1);
|
|
46
|
+
return Boolean(videoId && !videoId.includes("/"));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return false;
|
|
50
|
+
} catch {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function getYtDlpInstallInstructions() {
|
|
56
|
+
return `${colors.red("Error:")} yt-dlp is not installed or not found in your PATH.
|
|
57
|
+
|
|
58
|
+
Tubex requires yt-dlp to download videos.
|
|
59
|
+
|
|
60
|
+
${colors.yellow("Installation instructions:")}
|
|
61
|
+
${colors.bold("macOS (Homebrew):")}
|
|
62
|
+
${colors.cyan("brew install yt-dlp")}
|
|
63
|
+
|
|
64
|
+
${colors.bold("Linux (Debian/Ubuntu):")}
|
|
65
|
+
${colors.cyan("sudo apt install yt-dlp")}
|
|
66
|
+
(or via pip: ${colors.cyan("pip install yt-dlp")})
|
|
67
|
+
|
|
68
|
+
${colors.bold("Windows (winget / Chocolatey):")}
|
|
69
|
+
${colors.cyan("winget install yt-dlp")}
|
|
70
|
+
(or: ${colors.cyan("choco install yt-dlp")})
|
|
71
|
+
|
|
72
|
+
For additional installation methods, see:
|
|
73
|
+
${colors.dim("https://github.com/yt-dlp/yt-dlp#installation")}`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function getFfmpegInstallInstructions() {
|
|
77
|
+
return `${colors.red("Error:")} ffmpeg is not installed or not found in your PATH.
|
|
78
|
+
|
|
79
|
+
Audio-only extraction requires FFmpeg to convert and extract audio.
|
|
80
|
+
|
|
81
|
+
${colors.yellow("Installation instructions:")}
|
|
82
|
+
${colors.bold("macOS (Homebrew):")}
|
|
83
|
+
${colors.cyan("brew install ffmpeg")}
|
|
84
|
+
|
|
85
|
+
${colors.bold("Linux (Debian/Ubuntu):")}
|
|
86
|
+
${colors.cyan("sudo apt install ffmpeg")}
|
|
87
|
+
|
|
88
|
+
${colors.bold("Windows (winget / Chocolatey):")}
|
|
89
|
+
${colors.cyan("winget install Gyan.FFmpeg")}
|
|
90
|
+
(or: ${colors.cyan("choco install ffmpeg")})
|
|
91
|
+
|
|
92
|
+
For more installation methods, see:
|
|
93
|
+
${colors.dim("https://ffmpeg.org/download.html")}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function formatYtDlpError(stderr) {
|
|
97
|
+
if (!stderr) {
|
|
98
|
+
return "Download failed. Please check the video URL and try again.";
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (stderr.includes("Private video") || stderr.includes("Sign in")) {
|
|
102
|
+
return "This video is private or restricted.";
|
|
103
|
+
}
|
|
104
|
+
if (stderr.includes("Video unavailable")) {
|
|
105
|
+
return "This video is unavailable. Please check the URL.";
|
|
106
|
+
}
|
|
107
|
+
if (stderr.includes("DRM")) {
|
|
108
|
+
return "This video is DRM-protected and cannot be downloaded.";
|
|
109
|
+
}
|
|
110
|
+
if (
|
|
111
|
+
stderr.includes("network") ||
|
|
112
|
+
stderr.includes("Connection refused") ||
|
|
113
|
+
stderr.includes("timed out")
|
|
114
|
+
) {
|
|
115
|
+
return "Network error while downloading. Please check your internet connection.";
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const errorLines = stderr
|
|
119
|
+
.split("\n")
|
|
120
|
+
.filter((line) => line.startsWith("ERROR:"))
|
|
121
|
+
.map((line) => line.replace(/^ERROR:\s*/, "").trim());
|
|
122
|
+
|
|
123
|
+
if (errorLines.length > 0) {
|
|
124
|
+
return errorLines[0];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return "Download failed. Please check the video URL and try again.";
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function buildYtDlpArgs(url, options = {}) {
|
|
131
|
+
const args = ["--newline", "--no-warnings"];
|
|
132
|
+
|
|
133
|
+
const outputDir = path.resolve(options.output || "./downloads");
|
|
134
|
+
args.push("-P", outputDir);
|
|
135
|
+
|
|
136
|
+
if (options.audioOnly) {
|
|
137
|
+
args.push("-x", "--audio-format", "mp3");
|
|
138
|
+
} else {
|
|
139
|
+
if (options.quality) {
|
|
140
|
+
if (options.quality === "best") {
|
|
141
|
+
args.push("-f", "bestvideo+bestaudio/best");
|
|
142
|
+
} else {
|
|
143
|
+
args.push(
|
|
144
|
+
"-f",
|
|
145
|
+
`bestvideo[height<=${options.quality}]+bestaudio/best[height<=${options.quality}]/best`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (options.format) {
|
|
151
|
+
args.push("--merge-output-format", options.format);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
args.push(url.trim());
|
|
156
|
+
return args;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export async function downloadVideo(url, options = {}) {
|
|
160
|
+
if (!isValidYouTubeUrl(url)) {
|
|
161
|
+
const error = new Error(
|
|
162
|
+
"Invalid YouTube URL. Please provide a valid YouTube video URL (e.g., https://www.youtube.com/watch?v=VIDEO_ID).",
|
|
163
|
+
);
|
|
164
|
+
error.code = "INVALID_URL";
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const ytDlpReady = await isYtDlpAvailable();
|
|
169
|
+
if (!ytDlpReady) {
|
|
170
|
+
const error = new Error("yt-dlp is not installed.");
|
|
171
|
+
error.code = "MISSING_YTDLP";
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
if (options.audioOnly) {
|
|
176
|
+
const ffmpegReady = await isFfmpegAvailable();
|
|
177
|
+
if (!ffmpegReady) {
|
|
178
|
+
const error = new Error("ffmpeg is required for audio extraction.");
|
|
179
|
+
error.code = "MISSING_FFMPEG";
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const outputDir = path.resolve(options.output || "./downloads");
|
|
185
|
+
await fs.mkdir(outputDir, { recursive: true });
|
|
186
|
+
|
|
187
|
+
const args = buildYtDlpArgs(url, options);
|
|
188
|
+
|
|
189
|
+
return new Promise((resolve, reject) => {
|
|
190
|
+
const child = spawn("yt-dlp", args);
|
|
191
|
+
|
|
192
|
+
let stderrData = "";
|
|
193
|
+
let lastProgress = "";
|
|
194
|
+
let destination = "";
|
|
195
|
+
|
|
196
|
+
const handleSigInt = () => {
|
|
197
|
+
try {
|
|
198
|
+
child.kill("SIGINT");
|
|
199
|
+
} catch {}
|
|
200
|
+
process.stdout.write(colors.yellow("\nDownload cancelled.\n"));
|
|
201
|
+
process.exit(130);
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
process.once("SIGINT", handleSigInt);
|
|
205
|
+
|
|
206
|
+
child.stdout.on("data", (chunk) => {
|
|
207
|
+
const lines = chunk.toString().split(/\r?\n/);
|
|
208
|
+
for (const line of lines) {
|
|
209
|
+
const trimmed = line.trim();
|
|
210
|
+
if (!trimmed) continue;
|
|
211
|
+
|
|
212
|
+
if (trimmed.startsWith("[download] Destination:")) {
|
|
213
|
+
destination = trimmed.replace("[download] Destination:", "").trim();
|
|
214
|
+
console.log(`${colors.dim("Saving to:")} ${destination}`);
|
|
215
|
+
} else if (trimmed.startsWith("[download]") && trimmed.includes("%")) {
|
|
216
|
+
lastProgress = trimmed;
|
|
217
|
+
process.stdout.write(`\r${colors.cyan(trimmed)}`);
|
|
218
|
+
} else if (
|
|
219
|
+
trimmed.startsWith("[Merger]") ||
|
|
220
|
+
trimmed.startsWith("[Fixup]") ||
|
|
221
|
+
trimmed.startsWith("[ExtractAudio]")
|
|
222
|
+
) {
|
|
223
|
+
process.stdout.write("\nProcessing audio/video streams...");
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
child.stderr.on("data", (chunk) => {
|
|
229
|
+
stderrData += chunk.toString();
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
child.on("close", (code) => {
|
|
233
|
+
process.removeListener("SIGINT", handleSigInt);
|
|
234
|
+
|
|
235
|
+
if (lastProgress) {
|
|
236
|
+
process.stdout.write("\n");
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (code === 0) {
|
|
240
|
+
resolve({ destination, outputDir });
|
|
241
|
+
} else {
|
|
242
|
+
const cleanError = formatYtDlpError(stderrData);
|
|
243
|
+
const error = new Error(cleanError);
|
|
244
|
+
error.code = "DOWNLOAD_FAILED";
|
|
245
|
+
reject(error);
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
child.on("error", (err) => {
|
|
250
|
+
process.removeListener("SIGINT", handleSigInt);
|
|
251
|
+
reject(err);
|
|
252
|
+
});
|
|
253
|
+
});
|
|
254
|
+
}
|
package/src/ui.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
|
|
3
|
+
const canStyle = typeof styleText === "function";
|
|
4
|
+
|
|
5
|
+
export const colors = {
|
|
6
|
+
green: (text) => (canStyle ? styleText("green", String(text)) : String(text)),
|
|
7
|
+
red: (text) => (canStyle ? styleText("red", String(text)) : String(text)),
|
|
8
|
+
yellow: (text) => (canStyle ? styleText("yellow", String(text)) : String(text)),
|
|
9
|
+
cyan: (text) => (canStyle ? styleText("cyan", String(text)) : String(text)),
|
|
10
|
+
bold: (text) => (canStyle ? styleText("bold", String(text)) : String(text)),
|
|
11
|
+
dim: (text) => (canStyle ? styleText("dim", String(text)) : String(text)),
|
|
12
|
+
};
|