This commit is contained in:
Julian Freeman
2025-12-02 09:11:59 -04:00
parent f4e264708a
commit a18065de93
23 changed files with 2909 additions and 183 deletions

View File

@@ -10,16 +10,25 @@
"tauri": "tauri" "tauri": "tauri"
}, },
"dependencies": { "dependencies": {
"vue": "^3.5.13",
"@tauri-apps/api": "^2", "@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2" "@tauri-apps/plugin-dialog": "^2.4.2",
"@tauri-apps/plugin-opener": "^2",
"@vueuse/core": "^14.1.0",
"date-fns": "^4.1.0",
"lucide-vue-next": "^0.555.0",
"pinia": "^3.0.4",
"vue": "^3.5.13",
"vue-router": "^4.6.3"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2",
"@vitejs/plugin-vue": "^5.2.1", "@vitejs/plugin-vue": "^5.2.1",
"autoprefixer": "^10.4.22",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.18",
"typescript": "~5.6.2", "typescript": "~5.6.2",
"vite": "^6.0.3", "vite": "^6.0.3",
"vue-tsc": "^2.1.10", "vue-tsc": "^2.1.10"
"@tauri-apps/cli": "^2"
}, },
"packageManager": "pnpm@10.22.0+sha512.bf049efe995b28f527fd2b41ae0474ce29186f7edcb3bf545087bd61fbbebb2bf75362d1307fda09c2d288e1e499787ac12d4fcb617a974718a6051f2eee741c" "packageManager": "pnpm@10.22.0+sha512.bf049efe995b28f527fd2b41ae0474ce29186f7edcb3bf545087bd61fbbebb2bf75362d1307fda09c2d288e1e499787ac12d4fcb617a974718a6051f2eee741c"
} }

790
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

6
postcss.config.js Normal file
View File

@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

142
spec/prd.md Normal file
View File

