Compare commits

...

14 Commits

Author SHA1 Message Date
Julian Freeman
1554be25d2 fix ig ratio 2025-12-30 09:23:28 -04:00
Julian Freeman
05887fd7a3 fix ig thumbnail 2025-12-30 09:13:12 -04:00
Julian Freeman
63648f9d7c fix download fails in batch mode 2025-12-30 01:06:44 -04:00
Julian Freeman
0a439dbd71 support multiple input 2025-12-30 00:50:55 -04:00
Julian Freeman
f164569e89 fix product name 2025-12-25 18:32:09 -04:00
Julian Freeman
f4bdb85841 fix ffmpeg download 2025-12-25 18:20:45 -04:00
Julian Freeman
36bd5061a4 add splash screen 2025-12-08 18:59:48 -04:00
Julian Freeman
dde9ed7718 fix ffmpeg update status 2025-12-08 18:49:14 -04:00
Julian Freeman
8ae5f4f66c ensure ffmpeg 2025-12-08 18:22:49 -04:00
Julian Freeman
eada45bd9c add format convert support 2025-12-08 17:48:22 -04:00
Julian Freeman
77407c7e28 modify height 2025-12-08 17:24:59 -04:00
Julian Freeman
ac00c54ca3 add ffmpeg 2025-12-08 17:16:46 -04:00
Julian Freeman
14b0e96c7d trying fix macos download 2025-12-08 13:19:27 -04:00
Julian Freeman
fd28d4764a modify ui 2025-12-08 11:01:22 -04:00
21 changed files with 699 additions and 82 deletions

View File

@@ -3,8 +3,3 @@
A simple Youtube downloader.
Generated by Gemini CLI.
## Problems
1. windows 上打包后运行命令会出现黑窗,而且还是会出现找不到 js-runtimes 的问题,但是 quickjs 是正常下载了
2. macos 上未测试

View File

