Compare commits

..

10 Commits

Author SHA1 Message Date
Julian Freeman
94fa286f30 take notes 2025-12-02 13:50:22 -04:00
Julian Freeman
aacf765666 change quickjs to upstream one 2025-12-02 13:30:16 -04:00
Julian Freeman
4daba48b1f fix quickjs bug 1 2025-12-02 12:15:35 -04:00
Julian Freeman
97e869c037 fix quickjs manage 2025-12-02 12:07:21 -04:00
Julian Freeman
320c95041a add quickjs but has bugs 2025-12-02 11:59:30 -04:00
Julian Freeman
38ad2e64cc fix sidebar ui 2025-12-02 11:08:38 -04:00
Julian Freeman
c63b03b083 ignore download progress log 2025-12-02 11:03:00 -04:00
Julian Freeman
a04b0f4be1 fix logging style 2025-12-02 10:50:15 -04:00
Julian Freeman
d2cafc328f add logging 2025-12-02 10:44:14 -04:00
Julian Freeman
068bc1c79e trying parse different url, but failed 2025-12-02 10:29:39 -04:00
21 changed files with 1275 additions and 229 deletions

View File

@@ -3,3 +3,10 @@
A simple Youtube downloader.
Generated by Gemini CLI.
## Problems
1. windows 上打包后运行命令会出现黑窗,而且还是会出现找不到 js-runtimes 的问题,但是 quickjs 是正常下载了
2. macos 上未测试
3. 增加日志内容,除了下载日志,把运行日志,包括调用的完整命令也输出一下
4. 解析多视频还是有问题,不显示视频列表,缩略图也不对

58
spec/logging_feature.md Normal file
View File

@@ -0,0 +1,58 @@
# Feature Request: Real-time Logging & UI Refinement
## 1. Context & Objective
Users currently experience download failures without sufficient context or error details, making troubleshooting difficult.
The objective is to introduce a dedicated **Logs System** within the application to capture, display, and persist detailed execution logs from the `yt-dlp` process.
Additionally, the application's sidebar layout requires balancing for better UX.
## 2. Requirements
### 2.1. Backend (Rust) - Logging Infrastructure
* **Stream Capture**: The `downloader` module must capture both `STDOUT` (progress) and `STDERR` (errors/warnings) from the `yt-dlp` process.
* **Event Emission**: Emit a new Tauri event `download-log` to the frontend in real-time.
* Payload: `{ id: String, message: String, level: 'info' | 'error' | 'debug' }`
* **Persistence (Optional but Recommended)**: Ideally, write logs to a local file (e.g., `logs/{date}.log` or `logs/{task_id}.log`) for post-mortem analysis. *For this iteration, real-time event emission is priority.*
### 2.2. Frontend - Logs View
* **New Route**: `/logs`
* **UI Layout**:
* A dedicated **Logs Tab** in the main navigation.
* A console-like view displaying a stream of log messages.
* Filters: Filter by "Task ID" or "Level" (Error/Info).
* **Real-time**: The view must update automatically as new log events arrive.
* **Detail**: Failed downloads must show the specific error message returned by `yt-dlp` (e.g., "Sign in required", "Video unavailable").
### 2.3. UI/UX - Sidebar Refactoring
* **Reordering**:
* **Top Section**: Home (Downloader), History.
* **Bottom Section**: Logs, Settings.
* **Removal**: Remove the "Version Number" text from the bottom of the sidebar (it can be moved to the Settings page if needed, or just removed as requested).
## 3. Implementation Steps
### Step 1: Rust Backend Updates
* Modify `src-tauri/src/downloader.rs`:
* Update `download_video` to spawn the process with `Stdio::piped()` for both stdout and stderr.
* Use `tokio::select!` or separate tasks to read both streams concurrently.
* Emit `download-log` events for every line read.
* Ensure the final error message (if exit code != 0) is explicitly captured and returned/logged.
### Step 2: Frontend Store & Logic
* Create `src/stores/logs.ts`:
* State: `logs: LogEntry[]`.
* Action: `addLog(entry)`.
* Listener: Listen for `download-log` events globally.
### Step 3: Frontend UI
* Create `src/views/Logs.vue`:
* Display logs in a scrollable container.
* Style error logs in red, info in gray/white.
* Update `src/App.vue`:
* Add the `FileText` (or similar) icon for Logs.
* Refactor the sidebar Flexbox layout to push Logs and Settings to the bottom.
* Remove the version footer.
* Update `src/router/index.ts` to include the new route.
## 4. Success Criteria
* When a download fails, the user can go to the "Logs" tab and see the exact error output from `yt-dlp`.
* The sidebar looks balanced with navigation items split between top and bottom.

67
spec/quickjs_runtime.md Normal file
View File