@@ -0,0 +1,142 @@
# Project: StreamCapture (Tauri + Vue 3 YouTube Downloader)
## 1. Context & Objective
You are an expert Full-Stack Rust/TypeScript developer specializing in Tauri v2 application development.
Your task is to build a cross-platform (Windows & macOS) desktop application named "StreamCapture" in the current directory.
The app is a GUI wrapper for `yt-dlp`, but unlike standard sidecar implementations, it must manage the `yt-dlp` binary externally (in the user's AppData directory) to allow for frequent updates without rebuilding the app.
**Tech Stack:**
- **Core:** Tauri v2 (Rust)
- **Frontend:** Vue 3 (Composition API, `<script setup>`)
- **Build Tool:** Vite
- **Styling:** Tailwind CSS (Mobile-first, Modern UI)
- **State Management:** Pinia
- **Icons:** Lucide-vue-next
- **HTTP Client (Rust):** `reqwest` (for downloading yt-dlp)
---
## 2. Core Architecture & Workflow
### 2.1. External Binary Management (Crucial)
Since `yt-dlp` updates frequently, we **do NOT** bundle it inside the binary.
1. **Location:** The app must utilize the system's local data directory (e.g., `%APPDATA%/StreamCapture/bin` on Windows, `~/Library/Application Support/StreamCapture/bin` on macOS).
2. **Initialization:** On app launch, the Rust backend must check if `yt-dlp` exists in that directory.
3. **Auto-Download:** If missing, download the correct binary from the official GitHub releases (`yt-dlp.exe` for Win, `yt-dlp_macos` for Mac).
4. **Permissions:** On macOS, apply `chmod +x` (0o755) to the downloaded binary immediately.
5. **Execution:** Use Rust's `std::process::Command` to execute this specific binary using its absolute path.
### 2.2. Configuration Persistence
- File: `settings.json` in the app data directory.
- Fields:
- `download_path`: string (Default: System Download Dir)
- `theme`: 'light' | 'dark' | 'system' (Default: system)
- `last_updated`: timestamp (for yt-dlp check)
### 2.3. History Persistence
- File: `history.json`.
- Stores a list of completed or failed downloads (metadata, status, timestamp, file path).
---
## 3. Rust Backend Specifications (`src-tauri/src/lib.rs` & Modules)
Create specific commands to handle logic securely. Avoid exposing raw shell execution to the frontend.
### Module: `ytdlp_manager`
- **`init_ytdlp()`**: Checks existence. If missing, downloads it. Returns status.
- **`update_ytdlp()`**: Runs `yt-dlp -U`.
- **`get_version()`**: Returns current version string.
### Module: `downloader`
- **`fetch_metadata(url: String)`**:
- Runs `yt-dlp --dump-single-json --flat-playlist [url]`.
- **Logic:** If it's a playlist, return a list of video objects (id, title, thumbnail, duration). If single video, return one object.
- **Important:** Do NOT download media yet.
- **`download_video(url: String, options: DownloadOptions)`**:
- **Options Struct:** `{ is_audio_only: bool, quality: String, output_path: String }`
- **Process:** Spawns a command. Emits Tauri Events (`download-progress`) to frontend with percentage and speed.
### Module: `storage`
- Helper functions to read/write `settings.json` and `history.json`.
---
## 4. Frontend Specifications (Vue 3 + Tailwind)
### 4.1. UI Layout
- **Sidebar:** Navigation (Home/Download, History, Settings).
- **Header:** Theme toggle, App status (checking yt-dlp...).
- **Main Content:** Dynamic view based on route.
### 4.2. Views
#### A. Home View (The Downloader)
1. **Input Area:** Large, modern input box for URL. "Analyze" button.
2. **Selection Area (Conditional):**
- Appears after "Analyze" succeeds.
- Shows thumbnail(s) and title(s).
- If Playlist: Show list of items with checkboxes (Select All / Select None).
3. **Options Panel:**
- **Format:** Dropdown (Best Video+Audio, 1080p, 720p, 480p).
- **Mode:** Toggle Switch (Video / Audio Only).
4. **Action:** Big "Download" button.
5. **Progress:** Progress bars for active downloads.
#### B. History View
- Table/List of past downloads.
- Columns: Thumbnail (small), Title, Date, Format, Status (Success/Fail).
- Actions: "Open File Location", "Delete Record" (Icon), "Clear All" (Button at top).
#### C. Settings View
- **Download Path:** Input field + "Browse" button (use Tauri `dialog` API).
- **Yt-dlp:** Show current version. Button "Check for Updates".
- **Theme:** Radio buttons (Light/Dark/System).
### 4.3. State Management (Pinia stores)
- `useSettingsStore`: Loads/saves config. Handles theme applying (adding `.dark` class to `html`).
- `useQueueStore`: Manages active downloads and progress events.
---
## 5. Visual Design Guidelines (Tailwind)
- **Theme:**
- **Light Mode:** White/Gray-50 background, Zinc-900 text, Primary Blue-600.
- **Dark Mode:** Zinc-950 background, Gray-100 text, Primary Blue-500.
- **Components:**
- Rounded corners (`rounded-xl`).
- Subtle shadows (`shadow-sm`, `shadow-md`).
- Input fields with focus rings.
- Transitions for hover states and page switches.
---
## 6. Implementation Steps for Gemini
Please generate the code in the following order. **Ensure all files include `// filepath: ...` comments.**
1. **Rust Setup:**
- `Cargo.toml` (dependencies: reqwest, serde, serde_json, tokio, etc.).
- `src-tauri/src/lib.rs`: Main entry with command registration.
- `src-tauri/src/ytdlp.rs`: The download/update logic.
- `src-tauri/src/commands.rs`: The Tauri commands exposed to frontend.
2. **Frontend Setup:**
- `package.json`: deps (pinia, vue-router, lucide-vue-next, tailwindcss, autoprefixer, postcss).
- `src/style.css`: Tailwind directives.
- `src/stores/...`: Pinia stores.
- `src/components/...`: Reusable UI components (Input, Button, Card).
- `src/views/...`: The main pages.
- `src/App.vue`: Main layout.
3. **Configuration:**
- `tailwind.config.js`: Dark mode config.
- `src-tauri/capabilities/default.json`: **CRITICAL**. Configure permissions to allow accessing `app_data_dir` and the network scope.
## 7. Testing Requirements
- Create a basic Rust test in `src-tauri/src/ytdlp.rs` that verifies it can construct the correct path for the binary based on OS.
- Ensure Vue components handle "Loading" states gracefully (skeletons or spinners).
---
**IMPORTANT NOTE ON PERMISSIONS:**
Since we are using `std::process::Command` directly in Rust, we do not need to configure the strict `shell` scope in `tauri.conf.json`, but we MUST ensure the App Data directory is writable.
Start by generating the Rust backend logic first, as the frontend depends on these commands.

681
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -5,12 +5,7 @@ description = "A Tauri App"
authors = ["you"] authors = ["you"]
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib] [lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "stream_capture_lib" name = "stream_capture_lib"
crate-type = ["staticlib", "cdylib", "rlib"] crate-type = ["staticlib", "cdylib", "rlib"]
@@ -20,6 +15,13 @@ tauri-build = { version = "2", features = [] }
[dependencies] [dependencies]
tauri = { version = "2", features = [] } tauri = { version = "2", features = [] }
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
reqwest = { version = "0.12", features = ["json", "rustls-tls", "stream"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
chrono = { version = "0.4", features = ["serde"] }
futures-util = "0.3"
regex = "1.10"
uuid = { version = "1.0", features = ["v4", "serde"] }

View File

@@ -5,6 +5,7 @@
"windows": ["main"], "windows": ["main"],
"permissions": [ "permissions": [
"core:default", "core:default",
"opener:default" "opener:default",
"dialog:default"
] ]
} }

108
src-tauri/src/commands.rs Normal file
View File

@@ -0,0 +1,108 @@
// filepath: src-tauri/src/commands.rs
use tauri::AppHandle;
use crate::{ytdlp, downloader, storage};
use crate::downloader::DownloadOptions;
use crate::storage::{Settings, HistoryItem};
use uuid::Uuid;
#[tauri::command]
pub async fn init_ytdlp(app: AppHandle) -> Result<bool, String> {
if ytdlp::check_ytdlp(&app) {
return Ok(true);
}
// If not found, try to download
match ytdlp::download_ytdlp(&app).await {
Ok(_) => Ok(true),
Err(e) => Err(format!("Failed to download yt-dlp: {}", e)),
}
}
#[tauri::command]
pub async fn update_ytdlp(app: AppHandle) -> Result<String, String> {
ytdlp::update_ytdlp(&app).await.map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_ytdlp_version(app: AppHandle) -> Result<String, String> {
ytdlp::get_version(&app).map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn fetch_metadata(app: AppHandle, url: String) -> Result<downloader::MetadataResult, String> {
downloader::fetch_metadata(&app, &url).await.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn start_download(app: AppHandle, url: String, options: DownloadOptions, metadata: downloader::VideoMetadata) -> Result<String, String> {
// Generate a task ID
let id = Uuid::new_v4().to_string();
let id_clone = id.clone();
// Spawn the download task
tauri::async_runtime::spawn(async move {
let res = downloader::download_video(app.clone(), id_clone.clone(), url.clone(), options.clone()).await;
let status = if res.is_ok() { "success" } else { "failed" };
// Add to history
let item = HistoryItem {
id: id_clone,
title: metadata.title,
thumbnail: metadata.thumbnail,
url: url,
output_path: format!("{}/", options.output_path), // Rough path, real path is dynamic
timestamp: chrono::Utc::now(),
status: status.to_string(),
format: options.quality,
};
let _ = storage::add_history_item(&app, item);
});
Ok(id)
}
#[tauri::command]
pub fn get_settings(app: AppHandle) -> Result<Settings, String> {
storage::load_settings(&app).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn save_settings(app: AppHandle, settings: Settings) -> Result<(), String> {
storage::save_settings(&app, &settings).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn get_history(app: AppHandle) -> Result<Vec<HistoryItem>, String> {
storage::load_history(&app).map_err(|e| e.to_string())
}
#[tauri::command]
pub fn clear_history(app: AppHandle) -> Result<(), String> {
storage::clear_history(&app).map_err(|e| e.to_string())
}
#[tauri::command]
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 fn open_in_explorer(path: String) -> Result<(), String> {
#[cfg(target_os = "windows")]
{
std::process::Command::new("explorer")
.arg(path)
.spawn()
.map_err(|e| e.to_string())?;
}
#[cfg(target_os = "macos")]
{
std::process::Command::new("open")
.arg(path)
.spawn()
.map_err(|e| e.to_string())?;
}
Ok(())
}

185
src-tauri/src/downloader.rs Normal file
View File

@@ -0,0 +1,185 @@
// filepath: src-tauri/src/downloader.rs
use tauri::{AppHandle, Emitter};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
use std::process::Stdio;
use serde::{Deserialize, Serialize};
use anyhow::{Result, anyhow};
use regex::Regex;
use crate::ytdlp;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VideoMetadata {
pub id: String,
pub title: String,
pub thumbnail: String,
pub duration: Option<f64>,
pub uploader: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PlaylistMetadata {
pub id: String,
pub title: String,
pub entries: Vec<VideoMetadata>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum MetadataResult {
Video(VideoMetadata),
Playlist(PlaylistMetadata),
}
#[derive(Deserialize, Debug, Clone)]
pub struct DownloadOptions {
pub is_audio_only: bool,
pub quality: String, // e.g., "1080", "720", "best"
pub output_path: String, // Directory
}
#[derive(Serialize, Clone, Debug)]
pub struct ProgressEvent {
pub id: String,
pub progress: f64,
pub speed: String,
pub status: String, // "downloading", "processing", "finished", "error"
}
pub async fn fetch_metadata(app: &AppHandle, url: &str) -> Result<MetadataResult> {
let ytdlp_path = ytdlp::get_ytdlp_path(app)?;
// Use std::process for simple output capture if it's short, but tokio is safer for async.
let output = Command::new(ytdlp_path)
.arg("--dump-single-json")
.arg("--flat-playlist")
.arg(url)
// Stop errors from cluttering
.stderr(Stdio::piped())
.output()
.await?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(anyhow!("yt-dlp error: {}", stderr));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let json: serde_json::Value = serde_json::from_str(&stdout)?;
// Check if playlist
if let Some(_type) = json.get("_type") {
if _type == "playlist" {
let entries_json = json["entries"].as_array().ok_or(anyhow!("No entries in playlist"))?;
let mut entries = Vec::new();
for entry in entries_json {
entries.push(parse_video_metadata(entry));
}
return Ok(MetadataResult::Playlist(PlaylistMetadata {
id: json["id"].as_str().unwrap_or("").to_string(),
title: json["title"].as_str().unwrap_or("Unknown Playlist").to_string(),
entries,
}));
}
}
// Single video
Ok(MetadataResult::Video(parse_video_metadata(&json)))
}
fn parse_video_metadata(json: &serde_json::Value) -> VideoMetadata {
VideoMetadata {
id: json["id"].as_str().unwrap_or("").to_string(),
title: json["title"].as_str().unwrap_or("Unknown Title").to_string(),
thumbnail: json["thumbnail"].as_str().unwrap_or("").to_string(), // Note: thumbnails might be an array sometimes, usually string in flat-playlist
duration: json["duration"].as_f64(),
uploader: json["uploader"].as_str().map(|s| s.to_string()),
}
}
pub async fn download_video(
app: AppHandle,
id: String, // Unique ID for this download task (provided by frontend)
url: String,
options: DownloadOptions,
) -> Result<String> {
let ytdlp_path = ytdlp::get_ytdlp_path(&app)?;
let mut args = Vec::new();
args.push(url);
// Output template
let output_template = format!("{}/%(title)s.%(ext)s", options.output_path.trim_end_matches(std::path::MAIN_SEPARATOR));
args.push("-o".to_string());
args.push(output_template);
// Formats
if options.is_audio_only {
args.push("-x".to_string());
args.push("--audio-format".to_string());
args.push("mp3".to_string()); // Defaulting to mp3 for simplicity
} else {
let format_arg = if options.quality == "best" {
"bestvideo+bestaudio/best".to_string()
} else {
format!("bestvideo[height<={}]+bestaudio/best[height<={}]", options.quality, options.quality)
};
args.push("-f".to_string());
args.push(format_arg);
}
// Progress output
args.push("--newline".to_string()); // Easier parsing
let mut child = Command::new(ytdlp_path)
.args(&args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let stdout = child.stdout.take().ok_or(anyhow!("Failed to open stdout"))?;
let mut reader = BufReader::new(stdout);
let mut line = String::new();
// Regex for progress: [download] 42.5% of 10.00MiB at 2.00MiB/s ETA 00:05
let re = Regex::new(r"\[download\]\s+(\d+\.?\d*)%").unwrap();
while reader.read_line(&mut line).await? > 0 {
if let Some(caps) = re.captures(&line) {
if let Some(pct_match) = caps.get(1) {
if let Ok(pct) = pct_match.as_str().parse::<f64>() {
// Emit event
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: pct,
speed: "TODO".to_string(), // Speed parsing is a bit more complex, skipping for MVP or adding regex for it
status: "downloading".to_string(),
}).ok();
}
}
}
line.clear();
}
let status = child.wait().await?;
if status.success() {
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: 100.0,
speed: "-".to_string(),
status: "finished".to_string(),
}).ok();
Ok("Download complete".to_string())
} else {
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: 0.0,
speed: "-".to_string(),
status: "error".to_string(),
}).ok();
Err(anyhow!("Download process failed"))
}
}

View File

@@ -1,14 +1,27 @@
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/ // filepath: src-tauri/src/lib.rs
#[tauri::command] mod ytdlp;
fn greet(name: &str) -> String { mod downloader;
format!("Hello, {}! You've been greeted from Rust!", name) mod storage;
} mod commands;
#[cfg_attr(mobile, tauri::mobile_entry_point)] #[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
.plugin(tauri_plugin_opener::init()) .plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![greet]) .plugin(tauri_plugin_dialog::init())
.invoke_handler(tauri::generate_handler![
commands::init_ytdlp,
commands::update_ytdlp,
commands::get_ytdlp_version,
commands::fetch_metadata,
commands::start_download,
commands::get_settings,
commands::save_settings,
commands::get_history,
commands::clear_history,
commands::delete_history_item,
commands::open_in_explorer
])
.run(tauri::generate_context!()) .run(tauri::generate_context!())
.expect("error while running tauri application"); .expect("error while running tauri application");
} }