@@ -1,7 +1,7 @@
{
"name": "stream-capture",
"private": true,
"version": "0.1.0",
"version": "1.1.0",
"type": "module",
"scripts": {
"dev": "vite",

12
splashscreen.html Normal file
View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>StreamCapture Loading</title>
</head>
<body class="font-sans antialiased">
<div id="app"></div>
<script type="module" src="/src/splash/main.ts"></script>
</body>
</html>

3
src-tauri/Cargo.lock generated
View File

@@ -3971,9 +3971,10 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "stream-capture"
version = "0.1.0"
version = "1.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
"chrono",
"futures-util",
"regex",

View File

@@ -1,6 +1,6 @@
[package]
name = "stream-capture"
version = "0.1.0"
version = "1.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
@@ -19,6 +19,7 @@ tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
reqwest = { version = "0.12", features = ["json", "rustls-tls", "stream"] }
base64 = "0.22"
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
chrono = { version = "0.4", features = ["serde"] }

View File

@@ -2,7 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"windows": ["main", "splashscreen"],
"permissions": [
"core:default",
"opener:default",

View File

@@ -15,6 +15,9 @@ use crate::storage::{self};
const YT_DLP_REPO_URL: &str = "https://github.com/yt-dlp/yt-dlp/releases/latest/download";
// Bellard's QuickJS binary releases URL
const QJS_REPO_URL: &str = "https://bellard.org/quickjs/binary_releases";
// FFmpeg builds
const FFMPEG_GITHUB_API: &str = "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest";
const FFMPEG_EVERMEET_BASE: &str = "https://evermeet.cx/ffmpeg";
pub fn get_ytdlp_binary_name() -> &'static str {
if cfg!(target_os = "windows") {
@@ -62,10 +65,23 @@ pub fn get_qjs_path(app: &AppHandle) -> Result<PathBuf> {
Ok(get_bin_dir(app)?.join(get_qjs_binary_name()))
}
pub fn get_ffmpeg_binary_name() -> &'static str {
if cfg!(target_os = "windows") {
"ffmpeg.exe"
} else {
"ffmpeg"
}
}
pub fn get_ffmpeg_path(app: &AppHandle) -> Result<PathBuf> {
Ok(get_bin_dir(app)?.join(get_ffmpeg_binary_name()))
}
pub fn check_binaries(app: &AppHandle) -> bool {
let ytdlp = get_ytdlp_path(app).map(|p| p.exists()).unwrap_or(false);
let qjs = get_qjs_path(app).map(|p| p.exists()).unwrap_or(false);
ytdlp && qjs
let ffmpeg = get_ffmpeg_path(app).map(|p| p.exists()).unwrap_or(false);
ytdlp && qjs && ffmpeg
}
// --- yt-dlp Logic ---
@@ -95,6 +111,17 @@ pub async fn download_ytdlp(app: &AppHandle) -> Result<PathBuf> {
fs::set_permissions(&path, perms)?;
}
#[cfg(target_os = "macos")]
{
// Remove quarantine attribute to allow execution on macOS
std::process::Command::new("xattr")
.arg("-d")
.arg("com.apple.quarantine")
.arg(&path)
.output()
.ok();
}
Ok(path)
}
@@ -204,22 +231,31 @@ pub async fn download_qjs(app: &AppHandle) -> Result<PathBuf> {
let source_name = get_qjs_source_name_in_zip();
let target_name = get_qjs_binary_name(); // quickjs.exe or quickjs
let mut found = false;
let mut found_exe = false;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
// Filenames in zip might be like "quickjs-win-x86_64-2024-01-13/qjs.exe"
let name = file.name();
let name = file.name().to_string();
// Skip directories
if file.is_dir() {
continue;
}
let filename_only = name.split('/').last().unwrap_or("");
if filename_only == source_name {
let mut out_file = fs::File::create(bin_dir.join(target_name))?;
std::io::copy(&mut file, &mut out_file)?;
found = true;
break;
found_exe = true;
} else if filename_only.ends_with(".dll") {
// Extract DLLs (needed for Windows MinGW builds, e.g. libwinpthread-1.dll)
let mut out_file = fs::File::create(bin_dir.join(filename_only))?;
std::io::copy(&mut file, &mut out_file)?;
}
}
if !found {
if !found_exe {
return Err(anyhow!("在下载的压缩包中找不到 {}", source_name));
}
@@ -232,6 +268,17 @@ pub async fn download_qjs(app: &AppHandle) -> Result<PathBuf> {
fs::set_permissions(&final_path, perms)?;
}
#[cfg(target_os = "macos")]
{
// Remove quarantine attribute to allow execution on macOS
std::process::Command::new("xattr")
.arg("-d")
.arg("com.apple.quarantine")
.arg(&final_path)
.output()
.ok();
}
Ok(final_path)
}
@@ -241,6 +288,178 @@ pub async fn update_qjs(app: &AppHandle) -> Result<String> {
Ok("QuickJS 已更新/安装".to_string())
}
// --- FFmpeg Logic ---
pub async fn download_ffmpeg(app: &AppHandle) -> Result<PathBuf> {
let bin_dir = get_bin_dir(app)?;
if cfg!(target_os = "windows") {
// Query GitHub releases API to find a suitable win64 zip asset
let client = reqwest::Client::new();
let resp = client.get(FFMPEG_GITHUB_API)
.header(reqwest::header::USER_AGENT, "stream-capture")
.send()
.await?;
if !resp.status().is_success() {
return Err(anyhow!("无法获取 FFmpeg releases 信息"));
}
let json: serde_json::Value = resp.json().await?;
let mut download_url: Option<String> = None;
if let Some(assets) = json.get("assets").and_then(|a| a.as_array()) {
for asset in assets {
if let (Some(name), Some(url)) = (asset.get("name").and_then(|n| n.as_str()), asset.get("browser_download_url").and_then(|u| u.as_str())) {
let lname = name.to_lowercase();
// Prefer GPL static build, avoid shared to get a single exe
if lname.contains("win64") && lname.contains("gpl") && !lname.contains("shared") && lname.ends_with(".zip") {
download_url = Some(url.to_string());
break;
}
}
}
if download_url.is_none() {
// fallback: choose first zip asset that is NOT shared if possible
for asset in assets {
if let (Some(url), Some(name)) = (asset.get("browser_download_url").and_then(|u| u.as_str()), asset.get("name").and_then(|n| n.as_str())) {
let lname = name.to_lowercase();
if lname.ends_with(".zip") && !lname.contains("shared") {
download_url = Some(url.to_string());
break;
}
}
}
}
}
let url = download_url.ok_or(anyhow!("未找到适合 Windows 的 FFmpeg 发行包"))?;
let resp = client.get(&url).header(reqwest::header::USER_AGENT, "stream-capture").send().await?;
if !resp.status().is_success() {
return Err(anyhow!("下载 FFmpeg 失败"));
}
let bytes = resp.bytes().await?;
let mut archive = ZipArchive::new(Cursor::new(bytes))?;
let mut found = false;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
if file.is_dir() { continue; }
let name = file.name().to_string();
let filename_only = name.split('/').last().unwrap_or("");
// Only extract the executable, ignore DLLs
if filename_only.eq_ignore_ascii_case("ffmpeg.exe") {
let mut out_file = fs::File::create(bin_dir.join(filename_only))?;
std::io::copy(&mut file, &mut out_file)?;
found = true;
}
}
if !found {
return Err(anyhow!("在 FFmpeg 压缩包中未找到 ffmpeg 可执行文件"));
}
let final_path = get_ffmpeg_path(app)?;
Ok(final_path)
} else if cfg!(target_os = "macos") {
// Fetch listing page and find latest ffmpeg-*.zip
let resp = reqwest::get(FFMPEG_EVERMEET_BASE).await?;
if !resp.status().is_success() {
return Err(anyhow!("无法获取 evermeet.ffmpeg 列表"));
}
let body = resp.text().await?;
let re = regex::Regex::new(r#"href="(ffmpeg-[0-9][^"]*\.zip)"#)?;
let mut candidates: Vec<&str> = Vec::new();
for cap in re.captures_iter(&body) {
if let Some(m) = cap.get(1) {
candidates.push(m.as_str());
}
}
let filename = candidates.last().ok_or(anyhow!("未在 evermeet 找到 ffmpeg zip 文件"))?;
let url = format!("{}/{}", FFMPEG_EVERMEET_BASE, filename);
let resp = reqwest::get(&url).await?;
if !resp.status().is_success() {
return Err(anyhow!("下载 FFmpeg macOS 版本失败"));
}
let bytes = resp.bytes().await?;
let mut archive = ZipArchive::new(Cursor::new(bytes))?;
let mut found = false;
for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
if file.is_dir() { continue; }
let name = file.name().to_string();
let filename_only = name.split('/').last().unwrap_or("");
if filename_only == "ffmpeg" {
let mut out_file = fs::File::create(bin_dir.join("ffmpeg"))?;
std::io::copy(&mut file, &mut out_file)?;
found = true;
}
}
if !found {
return Err(anyhow!("在 FFmpeg 压缩包中未找到 ffmpeg 可执行文件"));
}
let final_path = get_ffmpeg_path(app)?;
#[cfg(target_family = "unix")]
{
let mut perms = fs::metadata(&final_path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&final_path, perms)?;
}
#[cfg(target_os = "macos")]
{
std::process::Command::new("xattr").arg("-d").arg("com.apple.quarantine").arg(&final_path).output().ok();
}
Ok(final_path)
} else {
Err(anyhow!("当前操作系统不支持自动下载 FFmpeg"))
}
}
pub async fn update_ffmpeg(app: &AppHandle) -> Result<String> {
let path = get_ffmpeg_path(app)?;
if !path.exists() {
download_ffmpeg(app).await?;
return Ok("FFmpeg 已安装".to_string());
}
// Re-download to update
download_ffmpeg(app).await?;
// Update settings timestamp
let mut settings = storage::load_settings(app)?;
settings.last_updated = Some(chrono::Utc::now());
storage::save_settings(app, &settings)?;
Ok("FFmpeg 已更新".to_string())
}
pub fn get_ffmpeg_version(app: &AppHandle) -> Result<String> {
let path = get_ffmpeg_path(app)?;
if !path.exists() {
return Ok("未安装".to_string());
}
let mut cmd = std::process::Command::new(&path);
cmd.arg("-version");
#[cfg(target_os = "windows")]
cmd.creation_flags(0x08000000);
let output = cmd.output()?;
if output.status.success() {
// Prefer stdout, fallback to stderr if stdout empty
let out = if !output.stdout.is_empty() {
String::from_utf8_lossy(&output.stdout).to_string()
} else {
String::from_utf8_lossy(&output.stderr).to_string()
};
if let Some(first_line) = out.lines().next() {
let v = first_line.trim().to_string();
if !v.is_empty() {
return Ok(v);
}
}
}
// If we couldn't obtain a usable version string, treat as not installed
Ok("未安装".to_string())
}
pub fn get_qjs_version(app: &AppHandle) -> Result<String> {
let path = get_qjs_path(app)?;
if !path.exists() {
@@ -253,11 +472,46 @@ pub async fn ensure_binaries(app: &AppHandle) -> Result<()> {
let ytdlp = get_ytdlp_path(app)?;
if !ytdlp.exists() {
download_ytdlp(app).await?;
} else {
#[cfg(target_os = "macos")]
{
std::process::Command::new("xattr")
.arg("-d")
.arg("com.apple.quarantine")
.arg(&ytdlp)
.output()
.ok();
}
}
let qjs = get_qjs_path(app)?;
if !qjs.exists() {
download_qjs(app).await?;
} else {
#[cfg(target_os = "macos")]
{
std::process::Command::new("xattr")
.arg("-d")
.arg("com.apple.quarantine")
.arg(&qjs)
.output()
.ok();
}
}
let ffmpeg = get_ffmpeg_path(app)?;
if !ffmpeg.exists() {
download_ffmpeg(app).await?;
} else {
#[cfg(target_os = "macos")]
{
std::process::Command::new("xattr")
.arg("-d")
.arg("com.apple.quarantine")
.arg(&ffmpeg)
.output()
.ok();
}
}
Ok(())

View File

@@ -29,6 +29,11 @@ pub async fn update_quickjs(app: AppHandle) -> Result<String, String> {
binary_manager::update_qjs(&app).await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn update_ffmpeg(app: AppHandle) -> Result<String, String> {
binary_manager::update_ffmpeg(&app).await.map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_ytdlp_version(app: AppHandle) -> Result<String, String> {
binary_manager::get_ytdlp_version(&app).map_err(|e| e.to_string())
@@ -39,6 +44,33 @@ pub fn get_quickjs_version(app: AppHandle) -> Result<String, String> {
binary_manager::get_qjs_version(&app).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_ffmpeg_version(app: AppHandle) -> Result<String, String> {
binary_manager::get_ffmpeg_version(&app).map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn fetch_image(url: String) -> Result<String, String> {
use base64::{Engine as _, engine::general_purpose};
let client = reqwest::Client::new();
let res = client.get(&url)
.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
.send()
.await
.map_err(|e| e.to_string())?;
let bytes = res.bytes().await.map_err(|e| e.to_string())?;
// Convert to base64
let b64 = general_purpose::STANDARD.encode(&bytes);
// Simple heuristic for mime type
let mime = if url.to_lowercase().ends_with(".png") { "image/png" } else { "image/jpeg" };
Ok(format!("data:{};base64,{}", mime, b64))
}
#[tauri::command]
pub async fn fetch_metadata(app: AppHandle, url: String, parse_mix_playlist: bool) -> Result<downloader::MetadataResult, String> {
downloader::fetch_metadata(&app, &url, parse_mix_playlist).await.map_err(|e| e.to_string())
@@ -67,7 +99,7 @@ pub async fn start_download(app: AppHandle, url: String, options: DownloadOption
output_path: output_dir,
timestamp: chrono::Utc::now(),
status: status.to_string(),
format: options.quality,
format: options.output_format,
};
let _ = storage::add_history_item(&app, item);
@@ -101,6 +133,16 @@ pub fn delete_history_item(app: AppHandle, id: String) -> Result<(), String> {
storage::delete_history_item(&app, &id).map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn close_splash(app: AppHandle) {
if let Some(splash) = app.get_webview_window("splashscreen") {
splash.close().unwrap();
}
if let Some(main) = app.get_webview_window("main") {
main.show().unwrap();
}
}
#[tauri::command]
pub fn open_in_explorer(app: AppHandle, path: String) -> Result<(), String> {
let path_to_open = if Path::new(&path).exists() {

View File

@@ -15,6 +15,7 @@ pub struct VideoMetadata {
pub thumbnail: String,
pub duration: Option<f64>,
pub uploader: Option<String>,
pub url: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -36,6 +37,7 @@ pub struct DownloadOptions {
pub is_audio_only: bool,
pub quality: String, // e.g., "1080", "720", "best"
pub output_path: String, // Directory
pub output_format: String, // "original", "mp4", "webm", "mkv", "m4a", "aac", "opus", "vorbis", "wav", etc.
}
#[derive(Serialize, Clone, Debug)]
@@ -70,6 +72,7 @@ pub async fn fetch_metadata(app: &AppHandle, url: &str, parse_mix_playlist: bool
cmd.creation_flags(0x08000000);
// Pass the runtime and its absolute path to --js-runtimes
// Rust's Command automatically handles spaces in arguments, so we should NOT quote the path here.
cmd.arg("--js-runtimes").arg(format!("quickjs:{}", qjs_path.to_string_lossy()));
cmd.arg("--dump-single-json")
@@ -148,12 +151,17 @@ fn parse_video_metadata(json: &serde_json::Value) -> VideoMetadata {
_ => format!("https://i.ytimg.com/vi/{}/mqdefault.jpg", id),
};
let url = json["webpage_url"].as_str()
.or_else(|| json["url"].as_str())
.map(|s| s.to_string());
VideoMetadata {
id,
title: json["title"].as_str().unwrap_or("Unknown Title").to_string(),
thumbnail,
duration: json["duration"].as_f64(),
uploader: json["uploader"].as_str().map(|s| s.to_string()),
url,
}
}
@@ -165,12 +173,17 @@ pub async fn download_video(
) -> Result<String> {
let ytdlp_path = binary_manager::get_ytdlp_path(&app)?;
let qjs_path = binary_manager::get_qjs_path(&app)?; // Get absolute path to quickjs
let ffmpeg_path = binary_manager::get_ffmpeg_path(&app)?; // Get absolute path to ffmpeg
let mut args = Vec::new();
// Pass the runtime and its absolute path to --js-runtimes
args.push("--js-runtimes".to_string());
// Rust's Command automatically handles spaces in arguments, so we should NOT quote the path here.
args.push(format!("quickjs:{}", qjs_path.to_string_lossy()));
// Pass ffmpeg location so yt-dlp can find our managed ffmpeg
args.push("--ffmpeg-location".to_string());
args.push(ffmpeg_path.to_string_lossy().to_string());
args.push(url);
@@ -182,16 +195,25 @@ pub async fn download_video(
// Formats
if options.is_audio_only {
args.push("-x".to_string());
args.push("--audio-format".to_string());
args.push("mp3".to_string());
// Only set audio format if not "original"
if options.output_format != "original" {
args.push("--audio-format".to_string());
args.push(options.output_format.clone());
}
} else {
let format_arg = if options.quality == "best" {
"bestvideo+bestaudio/best".to_string()
} else {
format!("bestvideo[height<={}]+bestaudio/best[height<={}]", options.quality, options.quality)
format!("bestvideo[height<={}]+bestaudio/best[height<={}]/best", options.quality, options.quality)
};
args.push("-f".to_string());
args.push(format_arg);
// Only set merge output format if not "original"
if options.output_format != "original" {
args.push("--merge-output-format".to_string());
args.push(options.output_format.clone());
}
}
// Progress output

View File

@@ -13,8 +13,11 @@ pub fn run() {
commands::init_ytdlp,
commands::update_ytdlp,
commands::update_quickjs,
commands::update_ffmpeg,
commands::get_ytdlp_version,
commands::get_quickjs_version,
commands::get_ffmpeg_version,
commands::fetch_image,
commands::fetch_metadata,
commands::start_download,
commands::get_settings,
@@ -22,6 +25,7 @@ pub fn run() {
commands::get_history,
commands::clear_history,
commands::delete_history_item,
commands::close_splash,
commands::open_in_explorer
])
.run(tauri::generate_context!())

View File

@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "stream-capture",
"version": "0.1.0",
"productName": "StreamCapture",
"version": "1.1.0",
"identifier": "top.volan.stream-capture",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -12,9 +12,22 @@
"app": {
"windows": [
{
"title": "Stream Capture",
"label": "main",
"title": "流萤 - 视频下载 v1.1.0",
"width": 1300,
"height": 850
"height": 900,
"visible": false
},
{
"label": "splashscreen",
"title": "StreamCapture Loading",
"url": "splashscreen.html",
"width": 400,
"height": 300,
"decorations": false,
"center": true,
"resizable": false,
"alwaysOnTop": true
}
],
"security": {

View File

@@ -1,4 +1,3 @@
// filepath: src/App.vue
<script setup lang="ts">
import { onMounted } from 'vue'
import { RouterView, RouterLink, useRoute } from 'vue-router'
@@ -23,7 +22,7 @@ onMounted(async () => {
<template>
<div class="flex h-screen bg-gray-50 dark:bg-zinc-950 text-zinc-900 dark:text-gray-100 font-sans overflow-hidden">
<!-- Sidebar -->
<aside class="w-20 lg:w-56 bg-white dark:bg-zinc-900 border-r border-gray-200 dark:border-zinc-800 flex flex-col flex-shrink-0">
<aside class="w-20 lg:w-48 bg-white dark:bg-zinc-900 border-r border-gray-200 dark:border-zinc-800 flex flex-col flex-shrink-0">
<div class="p-6 flex items-center gap-3 justify-center lg:justify-start">
<div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white shrink-0">
<Download class="w-5 h-5" />

44
src/splash/App.vue Normal file
View File

@@ -0,0 +1,44 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { Loader2, DownloadCloud, CheckCircle2, AlertCircle } from 'lucide-vue-next'
const status = ref('正在初始化...')
const isError = ref(false)
onMounted(async () => {
try {
status.value = '正在检查运行环境...'
// This command checks and downloads binaries if missing
await invoke('init_ytdlp')
status.value = '准备就绪'
setTimeout(async () => {
await invoke('close_splash')
}, 800)
} catch (e: any) {
status.value = '启动错误: ' + (e.toString() || '未知错误')
isError.value = true
}
})
</script>
<template>
<div class="h-screen w-screen bg-white dark:bg-zinc-900 flex flex-col items-center justify-center select-none cursor-default p-8 text-center overflow-hidden" data-tauri-drag-region>
<div class="mb-6 relative w-20 h-20 bg-blue-600 rounded-2xl shadow-xl flex items-center justify-center text-white">
<DownloadCloud v-if="!isError" class="w-10 h-10" />
<AlertCircle v-else class="w-10 h-10" />
</div>
<h1 class="text-xl font-bold text-zinc-900 dark:text-white mb-6">流萤 - 视频下载</h1>
<div class="flex flex-col items-center gap-3 w-full max-w-xs">
<div class="flex items-center gap-2.5 text-sm font-medium transition-colors duration-300"
:class="isError ? 'text-red-500' : 'text-gray-600 dark:text-gray-300'">
<Loader2 v-if="!isError && status !== '准备就绪'" class="animate-spin w-4 h-4" />
<CheckCircle2 v-if="status === '准备就绪'" class="w-4 h-4 text-green-500" />
<span>{{ status }}</span>
</div>
</div>
</div>
</template>

5
src/splash/main.ts Normal file
View File

@@ -0,0 +1,5 @@
import { createApp } from 'vue'
import App from './App.vue'
import '../style.css'
createApp(App).mount('#app')

View File

@@ -11,11 +11,15 @@ export const useAnalysisStore = defineStore('analysis', () => {
// New state for mix detection
const isMix = ref(false)
const scanMix = ref(false)
// Input mode state
const isBatchMode = ref(false)
const options = ref({
is_audio_only: false,
quality: 'best',
output_path: ''
output_path: '',
output_format: 'original'
})
function toggleEntry(id: string) {
@@ -54,5 +58,5 @@ export const useAnalysisStore = defineStore('analysis', () => {
scanMix.value = false
}
return { url, loading, error, metadata, options, isMix, scanMix, toggleEntry, setAllEntries, invertSelection, reset }
return { url, loading, error, metadata, options, isMix, scanMix, isBatchMode, toggleEntry, setAllEntries, invertSelection, reset }
})

View File

@@ -18,6 +18,7 @@ export const useSettingsStore = defineStore('settings', () => {
const ytdlpVersion = ref('Checking...')
const quickjsVersion = ref('Checking...')
const ffmpegVersion = ref('Checking...')
const isInitializing = ref(true)
async function loadSettings() {
@@ -49,6 +50,7 @@ export const useSettingsStore = defineStore('settings', () => {
console.error(e)
ytdlpVersion.value = 'Error'
quickjsVersion.value = 'Error'
ffmpegVersion.value = 'Error'
} finally {
isInitializing.value = false
}
@@ -57,6 +59,7 @@ export const useSettingsStore = defineStore('settings', () => {
async function refreshVersions() {
ytdlpVersion.value = await invoke('get_ytdlp_version')
quickjsVersion.value = await invoke('get_quickjs_version')
ffmpegVersion.value = await invoke('get_ffmpeg_version')
}
function applyTheme(theme: string) {
@@ -76,5 +79,5 @@ export const useSettingsStore = defineStore('settings', () => {
}
})
return { settings, loadSettings, save, initYtdlp, refreshVersions, ytdlpVersion, quickjsVersion, isInitializing }
return { settings, loadSettings, save, initYtdlp, refreshVersions, ytdlpVersion, quickjsVersion, ffmpegVersion, isInitializing }
})

View File

@@ -54,7 +54,7 @@ onMounted(loadHistory)
<header class="mb-8 flex justify-between items-center">
<div>
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">下载历史</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">管理您的下载记录</p>
<!-- <p class="text-gray-500 dark:text-gray-400 mt-2">管理您的下载记录</p> -->
</div>
<button
@click="clearHistory"

View File

@@ -1,7 +1,7 @@
<script setup lang="ts">
import { watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { Loader2 } from 'lucide-vue-next'
import { Loader2, List, Link } from 'lucide-vue-next'
import { useQueueStore } from '../stores/queue'
import { useSettingsStore } from '../stores/settings'
import { useAnalysisStore } from '../stores/analysis'
@@ -18,6 +18,26 @@ const qualityOptions = [
{ label: '480p', value: '480' },
]
const videoFormatOptions = [
{ label: '原格式', value: 'original' },
{ label: 'MP4', value: 'mp4' },
{ label: 'WebM', value: 'webm' },
{ label: 'Matroska (MKV)', value: 'mkv' },
{ label: 'FLV', value: 'flv' },
{ label: 'AVI', value: 'avi' },
]
const audioFormatOptions = [
{ label: '原格式', value: 'original' },
{ label: 'MP3', value: 'mp3' },
{ label: 'M4A', value: 'm4a' },
{ label: 'AAC', value: 'aac' },
{ label: 'Opus', value: 'opus' },
{ label: 'Vorbis', value: 'vorbis' },
{ label: 'WAV', value: 'wav' },
{ label: 'FLAC', value: 'flac' },
]
// Sync default download path if not set
watch(() => settingsStore.settings.download_path, (newPath) => {
if (newPath && !analysisStore.options.output_path) {
@@ -36,6 +56,43 @@ watch(() => analysisStore.url, (newUrl) => {
}
})
// Reset format to original when toggling audio-only mode
watch(() => analysisStore.options.is_audio_only, () => {
analysisStore.options.output_format = 'original'
})
async function processThumbnail(url: string | undefined): Promise<string | undefined> {
if (!url) return undefined;
// Check if it's an Instagram URL or similar that needs proxying
if (url.includes('instagram.com') || url.includes('fbcdn.net') || url.includes('cdninstagram.com')) {
try {
return await invoke<string>('fetch_image', { url });
} catch (e) {
console.warn('Thumbnail fetch failed, falling back to URL', e);
return url;
}
}
return url;
}
async function processMetadataThumbnails(metadata: any) {
if (!metadata) return;
// Process single video thumbnail
if (metadata.thumbnail) {
metadata.thumbnail = await processThumbnail(metadata.thumbnail);
}
// Process playlist entries
if (metadata.entries && Array.isArray(metadata.entries)) {
await Promise.all(metadata.entries.map(async (entry: any) => {
if (entry.thumbnail) {
entry.thumbnail = await processThumbnail(entry.thumbnail);
}
}));
}
}
async function analyze() {
if (!analysisStore.url) return
analysisStore.loading = true
@@ -43,36 +100,105 @@ async function analyze() {
analysisStore.metadata = null
try {
let urlToScan = analysisStore.url;
let parseMix = false;
if (analysisStore.isBatchMode) {
// Batch Mode Logic
const lines = analysisStore.url.split('\n').map(l => l.trim()).filter(l => l);
const validLinks = lines.filter(l => {
if (!(l.startsWith('http://') || l.startsWith('https://'))) return false;
// Allow if it has NO list param
if (!l.includes('list=')) return true;
if (analysisStore.isMix) {
if (analysisStore.scanMix) {
// Keep URL as is, tell backend to limit scan
parseMix = true;
} else {
// Strip list param
try {
const u = new URL(urlToScan);
u.searchParams.delete('list');
u.searchParams.delete('index');
u.searchParams.delete('start_radio');
urlToScan = u.toString();
} catch (e) {
// Fallback regex if URL parsing fails
urlToScan = urlToScan.replace(/&list=[^&]+/, '');
}
// Allow if it has list param BUT ALSO has v= (video in playlist/mix)
if (l.includes('list=') && l.includes('v=')) return true;
// Otherwise ignore (pure playlist)
return false;
});
if (validLinks.length === 0) {
throw new Error("未找到有效的单个视频链接(已忽略纯播放列表链接)。");
}
}
const res = await invoke<any>('fetch_metadata', { url: urlToScan, parseMixPlaylist: parseMix })
// Initialize selected state for playlist entries
if (res.entries) {
res.entries = res.entries.map((e: any) => ({ ...e, selected: true }))
const results: any[] = [];
// Process sequentially to be safe
for (let link of validLinks) {
try {
// If it's a mix/playlist context (has v= and list=), strip the list param to treat as single video
if (link.includes('list=') && link.includes('v=')) {
try {
const u = new URL(link);
u.searchParams.delete('list');
u.searchParams.delete('index');
u.searchParams.delete('start_radio');
link = u.toString();
} catch (e) {
link = link.replace(/&list=[^&]+/, '');
}
}
// Ensure we don't accidentally trigger mix parsing on single links if logic fails
const res = await invoke<any>('fetch_metadata', { url: link, parseMixPlaylist: false });
// Only add if it's a single video (no entries)
if (!res.entries) {
results.push(res);
}
} catch (e) {
console.warn(`Failed to parse ${link}`, e);
}
}
if (results.length === 0) {
throw new Error("所有链接解析失败或均为播放列表。");
}
// Process thumbnails for batch results
await Promise.all(results.map(r => processMetadataThumbnails(r)));
// Construct synthetic playlist
analysisStore.metadata = {
id: 'batch_download_' + Date.now(),
title: `批量解析结果 (${results.length} 个视频)`,
entries: results.map(e => ({ ...e, selected: true }))
};
} else {
// Single Link Mode
let urlToScan = analysisStore.url;
let parseMix = false;
if (analysisStore.isMix) {
if (analysisStore.scanMix) {
// Keep URL as is, tell backend to limit scan
parseMix = true;
} else {
// Strip list param
try {
const u = new URL(urlToScan);
u.searchParams.delete('list');
u.searchParams.delete('index');
u.searchParams.delete('start_radio');
urlToScan = u.toString();
} catch (e) {
// Fallback regex if URL parsing fails
urlToScan = urlToScan.replace(/&list=[^&]+/, '');
}
}
}
const res = await invoke<any>('fetch_metadata', { url: urlToScan, parseMixPlaylist: parseMix })
await processMetadataThumbnails(res);
// Initialize selected state for playlist entries
if (res.entries) {
res.entries = res.entries.map((e: any) => ({ ...e, selected: true }))
}
analysisStore.metadata = res
}
analysisStore.metadata = res
} catch (e: any) {
analysisStore.error = e.toString()
} finally {
@@ -99,7 +225,7 @@ async function startDownload() {
}
for (const entry of selectedEntries) {
const videoUrl = `https://www.youtube.com/watch?v=${entry.id}`
const videoUrl = entry.url || `https://www.youtube.com/watch?v=${entry.id}`
const id = await invoke<string>('start_download', {
url: videoUrl,
options: analysisStore.options,
@@ -159,31 +285,58 @@ async function startDownload() {
<div class="max-w-5xl mx-auto p-8">
<header class="mb-8">
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">新建下载</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">粘贴 URL 开始下载媒体</p>
<!-- <p class="text-gray-500 dark:text-gray-400 mt-2">粘贴 URL 开始下载媒体</p> -->
</header>
<!-- Input Section -->
<div class="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 mb-8">
<div class="flex gap-4">
<input
v-model="analysisStore.url"
type="text"
placeholder="https://youtube.com/watch?v=..."
class="flex-1 bg-gray-50 dark:bg-zinc-800 border-none rounded-xl px-4 py-3 text-zinc-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
@keyup.enter="analyze"
/>
<button
@click="analyze"
:disabled="analysisStore.loading"
class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-medium transition-colors disabled:opacity-50 flex items-center gap-2 shrink-0"
>
<Loader2 v-if="analysisStore.loading" class="animate-spin w-5 h-5" />
<span v-else>解析</span>
</button>
<!-- Input Area with Batch Toggle -->
<div class="flex flex-col gap-3">
<div class="flex justify-end mb-1">
<button
@click="analysisStore.isBatchMode = !analysisStore.isBatchMode"
class="text-xs font-medium flex items-center gap-1.5 px-3 py-1.5 rounded-lg transition-colors"
:class="analysisStore.isBatchMode ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400' : 'bg-gray-100 text-gray-600 dark:bg-zinc-800 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-zinc-700'"
>
<List v-if="analysisStore.isBatchMode" class="w-3.5 h-3.5" />
<Link v-else class="w-3.5 h-3.5" />
{{ analysisStore.isBatchMode ? '单链接模式' : '批量输入模式' }}
</button>
</div>
<div class="flex gap-4 items-start">
<div class="flex-1 relative">
<textarea
v-if="analysisStore.isBatchMode"
v-model="analysisStore.url"
placeholder="每行输入一个链接..."
rows="5"
class="w-full bg-gray-50 dark:bg-zinc-800 border-none rounded-xl px-4 py-3 text-zinc-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none resize-none font-mono text-sm leading-relaxed"
></textarea>
<input
v-else
v-model="analysisStore.url"
type="text"
placeholder="https://..."
class="w-full bg-gray-50 dark:bg-zinc-800 border-none rounded-xl px-4 py-3 text-zinc-900 dark:text-white focus:ring-2 focus:ring-blue-500 outline-none"
@keyup.enter="analyze"
/>
</div>
<button
@click="analyze"
:disabled="analysisStore.loading"
class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-xl font-medium transition-colors disabled:opacity-50 flex items-center gap-2 shrink-0 h-[48px]"
>
<Loader2 v-if="analysisStore.loading" class="animate-spin w-5 h-5" />
<span v-else>解析</span>
</button>
</div>
</div>
<!-- Mix Toggle -->
<div v-if="analysisStore.isMix" class="mt-4 flex items-center gap-3">
<!-- Mix Toggle (Only in Single Mode) -->
<div v-if="!analysisStore.isBatchMode && analysisStore.isMix" class="mt-4 flex items-center gap-3">
<button
@click="analysisStore.scanMix = !analysisStore.scanMix"
class="w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out flex-shrink-0"
@@ -217,9 +370,9 @@ async function startDownload() {
<!-- Left: Selection Controls -->
<div class="flex items-center gap-2 w-full md:w-auto">
<button @click="analysisStore.setAllEntries(true)" class="text-xs font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">全选</button>
<button @click="analysisStore.setAllEntries(false)" class="text-xs font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">取消全选</button>
<button @click="analysisStore.invertSelection()" class="text-xs font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">反选</button>
<button @click="analysisStore.setAllEntries(true)" class="text-base font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">全选</button>
<button @click="analysisStore.setAllEntries(false)" class="text-base font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">取消全选</button>
<button @click="analysisStore.invertSelection()" class="text-base font-medium px-3 py-1.5 rounded-lg bg-white dark:bg-zinc-700 hover:bg-gray-100 dark:hover:bg-zinc-600 text-zinc-700 dark:text-gray-200 border border-gray-200 dark:border-zinc-600 transition-colors shadow-sm">反选</button>
</div>
<!-- Right: Settings -->
@@ -249,6 +402,16 @@ async function startDownload() {
/>
</div>
</div>
<!-- Format Dropdown -->
<div class="flex items-center gap-3">
<div class="w-48">
<AppSelect
v-model="analysisStore.options.output_format"
:options="analysisStore.options.is_audio_only ? audioFormatOptions : videoFormatOptions"
/>
</div>
</div>
</div>
</div>
</div>
@@ -298,7 +461,7 @@ async function startDownload() {
<p v-if="analysisStore.metadata.entries" class="text-blue-500 mt-1 font-medium">{{ analysisStore.metadata.entries.length }} 个视频 (播放列表)</p>
<!-- Options -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6">
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
<!-- Audio Only Toggle -->
<div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-zinc-800 rounded-xl">
<span class="font-medium text-base">仅音频</span>
@@ -322,6 +485,14 @@ async function startDownload() {
:disabled="analysisStore.options.is_audio_only"
/>
</div>
<!-- Format Dropdown -->
<div class="relative">
<AppSelect
v-model="analysisStore.options.output_format"
:options="analysisStore.options.is_audio_only ? audioFormatOptions : videoFormatOptions"
/>
</div>
</div>
</div>
</div>

View File

@@ -65,7 +65,7 @@ function formatTime(ts: number) {
<div class="flex justify-between items-center mb-6">
<div>
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">运行日志</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">下载任务的实时输出</p>
<!-- <p class="text-gray-500 dark:text-gray-400 mt-2">下载任务的实时输出</p> -->
</div>
<div class="flex items-center gap-3">

View File

@@ -9,6 +9,7 @@ import { format } from 'date-fns' // Import format
const settingsStore = useSettingsStore()
const updatingYtdlp = ref(false)
const updatingQuickjs = ref(false)
const updatingFfmpeg = ref(false)
const updateStatus = ref('')
async function browsePath() {
@@ -52,6 +53,20 @@ async function updateQuickjs() {
}
}
async function updateFfmpeg() {
updatingFfmpeg.value = true
updateStatus.value = '正在更新 FFmpeg...'
try {
const res = await invoke<string>('update_ffmpeg')
updateStatus.value = res
await settingsStore.refreshVersions()
} catch (e: any) {
updateStatus.value = 'FFmpeg 错误:' + e.toString()
} finally {
updatingFfmpeg.value = false
}
}
function setTheme(theme: 'light' | 'dark' | 'system') {
settingsStore.settings.theme = theme
settingsStore.save()
@@ -62,7 +77,7 @@ function setTheme(theme: 'light' | 'dark' | 'system') {
<div class="max-w-3xl mx-auto p-8">
<header class="mb-8">
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">设置</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">配置您的下载偏好</p>
<!-- <p class="text-gray-500 dark:text-gray-400 mt-2">配置您的下载偏好</p> -->
</header>
<div class="space-y-6">
@@ -160,6 +175,29 @@ function setTheme(theme: 'light' | 'dark' | 'system') {
更新
</button>
</div>
<!-- FFmpeg -->
<div class="flex items-center justify-between p-4 bg-gray-50 dark:bg-zinc-800 rounded-xl">
<div class="flex items-center gap-4">
<div class="w-10 h-10 bg-white dark:bg-zinc-700 rounded-lg flex items-center justify-center shadow-sm">
<Terminal class="w-5 h-5 text-purple-600" />
</div>
<div>
<div class="font-medium text-zinc-900 dark:text-white">FFmpeg</div>
<div class="text-xs text-gray-500 mt-0.5 font-mono" :title="settingsStore.ffmpegVersion">
{{ ['Checking...', '未安装', 'Error'].includes(settingsStore.ffmpegVersion) ? settingsStore.ffmpegVersion : '已安装' }}
</div>
</div>
</div>
<button
@click="updateFfmpeg"
:disabled="updatingFfmpeg"
class="text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 px-4 py-2 rounded-lg transition-colors text-sm font-medium flex items-center gap-2 disabled:opacity-50"
>
<RefreshCw class="w-4 h-4" :class="{ 'animate-spin': updatingFfmpeg }" />
更新
</button>
</div>
</div>
<div v-if="updateStatus" class="mt-4 p-3 bg-gray-50 dark:bg-zinc-800 rounded-lg text-xs font-mono text-gray-600 dark:text-gray-400 whitespace-pre-wrap border border-gray-200 dark:border-zinc-700">

View File

@@ -1,5 +1,6 @@
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";
// @ts-expect-error process is a nodejs global
const host = process.env.TAURI_DEV_HOST;
@@ -29,4 +30,12 @@ export default defineConfig(async () => ({
ignored: ["**/src-tauri/**"],
},
},
build: {
rollupOptions: {
input: {
main: resolve(__dirname, 'index.html'),
splashscreen: resolve(__dirname, 'splashscreen.html'),
},
},
},
}));