@@ -0,0 +1,67 @@
# Feature Specification: QuickJS Runtime Integration for yt-dlp
## 1. Context & Objective
`yt-dlp` increasingly relies on a JavaScript runtime to execute complex decryption scripts (e.g., signature extraction) required by YouTube and other platforms. Without a JS runtime, downloads may fail or be throttled.
The objective is to automatically manage the **QuickJS** runtime binary (download, update, store) alongside the existing `yt-dlp` binary and configure the download process to utilize it via environment variable injection.
## 2. Technical Requirements
### 2.1. Binary Management
The application must manage the QuickJS binary lifecycle identically to how it currently handles `yt-dlp`.
* **Source Repository:** [https://github.com/quickjs-ng/quickjs](https://github.com/quickjs-ng/quickjs)
* **Storage Location:** The user's AppData `bin` directory (same as `yt-dlp`).
* Windows: `%APPDATA%\StreamCapture\bin\`
* macOS: `~/Library/Application Support/StreamCapture/bin/`
* **Unified Naming on Disk:**
Regardless of the source filename, the binary must be renamed upon saving to ensure consistent invocation:
* **Windows:** `qjs.exe`
* **macOS:** `qjs`
### 2.2. Download & Update Logic
* **Check:** On app launch (or `init_ytdlp`), check if `qjs` exists.
* **Download:** If missing, fetch the appropriate asset from the latest GitHub release of `quickjs-ng/quickjs`.
* *Note:* Logic must detect OS/Arch to pick the correct asset (e.g., `windows-x86_64`, `macos-x86_64/arm64`).
* **Permissions:** On macOS/Linux, ensure `chmod +x` is applied.
* **Update:** When `update_ytdlp` is triggered, also check/redownload the latest `qjs` binary.
### 2.3. Execution & Environment Injection
To enable `yt-dlp` to find the `qjs` binary without hardcoding absolute paths in the flags (which can be fragile), we will modify the **subprocess environment**.
* **Command Flag:** Always pass `--js-runtime qjs` to the `yt-dlp` command.
* **Environment Modification:**
Before spawning the `yt-dlp` child process in Rust, dynamically modify its `PATH` environment variable.
* **Action:** Prepend the absolute path of the application's `bin` directory to the system `PATH`.
* **Result:** When `yt-dlp` looks for `qjs`, it will find it in the injected `PATH`.
## 3. Implementation Plan
### Step 1: Refactor `src-tauri/src/ytdlp.rs`
* Rename file/module to `src-tauri/src/binary_manager.rs` (Optional, or just expand `ytdlp.rs`).
* Add constants/functions for QuickJS:
* `get_qjs_binary_name()`
* `download_qjs()`: Similar logic to `download_ytdlp` but parsing QuickJS release assets.
### Step 2: Update `src-tauri/src/commands.rs`
* Update `init_ytdlp` to initialize **both** binaries.
* Update `update_ytdlp` to update **both** binaries.
### Step 3: Update `src-tauri/src/downloader.rs`
* In `download_video` and `fetch_metadata`:
1. Resolve the absolute path to the `bin` directory.
2. Read the current system `PATH`.
3. Construct a new `PATH` string: `bin_dir + delimiter + system_path`.
4. Configure the `Command`:
```rust
Command::new(...)
.env("PATH", new_path)
.arg("--js-runtime")
.arg("qjs")
...
```
## 4. Acceptance Criteria
1. **File Existence:** `qjs.exe` (Win) or `qjs` (Mac) appears in the `bin` folder after app startup.
2. **Process Execution:** The logs show `yt-dlp` running successfully.
3. **Verification:** If a specific video requires JS interpretation (often indicated by slow downloads or errors without JS), it proceeds smoothly.
4. **Clean Logs:** No "PhantomJS not found" or "JS engine not found" warnings in the logs.

26
spec/quickjs_update.md Normal file
View File

@@ -0,0 +1,26 @@
# QuickJS Binary Source Update
## 1. Context
The current `quickjs-ng` runtime is proving too slow for our needs. We need to switch to the original QuickJS runtime provided by Bellard.
## 2. Source Details
* **Base URL:** `https://bellard.org/quickjs/binary_releases/`
* **Versioning:** Use `LATEST.json` at the base URL to find the latest version and filename.
* Format: `{"version":"2024-01-13","files":{"quickjs-win-x86_64.zip":"quickjs-win-x86_64-2024-01-13.zip", ...}}`
* **Target Files:**
* **Windows:** Look for key `quickjs-win-x86_64.zip`.
* **macOS:** Look for key `quickjs-cosmo-x86_64.zip` (Cosmo builds are generally portable). *Wait, need to confirm if macos specific builds exist or if cosmo is the intended one for unix-like.*
* *Correction*: Bellard's page lists `quickjs-macos-x86_64.zip`? Let's check LATEST.json first. Assuming `quickjs-cosmo` might be Linux/Universal. Let's fetch `LATEST.json` to be sure.
## 3. Implementation Changes
* **`src-tauri/src/binary_manager.rs`**:
* Update `QJS_REPO_URL` to `https://bellard.org/quickjs/binary_releases`.
* Add logic to fetch `LATEST.json` first.
* Parse the JSON to get the actual filename for the current OS.
* Download the ZIP file.
* Extract the binary (`qjs.exe` or `qjs`) from the ZIP.
* Rename it to our internal standard (`quickjs.exe` / `quickjs`).
## 4. Verification
* Re-run tests.
* Ensure `update_quickjs` flows correctly with the new logic.

111
spec/url_parsing.md Normal file
View File

@@ -0,0 +1,111 @@
# Feature Request: Advanced Playlist Parsing & Mix Handling
## Context
We are upgrading the **StreamCapture** application. Currently, the app only supports parsing standard single video URLs.
We need to implement robust support for **Standard Playlists** and **YouTube Mixes (Radio)**, while solving performance issues and thumbnail loading errors.
## Problem Statement
1. **Playlists (`/playlist?list=...`)**: Fails to parse entries or hangs because it attempts to resolve full metadata for every video. Thumbnails are missing.
2. **Mixes (`/watch?v=...&list=RD...`)**: Currently fails or behaves unpredictably.
3. **UI/UX**: Users need a specific choice when encountering a "Mix" link:
* **Option A (Default):** Treat it as a single video (ignore the list).
* **Option B:** Parse the Mix as a playlist (limit to top 20 items).
## Technical Requirements
### 1. Rust Backend Refactoring (`src-tauri/src/ytdlp.rs`)
Refactor the `fetch_metadata` command to use a unified, efficient parsing strategy.
#### A. Command Construction
For **ALL** metadata fetching, use the `--flat-playlist` flag to prevent deep extraction (which causes the hang).
**Base Command:**
```bash
yt-dlp --dump-single-json --flat-playlist --no-warnings [URL]
```
#### B. Handling Different URL Types
1. Single Video:
- `yt-dlp` returns a single JSON object with `_type: "video"` (or no type).
- Action: Wrap it in a list of 1.
2. Standard Playlist:
- `yt-dlp` returns `_type: "playlist"` with an `entries` array.
- Action: Map the `entries` to our `Video` struct.
3. Mix / Radio (Infinite List):
- Condition: If the frontend flags this request as a "Mix Playlist scan".
- Modification: Add flag --playlist-end 20 to the command.
- Reason: Mixes are infinite; we must cap them.
#### C. Data Normalization & Thumbnail Fallback
When using `--flat-playlist`, the `entries` often lack full `thumbnail` URLs or return webp formats that might not render immediately.
- Logic: If the `thumbnail` field is missing or empty in an entry, construct it manually using the ID:
- https://i.ytimg.com/vi/{video_id}/mqdefault.jpg
### 2. Frontend Logic (`src/views/Home.vue` & Stores)
#### A. URL Detection & User Choice
Before sending the URL to Rust, analyze the string:
1. Regex Check: Detect if the URL contains both `v=` AND `list=` (typical for Mixes).
2. New UI Element:
- If a Mix link is detected, show a **Checkbox** or **Toggle** near the "Analyze" button.
- Label: "Scan Playlist (Max 20)"
- Default State: Unchecked (Off).
3. Submission Logic:
- If Unchecked (Default): Strip the `&list=...` parameter from the URL string before calling Rust. Treat it as a pure single video.
- If Checked: Keep the full URL and pass a flag (e.g., `is_mix: true`) to the Rust backend (or handle the logic to request the top 20).
#### B. Displaying Results
- Ensure the "Selection Area" can render a list of cards whether it contains 1 video or 20 videos.
- If it's a playlist, show a "Select All" / "Deselect All" control.
## Implementation Plan
### Step 1: Rust Structs Update
Update the Serde structs in `ytdlp.rs` to handle the `flat-playlist` JSON structure.
```rust
// Example structure hint
struct YtDlpResponse {
_type: Option<String>,
entries: Option<Vec<VideoEntry>>,
// ... fields for single video fallback
id: Option<String>,
title: Option<String>,
}
struct VideoEntry {
id: String,
title: String,
duration: Option<f64>,
thumbnail: Option<String>, // Might be missing
}
```
### Step 2: Rust Logic Update
Modify `command::fetch_metadata`.
- Accept an optional argument `parse_mix_playlist: bool`.
- If `true`, append `--playlist-end 20`.
- Implement the thumbnail fallback logic (if `thumbnail` is None, use `i.ytimg.com`).
### Step 3: Frontend Update
- Add the "Mix Detected" logic in `Home.vue`.
- Add the toggle UI.
- Update the `analyze` function to handle URL stripping vs. passing through based on the toggle.
## Deliverables
Please rewrite the necessary parts of `src-tauri/src/ytdlp.rs`, `src-tauri/src/commands.rs`, and `src/views/Home.vue` to implement this logic.

249
src-tauri/Cargo.lock generated
View File

@@ -8,6 +8,17 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aes"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
]
[[package]]
name = "aho-corasick"
version = "1.1.4"
@@ -47,6 +58,15 @@ version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
[[package]]
name = "arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
dependencies = [
"derive_arbitrary",
]
[[package]]
name = "ashpd"
version = "0.11.0"
@@ -349,6 +369,15 @@ dependencies = [
"serde",
]
[[package]]
name = "bzip2"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a53fac24f34a81bc9954b5d6cfce0c21e18ec6959f44f56e8e90e4bb7c346c"
dependencies = [
"libbz2-rs-sys",
]
[[package]]
name = "cairo-rs"
version = "0.18.5"
@@ -423,6 +452,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c481bdbf0ed3b892f6f806287d72acd515b352a4ec27a208489b8c1bc839633a"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
@@ -479,6 +510,16 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "cipher"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "combine"
version = "4.6.7"
@@ -498,6 +539,12 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "constant_time_eq"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6"
[[package]]
name = "convert_case"
version = "0.4.0"
@@ -573,6 +620,21 @@ dependencies = [
"libc",
]
[[package]]
name = "crc"
version = "3.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
dependencies = [
"crc-catalog",
]
[[package]]
name = "crc-catalog"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5"
[[package]]
name = "crc32fast"
version = "1.5.0"
@@ -679,6 +741,12 @@ dependencies = [
"syn 2.0.111",
]
[[package]]
name = "deflate64"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26bf8fc351c5ed29b5c2f0cbbac1b209b74f60ecd62e675a998df72c49af5204"
[[package]]
name = "deranged"
version = "0.5.5"
@@ -689,6 +757,17 @@ dependencies = [
"serde_core",
]
[[package]]
name = "derive_arbitrary"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]]
name = "derive_more"
version = "0.99.20"
@@ -710,6 +789,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -978,6 +1058,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb"
dependencies = [
"crc32fast",
"libz-rs-sys",
"miniz_oxide",
]
@@ -1492,6 +1573,15 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "html5ever"
version = "0.29.1"
@@ -1798,6 +1888,15 @@ dependencies = [
"cfb",
]
[[package]]
name = "inout"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
dependencies = [
"generic-array",
]
[[package]]
name = "ipnet"
version = "2.11.0"
@@ -1884,6 +1983,16 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
[[package]]
name = "jobserver"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
dependencies = [
"getrandom 0.3.4",
"libc",
]
[[package]]
name = "js-sys"
version = "0.3.83"
@@ -1969,6 +2078,12 @@ dependencies = [
"once_cell",
]
[[package]]
name = "libbz2-rs-sys"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c4a545a15244c7d945065b5d392b2d2d7f21526fba56ce51467b06ed445e8f7"
[[package]]
name = "libc"
version = "0.2.177"
@@ -1995,6 +2110,15 @@ dependencies = [
"libc",
]
[[package]]
name = "libz-rs-sys"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "840db8cf39d9ec4dd794376f38acc40d0fc65eec2a8f484f7fd375b84602becd"
dependencies = [
"zlib-rs",
]
[[package]]
name = "linux-raw-sys"
version = "0.11.0"
@@ -2028,6 +2152,16 @@ version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
[[package]]
name = "lzma-rust2"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c60a23ffb90d527e23192f1246b14746e2f7f071cb84476dd879071696c18a4a"
dependencies = [
"crc",
"sha2",
]
[[package]]
name = "mac"
version = "0.1.1"
@@ -2639,6 +2773,16 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
[[package]]
name = "pbkdf2"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2"
dependencies = [
"digest",
"hmac",
]
[[package]]
name = "percent-encoding"
version = "2.3.2"
@@ -2863,6 +3007,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppmd-rust"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d558c559f0450f16f2a27a1f017ef38468c1090c9ce63c8e51366232d53717b4"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@@ -3682,6 +3832,17 @@ dependencies = [
"stable_deref_trait",
]
[[package]]
name = "sha1"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.10.9"
@@ -3825,6 +3986,7 @@ dependencies = [
"tauri-plugin-opener",
"tokio",
"uuid",
"zip",
]
[[package]]
@@ -5814,6 +5976,20 @@ name = "zeroize"
version = "1.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.111",
]
[[package]]
name = "zerotrie"
@@ -5848,6 +6024,79 @@ dependencies = [
"syn 2.0.111",
]
[[package]]
name = "zip"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b"
dependencies = [
"aes",
"arbitrary",
"bzip2",
"constant_time_eq",
"crc32fast",
"deflate64",
"flate2",
"getrandom 0.3.4",
"hmac",
"indexmap 2.12.1",
"lzma-rust2",
"memchr",
"pbkdf2",
"ppmd-rust",
"sha1",
"time",
"zeroize",
"zopfli",
"zstd",
]
[[package]]
name = "zlib-rs"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f06ae92f42f5e5c42443fd094f245eb656abf56dd7cce9b8b263236565e00f2"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
[[package]]
name = "zstd"
version = "0.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
dependencies = [
"zstd-safe",
]
[[package]]
name = "zstd-safe"
version = "7.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
dependencies = [
"zstd-sys",
]
[[package]]
name = "zstd-sys"
version = "2.0.16+zstd.1.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
dependencies = [
"cc",
"pkg-config",
]
[[package]]
name = "zvariant"
version = "5.8.0"