116
src-tauri/src/storage.rs Normal file
View File

@@ -0,0 +1,116 @@
// filepath: src-tauri/src/storage.rs
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use tauri::{AppHandle, Manager};
use anyhow::Result;
use chrono::{DateTime, Utc};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Settings {
pub download_path: String,
pub theme: String, // 'light', 'dark', 'system'
pub last_updated: Option<DateTime<Utc>>,
}
impl Default for Settings {
fn default() -> Self {
// We'll resolve the actual download path at runtime if empty,
// but for default struct we can keep it empty or a placeholder.
Self {
download_path: "".to_string(),
theme: "system".to_string(),
last_updated: None,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HistoryItem {
pub id: String,
pub title: String,
pub thumbnail: String,
pub url: String,
pub output_path: String,
pub timestamp: DateTime<Utc>,
pub status: String, // "success", "failed"
pub format: String,
}
pub fn get_app_data_dir(app: &AppHandle) -> Result<PathBuf> {
// In Tauri v2, we use app.path().app_data_dir()
let path = app.path().app_data_dir()?;
if !path.exists() {
fs::create_dir_all(&path)?;
}
Ok(path)
}
pub fn get_settings_path(app: &AppHandle) -> Result<PathBuf> {
Ok(get_app_data_dir(app)?.join("settings.json"))
}
pub fn get_history_path(app: &AppHandle) -> Result<PathBuf> {
Ok(get_app_data_dir(app)?.join("history.json"))
}
pub fn load_settings(app: &AppHandle) -> Result<Settings> {
let path = get_settings_path(app)?;
if path.exists() {
let content = fs::read_to_string(&path)?;
let settings: Settings = serde_json::from_str(&content)?;
return Ok(settings);
}
// If not exists, return default.
// Note: We might want to set a default download path here if possible.
let mut settings = Settings::default();
if let Ok(download_dir) = app.path().download_dir() {
settings.download_path = download_dir.to_string_lossy().to_string();
}
Ok(settings)
}
pub fn save_settings(app: &AppHandle, settings: &Settings) -> Result<()> {
let path = get_settings_path(app)?;
let content = serde_json::to_string_pretty(settings)?;
fs::write(path, content)?;
Ok(())
}
pub fn load_history(app: &AppHandle) -> Result<Vec<HistoryItem>> {
let path = get_history_path(app)?;
if path.exists() {
let content = fs::read_to_string(&path)?;
let history: Vec<HistoryItem> = serde_json::from_str(&content)?;
Ok(history)
} else {
Ok(Vec::new())
}
}
pub fn save_history(app: &AppHandle, history: &[HistoryItem]) -> Result<()> {
let path = get_history_path(app)?;
let content = serde_json::to_string_pretty(history)?;
fs::write(path, content)?;
Ok(())
}
pub fn add_history_item(app: &AppHandle, item: HistoryItem) -> Result<()> {
let mut history = load_history(app)?;
// Prepend
history.insert(0, item);
save_history(app, &history)?;
Ok(())
}
pub fn clear_history(app: &AppHandle) -> Result<()> {
save_history(app, &[])
}
pub fn delete_history_item(app: &AppHandle, id: &str) -> Result<()> {
let mut history = load_history(app)?;
history.retain(|item| item.id != id);
save_history(app, &history)?;
Ok(())
}

140
src-tauri/src/ytdlp.rs Normal file
View File

@@ -0,0 +1,140 @@
// filepath: src-tauri/src/ytdlp.rs
use std::fs;
use std::path::PathBuf;
use tauri::AppHandle;
use anyhow::{Result, anyhow};
#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;
use crate::storage::{self};
const REPO_URL: &str = "https://github.com/yt-dlp/yt-dlp/releases/latest/download";
pub fn get_binary_name() -> &'static str {
if cfg!(target_os = "windows") {
"yt-dlp.exe"
} else if cfg!(target_os = "macos") {
"yt-dlp_macos"
} else {
"yt-dlp"
}
}
// Helper for testing
pub fn get_ytdlp_path_from_dir(base_dir: &PathBuf) -> PathBuf {
base_dir.join("bin").join(get_binary_name())
}
pub fn get_ytdlp_path(app: &AppHandle) -> Result<PathBuf> {
let app_data = storage::get_app_data_dir(app)?;
// Use helper
Ok(get_ytdlp_path_from_dir(&app_data))
}
pub fn check_ytdlp(app: &AppHandle) -> bool {
match get_ytdlp_path(app) {
Ok(path) => path.exists(),
Err(_) => false,
}
}
pub async fn download_ytdlp(app: &AppHandle) -> Result<PathBuf> {
let binary_name = get_binary_name();
let url = format!("{}/{}", REPO_URL, binary_name);
let response = reqwest::get(&url).await?;
if !response.status().is_success() {
return Err(anyhow!("Failed to download yt-dlp: Status {}", response.status()));
}
let bytes = response.bytes().await?;
let path = get_ytdlp_path(app)?;
// Ensure parent directory exists
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, bytes)?;
// Set permissions on Unix
#[cfg(target_family = "unix")]
{
let mut perms = fs::metadata(&path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&path, perms)?;
}
// Update settings with timestamp
let mut settings = storage::load_settings(app)?;
settings.last_updated = Some(chrono::Utc::now());
storage::save_settings(app, &settings)?;
Ok(path)
}
pub async fn update_ytdlp(app: &AppHandle) -> Result<String> {
let path = get_ytdlp_path(app)?;
if !path.exists() {
download_ytdlp(app).await?;
return Ok("Downloaded fresh copy".to_string());
}
let output = std::process::Command::new(&path)
.arg("-U")
.output()?;
if output.status.success() {
// Update settings timestamp
let mut settings = storage::load_settings(app)?;
settings.last_updated = Some(chrono::Utc::now());
storage::save_settings(app, &settings)?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
Ok(stdout)
} else {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
Err(anyhow!("Update failed: {}", stderr))
}
}
pub fn get_version(app: &AppHandle) -> Result<String> {
let path = get_ytdlp_path(app)?;
if !path.exists() {
return Ok("Not installed".to_string());
}
let output = std::process::Command::new(&path)
.arg("--version")
.output()?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
Ok("Unknown".to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn test_binary_name() {
let name = get_binary_name();
if cfg!(target_os = "windows") {
assert_eq!(name, "yt-dlp.exe");
} else if cfg!(target_os = "macos") {
assert_eq!(name, "yt-dlp_macos");
}
}
#[test]
fn test_path_construction() {
let base = PathBuf::from("/tmp/app");
let path = get_ytdlp_path_from_dir(&base);
let name = get_binary_name();
assert_eq!(path, base.join("bin").join(name));
}
}

View File

@@ -13,8 +13,8 @@
"windows": [ "windows": [
{ {
"title": "stream-capture", "title": "stream-capture",
"width": 800, "width": 1200,
"height": 600 "height": 800
} }
], ],
"security": { "security": {

View File

@@ -1,160 +1,70 @@
// filepath: src/App.vue
<script setup lang="ts"> <script setup lang="ts">
import { ref } from "vue"; import { onMounted } from 'vue'
import { invoke } from "@tauri-apps/api/core"; import { RouterView, RouterLink, useRoute } from 'vue-router'
import { Home, History, Settings as SettingsIcon, Download } from 'lucide-vue-next'
import { useSettingsStore } from './stores/settings'
import { useQueueStore } from './stores/queue'
const greetMsg = ref(""); const settingsStore = useSettingsStore()
const name = ref(""); const queueStore = useQueueStore()
const route = useRoute()
async function greet() { onMounted(async () => {
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/ await settingsStore.loadSettings()
greetMsg.value = await invoke("greet", { name: name.value }); await settingsStore.initYtdlp()
} await queueStore.initListener()
})
</script> </script>
<template> <template>
<main class="container"> <div class="flex h-screen bg-gray-50 dark:bg-zinc-950 text-zinc-900 dark:text-gray-100 font-sans overflow-hidden">
<h1>Welcome to Tauri + Vue</h1> <!-- Sidebar -->
<aside class="w-20 lg:w-64 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" />
</div>
<span class="font-bold text-lg hidden lg:block">StreamCapture</span>
</div>
<div class="row"> <nav class="flex-1 px-4 space-y-2 mt-4">
<a href="https://vite.dev" target="_blank"> <RouterLink to="/"
<img src="/vite.svg" class="logo vite" alt="Vite logo" /> class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
</a> :class="route.path === '/' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
<a href="https://tauri.app" target="_blank"> >
<img src="/tauri.svg" class="logo tauri" alt="Tauri logo" /> <Home class="w-5 h-5 shrink-0" />
</a> <span class="hidden lg:block font-medium">Downloader</span>
<a href="https://vuejs.org/" target="_blank"> </RouterLink>
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
</a> <RouterLink to="/history"
</div> class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
<p>Click on the Tauri, Vite, and Vue logos to learn more.</p> :class="route.path === '/history' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
>
<History class="w-5 h-5 shrink-0" />
<span class="hidden lg:block font-medium">History</span>
</RouterLink>
<form class="row" @submit.prevent="greet"> <RouterLink to="/settings"
<input id="greet-input" v-model="name" placeholder="Enter a name..." /> class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
<button type="submit">Greet</button> :class="route.path === '/settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
</form> >
<p>{{ greetMsg }}</p> <SettingsIcon class="w-5 h-5 shrink-0" />
</main> <span class="hidden lg:block font-medium">Settings</span>
</RouterLink>
</nav>
<div class="p-4 border-t border-gray-200 dark:border-zinc-800">
<div class="text-xs text-gray-400 text-center lg:text-left truncate">
<p v-if="settingsStore.isInitializing">Initializing...</p>
<p v-else>v{{ settingsStore.ytdlpVersion }}</p>
</div>
</div>
</aside>
<!-- Main Content -->
<main class="flex-1 overflow-auto bg-gray-50 dark:bg-zinc-950 relative">
<RouterView />
</main>
</div>
</template> </template>
<style scoped>
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #249b73);
}
</style>
<style>
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}
</style>

View File

@@ -1,4 +1,10 @@
import { createApp } from "vue"; import { createApp } from "vue";
import { createPinia } from "pinia";
import router from "./router";
import App from "./App.vue"; import App from "./App.vue";
import "./style.css";
createApp(App).mount("#app"); const app = createApp(App);
app.use(createPinia());
app.use(router);
app.mount("#app");

27
src/router/index.ts Normal file
View File

@@ -0,0 +1,27 @@
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import History from '../views/History.vue'
import Settings from '../views/Settings.vue'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/history',
name: 'history',
component: History
},
{
path: '/settings',
name: 'settings',
component: Settings
}
]
})
export default router

47
src/stores/queue.ts Normal file
View File

@@ -0,0 +1,47 @@
// filepath: src/stores/queue.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listen } from '@tauri-apps/api/event'
export interface DownloadTask {
id: string
title: string
thumbnail: string
progress: number
speed: string
status: 'pending' | 'downloading' | 'finished' | 'error'
}
interface ProgressEvent {
id: string
progress: number
speed: string
status: string
}
export const useQueueStore = defineStore('queue', () => {
const tasks = ref<DownloadTask[]>([])
const isListening = ref(false)
function addTask(task: DownloadTask) {
tasks.value.push(task)
}
async function initListener() {
if (isListening.value) return
isListening.value = true
await listen<ProgressEvent>('download-progress', (event) => {
const { id, progress, speed, status } = event.payload
const task = tasks.value.find(t => t.id === id)
if (task) {
task.progress = progress
task.speed = speed
// Map status string to type if needed, or just assign
task.status = status as any
}
})
}
return { tasks, addTask, initListener }
})

73
src/stores/settings.ts Normal file
View File

@@ -0,0 +1,73 @@
// filepath: src/stores/settings.ts
import { defineStore } from 'pinia'
import { invoke } from '@tauri-apps/api/core'
import { ref } from 'vue'
export interface Settings {
download_path: string
theme: 'light' | 'dark' | 'system'
last_updated: string | null
}
export const useSettingsStore = defineStore('settings', () => {
const settings = ref<Settings>({
download_path: '',
theme: 'system',
last_updated: null
})
const ytdlpVersion = ref('Checking...')
const isInitializing = ref(true)
async function loadSettings() {
try {
const s = await invoke<Settings>('get_settings')
settings.value = s
applyTheme(s.theme)
} catch (e) {
console.error("Failed to load settings", e)
}
}
async function save() {
try {
await invoke('save_settings', { settings: settings.value })
applyTheme(settings.value.theme)
} catch (e) {
console.error("Failed to save settings", e)
}
}
async function initYtdlp() {
try {
isInitializing.value = true
// check/download
await invoke('init_ytdlp')
ytdlpVersion.value = await invoke('get_ytdlp_version')
} catch (e) {
console.error(e)
ytdlpVersion.value = 'Error'
} finally {
isInitializing.value = false
}
}
function applyTheme(theme: string) {
const root = document.documentElement
const isDark = theme === 'dark' || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
if (isDark) {
root.classList.add('dark')
} else {
root.classList.remove('dark')
}
}
// Watch system preference changes if theme is system
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (settings.value.theme === 'system') {
applyTheme('system')
}
})
return { settings, loadSettings, save, initYtdlp, ytdlpVersion, isInitializing }
})