View File

@@ -25,3 +25,4 @@ chrono = { version = "0.4", features = ["serde"] }
futures-util = "0.3"
regex = "1.10"
uuid = { version = "1.0", features = ["v4", "serde"] }
zip = "6.0.0"

View File

@@ -0,0 +1,272 @@
// filepath: src-tauri/src/binary_manager.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 zip::ZipArchive;
use std::io::Cursor;
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";
pub fn get_ytdlp_binary_name() -> &'static str {
if cfg!(target_os = "windows") {
"yt-dlp.exe"
} else if cfg!(target_os = "macos") {
"yt-dlp_macos"
} else {
"yt-dlp"
}
}
// Target name on disk (for yt-dlp usage)
pub fn get_qjs_binary_name() -> &'static str {
if cfg!(target_os = "windows") {
"quickjs.exe"
} else {
"quickjs"
}
}
// Source name inside the zip archive (standard QuickJS naming)
fn get_qjs_source_name_in_zip() -> &'static str {
if cfg!(target_os = "windows") {
"qjs.exe"
} else {
"qjs"
}
}
// Get base directory for all binaries
pub fn get_bin_dir(app: &AppHandle) -> Result<PathBuf> {
let app_data = storage::get_app_data_dir(app)?;
let bin_dir = app_data.join("bin");
if !bin_dir.exists() {
fs::create_dir_all(&bin_dir)?;
}
Ok(bin_dir)
}
pub fn get_ytdlp_path(app: &AppHandle) -> Result<PathBuf> {
Ok(get_bin_dir(app)?.join(get_ytdlp_binary_name()))
}
pub fn get_qjs_path(app: &AppHandle) -> Result<PathBuf> {
Ok(get_bin_dir(app)?.join(get_qjs_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
}
// --- yt-dlp Logic ---
pub async fn download_ytdlp(app: &AppHandle) -> Result<PathBuf> {
let binary_name = get_ytdlp_binary_name();
let url = format!("{}/{}", YT_DLP_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)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, bytes)?;
#[cfg(target_family = "unix")]
{
let mut perms = fs::metadata(&path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&path, perms)?;
}
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 yt-dlp".to_string());
}
// Use built-in update for yt-dlp
let output = std::process::Command::new(&path)
.arg("-U")
.output()?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
return Err(anyhow!("yt-dlp update failed: {}", stderr));
}
// Update settings timestamp
let mut settings = storage::load_settings(app)?;
settings.last_updated = Some(chrono::Utc::now());
storage::save_settings(app, &settings)?;
Ok("yt-dlp updated".to_string())
}
pub fn get_ytdlp_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())
}
}
// --- QuickJS Logic ---
#[derive(serde::Deserialize)]
struct LatestInfo {
version: String,
}
pub async fn download_qjs(app: &AppHandle) -> Result<PathBuf> {
// 1. Fetch LATEST.json to get version info (though filenames seem predictable-ish, version helps)
// Actually, looking at the file list, Bellard uses date-based versions.
// Format: quickjs-win-x86_64-YYYY-MM-DD.zip
// We need to find the correct filename dynamically or parse LATEST.json if it gave filenames.
// The LATEST.json content was {"version":"2024-01-13"} (example from prompt context).
// So we can construct the filename: quickjs-{platform}-{version}.zip
let latest_url = format!("{}/LATEST.json", QJS_REPO_URL);
let latest_resp = reqwest::get(&latest_url).await?;
if !latest_resp.status().is_success() {
return Err(anyhow!("Failed to fetch QuickJS version info"));
}
let latest_info: LatestInfo = latest_resp.json().await?;
let version = latest_info.version;
// Construct filename based on OS/Arch
let filename = if cfg!(target_os = "windows") {
format!("quickjs-win-x86_64-{}.zip", version)
} else if cfg!(target_os = "macos") {
// NOTE: Cosmo builds are universal/portable for Linux/Mac usually?
// Based on prompt instruction: "macos download quickjs-cosmo marked file"
// Bellard lists: quickjs-cosmo-YYYY-MM-DD.zip
format!("quickjs-cosmo-{}.zip", version)
} else {
return Err(anyhow!("Unsupported OS for QuickJS auto-download"));
};
let download_url = format!("{}/{}", QJS_REPO_URL, filename);
let response = reqwest::get(&download_url).await?;
if !response.status().is_success() {
return Err(anyhow!("Failed to download QuickJS: Status {}", response.status()));
}
let bytes = response.bytes().await?;
let cursor = Cursor::new(bytes);
let mut archive = ZipArchive::new(cursor)?;
let bin_dir = get_bin_dir(app)?;
// Extract logic: The zip from Bellard usually contains a folder or just binaries.
// We need to find the `qjs` binary.
// Windows zip usually has `qjs.exe`
// Cosmo zip usually has `qjs`? Let's search for it.
let source_name = get_qjs_source_name_in_zip();
let target_name = get_qjs_binary_name(); // quickjs.exe or quickjs
let mut found = 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 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;
}
}
if !found {
return Err(anyhow!("Could not find {} in downloaded archive", source_name));
}
let final_path = get_qjs_path(app)?;
#[cfg(target_family = "unix")]
{
let mut perms = fs::metadata(&final_path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&final_path, perms)?;
}
Ok(final_path)
}
pub async fn update_qjs(app: &AppHandle) -> Result<String> {
// QuickJS doesn't have self-update, so we just re-download
download_qjs(app).await?;
Ok("QuickJS updated/installed".to_string())
}
pub fn get_qjs_version(app: &AppHandle) -> Result<String> {
let path = get_qjs_path(app)?;
if !path.exists() {
return Ok("Not installed".to_string());
}
Ok("Installed".to_string())
}
pub async fn ensure_binaries(app: &AppHandle) -> Result<()> {
let ytdlp = get_ytdlp_path(app)?;
if !ytdlp.exists() {
download_ytdlp(app).await?;
}
let qjs = get_qjs_path(app)?;
if !qjs.exists() {
download_qjs(app).await?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_binary_names() {
if cfg!(target_os = "windows") {
assert_eq!(get_ytdlp_binary_name(), "yt-dlp.exe");
assert_eq!(get_qjs_binary_name(), "quickjs.exe");
assert_eq!(get_qjs_source_name_in_zip(), "qjs.exe");
} else if cfg!(target_os = "macos") {
assert_eq!(get_ytdlp_binary_name(), "yt-dlp_macos");
assert_eq!(get_qjs_binary_name(), "quickjs");
assert_eq!(get_qjs_source_name_in_zip(), "qjs");
}
}
}

View File

@@ -1,6 +1,6 @@
// filepath: src-tauri/src/commands.rs
use tauri::{AppHandle, Manager};
use crate::{ytdlp, downloader, storage};
use crate::{binary_manager, downloader, storage};
use crate::downloader::DownloadOptions;
use crate::storage::{Settings, HistoryItem};
use uuid::Uuid;
@@ -8,30 +8,40 @@ use std::path::Path;
#[tauri::command]
pub async fn init_ytdlp(app: AppHandle) -> Result<bool, String> {
if ytdlp::check_ytdlp(&app) {
if binary_manager::check_binaries(&app) {
return Ok(true);
}
// If not found, try to download
match ytdlp::download_ytdlp(&app).await {
match binary_manager::ensure_binaries(&app).await {
Ok(_) => Ok(true),
Err(e) => Err(format!("Failed to download yt-dlp: {}", e)),
Err(e) => Err(format!("Failed to download binaries: {}", e)),
}
}
#[tauri::command]
pub async fn update_ytdlp(app: AppHandle) -> Result<String, String> {
ytdlp::update_ytdlp(&app).await.map_err(|e| e.to_string())
binary_manager::update_ytdlp(&app).await.map_err(|e| e.to_string())
}
#[tauri::command]
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 fn get_ytdlp_version(app: AppHandle) -> Result<String, String> {
ytdlp::get_version(&app).map_err(|e| e.to_string())
binary_manager::get_ytdlp_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())
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 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())
}
#[tauri::command]
@@ -116,4 +126,4 @@ pub fn open_in_explorer(app: AppHandle, path: String) -> Result<(), String> {
.map_err(|e| e.to_string())?;
}
Ok(())
}
}