8
src/style.css Normal file
View File

@@ -0,0 +1,8 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom styles if needed */
body {
@apply bg-gray-50 text-zinc-900 dark:bg-zinc-950 dark:text-gray-100 transition-colors duration-300;
}

141
src/views/History.vue Normal file
View File

@@ -0,0 +1,141 @@
// filepath: src/views/History.vue
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { Trash2, FolderOpen } from 'lucide-vue-next'
import { formatDistanceToNow } from 'date-fns'
interface HistoryItem {
id: string
title: string
thumbnail: string
url: string
output_path: string
timestamp: string
status: string
format: string
}
const history = ref<HistoryItem[]>([])
async function loadHistory() {
try {
const res = await invoke<HistoryItem[]>('get_history')
// Sort by timestamp desc
history.value = res.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
} catch (e) {
console.error(e)
}
}
async function clearHistory() {
if(confirm('Clear all download history?')) {
await invoke('clear_history')
history.value = []
}
}
async function deleteItem(id: string) {
if(confirm('Delete this history record? (File will not be deleted)')) {
try {
await invoke('delete_history_item', { id })
history.value = history.value.filter(h => h.id !== id)
} catch (e) {
console.error(e)
}
}
}
async function openFolder(path: string) {
await invoke('open_in_explorer', { path })
}
onMounted(loadHistory)
</script>
<template>
<div class="max-w-5xl mx-auto p-8">
<header class="mb-8 flex justify-between items-center">
<div>
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">Download History</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">Manage your past downloads.</p>
</div>
<button
@click="clearHistory"
v-if="history.length > 0"
class="text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 px-4 py-2 rounded-lg transition-colors text-sm font-medium flex items-center gap-2"
>
<Trash2 class="w-4 h-4" />
Clear All
</button>
</header>
<div v-if="history.length === 0" class="text-center py-20">
<div class="bg-gray-100 dark:bg-zinc-900 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
<FolderOpen class="w-8 h-8 text-gray-400" />
</div>
<h3 class="text-lg font-medium text-zinc-900 dark:text-white">No downloads yet</h3>
<p class="text-gray-500">Your download history will appear here.</p>
</div>
<div v-else class="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-left">
<thead class="bg-gray-50 dark:bg-zinc-800/50 text-xs uppercase text-gray-500 font-medium">
<tr>
<th class="px-6 py-4">Media</th>
<th class="px-6 py-4">Date</th>
<th class="px-6 py-4">Format</th>
<th class="px-6 py-4">Status</th>
<th class="px-6 py-4 text-right">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-100 dark:divide-zinc-800">
<tr v-for="item in history" :key="item.id" class="hover:bg-gray-50 dark:hover:bg-zinc-800/50 transition-colors">
<td class="px-6 py-4">
<div class="flex items-center gap-4">
<img :src="item.thumbnail || '/placeholder.png'" class="w-12 h-12 rounded-lg object-cover bg-gray-200" />
<div class="max-w-xs">
<div class="font-medium text-zinc-900 dark:text-white truncate" :title="item.title">{{ item.title }}</div>
<div class="text-xs text-gray-500 truncate">{{ item.url }}</div>
</div>
</div>
</td>
<td class="px-6 py-4 text-sm text-gray-500 whitespace-nowrap">
{{ formatDistanceToNow(new Date(item.timestamp), { addSuffix: true }) }}
</td>
<td class="px-6 py-4 text-sm text-gray-500">
<span class="bg-gray-100 dark:bg-zinc-800 px-2 py-1 rounded text-xs font-mono">{{ item.format }}</span>
</td>
<td class="px-6 py-4">
<span
class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium"
:class="item.status === 'success' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'"
>
<span class="w-1.5 h-1.5 rounded-full" :class="item.status === 'success' ? 'bg-green-500' : 'bg-red-500'"></span>
{{ item.status === 'success' ? 'Completed' : 'Failed' }}
</span>
</td>
<td class="px-6 py-4 text-right whitespace-nowrap">
<button
@click="openFolder(item.output_path)"
class="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-lg transition-colors"
title="Open Output Folder"
>
<FolderOpen class="w-4 h-4" />
</button>
<button
@click="deleteItem(item.id)"
class="p-2 text-gray-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors ml-1"
title="Delete Record"
>
<Trash2 class="w-4 h-4" />
</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</template>