View File

@@ -6,7 +6,7 @@ use std::process::Stdio;
use serde::{Deserialize, Serialize};
use anyhow::{Result, anyhow};
use regex::Regex;
use crate::ytdlp;
use crate::binary_manager;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VideoMetadata {
@@ -46,18 +46,36 @@ pub struct ProgressEvent {
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)?;
#[derive(Serialize, Clone, Debug)]
pub struct LogEvent {
pub id: String,
pub message: String,
pub level: String, // "info", "error"
}
pub async fn fetch_metadata(app: &AppHandle, url: &str, parse_mix_playlist: bool) -> Result<MetadataResult> {
let ytdlp_path = binary_manager::get_ytdlp_path(app)?;
let qjs_path = binary_manager::get_qjs_path(app)?; // Get absolute path to quickjs
// 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?;
let mut cmd = Command::new(ytdlp_path);
// Pass the runtime and its absolute path to --js-runtimes
cmd.arg("--js-runtimes").arg(format!("quickjs:{}", qjs_path.to_string_lossy()));
cmd.arg("--dump-single-json")
.arg("--flat-playlist")
.arg("--no-warnings");
if parse_mix_playlist {
cmd.arg("--playlist-end").arg("20");
}
cmd.arg(url);
cmd.stderr(Stdio::piped());
let output = cmd.output().await?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -90,10 +108,18 @@ pub async fn fetch_metadata(app: &AppHandle, url: &str) -> Result<MetadataResult
}
fn parse_video_metadata(json: &serde_json::Value) -> VideoMetadata {
let id = json["id"].as_str().unwrap_or("").to_string();
// Thumbnail fallback logic
let thumbnail = match json.get("thumbnail").and_then(|t| t.as_str()) {
Some(t) if !t.is_empty() => t.to_string(),
_ => format!("https://i.ytimg.com/vi/{}/mqdefault.jpg", id),
};
VideoMetadata {
id: json["id"].as_str().unwrap_or("").to_string(),
id,
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
thumbnail,
duration: json["duration"].as_f64(),
uploader: json["uploader"].as_str().map(|s| s.to_string()),
}
@@ -105,9 +131,15 @@ pub async fn download_video(
url: String,
options: DownloadOptions,
) -> Result<String> {
let ytdlp_path = ytdlp::get_ytdlp_path(&app)?;
let ytdlp_path = binary_manager::get_ytdlp_path(&app)?;
let qjs_path = binary_manager::get_qjs_path(&app)?; // Get absolute path to quickjs
let mut args = Vec::new();
// Pass the runtime and its absolute path to --js-runtimes
args.push("--js-runtimes".to_string());
args.push(format!("quickjs:{}", qjs_path.to_string_lossy()));
args.push(url);
// Output template
@@ -119,7 +151,7 @@ pub async fn download_video(
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
args.push("mp3".to_string());
} else {
let format_arg = if options.quality == "best" {
"bestvideo+bestaudio/best".to_string()
@@ -131,36 +163,66 @@ pub async fn download_video(
}
// Progress output
args.push("--newline".to_string()); // Easier parsing
args.push("--newline".to_string());
let mut child = Command::new(ytdlp_path)
let mut cmd = Command::new(ytdlp_path);
let mut child = cmd
.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 stderr = child.stderr.take().ok_or(anyhow!("Failed to open stderr"))?;
let mut stdout_reader = BufReader::new(stdout);
let mut stderr_reader = BufReader::new(stderr);
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 {
// Loop to read both streams
loop {
let mut out_line = String::new();
let mut err_line = String::new();
tokio::select! {
res = stdout_reader.read_line(&mut out_line) => {
if res.unwrap_or(0) == 0 {
break; // EOF
}
// Parse progress
if let Some(caps) = re.captures(&out_line) {
if let Some(pct_match) = caps.get(1) {
if let Ok(pct) = pct_match.as_str().parse::<f64>() {
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: pct,
speed: "TODO".to_string(),
status: "downloading".to_string(),
}).ok();
}
}
} else { // Only emit download-log if it's NOT a progress line
app.emit("download-log", LogEvent {
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(),
message: out_line.trim().to_string(),
level: "info".to_string(),
}).ok();
}
}
res = stderr_reader.read_line(&mut err_line) => {
if res.unwrap_or(0) > 0 {
// Log error
app.emit("download-log", LogEvent {
id: id.clone(),
message: err_line.trim().to_string(),
level: "error".to_string(),
}).ok();
}
}
}
line.clear();
}
let status = child.wait().await?;

View File

@@ -1,5 +1,5 @@
// filepath: src-tauri/src/lib.rs
mod ytdlp;
mod binary_manager;
mod downloader;
mod storage;
mod commands;
@@ -12,7 +12,9 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![
commands::init_ytdlp,
commands::update_ytdlp,
commands::update_quickjs,
commands::get_ytdlp_version,
commands::get_quickjs_version,
commands::fetch_metadata,
commands::start_download,
commands::get_settings,

View File

@@ -1,140 +0,0 @@
// 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

@@ -14,7 +14,7 @@
{
"title": "stream-capture",
"width": 1300,
"height": 800
"height": 850
}
],
"security": {

View File

@@ -2,18 +2,21 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { RouterView, RouterLink, useRoute } from 'vue-router'
import { Home, History, Settings as SettingsIcon, Download } from 'lucide-vue-next'
import { Home, History, Settings as SettingsIcon, Download, FileText } from 'lucide-vue-next'
import { useSettingsStore } from './stores/settings'
import { useQueueStore } from './stores/queue'
import { useLogsStore } from './stores/logs'
const settingsStore = useSettingsStore()
const queueStore = useQueueStore()
const logsStore = useLogsStore()
const route = useRoute()
onMounted(async () => {
await settingsStore.loadSettings()
await settingsStore.initYtdlp()
await queueStore.initListener()
await logsStore.initListener()
})
</script>
@@ -28,7 +31,8 @@ onMounted(async () => {
<span class="font-bold text-lg hidden lg:block">StreamCapture</span>
</div>
<nav class="flex-1 px-4 space-y-2 mt-4">
<nav class="flex-1 px-4 space-y-2 mt-4 flex flex-col pb-6">
<!-- Top Section -->
<RouterLink to="/"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
: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'"
@@ -45,6 +49,17 @@ onMounted(async () => {
<span class="hidden lg:block font-medium">History</span>
</RouterLink>
<div class="flex-1"></div>
<!-- Bottom Section -->
<RouterLink to="/logs"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
:class="route.path === '/logs' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
>
<FileText class="w-5 h-5 shrink-0" />
<span class="hidden lg:block font-medium">Logs</span>
</RouterLink>
<RouterLink to="/settings"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
: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'"
@@ -53,13 +68,6 @@ onMounted(async () => {
<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 -->
@@ -67,4 +75,4 @@ onMounted(async () => {
<RouterView />
</main>
</div>
</template>
</template>

View File

@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import History from '../views/History.vue'
import Settings from '../views/Settings.vue'
import Logs from '../views/Logs.vue'
const router = createRouter({
history: createWebHistory(),
@@ -16,6 +17,11 @@ const router = createRouter({
name: 'history',
component: History
},
{
path: '/logs',
name: 'logs',
component: Logs
},
{
path: '/settings',
name: 'settings',
@@ -24,4 +30,4 @@ const router = createRouter({
]
})
export default router
export default router

View File

@@ -8,6 +8,10 @@ export const useAnalysisStore = defineStore('analysis', () => {
const error = ref('')
const metadata = ref<any>(null)
// New state for mix detection
const isMix = ref(false)
const scanMix = ref(false)
const options = ref({
is_audio_only: false,
quality: 'best',
@@ -19,10 +23,9 @@ export const useAnalysisStore = defineStore('analysis', () => {
loading.value = false
error.value = ''
metadata.value = null
// We keep options as is, or reset them?
// Usually keeping user preference for "Audio Only" is nice,
// but let's just reset the content-related stuff.
isMix.value = false
scanMix.value = false
}
return { url, loading, error, metadata, options, reset }
})
return { url, loading, error, metadata, options, isMix, scanMix, reset }
})

54
src/stores/logs.ts Normal file
View File

@@ -0,0 +1,54 @@
// filepath: src/stores/logs.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listen } from '@tauri-apps/api/event'
export interface LogEntry {
id: string
taskId: string
message: string
level: 'info' | 'error'
timestamp: number
}
interface LogEvent {
id: string
message: string
level: string
}
export const useLogsStore = defineStore('logs', () => {
const logs = ref<LogEntry[]>([])
const isListening = ref(false)
function addLog(taskId: string, message: string, level: 'info' | 'error') {
logs.value.push({
id: crypto.randomUUID(),
taskId,
message,
level,
timestamp: Date.now()
})
// Optional: Limit log size to avoid memory issues
if (logs.value.length > 5000) {
logs.value = logs.value.slice(-5000)
}
}
async function initListener() {
if (isListening.value) return
isListening.value = true
await listen<LogEvent>('download-log', (event) => {
const { id, message, level } = event.payload
addLog(id, message, level as 'info' | 'error')
})
}
function clearLogs() {
logs.value = []
}
return { logs, addLog, initListener, clearLogs }
})

View File

@@ -17,6 +17,7 @@ export const useSettingsStore = defineStore('settings', () => {
})
const ytdlpVersion = ref('Checking...')
const quickjsVersion = ref('Checking...')
const isInitializing = ref(true)
async function loadSettings() {
@@ -43,15 +44,21 @@ export const useSettingsStore = defineStore('settings', () => {
isInitializing.value = true
// check/download
await invoke('init_ytdlp')
ytdlpVersion.value = await invoke('get_ytdlp_version')
await refreshVersions()
} catch (e) {
console.error(e)
ytdlpVersion.value = 'Error'
quickjsVersion.value = 'Error'
} finally {
isInitializing.value = false
}
}
async function refreshVersions() {
ytdlpVersion.value = await invoke('get_ytdlp_version')
quickjsVersion.value = await invoke('get_quickjs_version')
}
function applyTheme(theme: string) {
const root = document.documentElement
const isDark = theme === 'dark' || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)
@@ -69,5 +76,5 @@ export const useSettingsStore = defineStore('settings', () => {
}
})
return { settings, loadSettings, save, initYtdlp, ytdlpVersion, isInitializing }
})
return { settings, loadSettings, save, initYtdlp, refreshVersions, ytdlpVersion, quickjsVersion, isInitializing }
})

View File

@@ -26,6 +26,17 @@ watch(() => settingsStore.settings.download_path, (newPath) => {
}
}, { immediate: true })
// Detect Mix URL
watch(() => analysisStore.url, (newUrl) => {
if (newUrl && newUrl.includes('v=') && newUrl.includes('list=')) {
analysisStore.isMix = true
} else {
analysisStore.isMix = false
// Reset scanMix if URL changes to non-mix
analysisStore.scanMix = false
}
})
async function analyze() {
if (!analysisStore.url) return
analysisStore.loading = true
@@ -33,7 +44,29 @@ async function analyze() {
analysisStore.metadata = null
try {
const res = await invoke('fetch_metadata', { url: analysisStore.url })
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('fetch_metadata', { url: urlToScan, parseMixPlaylist: parseMix })
analysisStore.metadata = res
} catch (e: any) {
analysisStore.error = e.toString()
@@ -55,8 +88,28 @@ async function startDownload() {
{ title: analysisStore.metadata.title, thumbnail: "", id: analysisStore.metadata.id } :
analysisStore.metadata;
// Note: We might want to pass the *cleaned* URL if it was cleaned during analyze
// But for now we pass the original URL or whatever was scanned.
// Actually, if we scanned as a single video (unchecked), we should probably download as single video.
// The user might expect the same result as analysis.
// Let's reconstruct the URL logic or just use what `analyze` used?
// Since `start_download` just takes a URL string, we should probably use the same logic.
let urlToDownload = analysisStore.url;
if (analysisStore.isMix && !analysisStore.scanMix) {
try {
const u = new URL(urlToDownload);
u.searchParams.delete('list');
u.searchParams.delete('index');
u.searchParams.delete('start_radio');
urlToDownload = u.toString();
} catch (e) {
urlToDownload = urlToDownload.replace(/&list=[^&]+/, '');
}
}
const id = await invoke<string>('start_download', {
url: analysisStore.url,
url: urlToDownload,
options: analysisStore.options,
metadata: metaToSend
})
@@ -104,6 +157,22 @@ async function startDownload() {
<span v-else>Analyze</span>
</button>
</div>
<!-- Mix Toggle -->
<div v-if="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"
:class="analysisStore.scanMix ? '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="analysisStore.scanMix ? 'translate-x-6' : 'translate-x-0'"
/>
</button>
<span class="text-sm font-medium text-zinc-700 dark:text-gray-300">Scan Playlist (Max 20)</span>
</div>
<p v-if="analysisStore.error" class="mt-3 text-red-500 text-sm">{{ analysisStore.error }}</p>
</div>
@@ -185,4 +254,4 @@ async function startDownload() {
</div>
</div>
</template>
</template>

127
src/views/Logs.vue Normal file
View File

@@ -0,0 +1,127 @@
// filepath: src/views/Logs.vue
<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useLogsStore } from '../stores/logs'
import { Trash2, Search } from 'lucide-vue-next'
const logsStore = useLogsStore()
const logsContainer = ref<HTMLElement | null>(null)
const autoScroll = ref(true)
const filterLevel = ref<'all' | 'info' | 'error'>('all')
const searchQuery = ref('')
const filteredLogs = computed(() => {
return logsStore.logs.filter(log => {
if (filterLevel.value !== 'all' && log.level !== filterLevel.value) return false
if (searchQuery.value && !log.message.toLowerCase().includes(searchQuery.value.toLowerCase()) && !log.taskId.includes(searchQuery.value)) return false
return true
})
})
// Auto-scroll
watch(() => logsStore.logs.length, () => {
if (autoScroll.value) {
nextTick(() => {
if (logsContainer.value) {
logsContainer.value.scrollTop = logsContainer.value.scrollHeight
}
})
}
})
function formatTime(ts: number) {
const d = new Date(ts)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
const hours = String(d.getHours()).padStart(2, '0')
const minutes = String(d.getMinutes()).padStart(2, '0')
const seconds = String(d.getSeconds()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>
<template>
<div class="flex flex-col h-full p-6">
<!-- Header -->
<div class="flex justify-between items-center mb-6">
<div>
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">Execution Logs</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">Real-time output from download processes.</p>
</div>
<div class="flex items-center gap-3">
<!-- Search -->
<div class="relative">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
v-model="searchQuery"
type="text"
placeholder="Search logs..."
class="pl-9 pr-4 py-2 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 text-zinc-900 dark:text-white w-48"
/>
</div>
<!-- Level Filter -->
<div class="flex bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-xl p-1">
<button
@click="filterLevel = 'all'"
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
:class="filterLevel === 'all' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>All</button>
<button
@click="filterLevel = 'info'"
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
:class="filterLevel === 'info' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>Info</button>
<button
@click="filterLevel = 'error'"
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
:class="filterLevel === 'error' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>Error</button>
</div>
<button
@click="logsStore.clearLogs"
class="p-2 text-gray-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 rounded-xl transition-colors border border-gray-200 dark:border-zinc-800 bg-white dark:bg-zinc-900"
title="Clear Logs"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<!-- Logs Console -->
<div class="flex-1 overflow-hidden relative bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 font-mono text-xs md:text-sm">
<div
ref="logsContainer"
class="absolute inset-0 overflow-auto p-4 space-y-1"
@scroll="(e) => {
const target = e.target as HTMLElement;
autoScroll = target.scrollTop + target.clientHeight >= target.scrollHeight - 10;
}"
>
<div v-if="filteredLogs.length === 0" class="h-full flex items-center justify-center text-gray-400 dark:text-gray-600">
No logs to display
</div>
<div v-for="log in filteredLogs" :key="log.id" class="flex gap-4 hover:bg-gray-50 dark:hover:bg-zinc-800/50 px-2 py-1 rounded transition-colors">
<span class="text-gray-400 dark:text-zinc-600 shrink-0 select-none w-36">{{ formatTime(log.timestamp) }}</span>
<span
class="break-all whitespace-pre-wrap"
:class="log.level === 'error' ? 'text-red-500 dark:text-red-400' : 'text-zinc-700 dark:text-gray-300'"
>{{ log.message }}</span>
</div>
</div>
<!-- Auto-scroll indicator -->
<div v-if="!autoScroll" class="absolute bottom-4 right-4">
<button
@click="() => { if(logsContainer) logsContainer.scrollTop = logsContainer.scrollHeight }"
class="bg-blue-600 hover:bg-blue-700 text-white text-xs px-3 py-1.5 rounded-full shadow-lg transition-colors"
>
Resume Auto-scroll
</button>
</div>
</div>
</div>
</template>

View File

@@ -4,10 +4,11 @@ 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'
import { Folder, RefreshCw, Monitor, Sun, Moon, Terminal } from 'lucide-vue-next'
const settingsStore = useSettingsStore()
const updating = ref(false)
const updatingYtdlp = ref(false)
const updatingQuickjs = ref(false)
const updateStatus = ref('')
async function browsePath() {
@@ -24,16 +25,30 @@ async function browsePath() {
}
async function updateYtdlp() {
updating.value = true
updateStatus.value = 'Checking...'
updatingYtdlp.value = true
updateStatus.value = 'Updating yt-dlp...'
try {
const res = await invoke<string>('update_ytdlp')
updateStatus.value = res
await settingsStore.initYtdlp()
await settingsStore.refreshVersions()
} catch (e: any) {
updateStatus.value = 'Error: ' + e.toString()
updateStatus.value = 'yt-dlp Error: ' + e.toString()
} finally {
updating.value = false
updatingYtdlp.value = false
}
}
async function updateQuickjs() {
updatingQuickjs.value = true
updateStatus.value = 'Updating QuickJS...'
try {
const res = await invoke<string>('update_quickjs')
updateStatus.value = res
await settingsStore.refreshVersions()
} catch (e: any) {
updateStatus.value = 'QuickJS Error: ' + e.toString()
} finally {
updatingQuickjs.value = false
}
}
@@ -99,27 +114,59 @@ function setTheme(theme: 'light' | 'dark' | 'system') {
</div>
</section>
<!-- yt-dlp Management -->
<!-- Binary 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>
<h2 class="text-lg font-bold mb-4 text-zinc-900 dark:text-white">External Binaries</h2>
<div class="space-y-4">
<!-- yt-dlp -->
<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">
<Download class="w-5 h-5 text-blue-600" />
</div>
<div>
<div class="font-medium text-zinc-900 dark:text-white">yt-dlp</div>
<div class="text-xs text-gray-500 mt-0.5 font-mono">v{{ settingsStore.ytdlpVersion }}</div>
</div>
</div>
<button
@click="updateYtdlp"
:disabled="updatingYtdlp"
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': updatingYtdlp }" />
Update
</button>
</div>
<!-- QuickJS -->
<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-green-600" />
</div>
<div>
<div class="font-medium text-zinc-900 dark:text-white">QuickJS</div>
<div class="text-xs text-gray-500 mt-0.5 font-mono">{{ settingsStore.quickjsVersion }}</div>
</div>
</div>
<button
@click="updateQuickjs"
:disabled="updatingQuickjs"
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': updatingQuickjs }" />
Update
</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">
<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">
{{ updateStatus }}
</div>
<p class="text-xs text-gray-400 mt-4 text-right">Last Checked: {{ settingsStore.settings.last_updated ? new Date(settingsStore.settings.last_updated).toLocaleString() : 'Never' }}</p>
</section>
</div>
</div>
</template>
</template>