208
src/views/Home.vue Normal file
View File

@@ -0,0 +1,208 @@
// filepath: src/views/Home.vue
<script setup lang="ts">
import { ref, watch } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { Loader2, ChevronDown } from 'lucide-vue-next'
import { useQueueStore } from '../stores/queue'
import { useSettingsStore } from '../stores/settings'
const queueStore = useQueueStore()
const settingsStore = useSettingsStore()
const url = ref('')
const loading = ref(false)
const error = ref('')
const metadata = ref<any>(null)
const options = ref({
is_audio_only: false,
quality: 'best',
output_path: ''
})
watch(() => settingsStore.settings.download_path, (newPath) => {
if (newPath) options.value.output_path = newPath
}, { immediate: true })
async function analyze() {
if (!url.value) return
loading.value = true
error.value = ''
metadata.value = null
try {
const res = await invoke('fetch_metadata', { url: url.value })
// Handle playlist vs single video
// For MVP, if playlist, just take the playlist info, or first entry?
// The rust struct MetadataResult handles both.
// Let's assume single video for simpler UI for now, or just show title.
metadata.value = res
// If it's a playlist, metadata might have 'entries'.
// For now we treat it generically.
} catch (e: any) {
error.value = e.toString()
} finally {
loading.value = false
}
}
async function startDownload() {
if (!metadata.value) return
// Use settings path if options is empty
if (!options.value.output_path) {
options.value.output_path = settingsStore.settings.download_path
}
try {
// We need to pass metadata to backend to create history item immediately if we want,
// but backend command signature is `start_download(app, url, options, metadata)`
// Prepare metadata object for the command
// If it's a playlist, we might need to handle differently.
// Let's assume simpler case: pass the main metadata object.
// Flatten metadata if it's a wrapper
const metaToSend = metadata.value.entries ?
{ title: metadata.value.title, thumbnail: "", id: metadata.value.id } : // Playlist
metadata.value; // Video
const id = await invoke<string>('start_download', {
url: url.value,
options: options.value,
metadata: metaToSend
})
// Add to queue store immediately for UI
queueStore.addTask({
id,
title: metaToSend.title,
thumbnail: metaToSend.thumbnail,
progress: 0,
speed: 'Pending...',
status: 'pending'
})
// Reset
url.value = ''
metadata.value = null
} catch (e: any) {
error.value = "Download failed to start: " + e.toString()
}
}
</script>
<template>
<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">New Download</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">Paste a URL to start downloading media.</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="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="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="loading" class="animate-spin w-5 h-5" />
<span v-else>Analyze</span>
</button>
</div>
<p v-if="error" class="mt-3 text-red-500 text-sm">{{ error }}</p>
</div>
<!-- Analysis Result -->
<div v-if="metadata" class="bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 overflow-hidden mb-8">
<div class="p-6 flex flex-col md:flex-row gap-6">
<!-- Thumbnail -->
<img :src="metadata.thumbnail || '/placeholder.png'" class="w-full md:w-64 aspect-video object-cover rounded-lg bg-gray-100 dark:bg-zinc-800" />
<!-- Details -->
<div class="flex-1">
<h2 class="text-xl font-bold text-zinc-900 dark:text-white line-clamp-2">{{ metadata.title }}</h2>
<p v-if="metadata.uploader" class="text-gray-500 dark:text-gray-400 mt-1">{{ metadata.uploader }}</p>
<p v-if="metadata.entries" class="text-blue-500 mt-1 font-medium">{{ metadata.entries.length }} videos in playlist</p>
<!-- Options -->
<div class="grid grid-cols-1 md:grid-cols-2 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-sm">Audio Only</span>
<button
@click="options.is_audio_only = !options.is_audio_only"
class="w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out"
:class="options.is_audio_only ? 'bg-blue-600' : 'bg-gray-300 dark:bg-zinc-600'"
>
<span
class="absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform duration-200"
:class="options.is_audio_only ? 'translate-x-6' : 'translate-x-0'"
/>
</button>
</div>
<!-- Quality Dropdown -->
<div class="relative">
<select
v-model="options.quality"
class="w-full appearance-none 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"
:disabled="options.is_audio_only"
>
<option value="best">Best Quality</option>
<option value="1080">1080p</option>
<option value="720">720p</option>
<option value="480">480p</option>
</select>
<ChevronDown class="absolute right-4 top-3.5 w-5 h-5 text-gray-400 pointer-events-none" />
</div>
</div>
</div>
</div>
<div class="px-6 py-4 bg-gray-50 dark:bg-zinc-800/50 border-t border-gray-200 dark:border-zinc-800 flex justify-end">
<button
@click="startDownload"
class="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-xl font-bold transition-colors shadow-lg shadow-blue-600/20"
>
Download Now
</button>
</div>
</div>
<!-- Active Downloads -->
<div v-if="queueStore.tasks.length > 0">
<h3 class="text-lg font-bold mb-4">Active Downloads</h3>
<div class="space-y-3">
<!-- Reversed to show newest first -->
<div v-for="task in queueStore.tasks.slice().reverse()" :key="task.id" class="bg-white dark:bg-zinc-900 p-4 rounded-xl border border-gray-200 dark:border-zinc-800 flex items-center gap-4">
<img :src="task.thumbnail || '/placeholder.png'" class="w-16 h-16 object-cover rounded-lg bg-gray-100 dark:bg-zinc-800" />
<div class="flex-1 min-w-0">
<div class="flex justify-between mb-1">
<h4 class="font-medium truncate pr-4">{{ task.title }}</h4>
<span class="text-xs font-mono text-gray-500 whitespace-nowrap">
{{ task.status === 'finished' ? 'Completed' : (task.status === 'error' ? 'Failed' : task.speed) }}
</span>
</div>
<div class="h-2 bg-gray-100 dark:bg-zinc-800 rounded-full overflow-hidden">
<div
class="h-full transition-all duration-300"
:style="{ width: `${task.progress}%` }"
:class="task.status === 'error' ? 'bg-red-500' : (task.status === 'finished' ? 'bg-green-500' : 'bg-blue-600')"
/>
</div>
</div>
</div>
</div>
</div>
</div>
</template>

125
src/views/Settings.vue Normal file
View File

@@ -0,0 +1,125 @@
// filepath: src/views/Settings.vue
<script setup lang="ts">
import { ref } from 'vue'
import { useSettingsStore } from '../stores/settings'
import { invoke } from '@tauri-apps/api/core'
import { open } from '@tauri-apps/plugin-dialog'
import { Folder, RefreshCw, Monitor, Sun, Moon } from 'lucide-vue-next'
const settingsStore = useSettingsStore()
const updating = ref(false)
const updateStatus = ref('')
async function browsePath() {
const selected = await open({
directory: true,
multiple: false,
defaultPath: settingsStore.settings.download_path
})
if (selected) {
settingsStore.settings.download_path = selected as string
await settingsStore.save()
}
}
async function updateYtdlp() {
updating.value = true
updateStatus.value = 'Checking...'
try {
const res = await invoke<string>('update_ytdlp')
updateStatus.value = res
await settingsStore.initYtdlp()
} catch (e: any) {
updateStatus.value = 'Error: ' + e.toString()
} finally {
updating.value = false
}
}
function setTheme(theme: 'light' | 'dark' | 'system') {
settingsStore.settings.theme = theme
settingsStore.save()
}
</script>
<template>
<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">Settings</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">Configure your download preferences.</p>
</header>
<div class="space-y-6">
<!-- Download Path -->
<section class="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800">
<h2 class="text-lg font-bold mb-4 text-zinc-900 dark:text-white">Download Location</h2>
<div class="flex gap-3">
<div class="flex-1 bg-gray-50 dark:bg-zinc-800 rounded-xl px-4 py-3 text-sm text-gray-600 dark:text-gray-300 font-mono truncate border border-transparent focus-within:border-blue-500 transition-colors">
{{ settingsStore.settings.download_path || 'Not set (using defaults)' }}
</div>
<button
@click="browsePath"
class="bg-gray-100 hover:bg-gray-200 dark:bg-zinc-800 dark:hover:bg-zinc-700 text-zinc-900 dark:text-white px-4 py-3 rounded-xl font-medium transition-colors flex items-center gap-2"
>
<Folder class="w-5 h-5" />
Browse
</button>
</div>
</section>
<!-- Theme -->
<section class="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800">
<h2 class="text-lg font-bold mb-4 text-zinc-900 dark:text-white">Appearance</h2>
<div class="grid grid-cols-3 gap-4">
<button
@click="setTheme('light')"
class="flex flex-col items-center gap-3 p-4 rounded-xl border-2 transition-all"
:class="settingsStore.settings.theme === 'light' ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-600' : 'border-transparent bg-gray-50 dark:bg-zinc-800 text-gray-500 hover:bg-gray-100 dark:hover:bg-zinc-700'"
>
<Sun class="w-6 h-6" />
<span class="font-medium">Light</span>
</button>
<button
@click="setTheme('dark')"
class="flex flex-col items-center gap-3 p-4 rounded-xl border-2 transition-all"
:class="settingsStore.settings.theme === 'dark' ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-600' : 'border-transparent bg-gray-50 dark:bg-zinc-800 text-gray-500 hover:bg-gray-100 dark:hover:bg-zinc-700'"
>
<Moon class="w-6 h-6" />
<span class="font-medium">Dark</span>
</button>
<button
@click="setTheme('system')"
class="flex flex-col items-center gap-3 p-4 rounded-xl border-2 transition-all"
:class="settingsStore.settings.theme === 'system' ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/20 text-blue-600' : 'border-transparent bg-gray-50 dark:bg-zinc-800 text-gray-500 hover:bg-gray-100 dark:hover:bg-zinc-700'"
>
<Monitor class="w-6 h-6" />
<span class="font-medium">System</span>
</button>
</div>
</section>
<!-- yt-dlp Management -->
<section class="bg-white dark:bg-zinc-900 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800">
<div class="flex justify-between items-start">
<div>
<h2 class="text-lg font-bold mb-1 text-zinc-900 dark:text-white">Binary Management</h2>
<p class="text-sm text-gray-500">Current Version: <span class="font-mono text-zinc-700 dark:text-gray-300">{{ settingsStore.ytdlpVersion }}</span></p>
<p class="text-xs text-gray-400 mt-1">Last Updated: {{ settingsStore.settings.last_updated ? new Date(settingsStore.settings.last_updated).toLocaleDateString() : 'Never' }}</p>
</div>
<button
@click="updateYtdlp"
:disabled="updating"
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': updating }" />
Check for Updates
</button>
</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">
{{ updateStatus }}
</div>
</section>
</div>
</div>
</template>

12
tailwind.config.js Normal file
View File

@@ -0,0 +1,12 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}",
],
darkMode: 'class',
theme: {
extend: {},
},
plugins: [],
}