Skip to content

Open-source download manager & offline media toolbox for YouTube, music, social media, learning platforms & 1,800+ sites. Built with Tauri 2.0, Rust & Svelte.

Port platform downloaders to core

Hanakoe732850680df
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..1c305fb1
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,266 @@
+# OmniGet
+
+Desktop download manager built with Tauri 2.0 (Rust backend) + SvelteKit (frontend). Modern design principles (2025-2026): clarity over features, immediate feedback, and universal accessibility. Monorepo: `src-tauri/` is Rust, `src/` is SvelteKit + TypeScript. Run `cargo tauri dev` to start.
+
+## Commands
+```bash
+pnpm install # install frontend deps
+pnpm dev # SvelteKit dev server only
+cargo tauri dev # full app (Rust + frontend)
+cargo check # typecheck Rust without building
+pnpm check # svelte-check + tsc
+```
+
+## Tech Stack
+
+- **Backend:** Rust, Tauri 2.x, tokio, reqwest, serde, sqlx (SQLite), chromiumoxide
+- **Frontend:** SvelteKit 2, Svelte 5 (runes: `$state`, `$derived`, `$effect`, `$props`), TypeScript strict
+- **Styling:** Scoped CSS with CSS custom properties. NO Tailwind. NO CSS-in-JS.
+- **Icons:** `@tabler/icons-svelte` — import individually: `import IconDownload from "@tabler/icons-svelte/IconDownload.svelte"`
+- **Fonts:** System fonts as default; IBM Plex Mono for code and technical content only
+- **i18n:** `sveltekit-i18n` with JSON locale files in `i18n/{lang}/`
+- **Bundler:** Vite 5, adapter-static, pnpm as package manager
+
+## Project Layout
+src-tauri/src/
+commands/ # Tauri IPC commands (invoked from frontend)
+platforms/ # Download platform implementations (trait-based plugin system)
+traits.rs # PlatformDownloader trait — all platforms implement this
+hotmart/ # Hotmart-specific: auth, api, parser, downloader
+core/ # Shared engine: registry, hls_downloader, media_processor, queue
+models/ # Data structs: media.rs, download.rs, settings.rs
+storage/ # Persistence: config, database (SQLite), cache
+src/
+routes/ # SvelteKit file-based routing (+page.svelte, +layout.svelte)
+components/ # Reusable UI, organized by domain (see Component Organization)
+lib/ # Shared logic: stores/, i18n/
+
+## Design System
+
+### Core Principles
+
+**Minimalism with Purpose**: Every element has a function. No decoration.
+
+**Immediate Feedback**: Progress bars show percent + bytes + speed. Errors are explicit ("Missing API key" not "Error").
+
+**Color as Guidance**: Accent for primary actions, error for destructive. Never communicate through color alone (pair with icon + text).
+
+**Accessibility First**: WCAG 2.2 AA baseline. 4.5:1 text contrast, 3:1 focus indicators, all elements keyboard accessible.
+
+### Color Architecture
+
+CSS custom properties exclusively. NEVER hardcode colors. Theme via `[data-theme="dark"]` / `[data-theme="light"]`. Every token defined in both `:root` and `[data-theme="dark"]`.
+
+**Tokens** (see app.css for values): `--primary`, `--secondary`, `--tertiary`, `--accent`, `--success`, `--error`, `--warning`, `--button`, `--button-hover`, `--button-press`, `--button-text`, `--button-stroke`, `--button-elevated`, `--sidebar-bg`, `--sidebar-highlight`, `--content-border`, `--input-border`, `--input-bg`, `--popup-bg`, `--dialog-backdrop`.
+
+**Contrast tokens** for text on colored backgrounds: `--on-primary`, `--on-accent`, `--on-success`, `--on-error`, `--on-button`, `--on-button-elevated`.
+
+**Layout constants**: `--padding: 12px`, `--border-radius: 11px`, `--sidebar-width: 80px`.
+
+### Typography
+
+System fonts for UI, monospace for code only:
+- `--font-system: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`
+- `--font-mono: "IBM Plex Mono", "Courier New", monospace`
+
+Headings: `font-weight: 500`, `margin-block: 0`. Scale: h1=24px, h2=20px, h3=16px, h4=14.5px, h5=12px, h6=11px.
+
+Body: buttons=14.5px/500, .label=13px/500, .body=14px/400/1.6, .subtext=12.5px/500, .caption=11.5px/400, code=13px/mono.
+
+### Spacing & Radius
+
+Base unit: `var(--padding)` (12px). Derive: `calc(var(--padding) / 2)` (6px), `calc(var(--padding) * 2)` (24px). Border radius: `var(--border-radius)` (11px).
+
+## Component Patterns
+
+### File Organization
+components/
+buttons/ # ActionButton, SettingsButton, SettingsToggle, Switcher
+dialog/ # DialogContainer, DialogButton, SmallDialog, PickerDialog
+hints/ # Contextual hints UI
+hotmart/ # Hotmart-specific components
+icons/ # Custom SVG icon components (only when tabler doesn't have it)
+mascot/ # Loop mascot animations
+misc/ # Toggle, Skeleton, Placeholder, SectionHeading, OuterLink
+omnibox/ # OmniboxInput, MediaPreview, FormatSelector, QualityPicker, DownloadModeSelector
+onboarding/ # First-run onboarding flow
+services/ # Platform service components
+settings/ # SettingsCategory, SettingsDropdown, SettingsInput
+toast/ # Toast notification components
+
+### Button System
+
+Classes: `.button` (default), `.button.elevated`, `.button.active`, `.button.active.color`. Hover via `@media (hover: hover)`. Focus: `outline: var(--focus-ring)` on `:focus-visible` only.
+
+### Custom Controls
+
+- **Toggle**: `<input type="checkbox" role="switch" aria-checked>` with CSS transform animation. RTL-aware via `:dir(rtl)`.
+- **Select**: Native `<select>` overlaid on styled button (position: absolute, transparent). Native provides a11y, button provides visuals.
+- **Input**: Always pair with `<label>` + `aria-describedby` for helper text.
+
+### Switcher
+
+Joined button row. Middle children get `border-radius: 0`. Negative margin eliminates double borders. `.big` variant with container bg.
+
+### Settings Components
+
+- **SettingsToggle**: label + description + Toggle. Generic TS for type-safe setting context/id.
+- **SettingsDropdown**: native select overlay pattern.
+- **SettingsCategory**: section with `id` for hash-linking + focus highlight animation.
+
+All call `updateSetting({ [context]: { [id]: value } })`.
+
+### Dialog System
+
+Native `<dialog>` + `showModal()`. ARIA: `role="dialog"`, `aria-modal="true"`, `aria-labelledby`. First element gets `autofocus`. ESC/backdrop closes. 150ms entry/exit animation.
+
+### Progress Bar
+
+Outer: `--button-elevated`, 6px, rounded. Inner: status-colored (`--blue` downloading, `--green` complete, `--red` error, `--gray` paused), width=percent, `transition: width 0.3s`. Indeterminate: Skeleton shimmer. Always determinate for downloads: `45% • 234 MB / 512 MB • 2.5 MB/s`.
+
+TO-DO: Add ETA display (`~3m 20s` via `(total - downloaded) / speed`).
+
+### Processing Queue Items
+
+Discriminated union: `waiting | running | done | error`. Icons: spinner, check, X, exclamation. File type map: `{ video: IconMovie, audio: IconMusic, image: IconPhoto, file: IconFile }`.
+
+## Layout Architecture
+
+### Grid System
+
+Two-column CSS Grid: sidebar + content. Content scrolls, sidebar fixed. Shadow border via `--content-border`.
+
+### Mobile Breakpoint: 535px
+
+Grid flips to rows. Sidebar becomes fixed bottom tab bar (horizontal scroll). Do NOT force dark theme on mobile.
+
+### Sub-Navigation
+
+Two-column: 250px nav + content (max 600px). Collapses at 750px to single column with back button.
+
+### Safe Area
+
+`env(safe-area-inset-top/bottom/left)` on all fixed/sticky elements.
+
+## Download UX Principles
+
+### Phase Indicators
+
+Show download phase explicitly (never "is it hung?"):
+1. "Preparing" — Item enqueued, building config
+2. "Fetching Info" — Running yt-dlp info extraction (only if cache miss)
+3. "Starting" — Download engine initializing (via -1.0 sentinel)
+4. "Connecting" — yt-dlp spawned, awaiting first response (via -2.0 sentinel)
+5. "Downloading" — Data flowing (percent > 0%)
+
+TO-DO: Add explicit "Merging" phase when yt-dlp emits `[Merger]` line (currently shows ~99% with no phase label).
+
+### Determinate Progress
+
+ALWAYS determinate bars: `234 MB / 512 MB (45%) • 2.5 MB/s`. ETA = (total - downloaded) / speed. Smooth speed with rolling average.
+
+TO-DO: ETA display not yet implemented. Speed rolling average not yet implemented (raw yt-dlp speed used directly).
+
+### Optimistic UI
+
+Pause/Resume/Remove: update UI instantly, send command in background, revert on failure.
+
+### Error Feedback
+
+Never vague. Always: what happened + why + what to do.
+- ❌ "Error" → ✅ "HTTP 429 - Retrying in 15s..."
+- ❌ "Loading..." → ✅ "Cannot access cookies - Continuing without auth"
+
+Toast for transient (5s auto-dismiss). Inline for persistent.
+
+### Completion Feedback
+
+Color → --success, icon → checkmark, haptic → hapticConfirm(), toast → "Downloaded: file.mp4 (123 MB)" + "Open folder".
+
+TO-DO: "Open folder" button not yet implemented on completed items (i18n key `open_folder` exists but is unused).
+
+### Rate Limiting (429)
+
+Detect → show "Retrying in 10s (2/3)" → rotate player_client/cookies → after 3: detailed error + manual retry button.
+
+TO-DO: Retry status ("Retrying in 10s (2/3)") is only logged server-side via `tracing::warn!`, not shown to the user. Need to emit retry events to frontend.
+
+### Batch Operations
+
+Aggregate: "3 Downloading, 2 Paused". Sidebar badge (red circle). Peek panel: top 3 + total.
+
+## State Management
+
+### Settings Store
+
+Partial-merge: store holds user-changed values only. Derived store merges with defaults via `ts-deepmerge`.
+
+### Schema Versioning
+
+`schemaVersion: number` + migration functions keyed by version. Increment version + add migrator when changing settings.
+
+### Theme System
+
+`auto | light | dark`. Applied as `data-theme` on wrapper div (not html/body).
+
+### Other Stores
+
+All stores in `$lib/stores/`: `download-store` (queue state), `download-listener` (Tauri event listeners), `media-preview-store` (URL preview), `toast-store`, `settings-store`, `update-store`, `convert-store`, `changelog-store`, `onboarding-store`, `clipboard-monitor`.
+
+## Accessibility
+
+WCAG 2.2 AA compliance required.
+
+### ARIA Rules
+
+Semantic HTML first. `role="dialog"` + `aria-modal`. `aria-label`/`aria-labelledby` for unlabeled buttons. `role="switch"` for toggles. `aria-live="polite"` for dynamic updates. `aria-valuenow/min/max` for progress. No `role="button"` on `<div>`.
+
+### Preferences
+
+`[data-reduce-motion="true"]` → disable all animation. `[data-reduce-transparency="true"]` → solid backdrops. Settings: `reduceMotion`, `reduceTransparency`, `disableHaptics`.
+
+### Contrast
+
+Text: 4.5:1. Focus: 3:1 + min 6px area. Never color alone. Use `--on-*` tokens. Test in forced-colors mode.
+
+### Haptics
+
+`hapticSwitch()`, `hapticConfirm()`, `hapticError()`. Gated by `device.supports.haptics && !disableHaptics`.
+
+### Focus & Keyboard
+
+Tab order: natural DOM. `:focus-visible` only. Focus ring: 2px --accent, offset 2px. ESC closes dialogs. Enter/Space activates buttons. Arrow keys navigate lists.
+
+### RTL
+
+`:dir(rtl)` for overrides. Logical properties preferred.
+
+## Loop Mascot
+
+Expressive creature reacting to download state (idle → downloading → paused → complete → error). Pure visual feedback — never required for understanding. IP protected.
+
+## i18n
+
+Lazy per route. `i18n/{lang}/{namespace}.json`. `$t("namespace.key")`. Default: `en`. All visible strings via `$t()`.
+
+## Coding Rules
+
+### Svelte & TypeScript
+
+Svelte 5 runes only (`$state`, `$derived`, `$effect`, `$props`). TypeScript strict. Discriminated unions for state.
+
+### Styling
+
+Scoped `<style>`. `$components/`, `$lib/`, `$i18n/` aliases. `@media (hover: hover)` + `:active` fallback. `pointer-events: none` on images/SVGs. Scrollbar hidden. No `!important` except a11y. Safe area insets.
+
+### Feedback
+
+Immediate UI on click (optimistic). Progress: phase + percent + bytes + speed. Errors: explicit + actionable. Tooltips: 5-10 words + shortcut.
+
+### Focus & Animations
+
+`:focus-visible` ring (2px --accent, offset 2px). `prefers-reduced-motion` alternative. Dialog: autofocus first element, trap, ESC closes.
+
+### Downloads
+
+Determinate progress with ARIA. Phase icon + text (no color-alone). Error → detail + Retry button. Batch → sidebar badge + aggregate.
diff --git a/PORTING-HANDOVER.md b/PORTING-HANDOVER.md
index e9513868..6f1eb7e5 100644
--- a/PORTING-HANDOVER.md
+++ b/PORTING-HANDOVER.md
@@ -1,7 +1,7 @@
# OmniGet 平台提取器移植 — 交接文档
> 日期:2026-07-01
-> 状态:Phase 0-2 完成,12/15 平台已移植到 `omniget-core`
+> 状态:Phase 0-4 基本完成;14/15 平台 Downloader 已移植到 `omniget-core`,Bilibili auth 网络流程已移入 core,桌面写入通过 runtime provider 适配
> Fork:https://github.com/gkd2323c/omniget
> PR:https://github.com/tonhowtf/omniget/pull/163
@@ -83,7 +83,8 @@ pub trait PlatformDownloader: Send + Sync {
| 组件 | 文件 | 说明 |
|------|------|------|
-| PlatformDownloader trait | `omniget-core/src/platforms/traits.ts` | 统一下载接口 |
+| PlatformDownloader trait | `omniget-core/src/platforms/traits.rs` | 统一下载接口 |
+| CookieProvider trait | `omniget-core/src/platforms/cookie_provider.rs` | 框架无关 Cookie 路径/手动 Cookie 抽象,CLI 默认读取 app data cookies.txt |
| GenericYtdlpDownloader | `omniget-core/src/platforms/generic_ytdlp.rs` | yt-dlp 通用封装,含质量选择、HLS、直链、fallback |
| Platform 枚举 | `omniget-core/src/platforms/mod.rs` | URL→平台检测 |
| is_direct_file_url | `omniget-core/src/platforms/mod.rs` | 直链文件检测 |
@@ -101,6 +102,7 @@ pub trait PlatformDownloader: Send + Sync {
| Reddit | `reddit.rs` | 28KB | cookie + 音频提取 |
| Instagram | `instagram.rs` | 36KB | cookie + GraphQL API |
| TikTok | `tiktok.rs` | 24KB | cookie + 浏览器指纹 |
+| Twitter/X | `twitter.rs` | 41KB | CookieProvider + GraphQL guest token + yt-dlp fallback |
| P2P | `p2p.rs` + `p2p_words.rs` | 16KB | 纯网络传输 |
| DirectFile | `direct_file.rs` | 5KB | HTTP 直链下载 |
@@ -108,36 +110,64 @@ pub trait PlatformDownloader: Send + Sync {
## 4. 未移植平台分析
-### 4.1 Twitter(~41KB) — Phase 3
-
-**阻塞依赖**:
-- `crate::cookies::account_path_for_consumer` — 多账户 Cookie 路径
-- `crate::storage::config::load_settings_standalone` — 读取 PlaybackQuality
-
-**移植方案**:
-1. 在 `omniget-core` 中定义 `CookieProvider` trait:
- ```rust
- pub trait CookieProvider: Send + Sync {
- fn cookie_path_for(&self, domain: &str) -> Option<PathBuf>;
- }
- ```
-2. CLI 实现:返回 `~/.omniget/cookies/cookies.txt`(如果存在)
-3. Tauri 实现:委托给 `crate::cookies::account_path_for_consumer`
-
-### 4.2 Bilibili(~200KB/36 文件) — Phase 4-5
-
-**阻塞依赖**:
-- Twitter 的两个依赖 +
-- WBI 签名算法(`src-tauri/src/platforms/bilibili/wbi.rs`)
-- 认证模块(auth/:二维码、短信、CAPTCHA)
-- 弹幕系统(danmaku/:ASS/XML/JSON 渲染)
-- 番剧/课程解析器(parser/ 8 个子模块)
-
-**移植方案**:
-1. 先解决 CookieProvider/SettingsProvider
-2. 将 wbi.rs、cookie.rs 等辅助模块移到 `omniget-core/src/platforms/bilibili/`
-3. 保持 `mod.rs` 作为入口,子模块按功能分组
-4. 弹幕渲染可保留为可选 feature(`features = ["danmaku"]`)
+### 4.1 Twitter(~41KB) — Phase 3 ✅ core/CLI/桌面注册已完成
+
+已完成:
+- `omniget-core/src/platforms/cookie_provider.rs` 定义 `CookieProvider`
+- `omniget-core/src/platforms/twitter.rs` 已移除 Tauri 依赖
+- CLI 核心平台注册表已接入 `TwitterDownloader`
+- 桌面端 `src-tauri/src/lib.rs` 已切换注册 `omniget_core::platforms::TwitterDownloader`
+- 桌面端已实现 `DesktopCookieProvider`,委托 `crate::cookies::account_path_for_consumer` 与设置里的手动 cookie
+- 原生 Twitter 失败时仍保留 yt-dlp fallback
+- 2026-07-01 实测:`omniget-cli --json --proxy http://127.0.0.1:7897 info https://twitter.com/CTVJLaidlaw/status/1600649710662213632` 命中 `platform=twitter`,GraphQL 200,提取 2 个媒体项
+- 2026-07-01 实测:同 URL `download -o target/twitter-smoke` 成功下载 2 个 mp4(16,344,602 + 14,872,817 bytes)
+
+实测修复:
+- DefaultCookieProvider 从全局 `cookies.txt` 读取时必须按 domain 过滤 Netscape cookie,否则会把整份 cookies 拼进 Cookie header,Windows 下触发 yt-dlp `os error 206`
+- Twitter 多媒体下载分支不能把 progress 发到无人消费的 mpsc channel,否则 direct downloader 会在缓冲区满后死锁
+
+待收尾:
+- `src-tauri/src/platforms/twitter/` 旧适配层已不再注册,可后续单独删除
+- 桌面 GUI 运行时 smoke test 尚未执行;当前完成的是 `cargo check` 层面的注册切换验证
+
+### 4.2 Bilibili(~200KB/36 文件) — Phase 4 基本完成
+
+已迁移到 `omniget-core/src/platforms/bilibili/`:
+- 底座:`api.rs`, `wbi.rs`, `url_kind.rs`, `cdn.rs`, `cover.rs`, `cookie.rs`
+- 解析:`parser/` 全量子模块(video / bangumi / cheese / favlist / list / space / popular / history / watch_later / festival)
+- 媒体选择与元数据:`preview.rs`, `naming.rs`, `nfo.rs`
+- 弹幕:`danmaku/`(proto/xml/json/ass)
+- 下载执行层:`engine/`(fetch/query/mux)
+- 入口与 fallback:`mod.rs`, `legacy.rs`, `notify.rs`
+
+同步完成的抽象与接线:
+- `CookieProvider` 增加 `cookie_path_for_account(domain, slug)`,支持 Bilibili 精确账户 cookie 读取
+- 默认 `CookieProvider` 支持 core/CLI 写入 `cookies/<domain>/<slug>.txt`
+- 新增 `BilibiliRuntimeProvider`,用于注入 active account、settings、session-expired 通知
+- 桌面端实现 `DesktopBilibiliRuntimeProvider`,保留原 Bilibili active-account 选择语义
+- Bilibili auth(二维码、短信、CAPTCHA、账号探测)已迁移到 `omniget-core/src/platforms/bilibili/auth/`
+- `BilibiliRuntimeProvider::persist_account` 负责登录 cookie 持久化,桌面端实现仍复用现有 `cookies::storage` registry
+- 桌面 registry 已从 `platforms::bilibili::BilibiliDownloader` 切到 `omniget_core::platforms::BilibiliDownloader`
+- CLI registry 已注册 core `BilibiliDownloader`
+- `omniget-core` 新增依赖:`once_cell`, `thiserror`, `md-5`, `hex`, `hmac`, `murmur3`, `qrcode`
+
+当前验证:
+- `cargo check -p omniget-core` ✅
+- `cargo check -p omniget-cli` ✅
+- `cargo check` ✅
+- `cargo test -p omniget-core --lib platforms::bilibili` ✅ 51 passed
+- `cargo test -p omniget-core --lib` ✅ 244 passed
+- 2026-07-01 继续移植 auth 后复验:`cargo check -p omniget-core` ✅,`cargo check` ✅,`cargo test -p omniget-core --lib platforms::bilibili` ✅ 51 passed,`cargo test -p omniget-core --lib` ✅ 244 passed
+
+仍未迁移 / 阻塞:
+- 旧 `src-tauri/src/platforms/bilibili/auth/` 仍保留但桌面命令已改用 core auth;可在确认无其他引用后删除
+- 旧 `src-tauri/src/platforms/bilibili/` 下载相关模块仍保留,供 cleanup 过渡使用;删除需要单独清理引用
+- GUI runtime smoke test 尚未执行
+
+建议下一步:
+1. 跑桌面 GUI Bilibili 登录账号下载 smoke test,确认 core Downloader 与桌面 runtime provider 行为一致
+2. 删除旧 Tauri `platforms/bilibili/auth/`,确认 `bilibili_auth` 命令仍只依赖 core auth
+3. 清理旧 Tauri Bilibili 下载模块,只保留必要 adapter 或完全移除旧目录
### 4.3 Magnet — 视需求决定
@@ -183,7 +213,7 @@ cargo check # 全 workspace
1. **`pub use` 不要立即删除**:先添加核心库导出,确认编译通过后再清理旧模块
2. **Tauri 特有依赖**:如遇到 `crate::cookies::*` 或 `crate::storage::*`,需要引入 trait 抽象
3. **测试移植**:`#[cfg(test)]` 模块随文件一起搬运,确保单元测试不中断
-4. **文件后缀**:核心库使用单文件(`youtube.rs`),不使用目录(`youtube/mod.rs`)
+4. **文件布局**:小平台使用单文件(如 `youtube.rs`);Bilibili 这种多子系统平台使用目录模块(`bilibili/mod.rs` + 子模块)
---
@@ -213,7 +243,7 @@ cargo test -p omniget-core --lib platforms::youtube::tests
cargo test -p omniget-core --lib platforms::instagram::tests
```
-当前:**191 tests passed**。
+当前:核心库完整测试 **244 tests passed**;Bilibili 子模块定向测试 **51 tests passed**。
### 6.3 CLI 实操测试
@@ -267,9 +297,9 @@ omniget-cli --proxy http://127.0.0.1:7897 batch urls.txt -m 3
- 包含 `import-cookies` 新命令
- 包含 `omniget-cli` binary
-**PR-B(后续)**:Twitter + Bilibili 移植
-- 需要引入 `CookieProvider` / `SettingsProvider` trait
-- Bilibili 代码量大,需要单独 review
+**PR-B(后续)**:Bilibili smoke + auth/旧模块清理
+- Twitter 已完成 core/CLI/桌面注册切换,旧 `src-tauri/src/platforms/twitter/` 可单独删除
+- Bilibili Downloader 与 auth 已完成 core/CLI/桌面注册切换,仍需 GUI smoke 与旧模块删除
---
@@ -279,24 +309,26 @@ omniget-cli --proxy http://127.0.0.1:7897 batch urls.txt -m 3
|------|------|------|
| P2P 代码验证 | ✅ 已修复 | 使用 `super::p2p_words` 替代 `crate::platforms::p2p_words` |
| Magnet 磁力链 | ⏸ 暂缓 | 需 librqbit 进入核心库 |
-| CLI 平台调度器 | ⏳ 待实现 | 当前 CLI 直接调 ytdlp,尚未使用 PlatformDispatcher 路由 |
-| Bilibili 4K/HDR | ⏳ 待移植 | 原生提取器仍在 Tauri 层 |
+| CLI 平台调度器 | ✅ 已实现 | `info` / `download` 通过核心 PlatformRegistry 路由,非 generic 失败时回退 GenericYtdlp |
+| Twitter CLI 实测 | ✅ 已通过 | info + carousel download 通过,测试产物位于 `src-tauri/target/twitter-smoke/` |
+| Twitter 桌面注册 | ✅ 已切换 | `lib.rs` 注册 core Twitter,并在 setup 安装 `DesktopCookieProvider`;`cargo check` 通过 |
+| Bilibili Downloader 迁移 | ✅ 已切换 | core 已包含 cookie/legacy/notify/mod,CLI 与桌面 registry 已注册 core Bilibili,51 个定向测试通过 |
+| Bilibili auth/旧模块清理 | ⏳ 部分完成 | auth 网络流程已迁入 core,桌面写入由 provider 适配;旧目录暂保留,GUI runtime smoke 未跑 |
---
## 10. 下一步
-如果要继续 Phase 3(Twitter 移植):
+如果要继续 Phase 3 清理:
-1. 在 `omniget-core/src/platforms/` 创建 `cookie_provider.rs` trait
-2. 实现 `DefaultCookieProvider`(CLI 使用)
-3. 移植 `twitter/mod.rs`,抽象 cookie/settings 访问
-4. 编译测试
+1. 删除未注册的 `src-tauri/src/platforms/twitter/` 旧适配层
+2. 运行桌面 GUI smoke test,确认队列中的 Twitter 下载仍走 core Twitter
+3. 视情况优化 Twitter 多文件下载的聚合进度显示
如果要继续 Bilibili:
-1. 先完成 Twitter(解决 cookie/settings 问题)
-2. 将 Bilibili 辅助模块分批移植(wbi → auth → parser → danmaku)
-3. 考虑将弹幕系统拆分为独立 crate 或 feature flag
+1. 跑桌面 GUI 登录账号下载 smoke test,确认 core Downloader 与 `DesktopBilibiliRuntimeProvider` 行为一致
+2. 删除旧 `src-tauri/src/platforms/bilibili/auth/`,确认桌面 auth 命令仍编译通过
+3. 清理旧 `src-tauri/src/platforms/bilibili/` 下载相关代码,只保留必要 adapter 或完全移除旧目录
---
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 10524a5a..e69b1d32 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -4305,8 +4305,14 @@ dependencies = [
"filetime",
"flate2",
"futures",
+ "hex 0.4.3",
+ "hmac",
"m3u8-rs",
+ "md-5",
+ "murmur3",
+ "once_cell",
"open",
+ "qrcode",
"rand 0.10.0",
"regex",
"reqwest 0.12.28",
@@ -4315,6 +4321,7 @@ dependencies = [
"serde_json",
"sha2",
"tar",
+ "thiserror 1.0.69",
"tokio",
"tokio-util",
"tracing",
diff --git a/src-tauri/omniget-cli/src/commands/common.rs b/src-tauri/omniget-cli/src/commands/common.rs
new file mode 100644
index 00000000..3f38823b
--- /dev/null
+++ b/src-tauri/omniget-cli/src/commands/common.rs
@@ -0,0 +1,168 @@
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use anyhow::{anyhow, Context, Result};
+use omniget_core::core::http_client;
+use omniget_core::core::registry::PlatformRegistry;
+use omniget_core::core::ytdlp;
+use omniget_core::models::media::{DownloadOptions, MediaInfo};
+use omniget_core::models::settings::ProxySettings;
+use omniget_core::platforms::{
+ BilibiliDownloader, BlueskyDownloader, DirectFileDownloader, DouyinDownloader,
+ GenericYtdlpDownloader, InstagramDownloader, P2pDownloader, PinterestDownloader,
+ PlatformDownloader, RedditDownloader,
+ TikTokDownloader, TwitchClipsDownloader, TwitterDownloader, VimeoDownloader, YouTubeDownloader,
+};
+use tokio_util::sync::CancellationToken;
+
+use crate::reporter;
+
+pub fn init_cli_runtime(proxy: Option<&str>) -> Result<()> {
+ init_cookie_provider();
+
+ if let Some(proxy_url) = proxy {
+ http_client::init_proxy(parse_proxy(proxy_url)?);
+ } else {
+ http_client::init_proxy(ProxySettings::default());
+ }
+
+ Ok(())
+}
+
+fn init_cookie_provider() {
+ ytdlp::set_global_cookie_file_fn(|| {
+ reporter::default_cookie_path().map(|path| path.to_string_lossy().to_string())
+ });
+}
+
+fn parse_proxy(raw: &str) -> Result<ProxySettings> {
+ let (scheme, rest) = raw
+ .split_once("://")
+ .ok_or_else(|| anyhow!("Proxy must include a scheme, e.g. http://127.0.0.1:7897"))?;
+
+ let proxy_type = match scheme {
+ "http" | "https" | "socks5" => scheme.to_string(),
+ other => return Err(anyhow!("Unsupported proxy scheme: {}", other)),
+ };
+
+ let authority = rest.split('/').next().unwrap_or(rest);
+ let (auth, host_port) = match authority.rsplit_once('@') {
+ Some((auth, host_port)) => (Some(auth), host_port),
+ None => (None, authority),
+ };
+
+ let (host, port) = host_port
+ .rsplit_once(':')
+ .ok_or_else(|| anyhow!("Proxy must include host and port, e.g. http://127.0.0.1:7897"))?;
+
+ if host.is_empty() {
+ return Err(anyhow!("Proxy host cannot be empty"));
+ }
+
+ let port = port
+ .parse::<u16>()
+ .with_context(|| format!("Invalid proxy port: {}", port))?;
+
+ let (username, password) = match auth.and_then(|a| a.split_once(':')) {
+ Some((u, p)) => (u.to_string(), p.to_string()),
+ None => (String::new(), String::new()),
+ };
+
+ Ok(ProxySettings {
+ enabled: true,
+ proxy_type,
+ host: host.to_string(),
+ port,
+ username,
+ password,
+ })
+}
+
+pub fn core_platform_registry() -> PlatformRegistry {
+ let mut registry = PlatformRegistry::new();
+ registry.register(Arc::new(InstagramDownloader::new()));
+ registry.register(Arc::new(PinterestDownloader::new()));
+ registry.register(Arc::new(TikTokDownloader::new()));
+ registry.register(Arc::new(TwitchClipsDownloader::new()));
+ registry.register(Arc::new(TwitterDownloader::new()));
+ registry.register(Arc::new(BlueskyDownloader::new()));
+ registry.register(Arc::new(RedditDownloader::new()));
+ registry.register(Arc::new(YouTubeDownloader::new()));
+ registry.register(Arc::new(VimeoDownloader::new()));
+ registry.register(Arc::new(BilibiliDownloader::new()));
+ registry.register(Arc::new(DouyinDownloader::new()));
+ registry.register(Arc::new(P2pDownloader::new()));
+ registry.register(Arc::new(DirectFileDownloader::new()));
+ registry.register(Arc::new(GenericYtdlpDownloader::new()));
+ registry
+}
+
+pub async fn resolve_media_info(
+ registry: &PlatformRegistry,
+ url: &str,
+) -> Result<(Arc<dyn PlatformDownloader>, MediaInfo)> {
+ let platform = registry
+ .find_platform(url)
+ .unwrap_or_else(|| Arc::new(GenericYtdlpDownloader::new()));
+
+ match platform.get_media_info(url).await {
+ Ok(info) => Ok((platform, info)),
+ Err(primary_error)
+ if platform.name() != "generic" && GenericYtdlpDownloader::new().can_handle(url) =>
+ {
+ let generic: Arc<dyn PlatformDownloader> = Arc::new(GenericYtdlpDownloader::new());
+ match generic.get_media_info(url).await {
+ Ok(info) => Ok((generic, info)),
+ Err(fallback_error) => Err(fallback_error).with_context(|| {
+ format!(
+ "{} extractor failed first: {}; generic fallback also failed",
+ platform.name(),
+ primary_error
+ )
+ }),
+ }
+ }
+ Err(error) => Err(error),
+ }
+}
+
+pub fn download_options(
+ output_dir: PathBuf,
+ quality: Option<u32>,
+ audio_only: bool,
+ subs: Option<String>,
+ format: Option<String>,
+ ytdlp_path: Option<PathBuf>,
+) -> DownloadOptions {
+ let mut custom_ytdlp_args = Vec::new();
+ let download_subtitles = subs.is_some();
+ if let Some(lang) = subs {
+ custom_ytdlp_args.push("--write-subs".to_string());
+ custom_ytdlp_args.push("--sub-langs".to_string());
+ custom_ytdlp_args.push(lang);
+ }
+
+ DownloadOptions {
+ quality: quality.map(|q| q.to_string()),
+ output_dir,
+ filename_template: None,
+ download_subtitles,
+ include_auto_subtitles: false,
+ download_mode: audio_only.then(|| "audio".to_string()),
+ audio_format: audio_only.then(|| format.clone()).flatten(),
+ format_id: (!audio_only).then(|| format.clone()).flatten(),
+ referer: None,
+ extra_headers: None,
+ page_url: None,
+ user_agent: None,
+ cancel_token: CancellationToken::new(),
+ concurrent_fragments: 4,
+ ytdlp_path,
+ torrent_listen_port: None,
+ torrent_id_slot: None,
+ custom_ytdlp_args: (!custom_ytdlp_args.is_empty()).then_some(custom_ytdlp_args),
+ torrent_files: None,
+ torrent_auto_trackers: true,
+ torrent_upnp: false,
+ }
+}
diff --git a/src-tauri/omniget-cli/src/commands/download.rs b/src-tauri/omniget-cli/src/commands/download.rs
index b371dc55..9f70cc48 100644
--- a/src-tauri/omniget-cli/src/commands/download.rs
+++ b/src-tauri/omniget-cli/src/commands/download.rs
@@ -2,15 +2,15 @@ use anyhow::Result;
use indicatif::{ProgressBar, ProgressStyle};
use std::path::PathBuf;
use tokio::sync::mpsc;
-use tokio_util::sync::CancellationToken;
-use omniget_core::core::ytdlp;
use omniget_core::models::progress::ProgressUpdate;
+use crate::commands::common;
use crate::output;
use crate::reporter;
-const PROGRESS_STYLE: &str = "{spinner:.cyan} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, ETA {eta})";
+const PROGRESS_STYLE: &str =
+ "{spinner:.cyan} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos:>3}% {msg}";
const SPINNER_STYLE: &str = "{spinner:.cyan} {msg:.dim}";
pub async fn execute(
@@ -22,13 +22,16 @@ pub async fn execute(
format: Option<String>,
proxy: Option<String>,
) -> Result<()> {
+ common::init_cli_runtime(proxy.as_deref())?;
+
let json_mode = output::is_json_mode();
let pb = ProgressBar::new(100);
- pb.set_style(ProgressStyle::default_bar().template(SPINNER_STYLE).unwrap());
- pb.set_message("Searching for yt-dlp...");
-
- let ytdlp = reporter::find_yt_dlp().await?;
- pb.set_message("yt-dlp found");
+ pb.set_style(
+ ProgressStyle::default_bar()
+ .template(SPINNER_STYLE)
+ .unwrap(),
+ );
+ pb.set_message("Resolving media info...");
let output_path = match output_dir {
Some(dir) => PathBuf::from(dir),
@@ -36,6 +39,17 @@ pub async fn execute(
};
tokio::fs::create_dir_all(&output_path).await.ok();
+ let registry = common::core_platform_registry();
+ let (platform, info) = common::resolve_media_info(&registry, &url).await?;
+
+ if !json_mode {
+ pb.set_message(format!(
+ "Starting {} download: {}",
+ platform.name(),
+ info.title
+ ));
+ }
+
let (tx, mut rx) = mpsc::channel::<ProgressUpdate>(100);
let pb_clone = pb.clone();
@@ -43,64 +57,39 @@ pub async fn execute(
while let Some(update) = rx.recv().await {
if json_mode {
println!(
- r#"{{"type":"progress","percent":{},"downloaded_bytes":{:?},"total_bytes":{:?}}}"#,
- update.percent, update.downloaded_bytes, update.total_bytes
+ r#"{{"type":"progress","percent":{},"downloaded_bytes":{:?},"total_bytes":{:?},"speed_bps":{:?},"eta_seconds":{:?}}}"#,
+ update.percent,
+ update.downloaded_bytes,
+ update.total_bytes,
+ update.speed_bps,
+ update.eta_seconds,
);
} else if update.percent >= 0.0 {
- pb_clone.set_position((update.percent * 100.0) as u64);
+ pb_clone.set_position(update.percent.clamp(0.0, 100.0).round() as u64);
pb_clone.set_style(
ProgressStyle::default_bar()
.template(PROGRESS_STYLE)
.unwrap(),
);
+ if let (Some(downloaded), Some(total)) =
+ (update.downloaded_bytes, update.total_bytes)
+ {
+ pb_clone.set_message(format!("{} / {} bytes", downloaded, total));
+ }
+ } else if !json_mode {
+ let phase = match update.percent as i32 {
+ -2 => "Connecting...",
+ -1 => "Starting...",
+ _ => "Preparing...",
+ };
+ pb_clone.set_message(phase);
}
}
});
- let download_mode = if audio_only { Some("audio") } else { None };
- let msg = format!("Starting: {}", url);
- pb.set_message(msg);
-
- // Build extra flags for proxy, cookies, and subtitles
- let mut extra_flags: Vec<String> = Vec::new();
- if let Some(p) = &proxy {
- extra_flags.push("--proxy".to_string());
- extra_flags.push(p.clone());
- }
-
- // Auto-include cookie file if exists
- if let Some(cookie_file) = reporter::default_cookie_path() {
- if cookie_file.exists() {
- extra_flags.push("--cookies".to_string());
- extra_flags.push(cookie_file.display().to_string());
- }
- }
-
- let download_subtitles = subs.is_some();
- if let Some(lang) = &subs {
- extra_flags.push("--write-subs".to_string());
- extra_flags.push("--sub-langs".to_string());
- extra_flags.push(lang.clone());
- }
-
- let result = ytdlp::download_video(
- &ytdlp,
- &url,
- &output_path,
- quality,
- tx.clone(),
- download_mode,
- format.as_deref(),
- None,
- None,
- CancellationToken::new(),
- reporter::default_cookie_path().as_deref(),
- 4,
- download_subtitles,
- &extra_flags,
- None,
- )
- .await;
+ let ytdlp_path = reporter::find_yt_dlp().await.ok();
+ let opts = common::download_options(output_path, quality, audio_only, subs, format, ytdlp_path);
+ let result = platform.download(&info, &opts, tx.clone()).await;
drop(tx);
let _ = progress_task.await;
@@ -108,21 +97,30 @@ pub async fn execute(
match result {
Ok(dl_result) => {
- if json_mode {
- println!(
- r#"{{"type":"complete","success":true,"file_path":"{}","size":{},"duration":{}}}"#,
- dl_result.file_path.display(),
- dl_result.file_size_bytes,
- dl_result.duration_seconds
- );
+ if output::is_json_mode() {
+ let json = serde_json::json!({
+ "type": "complete",
+ "success": true,
+ "platform": platform.name(),
+ "file_path": dl_result.file_path,
+ "size": dl_result.file_size_bytes,
+ "duration": dl_result.duration_seconds,
+ });
+ println!("{}", json);
} else {
println!("✓ Downloaded to: {}", dl_result.file_path.display());
}
Ok(())
}
Err(e) => {
- if json_mode {
- println!(r#"{{"type":"complete","success":false,"error":"{}"}}"#, e);
+ if output::is_json_mode() {
+ let json = serde_json::json!({
+ "type": "complete",
+ "success": false,
+ "platform": platform.name(),
+ "error": e.to_string(),
+ });
+ println!("{}", json);
} else {
eprintln!("✗ Failed: {}", e);
}
diff --git a/src-tauri/omniget-cli/src/commands/info.rs b/src-tauri/omniget-cli/src/commands/info.rs
index 1eedbed3..4f8afd8a 100644
--- a/src-tauri/omniget-cli/src/commands/info.rs
+++ b/src-tauri/omniget-cli/src/commands/info.rs
@@ -1,67 +1,46 @@
use anyhow::Result;
-use omniget_core::core::ytdlp;
-
+use crate::commands::common;
use crate::output;
-use crate::reporter::find_yt_dlp;
-use crate::reporter;
pub async fn execute(url: String, proxy: Option<String>) -> Result<()> {
- let ytdlp = find_yt_dlp().await?;
-
- let mut extra_flags: Vec<String> = Vec::new();
- if let Some(p) = &proxy {
- extra_flags.push("--proxy".to_string());
- extra_flags.push(p.clone());
- }
-
- // Auto-include cookie file if exists
- if let Some(cookie_file) = reporter::default_cookie_path() {
- if cookie_file.exists() {
- extra_flags.push("--cookies".to_string());
- extra_flags.push(cookie_file.display().to_string());
- }
- }
-
- let info = match tokio::time::timeout(
- std::time::Duration::from_secs(120),
- ytdlp::get_video_info(&ytdlp, &url, &extra_flags)
- ).await {
- Ok(Ok(info)) => info,
- Ok(Err(e)) => return Err(e),
- Err(_) => anyhow::bail!("Timed out after 120s"),
- };
+ common::init_cli_runtime(proxy.as_deref())?;
- let formats = ytdlp::parse_formats(&info);
+ let registry = common::core_platform_registry();
+ let (platform, info) = common::resolve_media_info(&registry, &url).await?;
if output::is_json_mode() {
- println!(
- r#"{{"url":"{}","title":"{}","duration":{},"uploader":"{}","format_count":{}}}"#,
- url.replace('"', "\\\""),
- info.get("title").and_then(|v| v.as_str()).unwrap_or("").replace('"', "\\\""),
- info.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0),
- info.get("uploader").and_then(|v| v.as_str()).unwrap_or("").replace('"', "\\\""),
- formats.len()
- );
+ let json = serde_json::json!({
+ "url": url,
+ "platform": platform.name(),
+ "title": info.title,
+ "duration": info.duration_seconds.unwrap_or(0.0),
+ "uploader": info.author,
+ "media_type": info.media_type,
+ "format_count": info.available_qualities.len(),
+ "thumbnail_url": info.thumbnail_url,
+ "file_size_bytes": info.file_size_bytes,
+ });
+ println!("{}", json);
} else {
- println!(
- "Title: {}",
- info.get("title").and_then(|v| v.as_str()).unwrap_or("")
- );
- println!(
- "Duration: {:.0}s",
- info.get("duration").and_then(|v| v.as_f64()).unwrap_or(0.0)
- );
- println!("Uploader: {}", info.get("uploader").and_then(|v| v.as_str()).unwrap_or(""));
- println!("Formats: {}", formats.len());
- for f in formats.iter().take(15) {
- let res = f.resolution.as_deref().unwrap_or("?");
+ println!("Platform: {}", platform.name());
+ println!("Title: {}", info.title);
+ println!("Duration: {:.0}s", info.duration_seconds.unwrap_or(0.0));
+ println!("Uploader: {}", info.author);
+ println!("Type: {:?}", info.media_type);
+ println!("Formats: {}", info.available_qualities.len());
+
+ for quality in info.available_qualities.iter().take(15) {
+ let resolution = if quality.width > 0 && quality.height > 0 {
+ format!("{}x{}", quality.width, quality.height)
+ } else if quality.height > 0 {
+ format!("{}p", quality.height)
+ } else {
+ "?".to_string()
+ };
println!(
- " {:<10} {:<6} {:>5} {}",
- f.format_id,
- f.ext,
- res,
- f.format_note.as_deref().unwrap_or("")
+ " {:<14} {:<8} {:>8} {}",
+ quality.label, quality.format, resolution, quality.url
);
}
}
diff --git a/src-tauri/omniget-cli/src/commands/mod.rs b/src-tauri/omniget-cli/src/commands/mod.rs
index a8b20fd7..76d18b0d 100644
--- a/src-tauri/omniget-cli/src/commands/mod.rs
+++ b/src-tauri/omniget-cli/src/commands/mod.rs
@@ -1,4 +1,5 @@
+pub mod batch;
+pub mod common;
pub mod download;
pub mod import_cookies;
pub mod info;
-pub mod batch;
diff --git a/src-tauri/omniget-cli/src/reporter.rs b/src-tauri/omniget-cli/src/reporter.rs
index 7341dbfe..9fc68adc 100644
--- a/src-tauri/omniget-cli/src/reporter.rs
+++ b/src-tauri/omniget-cli/src/reporter.rs
@@ -42,7 +42,7 @@ impl CliReporter {
println!("{}", json);
} else {
if update.percent >= 0.0 {
- self.pb.set_position((update.percent * 100.0) as u64);
+ self.pb.set_position(update.percent.clamp(0.0, 100.0).round() as u64);
self.pb.set_style(
ProgressStyle::default_bar()
.template(PROGRESS_STYLE)
diff --git a/src-tauri/omniget-core/Cargo.toml b/src-tauri/omniget-core/Cargo.toml
index 771339ad..8bf35901 100644
--- a/src-tauri/omniget-core/Cargo.toml
+++ b/src-tauri/omniget-core/Cargo.toml
@@ -35,6 +35,13 @@ urlencoding = "2"
rand = "0.10.0"
base64 = "0.22.1"
sha2 = "0.10"
+hmac = "0.12"
+murmur3 = "0.5"
+md-5 = "0.10"
+hex = "0.4"
+once_cell = "1"
+thiserror = "1"
+qrcode = { version = "0.14", default-features = false, features = ["svg"] }
filetime = "0.2.27"
zip = { version = "2", default-features = false, features = ["deflate"] }
tar = "0.4"
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/api.rs b/src-tauri/omniget-core/src/platforms/bilibili/api.rs
new file mode 100644
index 00000000..80cd277b
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/api.rs
@@ -0,0 +1,369 @@
+use std::time::Duration;
+
+use reqwest::header::{HeaderMap, HeaderValue, COOKIE, REFERER, USER_AGENT};
+use reqwest::{Client, StatusCode};
+use serde::de::DeserializeOwned;
+use serde_json::Value;
+use thiserror::Error;
+
+pub const DEFAULT_REFERER: &str = "https://www.bilibili.com";
+pub const DEFAULT_USER_AGENT: &str =
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36";
+
+const REQUEST_TIMEOUT_SECS: u64 = 20;
+const MAX_RETRIES: u32 = 3;
+const RETRY_BACKOFF_MS: u64 = 600;
+
+#[derive(Debug, Error)]
+pub enum BilibiliError {
+ #[error("errors.bilibili.network_failed")]
+ Network(#[source] reqwest::Error),
+ #[error("errors.bilibili.http_status")]
+ HttpStatus(StatusCode),
+ #[error("errors.bilibili.invalid_json")]
+ InvalidJson(#[source] serde_json::Error),
+ #[error("errors.bilibili.api_code")]
+ ApiCode { code: i64, message: String },
+ #[error("errors.bilibili.not_logged_in")]
+ NotLoggedIn,
+ #[error("errors.bilibili.geo_blocked")]
+ GeoBlocked,
+ #[error("errors.bilibili.rate_limited")]
+ RateLimited,
+ #[error("errors.bilibili.premium_required")]
+ PremiumRequired,
+ #[error("errors.bilibili.content_unavailable")]
+ ContentUnavailable,
+ #[error("errors.bilibili.cookie_missing")]
+ CookieMissing,
+ #[error("errors.bilibili.cancelled")]
+ Cancelled,
+}
+
+impl BilibiliError {
+ pub fn i18n_key(&self) -> &'static str {
+ match self {
+ BilibiliError::Network(_) => "errors.bilibili.network_failed",
+ BilibiliError::HttpStatus(_) => "errors.bilibili.http_status",
+ BilibiliError::InvalidJson(_) => "errors.bilibili.invalid_json",
+ BilibiliError::ApiCode { .. } => "errors.bilibili.api_code",
+ BilibiliError::NotLoggedIn => "errors.bilibili.not_logged_in",
+ BilibiliError::GeoBlocked => "errors.bilibili.geo_blocked",
+ BilibiliError::RateLimited => "errors.bilibili.rate_limited",
+ BilibiliError::PremiumRequired => "errors.bilibili.premium_required",
+ BilibiliError::ContentUnavailable => "errors.bilibili.content_unavailable",
+ BilibiliError::CookieMissing => "errors.bilibili.cookie_missing",
+ BilibiliError::Cancelled => "errors.bilibili.cancelled",
+ }
+ }
+}
+
+pub type Result<T> = std::result::Result<T, BilibiliError>;
+
+#[derive(Clone)]
+pub struct ApiClient {
+ inner: Client,
+ referer: String,
+ user_agent: String,
+ cookie_header: Option<String>,
+ account_slug: Option<String>,
+}
+
+impl ApiClient {
+ pub fn new() -> Result<Self> {
+ let inner = crate::core::http_client::apply_global_proxy(
+ Client::builder()
+ .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))
+ .connect_timeout(Duration::from_secs(10)),
+ )
+ .build()
+ .map_err(BilibiliError::Network)?;
+ Ok(Self {
+ inner,
+ referer: DEFAULT_REFERER.to_string(),
+ user_agent: DEFAULT_USER_AGENT.to_string(),
+ cookie_header: None,
+ account_slug: None,
+ })
+ }
+
+ pub fn with_referer(mut self, referer: impl Into<String>) -> Self {
+ self.referer = referer.into();
+ self
+ }
+
+ pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
+ self.user_agent = ua.into();
+ self
+ }
+
+ pub fn with_account(mut self, slug: impl Into<String>) -> Self {
+ let slug = slug.into();
+ self.cookie_header = build_cookie_header_for_account(&slug);
+ if self.cookie_header.is_some() {
+ self.account_slug = Some(slug);
+ }
+ self
+ }
+
+ pub fn with_anonymous_cookies(mut self) -> Self {
+ self.cookie_header = build_cookie_header_for_account("_anonymous");
+ self
+ }
+
+ pub fn with_raw_cookies(mut self, header: impl Into<String>) -> Self {
+ self.cookie_header = Some(header.into());
+ self
+ }
+
+ pub fn account_slug(&self) -> Option<&str> {
+ self.account_slug.as_deref()
+ }
+
+ pub fn user_agent(&self) -> &str {
+ &self.user_agent
+ }
+
+ pub fn cookie_header(&self) -> Option<&str> {
+ self.cookie_header.as_deref()
+ }
+
+ fn build_headers(&self) -> HeaderMap {
+ let mut h = HeaderMap::new();
+ if let Ok(v) = HeaderValue::from_str(&self.referer) {
+ h.insert(REFERER, v);
+ }
+ if let Ok(v) = HeaderValue::from_str(&self.user_agent) {
+ h.insert(USER_AGENT, v);
+ }
+ if let Some(c) = self.cookie_header.as_ref() {
+ if let Ok(v) = HeaderValue::from_str(c) {
+ h.insert(COOKIE, v);
+ }
+ }
+ h
+ }
+
+ pub async fn get_json(&self, url: &str) -> Result<Value> {
+ let mut last_err: Option<BilibiliError> = None;
+ for attempt in 0..MAX_RETRIES {
+ match self
+ .inner
+ .get(url)
+ .headers(self.build_headers())
+ .send()
+ .await
+ {
+ Ok(resp) => {
+ let status = resp.status();
+ if status.is_success() {
+ let text = resp.text().await.map_err(BilibiliError::Network)?;
+ let json: Value =
+ serde_json::from_str(&text).map_err(BilibiliError::InvalidJson)?;
+ return Ok(json);
+ }
+ if status == StatusCode::TOO_MANY_REQUESTS {
+ last_err = Some(BilibiliError::RateLimited);
+ } else if status.is_server_error() {
+ last_err = Some(BilibiliError::HttpStatus(status));
+ } else {
+ return Err(BilibiliError::HttpStatus(status));
+ }
+ }
+ Err(e) => {
+ last_err = Some(BilibiliError::Network(e));
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(RETRY_BACKOFF_MS * 2u64.pow(attempt))).await;
+ }
+ Err(last_err.unwrap_or(BilibiliError::ContentUnavailable))
+ }
+
+ pub async fn post_json(&self, url: &str, body: &Value) -> Result<Value> {
+ let resp = self
+ .inner
+ .post(url)
+ .headers(self.build_headers())
+ .json(body)
+ .send()
+ .await
+ .map_err(BilibiliError::Network)?;
+ let status = resp.status();
+ let text = resp.text().await.map_err(BilibiliError::Network)?;
+ if !status.is_success() {
+ return Err(BilibiliError::HttpStatus(status));
+ }
+ serde_json::from_str(&text).map_err(BilibiliError::InvalidJson)
+ }
+
+ pub async fn post_form(&self, url: &str, form: &[(&str, &str)]) -> Result<Value> {
+ let resp = self
+ .inner
+ .post(url)
+ .headers(self.build_headers())
+ .form(form)
+ .send()
+ .await
+ .map_err(BilibiliError::Network)?;
+ let status = resp.status();
+ let text = resp.text().await.map_err(BilibiliError::Network)?;
+ if !status.is_success() {
+ return Err(BilibiliError::HttpStatus(status));
+ }
+ serde_json::from_str(&text).map_err(BilibiliError::InvalidJson)
+ }
+
+ pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>> {
+ let resp = self
+ .inner
+ .get(url)
+ .headers(self.build_headers())
+ .send()
+ .await
+ .map_err(BilibiliError::Network)?;
+ let status = resp.status();
+ if !status.is_success() {
+ return Err(BilibiliError::HttpStatus(status));
+ }
+ let bytes = resp.bytes().await.map_err(BilibiliError::Network)?;
+ Ok(bytes.to_vec())
+ }
+
+ pub async fn head_content_length(&self, url: &str) -> Result<Option<u64>> {
+ let resp = self
+ .inner
+ .head(url)
+ .headers(self.build_headers())
+ .send()
+ .await
+ .map_err(BilibiliError::Network)?;
+ let status = resp.status();
+ if !status.is_success() {
+ return Err(BilibiliError::HttpStatus(status));
+ }
+ Ok(resp
+ .headers()
+ .get(reqwest::header::CONTENT_LENGTH)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|s| s.parse::<u64>().ok()))
+ }
+
+ pub async fn resolve_redirect(&self, url: &str) -> Result<String> {
+ let no_follow = crate::core::http_client::apply_global_proxy(
+ Client::builder()
+ .timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))
+ .redirect(reqwest::redirect::Policy::none()),
+ )
+ .build()
+ .map_err(BilibiliError::Network)?;
+ let resp = no_follow
+ .get(url)
+ .headers(self.build_headers())
+ .send()
+ .await
+ .map_err(BilibiliError::Network)?;
+ if let Some(loc) = resp.headers().get(reqwest::header::LOCATION) {
+ if let Ok(s) = loc.to_str() {
+ return Ok(s.to_string());
+ }
+ }
+ Ok(url.to_string())
+ }
+}
+
+pub fn check_api_response(value: &Value) -> Result<&Value> {
+ let code = value.get("code").and_then(|v| v.as_i64()).unwrap_or(-1);
+ if code == 0 {
+ if let Some(data) = value.get("data") {
+ return Ok(data);
+ }
+ if let Some(result) = value.get("result") {
+ return Ok(result);
+ }
+ return Ok(value);
+ }
+ let message = value
+ .get("message")
+ .and_then(|v| v.as_str())
+ .unwrap_or("")
+ .to_string();
+ Err(map_api_code(code, message))
+}
+
+pub fn map_api_code(code: i64, message: String) -> BilibiliError {
+ match code {
+ -101 | -400 => BilibiliError::NotLoggedIn,
+ -403 | 62002 => BilibiliError::ContentUnavailable,
+ -404 | 6002003 => BilibiliError::ContentUnavailable,
+ -412 => BilibiliError::RateLimited,
+ 87007 | 87008 => BilibiliError::PremiumRequired,
+ 62004 => BilibiliError::GeoBlocked,
+ _ => BilibiliError::ApiCode { code, message },
+ }
+}
+
+pub fn parse_data<T: DeserializeOwned>(value: &Value) -> Result<T> {
+ serde_json::from_value(value.clone()).map_err(BilibiliError::InvalidJson)
+}
+
+fn build_cookie_header_for_account(slug: &str) -> Option<String> {
+ let path = crate::platforms::cookie_provider::cookie_path_for_account("bilibili.com", slug)?;
+ let content = std::fs::read_to_string(&path).ok()?;
+ cookie_header_from_netscape(&content)
+}
+
+fn cookie_header_from_netscape(content: &str) -> Option<String> {
+ let mut pairs: Vec<String> = Vec::new();
+ for raw in content.lines() {
+ let line = raw.trim_end();
+ if line.is_empty() {
+ continue;
+ }
+ let effective = if let Some(rest) = line.strip_prefix("#HttpOnly_") {
+ rest
+ } else if line.starts_with('#') {
+ continue;
+ } else {
+ line
+ };
+ let mut parts = effective.split('\t');
+ let _domain = parts.next();
+ let _include = parts.next();
+ let _path = parts.next();
+ let _secure = parts.next();
+ let _expires = parts.next();
+ let name = parts.next();
+ let value = parts.next();
+ if let (Some(n), Some(v)) = (name, value) {
+ pairs.push(format!("{}={}", n, v));
+ }
+ }
+ if pairs.is_empty() {
+ None
+ } else {
+ Some(pairs.join("; "))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn cookie_header_keeps_httponly_netscape_cookies() {
+ let raw = "# Netscape HTTP Cookie File\n#HttpOnly_.bilibili.com\tTRUE\t/\tTRUE\t1830000000\tSESSDATA\tabc123\n.bilibili.com\tTRUE\t/\tTRUE\t1830000000\tbili_jct\tcsrf\n";
+ let header = cookie_header_from_netscape(raw).unwrap();
+
+ assert!(header.contains("SESSDATA=abc123"));
+ assert!(header.contains("bili_jct=csrf"));
+ assert!(!header.contains("#HttpOnly_"));
+ }
+
+ #[test]
+ fn cookie_header_skips_regular_comments() {
+ let raw = "# comment\n.bilibili.com\tTRUE\t/\tTRUE\t1830000000\tDedeUserID\t42\n";
+ let header = cookie_header_from_netscape(raw).unwrap();
+
+ assert_eq!(header, "DedeUserID=42");
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/auth/captcha.rs b/src-tauri/omniget-core/src/platforms/bilibili/auth/captcha.rs
new file mode 100644
index 00000000..4937a743
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/auth/captcha.rs
@@ -0,0 +1,41 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+
+const CAPTCHA_URL: &str = "https://passport.bilibili.com/x/passport-login/captcha?source=main_h5";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CaptchaChallenge {
+ pub token: String,
+ pub geetest_gt: String,
+ pub geetest_challenge: String,
+}
+
+pub async fn request_challenge(client: &ApiClient) -> Result<CaptchaChallenge> {
+ let raw = client.get_json(CAPTCHA_URL).await?;
+ let data = check_api_response(&raw)?;
+ let token = data
+ .get("token")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?
+ .to_string();
+ let geetest = data
+ .get("geetest")
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let gt = geetest
+ .get("gt")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?
+ .to_string();
+ let challenge = geetest
+ .get("challenge")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?
+ .to_string();
+ Ok(CaptchaChallenge {
+ token,
+ geetest_gt: gt,
+ geetest_challenge: challenge,
+ })
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/auth/mod.rs b/src-tauri/omniget-core/src/platforms/bilibili/auth/mod.rs
new file mode 100644
index 00000000..b5977684
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/auth/mod.rs
@@ -0,0 +1,112 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::api::{ApiClient, BilibiliError, Result};
+use super::{runtime_persist_account, BilibiliAuthCookie};
+
+pub mod captcha;
+pub mod qr;
+pub mod sms;
+
+const NAV_URL: &str = "https://api.bilibili.com/x/web-interface/nav";
+const LOGOUT_URL: &str = "https://passport.bilibili.com/login/exit/v2";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AccountInfo {
+ pub uname: String,
+ pub mid: u64,
+ pub face: Option<String>,
+ pub is_vip: bool,
+ pub vip_due_secs: Option<u64>,
+}
+
+pub async fn fetch_account_info(client: &ApiClient) -> Result<AccountInfo> {
+ let raw = client.get_json(NAV_URL).await?;
+ let code = raw.get("code").and_then(Value::as_i64).unwrap_or(-1);
+ let data = if code == 0 {
+ raw.get("data")
+ } else {
+ Some(&raw)
+ }
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let is_login = data
+ .get("isLogin")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ if !is_login {
+ return Err(BilibiliError::NotLoggedIn);
+ }
+ let uname = data
+ .get("uname")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let mid = data.get("mid").and_then(Value::as_u64).unwrap_or(0);
+ let face = data.get("face").and_then(Value::as_str).map(String::from);
+ let vip_status = data.get("vipStatus").and_then(Value::as_u64).unwrap_or(0);
+ let vip_due_ms = data
+ .get("vip_due_date")
+ .or_else(|| data.get("vipDueDate"))
+ .and_then(Value::as_u64);
+ Ok(AccountInfo {
+ uname,
+ mid,
+ face,
+ is_vip: vip_status == 1,
+ vip_due_secs: vip_due_ms.map(|ms| ms / 1000),
+ })
+}
+
+pub async fn logout(client: &ApiClient, csrf: &str) -> Result<()> {
+ let url = format!("{}?biliCSRF={}", LOGOUT_URL, urlencoding::encode(csrf));
+ let _ = client.post_form(&url, &[("biliCSRF", csrf)]).await?;
+ Ok(())
+}
+
+pub fn slug_from_uname(uname: &str) -> String {
+ let lower = uname.to_lowercase();
+ let cleaned: String = lower
+ .chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
+ c
+ } else {
+ '-'
+ }
+ })
+ .collect();
+ if cleaned.is_empty() {
+ "user".to_string()
+ } else {
+ cleaned
+ }
+}
+
+pub fn persist_account(
+ cookies: &[(String, String)],
+ uname: &str,
+ source_label: &str,
+) -> std::result::Result<String, String> {
+ let now_unix = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs() as i64)
+ .unwrap_or(0);
+ let expires = now_unix + 60 * 60 * 24 * 365;
+
+ let entries: Vec<BilibiliAuthCookie> = cookies
+ .iter()
+ .map(|(name, value)| BilibiliAuthCookie {
+ domain: ".bilibili.com".to_string(),
+ http_only: name == "SESSDATA",
+ path: "/".to_string(),
+ secure: true,
+ expires,
+ name: name.clone(),
+ value: value.clone(),
+ host_only: None,
+ same_site: None,
+ })
+ .collect();
+
+ runtime_persist_account(&entries, uname, source_label)
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/auth/qr.rs b/src-tauri/omniget-core/src/platforms/bilibili/auth/qr.rs
new file mode 100644
index 00000000..e9f74d51
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/auth/qr.rs
@@ -0,0 +1,140 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{fetch_account_info, persist_account};
+
+const QR_GENERATE_URL: &str =
+ "https://passport.bilibili.com/x/passport-login/web/qrcode/generate?source=main-fe-header&go_url=https%3A%2F%2Fwww.bilibili.com%2F&web_location=333.1007";
+const QR_POLL_URL: &str = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct QrSession {
+ pub qrcode_key: String,
+ pub login_url: String,
+ pub qrcode_svg: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(tag = "status", rename_all = "snake_case")]
+pub enum QrPollStatus {
+ Pending,
+ Scanned,
+ Success {
+ slug: String,
+ uname: String,
+ mid: u64,
+ is_vip: bool,
+ },
+ Expired,
+ Cancelled,
+}
+
+pub async fn generate(client: &ApiClient) -> Result<QrSession> {
+ let raw = client.get_json(QR_GENERATE_URL).await?;
+ let data = check_api_response(&raw)?;
+ let login_url = data
+ .get("url")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?
+ .to_string();
+ let qrcode_key = data
+ .get("qrcode_key")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?
+ .to_string();
+ let svg = render_qr_svg(&login_url)?;
+ Ok(QrSession {
+ qrcode_key,
+ login_url,
+ qrcode_svg: svg,
+ })
+}
+
+pub async fn poll(client: &ApiClient, qrcode_key: &str) -> Result<QrPollStatus> {
+ let url = format!(
+ "{}?qrcode_key={}",
+ QR_POLL_URL,
+ urlencoding::encode(qrcode_key)
+ );
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ let code = data.get("code").and_then(Value::as_i64).unwrap_or(-1);
+ match code {
+ 86101 => Ok(QrPollStatus::Pending),
+ 86090 => Ok(QrPollStatus::Scanned),
+ 86038 => Ok(QrPollStatus::Expired),
+ 86039 | 86087 => Ok(QrPollStatus::Cancelled),
+ 0 => {
+ let redirect_url = data
+ .get("url")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let cookies = extract_cookies_from_url(redirect_url);
+ if cookies.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ finalize(client, cookies).await
+ }
+ _ => Err(BilibiliError::ApiCode {
+ code,
+ message: data
+ .get("message")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ }),
+ }
+}
+
+async fn finalize(base_client: &ApiClient, cookies: Vec<(String, String)>) -> Result<QrPollStatus> {
+ let cookie_header = cookies
+ .iter()
+ .map(|(k, v)| format!("{}={}", k, v))
+ .collect::<Vec<_>>()
+ .join("; ");
+
+ let probe_client = ApiClient::new()?
+ .with_user_agent(base_client.user_agent())
+ .with_raw_cookies(cookie_header);
+
+ let info = fetch_account_info(&probe_client).await?;
+ let slug = persist_account(&cookies, &info.uname, "QR login")
+ .map_err(|_| BilibiliError::ContentUnavailable)?;
+
+ Ok(QrPollStatus::Success {
+ slug,
+ uname: info.uname,
+ mid: info.mid,
+ is_vip: info.is_vip,
+ })
+}
+
+fn extract_cookies_from_url(redirect_url: &str) -> Vec<(String, String)> {
+ let mut out: Vec<(String, String)> = Vec::new();
+ if let Ok(u) = url::Url::parse(redirect_url) {
+ for (k, v) in u.query_pairs() {
+ let key = k.to_string();
+ if matches!(
+ key.as_str(),
+ "SESSDATA" | "bili_jct" | "DedeUserID" | "DedeUserID__ckMd5" | "sid"
+ ) {
+ out.push((key, v.into_owned()));
+ }
+ }
+ }
+ out
+}
+
+fn render_qr_svg(content: &str) -> Result<String> {
+ use qrcode::render::svg;
+ use qrcode::QrCode;
+
+ let code = QrCode::new(content.as_bytes()).map_err(|_| BilibiliError::ContentUnavailable)?;
+ let svg = code
+ .render::<svg::Color>()
+ .min_dimensions(240, 240)
+ .quiet_zone(true)
+ .build();
+ Ok(svg)
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/auth/sms.rs b/src-tauri/omniget-core/src/platforms/bilibili/auth/sms.rs
new file mode 100644
index 00000000..c8620b17
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/auth/sms.rs
@@ -0,0 +1,145 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{fetch_account_info, persist_account};
+
+const SMS_SEND_URL: &str = "https://passport.bilibili.com/x/passport-login/web/sms/send";
+const SMS_LOGIN_URL: &str = "https://passport.bilibili.com/x/passport-login/web/login/sms";
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SmsSendInput {
+ pub cid: String,
+ pub tel: String,
+ pub captcha_token: String,
+ pub geetest_challenge: String,
+ pub geetest_validate: String,
+ pub geetest_seccode: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SmsSendResult {
+ pub captcha_key: String,
+ pub recaptcha_url: Option<String>,
+}
+
+pub async fn send(client: &ApiClient, input: SmsSendInput) -> Result<SmsSendResult> {
+ let form = [
+ ("cid", input.cid.as_str()),
+ ("tel", input.tel.as_str()),
+ ("source", "main-fe-header"),
+ ("token", input.captcha_token.as_str()),
+ ("challenge", input.geetest_challenge.as_str()),
+ ("validate", input.geetest_validate.as_str()),
+ ("seccode", input.geetest_seccode.as_str()),
+ ];
+ let raw = client.post_form(SMS_SEND_URL, &form).await?;
+ let data = check_api_response(&raw)?;
+ let captcha_key = data
+ .get("captcha_key")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?
+ .to_string();
+ let recaptcha = data
+ .get("recaptcha_url")
+ .and_then(Value::as_str)
+ .map(String::from);
+ Ok(SmsSendResult {
+ captcha_key,
+ recaptcha_url: recaptcha,
+ })
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SmsVerifyInput {
+ pub cid: String,
+ pub tel: String,
+ pub code: String,
+ pub captcha_key: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SmsVerifyResult {
+ pub slug: String,
+ pub uname: String,
+ pub mid: u64,
+ pub is_vip: bool,
+}
+
+pub async fn verify(client: &ApiClient, input: SmsVerifyInput) -> Result<SmsVerifyResult> {
+ let form = [
+ ("cid", input.cid.as_str()),
+ ("tel", input.tel.as_str()),
+ ("code", input.code.as_str()),
+ ("source", "main-fe-header"),
+ ("captcha_key", input.captcha_key.as_str()),
+ ("go_url", "https://www.bilibili.com/"),
+ ("keep", "true"),
+ ];
+ let raw = client.post_form(SMS_LOGIN_URL, &form).await?;
+ let data = check_api_response(&raw)?;
+ let status = data.get("status").and_then(Value::as_i64).unwrap_or(0);
+ if status != 0 {
+ return Err(BilibiliError::ApiCode {
+ code: status,
+ message: data
+ .get("message")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ });
+ }
+
+ let cookies = extract_cookies(data);
+ if cookies.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ let cookie_header = cookies
+ .iter()
+ .map(|(k, v)| format!("{}={}", k, v))
+ .collect::<Vec<_>>()
+ .join("; ");
+ let probe_client = ApiClient::new()?
+ .with_user_agent(client.user_agent())
+ .with_raw_cookies(cookie_header);
+ let info = fetch_account_info(&probe_client).await?;
+ let slug = persist_account(&cookies, &info.uname, "SMS login")
+ .map_err(|_| BilibiliError::ContentUnavailable)?;
+ Ok(SmsVerifyResult {
+ slug,
+ uname: info.uname,
+ mid: info.mid,
+ is_vip: info.is_vip,
+ })
+}
+
+fn extract_cookies(data: &Value) -> Vec<(String, String)> {
+ let mut out: Vec<(String, String)> = Vec::new();
+ if let Some(arr) = data
+ .get("cookie_info")
+ .and_then(|v| v.get("cookies"))
+ .and_then(Value::as_array)
+ {
+ for c in arr {
+ if let (Some(name), Some(value)) = (
+ c.get("name").and_then(Value::as_str),
+ c.get("value").and_then(Value::as_str),
+ ) {
+ out.push((name.to_string(), value.to_string()));
+ }
+ }
+ }
+ if let Some(url) = data.get("url").and_then(Value::as_str) {
+ if let Ok(u) = url::Url::parse(url) {
+ for (k, v) in u.query_pairs() {
+ if matches!(
+ k.as_ref(),
+ "SESSDATA" | "bili_jct" | "DedeUserID" | "DedeUserID__ckMd5" | "sid"
+ ) {
+ out.push((k.to_string(), v.into_owned()));
+ }
+ }
+ }
+ }
+ out
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/cdn.rs b/src-tauri/omniget-core/src/platforms/bilibili/cdn.rs
new file mode 100644
index 00000000..7726f95d
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/cdn.rs
@@ -0,0 +1,139 @@
+const BLOCKED_HOST_PATTERNS: &[&str] = &["szbdyd.com", "mcdn"];
+
+pub fn parse_hosts(setting_value: &str) -> Vec<String> {
+ setting_value
+ .split([',', '\n'])
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty() && !s.starts_with('#'))
+ .map(|s| {
+ s.trim_start_matches("http://")
+ .trim_start_matches("https://")
+ .trim_end_matches('/')
+ .to_string()
+ })
+ .filter(|s| !s.is_empty())
+ .collect()
+}
+
+pub fn filter_blocked(urls: &[String]) -> Vec<String> {
+ urls.iter()
+ .filter(|u| !host_is_blocked(u))
+ .cloned()
+ .collect()
+}
+
+pub fn host_is_blocked(url: &str) -> bool {
+ let host = match url::Url::parse(url)
+ .ok()
+ .and_then(|u| u.host_str().map(String::from))
+ {
+ Some(h) => h.to_lowercase(),
+ None => return false,
+ };
+ BLOCKED_HOST_PATTERNS
+ .iter()
+ .any(|p| host.contains(&p.to_lowercase()))
+}
+
+pub fn replace_host(url: &str, new_host: &str) -> Option<String> {
+ let parsed = url::Url::parse(url).ok()?;
+ let scheme = parsed.scheme();
+ let path = parsed.path();
+ let query = parsed
+ .query()
+ .map(|q| format!("?{}", q))
+ .unwrap_or_default();
+ Some(format!("{}://{}{}{}", scheme, new_host, path, query))
+}
+
+pub fn expand_with_alternatives(
+ primary: &str,
+ backups: &[String],
+ alt_hosts: &[String],
+ prefer_alternatives: bool,
+) -> Vec<String> {
+ let mut originals: Vec<String> = std::iter::once(primary.to_string())
+ .chain(backups.iter().cloned())
+ .collect();
+ originals = filter_blocked(&originals);
+
+ let mut alternatives: Vec<String> = Vec::new();
+ for source in &originals {
+ for host in alt_hosts {
+ if let Some(replaced) = replace_host(source, host) {
+ if !alternatives.contains(&replaced) && !originals.contains(&replaced) {
+ alternatives.push(replaced);
+ }
+ }
+ }
+ }
+
+ let mut chain: Vec<String> = if prefer_alternatives {
+ alternatives.into_iter().chain(originals).collect()
+ } else {
+ originals.into_iter().chain(alternatives).collect()
+ };
+
+ let mut seen = std::collections::HashSet::new();
+ chain.retain(|u| seen.insert(u.clone()));
+ chain
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parse_hosts_accepts_csv_and_newlines() {
+ let raw = "upos-hz-mirrorcos.bilivideo.com, upos-sz-mirroraliov.bilivideo.com\nhttps://upos-cos-cf.bilibili.com/\n#comment\n";
+ let hosts = parse_hosts(raw);
+ assert_eq!(
+ hosts,
+ vec![
+ "upos-hz-mirrorcos.bilivideo.com",
+ "upos-sz-mirroraliov.bilivideo.com",
+ "upos-cos-cf.bilibili.com",
+ ]
+ );
+ }
+
+ #[test]
+ fn filter_blocks_known_bad_hosts() {
+ let urls = vec![
+ "https://upos-sz-mirrorcosbktx.bilivideo.com/a.m4s".into(),
+ "https://upos-sz-mirror08hw.bilivideo.szbdyd.com/a.m4s".into(),
+ "https://mcdn.bilivideo.cn/a.m4s".into(),
+ ];
+ let filtered = filter_blocked(&urls);
+ assert_eq!(filtered.len(), 1);
+ assert!(filtered[0].contains("mirrorcosbktx"));
+ }
+
+ #[test]
+ fn replace_host_swaps_authority() {
+ let out = replace_host(
+ "https://upos-sz-mirrorcosbktx.bilivideo.com/p/a.m4s?q=1",
+ "upos-hz-mirrorcos.bilivideo.com",
+ )
+ .unwrap();
+ assert_eq!(out, "https://upos-hz-mirrorcos.bilivideo.com/p/a.m4s?q=1");
+ }
+
+ #[test]
+ fn expand_prefers_alternatives_when_requested() {
+ let primary = "https://upos-sz-mirrorcosbktx.bilivideo.com/x.m4s".to_string();
+ let alts = vec!["upos-hz-mirrorcos.bilivideo.com".to_string()];
+ let chain = expand_with_alternatives(&primary, &[], &alts, true);
+ assert!(chain[0].contains("upos-hz-mirrorcos"));
+ assert!(chain[1].contains("upos-sz-mirrorcosbktx"));
+ }
+
+ #[test]
+ fn expand_fallback_keeps_original_first_by_default() {
+ let primary = "https://upos-sz-mirrorcosbktx.bilivideo.com/x.m4s".to_string();
+ let alts = vec!["upos-hz-mirrorcos.bilivideo.com".to_string()];
+ let chain = expand_with_alternatives(&primary, &[], &alts, false);
+ assert!(chain[0].contains("upos-sz-mirrorcosbktx"));
+ assert!(chain[1].contains("upos-hz-mirrorcos"));
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/cookie.rs b/src-tauri/omniget-core/src/platforms/bilibili/cookie.rs
new file mode 100644
index 00000000..e2f4cb8e
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/cookie.rs
@@ -0,0 +1,353 @@
+use std::io::Cursor;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use hmac::{Hmac, Mac};
+use rand::RngExt;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use sha2::Sha256;
+
+use super::api::{check_api_response, ApiClient, Result};
+
+const FINGER_SPI_URL: &str = "https://api.bilibili.com/x/frontend/finger/spi";
+const GEN_TICKET_URL: &str =
+ "https://api.bilibili.com/bapis/bilibili.api.ticket.v1.Ticket/GenWebTicket";
+const EXCLIMB_URL: &str = "https://api.bilibili.com/x/internal/gaia-gateway/ExClimbWuzhi";
+const ANONYMOUS_SLUG: &str = "_anonymous";
+const HMAC_KEY: &[u8] = b"XgwSnGZ1p";
+const TICKET_TTL_SECS: u64 = 3 * 24 * 60 * 60;
+
+type HmacSha256 = Hmac<Sha256>;
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct AnonymousCookieState {
+ pub uuid: String,
+ pub b_lsid: String,
+ pub b_nut: String,
+ pub buvid3: String,
+ pub buvid4: String,
+ pub buvid_fp: String,
+ pub bili_ticket: String,
+ pub bili_ticket_expires: u64,
+ pub last_bootstrap_secs: u64,
+}
+
+impl AnonymousCookieState {
+ pub fn is_fresh(&self) -> bool {
+ if self.bili_ticket.is_empty() {
+ return false;
+ }
+ now_secs() < self.bili_ticket_expires.saturating_sub(60 * 60)
+ }
+}
+
+pub fn meta_file_path() -> Option<std::path::PathBuf> {
+ let cookie_path =
+ crate::platforms::cookie_provider::cookie_path_for_account("bilibili.com", ANONYMOUS_SLUG)?;
+ Some(cookie_path.with_file_name("_anonymous_meta.json"))
+}
+
+pub fn load_state() -> AnonymousCookieState {
+ let path = match meta_file_path() {
+ Some(p) => p,
+ None => return AnonymousCookieState::default(),
+ };
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(_) => return AnonymousCookieState::default(),
+ };
+ serde_json::from_str(&content).unwrap_or_default()
+}
+
+pub fn save_state(state: &AnonymousCookieState) -> std::io::Result<()> {
+ let path = meta_file_path().ok_or_else(|| {
+ std::io::Error::new(std::io::ErrorKind::Other, "app_data_dir unavailable")
+ })?;
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let serialized = serde_json::to_string_pretty(state)
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?;
+ std::fs::write(path, serialized)
+}
+
+pub async fn ensure_fresh() -> Result<AnonymousCookieState> {
+ let cached = load_state();
+ if cached.is_fresh() {
+ write_netscape_for_anonymous(&cached).ok();
+ return Ok(cached);
+ }
+ bootstrap_anonymous().await
+}
+
+pub async fn bootstrap_anonymous() -> Result<AnonymousCookieState> {
+ let ua = super::api::DEFAULT_USER_AGENT;
+ let now_ms = now_ms();
+ let uuid = gen_uuid_b_lsid();
+ let b_lsid = gen_b_lsid();
+ let b_nut = now_ms.to_string();
+ let buvid_fp = gen_buvid_fp(ua);
+
+ let mut state = AnonymousCookieState {
+ uuid: uuid.clone(),
+ b_lsid: b_lsid.clone(),
+ b_nut: b_nut.clone(),
+ buvid_fp: buvid_fp.clone(),
+ ..AnonymousCookieState::default()
+ };
+
+ let prelim = ApiClient::new()?
+ .with_user_agent(ua)
+ .with_raw_cookies(seed_cookie_header(&state));
+
+ match prelim.get_json(FINGER_SPI_URL).await {
+ Ok(raw) => {
+ if let Ok(data) = check_api_response(&raw) {
+ state.buvid3 = data
+ .get("b_3")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ state.buvid4 = data
+ .get("b_4")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ }
+ }
+ Err(e) => {
+ tracing::warn!("[bilibili] finger/spi failed: {:?}", e);
+ }
+ }
+
+ let ticket_cookies = seed_cookie_header(&state);
+ let ticket_client = ApiClient::new()?
+ .with_user_agent(ua)
+ .with_raw_cookies(ticket_cookies);
+
+ let ts = now_secs();
+ let hexsign = hmac_sha256_hex(HMAC_KEY, format!("ts{}", ts).as_bytes());
+ let ticket_url = format!(
+ "{}?key_id=ec02&hexsign={}&context%5Bts%5D={}&csrf=",
+ GEN_TICKET_URL, hexsign, ts
+ );
+ match ticket_client.post_form(&ticket_url, &[]).await {
+ Ok(raw) => {
+ if let Ok(data) = check_api_response(&raw) {
+ state.bili_ticket = data
+ .get("ticket")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let created_at = data.get("created_at").and_then(Value::as_u64).unwrap_or(ts);
+ let ttl = data
+ .get("ttl")
+ .and_then(Value::as_u64)
+ .unwrap_or(TICKET_TTL_SECS);
+ state.bili_ticket_expires = created_at + ttl;
+ }
+ }
+ Err(e) => {
+ tracing::warn!("[bilibili] bili_ticket generation failed: {:?}", e);
+ }
+ }
+
+ if !state.buvid3.is_empty() {
+ let exclimb_client = ApiClient::new()?
+ .with_user_agent(ua)
+ .with_raw_cookies(seed_cookie_header(&state));
+ let payload = exclimb_payload(ua, &state.uuid);
+ match exclimb_client.post_json(EXCLIMB_URL, &payload).await {
+ Ok(_) => {}
+ Err(e) => {
+ tracing::debug!("[bilibili] ExClimbWuzhi ack failed (non-fatal): {:?}", e);
+ }
+ }
+ }
+
+ state.last_bootstrap_secs = now_secs();
+ save_state(&state).ok();
+ write_netscape_for_anonymous(&state).ok();
+ Ok(state)
+}
+
+pub fn build_cookie_header(state: &AnonymousCookieState) -> String {
+ let mut pairs: Vec<String> = Vec::new();
+ pairs.push(format!("_uuid={}", state.uuid));
+ pairs.push(format!("b_lsid={}", state.b_lsid));
+ pairs.push(format!("b_nut={}", state.b_nut));
+ pairs.push(format!("buvid_fp={}", state.buvid_fp));
+ if !state.buvid3.is_empty() {
+ pairs.push(format!("buvid3={}", state.buvid3));
+ }
+ if !state.buvid4.is_empty() {
+ pairs.push(format!("buvid4={}", state.buvid4));
+ }
+ if !state.bili_ticket.is_empty() {
+ pairs.push(format!("bili_ticket={}", state.bili_ticket));
+ pairs.push(format!("bili_ticket_expires={}", state.bili_ticket_expires));
+ }
+ pairs.push("CURRENT_FNVAL=4048".to_string());
+ pairs.push("CURRENT_QUALITY=0".to_string());
+ pairs.join("; ")
+}
+
+fn seed_cookie_header(state: &AnonymousCookieState) -> String {
+ build_cookie_header(state)
+}
+
+fn write_netscape_for_anonymous(state: &AnonymousCookieState) -> std::io::Result<()> {
+ let path =
+ crate::platforms::cookie_provider::cookie_path_for_account("bilibili.com", ANONYMOUS_SLUG)
+ .ok_or_else(|| {
+ std::io::Error::new(std::io::ErrorKind::Other, "cookie path unavailable")
+ })?;
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ let session_expires = now_secs() + 86400;
+ let expires = if state.bili_ticket_expires > 0 {
+ state.bili_ticket_expires
+ } else {
+ session_expires
+ };
+ let mut content = String::from("# Netscape HTTP Cookie File\n");
+ let pairs: Vec<(&str, String)> = vec![
+ ("_uuid", state.uuid.clone()),
+ ("b_lsid", state.b_lsid.clone()),
+ ("b_nut", state.b_nut.clone()),
+ ("buvid_fp", state.buvid_fp.clone()),
+ ("buvid3", state.buvid3.clone()),
+ ("buvid4", state.buvid4.clone()),
+ ("bili_ticket", state.bili_ticket.clone()),
+ ("bili_ticket_expires", state.bili_ticket_expires.to_string()),
+ ("CURRENT_FNVAL", "4048".to_string()),
+ ("CURRENT_QUALITY", "0".to_string()),
+ ];
+ for (name, value) in pairs {
+ if value.is_empty() {
+ continue;
+ }
+ content.push_str(&format!(
+ ".bilibili.com\tTRUE\t/\tTRUE\t{}\t{}\t{}\n",
+ expires, name, value
+ ));
+ }
+ std::fs::write(path, content)
+}
+
+fn gen_uuid_b_lsid() -> String {
+ let mut rng = rand::rng();
+ let s: String = (0..32)
+ .map(|i| {
+ if i == 8 || i == 12 || i == 16 || i == 20 {
+ '-'
+ } else {
+ let n: u32 = rng.random_range(0..16);
+ std::char::from_digit(n, 16).unwrap_or('0')
+ }
+ })
+ .collect();
+ format!("{}{}infoc", s, now_ms() % 100000)
+}
+
+fn gen_b_lsid() -> String {
+ let mut rng = rand::rng();
+ let head: String = (0..8)
+ .map(|_| {
+ let n: u32 = rng.random_range(0..16);
+ std::char::from_digit(n, 16).unwrap_or('0')
+ })
+ .collect::<String>()
+ .to_uppercase();
+ format!("{}_{:X}", head, now_ms())
+}
+
+fn gen_buvid_fp(ua: &str) -> String {
+ let mut cursor = Cursor::new(ua.as_bytes());
+ let hash = murmur3::murmur3_x64_128(&mut cursor, 31).unwrap_or(0);
+ let low = (hash & 0xFFFFFFFFFFFFFFFF) as u64;
+ let high = (hash >> 64) as u64;
+ format!("{:016x}{:016x}", low, high)
+}
+
+fn hmac_sha256_hex(key: &[u8], data: &[u8]) -> String {
+ let mut mac = match HmacSha256::new_from_slice(key) {
+ Ok(m) => m,
+ Err(_) => return String::new(),
+ };
+ mac.update(data);
+ hex::encode(mac.finalize().into_bytes())
+}
+
+fn exclimb_payload(ua: &str, uuid: &str) -> Value {
+ use serde_json::Map;
+ let mut device = Map::new();
+ device.insert("2673".into(), Value::from(0));
+ device.insert("5766".into(), Value::from(24));
+ device.insert("6527".into(), Value::from(0));
+ device.insert("7003".into(), Value::from(1));
+ device.insert("807e".into(), Value::from(1));
+ device.insert("b8ce".into(), Value::from(ua));
+ device.insert("641c".into(), Value::from(0));
+ device.insert("07a4".into(), Value::from("en-US"));
+ device.insert("1c57".into(), Value::from(8));
+ device.insert("0bd0".into(), Value::from(24));
+ device.insert("748e".into(), Value::from(vec![1080, 1920]));
+ device.insert("d61f".into(), Value::from(vec![1032, 1920]));
+ device.insert("fc9d".into(), Value::from(-180));
+ device.insert("6aa9".into(), Value::from("Asia/Shanghai"));
+ device.insert("75b8".into(), Value::from(1));
+ device.insert("3b21".into(), Value::from(1));
+ device.insert("8a1c".into(), Value::from(0));
+ device.insert("d52f".into(), Value::from("not available"));
+ device.insert("adca".into(), Value::from("MacIntel"));
+ device.insert("80c9".into(), Value::Array(vec![]));
+ device.insert("13ab".into(), Value::from(""));
+ device.insert("bfe9".into(), Value::from(""));
+ device.insert("a3c1".into(), Value::Array(vec![]));
+ device.insert("6bc5".into(), Value::from(""));
+ device.insert("ed31".into(), Value::from(0));
+ device.insert("72bd".into(), Value::from(0));
+ device.insert("097b".into(), Value::from(0));
+ device.insert("52cd".into(), Value::from(vec![0, 0, 0]));
+ device.insert("a658".into(), Value::Array(vec![]));
+ device.insert("d4a0".into(), Value::from(false));
+ device.insert("159f".into(), Value::from(false));
+ device.insert("5ea0".into(), Value::from(false));
+ device.insert("8eb3".into(), Value::from(false));
+
+ let mut payload = Map::new();
+ payload.insert("3064".into(), Value::from(1));
+ payload.insert("5062".into(), Value::from(now_ms().to_string()));
+ payload.insert("03bf".into(), Value::from("https://www.bilibili.com/"));
+ payload.insert("39c8".into(), Value::from("333.999.fp.risk"));
+ payload.insert("34f1".into(), Value::from(""));
+ payload.insert("d402".into(), Value::from(""));
+ payload.insert("654a".into(), Value::from(""));
+ payload.insert("6e7c".into(), Value::from("839x959"));
+ payload.insert("3c43".into(), Value::Object(device));
+ payload.insert("8b94".into(), Value::from(""));
+ payload.insert("df35".into(), Value::from(uuid));
+ payload.insert("07a4".into(), Value::from("en-US"));
+ payload.insert("5f45".into(), Value::Null);
+ payload.insert("db46".into(), Value::from(0));
+
+ let mut root = Map::new();
+ root.insert("payload".into(), Value::Object(payload));
+ Value::Object(root)
+}
+
+fn now_secs() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+fn now_ms() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis() as u64)
+ .unwrap_or(0)
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/cover.rs b/src-tauri/omniget-core/src/platforms/bilibili/cover.rs
new file mode 100644
index 00000000..ebb8e6fb
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/cover.rs
@@ -0,0 +1,94 @@
+use std::path::{Path, PathBuf};
+
+use super::api::{ApiClient, BilibiliError, Result};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CoverFormat {
+ Jpg,
+ Png,
+ Webp,
+ Avif,
+}
+
+impl CoverFormat {
+ pub fn extension(self) -> &'static str {
+ match self {
+ CoverFormat::Jpg => "jpg",
+ CoverFormat::Png => "png",
+ CoverFormat::Webp => "webp",
+ CoverFormat::Avif => "avif",
+ }
+ }
+
+ pub fn from_str(s: &str) -> Self {
+ match s.to_ascii_lowercase().as_str() {
+ "png" => CoverFormat::Png,
+ "webp" => CoverFormat::Webp,
+ "avif" => CoverFormat::Avif,
+ _ => CoverFormat::Jpg,
+ }
+ }
+}
+
+pub fn typed_url(base_url: &str, format: CoverFormat) -> String {
+ let stripped = base_url.split('@').next().unwrap_or(base_url);
+ format!("{}@.{}", stripped, format.extension())
+}
+
+pub async fn download(
+ client: &ApiClient,
+ cover_url: &str,
+ output_dir: &Path,
+ filename: &str,
+ format: CoverFormat,
+) -> Result<PathBuf> {
+ let typed = typed_url(cover_url, format);
+ let bytes = client.get_bytes(&typed).await?;
+ let path = output_dir.join(format!("{}.{}", filename, format.extension()));
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+ std::fs::write(&path, bytes).map_err(|_| BilibiliError::ContentUnavailable)?;
+ Ok(path)
+}
+
+pub async fn download_to(
+ client: &ApiClient,
+ cover_url: &str,
+ path: &Path,
+ format: CoverFormat,
+) -> Result<PathBuf> {
+ let typed = typed_url(cover_url, format);
+ let bytes = client.get_bytes(&typed).await?;
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+ std::fs::write(path, bytes).map_err(|_| BilibiliError::ContentUnavailable)?;
+ Ok(path.to_path_buf())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn typed_url_strips_existing_at_suffix() {
+ let url = "https://i0.hdslb.com/bfs/archive/[email protected]";
+ let out = typed_url(url, CoverFormat::Png);
+ assert_eq!(out, "https://i0.hdslb.com/bfs/archive/[email protected]");
+ }
+
+ #[test]
+ fn typed_url_appends_when_no_suffix() {
+ let url = "https://i0.hdslb.com/bfs/archive/abc.jpg";
+ let out = typed_url(url, CoverFormat::Webp);
+ assert_eq!(out, "https://i0.hdslb.com/bfs/archive/[email protected]");
+ }
+
+ #[test]
+ fn cover_format_from_str_falls_back_to_jpg() {
+ assert_eq!(CoverFormat::from_str("avif"), CoverFormat::Avif);
+ assert_eq!(CoverFormat::from_str("PNG"), CoverFormat::Png);
+ assert_eq!(CoverFormat::from_str("invalid"), CoverFormat::Jpg);
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/lanes.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/lanes.rs
new file mode 100644
index 00000000..00a6c539
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/lanes.rs
@@ -0,0 +1,96 @@
+#[derive(Debug, Clone, Copy)]
+pub struct ScrollLane {
+ pub free_at_secs: f64,
+}
+
+pub struct ScrollLaneSet {
+ pub lanes: Vec<ScrollLane>,
+}
+
+impl ScrollLaneSet {
+ pub fn new(count: usize) -> Self {
+ Self {
+ lanes: vec![ScrollLane { free_at_secs: 0.0 }; count],
+ }
+ }
+
+ pub fn allocate(&mut self, start_secs: f64, exit_secs: f64) -> usize {
+ let mut best = 0usize;
+ let mut best_free_at = f64::MAX;
+ for (i, lane) in self.lanes.iter().enumerate() {
+ if lane.free_at_secs <= start_secs {
+ self.lanes[i].free_at_secs = exit_secs;
+ return i;
+ }
+ if lane.free_at_secs < best_free_at {
+ best_free_at = lane.free_at_secs;
+ best = i;
+ }
+ }
+ self.lanes[best].free_at_secs = exit_secs;
+ best
+ }
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct StaticLane {
+ pub free_at_secs: f64,
+}
+
+pub struct StaticLaneSet {
+ pub lanes: Vec<StaticLane>,
+}
+
+impl StaticLaneSet {
+ pub fn new(count: usize) -> Self {
+ Self {
+ lanes: vec![StaticLane { free_at_secs: 0.0 }; count],
+ }
+ }
+
+ pub fn allocate(&mut self, start_secs: f64, end_secs: f64) -> usize {
+ let mut best = 0usize;
+ let mut best_free_at = f64::MAX;
+ for (i, lane) in self.lanes.iter().enumerate() {
+ if lane.free_at_secs <= start_secs {
+ self.lanes[i].free_at_secs = end_secs;
+ return i;
+ }
+ if lane.free_at_secs < best_free_at {
+ best_free_at = lane.free_at_secs;
+ best = i;
+ }
+ }
+ self.lanes[best].free_at_secs = end_secs;
+ best
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn scroll_lane_reuses_freed_slot() {
+ let mut lanes = ScrollLaneSet::new(3);
+ let a = lanes.allocate(0.0, 5.0);
+ let b = lanes.allocate(0.5, 5.5);
+ let c = lanes.allocate(1.0, 6.0);
+ let d = lanes.allocate(6.0, 11.0);
+ assert_eq!(a, 0);
+ assert_eq!(b, 1);
+ assert_eq!(c, 2);
+ assert_eq!(d, 0);
+ }
+
+ #[test]
+ fn static_lane_picks_earliest_free() {
+ let mut lanes = StaticLaneSet::new(2);
+ let a = lanes.allocate(0.0, 4.0);
+ let b = lanes.allocate(2.0, 6.0);
+ let c = lanes.allocate(4.5, 8.0);
+ assert_eq!(a, 0);
+ assert_eq!(b, 1);
+ assert_eq!(c, 0);
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/mod.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/mod.rs
new file mode 100644
index 00000000..b8595f5d
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/mod.rs
@@ -0,0 +1,10 @@
+use super::proto::DanmakuElem;
+
+pub mod lanes;
+mod render;
+
+pub use render::AssRenderOptions;
+
+pub fn render(elems: &[DanmakuElem], opts: &AssRenderOptions) -> String {
+ render::render_ass(elems, opts)
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/render.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/render.rs
new file mode 100644
index 00000000..7ea17a41
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/ass/render.rs
@@ -0,0 +1,260 @@
+use super::super::proto::DanmakuElem;
+use super::lanes::{ScrollLaneSet, StaticLaneSet};
+
+#[derive(Debug, Clone)]
+pub struct AssRenderOptions {
+ pub resolution_x: u32,
+ pub resolution_y: u32,
+ pub font_name: String,
+ pub font_size: u32,
+ pub scroll_duration_secs: f64,
+ pub static_duration_secs: f64,
+ pub alpha: u8,
+ pub bold: bool,
+ pub outline: f32,
+ pub shadow: f32,
+ pub avg_char_width_px: f32,
+}
+
+impl Default for AssRenderOptions {
+ fn default() -> Self {
+ Self {
+ resolution_x: 1920,
+ resolution_y: 1080,
+ font_name: "Microsoft YaHei".to_string(),
+ font_size: 42,
+ scroll_duration_secs: 12.0,
+ static_duration_secs: 5.0,
+ alpha: 0x40,
+ bold: false,
+ outline: 1.0,
+ shadow: 0.0,
+ avg_char_width_px: 25.0,
+ }
+ }
+}
+
+pub fn render_ass(elems: &[DanmakuElem], opts: &AssRenderOptions) -> String {
+ let scroll_lane_count = ((opts.resolution_y as f32) / (opts.font_size as f32 * 1.2)) as usize;
+ let static_lane_count = scroll_lane_count;
+ let mut scroll = ScrollLaneSet::new(scroll_lane_count.max(8));
+ let mut top = StaticLaneSet::new(static_lane_count.max(8));
+ let mut bottom = StaticLaneSet::new(static_lane_count.max(8));
+
+ let mut sorted: Vec<&DanmakuElem> = elems.iter().collect();
+ sorted.sort_by_key(|e| e.progress_ms);
+
+ let mut events: Vec<String> = Vec::new();
+ let line_height = (opts.font_size as f32 * 1.2) as i32;
+
+ for elem in sorted {
+ if elem.content.is_empty() {
+ continue;
+ }
+ let start_secs = (elem.progress_ms as f64) / 1000.0;
+ let text_width_px = (elem.content.chars().count() as f32) * opts.avg_char_width_px;
+ let mode = elem.mode;
+
+ let line = match mode {
+ 1 | 2 | 3 => {
+ let exit_secs = start_secs + opts.scroll_duration_secs;
+ let lane_idx = scroll.allocate(start_secs, exit_secs);
+ let y = line_height + (lane_idx as i32) * line_height;
+ let x1 = opts.resolution_x as i32;
+ let x2 = -(text_width_px as i32);
+ build_scroll_event(elem, start_secs, exit_secs, x1, x2, y, opts)
+ }
+ 4 => {
+ let end_secs = start_secs + opts.static_duration_secs;
+ let lane_idx = bottom.allocate(start_secs, end_secs);
+ let y = (opts.resolution_y as i32) - line_height - (lane_idx as i32) * line_height;
+ let x = (opts.resolution_x as i32) / 2;
+ build_static_event(elem, start_secs, end_secs, x, y, opts)
+ }
+ 5 => {
+ let end_secs = start_secs + opts.static_duration_secs;
+ let lane_idx = top.allocate(start_secs, end_secs);
+ let y = line_height + (lane_idx as i32) * line_height;
+ let x = (opts.resolution_x as i32) / 2;
+ build_static_event(elem, start_secs, end_secs, x, y, opts)
+ }
+ _ => continue,
+ };
+ events.push(line);
+ }
+
+ let mut out = String::new();
+ out.push_str("[Script Info]\n");
+ out.push_str("ScriptType: v4.00+\n");
+ out.push_str("Collisions: Normal\n");
+ out.push_str(&format!("PlayResX: {}\n", opts.resolution_x));
+ out.push_str(&format!("PlayResY: {}\n", opts.resolution_y));
+ out.push_str("Timer: 100.0000\n");
+ out.push_str("WrapStyle: 2\n\n");
+
+ out.push_str("[V4+ Styles]\n");
+ out.push_str("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n");
+ out.push_str(&format!(
+ "Style: Danmaku,{font},{size},&H{alpha:02X}FFFFFF,&H{alpha:02X}FFFFFF,&H{alpha:02X}000000,&H{alpha:02X}000000,{bold},0,0,0,100,100,0,0,1,{outline:.1},{shadow:.1},7,0,0,0,1\n\n",
+ font = opts.font_name,
+ size = opts.font_size,
+ alpha = opts.alpha,
+ bold = if opts.bold { -1 } else { 0 },
+ outline = opts.outline,
+ shadow = opts.shadow,
+ ));
+
+ out.push_str("[Events]\n");
+ out.push_str(
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n",
+ );
+ for ev in events {
+ out.push_str(&ev);
+ out.push('\n');
+ }
+ out
+}
+
+fn build_scroll_event(
+ elem: &DanmakuElem,
+ start_secs: f64,
+ end_secs: f64,
+ x1: i32,
+ x2: i32,
+ y: i32,
+ opts: &AssRenderOptions,
+) -> String {
+ let start = ass_time(start_secs);
+ let end = ass_time(end_secs);
+ let color_tag = ass_color_tag(elem.color);
+ let size_tag = ass_size_tag(elem.fontsize, opts.font_size);
+ let text = escape_ass(&elem.content);
+ format!(
+ "Dialogue: 0,{},{},Danmaku,,0,0,0,,{{\\move({},{},{},{}){}{}}}{}",
+ start, end, x1, y, x2, y, size_tag, color_tag, text
+ )
+}
+
+fn build_static_event(
+ elem: &DanmakuElem,
+ start_secs: f64,
+ end_secs: f64,
+ x: i32,
+ y: i32,
+ opts: &AssRenderOptions,
+) -> String {
+ let start = ass_time(start_secs);
+ let end = ass_time(end_secs);
+ let color_tag = ass_color_tag(elem.color);
+ let size_tag = ass_size_tag(elem.fontsize, opts.font_size);
+ let text = escape_ass(&elem.content);
+ format!(
+ "Dialogue: 0,{},{},Danmaku,,0,0,0,,{{\\an8\\pos({},{}){}{}}}{}",
+ start, end, x, y, size_tag, color_tag, text
+ )
+}
+
+fn ass_time(seconds: f64) -> String {
+ let total_cs = (seconds * 100.0).round() as i64;
+ let hours = total_cs / 360_000;
+ let rem = total_cs % 360_000;
+ let minutes = rem / 6000;
+ let rem = rem % 6000;
+ let secs = rem / 100;
+ let cs = rem % 100;
+ format!("{:01}:{:02}:{:02}.{:02}", hours, minutes, secs, cs)
+}
+
+fn ass_color_tag(rgb: u32) -> String {
+ if rgb == 0xFFFFFF || rgb == 0 {
+ return String::new();
+ }
+ let r = (rgb >> 16) & 0xFF;
+ let g = (rgb >> 8) & 0xFF;
+ let b = rgb & 0xFF;
+ format!("\\c&H{:02X}{:02X}{:02X}&", b, g, r)
+}
+
+fn ass_size_tag(actual: i32, default_size: u32) -> String {
+ if actual <= 0 {
+ return String::new();
+ }
+ if actual == default_size as i32 {
+ return String::new();
+ }
+ format!("\\fs{}", actual)
+}
+
+fn escape_ass(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '{' => out.push_str("\\{"),
+ '}' => out.push_str("\\}"),
+ '\\' => out.push_str("\\\\"),
+ '\n' => out.push_str("\\N"),
+ '\r' => continue,
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn elem(progress_ms: i32, mode: i32, content: &str) -> DanmakuElem {
+ DanmakuElem {
+ progress_ms,
+ mode,
+ fontsize: 25,
+ color: 0xFFFFFF,
+ content: content.to_string(),
+ ..DanmakuElem::default()
+ }
+ }
+
+ #[test]
+ fn renders_header_and_events() {
+ let elems = vec![
+ elem(0, 1, "scroll line"),
+ elem(1000, 5, "top line"),
+ elem(2000, 4, "bottom line"),
+ ];
+ let ass = render_ass(&elems, &AssRenderOptions::default());
+ assert!(ass.contains("[Script Info]"));
+ assert!(ass.contains("[V4+ Styles]"));
+ assert!(ass.contains("[Events]"));
+ assert!(ass.contains("scroll line"));
+ assert!(ass.contains("top line"));
+ assert!(ass.contains("bottom line"));
+ assert!(ass.contains("\\move("));
+ assert!(ass.contains("\\pos("));
+ }
+
+ #[test]
+ fn escapes_braces_in_content() {
+ let elems = vec![elem(0, 1, "hello {world}")];
+ let ass = render_ass(&elems, &AssRenderOptions::default());
+ assert!(ass.contains("\\{world\\}"));
+ }
+
+ #[test]
+ fn color_tag_omitted_for_white() {
+ let elems = vec![elem(0, 1, "white text")];
+ let ass = render_ass(&elems, &AssRenderOptions::default());
+ for line in ass.lines() {
+ if line.starts_with("Dialogue:") {
+ assert!(!line.contains("\\c&H"));
+ }
+ }
+ }
+
+ #[test]
+ fn time_format() {
+ assert_eq!(ass_time(0.0), "0:00:00.00");
+ assert_eq!(ass_time(65.5), "0:01:05.50");
+ assert_eq!(ass_time(3661.25), "1:01:01.25");
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/json.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/json.rs
new file mode 100644
index 00000000..1cffea56
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/json.rs
@@ -0,0 +1,43 @@
+use serde_json::json;
+
+use super::proto::DanmakuElem;
+
+pub fn render(elems: &[DanmakuElem]) -> String {
+ let arr: Vec<serde_json::Value> = elems
+ .iter()
+ .map(|e| {
+ json!({
+ "id": e.id,
+ "progress_ms": e.progress_ms,
+ "mode": e.mode,
+ "fontsize": e.fontsize,
+ "color": e.color,
+ "mid_hash": e.mid_hash,
+ "content": e.content,
+ "ctime": e.ctime,
+ "weight": e.weight,
+ "pool": e.pool,
+ "attr": e.attr,
+ })
+ })
+ .collect();
+ serde_json::to_string_pretty(&arr).unwrap_or_else(|_| "[]".to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn renders_json_array() {
+ let e = DanmakuElem {
+ id: 42,
+ progress_ms: 1000,
+ content: "x".to_string(),
+ ..DanmakuElem::default()
+ };
+ let s = render(&[e]);
+ assert!(s.contains("\"progress_ms\": 1000"));
+ assert!(s.contains("\"content\": \"x\""));
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/mod.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/mod.rs
new file mode 100644
index 00000000..8857a76f
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/mod.rs
@@ -0,0 +1,78 @@
+use serde::{Deserialize, Serialize};
+
+use super::api::{ApiClient, BilibiliError, Result};
+use super::wbi;
+
+pub mod ass;
+pub mod json;
+pub mod proto;
+pub mod xml;
+
+pub use proto::DanmakuElem;
+
+const SEG_URL: &str = "https://api.bilibili.com/x/v2/dm/wbi/web/seg.so";
+const SEGMENT_DURATION_SECS: u64 = 360;
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum DanmakuFormat {
+ Xml,
+ Ass,
+ Json,
+}
+
+impl DanmakuFormat {
+ pub fn extension(self) -> &'static str {
+ match self {
+ DanmakuFormat::Xml => "xml",
+ DanmakuFormat::Ass => "ass",
+ DanmakuFormat::Json => "json",
+ }
+ }
+}
+
+pub async fn fetch_elems(
+ client: &ApiClient,
+ cid: u64,
+ duration_secs: u64,
+) -> Result<Vec<DanmakuElem>> {
+ let segments = ((duration_secs + SEGMENT_DURATION_SECS - 1) / SEGMENT_DURATION_SECS).max(1);
+ let mut all: Vec<DanmakuElem> = Vec::new();
+ for i in 1..=segments {
+ let params: Vec<(&str, String)> = vec![
+ ("type", "1".to_string()),
+ ("oid", cid.to_string()),
+ ("segment_index", i.to_string()),
+ ];
+ let signed = wbi::signed_query(client, &params).await?;
+ let url = format!("{}?{}", SEG_URL, signed);
+ match client.get_bytes(&url).await {
+ Ok(bytes) => {
+ if let Ok(elems) = proto::decode_segment(&bytes) {
+ all.extend(elems.into_iter().filter(|e| !e.content.is_empty()));
+ }
+ }
+ Err(e) => {
+ tracing::warn!(
+ "[bilibili] danmaku segment {}/{} fetch failed: {:?}",
+ i,
+ segments,
+ e
+ );
+ }
+ }
+ }
+ if all.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ all.sort_by_key(|e| e.progress_ms);
+ Ok(all)
+}
+
+pub fn render(elems: &[DanmakuElem], format: DanmakuFormat) -> String {
+ match format {
+ DanmakuFormat::Xml => xml::render(elems),
+ DanmakuFormat::Json => json::render(elems),
+ DanmakuFormat::Ass => ass::render(elems, &ass::AssRenderOptions::default()),
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/proto.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/proto.rs
new file mode 100644
index 00000000..167e5d7e
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/proto.rs
@@ -0,0 +1,244 @@
+use super::super::api::{BilibiliError, Result};
+
+#[derive(Debug, Clone, Default)]
+pub struct DanmakuElem {
+ pub id: i64,
+ pub progress_ms: i32,
+ pub mode: i32,
+ pub fontsize: i32,
+ pub color: u32,
+ pub mid_hash: String,
+ pub content: String,
+ pub ctime: i64,
+ pub weight: i32,
+ pub pool: i32,
+ pub attr: i32,
+}
+
+pub fn decode_segment(bytes: &[u8]) -> Result<Vec<DanmakuElem>> {
+ let mut elems: Vec<DanmakuElem> = Vec::new();
+ let mut idx = 0usize;
+ while idx < bytes.len() {
+ let (key, k_len) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += k_len;
+ let field = (key >> 3) as u32;
+ let wire = (key & 0x07) as u8;
+ if field == 1 && wire == 2 {
+ let (len, l_len) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += l_len;
+ let end = idx
+ .checked_add(len as usize)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ if end > bytes.len() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ let elem = decode_elem(&bytes[idx..end])?;
+ elems.push(elem);
+ idx = end;
+ } else {
+ idx = skip_field(bytes, idx, wire).ok_or(BilibiliError::ContentUnavailable)?;
+ }
+ }
+ Ok(elems)
+}
+
+fn decode_elem(bytes: &[u8]) -> Result<DanmakuElem> {
+ let mut elem = DanmakuElem::default();
+ let mut idx = 0usize;
+ while idx < bytes.len() {
+ let (key, k_len) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += k_len;
+ let field = (key >> 3) as u32;
+ let wire = (key & 0x07) as u8;
+ match (field, wire) {
+ (1, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.id = v as i64;
+ }
+ (2, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.progress_ms = v as i32;
+ }
+ (3, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.mode = v as i32;
+ }
+ (4, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.fontsize = v as i32;
+ }
+ (5, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.color = v as u32;
+ }
+ (6, 2) => {
+ let (v, vl) =
+ read_length_delimited(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.mid_hash = String::from_utf8(v.to_vec()).unwrap_or_default();
+ }
+ (7, 2) => {
+ let (v, vl) =
+ read_length_delimited(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.content = String::from_utf8(v.to_vec()).unwrap_or_default();
+ }
+ (8, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.ctime = v as i64;
+ }
+ (9, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.weight = v as i32;
+ }
+ (11, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.pool = v as i32;
+ }
+ (13, 0) => {
+ let (v, vl) = read_varint(bytes, idx).ok_or(BilibiliError::ContentUnavailable)?;
+ idx += vl;
+ elem.attr = v as i32;
+ }
+ _ => {
+ idx = skip_field(bytes, idx, wire).ok_or(BilibiliError::ContentUnavailable)?;
+ }
+ }
+ }
+ Ok(elem)
+}
+
+fn read_varint(bytes: &[u8], start: usize) -> Option<(u64, usize)> {
+ let mut result: u64 = 0;
+ let mut shift = 0u32;
+ let mut idx = start;
+ while idx < bytes.len() {
+ let b = bytes[idx];
+ idx += 1;
+ result |= ((b & 0x7F) as u64) << shift;
+ if b & 0x80 == 0 {
+ return Some((result, idx - start));
+ }
+ shift += 7;
+ if shift >= 64 {
+ return None;
+ }
+ }
+ None
+}
+
+fn read_length_delimited(bytes: &[u8], start: usize) -> Option<(&[u8], usize)> {
+ let (len, l_len) = read_varint(bytes, start)?;
+ let body_start = start + l_len;
+ let body_end = body_start.checked_add(len as usize)?;
+ if body_end > bytes.len() {
+ return None;
+ }
+ Some((&bytes[body_start..body_end], body_end - start))
+}
+
+fn skip_field(bytes: &[u8], start: usize, wire: u8) -> Option<usize> {
+ match wire {
+ 0 => {
+ let (_, len) = read_varint(bytes, start)?;
+ Some(start + len)
+ }
+ 1 => {
+ if start + 8 > bytes.len() {
+ None
+ } else {
+ Some(start + 8)
+ }
+ }
+ 2 => {
+ let (_, len) = read_length_delimited(bytes, start)?;
+ Some(start + len)
+ }
+ 5 => {
+ if start + 4 > bytes.len() {
+ None
+ } else {
+ Some(start + 4)
+ }
+ }
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn build_elem_bytes() -> Vec<u8> {
+ let mut buf: Vec<u8> = Vec::new();
+ write_tag_varint(&mut buf, 2, 1234);
+ write_tag_varint(&mut buf, 3, 1);
+ write_tag_varint(&mut buf, 4, 25);
+ write_tag_varint(&mut buf, 5, 0xFFFFFF);
+ write_tag_str(&mut buf, 7, "hello danmaku");
+ write_tag_varint(&mut buf, 8, 1700000000);
+ buf
+ }
+
+ fn write_varint(buf: &mut Vec<u8>, mut v: u64) {
+ while v >= 0x80 {
+ buf.push(((v & 0x7F) as u8) | 0x80);
+ v >>= 7;
+ }
+ buf.push(v as u8);
+ }
+
+ fn write_tag_varint(buf: &mut Vec<u8>, field: u32, value: u64) {
+ let key = (field << 3) | 0;
+ write_varint(buf, key as u64);
+ write_varint(buf, value);
+ }
+
+ fn write_tag_str(buf: &mut Vec<u8>, field: u32, s: &str) {
+ let key = (field << 3) | 2;
+ write_varint(buf, key as u64);
+ write_varint(buf, s.len() as u64);
+ buf.extend_from_slice(s.as_bytes());
+ }
+
+ fn build_segment_bytes(elems: usize) -> Vec<u8> {
+ let elem_bytes = build_elem_bytes();
+ let mut buf: Vec<u8> = Vec::new();
+ for _ in 0..elems {
+ let key = (1 << 3) | 2;
+ write_varint(&mut buf, key as u64);
+ write_varint(&mut buf, elem_bytes.len() as u64);
+ buf.extend_from_slice(&elem_bytes);
+ }
+ buf
+ }
+
+ #[test]
+ fn decode_single_elem() {
+ let bytes = build_segment_bytes(1);
+ let elems = decode_segment(&bytes).unwrap();
+ assert_eq!(elems.len(), 1);
+ let e = &elems[0];
+ assert_eq!(e.progress_ms, 1234);
+ assert_eq!(e.mode, 1);
+ assert_eq!(e.fontsize, 25);
+ assert_eq!(e.color, 0xFFFFFF);
+ assert_eq!(e.content, "hello danmaku");
+ assert_eq!(e.ctime, 1700000000);
+ }
+
+ #[test]
+ fn decode_multiple_elems() {
+ let bytes = build_segment_bytes(5);
+ let elems = decode_segment(&bytes).unwrap();
+ assert_eq!(elems.len(), 5);
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/danmaku/xml.rs b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/xml.rs
new file mode 100644
index 00000000..c36e427a
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/danmaku/xml.rs
@@ -0,0 +1,81 @@
+use super::proto::DanmakuElem;
+
+pub fn render(elems: &[DanmakuElem]) -> String {
+ let mut out = String::new();
+ out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
+ out.push_str("<i>\n");
+ out.push_str(" <chatserver>chat.bilibili.com</chatserver>\n");
+ out.push_str(" <chatid>0</chatid>\n");
+ out.push_str(" <mission>0</mission>\n");
+ out.push_str(" <maxlimit>1500</maxlimit>\n");
+ out.push_str(" <state>0</state>\n");
+ out.push_str(" <real_name>0</real_name>\n");
+ out.push_str(" <source>k-v</source>\n");
+ for e in elems {
+ let stime = (e.progress_ms as f64) / 1000.0;
+ let mode = e.mode.max(1);
+ let size = if e.fontsize > 0 { e.fontsize } else { 25 };
+ let color = e.color;
+ let date = e.ctime;
+ let pool = e.pool;
+ let mid_hash = escape_xml_attr(&e.mid_hash);
+ let dmid = e.id;
+ let text = escape_xml_text(&e.content);
+ out.push_str(&format!(
+ " <d p=\"{:.3},{},{},{},{},{},{},{}\">{}</d>\n",
+ stime, mode, size, color, date, pool, mid_hash, dmid, text
+ ));
+ }
+ out.push_str("</i>\n");
+ out
+}
+
+fn escape_xml_text(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+fn escape_xml_attr(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&apos;"),
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn renders_minimal_xml() {
+ let elem = DanmakuElem {
+ id: 1,
+ progress_ms: 1500,
+ mode: 1,
+ fontsize: 25,
+ color: 0xFFFFFF,
+ content: "hello & world".to_string(),
+ ..DanmakuElem::default()
+ };
+ let xml = render(&[elem]);
+ assert!(xml.contains("<i>"));
+ assert!(xml.contains("hello &amp; world"));
+ assert!(xml.contains("1.500,1,25,16777215"));
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/engine/fetch.rs b/src-tauri/omniget-core/src/platforms/bilibili/engine/fetch.rs
new file mode 100644
index 00000000..a82b1e8b
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/engine/fetch.rs
@@ -0,0 +1,85 @@
+use std::path::Path;
+use std::time::Duration;
+
+use crate::core::http_fetcher::{HttpFetcher, HttpFetcherConfig, HttpFetcherResult};
+use crate::models::progress::ProgressUpdate;
+use reqwest::header::{HeaderMap, HeaderName, HeaderValue, COOKIE, REFERER, USER_AGENT};
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use super::super::api::{ApiClient, BilibiliError, Result};
+
+pub struct FetchOptions<'a> {
+ pub url: &'a str,
+ pub output_path: &'a Path,
+ pub referer: &'a str,
+ pub user_agent: &'a str,
+ pub cookie_header: Option<&'a str>,
+ pub cancel: Option<CancellationToken>,
+}
+
+fn build_client() -> Result<reqwest::Client> {
+ crate::core::http_client::apply_global_proxy(
+ reqwest::Client::builder()
+ .timeout(Duration::from_secs(60 * 30))
+ .connect_timeout(Duration::from_secs(15)),
+ )
+ .build()
+ .map_err(BilibiliError::Network)
+}
+
+fn build_headers(referer: &str, user_agent: &str, cookie_header: Option<&str>) -> HeaderMap {
+ let mut h = HeaderMap::new();
+ if let Ok(v) = HeaderValue::from_str(referer) {
+ h.insert(REFERER, v);
+ }
+ if let Ok(v) = HeaderValue::from_str(user_agent) {
+ h.insert(USER_AGENT, v);
+ }
+ if let Some(c) = cookie_header {
+ if let Ok(v) = HeaderValue::from_str(c) {
+ h.insert(COOKIE, v);
+ }
+ }
+ if let (Ok(k), Ok(v)) = (
+ HeaderName::from_bytes(b"Origin"),
+ HeaderValue::from_str("https://www.bilibili.com"),
+ ) {
+ h.insert(k, v);
+ }
+ h
+}
+
+pub async fn fetch_stream(
+ opts: FetchOptions<'_>,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<HttpFetcherResult> {
+ let client = build_client()?;
+ let headers = build_headers(opts.referer, opts.user_agent, opts.cookie_header);
+ let mut fetcher =
+ HttpFetcher::new(client, opts.url.to_string(), opts.output_path.to_path_buf())
+ .with_headers(headers)
+ .with_config(HttpFetcherConfig {
+ concurrent_segments: 8,
+ segment_size_hint: 4 * 1024 * 1024,
+ min_size_for_chunked: 8 * 1024 * 1024,
+ connect_timeout: Duration::from_secs(10),
+ read_timeout: Duration::from_secs(45),
+ max_retries_per_segment: 3,
+ steal_threshold: Duration::from_secs(3),
+ steal_min_chunk_size: 512 * 1024,
+ use_sidecar_resume: true,
+ resume_save_interval: Duration::from_secs(2),
+ });
+ if let Some(c) = opts.cancel {
+ fetcher = fetcher.with_cancel(c);
+ }
+ fetcher
+ .download(progress)
+ .await
+ .map_err(|_| BilibiliError::ContentUnavailable)
+}
+
+pub fn from_api_client(client: &ApiClient) -> (&str, Option<&str>) {
+ (client.user_agent(), client.cookie_header())
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/engine/mod.rs b/src-tauri/omniget-core/src/platforms/bilibili/engine/mod.rs
new file mode 100644
index 00000000..b0148c47
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/engine/mod.rs
@@ -0,0 +1,444 @@
+use std::path::PathBuf;
+
+use crate::models::progress::ProgressUpdate;
+use tokio::sync::mpsc;
+use tokio_util::sync::CancellationToken;
+
+use super::api::{ApiClient, BilibiliError, Result};
+use super::parser::{ContentMetadata, EpisodeItem, ParsedContent};
+use super::preview::{self, AudioStream, MediaContainer, PreviewInfo, VideoStream};
+use super::url_kind::UrlKind;
+
+pub mod fetch;
+pub mod mux;
+pub mod query;
+
+pub struct EngineOptions {
+ pub output_dir: PathBuf,
+ pub container: mux::Container,
+ pub video_qn_pref: u32,
+ pub video_codec_pref: u32,
+ pub audio_qn_pref: u32,
+ pub embed_cover: bool,
+ pub keep_streams: bool,
+ pub filename: String,
+ pub cancel: CancellationToken,
+ pub danmaku_enabled: bool,
+ pub danmaku_format: Option<super::danmaku::DanmakuFormat>,
+ pub nfo_enabled: bool,
+ pub cover_sidecar_enabled: bool,
+ pub cover_format: super::cover::CoverFormat,
+ pub cdn_alt_hosts: Vec<String>,
+ pub cdn_prefer_alternatives: bool,
+}
+
+pub struct EngineResult {
+ pub final_path: PathBuf,
+ pub bytes: u64,
+}
+
+pub async fn run_single(
+ client: &ApiClient,
+ item: &EpisodeItem,
+ kind: &UrlKind,
+ opts: &EngineOptions,
+ metadata: Option<&ContentMetadata>,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<EngineResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+ let preview_info: PreviewInfo = preview::fetch(client, item, kind).await?;
+
+ if preview_info.container != MediaContainer::Dash {
+ return run_progressive(client, item, &preview_info, opts, progress).await;
+ }
+
+ let video = preview_info
+ .pick_video(opts.video_qn_pref, opts.video_codec_pref)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let audio = preview_info.pick_audio(opts.audio_qn_pref);
+
+ let _ = progress.send(ProgressUpdate::percent(2.0)).await;
+ let cdn_prefs = query::CdnPreferences {
+ alt_hosts: opts.cdn_alt_hosts.clone(),
+ prefer_alternatives: opts.cdn_prefer_alternatives,
+ };
+ let video_url =
+ query::resolve_best_url_with_cdn(client, &video.base_url, &video.backup_urls, &cdn_prefs)
+ .await?;
+ let audio_resolved = if let Some(a) = audio {
+ Some(
+ query::resolve_best_url_with_cdn(client, &a.base_url, &a.backup_urls, &cdn_prefs)
+ .await?,
+ )
+ } else {
+ None
+ };
+
+ std::fs::create_dir_all(&opts.output_dir).ok();
+ let temp_stem = sanitize_for_temp(&opts.filename);
+
+ let temp_video = opts.output_dir.join(format!(".{}.video.tmp", temp_stem));
+ let temp_audio = opts.output_dir.join(format!(".{}.audio.tmp", temp_stem));
+ let temp_cover = opts.output_dir.join(format!(".{}.cover.tmp", temp_stem));
+
+ let (ua, cookie_header) = (
+ client.user_agent().to_string(),
+ client.cookie_header().map(|s| s.to_string()),
+ );
+ let referer = item
+ .url
+ .clone()
+ .unwrap_or_else(|| "https://www.bilibili.com".to_string());
+
+ let total_streams = 1 + audio_resolved.as_ref().map(|_| 1).unwrap_or(0);
+
+ let (video_tx, mut video_rx) = mpsc::channel::<ProgressUpdate>(32);
+ let progress_video = progress.clone();
+ let agg_total_video = video_url.size;
+ let agg_total_audio = audio_resolved.as_ref().map(|a| a.size).unwrap_or(0);
+ let total_size_hint = agg_total_video + agg_total_audio;
+ tokio::spawn(async move {
+ while let Some(p) = video_rx.recv().await {
+ let scaled = scale_progress(p.percent, 0, total_streams);
+ let _ = progress_video
+ .send(ProgressUpdate::rich(
+ scaled,
+ p.downloaded_bytes,
+ Some(total_size_hint.max(1)),
+ p.speed_bps,
+ p.eta_seconds,
+ ))
+ .await;
+ }
+ });
+
+ let video_handle = {
+ let cancel = opts.cancel.clone();
+ let url = video_url.url.clone();
+ let path = temp_video.clone();
+ let referer = referer.clone();
+ let ua = ua.clone();
+ let cookie = cookie_header.clone();
+ tokio::spawn(async move {
+ fetch::fetch_stream(
+ fetch::FetchOptions {
+ url: &url,
+ output_path: &path,
+ referer: &referer,
+ user_agent: &ua,
+ cookie_header: cookie.as_deref(),
+ cancel: Some(cancel),
+ },
+ video_tx,
+ )
+ .await
+ })
+ };
+
+ let audio_handle = if let Some(audio_res) = audio_resolved.clone() {
+ let (audio_tx, mut audio_rx) = mpsc::channel::<ProgressUpdate>(32);
+ let progress_audio = progress.clone();
+ tokio::spawn(async move {
+ while let Some(p) = audio_rx.recv().await {
+ let scaled = scale_progress(p.percent, 1, total_streams);
+ let _ = progress_audio
+ .send(ProgressUpdate::rich(
+ scaled,
+ p.downloaded_bytes,
+ Some(total_size_hint.max(1)),
+ p.speed_bps,
+ p.eta_seconds,
+ ))
+ .await;
+ }
+ });
+ let cancel = opts.cancel.clone();
+ let url = audio_res.url.clone();
+ let path = temp_audio.clone();
+ let referer = referer.clone();
+ let ua = ua.clone();
+ let cookie = cookie_header.clone();
+ Some(tokio::spawn(async move {
+ fetch::fetch_stream(
+ fetch::FetchOptions {
+ url: &url,
+ output_path: &path,
+ referer: &referer,
+ user_agent: &ua,
+ cookie_header: cookie.as_deref(),
+ cancel: Some(cancel),
+ },
+ audio_tx,
+ )
+ .await
+ }))
+ } else {
+ None
+ };
+
+ let video_result = video_handle
+ .await
+ .map_err(|_| BilibiliError::ContentUnavailable)??;
+ let audio_result = match audio_handle {
+ Some(h) => Some(h.await.map_err(|_| BilibiliError::ContentUnavailable)??),
+ None => None,
+ };
+
+ if opts.cancel.is_cancelled() {
+ cleanup(&[&temp_video, &temp_audio, &temp_cover]);
+ return Err(BilibiliError::Cancelled);
+ }
+
+ let cover_path_opt = if opts.embed_cover {
+ if let Some(cover_url) = item.cover_url.as_deref() {
+ download_cover(client, cover_url, &temp_cover).await.ok()
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
+ let _ = progress.send(ProgressUpdate::percent(95.0)).await;
+
+ let final_path =
+ opts.output_dir
+ .join(format!("{}.{}", opts.filename, opts.container.extension()));
+ if let Some(parent) = final_path.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+
+ if audio_result.is_some() {
+ mux::mux(mux::MuxInputs {
+ video: &temp_video,
+ audio: &temp_audio,
+ cover: cover_path_opt.as_deref(),
+ output: &final_path,
+ container: opts.container,
+ })
+ .await?;
+ } else {
+ std::fs::rename(&temp_video, &final_path).map_err(|_| BilibiliError::ContentUnavailable)?;
+ }
+
+ if !opts.keep_streams {
+ cleanup(&[&temp_video, &temp_audio, &temp_cover]);
+ }
+
+ let folder_for_sidecars = final_path
+ .parent()
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|| opts.output_dir.clone());
+ let file_stem_for_sidecars = final_path
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| opts.filename.clone());
+
+ if opts.danmaku_enabled {
+ let cid = item.cid;
+ let duration = item.duration_seconds.unwrap_or(0.0).max(0.0) as u64;
+ if let (Some(cid_v), format) = (
+ cid,
+ opts.danmaku_format
+ .unwrap_or(super::danmaku::DanmakuFormat::Xml),
+ ) {
+ if duration > 0 {
+ match super::danmaku::fetch_elems(client, cid_v, duration).await {
+ Ok(elems) => {
+ let rendered = super::danmaku::render(&elems, format);
+ let dm_path = folder_for_sidecars.join(format!(
+ "{}.danmaku.{}",
+ file_stem_for_sidecars,
+ format.extension()
+ ));
+ if let Err(e) = std::fs::write(&dm_path, rendered) {
+ tracing::warn!("[bilibili] failed to write danmaku: {}", e);
+ }
+ }
+ Err(e) => {
+ tracing::warn!("[bilibili] danmaku fetch failed: {:?}", e);
+ }
+ }
+ }
+ }
+ }
+
+ if opts.cover_sidecar_enabled {
+ if let Some(cover_url) = item.cover_url.as_deref() {
+ let cover_path = folder_for_sidecars.join(format!(
+ "{}.{}",
+ file_stem_for_sidecars,
+ opts.cover_format.extension()
+ ));
+ if let Err(e) =
+ super::cover::download_to(client, cover_url, &cover_path, opts.cover_format).await
+ {
+ tracing::warn!("[bilibili] cover sidecar failed: {:?}", e);
+ }
+ }
+ }
+
+ if opts.nfo_enabled {
+ if let Some(meta_ref) = metadata {
+ let folder_for_extras = final_path
+ .parent()
+ .map(|p| p.to_path_buf())
+ .unwrap_or_else(|| opts.output_dir.clone());
+ let file_stem = final_path
+ .file_stem()
+ .map(|s| s.to_string_lossy().to_string())
+ .unwrap_or_else(|| opts.filename.clone());
+ write_nfo_files(item, meta_ref, kind, client, &folder_for_extras, &file_stem).await;
+ }
+ }
+
+ let bytes = std::fs::metadata(&final_path).map(|m| m.len()).unwrap_or(0);
+
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+
+ let _ = video_result;
+ Ok(EngineResult { final_path, bytes })
+}
+
+pub async fn run_parsed_content(
+ client: &ApiClient,
+ parsed: &ParsedContent,
+ kind: &UrlKind,
+ opts: &EngineOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<EngineResult> {
+ let first = parsed
+ .items
+ .first()
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ run_single(client, first, kind, opts, Some(&parsed.metadata), progress).await
+}
+
+async fn write_nfo_files(
+ item: &EpisodeItem,
+ metadata: &ContentMetadata,
+ kind: &UrlKind,
+ client: &ApiClient,
+ output_dir: &std::path::Path,
+ filename: &str,
+) {
+ use super::nfo;
+ let nfo_kind = match nfo::classify(kind) {
+ Some(k) => k,
+ None => return,
+ };
+
+ let mut tags: Vec<String> = Vec::new();
+ if nfo_kind == nfo::NfoKind::Movie {
+ if let Some(b) = item.bvid.as_deref() {
+ tags = nfo::fetch_tags(client, b).await;
+ }
+ }
+
+ let xml = nfo::render(nfo_kind, item, metadata, &tags);
+ let path = match nfo_kind {
+ nfo::NfoKind::Movie => output_dir.join(format!("{}.nfo", filename)),
+ nfo::NfoKind::Episode => output_dir.join(format!("{}.nfo", filename)),
+ nfo::NfoKind::TvShow => output_dir.join("tvshow.nfo"),
+ };
+ if let Err(e) = std::fs::write(&path, xml) {
+ tracing::warn!("[bilibili] nfo write failed: {}", e);
+ }
+
+ if nfo::season_uses_tvshow(kind) {
+ let tvshow_path = output_dir.join("tvshow.nfo");
+ if !tvshow_path.exists() {
+ let tvshow_xml = nfo::render(nfo::NfoKind::TvShow, item, metadata, &[]);
+ if let Err(e) = std::fs::write(&tvshow_path, tvshow_xml) {
+ tracing::warn!("[bilibili] tvshow nfo write failed: {}", e);
+ }
+ }
+ }
+}
+
+async fn run_progressive(
+ client: &ApiClient,
+ item: &EpisodeItem,
+ info: &PreviewInfo,
+ opts: &EngineOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> Result<EngineResult> {
+ let stream: &VideoStream = info
+ .video_streams
+ .first()
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let cdn_prefs = query::CdnPreferences {
+ alt_hosts: opts.cdn_alt_hosts.clone(),
+ prefer_alternatives: opts.cdn_prefer_alternatives,
+ };
+ let resolved =
+ query::resolve_best_url_with_cdn(client, &stream.base_url, &stream.backup_urls, &cdn_prefs)
+ .await?;
+ let final_path =
+ opts.output_dir
+ .join(format!("{}.{}", opts.filename, opts.container.extension()));
+ let referer = item
+ .url
+ .clone()
+ .unwrap_or_else(|| "https://www.bilibili.com".to_string());
+ let (ua, cookie_header) = (
+ client.user_agent().to_string(),
+ client.cookie_header().map(|s| s.to_string()),
+ );
+ let result = fetch::fetch_stream(
+ fetch::FetchOptions {
+ url: &resolved.url,
+ output_path: &final_path,
+ referer: &referer,
+ user_agent: &ua,
+ cookie_header: cookie_header.as_deref(),
+ cancel: Some(opts.cancel.clone()),
+ },
+ progress.clone(),
+ )
+ .await?;
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+ Ok(EngineResult {
+ final_path,
+ bytes: result.bytes_written,
+ })
+}
+
+async fn download_cover(
+ client: &ApiClient,
+ cover_url: &str,
+ out_path: &std::path::Path,
+) -> Result<std::path::PathBuf> {
+ let bytes = client.get_bytes(cover_url).await?;
+ if let Some(parent) = out_path.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+ std::fs::write(out_path, bytes).map_err(|_| BilibiliError::ContentUnavailable)?;
+ Ok(out_path.to_path_buf())
+}
+
+fn cleanup(paths: &[&std::path::Path]) {
+ for p in paths {
+ let _ = std::fs::remove_file(p);
+ }
+}
+
+fn sanitize_for_temp(s: &str) -> String {
+ s.chars()
+ .map(|c| match c {
+ '/' | '\\' | ':' | '<' | '>' | '"' | '|' | '?' | '*' => '_',
+ _ => c,
+ })
+ .take(80)
+ .collect()
+}
+
+fn scale_progress(local_pct: f64, stream_index: u32, total_streams: u32) -> f64 {
+ let denom = total_streams.max(1) as f64;
+ let base = stream_index as f64 / denom;
+ let scaled = base + (local_pct / 100.0) / denom;
+ (scaled * 100.0).clamp(0.0, 95.0)
+}
+
+#[allow(dead_code)]
+fn unused_audio_stream(_: &AudioStream) {}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/engine/mux.rs b/src-tauri/omniget-core/src/platforms/bilibili/engine/mux.rs
new file mode 100644
index 00000000..a8a1272e
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/engine/mux.rs
@@ -0,0 +1,90 @@
+use std::path::{Path, PathBuf};
+
+use crate::core::process;
+
+use super::super::api::{BilibiliError, Result};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Container {
+ Mp4,
+ Mkv,
+}
+
+impl Container {
+ pub fn extension(self) -> &'static str {
+ match self {
+ Container::Mp4 => "mp4",
+ Container::Mkv => "mkv",
+ }
+ }
+}
+
+pub struct MuxInputs<'a> {
+ pub video: &'a Path,
+ pub audio: &'a Path,
+ pub cover: Option<&'a Path>,
+ pub output: &'a Path,
+ pub container: Container,
+}
+
+pub async fn mux(inputs: MuxInputs<'_>) -> Result<PathBuf> {
+ if let Some(parent) = inputs.output.parent() {
+ std::fs::create_dir_all(parent).ok();
+ }
+
+ let mut args: Vec<String> = Vec::new();
+ args.push("-y".into());
+ args.push("-i".into());
+ args.push(inputs.video.to_string_lossy().into_owned());
+ args.push("-i".into());
+ args.push(inputs.audio.to_string_lossy().into_owned());
+
+ if let Some(cover_path) = inputs.cover {
+ args.push("-i".into());
+ args.push(cover_path.to_string_lossy().into_owned());
+ }
+
+ args.push("-map".into());
+ args.push("0:v:0".into());
+ args.push("-map".into());
+ args.push("1:a:0".into());
+
+ if inputs.cover.is_some() {
+ args.push("-map".into());
+ args.push("2:v:0".into());
+ }
+
+ args.push("-c:v".into());
+ args.push("copy".into());
+ args.push("-c:a".into());
+ args.push("copy".into());
+
+ if inputs.cover.is_some() && inputs.container == Container::Mp4 {
+ args.push("-c:v:1".into());
+ args.push("mjpeg".into());
+ args.push("-disposition:v:1".into());
+ args.push("attached_pic".into());
+ args.push("-pix_fmt:v:1".into());
+ args.push("yuvj420p".into());
+ }
+
+ if inputs.container == Container::Mp4 {
+ args.push("-movflags".into());
+ args.push("+faststart".into());
+ }
+
+ args.push(inputs.output.to_string_lossy().into_owned());
+
+ let status = process::command("ffmpeg")
+ .args(args.iter().map(|s| s.as_str()))
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .await
+ .map_err(|_| BilibiliError::ContentUnavailable)?;
+
+ if !status.success() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ Ok(inputs.output.to_path_buf())
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/engine/query.rs b/src-tauri/omniget-core/src/platforms/bilibili/engine/query.rs
new file mode 100644
index 00000000..7e3b9fcd
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/engine/query.rs
@@ -0,0 +1,75 @@
+use super::super::api::{ApiClient, BilibiliError, Result};
+use super::super::cdn;
+
+const MIN_VALID_SIZE: u64 = 10 * 1024;
+
+#[derive(Debug, Clone)]
+pub struct ResolvedStream {
+ pub url: String,
+ pub size: u64,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct CdnPreferences {
+ pub alt_hosts: Vec<String>,
+ pub prefer_alternatives: bool,
+}
+
+pub async fn resolve_best_url(
+ client: &ApiClient,
+ primary: &str,
+ backups: &[String],
+) -> Result<ResolvedStream> {
+ resolve_best_url_with_cdn(client, primary, backups, &CdnPreferences::default()).await
+}
+
+pub async fn resolve_best_url_with_cdn(
+ client: &ApiClient,
+ primary: &str,
+ backups: &[String],
+ cdn_prefs: &CdnPreferences,
+) -> Result<ResolvedStream> {
+ let chain = if cdn_prefs.alt_hosts.is_empty() {
+ let mut filtered = cdn::filter_blocked(
+ &std::iter::once(primary.to_string())
+ .chain(backups.iter().cloned())
+ .collect::<Vec<_>>(),
+ );
+ if filtered.is_empty() {
+ filtered.push(primary.to_string());
+ }
+ filtered
+ } else {
+ cdn::expand_with_alternatives(
+ primary,
+ backups,
+ &cdn_prefs.alt_hosts,
+ cdn_prefs.prefer_alternatives,
+ )
+ };
+
+ let mut last_err: Option<BilibiliError> = None;
+ for url in &chain {
+ match client.head_content_length(url).await {
+ Ok(Some(size)) if size >= MIN_VALID_SIZE => {
+ return Ok(ResolvedStream {
+ url: url.clone(),
+ size,
+ });
+ }
+ Ok(Some(_)) => {
+ last_err = Some(BilibiliError::ContentUnavailable);
+ }
+ Ok(None) => {
+ return Ok(ResolvedStream {
+ url: url.clone(),
+ size: 0,
+ });
+ }
+ Err(e) => {
+ last_err = Some(e);
+ }
+ }
+ }
+ Err(last_err.unwrap_or(BilibiliError::ContentUnavailable))
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/legacy.rs b/src-tauri/omniget-core/src/platforms/bilibili/legacy.rs
new file mode 100644
index 00000000..67f97629
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/legacy.rs
@@ -0,0 +1,285 @@
+use crate::models::progress::ProgressUpdate;
+use std::collections::HashSet;
+
+use anyhow::anyhow;
+use tokio::sync::mpsc;
+
+use crate::core::ytdlp;
+use crate::models::media::{
+ DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,
+};
+
+pub fn is_playlist_or_series(url: &str) -> bool {
+ if let Ok(parsed) = url::Url::parse(url) {
+ let path = parsed.path();
+ if path.starts_with("/bangumi/") || path.starts_with("/cheese/") {
+ return true;
+ }
+ if path.contains("/channel/") || path.contains("/favlist/") || path.contains("/medialist/")
+ {
+ return true;
+ }
+ }
+ false
+}
+
+pub fn bilibili_extra_flags() -> Vec<String> {
+ vec![
+ "--referer".to_string(),
+ "https://www.bilibili.com".to_string(),
+ ]
+}
+
+pub async fn get_media_info(url: &str) -> anyhow::Result<MediaInfo> {
+ let ytdlp_path = ytdlp::find_ytdlp_cached()
+ .await
+ .ok_or_else(|| anyhow!("yt-dlp not found"))?;
+
+ let extra = bilibili_extra_flags();
+
+ if is_playlist_or_series(url) {
+ let (title, entries) = ytdlp::get_playlist_info(&ytdlp_path, url, &extra).await?;
+
+ if entries.is_empty() {
+ return Err(anyhow!("Playlist empty or unavailable"));
+ }
+
+ let qualities: Vec<MediaVideoQuality> = entries
+ .iter()
+ .enumerate()
+ .map(|(i, e)| MediaVideoQuality {
+ label: format!("{}. {}", i + 1, e.title),
+ width: 0,
+ height: 0,
+ url: e.url.clone(),
+ format: "mp4".to_string(),
+ })
+ .collect();
+
+ return Ok(MediaInfo {
+ title,
+ author: "Bilibili".to_string(),
+ platform: "bilibili".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: qualities,
+ media_type: MediaType::Playlist,
+ file_size_bytes: None,
+ });
+ }
+
+ let json = ytdlp::get_video_info(&ytdlp_path, url, &extra).await?;
+
+ let title = json
+ .get("title")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Bilibili Video")
+ .to_string();
+
+ let author = json
+ .get("uploader")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Unknown")
+ .to_string();
+
+ let duration = json.get("duration").and_then(|v| v.as_f64());
+
+ let thumbnail = json
+ .get("thumbnail")
+ .and_then(|v| v.as_str())
+ .map(String::from);
+
+ let formats = json
+ .get("formats")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .unwrap_or_default();
+
+ let mut seen_heights = HashSet::new();
+ let mut qualities = Vec::new();
+
+ for fmt in &formats {
+ let height = fmt.get("height").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
+ let vcodec = fmt.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none");
+
+ if height == 0 || vcodec == "none" {
+ continue;
+ }
+ if !seen_heights.insert(height) {
+ continue;
+ }
+
+ let label = match height {
+ 2160 => "4K".to_string(),
+ 1440 => "2K".to_string(),
+ 1080 => "1080p".to_string(),
+ 720 => "720p".to_string(),
+ 480 => "480p".to_string(),
+ 360 => "360p".to_string(),
+ _ => format!("{}p", height),
+ };
+
+ qualities.push(MediaVideoQuality {
+ label,
+ width: fmt.get("width").and_then(|v| v.as_u64()).unwrap_or(0) as u32,
+ height,
+ url: url.to_string(),
+ format: "mp4".to_string(),
+ });
+ }
+
+ qualities.sort_by(|a, b| b.height.cmp(&a.height));
+
+ if qualities.is_empty() {
+ qualities.push(MediaVideoQuality {
+ label: "best".to_string(),
+ width: 0,
+ height: 0,
+ url: url.to_string(),
+ format: "mp4".to_string(),
+ });
+ }
+
+ let has_video = formats
+ .iter()
+ .any(|f| f.get("vcodec").and_then(|v| v.as_str()).unwrap_or("none") != "none");
+
+ Ok(MediaInfo {
+ title,
+ author,
+ platform: "bilibili".to_string(),
+ duration_seconds: duration,
+ thumbnail_url: thumbnail,
+ available_qualities: qualities,
+ media_type: if has_video {
+ MediaType::Video
+ } else {
+ MediaType::Audio
+ },
+ file_size_bytes: None,
+ })
+}
+
+pub async fn download(
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> anyhow::Result<DownloadResult> {
+ let _ = progress.send(ProgressUpdate::percent(0.0)).await;
+
+ let ytdlp_path = match &opts.ytdlp_path {
+ Some(p) => p.clone(),
+ None => ytdlp::find_ytdlp_cached()
+ .await
+ .ok_or_else(|| anyhow!("yt-dlp not found"))?,
+ };
+
+ let url = info
+ .available_qualities
+ .first()
+ .map(|q| q.url.as_str())
+ .unwrap_or("");
+
+ if url.is_empty() {
+ return Err(anyhow!("No URL available"));
+ }
+
+ if info.media_type == MediaType::Playlist {
+ return download_playlist(info, opts, progress, &ytdlp_path).await;
+ }
+
+ let quality_height = opts
+ .quality
+ .as_ref()
+ .and_then(|q| q.trim_end_matches('p').parse::<u32>().ok());
+
+ let extra = vec!["--no-playlist".to_string()];
+
+ ytdlp::download_video(
+ &ytdlp_path,
+ url,
+ &opts.output_dir,
+ quality_height,
+ progress,
+ opts.download_mode.as_deref(),
+ opts.format_id.as_deref(),
+ opts.filename_template.as_deref(),
+ opts.referer.as_deref().or(Some("https://www.bilibili.com")),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ opts.download_subtitles,
+ &extra,
+ opts.audio_format.as_deref(),
+ )
+ .await
+}
+
+async fn download_playlist(
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ytdlp_path: &std::path::Path,
+) -> anyhow::Result<DownloadResult> {
+ let total = info.available_qualities.len().max(1);
+ let mut last_result = DownloadResult {
+ file_path: opts.output_dir.clone(),
+ file_size_bytes: 0,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ };
+
+ for (i, quality) in info.available_qualities.iter().enumerate() {
+ if opts.cancel_token.is_cancelled() {
+ return Err(anyhow!("Download cancelled"));
+ }
+
+ let (entry_tx, mut entry_rx) = mpsc::channel::<ProgressUpdate>(16);
+ let progress_clone = progress.clone();
+ let total_f = total as f64;
+ let idx = i as f64;
+
+ tokio::spawn(async move {
+ while let Some(p) = entry_rx.recv().await {
+ let overall = (idx + p.percent / 100.0) / total_f * 100.0;
+ let _ = progress_clone
+ .send(ProgressUpdate::rich(overall, None, None, p.speed_bps, None))
+ .await;
+ }
+ });
+
+ let extra = vec!["--no-playlist".to_string()];
+
+ match ytdlp::download_video(
+ ytdlp_path,
+ &quality.url,
+ &opts.output_dir,
+ None,
+ entry_tx,
+ opts.download_mode.as_deref(),
+ None,
+ opts.filename_template.as_deref(),
+ opts.referer.as_deref().or(Some("https://www.bilibili.com")),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ opts.download_subtitles,
+ &extra,
+ opts.audio_format.as_deref(),
+ )
+ .await
+ {
+ Ok(result) => {
+ last_result.file_size_bytes += result.file_size_bytes;
+ last_result.duration_seconds += result.duration_seconds;
+ last_result.file_path = result.file_path;
+ }
+ Err(e) => {
+ tracing::error!("[bilibili] playlist item {} failed: {}", i + 1, e);
+ }
+ }
+ }
+
+ let _ = progress.send(ProgressUpdate::percent(100.0)).await;
+ Ok(last_result)
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/mod.rs b/src-tauri/omniget-core/src/platforms/bilibili/mod.rs
new file mode 100644
index 00000000..bbe7d52c
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/mod.rs
@@ -0,0 +1,412 @@
+use std::path::PathBuf;
+use std::sync::{Arc, OnceLock};
+
+use crate::models::progress::ProgressUpdate;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::mpsc;
+
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
+use crate::models::settings::AppSettings;
+use crate::platforms::traits::PlatformDownloader;
+
+pub mod api;
+pub mod auth;
+pub mod cdn;
+pub mod cookie;
+pub mod cover;
+pub mod danmaku;
+pub mod engine;
+pub mod legacy;
+pub mod naming;
+pub mod nfo;
+pub mod notify;
+pub mod parser;
+pub mod preview;
+pub mod url_kind;
+pub mod wbi;
+
+#[derive(Debug, Clone)]
+pub struct BilibiliAuthCookie {
+ pub domain: String,
+ pub http_only: bool,
+ pub path: String,
+ pub secure: bool,
+ pub expires: i64,
+ pub name: String,
+ pub value: String,
+ pub host_only: Option<bool>,
+ pub same_site: Option<String>,
+}
+
+pub trait BilibiliRuntimeProvider: Send + Sync {
+ fn active_account_slug(&self) -> Option<String> {
+ None
+ }
+
+ fn settings(&self) -> AppSettings {
+ AppSettings::default()
+ }
+
+ fn session_expired(&self, slug: Option<&str>) {
+ notify::session_expired(slug);
+ }
+
+ fn persist_account(
+ &self,
+ _cookies: &[BilibiliAuthCookie],
+ _uname: &str,
+ _source_label: &str,
+ ) -> Result<String, String> {
+ Err("errors.bilibili.content_unavailable".to_string())
+ }
+}
+
+static RUNTIME_PROVIDER: OnceLock<Arc<dyn BilibiliRuntimeProvider>> = OnceLock::new();
+
+pub fn set_runtime_provider(provider: Arc<dyn BilibiliRuntimeProvider>) {
+ let _ = RUNTIME_PROVIDER.set(provider);
+}
+
+fn runtime_provider() -> Option<&'static Arc<dyn BilibiliRuntimeProvider>> {
+ RUNTIME_PROVIDER.get()
+}
+
+fn runtime_settings() -> AppSettings {
+ runtime_provider()
+ .map(|provider| provider.settings())
+ .unwrap_or_default()
+}
+
+fn runtime_session_expired(slug: Option<&str>) {
+ if let Some(provider) = runtime_provider() {
+ provider.session_expired(slug);
+ } else {
+ notify::session_expired(slug);
+ }
+}
+
+pub(crate) fn runtime_persist_account(
+ cookies: &[BilibiliAuthCookie],
+ uname: &str,
+ source_label: &str,
+) -> Result<String, String> {
+ if let Some(provider) = runtime_provider() {
+ provider.persist_account(cookies, uname, source_label)
+ } else {
+ persist_account_to_default_cookie_file(cookies, uname)
+ }
+}
+
+fn persist_account_to_default_cookie_file(
+ cookies: &[BilibiliAuthCookie],
+ uname: &str,
+) -> Result<String, String> {
+ let slug = auth::slug_from_uname(uname);
+ let path = crate::core::paths::app_data_dir()
+ .ok_or_else(|| "errors.bilibili.content_unavailable".to_string())?
+ .join("cookies")
+ .join("bilibili.com")
+ .join(format!("{}.txt", slug));
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
+ }
+
+ let mut content = String::from("# Netscape HTTP Cookie File\n");
+ for cookie in cookies {
+ let raw_domain = sanitize_cookie_field(&cookie.domain);
+ let path_field = sanitize_cookie_field(&cookie.path);
+ let name = sanitize_cookie_field(&cookie.name);
+ let value = sanitize_cookie_field(&cookie.value);
+ let http_only_prefix = if cookie.http_only { "#HttpOnly_" } else { "" };
+ let is_host_only = cookie
+ .host_only
+ .unwrap_or_else(|| !raw_domain.starts_with('.'));
+ let (domain, include_subdomains) = if is_host_only {
+ (
+ raw_domain
+ .strip_prefix('.')
+ .unwrap_or(&raw_domain)
+ .to_string(),
+ "FALSE",
+ )
+ } else if raw_domain.starts_with('.') {
+ (raw_domain.clone(), "TRUE")
+ } else {
+ (format!(".{}", raw_domain), "TRUE")
+ };
+ let secure = if cookie.secure { "TRUE" } else { "FALSE" };
+ content.push_str(&format!(
+ "{}{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
+ http_only_prefix,
+ domain,
+ include_subdomains,
+ path_field,
+ secure,
+ cookie.expires,
+ name,
+ value,
+ ));
+ }
+ std::fs::write(path, content).map_err(|e| e.to_string())?;
+ Ok(slug)
+}
+
+fn sanitize_cookie_field(s: &str) -> String {
+ s.chars()
+ .filter(|c| *c != '\n' && *c != '\r' && *c != '\t')
+ .collect()
+}
+
+pub struct BilibiliDownloader;
+
+impl Default for BilibiliDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl BilibiliDownloader {
+ pub fn new() -> Self {
+ Self
+ }
+}
+
+pub fn has_active_account() -> bool {
+ active_account_slug().is_some()
+}
+
+pub fn active_account_slug() -> Option<String> {
+ if let Some(slug) = runtime_provider().and_then(|provider| provider.active_account_slug()) {
+ return Some(slug);
+ }
+
+ if let Some(selected) = crate::core::log_hook::current_cookie_slug() {
+ if selected != "_anonymous" && slug_has_session_cookie(&selected) {
+ return Some(selected);
+ }
+ }
+
+ if slug_has_session_cookie("_default") {
+ return Some("_default".to_string());
+ }
+
+ None
+}
+
+fn slug_has_session_cookie(slug: &str) -> bool {
+ let path =
+ match crate::platforms::cookie_provider::cookie_path_for_account("bilibili.com", slug) {
+ Some(p) => p,
+ None => return false,
+ };
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(_) => return false,
+ };
+ content.lines().any(|line| {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ return false;
+ }
+ line.split('\t').nth(5) == Some("SESSDATA")
+ })
+}
+
+async fn api_engine_download(
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+) -> anyhow::Result<DownloadResult> {
+ let _ = cookie::ensure_fresh().await;
+
+ let url = info
+ .available_qualities
+ .first()
+ .map(|q| q.url.as_str())
+ .unwrap_or("");
+ if url.is_empty() {
+ return Err(anyhow!("No URL available"));
+ }
+
+ let slug = active_account_slug();
+ let client = build_api_client(slug.as_deref(), opts.user_agent.as_deref())?;
+
+ let mut effective_url = url.to_string();
+ if url_kind::is_b23_short(&effective_url) {
+ if let Ok(resolved) = url_kind::resolve_b23(&client, &effective_url).await {
+ effective_url = resolved;
+ }
+ }
+
+ let kind = url_kind::detect(&effective_url)
+ .map_err(|e| anyhow!("Failed to detect URL kind: {}", e.i18n_key()))?;
+ let parsed = parser::parse(&client, &kind)
+ .await
+ .map_err(|e| anyhow!("Failed to parse content: {}", e.i18n_key()))?;
+
+ let settings = runtime_settings();
+ let container = mux::container_from_setting(&settings.download.bilibili_container);
+ let danmaku_format = danmaku_format_from_setting(&settings.download.bilibili_danmaku_format);
+ let cover_format = cover::CoverFormat::from_str(&settings.download.bilibili_cover_format);
+ let template_set = naming::TemplateSet {
+ video: settings.download.bilibili_naming_video.clone(),
+ multi_part: settings.download.bilibili_naming_multi_part.clone(),
+ bangumi: settings.download.bilibili_naming_bangumi.clone(),
+ cheese: settings.download.bilibili_naming_cheese.clone(),
+ collection: settings.download.bilibili_naming_collection.clone(),
+ };
+ let first_item_owned = parsed.items.first().cloned().unwrap_or_default();
+ let naming_kind = naming::classify(&kind, &first_item_owned);
+ let naming_inputs = naming::NamingInputs {
+ item: &first_item_owned,
+ metadata: &parsed.metadata,
+ parsed_title: &parsed.title,
+ };
+ let rendered_name = naming::render_for_kind(naming_kind, &naming_inputs, &template_set);
+ let filename = if rendered_name.is_empty() {
+ sanitize(&first_item_owned.title)
+ } else {
+ rendered_name
+ };
+ let cdn_alt_hosts = cdn::parse_hosts(&settings.download.bilibili_cdn_hosts);
+ let engine_opts = engine::EngineOptions {
+ output_dir: PathBuf::from(opts.output_dir.clone()),
+ container,
+ video_qn_pref: if settings.download.bilibili_preferred_qn != 0 {
+ settings.download.bilibili_preferred_qn
+ } else {
+ preview::QN_AUTO
+ },
+ video_codec_pref: if settings.download.bilibili_preferred_codec != 0 {
+ settings.download.bilibili_preferred_codec
+ } else {
+ preview::CODEC_AUTO
+ },
+ audio_qn_pref: if settings.download.bilibili_preferred_audio_qn != 0 {
+ settings.download.bilibili_preferred_audio_qn
+ } else {
+ preview::AUDIO_AUTO
+ },
+ embed_cover: settings.download.embed_thumbnail,
+ keep_streams: false,
+ filename,
+ cancel: opts.cancel_token.clone(),
+ danmaku_enabled: settings.download.bilibili_danmaku_enabled,
+ danmaku_format: Some(danmaku_format),
+ nfo_enabled: settings.download.bilibili_nfo_enabled,
+ cover_sidecar_enabled: settings.download.bilibili_cover_sidecar,
+ cover_format,
+ cdn_alt_hosts,
+ cdn_prefer_alternatives: settings.download.bilibili_cdn_prefer_alternatives,
+ };
+
+ let result = engine::run_parsed_content(&client, &parsed, &kind, &engine_opts, progress)
+ .await
+ .map_err(|e| anyhow!("Engine failed: {}", e.i18n_key()))?;
+
+ Ok(DownloadResult {
+ file_path: result.final_path,
+ file_size_bytes: result.bytes,
+ duration_seconds: parsed
+ .items
+ .first()
+ .and_then(|i| i.duration_seconds)
+ .unwrap_or(0.0),
+ torrent_id: None,
+ })
+}
+
+fn build_api_client(
+ slug: Option<&str>,
+ user_agent: Option<&str>,
+) -> anyhow::Result<api::ApiClient> {
+ let mut client =
+ api::ApiClient::new().map_err(|e| anyhow!("api client init failed: {}", e.i18n_key()))?;
+ if let Some(ua) = user_agent.filter(|s| !s.is_empty()) {
+ client = client.with_user_agent(ua);
+ }
+ match slug {
+ Some(s) => client = client.with_account(s),
+ None => client = client.with_anonymous_cookies(),
+ }
+ Ok(client)
+}
+
+fn sanitize(s: &str) -> String {
+ let cleaned = sanitize_filename::sanitize(s);
+ if cleaned.is_empty() {
+ "video".to_string()
+ } else {
+ cleaned
+ }
+}
+
+mod mux {
+ pub use super::engine::mux::Container;
+
+ pub fn container_from_setting(value: &str) -> Container {
+ match value {
+ "mkv" => Container::Mkv,
+ _ => Container::Mp4,
+ }
+ }
+}
+
+fn danmaku_format_from_setting(value: &str) -> danmaku::DanmakuFormat {
+ match value {
+ "ass" => danmaku::DanmakuFormat::Ass,
+ "json" => danmaku::DanmakuFormat::Json,
+ _ => danmaku::DanmakuFormat::Xml,
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for BilibiliDownloader {
+ fn name(&self) -> &str {
+ "bilibili"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ if let Ok(parsed) = url::Url::parse(url) {
+ if let Some(host) = parsed.host_str() {
+ let host = host.to_lowercase();
+ return host.contains("bilibili.com")
+ || host.contains("bilibili.tv")
+ || host == "b23.tv";
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ legacy::get_media_info(url).await
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ if has_active_account() && info.media_type != MediaType::Playlist {
+ tracing::info!("[bilibili] using api-direct engine (account active)");
+ match api_engine_download(info, opts, progress.clone()).await {
+ Ok(r) => return Ok(r),
+ Err(e) => {
+ let msg = e.to_string();
+ if msg.contains("errors.bilibili.not_logged_in") {
+ runtime_session_expired(active_account_slug().as_deref());
+ }
+ tracing::warn!(
+ "[bilibili] api engine failed, falling back to legacy yt-dlp: {}",
+ e
+ );
+ return legacy::download(info, opts, progress).await;
+ }
+ }
+ }
+ legacy::download(info, opts, progress).await
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/naming.rs b/src-tauri/omniget-core/src/platforms/bilibili/naming.rs
new file mode 100644
index 00000000..3647c2e6
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/naming.rs
@@ -0,0 +1,340 @@
+use chrono::{DateTime, Utc};
+use std::collections::HashMap;
+
+use super::parser::{ContentMetadata, EpisodeItem};
+use super::url_kind::UrlKind;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NamingKind {
+ Video,
+ MultiPart,
+ Bangumi,
+ Cheese,
+ Collection,
+}
+
+pub fn classify(kind: &UrlKind, item: &EpisodeItem) -> NamingKind {
+ match kind {
+ UrlKind::BangumiEpisode { .. }
+ | UrlKind::BangumiSeason { .. }
+ | UrlKind::BangumiMedia { .. } => NamingKind::Bangumi,
+ UrlKind::CheeseEpisode { .. } | UrlKind::CheeseSeason { .. } => NamingKind::Cheese,
+ UrlKind::Space { .. }
+ | UrlKind::Favlist { .. }
+ | UrlKind::Collection { .. }
+ | UrlKind::Series { .. }
+ | UrlKind::PopularWeek { .. } => NamingKind::Collection,
+ UrlKind::Video { .. } | UrlKind::Festival { .. } => {
+ if item.page.is_some() {
+ NamingKind::MultiPart
+ } else {
+ NamingKind::Video
+ }
+ }
+ UrlKind::WatchLater | UrlKind::History => NamingKind::Video,
+ }
+}
+
+pub const DEFAULT_VIDEO: &str = "{title}";
+pub const DEFAULT_MULTI_PART: &str = "{parent_title}/P{page} - {leaf_title}";
+pub const DEFAULT_BANGUMI: &str =
+ "{series_title}/Season {season_number}/{episode_number_pad2} - {episode_title}";
+pub const DEFAULT_CHEESE: &str =
+ "{series_title}/{section_title}/{episode_number_pad2} - {episode_title}";
+pub const DEFAULT_COLLECTION: &str = "{collection_title}/{title}";
+
+pub struct NamingInputs<'a> {
+ pub item: &'a EpisodeItem,
+ pub metadata: &'a ContentMetadata,
+ pub parsed_title: &'a str,
+}
+
+pub fn render(template: &str, inputs: &NamingInputs<'_>) -> String {
+ let vars = build_vars(inputs);
+ let rendered = substitute(template, &vars);
+ sanitize_path(&rendered)
+}
+
+pub fn render_for_kind(
+ kind: NamingKind,
+ inputs: &NamingInputs<'_>,
+ overrides: &TemplateSet,
+) -> String {
+ let template = overrides.template_for(kind);
+ render(template, inputs)
+}
+
+#[derive(Debug, Clone)]
+pub struct TemplateSet {
+ pub video: String,
+ pub multi_part: String,
+ pub bangumi: String,
+ pub cheese: String,
+ pub collection: String,
+}
+
+impl Default for TemplateSet {
+ fn default() -> Self {
+ Self {
+ video: DEFAULT_VIDEO.into(),
+ multi_part: DEFAULT_MULTI_PART.into(),
+ bangumi: DEFAULT_BANGUMI.into(),
+ cheese: DEFAULT_CHEESE.into(),
+ collection: DEFAULT_COLLECTION.into(),
+ }
+ }
+}
+
+impl TemplateSet {
+ pub fn template_for(&self, kind: NamingKind) -> &str {
+ match kind {
+ NamingKind::Video => &self.video,
+ NamingKind::MultiPart => &self.multi_part,
+ NamingKind::Bangumi => &self.bangumi,
+ NamingKind::Cheese => &self.cheese,
+ NamingKind::Collection => &self.collection,
+ }
+ }
+}
+
+fn build_vars(inputs: &NamingInputs<'_>) -> HashMap<String, String> {
+ let mut vars: HashMap<String, String> = HashMap::new();
+ let item = inputs.item;
+ let meta = inputs.metadata;
+
+ vars.insert("title".into(), item.title.clone());
+ vars.insert("leaf_title".into(), item.title.clone());
+ vars.insert(
+ "parent_title".into(),
+ meta.series_title
+ .clone()
+ .or(meta.season_title.clone())
+ .or(meta.collection_title.clone())
+ .unwrap_or_else(|| inputs.parsed_title.to_string()),
+ );
+
+ if let Some(b) = item.bvid.as_deref() {
+ vars.insert("bvid".into(), b.to_string());
+ }
+ if let Some(a) = item.aid {
+ vars.insert("aid".into(), a.to_string());
+ }
+ if let Some(c) = item.cid {
+ vars.insert("cid".into(), c.to_string());
+ }
+ if let Some(ep) = item.ep_id {
+ vars.insert("ep_id".into(), ep.to_string());
+ }
+ if let Some(s) = item.season_id {
+ vars.insert("season_id".into(), s.to_string());
+ }
+ if let Some(p) = item.page {
+ vars.insert("page".into(), p.to_string());
+ vars.insert("p".into(), p.to_string());
+ }
+ if let Some(num) = item.episode_number {
+ vars.insert("episode_number".into(), num.to_string());
+ vars.insert("episode_number_pad2".into(), format!("{:02}", num));
+ vars.insert("episode_number_pad3".into(), format!("{:03}", num));
+ }
+ if let Some(section) = item.section_title.as_deref() {
+ vars.insert("section_title".into(), section.to_string());
+ }
+ if let Some(page_title) = item.page_title.as_deref() {
+ vars.insert("page_title".into(), page_title.to_string());
+ }
+
+ if let Some(s) = meta.series_title.as_deref() {
+ vars.insert("series_title".into(), s.to_string());
+ }
+ if let Some(s) = meta.season_title.as_deref() {
+ vars.insert("season_title".into(), s.to_string());
+ }
+ if let Some(n) = meta.season_number {
+ vars.insert("season_number".into(), n.to_string());
+ vars.insert("season_number_pad2".into(), format!("{:02}", n));
+ }
+ if let Some(s) = meta.collection_title.as_deref() {
+ vars.insert("collection_title".into(), s.to_string());
+ }
+ if let Some(s) = meta.uploader.as_deref() {
+ vars.insert("uploader".into(), s.to_string());
+ }
+ if let Some(u) = meta.uploader_uid {
+ vars.insert("uploader_uid".into(), u.to_string());
+ }
+ if let Some(s) = meta.favorites_name.as_deref() {
+ vars.insert("favorites_name".into(), s.to_string());
+ }
+ if let Some(s) = meta.favorites_owner.as_deref() {
+ vars.insert("favorites_owner".into(), s.to_string());
+ }
+ if let Some(s) = meta.space_owner.as_deref() {
+ vars.insert("space_owner".into(), s.to_string());
+ vars.insert("uploader".into(), s.to_string());
+ }
+
+ let episode_title = item.title.clone();
+ vars.insert("episode_title".into(), episode_title);
+
+ if let Some(secs) = item.pub_time_secs.or(meta.premiered_secs) {
+ if let Some(dt) = DateTime::<Utc>::from_timestamp(secs as i64, 0) {
+ vars.insert("pub_year".into(), dt.format("%Y").to_string());
+ vars.insert("pub_month".into(), dt.format("%m").to_string());
+ vars.insert("pub_day".into(), dt.format("%d").to_string());
+ vars.insert("pub_date".into(), dt.format("%Y-%m-%d").to_string());
+ }
+ }
+ vars
+}
+
+fn substitute(template: &str, vars: &HashMap<String, String>) -> String {
+ let mut out = String::with_capacity(template.len());
+ let mut chars = template.chars().peekable();
+ while let Some(c) = chars.next() {
+ if c == '{' {
+ let mut name = String::new();
+ let mut closed = false;
+ for nc in chars.by_ref() {
+ if nc == '}' {
+ closed = true;
+ break;
+ }
+ name.push(nc);
+ }
+ if !closed {
+ out.push('{');
+ out.push_str(&name);
+ continue;
+ }
+ let key = name.trim();
+ if let Some(v) = vars.get(key) {
+ out.push_str(v);
+ } else {
+ out.push_str("");
+ }
+ } else if c == '\\' {
+ if let Some(&next) = chars.peek() {
+ if next == '{' || next == '}' {
+ out.push(next);
+ chars.next();
+ continue;
+ }
+ }
+ out.push(c);
+ } else {
+ out.push(c);
+ }
+ }
+ out
+}
+
+pub fn sanitize_path(s: &str) -> String {
+ let parts: Vec<&str> = s.split('/').collect();
+ let cleaned: Vec<String> = parts
+ .into_iter()
+ .map(|p| sanitize_path_segment(p))
+ .filter(|p| !p.is_empty())
+ .collect();
+ cleaned.join("/")
+}
+
+fn sanitize_path_segment(s: &str) -> String {
+ let trimmed = s.trim();
+ let mut out = String::with_capacity(trimmed.len());
+ for c in trimmed.chars() {
+ match c {
+ '<' | '>' | ':' | '"' | '\\' | '|' | '?' | '*' => out.push('-'),
+ '\0'..='\x1f' => out.push('-'),
+ _ => out.push(c),
+ }
+ }
+ let trimmed_end = out.trim_end_matches(['.', ' ']);
+ let mut final_str = trimmed_end.to_string();
+ if final_str.len() > 200 {
+ final_str.truncate(200);
+ }
+ final_str
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn item() -> EpisodeItem {
+ EpisodeItem {
+ title: "My Episode".into(),
+ bvid: Some("BV111".into()),
+ cid: Some(987),
+ episode_number: Some(7),
+ ..EpisodeItem::default()
+ }
+ }
+
+ fn meta() -> ContentMetadata {
+ ContentMetadata {
+ series_title: Some("My Series".into()),
+ season_number: Some(2),
+ uploader: Some("Up".into()),
+ ..ContentMetadata::default()
+ }
+ }
+
+ #[test]
+ fn renders_bangumi_default() {
+ let inputs = NamingInputs {
+ item: &item(),
+ metadata: &meta(),
+ parsed_title: "Whatever",
+ };
+ let out = render(DEFAULT_BANGUMI, &inputs);
+ assert_eq!(out, "My Series/Season 2/07 - My Episode");
+ }
+
+ #[test]
+ fn missing_variables_substituted_empty() {
+ let inputs = NamingInputs {
+ item: &item(),
+ metadata: &ContentMetadata::default(),
+ parsed_title: "T",
+ };
+ let out = render("{unknown_var}/{title}", &inputs);
+ assert_eq!(out, "My Episode");
+ }
+
+ #[test]
+ fn sanitizes_invalid_chars_per_segment() {
+ let mut i = item();
+ i.title = "Bad?<title>:|*".into();
+ let inputs = NamingInputs {
+ item: &i,
+ metadata: &meta(),
+ parsed_title: "T",
+ };
+ let out = render("{title}", &inputs);
+ assert_eq!(out, "Bad--title----");
+ }
+
+ #[test]
+ fn slash_in_template_creates_subfolder() {
+ let inputs = NamingInputs {
+ item: &item(),
+ metadata: &meta(),
+ parsed_title: "T",
+ };
+ let out = render("{series_title}/{episode_number_pad2}", &inputs);
+ assert!(out.contains('/'));
+ assert!(out.contains("07"));
+ }
+
+ #[test]
+ fn escape_braces_with_backslash() {
+ let inputs = NamingInputs {
+ item: &item(),
+ metadata: &meta(),
+ parsed_title: "T",
+ };
+ let out = render(r"\{not a var\}", &inputs);
+ assert_eq!(out, "{not a var}");
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/nfo.rs b/src-tauri/omniget-core/src/platforms/bilibili/nfo.rs
new file mode 100644
index 00000000..a3189a78
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/nfo.rs
@@ -0,0 +1,302 @@
+use chrono::{DateTime, Utc};
+use serde_json::Value;
+
+use super::api::{check_api_response, ApiClient};
+use super::parser::{ContentMetadata, EpisodeItem};
+use super::url_kind::UrlKind;
+
+const TAG_DETAIL_URL: &str = "https://api.bilibili.com/x/web-interface/view/detail/tag";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NfoKind {
+ Movie,
+ TvShow,
+ Episode,
+}
+
+pub fn classify(kind: &UrlKind) -> Option<NfoKind> {
+ match kind {
+ UrlKind::Video { .. } | UrlKind::Festival { .. } => Some(NfoKind::Movie),
+ UrlKind::BangumiEpisode { .. } | UrlKind::CheeseEpisode { .. } => Some(NfoKind::Episode),
+ UrlKind::BangumiSeason { .. }
+ | UrlKind::BangumiMedia { .. }
+ | UrlKind::CheeseSeason { .. } => Some(NfoKind::Episode),
+ _ => None,
+ }
+}
+
+pub fn season_uses_tvshow(kind: &UrlKind) -> bool {
+ matches!(
+ kind,
+ UrlKind::BangumiSeason { .. } | UrlKind::BangumiMedia { .. } | UrlKind::CheeseSeason { .. }
+ )
+}
+
+pub async fn fetch_tags(client: &ApiClient, bvid: &str) -> Vec<String> {
+ let url = format!("{}?bvid={}", TAG_DETAIL_URL, urlencoding::encode(bvid));
+ let raw = match client.get_json(&url).await {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+ let data = match check_api_response(&raw) {
+ Ok(v) => v,
+ Err(_) => return Vec::new(),
+ };
+ let arr = match data.as_array() {
+ Some(a) => a,
+ None => return Vec::new(),
+ };
+ arr.iter()
+ .filter_map(|t| t.get("tag_name").and_then(Value::as_str).map(String::from))
+ .collect()
+}
+
+pub fn render(
+ nfo_kind: NfoKind,
+ item: &EpisodeItem,
+ metadata: &ContentMetadata,
+ tags: &[String],
+) -> String {
+ match nfo_kind {
+ NfoKind::Movie => render_movie(item, metadata, tags),
+ NfoKind::TvShow => render_tvshow(metadata),
+ NfoKind::Episode => render_episode(item, metadata),
+ }
+}
+
+fn render_movie(item: &EpisodeItem, metadata: &ContentMetadata, tags: &[String]) -> String {
+ let mut buf = String::new();
+ buf.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
+ buf.push_str("<movie>\n");
+ write_tag(&mut buf, "title", &item.title);
+ if let Some(plot) = metadata.description.as_deref() {
+ write_tag(&mut buf, "plot", plot);
+ }
+ if let Some(d) = item.duration_seconds {
+ write_tag(
+ &mut buf,
+ "runtime",
+ &format!("{}", (d / 60.0).round() as i64),
+ );
+ }
+ if let Some((year, ymd)) = parse_date(item.pub_time_secs.or(metadata.premiered_secs)) {
+ write_tag(&mut buf, "premiered", &ymd);
+ write_tag(&mut buf, "year", &year.to_string());
+ }
+ write_tag(&mut buf, "studio", "Bilibili");
+ if let Some(uname) = metadata.uploader.as_deref() {
+ write_tag(&mut buf, "director", uname);
+ }
+ for tag in tags.iter().take(20) {
+ write_tag(&mut buf, "tag", tag);
+ write_tag(&mut buf, "genre", tag);
+ }
+ if let Some(b) = item.bvid.as_deref() {
+ buf.push_str(&format!(
+ " <uniqueid type=\"bilibili\">{}</uniqueid>\n",
+ escape(b)
+ ));
+ }
+ buf.push_str("</movie>\n");
+ buf
+}
+
+fn render_tvshow(metadata: &ContentMetadata) -> String {
+ let title = metadata
+ .series_title
+ .as_deref()
+ .or(metadata.season_title.as_deref())
+ .unwrap_or("Bilibili")
+ .to_string();
+ let mut buf = String::new();
+ buf.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
+ buf.push_str("<tvshow>\n");
+ write_tag(&mut buf, "title", &title);
+ if let Some(plot) = metadata.description.as_deref() {
+ write_tag(&mut buf, "plot", plot);
+ }
+ if let Some((year, ymd)) = parse_date(metadata.premiered_secs) {
+ write_tag(&mut buf, "premiered", &ymd);
+ write_tag(&mut buf, "year", &year.to_string());
+ }
+ write_tag(&mut buf, "studio", "Bilibili");
+ if let Some(uname) = metadata.uploader.as_deref() {
+ write_tag(&mut buf, "director", uname);
+ }
+ if let Some(actors) = metadata.actors.as_deref() {
+ for actor in actors
+ .split(['\n', ',', '/', '、'])
+ .map(|s| s.trim())
+ .filter(|s| !s.is_empty())
+ {
+ buf.push_str(" <actor>\n");
+ write_tag_indented(&mut buf, " ", "name", actor);
+ buf.push_str(" </actor>\n");
+ }
+ }
+ if let Some(score) = metadata.rating {
+ write_tag(&mut buf, "rating", &format!("{:.1}", score));
+ }
+ for style in &metadata.styles {
+ write_tag(&mut buf, "genre", style);
+ }
+ for area in &metadata.areas {
+ write_tag(&mut buf, "country", area);
+ }
+ if let Some(sid) = metadata.season_id {
+ buf.push_str(&format!(
+ " <uniqueid type=\"bilibili-ss\">{}</uniqueid>\n",
+ sid
+ ));
+ }
+ if let Some(mid) = metadata.media_id {
+ buf.push_str(&format!(
+ " <uniqueid type=\"bilibili-md\">{}</uniqueid>\n",
+ mid
+ ));
+ }
+ buf.push_str("</tvshow>\n");
+ buf
+}
+
+fn render_episode(item: &EpisodeItem, metadata: &ContentMetadata) -> String {
+ let mut buf = String::new();
+ buf.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
+ buf.push_str("<episodedetails>\n");
+ write_tag(&mut buf, "title", &item.title);
+ if let Some(plot) = metadata.description.as_deref() {
+ write_tag(&mut buf, "plot", plot);
+ }
+ if let Some(d) = item.duration_seconds {
+ write_tag(
+ &mut buf,
+ "runtime",
+ &format!("{}", (d / 60.0).round() as i64),
+ );
+ }
+ if let Some((year, ymd)) = parse_date(item.pub_time_secs.or(metadata.premiered_secs)) {
+ write_tag(&mut buf, "premiered", &ymd);
+ write_tag(&mut buf, "year", &year.to_string());
+ }
+ write_tag(&mut buf, "studio", "Bilibili");
+ if let Some(num) = item.episode_number {
+ write_tag(&mut buf, "episode", &num.to_string());
+ }
+ if let Some(season) = metadata.season_number {
+ write_tag(&mut buf, "season", &season.to_string());
+ }
+ if let Some(uname) = metadata.uploader.as_deref() {
+ write_tag(&mut buf, "director", uname);
+ }
+ for style in &metadata.styles {
+ write_tag(&mut buf, "genre", style);
+ }
+ for area in &metadata.areas {
+ write_tag(&mut buf, "country", area);
+ }
+ if let Some(ep_id) = item.ep_id {
+ buf.push_str(&format!(
+ " <uniqueid type=\"bilibili-ep\">{}</uniqueid>\n",
+ ep_id
+ ));
+ }
+ buf.push_str("</episodedetails>\n");
+ buf
+}
+
+fn write_tag(buf: &mut String, name: &str, value: &str) {
+ buf.push_str(&format!(" <{}>{}</{}>\n", name, escape(value), name));
+}
+
+fn write_tag_indented(buf: &mut String, indent: &str, name: &str, value: &str) {
+ buf.push_str(&format!(
+ "{}<{}>{}</{}>\n",
+ indent,
+ name,
+ escape(value),
+ name
+ ));
+}
+
+fn escape(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for c in s.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&apos;"),
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+fn parse_date(secs: Option<u64>) -> Option<(i32, String)> {
+ let s = secs?;
+ let dt: DateTime<Utc> = DateTime::from_timestamp(s as i64, 0)?;
+ let year = dt.format("%Y").to_string().parse::<i32>().ok()?;
+ let ymd = dt.format("%Y-%m-%d").to_string();
+ Some((year, ymd))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn dummy_item() -> EpisodeItem {
+ EpisodeItem {
+ episode_id: "video:BV123".into(),
+ title: "My Title".into(),
+ bvid: Some("BV123".into()),
+ duration_seconds: Some(180.0),
+ pub_time_secs: Some(1700000000),
+ episode_number: Some(3),
+ ..EpisodeItem::default()
+ }
+ }
+
+ fn dummy_meta() -> ContentMetadata {
+ ContentMetadata {
+ series_title: Some("My Series".into()),
+ description: Some("Some <plot> & more".into()),
+ uploader: Some("UpName".into()),
+ premiered_secs: Some(1700000000),
+ season_number: Some(2),
+ styles: vec!["Anime".into()],
+ areas: vec!["Japan".into()],
+ season_id: Some(42),
+ media_id: Some(99),
+ ..ContentMetadata::default()
+ }
+ }
+
+ #[test]
+ fn movie_includes_basics_and_escapes() {
+ let xml = render_movie(&dummy_item(), &dummy_meta(), &["Tag1".into()]);
+ assert!(xml.contains("<title>My Title</title>"));
+ assert!(xml.contains("Some &lt;plot&gt; &amp; more"));
+ assert!(xml.contains("<studio>Bilibili</studio>"));
+ assert!(xml.contains("<runtime>3</runtime>"));
+ assert!(xml.contains("<year>2023</year>"));
+ assert!(xml.contains("<tag>Tag1</tag>"));
+ assert!(xml.contains("<uniqueid type=\"bilibili\">BV123</uniqueid>"));
+ }
+
+ #[test]
+ fn tvshow_includes_series_and_genres() {
+ let xml = render_tvshow(&dummy_meta());
+ assert!(xml.contains("<title>My Series</title>"));
+ assert!(xml.contains("<genre>Anime</genre>"));
+ assert!(xml.contains("<country>Japan</country>"));
+ assert!(xml.contains("<uniqueid type=\"bilibili-ss\">42</uniqueid>"));
+ }
+
+ #[test]
+ fn episode_has_season_and_episode() {
+ let xml = render_episode(&dummy_item(), &dummy_meta());
+ assert!(xml.contains("<season>2</season>"));
+ assert!(xml.contains("<episode>3</episode>"));
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/notify.rs b/src-tauri/omniget-core/src/platforms/bilibili/notify.rs
new file mode 100644
index 00000000..eecf832f
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/notify.rs
@@ -0,0 +1,31 @@
+use once_cell::sync::OnceCell;
+use serde::Serialize;
+
+pub type Emitter = Box<dyn Fn(&str, serde_json::Value) + Send + Sync + 'static>;
+
+static EMITTER: OnceCell<Emitter> = OnceCell::new();
+
+pub fn set_emitter(emitter: Emitter) {
+ let _ = EMITTER.set(emitter);
+}
+
+pub fn emit(event: &str, payload: serde_json::Value) {
+ if let Some(em) = EMITTER.get() {
+ em(event, payload);
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct SessionExpiredPayload {
+ pub slug: Option<String>,
+ pub uname_hint: Option<String>,
+}
+
+pub fn session_expired(slug: Option<&str>) {
+ let payload = SessionExpiredPayload {
+ slug: slug.map(String::from),
+ uname_hint: None,
+ };
+ let value = serde_json::to_value(&payload).unwrap_or(serde_json::Value::Null);
+ emit("bilibili-session-expired", value);
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/bangumi.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/bangumi.rs
new file mode 100644
index 00000000..bc997f52
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/bangumi.rs
@@ -0,0 +1,242 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{ContentMetadata, EpisodeItem, ParsedContent};
+
+const SEASON_URL: &str = "https://api.bilibili.com/pgc/view/web/season";
+const REVIEW_USER_URL: &str = "https://api.bilibili.com/pgc/review/user";
+
+pub async fn parse_by_ep(client: &ApiClient, ep_id: u64) -> Result<ParsedContent> {
+ let url = format!("{}?ep_id={}", SEASON_URL, ep_id);
+ let raw = client.get_json(&url).await?;
+ let result = check_api_response(&raw)?;
+ build_parsed_content(result, Some(ep_id))
+}
+
+pub async fn parse_by_season(client: &ApiClient, season_id: u64) -> Result<ParsedContent> {
+ let url = format!("{}?season_id={}", SEASON_URL, season_id);
+ let raw = client.get_json(&url).await?;
+ let result = check_api_response(&raw)?;
+ build_parsed_content(result, None)
+}
+
+pub async fn parse_by_media(client: &ApiClient, media_id: u64) -> Result<ParsedContent> {
+ let lookup_url = format!("{}?media_id={}", REVIEW_USER_URL, media_id);
+ let raw = client.get_json(&lookup_url).await?;
+ let data = check_api_response(&raw)?;
+ let season_id = data
+ .get("media")
+ .and_then(|m| m.get("season_id"))
+ .and_then(Value::as_u64)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ parse_by_season(client, season_id).await
+}
+
+fn build_parsed_content(result: &Value, highlight_ep: Option<u64>) -> Result<ParsedContent> {
+ let series_title = result
+ .get("series")
+ .and_then(|s| s.get("series_title"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let season_title = result
+ .get("season_title")
+ .and_then(Value::as_str)
+ .map(String::from);
+ let title = series_title
+ .clone()
+ .or_else(|| season_title.clone())
+ .unwrap_or_else(|| "Bilibili Bangumi".to_string());
+
+ let cover = result
+ .get("cover")
+ .and_then(Value::as_str)
+ .map(String::from);
+ let poster = result
+ .get("bkg_cover")
+ .and_then(Value::as_str)
+ .or_else(|| result.get("horizontal_cover").and_then(Value::as_str))
+ .map(String::from)
+ .or_else(|| cover.clone());
+ let description = result
+ .get("evaluate")
+ .and_then(Value::as_str)
+ .map(String::from);
+ let media_id = result.get("media_id").and_then(Value::as_u64);
+ let season_id = result.get("season_id").and_then(Value::as_u64);
+ let actors = result
+ .get("actors")
+ .and_then(Value::as_str)
+ .map(String::from);
+ let rating = result
+ .get("rating")
+ .and_then(|r| r.get("score"))
+ .and_then(Value::as_f64)
+ .map(|v| v as f32);
+ let premiered = result
+ .get("publish")
+ .and_then(|p| p.get("pub_time"))
+ .and_then(Value::as_str)
+ .and_then(parse_pub_time)
+ .or_else(|| {
+ result
+ .get("publish")
+ .and_then(|p| p.get("pub_time_show"))
+ .and_then(Value::as_str)
+ .and_then(parse_pub_time)
+ });
+ let areas: Vec<String> = result
+ .get("areas")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|a| a.get("name").and_then(Value::as_str).map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ let styles: Vec<String> = result
+ .get("styles")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|s| s.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ let uploader = result
+ .get("up_info")
+ .and_then(|u| u.get("uname"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let uploader_uid = result
+ .get("up_info")
+ .and_then(|u| u.get("mid"))
+ .and_then(Value::as_u64);
+ let uploader_avatar = result
+ .get("up_info")
+ .and_then(|u| u.get("avatar"))
+ .and_then(Value::as_str)
+ .map(String::from);
+
+ let metadata = ContentMetadata {
+ series_title: series_title.clone().or_else(|| Some(title.clone())),
+ season_title,
+ season_id,
+ media_id,
+ uploader,
+ uploader_uid,
+ uploader_avatar,
+ description,
+ cover: cover.clone(),
+ poster,
+ areas,
+ styles,
+ actors,
+ rating,
+ premiered_secs: premiered,
+ ..ContentMetadata::default()
+ };
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ let mut counter: u32 = 0;
+ if let Some(eps) = result.get("episodes").and_then(Value::as_array) {
+ for ep in eps {
+ if let Some(item) = build_episode_item(ep, None, &mut counter, false) {
+ items.push(item);
+ }
+ }
+ }
+ if let Some(secs) = result.get("section").and_then(Value::as_array) {
+ for sec in secs {
+ let section_title = sec.get("title").and_then(Value::as_str).map(String::from);
+ let is_preview = section_title
+ .as_deref()
+ .map(|t| t.contains("预告") || t.contains("PV"))
+ .unwrap_or(false);
+ if let Some(eps) = sec.get("episodes").and_then(Value::as_array) {
+ for ep in eps {
+ if let Some(item) =
+ build_episode_item(ep, section_title.clone(), &mut counter, is_preview)
+ {
+ items.push(item);
+ }
+ }
+ }
+ }
+ }
+ let _ = highlight_ep;
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ Ok(ParsedContent {
+ title,
+ items,
+ metadata,
+ pagination: None,
+ })
+}
+
+fn build_episode_item(
+ ep: &Value,
+ section_title: Option<String>,
+ counter: &mut u32,
+ is_preview_section: bool,
+) -> Option<EpisodeItem> {
+ let bvid = ep.get("bvid").and_then(Value::as_str)?;
+ let cid = ep.get("cid").and_then(Value::as_u64);
+ let aid = ep.get("aid").and_then(Value::as_u64);
+ let ep_id = ep
+ .get("id")
+ .and_then(Value::as_u64)
+ .or_else(|| ep.get("ep_id").and_then(Value::as_u64));
+ let title = ep
+ .get("long_title")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty())
+ .or_else(|| ep.get("show_title").and_then(Value::as_str))
+ .or_else(|| ep.get("title").and_then(Value::as_str))
+ .unwrap_or("")
+ .to_string();
+ let duration_ms = ep.get("duration").and_then(Value::as_f64);
+ let duration_seconds = duration_ms.map(|ms| ms / 1000.0);
+ let cover = ep.get("cover").and_then(Value::as_str).map(String::from);
+ let pub_time = ep.get("pub_time").and_then(Value::as_u64);
+ let badge_raw = ep.get("badge").and_then(Value::as_str).unwrap_or("");
+ let is_preview = is_preview_section || badge_raw.contains("预告") || badge_raw.contains("PV");
+ let badge = if is_preview {
+ Some("badge.bilibili.preview".to_string())
+ } else if badge_raw.contains("充电") {
+ Some("badge.bilibili.charging_exclusive".to_string())
+ } else if !badge_raw.is_empty() {
+ Some(badge_raw.to_string())
+ } else {
+ None
+ };
+ let episode_number = if is_preview {
+ None
+ } else {
+ *counter += 1;
+ Some(*counter)
+ };
+ Some(EpisodeItem {
+ episode_id: format!("ep:{}", ep_id.unwrap_or(0)),
+ title,
+ aid,
+ bvid: Some(bvid.to_string()),
+ cid,
+ ep_id,
+ duration_seconds,
+ cover_url: cover,
+ pub_time_secs: pub_time,
+ badge,
+ section_title,
+ episode_number,
+ url: ep_id.map(|id| format!("https://www.bilibili.com/bangumi/play/ep{}", id)),
+ ..EpisodeItem::default()
+ })
+}
+
+fn parse_pub_time(s: &str) -> Option<u64> {
+ chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
+ .ok()
+ .map(|dt| dt.and_utc().timestamp().max(0) as u64)
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/cheese.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/cheese.rs
new file mode 100644
index 00000000..9510f34e
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/cheese.rs
@@ -0,0 +1,127 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{ContentMetadata, EpisodeItem, ParsedContent};
+
+const SEASON_URL: &str = "https://api.bilibili.com/pugv/view/web/season/v2";
+
+pub async fn parse_by_ep(client: &ApiClient, ep_id: u64) -> Result<ParsedContent> {
+ let url = format!("{}?ep_id={}", SEASON_URL, ep_id);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ build_parsed_content(data)
+}
+
+pub async fn parse_by_season(client: &ApiClient, season_id: u64) -> Result<ParsedContent> {
+ let url = format!("{}?season_id={}", SEASON_URL, season_id);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ build_parsed_content(data)
+}
+
+fn build_parsed_content(data: &Value) -> Result<ParsedContent> {
+ let title = data
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("Bilibili Course")
+ .to_string();
+ let cover = data.get("cover").and_then(Value::as_str).map(String::from);
+ let description = data
+ .get("subtitle")
+ .and_then(Value::as_str)
+ .map(String::from);
+ let season_id = data.get("season_id").and_then(Value::as_u64);
+ let uploader = data
+ .get("up_info")
+ .and_then(|u| u.get("uname"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let uploader_uid = data
+ .get("up_info")
+ .and_then(|u| u.get("mid"))
+ .and_then(Value::as_u64);
+ let uploader_avatar = data
+ .get("up_info")
+ .and_then(|u| u.get("avatar"))
+ .and_then(Value::as_str)
+ .map(String::from);
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ let mut counter: u32 = 0;
+ let mut first_release: Option<u64> = None;
+ if let Some(secs) = data.get("sections").and_then(Value::as_array) {
+ for sec in secs {
+ let section_title = sec.get("title").and_then(Value::as_str).map(String::from);
+ if let Some(eps) = sec.get("episodes").and_then(Value::as_array) {
+ for ep in eps {
+ let aid = ep.get("aid").and_then(Value::as_u64);
+ let cid = ep.get("cid").and_then(Value::as_u64);
+ let ep_id = ep
+ .get("id")
+ .and_then(Value::as_u64)
+ .or_else(|| ep.get("ep_id").and_then(Value::as_u64));
+ let title_ep = ep
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let dur = ep.get("duration").and_then(Value::as_f64);
+ let cover_ep = ep.get("cover").and_then(Value::as_str).map(String::from);
+ let release = ep.get("release_date").and_then(Value::as_u64);
+ if first_release.is_none() && release.is_some() {
+ first_release = release;
+ }
+ let status = ep.get("status").and_then(Value::as_u64).unwrap_or(0);
+ let badge = match status {
+ 2 => Some("badge.bilibili.paid_locked".to_string()),
+ 3 => Some("badge.bilibili.partial_preview".to_string()),
+ _ => None,
+ };
+ counter += 1;
+ items.push(EpisodeItem {
+ episode_id: format!("cheese:{}", ep_id.unwrap_or(0)),
+ title: title_ep,
+ aid,
+ cid,
+ ep_id,
+ season_id,
+ duration_seconds: dur,
+ cover_url: cover_ep,
+ pub_time_secs: release,
+ episode_number: Some(counter),
+ section_title: section_title.clone(),
+ badge,
+ url: ep_id
+ .map(|id| format!("https://www.bilibili.com/cheese/play/ep{}", id)),
+ ..EpisodeItem::default()
+ });
+ }
+ }
+ }
+ }
+
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ let metadata = ContentMetadata {
+ series_title: Some(title.clone()),
+ season_id,
+ uploader,
+ uploader_uid,
+ uploader_avatar,
+ description,
+ cover: cover.clone(),
+ poster: cover,
+ styles: vec!["Bilibili Cheese".to_string()],
+ premiered_secs: first_release,
+ ..ContentMetadata::default()
+ };
+
+ Ok(ParsedContent {
+ title,
+ items,
+ metadata,
+ pagination: None,
+ })
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/favlist.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/favlist.rs
new file mode 100644
index 00000000..195745c9
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/favlist.rs
@@ -0,0 +1,119 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{ContentMetadata, EpisodeItem, PaginationInfo, ParsedContent};
+
+const RESOURCE_LIST_URL: &str = "https://api.bilibili.com/x/v3/fav/resource/list";
+const PAGE_SIZE: u32 = 40;
+
+pub async fn parse(client: &ApiClient, fid: u64, page: u32) -> Result<ParsedContent> {
+ let url = format!(
+ "{}?media_id={}&pn={}&ps={}&keyword=&order=mtime&type=0&tid=0&platform=web&web_location=333.1387",
+ RESOURCE_LIST_URL,
+ fid,
+ page.max(1),
+ PAGE_SIZE
+ );
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+
+ let info = data.get("info");
+ let fav_title = info
+ .and_then(|i| i.get("title"))
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let media_count = info
+ .and_then(|i| i.get("media_count"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0) as u32;
+ let owner_name = info
+ .and_then(|i| i.get("upper"))
+ .and_then(|u| u.get("name"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let owner_id = info
+ .and_then(|i| i.get("upper"))
+ .and_then(|u| u.get("mid"))
+ .and_then(Value::as_u64);
+ let total_pages = ((media_count + PAGE_SIZE - 1) / PAGE_SIZE).max(1);
+
+ let medias = data
+ .get("medias")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for m in &medias {
+ let bvid = m
+ .get("bvid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if bvid.is_empty() {
+ continue;
+ }
+ let title = m
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let duration = m.get("duration").and_then(Value::as_f64);
+ let cover = m.get("cover").and_then(Value::as_str).map(String::from);
+ let pub_time = m.get("pubtime").and_then(Value::as_u64);
+ let fav_time = m.get("fav_time").and_then(Value::as_u64);
+ let is_ogv = m.get("ogv").is_some() && !m.get("ogv").unwrap_or(&Value::Null).is_null();
+ let badge = if is_ogv {
+ Some("badge.bilibili.pgc".to_string())
+ } else {
+ None
+ };
+ let ep_id = m
+ .get("ogv")
+ .and_then(|o| o.get("ep_id"))
+ .and_then(Value::as_u64);
+ items.push(EpisodeItem {
+ episode_id: format!("fav:{}:{}", fid, bvid),
+ title,
+ bvid: Some(bvid.clone()),
+ ep_id,
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: fav_time.or(pub_time),
+ badge,
+ url: Some(if is_ogv {
+ format!(
+ "https://www.bilibili.com/bangumi/play/ep{}",
+ ep_id.unwrap_or(0)
+ )
+ } else {
+ format!("https://www.bilibili.com/video/{}", bvid)
+ }),
+ ..EpisodeItem::default()
+ });
+ }
+
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ let metadata = ContentMetadata {
+ favorites_name: Some(fav_title.clone()),
+ favorites_owner: owner_name,
+ uploader_uid: owner_id,
+ ..ContentMetadata::default()
+ };
+
+ Ok(ParsedContent {
+ title: fav_title,
+ items,
+ metadata,
+ pagination: Some(PaginationInfo {
+ total_items: media_count,
+ total_pages,
+ current_page: page.max(1),
+ page_size: PAGE_SIZE,
+ }),
+ })
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/festival.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/festival.rs
new file mode 100644
index 00000000..ab9f23f1
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/festival.rs
@@ -0,0 +1,11 @@
+use super::super::api::{ApiClient, BilibiliError, Result};
+use super::super::url_kind::extract_festival_bvid;
+use super::video;
+use super::ParsedContent;
+
+pub async fn parse(client: &ApiClient, url: &str) -> Result<ParsedContent> {
+ let html = String::from_utf8(client.get_bytes(url).await?)
+ .map_err(|_| BilibiliError::ContentUnavailable)?;
+ let bvid = extract_festival_bvid(&html).ok_or(BilibiliError::ContentUnavailable)?;
+ video::parse(client, &bvid, None).await
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/history.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/history.rs
new file mode 100644
index 00000000..20ab585b
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/history.rs
@@ -0,0 +1,118 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{ContentMetadata, EpisodeItem, PaginationInfo, ParsedContent};
+
+const HISTORY_URL: &str = "https://api.bilibili.com/x/web-interface/history/search";
+const PAGE_SIZE: u32 = 20;
+
+pub async fn parse(client: &ApiClient, page: u32) -> Result<ParsedContent> {
+ if client.account_slug().is_none() && client.cookie_header().is_none() {
+ return Err(BilibiliError::NotLoggedIn);
+ }
+ let url = format!(
+ "{}?pn={}&ps={}&keyword=&business=archive&add_time_start=0&add_time_end=0&arc_max_duration=0&arc_min_duration=0&device_type=0&web_location=333.1391",
+ HISTORY_URL,
+ page.max(1),
+ PAGE_SIZE
+ );
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+
+ let total = data
+ .get("page")
+ .and_then(|p| p.get("total"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0) as u32;
+ let total_pages = ((total + PAGE_SIZE - 1) / PAGE_SIZE).max(1);
+ let list = data
+ .get("list")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for v in &list {
+ let history = v.get("history");
+ let business = history
+ .and_then(|h| h.get("business"))
+ .and_then(Value::as_str)
+ .unwrap_or("archive");
+ let bvid = history
+ .and_then(|h| h.get("bvid"))
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let cid = history.and_then(|h| h.get("cid")).and_then(Value::as_u64);
+ if bvid.is_empty() && business == "archive" {
+ continue;
+ }
+ let title_main = v
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let long_title = v
+ .get("long_title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let composed_title = if business == "pgc" && !long_title.is_empty() {
+ format!("{} - {}", title_main, long_title)
+ } else {
+ title_main
+ };
+ let cover = v.get("cover").and_then(Value::as_str).map(String::from);
+ let duration = v.get("duration").and_then(Value::as_f64);
+ let view_at = v.get("view_at").and_then(Value::as_u64);
+ let expired = duration.map(|d| d <= 0.0).unwrap_or(true);
+ let badge = if expired {
+ Some("badge.bilibili.expired".to_string())
+ } else {
+ None
+ };
+ let ep_id = history
+ .and_then(|h| h.get("epid").and_then(Value::as_u64))
+ .or_else(|| history.and_then(|h| h.get("ep_id")).and_then(Value::as_u64));
+ items.push(EpisodeItem {
+ episode_id: format!("history:{}:{}", business, bvid),
+ title: composed_title,
+ bvid: if bvid.is_empty() {
+ None
+ } else {
+ Some(bvid.clone())
+ },
+ cid,
+ ep_id,
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: view_at,
+ badge,
+ url: Some(if business == "pgc" {
+ format!(
+ "https://www.bilibili.com/bangumi/play/ep{}",
+ ep_id.unwrap_or(0)
+ )
+ } else {
+ format!("https://www.bilibili.com/video/{}", bvid)
+ }),
+ ..EpisodeItem::default()
+ });
+ }
+
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ Ok(ParsedContent {
+ title: String::from("History"),
+ items,
+ metadata: ContentMetadata::default(),
+ pagination: Some(PaginationInfo {
+ total_items: total,
+ total_pages,
+ current_page: page.max(1),
+ page_size: PAGE_SIZE,
+ }),
+ })
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/list.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/list.rs
new file mode 100644
index 00000000..8c2a4b98
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/list.rs
@@ -0,0 +1,166 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::{ContentMetadata, EpisodeItem, PaginationInfo, ParsedContent};
+
+const COLLECTION_URL: &str = "https://api.bilibili.com/x/polymer/web-space/seasons_archives_list";
+const SERIES_ARCHIVES_URL: &str = "https://api.bilibili.com/x/series/archives";
+const SERIES_META_URL: &str = "https://api.bilibili.com/x/series/series";
+const PAGE_SIZE: u32 = 30;
+
+pub async fn parse_collection(
+ client: &ApiClient,
+ mid: u64,
+ sid: u64,
+ page: u32,
+) -> Result<ParsedContent> {
+ let url = format!(
+ "{}?mid={}&season_id={}&sort_reverse=false&page_size={}&page_num={}",
+ COLLECTION_URL,
+ mid,
+ sid,
+ PAGE_SIZE,
+ page.max(1)
+ );
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ let meta_title = data
+ .get("meta")
+ .and_then(|m| m.get("name"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let total = data
+ .get("page")
+ .and_then(|p| p.get("total"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0) as u32;
+ let total_pages = ((total + PAGE_SIZE - 1) / PAGE_SIZE).max(1);
+ let archives = data
+ .get("archives")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ let items = archives_to_items(&archives, format!("collection:{}", sid));
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ let title = meta_title
+ .clone()
+ .unwrap_or_else(|| format!("Bilibili Collection {}", sid));
+ let metadata = ContentMetadata {
+ collection_title: meta_title,
+ uploader_uid: Some(mid),
+ ..ContentMetadata::default()
+ };
+ Ok(ParsedContent {
+ title,
+ items,
+ metadata,
+ pagination: Some(PaginationInfo {
+ total_items: total,
+ total_pages,
+ current_page: page.max(1),
+ page_size: PAGE_SIZE,
+ }),
+ })
+}
+
+pub async fn parse_series(
+ client: &ApiClient,
+ mid: u64,
+ sid: u64,
+ page: u32,
+) -> Result<ParsedContent> {
+ let url = format!(
+ "{}?mid={}&series_id={}&only_normal=true&sort=desc&pn={}&ps={}&web_location=333.999",
+ SERIES_ARCHIVES_URL,
+ mid,
+ sid,
+ page.max(1),
+ PAGE_SIZE
+ );
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ let total = data
+ .get("page")
+ .and_then(|p| p.get("total"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0) as u32;
+ let total_pages = ((total + PAGE_SIZE - 1) / PAGE_SIZE).max(1);
+ let archives = data
+ .get("archives")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+ let items = archives_to_items(&archives, format!("series:{}", sid));
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ let meta_title: Option<String> = {
+ let meta_url = format!("{}?series_id={}", SERIES_META_URL, sid);
+ let meta_raw = client.get_json(&meta_url).await.ok();
+ meta_raw
+ .as_ref()
+ .and_then(|r| check_api_response(r).ok())
+ .and_then(|d| d.get("meta"))
+ .and_then(|m| m.get("name"))
+ .and_then(Value::as_str)
+ .map(String::from)
+ };
+
+ let title = meta_title
+ .clone()
+ .unwrap_or_else(|| format!("Bilibili Series {}", sid));
+ let metadata = ContentMetadata {
+ collection_title: meta_title,
+ uploader_uid: Some(mid),
+ ..ContentMetadata::default()
+ };
+ Ok(ParsedContent {
+ title,
+ items,
+ metadata,
+ pagination: Some(PaginationInfo {
+ total_items: total,
+ total_pages,
+ current_page: page.max(1),
+ page_size: PAGE_SIZE,
+ }),
+ })
+}
+
+fn archives_to_items(archives: &[Value], prefix: String) -> Vec<EpisodeItem> {
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for a in archives {
+ let bvid = a
+ .get("bvid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if bvid.is_empty() {
+ continue;
+ }
+ let aid = a.get("aid").and_then(Value::as_u64);
+ let title = a
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let cover = a.get("pic").and_then(Value::as_str).map(String::from);
+ let duration = a.get("duration").and_then(Value::as_f64);
+ let pub_time = a.get("pubdate").and_then(Value::as_u64);
+ items.push(EpisodeItem {
+ episode_id: format!("{}:{}", prefix, bvid),
+ title,
+ aid,
+ bvid: Some(bvid.clone()),
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: pub_time,
+ url: Some(format!("https://www.bilibili.com/video/{}", bvid)),
+ ..EpisodeItem::default()
+ });
+ }
+ items
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/mod.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/mod.rs
new file mode 100644
index 00000000..af1f9e1f
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/mod.rs
@@ -0,0 +1,105 @@
+use serde::{Deserialize, Serialize};
+
+use super::api::{ApiClient, Result};
+use super::url_kind::UrlKind;
+
+pub mod bangumi;
+pub mod cheese;
+pub mod favlist;
+pub mod festival;
+pub mod history;
+pub mod list;
+pub mod popular;
+pub mod space;
+pub mod video;
+pub mod watch_later;
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct EpisodeItem {
+ pub episode_id: String,
+ pub title: String,
+ pub aid: Option<u64>,
+ pub bvid: Option<String>,
+ pub cid: Option<u64>,
+ pub ep_id: Option<u64>,
+ pub season_id: Option<u64>,
+ pub duration_seconds: Option<f64>,
+ pub cover_url: Option<String>,
+ pub pub_time_secs: Option<u64>,
+ pub page: Option<u32>,
+ pub page_title: Option<String>,
+ pub badge: Option<String>,
+ pub section_title: Option<String>,
+ pub episode_number: Option<u32>,
+ pub url: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct ContentMetadata {
+ pub series_title: Option<String>,
+ pub season_title: Option<String>,
+ pub season_number: Option<u32>,
+ pub season_id: Option<u64>,
+ pub media_id: Option<u64>,
+ pub uploader: Option<String>,
+ pub uploader_uid: Option<u64>,
+ pub uploader_avatar: Option<String>,
+ pub description: Option<String>,
+ pub cover: Option<String>,
+ pub poster: Option<String>,
+ pub areas: Vec<String>,
+ pub styles: Vec<String>,
+ pub actors: Option<String>,
+ pub rating: Option<f32>,
+ pub premiered_secs: Option<u64>,
+ pub favorites_name: Option<String>,
+ pub favorites_owner: Option<String>,
+ pub collection_title: Option<String>,
+ pub space_owner: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct PaginationInfo {
+ pub total_items: u32,
+ pub total_pages: u32,
+ pub current_page: u32,
+ pub page_size: u32,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ParsedContent {
+ pub title: String,
+ pub items: Vec<EpisodeItem>,
+ pub metadata: ContentMetadata,
+ pub pagination: Option<PaginationInfo>,
+}
+
+impl ParsedContent {
+ pub fn single(title: String, item: EpisodeItem) -> Self {
+ Self {
+ title,
+ items: vec![item],
+ metadata: ContentMetadata::default(),
+ pagination: None,
+ }
+ }
+}
+
+pub async fn parse(client: &ApiClient, kind: &UrlKind) -> Result<ParsedContent> {
+ match kind {
+ UrlKind::Video { bvid_or_av, page } => video::parse(client, bvid_or_av, *page).await,
+ UrlKind::BangumiEpisode { ep_id } => bangumi::parse_by_ep(client, *ep_id).await,
+ UrlKind::BangumiSeason { season_id } => bangumi::parse_by_season(client, *season_id).await,
+ UrlKind::BangumiMedia { media_id } => bangumi::parse_by_media(client, *media_id).await,
+ UrlKind::CheeseEpisode { ep_id } => cheese::parse_by_ep(client, *ep_id).await,
+ UrlKind::CheeseSeason { season_id } => cheese::parse_by_season(client, *season_id).await,
+ UrlKind::Space { mid } => space::parse(client, *mid, 1).await,
+ UrlKind::Favlist { fid } => favlist::parse(client, *fid, 1).await,
+ UrlKind::Collection { mid, sid } => list::parse_collection(client, *mid, *sid, 1).await,
+ UrlKind::Series { mid, sid } => list::parse_series(client, *mid, *sid, 1).await,
+ UrlKind::PopularWeek { num } => popular::parse(client, *num).await,
+ UrlKind::WatchLater => watch_later::parse(client, 1).await,
+ UrlKind::History => history::parse(client, 1).await,
+ UrlKind::Festival { url } => festival::parse(client, url).await,
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/popular.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/popular.rs
new file mode 100644
index 00000000..cab8c549
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/popular.rs
@@ -0,0 +1,81 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::super::wbi;
+use super::{ContentMetadata, EpisodeItem, ParsedContent};
+
+const POPULAR_URL: &str = "https://api.bilibili.com/x/web-interface/popular/series/one";
+
+pub async fn parse(client: &ApiClient, num: u32) -> Result<ParsedContent> {
+ let params: Vec<(&str, String)> = vec![
+ ("number", num.to_string()),
+ ("web_location", "333.934".to_string()),
+ ];
+ let signed = wbi::signed_query(client, &params).await?;
+ let url = format!("{}?{}", POPULAR_URL, signed);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+
+ let label = data
+ .get("config")
+ .and_then(|c| c.get("label"))
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let title = if label.is_empty() {
+ format!("Bilibili Popular #{}", num)
+ } else {
+ label
+ };
+
+ let list = data
+ .get("list")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for v in &list {
+ let bvid = v
+ .get("bvid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if bvid.is_empty() {
+ continue;
+ }
+ let aid = v.get("aid").and_then(Value::as_u64);
+ let cid = v.get("cid").and_then(Value::as_u64);
+ let title_v = v
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let cover = v.get("pic").and_then(Value::as_str).map(String::from);
+ let duration = v.get("duration").and_then(Value::as_f64);
+ let pub_time = v.get("pubdate").and_then(Value::as_u64);
+ items.push(EpisodeItem {
+ episode_id: format!("popular:{}:{}", num, bvid),
+ title: title_v,
+ aid,
+ bvid: Some(bvid.clone()),
+ cid,
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: pub_time,
+ url: Some(format!("https://www.bilibili.com/video/{}", bvid)),
+ ..EpisodeItem::default()
+ });
+ }
+
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ Ok(ParsedContent {
+ title,
+ items,
+ metadata: ContentMetadata::default(),
+ pagination: None,
+ })
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/space.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/space.rs
new file mode 100644
index 00000000..76063384
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/space.rs
@@ -0,0 +1,142 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::super::wbi;
+use super::{ContentMetadata, EpisodeItem, PaginationInfo, ParsedContent};
+
+const SEARCH_URL: &str = "https://api.bilibili.com/x/space/wbi/arc/search";
+const CARD_URL: &str = "https://api.bilibili.com/x/web-interface/card";
+const PAGE_SIZE: u32 = 40;
+
+pub async fn parse(client: &ApiClient, mid: u64, page: u32) -> Result<ParsedContent> {
+ let card_url = format!("{}?mid={}", CARD_URL, mid);
+ let card_raw = client.get_json(&card_url).await.ok();
+ let space_owner = card_raw
+ .as_ref()
+ .and_then(|r| check_api_response(r).ok())
+ .and_then(|d| d.get("card"))
+ .and_then(|c| c.get("name"))
+ .and_then(Value::as_str)
+ .map(String::from);
+
+ let pn = page.max(1).to_string();
+ let ps = PAGE_SIZE.to_string();
+ let mid_str = mid.to_string();
+ let params: Vec<(&str, String)> = vec![
+ ("mid", mid_str),
+ ("pn", pn),
+ ("ps", ps),
+ ("tid", "0".to_string()),
+ ("order", "pubdate".to_string()),
+ ("platform", "web".to_string()),
+ ("web_location", "333.1387".to_string()),
+ ];
+ let signed = wbi::signed_query(client, &params).await?;
+ let url = format!("{}?{}", SEARCH_URL, signed);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+
+ let count = data
+ .get("page")
+ .and_then(|p| p.get("count"))
+ .and_then(Value::as_u64)
+ .unwrap_or(0) as u32;
+ let total_pages = ((count + PAGE_SIZE - 1) / PAGE_SIZE).max(1);
+
+ let vlist = data
+ .get("list")
+ .and_then(|l| l.get("vlist"))
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for v in &vlist {
+ let bvid = v
+ .get("bvid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if bvid.is_empty() {
+ continue;
+ }
+ let aid = v.get("aid").and_then(Value::as_u64);
+ let title = v
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let cover = v.get("pic").and_then(Value::as_str).map(String::from);
+ let duration = v
+ .get("length")
+ .and_then(Value::as_str)
+ .and_then(parse_mmss_to_seconds);
+ let created = v.get("created").and_then(Value::as_u64);
+ let mut badge: Option<String> = None;
+ if v.get("is_charging_arc")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ badge = Some("badge.bilibili.charging_exclusive".to_string());
+ } else if v.get("is_union_video").and_then(Value::as_u64).unwrap_or(0) > 0 {
+ badge = Some("badge.bilibili.collab".to_string());
+ }
+ items.push(EpisodeItem {
+ episode_id: format!("space:{}:{}", mid, bvid),
+ title,
+ aid,
+ bvid: Some(bvid.clone()),
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: created,
+ badge,
+ url: Some(format!("https://www.bilibili.com/video/{}", bvid)),
+ ..EpisodeItem::default()
+ });
+ }
+
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ let title = space_owner
+ .clone()
+ .map(|n| format!("{} · Bilibili", n))
+ .unwrap_or_else(|| format!("Bilibili Space {}", mid));
+
+ let metadata = ContentMetadata {
+ space_owner,
+ uploader_uid: Some(mid),
+ ..ContentMetadata::default()
+ };
+
+ Ok(ParsedContent {
+ title,
+ items,
+ metadata,
+ pagination: Some(PaginationInfo {
+ total_items: count,
+ total_pages,
+ current_page: page.max(1),
+ page_size: PAGE_SIZE,
+ }),
+ })
+}
+
+fn parse_mmss_to_seconds(s: &str) -> Option<f64> {
+ let parts: Vec<&str> = s.split(':').collect();
+ match parts.len() {
+ 2 => {
+ let m: u64 = parts[0].parse().ok()?;
+ let sec: u64 = parts[1].parse().ok()?;
+ Some((m * 60 + sec) as f64)
+ }
+ 3 => {
+ let h: u64 = parts[0].parse().ok()?;
+ let m: u64 = parts[1].parse().ok()?;
+ let sec: u64 = parts[2].parse().ok()?;
+ Some((h * 3600 + m * 60 + sec) as f64)
+ }
+ _ => None,
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/video.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/video.rs
new file mode 100644
index 00000000..af67a00e
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/video.rs
@@ -0,0 +1,227 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::super::url_kind::av_to_bv;
+use super::super::wbi;
+use super::{ContentMetadata, EpisodeItem, ParsedContent};
+
+const VIEW_URL: &str = "https://api.bilibili.com/x/web-interface/wbi/view";
+
+pub async fn parse(
+ client: &ApiClient,
+ bvid_or_av: &str,
+ page_filter: Option<u32>,
+) -> Result<ParsedContent> {
+ let bvid = normalize_bvid(bvid_or_av).ok_or(BilibiliError::ContentUnavailable)?;
+ let params: Vec<(&str, String)> = vec![("bvid", bvid.clone())];
+ let signed = wbi::signed_query(client, &params).await?;
+ let url = format!("{}?{}", VIEW_URL, signed);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+
+ let title = data
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("Bilibili Video")
+ .to_string();
+ let cover = data.get("pic").and_then(Value::as_str).map(String::from);
+ let uploader = data
+ .get("owner")
+ .and_then(|o| o.get("name"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let uploader_uid = data
+ .get("owner")
+ .and_then(|o| o.get("mid"))
+ .and_then(Value::as_u64);
+ let uploader_avatar = data
+ .get("owner")
+ .and_then(|o| o.get("face"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let description = data.get("desc").and_then(Value::as_str).map(String::from);
+ let pub_time = data.get("pubdate").and_then(Value::as_u64);
+ let bvid_val = data
+ .get("bvid")
+ .and_then(Value::as_str)
+ .unwrap_or(&bvid)
+ .to_string();
+ let aid = data.get("aid").and_then(Value::as_u64);
+ let badge = if data
+ .get("is_upower_exclusive")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ Some("badge.bilibili.charging_exclusive".to_string())
+ } else {
+ None
+ };
+
+ let mut metadata = ContentMetadata {
+ uploader,
+ uploader_uid,
+ uploader_avatar,
+ description,
+ cover: cover.clone(),
+ premiered_secs: pub_time,
+ ..ContentMetadata::default()
+ };
+
+ if let Some(season) = data.get("ugc_season").and_then(Value::as_object) {
+ let series_title = season
+ .get("title")
+ .and_then(Value::as_str)
+ .map(String::from);
+ metadata.collection_title = series_title.clone();
+ metadata.series_title = series_title;
+
+ // Try to match the requested bvid against ugc_season episodes.
+ // If found, return only that single episode (preserving user intent).
+ // If not found, fall through to normal single-video handling below.
+ if let Some(sections) = season.get("sections").and_then(Value::as_array) {
+ for sec in sections {
+ if let Some(eps) = sec.get("episodes").and_then(Value::as_array) {
+ for ep in eps {
+ let ep_bvid = ep.get("bvid").and_then(Value::as_str).unwrap_or("");
+ if ep_bvid == bvid {
+ let ep_aid = ep.get("aid").and_then(Value::as_u64);
+ let ep_cid = ep.get("cid").and_then(Value::as_u64);
+ let ep_title = ep
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let arc = ep.get("arc");
+ let dur = arc.and_then(|a| a.get("duration")).and_then(Value::as_f64);
+ let cover_ep = arc
+ .and_then(|a| a.get("pic"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let pub_ep = arc.and_then(|a| a.get("pubdate")).and_then(Value::as_u64);
+ let item = EpisodeItem {
+ episode_id: format!("ugc:{}", ep_bvid),
+ title: ep_title,
+ aid: ep_aid,
+ bvid: Some(ep_bvid.to_string()),
+ cid: ep_cid,
+ duration_seconds: dur,
+ cover_url: cover_ep,
+ pub_time_secs: pub_ep,
+ section_title: sec
+ .get("title")
+ .and_then(Value::as_str)
+ .map(String::from),
+ url: Some(format!("https://www.bilibili.com/video/{}", ep_bvid)),
+ ..EpisodeItem::default()
+ };
+ return Ok(ParsedContent {
+ title,
+ items: vec![item],
+ metadata,
+ pagination: None,
+ });
+ }
+ }
+ }
+ }
+ }
+ // No match found in ugc_season — fall through to single-video handling.
+ }
+
+ let pages = data.get("pages").and_then(Value::as_array);
+ if let Some(pgs) = pages {
+ if pgs.len() > 1 || page_filter.is_some() {
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for p in pgs {
+ let page_num = p.get("page").and_then(Value::as_u64).unwrap_or(0) as u32;
+ if let Some(filter) = page_filter {
+ if filter != page_num {
+ continue;
+ }
+ }
+ let cid = p.get("cid").and_then(Value::as_u64);
+ let part = p
+ .get("part")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let dur = p.get("duration").and_then(Value::as_f64);
+ items.push(EpisodeItem {
+ episode_id: format!("page:{}:{}", bvid_val, page_num),
+ title: if part.is_empty() {
+ title.clone()
+ } else {
+ part.clone()
+ },
+ aid,
+ bvid: Some(bvid_val.clone()),
+ cid,
+ duration_seconds: dur,
+ cover_url: cover.clone(),
+ pub_time_secs: pub_time,
+ page: Some(page_num),
+ page_title: Some(part),
+ badge: badge.clone(),
+ url: Some(format!(
+ "https://www.bilibili.com/video/{}?p={}",
+ bvid_val, page_num
+ )),
+ ..EpisodeItem::default()
+ });
+ }
+ if !items.is_empty() {
+ return Ok(ParsedContent {
+ title: title.clone(),
+ items,
+ metadata,
+ pagination: None,
+ });
+ }
+ }
+ }
+
+ let cid = data.get("cid").and_then(Value::as_u64).or_else(|| {
+ pages
+ .and_then(|p| p.first())
+ .and_then(|p| p.get("cid"))
+ .and_then(Value::as_u64)
+ });
+ let duration = data.get("duration").and_then(Value::as_f64);
+ let item = EpisodeItem {
+ episode_id: format!("video:{}", bvid_val),
+ title: title.clone(),
+ aid,
+ bvid: Some(bvid_val.clone()),
+ cid,
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: pub_time,
+ badge,
+ url: Some(format!("https://www.bilibili.com/video/{}", bvid_val)),
+ ..EpisodeItem::default()
+ };
+ Ok(ParsedContent::single_with_meta(title, item, metadata))
+}
+
+fn normalize_bvid(input: &str) -> Option<String> {
+ if input.starts_with("BV") {
+ return Some(input.to_string());
+ }
+ if let Some(rest) = input.strip_prefix("av") {
+ if let Ok(n) = rest.parse::<u64>() {
+ return Some(av_to_bv(n));
+ }
+ }
+ None
+}
+
+impl ParsedContent {
+ pub fn single_with_meta(title: String, item: EpisodeItem, metadata: ContentMetadata) -> Self {
+ Self {
+ title,
+ items: vec![item],
+ metadata,
+ pagination: None,
+ }
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/parser/watch_later.rs b/src-tauri/omniget-core/src/platforms/bilibili/parser/watch_later.rs
new file mode 100644
index 00000000..0fc953e8
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/parser/watch_later.rs
@@ -0,0 +1,100 @@
+use serde_json::Value;
+
+use super::super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::super::wbi;
+use super::{ContentMetadata, EpisodeItem, PaginationInfo, ParsedContent};
+
+const TOVIEW_URL: &str = "https://api.bilibili.com/x/v2/history/toview/web";
+const PAGE_SIZE: u32 = 20;
+
+pub async fn parse(client: &ApiClient, page: u32) -> Result<ParsedContent> {
+ if client.account_slug().is_none() && client.cookie_header().is_none() {
+ return Err(BilibiliError::NotLoggedIn);
+ }
+
+ let params: Vec<(&str, String)> = vec![
+ ("pn", page.max(1).to_string()),
+ ("ps", PAGE_SIZE.to_string()),
+ ("viewed", "0".to_string()),
+ ("key", String::new()),
+ ("asc", "false".to_string()),
+ ("need_split", "true".to_string()),
+ ("web_location", "333.881".to_string()),
+ ];
+ let signed = wbi::signed_query(client, &params).await?;
+ let url = format!("{}?{}", TOVIEW_URL, signed);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+
+ let count = data.get("count").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let total_pages = ((count + PAGE_SIZE - 1) / PAGE_SIZE).max(1);
+ let list = data
+ .get("list")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_default();
+
+ let mut items: Vec<EpisodeItem> = Vec::new();
+ for v in &list {
+ let bvid = v
+ .get("bvid")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ if bvid.is_empty() {
+ continue;
+ }
+ let aid = v.get("aid").and_then(Value::as_u64);
+ let cid = v.get("cid").and_then(Value::as_u64);
+ let title = v
+ .get("title")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string();
+ let cover = v.get("pic").and_then(Value::as_str).map(String::from);
+ let duration = v.get("duration").and_then(Value::as_f64);
+ let pub_time = v.get("pubdate").and_then(Value::as_u64);
+ let add_at = v.get("add_at").and_then(Value::as_u64);
+ let bangumi = v.get("bangumi");
+ let ep_id = bangumi.and_then(|b| b.get("ep_id")).and_then(Value::as_u64);
+ let badge = if ep_id.is_some() {
+ Some("badge.bilibili.pgc".to_string())
+ } else {
+ None
+ };
+ items.push(EpisodeItem {
+ episode_id: format!("toview:{}", bvid),
+ title,
+ aid,
+ bvid: Some(bvid.clone()),
+ cid,
+ ep_id,
+ duration_seconds: duration,
+ cover_url: cover,
+ pub_time_secs: add_at.or(pub_time),
+ badge,
+ url: Some(if let Some(id) = ep_id {
+ format!("https://www.bilibili.com/bangumi/play/ep{}", id)
+ } else {
+ format!("https://www.bilibili.com/video/{}", bvid)
+ }),
+ ..EpisodeItem::default()
+ });
+ }
+
+ if items.is_empty() {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+
+ Ok(ParsedContent {
+ title: String::from("Watch Later"),
+ items,
+ metadata: ContentMetadata::default(),
+ pagination: Some(PaginationInfo {
+ total_items: count,
+ total_pages,
+ current_page: page.max(1),
+ page_size: PAGE_SIZE,
+ }),
+ })
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/preview.rs b/src-tauri/omniget-core/src/platforms/bilibili/preview.rs
new file mode 100644
index 00000000..3692d770
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/preview.rs
@@ -0,0 +1,610 @@
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::api::{check_api_response, ApiClient, BilibiliError, Result};
+use super::parser::EpisodeItem;
+use super::url_kind::UrlKind;
+use super::wbi;
+
+const UGC_PLAYURL: &str = "https://api.bilibili.com/x/player/wbi/playurl";
+const PGC_PLAYURL: &str = "https://api.bilibili.com/pgc/player/web/playurl";
+const CHEESE_PLAYURL: &str = "https://api.bilibili.com/pugv/player/web/playurl";
+
+pub const QN_AUTO: u32 = 200;
+pub const QN_8K: u32 = 127;
+pub const QN_DOLBY_VISION: u32 = 126;
+pub const QN_HDR: u32 = 125;
+pub const QN_4K: u32 = 120;
+pub const QN_1080P60: u32 = 116;
+pub const QN_1080P_PLUS: u32 = 112;
+pub const QN_AI: u32 = 100;
+pub const QN_1080P: u32 = 80;
+pub const QN_720P: u32 = 64;
+pub const QN_480P: u32 = 32;
+pub const QN_360P: u32 = 16;
+
+pub const CODEC_AUTO: u32 = 20;
+pub const CODEC_AVC: u32 = 7;
+pub const CODEC_HEVC: u32 = 12;
+pub const CODEC_AV1: u32 = 13;
+
+pub const AUDIO_AUTO: u32 = 30300;
+pub const AUDIO_HIRES: u32 = 30251;
+pub const AUDIO_DOLBY_ATMOS: u32 = 30250;
+pub const AUDIO_192K: u32 = 30280;
+pub const AUDIO_132K: u32 = 30232;
+pub const AUDIO_64K: u32 = 30216;
+
+const DEFAULT_VIDEO_QUALITY_PRIORITY: &[u32] = &[
+ QN_8K,
+ QN_DOLBY_VISION,
+ QN_HDR,
+ QN_4K,
+ QN_1080P60,
+ QN_1080P_PLUS,
+ QN_1080P,
+ QN_720P,
+ QN_480P,
+ QN_360P,
+];
+
+const DEFAULT_CODEC_PRIORITY: &[u32] = &[CODEC_AV1, CODEC_HEVC, CODEC_AVC];
+
+const DEFAULT_AUDIO_PRIORITY: &[u32] = &[
+ AUDIO_HIRES,
+ AUDIO_DOLBY_ATMOS,
+ AUDIO_192K,
+ AUDIO_132K,
+ AUDIO_64K,
+];
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub enum MediaContainer {
+ Dash,
+ Mp4,
+ Flv,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VideoStream {
+ pub qn: u32,
+ pub codec_id: u32,
+ pub width: Option<u32>,
+ pub height: Option<u32>,
+ pub frame_rate: Option<String>,
+ pub bandwidth: Option<u64>,
+ pub base_url: String,
+ pub backup_urls: Vec<String>,
+ pub mime_type: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AudioStream {
+ pub qn: u32,
+ pub codec: Option<String>,
+ pub bandwidth: Option<u64>,
+ pub base_url: String,
+ pub backup_urls: Vec<String>,
+ pub mime_type: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PreviewInfo {
+ pub container: MediaContainer,
+ pub video_streams: Vec<VideoStream>,
+ pub audio_streams: Vec<AudioStream>,
+ pub accepted_qns: Vec<u32>,
+ pub accepted_qn_labels: Vec<String>,
+ pub timelength_ms: Option<u64>,
+ pub premium_required: bool,
+}
+
+impl PreviewInfo {
+ pub fn available_qns(&self) -> Vec<u32> {
+ let mut set: BTreeMap<u32, ()> = BTreeMap::new();
+ for v in &self.video_streams {
+ set.insert(v.qn, ());
+ }
+ set.into_keys().rev().collect()
+ }
+
+ pub fn available_codecs_for(&self, qn: u32) -> Vec<u32> {
+ let mut codecs: Vec<u32> = self
+ .video_streams
+ .iter()
+ .filter(|v| v.qn == qn)
+ .map(|v| v.codec_id)
+ .collect();
+ codecs.sort_unstable();
+ codecs.dedup();
+ codecs
+ }
+
+ pub fn available_audio_qns(&self) -> Vec<u32> {
+ let mut set: BTreeMap<u32, ()> = BTreeMap::new();
+ for a in &self.audio_streams {
+ set.insert(a.qn, ());
+ }
+ set.into_keys().rev().collect()
+ }
+
+ pub fn pick_video(&self, qn_pref: u32, codec_pref: u32) -> Option<&VideoStream> {
+ let qn = if qn_pref == QN_AUTO {
+ self.video_streams
+ .iter()
+ .map(|v| v.qn)
+ .filter(|q| DEFAULT_VIDEO_QUALITY_PRIORITY.contains(q))
+ .max_by_key(|q| {
+ DEFAULT_VIDEO_QUALITY_PRIORITY
+ .iter()
+ .rev()
+ .position(|p| p == q)
+ .unwrap_or(0)
+ })
+ .or_else(|| self.video_streams.iter().map(|v| v.qn).max())?
+ } else if self.video_streams.iter().any(|v| v.qn == qn_pref) {
+ qn_pref
+ } else {
+ self.video_streams.iter().map(|v| v.qn).max()?
+ };
+
+ if codec_pref == CODEC_AUTO {
+ for &c in DEFAULT_CODEC_PRIORITY {
+ if let Some(s) = self
+ .video_streams
+ .iter()
+ .find(|v| v.qn == qn && v.codec_id == c)
+ {
+ return Some(s);
+ }
+ }
+ return self.video_streams.iter().find(|v| v.qn == qn);
+ }
+ if let Some(s) = self
+ .video_streams
+ .iter()
+ .find(|v| v.qn == qn && v.codec_id == codec_pref)
+ {
+ return Some(s);
+ }
+ self.video_streams.iter().find(|v| v.qn == qn)
+ }
+
+ pub fn pick_audio(&self, qn_pref: u32) -> Option<&AudioStream> {
+ if qn_pref == AUDIO_AUTO {
+ for &q in DEFAULT_AUDIO_PRIORITY {
+ if let Some(s) = self.audio_streams.iter().find(|a| a.qn == q) {
+ return Some(s);
+ }
+ }
+ return self.audio_streams.first();
+ }
+ if let Some(s) = self.audio_streams.iter().find(|a| a.qn == qn_pref) {
+ return Some(s);
+ }
+ self.audio_streams.first()
+ }
+}
+
+pub fn qn_label(qn: u32) -> &'static str {
+ match qn {
+ QN_8K => "platforms.bilibili.qn.8k",
+ QN_DOLBY_VISION => "platforms.bilibili.qn.dolby_vision",
+ QN_HDR => "platforms.bilibili.qn.hdr",
+ QN_4K => "platforms.bilibili.qn.4k",
+ QN_1080P60 => "platforms.bilibili.qn.1080p60",
+ QN_1080P_PLUS => "platforms.bilibili.qn.1080p_plus",
+ QN_AI => "platforms.bilibili.qn.ai",
+ QN_1080P => "platforms.bilibili.qn.1080p",
+ QN_720P => "platforms.bilibili.qn.720p",
+ QN_480P => "platforms.bilibili.qn.480p",
+ QN_360P => "platforms.bilibili.qn.360p",
+ _ => "platforms.bilibili.qn.unknown",
+ }
+}
+
+pub fn codec_label(codec: u32) -> &'static str {
+ match codec {
+ CODEC_AVC => "platforms.bilibili.codec.avc",
+ CODEC_HEVC => "platforms.bilibili.codec.hevc",
+ CODEC_AV1 => "platforms.bilibili.codec.av1",
+ _ => "platforms.bilibili.codec.unknown",
+ }
+}
+
+pub fn audio_qn_label(qn: u32) -> &'static str {
+ match qn {
+ AUDIO_HIRES => "platforms.bilibili.audio.hires",
+ AUDIO_DOLBY_ATMOS => "platforms.bilibili.audio.dolby_atmos",
+ AUDIO_192K => "platforms.bilibili.audio.192k",
+ AUDIO_132K => "platforms.bilibili.audio.132k",
+ AUDIO_64K => "platforms.bilibili.audio.64k",
+ _ => "platforms.bilibili.audio.unknown",
+ }
+}
+
+pub async fn fetch(client: &ApiClient, item: &EpisodeItem, kind: &UrlKind) -> Result<PreviewInfo> {
+ match kind {
+ UrlKind::BangumiEpisode { .. }
+ | UrlKind::BangumiSeason { .. }
+ | UrlKind::BangumiMedia { .. } => fetch_pgc(client, item).await,
+ UrlKind::CheeseEpisode { .. } | UrlKind::CheeseSeason { .. } => {
+ fetch_cheese(client, item).await
+ }
+ _ => fetch_ugc(client, item).await,
+ }
+}
+
+async fn fetch_ugc(client: &ApiClient, item: &EpisodeItem) -> Result<PreviewInfo> {
+ let bvid = item
+ .bvid
+ .as_deref()
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let cid = item.cid.ok_or(BilibiliError::ContentUnavailable)?;
+ let params: Vec<(&str, String)> = vec![
+ ("bvid", bvid.to_string()),
+ ("cid", cid.to_string()),
+ ("qn", QN_1080P.to_string()),
+ ("fnver", "0".to_string()),
+ ("fnval", "4048".to_string()),
+ ("fourk", "1".to_string()),
+ ];
+ let signed = wbi::signed_query(client, &params).await?;
+ let url = format!("{}?{}", UGC_PLAYURL, signed);
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ build_preview(data)
+}
+
+async fn fetch_pgc(client: &ApiClient, item: &EpisodeItem) -> Result<PreviewInfo> {
+ let bvid = item
+ .bvid
+ .as_deref()
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let cid = item.cid.ok_or(BilibiliError::ContentUnavailable)?;
+ let url = format!(
+ "{}?bvid={}&cid={}&qn={}&fnver=0&fnval=12240&fourk=1",
+ PGC_PLAYURL, bvid, cid, QN_1080P
+ );
+ let raw = client.get_json(&url).await?;
+ let result = check_api_response(&raw)?;
+ build_preview(result)
+}
+
+async fn fetch_cheese(client: &ApiClient, item: &EpisodeItem) -> Result<PreviewInfo> {
+ let aid = item.aid.ok_or(BilibiliError::ContentUnavailable)?;
+ let cid = item.cid.ok_or(BilibiliError::ContentUnavailable)?;
+ let ep_id = item.ep_id.unwrap_or(0);
+ let url = format!(
+ "{}?avid={}&cid={}&qn={}&fnver=0&fnval=4048&fourk=1&ep_id={}",
+ CHEESE_PLAYURL, aid, cid, QN_1080P, ep_id
+ );
+ let raw = client.get_json(&url).await?;
+ let data = check_api_response(&raw)?;
+ build_preview(data)
+}
+
+fn build_preview(data: &Value) -> Result<PreviewInfo> {
+ let timelength_ms = data.get("timelength").and_then(Value::as_u64);
+ let accepted_qns: Vec<u32> = data
+ .get("accept_quality")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| v.as_u64().map(|n| n as u32))
+ .collect()
+ })
+ .unwrap_or_default();
+ let accepted_qn_labels: Vec<String> = data
+ .get("accept_description")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+
+ if let Some(dash) = data.get("dash").and_then(Value::as_object) {
+ let video_streams = parse_dash_video(dash);
+ let audio_streams = parse_dash_audio(dash);
+ let premium_required = is_premium_required(&accepted_qns, &video_streams);
+ return Ok(PreviewInfo {
+ container: MediaContainer::Dash,
+ video_streams,
+ audio_streams,
+ accepted_qns,
+ accepted_qn_labels,
+ timelength_ms,
+ premium_required,
+ });
+ }
+
+ if let Some(durl) = data.get("durl").and_then(Value::as_array) {
+ let format = data.get("format").and_then(Value::as_str).unwrap_or("mp4");
+ let container = if format.starts_with("flv") {
+ MediaContainer::Flv
+ } else {
+ MediaContainer::Mp4
+ };
+ let quality = data.get("quality").and_then(Value::as_u64).unwrap_or(80) as u32;
+ let video_streams: Vec<VideoStream> = durl
+ .iter()
+ .filter_map(|d| {
+ let url = d.get("url").and_then(Value::as_str)?.to_string();
+ let backups = d
+ .get("backup_url")
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ Some(VideoStream {
+ qn: quality,
+ codec_id: CODEC_AVC,
+ width: None,
+ height: None,
+ frame_rate: None,
+ bandwidth: None,
+ base_url: url,
+ backup_urls: backups,
+ mime_type: Some(format!("video/{}", format)),
+ })
+ })
+ .collect();
+ return Ok(PreviewInfo {
+ container,
+ video_streams,
+ audio_streams: Vec::new(),
+ accepted_qns,
+ accepted_qn_labels,
+ timelength_ms,
+ premium_required: false,
+ });
+ }
+
+ Err(BilibiliError::ContentUnavailable)
+}
+
+fn parse_dash_video(dash: &serde_json::Map<String, Value>) -> Vec<VideoStream> {
+ let mut streams: Vec<VideoStream> = Vec::new();
+ let arr = match dash.get("video").and_then(Value::as_array) {
+ Some(a) => a,
+ None => return streams,
+ };
+ for entry in arr {
+ let qn = entry.get("id").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let codec_id = entry.get("codecid").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let width = entry.get("width").and_then(Value::as_u64).map(|n| n as u32);
+ let height = entry
+ .get("height")
+ .and_then(Value::as_u64)
+ .map(|n| n as u32);
+ let frame_rate = entry
+ .get("frame_rate")
+ .or_else(|| entry.get("frameRate"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let bandwidth = entry.get("bandwidth").and_then(Value::as_u64);
+ let base_url = entry
+ .get("baseUrl")
+ .or_else(|| entry.get("base_url"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let backup_urls = entry
+ .get("backupUrl")
+ .or_else(|| entry.get("backup_url"))
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ let mime_type = entry
+ .get("mimeType")
+ .or_else(|| entry.get("mime_type"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ if let Some(url) = base_url {
+ streams.push(VideoStream {
+ qn,
+ codec_id,
+ width,
+ height,
+ frame_rate,
+ bandwidth,
+ base_url: url,
+ backup_urls,
+ mime_type,
+ });
+ }
+ }
+ streams
+}
+
+fn parse_dash_audio(dash: &serde_json::Map<String, Value>) -> Vec<AudioStream> {
+ let mut streams: Vec<AudioStream> = Vec::new();
+ if let Some(flac) = dash
+ .get("flac")
+ .and_then(Value::as_object)
+ .and_then(|o| o.get("audio"))
+ {
+ if let Some(s) = audio_entry(flac, "audio/flac") {
+ streams.push(s);
+ }
+ }
+ if let Some(dolby_arr) = dash
+ .get("dolby")
+ .and_then(Value::as_object)
+ .and_then(|o| o.get("audio"))
+ .and_then(Value::as_array)
+ {
+ for entry in dolby_arr {
+ if let Some(s) = audio_entry(entry, "audio/eac3") {
+ streams.push(s);
+ }
+ }
+ }
+ if let Some(arr) = dash.get("audio").and_then(Value::as_array) {
+ for entry in arr {
+ if let Some(s) = audio_entry(entry, "audio/mp4") {
+ streams.push(s);
+ }
+ }
+ }
+ streams
+}
+
+fn audio_entry(entry: &Value, default_mime: &str) -> Option<AudioStream> {
+ let qn = entry.get("id").and_then(Value::as_u64).unwrap_or(0) as u32;
+ let codec = entry
+ .get("codecs")
+ .or_else(|| entry.get("codec"))
+ .and_then(Value::as_str)
+ .map(String::from);
+ let bandwidth = entry.get("bandwidth").and_then(Value::as_u64);
+ let base_url = entry
+ .get("baseUrl")
+ .or_else(|| entry.get("base_url"))
+ .and_then(Value::as_str)
+ .map(String::from)?;
+ let backup_urls = entry
+ .get("backupUrl")
+ .or_else(|| entry.get("backup_url"))
+ .and_then(Value::as_array)
+ .map(|arr| {
+ arr.iter()
+ .filter_map(|v| v.as_str().map(String::from))
+ .collect()
+ })
+ .unwrap_or_default();
+ let mime_type = entry
+ .get("mimeType")
+ .or_else(|| entry.get("mime_type"))
+ .and_then(Value::as_str)
+ .map(String::from)
+ .or_else(|| Some(default_mime.to_string()));
+ Some(AudioStream {
+ qn,
+ codec,
+ bandwidth,
+ base_url,
+ backup_urls,
+ mime_type,
+ })
+}
+
+fn is_premium_required(accepted_qns: &[u32], video_streams: &[VideoStream]) -> bool {
+ let has_high = accepted_qns
+ .iter()
+ .any(|q| *q == QN_4K || *q == QN_8K || *q == QN_HDR || *q == QN_DOLBY_VISION);
+ if !has_high {
+ return false;
+ }
+ let downloaded_high = video_streams
+ .iter()
+ .any(|v| v.qn == QN_4K || v.qn == QN_8K || v.qn == QN_HDR || v.qn == QN_DOLBY_VISION);
+ !downloaded_high
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn dummy_stream(qn: u32, codec: u32) -> VideoStream {
+ VideoStream {
+ qn,
+ codec_id: codec,
+ width: None,
+ height: None,
+ frame_rate: None,
+ bandwidth: None,
+ base_url: "https://example/x.m4s".to_string(),
+ backup_urls: vec![],
+ mime_type: None,
+ }
+ }
+
+ #[test]
+ fn pick_video_auto_prefers_higher_quality_and_av1() {
+ let info = PreviewInfo {
+ container: MediaContainer::Dash,
+ video_streams: vec![
+ dummy_stream(QN_1080P, CODEC_AVC),
+ dummy_stream(QN_1080P, CODEC_HEVC),
+ dummy_stream(QN_1080P, CODEC_AV1),
+ dummy_stream(QN_720P, CODEC_AV1),
+ ],
+ audio_streams: vec![],
+ accepted_qns: vec![],
+ accepted_qn_labels: vec![],
+ timelength_ms: None,
+ premium_required: false,
+ };
+ let picked = info.pick_video(QN_AUTO, CODEC_AUTO).expect("picked");
+ assert_eq!(picked.qn, QN_1080P);
+ assert_eq!(picked.codec_id, CODEC_AV1);
+ }
+
+ #[test]
+ fn pick_video_specific_qn_codec() {
+ let info = PreviewInfo {
+ container: MediaContainer::Dash,
+ video_streams: vec![
+ dummy_stream(QN_720P, CODEC_AVC),
+ dummy_stream(QN_720P, CODEC_HEVC),
+ ],
+ audio_streams: vec![],
+ accepted_qns: vec![],
+ accepted_qn_labels: vec![],
+ timelength_ms: None,
+ premium_required: false,
+ };
+ let picked = info.pick_video(QN_720P, CODEC_HEVC).expect("picked");
+ assert_eq!(picked.codec_id, CODEC_HEVC);
+ }
+
+ #[test]
+ fn pick_audio_auto_prefers_hires() {
+ let info = PreviewInfo {
+ container: MediaContainer::Dash,
+ video_streams: vec![],
+ audio_streams: vec![
+ AudioStream {
+ qn: AUDIO_192K,
+ codec: Some("mp4a".into()),
+ bandwidth: None,
+ base_url: "https://x/192k".into(),
+ backup_urls: vec![],
+ mime_type: None,
+ },
+ AudioStream {
+ qn: AUDIO_HIRES,
+ codec: Some("flac".into()),
+ bandwidth: None,
+ base_url: "https://x/hires".into(),
+ backup_urls: vec![],
+ mime_type: None,
+ },
+ ],
+ accepted_qns: vec![],
+ accepted_qn_labels: vec![],
+ timelength_ms: None,
+ premium_required: false,
+ };
+ let picked = info.pick_audio(AUDIO_AUTO).expect("picked");
+ assert_eq!(picked.qn, AUDIO_HIRES);
+ }
+
+ #[test]
+ fn labels_have_i18n_keys() {
+ assert!(qn_label(QN_4K).starts_with("platforms.bilibili."));
+ assert!(codec_label(CODEC_AV1).starts_with("platforms.bilibili."));
+ assert!(audio_qn_label(AUDIO_HIRES).starts_with("platforms.bilibili."));
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/url_kind.rs b/src-tauri/omniget-core/src/platforms/bilibili/url_kind.rs
new file mode 100644
index 00000000..ac3f8aaf
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/url_kind.rs
@@ -0,0 +1,481 @@
+use once_cell::sync::Lazy;
+use regex::Regex;
+
+use super::api::{ApiClient, BilibiliError, Result};
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum UrlKind {
+ Video {
+ bvid_or_av: String,
+ page: Option<u32>,
+ },
+ BangumiEpisode {
+ ep_id: u64,
+ },
+ BangumiSeason {
+ season_id: u64,
+ },
+ BangumiMedia {
+ media_id: u64,
+ },
+ CheeseEpisode {
+ ep_id: u64,
+ },
+ CheeseSeason {
+ season_id: u64,
+ },
+ Space {
+ mid: u64,
+ },
+ Favlist {
+ fid: u64,
+ },
+ Collection {
+ mid: u64,
+ sid: u64,
+ },
+ Series {
+ mid: u64,
+ sid: u64,
+ },
+ PopularWeek {
+ num: u32,
+ },
+ WatchLater,
+ History,
+ Festival {
+ url: String,
+ },
+}
+
+impl UrlKind {
+ pub fn label_key(&self) -> &'static str {
+ match self {
+ UrlKind::Video { .. } => "platforms.bilibili.kind.video",
+ UrlKind::BangumiEpisode { .. } => "platforms.bilibili.kind.bangumi_episode",
+ UrlKind::BangumiSeason { .. } => "platforms.bilibili.kind.bangumi_season",
+ UrlKind::BangumiMedia { .. } => "platforms.bilibili.kind.bangumi_media",
+ UrlKind::CheeseEpisode { .. } => "platforms.bilibili.kind.cheese_episode",
+ UrlKind::CheeseSeason { .. } => "platforms.bilibili.kind.cheese_season",
+ UrlKind::Space { .. } => "platforms.bilibili.kind.space",
+ UrlKind::Favlist { .. } => "platforms.bilibili.kind.favlist",
+ UrlKind::Collection { .. } => "platforms.bilibili.kind.collection",
+ UrlKind::Series { .. } => "platforms.bilibili.kind.series",
+ UrlKind::PopularWeek { .. } => "platforms.bilibili.kind.popular",
+ UrlKind::WatchLater => "platforms.bilibili.kind.watch_later",
+ UrlKind::History => "platforms.bilibili.kind.history",
+ UrlKind::Festival { .. } => "platforms.bilibili.kind.festival",
+ }
+ }
+}
+
+static RE_VIDEO_BV: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"bilibili\.com/video/(BV[a-zA-Z0-9]+|av\d+)").unwrap());
+static RE_BARE_BV: Lazy<Regex> = Lazy::new(|| Regex::new(r"(BV[a-zA-Z0-9]{8,})").unwrap());
+static RE_BARE_AV: Lazy<Regex> = Lazy::new(|| Regex::new(r"\bav(\d+)\b").unwrap());
+static RE_BANGUMI: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"bilibili\.com/bangumi/(?:play|media)/(ss\d+|ep\d+|md\d+)").unwrap());
+static RE_BARE_BANGUMI: Lazy<Regex> = Lazy::new(|| Regex::new(r"\b(ss\d+|ep\d+|md\d+)\b").unwrap());
+static RE_CHEESE: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"bilibili\.com/cheese/play/(ss\d+|ep\d+)").unwrap());
+static RE_LIST_LISTS: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"space\.bilibili\.com/(\d+)/lists(?:/(\d+))?").unwrap());
+static RE_FAVLIST_SPACE: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"space\.bilibili\.com/\d+/favlist").unwrap());
+static RE_FAVLIST_LIST: Lazy<Regex> = Lazy::new(|| {
+ Regex::new(r"bilibili\.com/(?:medialist/detail/)?ml(\d+)|bilibili\.com/list/ml(\d+)").unwrap()
+});
+static RE_SPACE: Lazy<Regex> = Lazy::new(|| Regex::new(r"space\.bilibili\.com/(\d+)").unwrap());
+static RE_MEDIALIST_PLAY: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"bilibili\.com/medialist/play/(\d+)").unwrap());
+static RE_POPULAR: Lazy<Regex> = Lazy::new(|| Regex::new(r"bilibili\.com/v/popular").unwrap());
+static RE_FESTIVAL: Lazy<Regex> = Lazy::new(|| Regex::new(r"bilibili\.com/festival").unwrap());
+static RE_B23: Lazy<Regex> = Lazy::new(|| Regex::new(r"(b23\.tv|bili2233\.cn)").unwrap());
+static RE_LIST_OLD: Lazy<Regex> = Lazy::new(|| Regex::new(r"bilibili\.com/list/(\d+)").unwrap());
+
+pub fn detect(url: &str) -> Result<UrlKind> {
+ detect_internal(url, None)
+}
+
+pub fn detect_with_query(url: &str, query: Option<&str>) -> Result<UrlKind> {
+ detect_internal(url, query)
+}
+
+fn detect_internal(url: &str, query_override: Option<&str>) -> Result<UrlKind> {
+ if url == "omniget://bilibili/watch-later" {
+ return Ok(UrlKind::WatchLater);
+ }
+ if url == "omniget://bilibili/history" {
+ return Ok(UrlKind::History);
+ }
+
+ if RE_VIDEO_BV.is_match(url) {
+ if let Some(cap) = RE_VIDEO_BV.captures(url) {
+ let id = cap
+ .get(1)
+ .map(|m| m.as_str().to_string())
+ .unwrap_or_default();
+ let page = extract_page_query(url, query_override);
+ return Ok(UrlKind::Video {
+ bvid_or_av: id,
+ page,
+ });
+ }
+ }
+
+ if let Some(cap) = RE_BANGUMI.captures(url) {
+ let raw = cap.get(1).map(|m| m.as_str()).unwrap_or("");
+ return parse_bangumi_id(raw);
+ }
+
+ if let Some(cap) = RE_CHEESE.captures(url) {
+ let raw = cap.get(1).map(|m| m.as_str()).unwrap_or("");
+ if let Some(rest) = raw.strip_prefix("ss") {
+ if let Ok(id) = rest.parse::<u64>() {
+ return Ok(UrlKind::CheeseSeason { season_id: id });
+ }
+ }
+ if let Some(rest) = raw.strip_prefix("ep") {
+ if let Ok(id) = rest.parse::<u64>() {
+ return Ok(UrlKind::CheeseEpisode { ep_id: id });
+ }
+ }
+ }
+
+ if let Some(cap) = RE_LIST_LISTS.captures(url) {
+ let mid: u64 = cap
+ .get(1)
+ .and_then(|m| m.as_str().parse().ok())
+ .unwrap_or(0);
+ let sid: u64 = cap
+ .get(2)
+ .and_then(|m| m.as_str().parse().ok())
+ .unwrap_or(0);
+ let kind_q = extract_query_value(url, query_override, "type").unwrap_or_default();
+ let resolved_sid = if sid == 0 {
+ extract_query_value(url, query_override, "sid")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0)
+ } else {
+ sid
+ };
+ if kind_q == "series" {
+ return Ok(UrlKind::Series {
+ mid,
+ sid: resolved_sid,
+ });
+ }
+ return Ok(UrlKind::Collection {
+ mid,
+ sid: resolved_sid,
+ });
+ }
+
+ if RE_FAVLIST_SPACE.is_match(url) {
+ let fid = extract_query_value(url, query_override, "fid")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0);
+ return Ok(UrlKind::Favlist { fid });
+ }
+
+ if let Some(cap) = RE_FAVLIST_LIST.captures(url) {
+ let id = cap
+ .get(1)
+ .or_else(|| cap.get(2))
+ .and_then(|m| m.as_str().parse().ok())
+ .unwrap_or(0);
+ return Ok(UrlKind::Favlist { fid: id });
+ }
+
+ if let Some(cap) = RE_MEDIALIST_PLAY.captures(url) {
+ if let Some(mid) = cap.get(1).and_then(|m| m.as_str().parse().ok()) {
+ return Ok(UrlKind::Space { mid });
+ }
+ }
+
+ if let Some(cap) = RE_SPACE.captures(url) {
+ if let Some(mid) = cap.get(1).and_then(|m| m.as_str().parse().ok()) {
+ return Ok(UrlKind::Space { mid });
+ }
+ }
+
+ if let Some(cap) = RE_LIST_OLD.captures(url) {
+ if let Some(sid) = cap.get(1).and_then(|m| m.as_str().parse().ok()) {
+ return Ok(UrlKind::Collection { mid: 0, sid });
+ }
+ }
+
+ if RE_POPULAR.is_match(url) {
+ let num = extract_query_value(url, query_override, "num")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0);
+ return Ok(UrlKind::PopularWeek { num });
+ }
+
+ if RE_FESTIVAL.is_match(url) {
+ return Ok(UrlKind::Festival {
+ url: url.to_string(),
+ });
+ }
+
+ if let Some(cap) = RE_BARE_BV.captures(url) {
+ let id = cap
+ .get(1)
+ .map(|m| m.as_str().to_string())
+ .unwrap_or_default();
+ return Ok(UrlKind::Video {
+ bvid_or_av: id,
+ page: None,
+ });
+ }
+
+ if let Some(cap) = RE_BARE_AV.captures(url) {
+ let n = cap.get(1).map(|m| m.as_str()).unwrap_or("");
+ return Ok(UrlKind::Video {
+ bvid_or_av: format!("av{}", n),
+ page: None,
+ });
+ }
+
+ if let Some(cap) = RE_BARE_BANGUMI.captures(url) {
+ return parse_bangumi_id(cap.get(1).map(|m| m.as_str()).unwrap_or(""));
+ }
+
+ Err(BilibiliError::ContentUnavailable)
+}
+
+fn parse_bangumi_id(raw: &str) -> Result<UrlKind> {
+ if let Some(rest) = raw.strip_prefix("ep") {
+ if let Ok(id) = rest.parse::<u64>() {
+ return Ok(UrlKind::BangumiEpisode { ep_id: id });
+ }
+ }
+ if let Some(rest) = raw.strip_prefix("ss") {
+ if let Ok(id) = rest.parse::<u64>() {
+ return Ok(UrlKind::BangumiSeason { season_id: id });
+ }
+ }
+ if let Some(rest) = raw.strip_prefix("md") {
+ if let Ok(id) = rest.parse::<u64>() {
+ return Ok(UrlKind::BangumiMedia { media_id: id });
+ }
+ }
+ Err(BilibiliError::ContentUnavailable)
+}
+
+fn extract_query_value(url: &str, query_override: Option<&str>, key: &str) -> Option<String> {
+ if let Some(q) = query_override {
+ for pair in q.split('&') {
+ let mut it = pair.splitn(2, '=');
+ let k = it.next()?;
+ let v = it.next().unwrap_or("");
+ if k == key {
+ return Some(v.to_string());
+ }
+ }
+ }
+ if let Ok(parsed) = url::Url::parse(url) {
+ for (k, v) in parsed.query_pairs() {
+ if k == key {
+ return Some(v.into_owned());
+ }
+ }
+ }
+ None
+}
+
+fn extract_page_query(url: &str, query_override: Option<&str>) -> Option<u32> {
+ extract_query_value(url, query_override, "p").and_then(|s| s.parse().ok())
+}
+
+pub async fn resolve_b23(client: &ApiClient, short: &str) -> Result<String> {
+ let resolved = client.resolve_redirect(short).await?;
+ if resolved == short {
+ return Err(BilibiliError::ContentUnavailable);
+ }
+ Ok(resolved)
+}
+
+pub fn is_b23_short(url: &str) -> bool {
+ RE_B23.is_match(url)
+}
+
+pub fn av_to_bv(avid: u64) -> String {
+ const TABLE: &[u8; 58] = b"fZodR9XQDSUm21yCkr6zBqiveYah8bt4xsWpHnJE7jL5VG3guMTKNPAwcF";
+ const XOR: u64 = 177451812;
+ const ADD: u64 = 8728348608;
+ let s: [usize; 6] = [11, 10, 3, 8, 4, 6];
+ let mut x = (avid ^ XOR).wrapping_add(ADD);
+ let mut chars: [u8; 12] = *b"BV1 4 1 7 ";
+ let mut idx: [usize; 6] = [0; 6];
+ for i in 0..6 {
+ idx[i] = ((x as f64 / 58f64.powi(i as i32)) as u64 % 58) as usize;
+ chars[s[i]] = TABLE[idx[i]];
+ let _ = &mut x;
+ }
+ String::from_utf8(chars.to_vec()).unwrap_or_default()
+}
+
+pub fn parse_video_id(input: &str) -> (Option<String>, Option<u64>) {
+ if let Some(rest) = input.strip_prefix("av") {
+ if let Ok(n) = rest.parse::<u64>() {
+ return (None, Some(n));
+ }
+ }
+ if input.starts_with("BV") {
+ return (Some(input.to_string()), None);
+ }
+ (None, None)
+}
+
+pub fn extract_festival_bvid(html: &str) -> Option<String> {
+ static RE_STATE: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"window\.__INITIAL_STATE__\s*=\s*(\{.*?\});").unwrap());
+ let cap = RE_STATE.captures(html)?;
+ let json_str = cap.get(1)?.as_str();
+ let v: serde_json::Value = serde_json::from_str(json_str).ok()?;
+ v.get("videoInfo")
+ .and_then(|x| x.get("bvid"))
+ .and_then(|x| x.as_str())
+ .map(|s| s.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detects_video_bv() {
+ let url = "https://www.bilibili.com/video/BV1xx411c7mu";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::Video {
+ bvid_or_av: "BV1xx411c7mu".to_string(),
+ page: None,
+ }
+ );
+ }
+
+ #[test]
+ fn detects_video_av() {
+ let url = "https://www.bilibili.com/video/av170001";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::Video {
+ bvid_or_av: "av170001".to_string(),
+ page: None,
+ }
+ );
+ }
+
+ #[test]
+ fn detects_video_multipart() {
+ let url = "https://www.bilibili.com/video/BV1xx411c7mu?p=3";
+ match detect(url).unwrap() {
+ UrlKind::Video { page, .. } => assert_eq!(page, Some(3)),
+ _ => panic!("expected Video"),
+ }
+ }
+
+ #[test]
+ fn detects_bangumi_ep() {
+ let url = "https://www.bilibili.com/bangumi/play/ep123456";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::BangumiEpisode { ep_id: 123456 }
+ );
+ }
+
+ #[test]
+ fn detects_bangumi_ss() {
+ let url = "https://www.bilibili.com/bangumi/play/ss12345";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::BangumiSeason { season_id: 12345 }
+ );
+ }
+
+ #[test]
+ fn detects_bangumi_md() {
+ let url = "https://www.bilibili.com/bangumi/media/md28223066";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::BangumiMedia { media_id: 28223066 }
+ );
+ }
+
+ #[test]
+ fn detects_cheese() {
+ let url = "https://www.bilibili.com/cheese/play/ss1234";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::CheeseSeason { season_id: 1234 }
+ );
+ }
+
+ #[test]
+ fn detects_space() {
+ let url = "https://space.bilibili.com/123456";
+ assert_eq!(detect(url).unwrap(), UrlKind::Space { mid: 123456 });
+ }
+
+ #[test]
+ fn detects_favlist_query() {
+ let url = "https://space.bilibili.com/123/favlist?fid=789";
+ assert_eq!(detect(url).unwrap(), UrlKind::Favlist { fid: 789 });
+ }
+
+ #[test]
+ fn detects_favlist_short() {
+ let url = "https://www.bilibili.com/list/ml42";
+ assert_eq!(detect(url).unwrap(), UrlKind::Favlist { fid: 42 });
+ }
+
+ #[test]
+ fn detects_collection() {
+ let url = "https://space.bilibili.com/123/lists/456?type=season";
+ assert_eq!(
+ detect(url).unwrap(),
+ UrlKind::Collection { mid: 123, sid: 456 }
+ );
+ }
+
+ #[test]
+ fn detects_series() {
+ let url = "https://space.bilibili.com/123/lists/456?type=series";
+ assert_eq!(detect(url).unwrap(), UrlKind::Series { mid: 123, sid: 456 });
+ }
+
+ #[test]
+ fn detects_popular() {
+ let url = "https://www.bilibili.com/v/popular?num=10";
+ assert_eq!(detect(url).unwrap(), UrlKind::PopularWeek { num: 10 });
+ }
+
+ #[test]
+ fn detects_festival() {
+ let url = "https://www.bilibili.com/festival/2024_anime";
+ match detect(url).unwrap() {
+ UrlKind::Festival { .. } => {}
+ _ => panic!("expected Festival"),
+ }
+ }
+
+ #[test]
+ fn detects_b23_short() {
+ assert!(is_b23_short("https://b23.tv/abc"));
+ assert!(is_b23_short("https://bili2233.cn/xyz"));
+ }
+
+ #[test]
+ fn detects_internal_schemas() {
+ assert_eq!(
+ detect("omniget://bilibili/watch-later").unwrap(),
+ UrlKind::WatchLater
+ );
+ assert_eq!(
+ detect("omniget://bilibili/history").unwrap(),
+ UrlKind::History
+ );
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/bilibili/wbi.rs b/src-tauri/omniget-core/src/platforms/bilibili/wbi.rs
new file mode 100644
index 00000000..edc53f12
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/bilibili/wbi.rs
@@ -0,0 +1,182 @@
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use md5::{Digest, Md5};
+use serde_json::Value;
+use tokio::sync::RwLock;
+
+use super::api::{check_api_response, ApiClient, BilibiliError, Result};
+
+const NAV_URL: &str = "https://api.bilibili.com/x/web-interface/nav";
+const KEYS_TTL_SECS: u64 = 30 * 60;
+
+const MIXIN_KEY_ENC_TAB: [usize; 64] = [
+ 46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35, 27, 43, 5, 49, 33, 9, 42, 19, 29,
+ 28, 14, 39, 12, 38, 41, 13, 37, 48, 7, 16, 24, 55, 40, 61, 26, 17, 0, 1, 60, 51, 30, 4, 22, 25,
+ 54, 21, 56, 59, 6, 63, 57, 62, 11, 36, 20, 34, 44, 52,
+];
+
+const RESERVED_FILTER: &[char] = &['!', '\'', '(', ')', '*'];
+
+#[derive(Debug, Clone)]
+pub struct WbiKeys {
+ pub img_key: String,
+ pub sub_key: String,
+ pub fetched_at_secs: u64,
+}
+
+impl WbiKeys {
+ pub fn mixin_key(&self) -> String {
+ let combined = format!("{}{}", self.img_key, self.sub_key);
+ let bytes = combined.as_bytes();
+ let mut mixin = String::with_capacity(32);
+ for &idx in MIXIN_KEY_ENC_TAB.iter().take(32) {
+ if idx < bytes.len() {
+ mixin.push(bytes[idx] as char);
+ }
+ }
+ mixin
+ }
+
+ pub fn is_fresh(&self) -> bool {
+ now_secs().saturating_sub(self.fetched_at_secs) < KEYS_TTL_SECS
+ }
+}
+
+static KEYS_CACHE: RwLock<Option<WbiKeys>> = RwLock::const_new(None);
+
+pub async fn keys(client: &ApiClient) -> Result<WbiKeys> {
+ {
+ let guard = KEYS_CACHE.read().await;
+ if let Some(k) = guard.as_ref() {
+ if k.is_fresh() {
+ return Ok(k.clone());
+ }
+ }
+ }
+ let fresh = fetch_keys(client).await?;
+ {
+ let mut guard = KEYS_CACHE.write().await;
+ *guard = Some(fresh.clone());
+ }
+ Ok(fresh)
+}
+
+pub async fn invalidate_cache() {
+ let mut guard = KEYS_CACHE.write().await;
+ *guard = None;
+}
+
+async fn fetch_keys(client: &ApiClient) -> Result<WbiKeys> {
+ let raw = client.get_json(NAV_URL).await?;
+ let data = match check_api_response(&raw) {
+ Ok(d) => d,
+ Err(BilibiliError::NotLoggedIn) => {
+ raw.get("data").ok_or(BilibiliError::ContentUnavailable)?
+ }
+ Err(e) => return Err(e),
+ };
+ let wbi_img = data
+ .get("wbi_img")
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let img_url = wbi_img
+ .get("img_url")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ let sub_url = wbi_img
+ .get("sub_url")
+ .and_then(Value::as_str)
+ .ok_or(BilibiliError::ContentUnavailable)?;
+ Ok(WbiKeys {
+ img_key: extract_key_from_url(img_url),
+ sub_key: extract_key_from_url(sub_url),
+ fetched_at_secs: now_secs(),
+ })
+}
+
+fn extract_key_from_url(url: &str) -> String {
+ url.rsplit('/')
+ .next()
+ .map(|seg| seg.split('.').next().unwrap_or(seg).to_string())
+ .unwrap_or_default()
+}
+
+pub fn sign(params: &[(&str, String)], keys: &WbiKeys) -> String {
+ let wts = now_secs().to_string();
+ let mut all: Vec<(String, String)> = params
+ .iter()
+ .map(|(k, v)| ((*k).to_string(), filter_value(v)))
+ .collect();
+ all.push(("wts".to_string(), wts.clone()));
+ all.sort_by(|a, b| a.0.cmp(&b.0));
+
+ let query = encode_pairs(&all);
+ let to_hash = format!("{}{}", query, keys.mixin_key());
+ let mut hasher = Md5::new();
+ hasher.update(to_hash.as_bytes());
+ let w_rid = hex::encode(hasher.finalize());
+
+ format!("{}&w_rid={}", query, w_rid)
+}
+
+pub async fn signed_query(client: &ApiClient, params: &[(&str, String)]) -> Result<String> {
+ let k = keys(client).await?;
+ Ok(sign(params, &k))
+}
+
+fn filter_value(v: &str) -> String {
+ v.chars().filter(|c| !RESERVED_FILTER.contains(c)).collect()
+}
+
+fn encode_pairs(pairs: &[(String, String)]) -> String {
+ pairs
+ .iter()
+ .map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v)))
+ .collect::<Vec<_>>()
+ .join("&")
+}
+
+fn now_secs() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap_or(Duration::ZERO)
+ .as_secs()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mixin_key_extracts_32_chars() {
+ let k = WbiKeys {
+ img_key: "7cd084941338484aae1ad9425b84077c".to_string(),
+ sub_key: "4932caff0ff746eab6f01bf08b70ac45".to_string(),
+ fetched_at_secs: 0,
+ };
+ let mix = k.mixin_key();
+ assert_eq!(mix.len(), 32);
+ }
+
+ #[test]
+ fn extract_key_handles_typical_url() {
+ let url = "https://i0.hdslb.com/bfs/wbi/7cd084941338484aae1ad9425b84077c.png";
+ assert_eq!(
+ extract_key_from_url(url),
+ "7cd084941338484aae1ad9425b84077c"
+ );
+ }
+
+ #[test]
+ fn sign_produces_w_rid() {
+ let k = WbiKeys {
+ img_key: "7cd084941338484aae1ad9425b84077c".to_string(),
+ sub_key: "4932caff0ff746eab6f01bf08b70ac45".to_string(),
+ fetched_at_secs: 0,
+ };
+ let params: Vec<(&str, String)> =
+ vec![("foo", "114".to_string()), ("bar", "514".to_string())];
+ let query = sign(&params, &k);
+ assert!(query.contains("w_rid="));
+ assert!(query.contains("wts="));
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/cookie_provider.rs b/src-tauri/omniget-core/src/platforms/cookie_provider.rs
new file mode 100644
index 00000000..c117bc36
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/cookie_provider.rs
@@ -0,0 +1,188 @@
+use std::path::PathBuf;
+use std::sync::{Arc, OnceLock};
+
+pub trait CookieProvider: Send + Sync {
+ fn cookie_path_for(&self, domain: &str) -> Option<PathBuf>;
+
+ fn cookie_path_for_account(&self, domain: &str, _slug: &str) -> Option<PathBuf> {
+ self.cookie_path_for(domain)
+ }
+
+ fn manual_cookie_header(&self, _domain: &str) -> Option<String> {
+ None
+ }
+}
+
+static COOKIE_PROVIDER: OnceLock<Arc<dyn CookieProvider>> = OnceLock::new();
+
+pub struct DefaultCookieProvider;
+
+impl CookieProvider for DefaultCookieProvider {
+ fn cookie_path_for(&self, _domain: &str) -> Option<PathBuf> {
+ let path = crate::core::paths::app_data_dir()?
+ .join("cookies")
+ .join("cookies.txt");
+ path.exists().then_some(path)
+ }
+
+ fn cookie_path_for_account(&self, domain: &str, slug: &str) -> Option<PathBuf> {
+ Some(
+ crate::core::paths::app_data_dir()?
+ .join("cookies")
+ .join(domain)
+ .join(format!("{}.txt", slug)),
+ )
+ }
+}
+
+pub fn set_cookie_provider(provider: Arc<dyn CookieProvider>) {
+ let _ = COOKIE_PROVIDER.set(provider);
+}
+
+pub fn cookie_path_for(domain: &str) -> Option<PathBuf> {
+ COOKIE_PROVIDER
+ .get()
+ .and_then(|provider| provider.cookie_path_for(domain))
+ .or_else(|| DefaultCookieProvider.cookie_path_for(domain))
+}
+
+pub fn cookie_path_for_account(domain: &str, slug: &str) -> Option<PathBuf> {
+ COOKIE_PROVIDER
+ .get()
+ .and_then(|provider| provider.cookie_path_for_account(domain, slug))
+ .or_else(|| DefaultCookieProvider.cookie_path_for_account(domain, slug))
+}
+
+pub fn manual_cookie_header(domain: &str) -> Option<String> {
+ COOKIE_PROVIDER
+ .get()
+ .and_then(|provider| provider.manual_cookie_header(domain))
+}
+
+fn netscape_domain_matches(cookie_domain: &str, requested_domain: &str) -> bool {
+ let cookie_domain = cookie_domain
+ .trim()
+ .trim_start_matches("#HttpOnly_")
+ .trim_start_matches('.')
+ .to_ascii_lowercase();
+ let requested_domain = requested_domain
+ .trim()
+ .trim_start_matches('.')
+ .to_ascii_lowercase();
+
+ !cookie_domain.is_empty()
+ && !requested_domain.is_empty()
+ && (cookie_domain == requested_domain
+ || cookie_domain.ends_with(&format!(".{}", requested_domain))
+ || requested_domain.ends_with(&format!(".{}", cookie_domain)))
+}
+
+pub fn cookie_header_from_netscape_for_domain(content: &str, domain: &str) -> Option<String> {
+ let pairs: Vec<String> = content
+ .lines()
+ .filter_map(|line| {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with("# Netscape") {
+ return None;
+ }
+ let normalized = trimmed.strip_prefix("#HttpOnly_").unwrap_or(trimmed);
+ if normalized.starts_with('#') {
+ return None;
+ }
+ let parts: Vec<&str> = normalized.split('\t').collect();
+ if parts.len() < 7 || !netscape_domain_matches(parts[0], domain) {
+ return None;
+ }
+ let name = parts[5].trim();
+ let value = parts[6].trim();
+ if name.is_empty() {
+ return None;
+ }
+ Some(format!("{}={}", name, value))
+ })
+ .collect();
+
+ if pairs.is_empty() {
+ None
+ } else {
+ Some(pairs.join("; "))
+ }
+}
+
+pub fn cookie_header_from_netscape(content: &str) -> Option<String> {
+ let pairs: Vec<String> = content
+ .lines()
+ .filter_map(|line| {
+ let trimmed = line.trim();
+ if trimmed.is_empty() || trimmed.starts_with("# Netscape") {
+ return None;
+ }
+ let normalized = trimmed.strip_prefix("#HttpOnly_").unwrap_or(trimmed);
+ if normalized.starts_with('#') {
+ return None;
+ }
+ let parts: Vec<&str> = normalized.split('\t').collect();
+ if parts.len() < 7 {
+ return None;
+ }
+ let name = parts[5].trim();
+ let value = parts[6].trim();
+ if name.is_empty() {
+ return None;
+ }
+ Some(format!("{}={}", name, value))
+ })
+ .collect();
+
+ if pairs.is_empty() {
+ None
+ } else {
+ Some(pairs.join("; "))
+ }
+}
+
+pub fn cookie_header_for_domains(domains: &[&str]) -> Option<String> {
+ for domain in domains {
+ if let Some(header) = manual_cookie_header(domain) {
+ let trimmed = header.trim();
+ if !trimmed.is_empty() {
+ return Some(trimmed.to_string());
+ }
+ }
+
+ let Some(path) = cookie_path_for(domain) else {
+ continue;
+ };
+ let Ok(content) = std::fs::read_to_string(path) else {
+ continue;
+ };
+ if let Some(header) = cookie_header_from_netscape_for_domain(&content, domain) {
+ return Some(header);
+ }
+ }
+
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn filters_netscape_cookies_by_domain() {
+ let content = "# Netscape HTTP Cookie File\n.example.com\tTRUE\t/\tFALSE\t0\tsid\tbad\n.x.com\tTRUE\t/\tFALSE\t0\tauth_token\tok\ntwitter.com\tFALSE\t/\tFALSE\t0\tct0\tcsrf\n";
+
+ let x_header = cookie_header_from_netscape_for_domain(content, "x.com").unwrap();
+ assert_eq!(x_header, "auth_token=ok");
+
+ let twitter_header =
+ cookie_header_from_netscape_for_domain(content, "twitter.com").unwrap();
+ assert_eq!(twitter_header, "ct0=csrf");
+ }
+
+ #[test]
+ fn does_not_include_unrelated_domains() {
+ let content = ".youtube.com\tTRUE\t/\tFALSE\t0\tSID\tsecret\n";
+ assert!(cookie_header_from_netscape_for_domain(content, "x.com").is_none());
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/mod.rs b/src-tauri/omniget-core/src/platforms/mod.rs
index e5926be6..43ac9ab1 100644
--- a/src-tauri/omniget-core/src/platforms/mod.rs
+++ b/src-tauri/omniget-core/src/platforms/mod.rs
@@ -1,29 +1,34 @@
+pub mod bilibili;
pub mod bluesky;
+pub mod cookie_provider;
pub mod direct_file;
pub mod douyin;
pub mod generic_ytdlp;
pub mod instagram;
-pub mod pinterest;
pub mod p2p;
pub mod p2p_words;
+pub mod pinterest;
pub mod reddit;
-pub mod traits;
pub mod tiktok;
+pub mod traits;
pub mod twitch;
+pub mod twitter;
pub mod vimeo;
pub mod youtube;
+pub use bilibili::BilibiliDownloader;
pub use bluesky::BlueskyDownloader;
pub use direct_file::DirectFileDownloader;
pub use douyin::DouyinDownloader;
pub use generic_ytdlp::GenericYtdlpDownloader;
pub use instagram::InstagramDownloader;
-pub use pinterest::PinterestDownloader;
pub use p2p::P2pDownloader;
+pub use pinterest::PinterestDownloader;
pub use reddit::RedditDownloader;
pub use tiktok::TikTokDownloader;
pub use traits::PlatformDownloader;
pub use twitch::TwitchClipsDownloader;
+pub use twitter::TwitterDownloader;
pub use vimeo::VimeoDownloader;
pub use youtube::YouTubeDownloader;
diff --git a/src-tauri/omniget-core/src/platforms/twitter.rs b/src-tauri/omniget-core/src/platforms/twitter.rs
new file mode 100644
index 00000000..3d7dc02b
--- /dev/null
+++ b/src-tauri/omniget-core/src/platforms/twitter.rs
@@ -0,0 +1,1013 @@
+use crate::models::progress::ProgressUpdate;
+use regex::Regex;
+use std::sync::Arc;
+
+use anyhow::anyhow;
+use async_trait::async_trait;
+use tokio::sync::{mpsc, Mutex};
+
+use crate::core::direct_downloader;
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality};
+use crate::platforms::traits::PlatformDownloader;
+
+const GRAPHQL_URL: &str = "https://api.x.com/graphql/4Siu98E55GquhG52zHdY5w/TweetDetail";
+const TOKEN_URL: &str = "https://api.x.com/1.1/guest/activate.json";
+const BEARER: &str = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
+const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
+
+const TWEET_FEATURES: &str = r#"{"rweb_video_screen_enabled":false,"payments_enabled":false,"rweb_xchat_enabled":false,"profile_label_improvements_pcf_label_in_post_enabled":true,"rweb_tipjar_consumption_enabled":true,"verified_phone_label_enabled":false,"creator_subscriptions_tweet_preview_api_enabled":true,"responsive_web_graphql_timeline_navigation_enabled":true,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"premium_content_api_read_enabled":false,"communities_web_enable_tweet_community_results_fetch":true,"c9s_tweet_anatomy_moderator_badge_enabled":true,"responsive_web_grok_analyze_button_fetch_trends_enabled":false,"responsive_web_grok_analyze_post_followups_enabled":true,"responsive_web_jetfuel_frame":true,"responsive_web_grok_share_attachment_enabled":true,"articles_preview_enabled":true,"responsive_web_edit_tweet_api_enabled":true,"graphql_is_translatable_rweb_tweet_is_translatable_enabled":true,"view_counts_everywhere_api_enabled":true,"longform_notetweets_consumption_enabled":true,"responsive_web_twitter_article_tweet_consumption_enabled":true,"tweet_awards_web_tipping_enabled":false,"responsive_web_grok_show_grok_translated_post":false,"responsive_web_grok_analysis_button_from_backend":true,"creator_subscriptions_quote_tweet_preview_enabled":false,"freedom_of_speech_not_reach_fetch_enabled":true,"standardized_nudges_misinfo":true,"tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled":true,"longform_notetweets_rich_text_read_enabled":true,"longform_notetweets_inline_media_enabled":true,"responsive_web_grok_image_annotation_enabled":true,"responsive_web_grok_imagine_annotation_enabled":true,"responsive_web_grok_community_note_auto_translation_is_enabled":false,"responsive_web_enhance_cards_enabled":false}"#;
+
+const TWEET_FIELD_TOGGLES: &str = r#"{"withArticleRichContentState":true,"withArticlePlainText":false,"withGrokAnalyze":false,"withDisallowedReplyControls":false}"#;
+
+pub struct TwitterDownloader {
+ client: reqwest::Client,
+ guest_token: Arc<Mutex<Option<String>>>,
+}
+
+enum TwitterMedia {
+ Single(TwitterMediaItem),
+ Multiple(Vec<TwitterMediaItem>),
+}
+
+struct TwitterMediaItem {
+ media_type: TwitterMediaType,
+ url: String,
+ extension: String,
+}
+
+enum TwitterMediaType {
+ Video,
+ Photo,
+ AnimatedGif,
+}
+
+impl Default for TwitterDownloader {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl TwitterDownloader {
+ fn auth_cookie_string() -> Option<String> {
+ crate::platforms::cookie_provider::cookie_header_for_domains(&["x.com", "twitter.com"])
+ }
+
+ fn cookie_value(cookie_header: &str, name: &str) -> Option<String> {
+ cookie_header.split(';').find_map(|part| {
+ let (k, v) = part.trim().split_once('=')?;
+ (k.trim() == name).then(|| v.trim().to_string())
+ })
+ }
+
+ fn request_cookie_header(guest_token: &str) -> String {
+ let guest_cookie = format!(
+ "guest_id={}",
+ urlencoding::encode(&format!("v1:{}", guest_token))
+ );
+
+ if let Some(auth) = Self::auth_cookie_string() {
+ format!("{}; {}", guest_cookie, auth)
+ } else {
+ guest_cookie
+ }
+ }
+
+ fn clone_media_array(value: &serde_json::Value) -> Option<Vec<serde_json::Value>> {
+ value.as_array().filter(|items| !items.is_empty()).cloned()
+ }
+
+ fn find_first_array_for_key(
+ value: &serde_json::Value,
+ target_key: &str,
+ ) -> Option<Vec<serde_json::Value>> {
+ match value {
+ serde_json::Value::Object(map) => {
+ if let Some(found) = map
+ .get(target_key)
+ .and_then(Self::clone_media_array)
+ .filter(|items| !items.is_empty())
+ {
+ return Some(found);
+ }
+
+ for child in map.values() {
+ if let Some(found) = Self::find_first_array_for_key(child, target_key) {
+ return Some(found);
+ }
+ }
+ }
+ serde_json::Value::Array(items) => {
+ for child in items {
+ if let Some(found) = Self::find_first_array_for_key(child, target_key) {
+ return Some(found);
+ }
+ }
+ }
+ _ => {}
+ }
+
+ None
+ }
+
+ fn media_arrays_from_tweet_result(
+ tweet_result: &serde_json::Value,
+ ) -> Option<Vec<serde_json::Value>> {
+ let candidate_paths = [
+ "/legacy/extended_entities/media",
+ "/tweet/legacy/extended_entities/media",
+ "/legacy/retweeted_status_result/result/legacy/extended_entities/media",
+ "/legacy/retweeted_status_result/result/tweet/legacy/extended_entities/media",
+ "/tweet/legacy/retweeted_status_result/result/legacy/extended_entities/media",
+ "/tweet/legacy/retweeted_status_result/result/tweet/legacy/extended_entities/media",
+ "/legacy/quoted_status_result/result/legacy/extended_entities/media",
+ "/legacy/quoted_status_result/result/tweet/legacy/extended_entities/media",
+ "/tweet/legacy/quoted_status_result/result/legacy/extended_entities/media",
+ "/tweet/legacy/quoted_status_result/result/tweet/legacy/extended_entities/media",
+ ];
+
+ for path in candidate_paths {
+ if let Some(items) = tweet_result
+ .pointer(path)
+ .and_then(Self::clone_media_array)
+ .filter(|items| !items.is_empty())
+ {
+ return Some(items);
+ }
+ }
+
+ Self::find_first_array_for_key(tweet_result, "media")
+ }
+
+ fn infer_media_type(media_item: &serde_json::Value) -> Option<TwitterMediaType> {
+ match media_item.get("type").and_then(|v| v.as_str()) {
+ Some("photo") => return Some(TwitterMediaType::Photo),
+ Some("video") => return Some(TwitterMediaType::Video),
+ Some("animated_gif") => return Some(TwitterMediaType::AnimatedGif),
+ _ => {}
+ }
+
+ if media_item
+ .pointer("/video_info/variants")
+ .and_then(|v| v.as_array())
+ .is_some()
+ || media_item
+ .pointer("/video/variants")
+ .and_then(|v| v.as_array())
+ .is_some()
+ {
+ return Some(TwitterMediaType::Video);
+ }
+
+ if media_item
+ .get("media_url_https")
+ .and_then(|v| v.as_str())
+ .is_some()
+ || media_item
+ .get("media_url")
+ .and_then(|v| v.as_str())
+ .is_some()
+ || media_item.get("url").and_then(|v| v.as_str()).is_some()
+ {
+ return Some(TwitterMediaType::Photo);
+ }
+
+ None
+ }
+
+ pub fn new() -> Self {
+ let mut builder = crate::core::http_client::apply_global_proxy(reqwest::Client::builder())
+ .user_agent(USER_AGENT)
+ .timeout(std::time::Duration::from_secs(120))
+ .connect_timeout(std::time::Duration::from_secs(15));
+
+ if let Some(jar) = crate::core::cookie_parser::load_extension_cookies_for_domain("x.com") {
+ builder = builder.cookie_provider(jar);
+ }
+
+ let client = builder.build().unwrap_or_default();
+ Self {
+ client,
+ guest_token: Arc::new(Mutex::new(None)),
+ }
+ }
+
+ fn extract_tweet_id(url: &str) -> Option<String> {
+ let parsed = url::Url::parse(url).ok()?;
+ let segments: Vec<&str> = parsed.path().split('/').filter(|s| !s.is_empty()).collect();
+
+ if segments.len() >= 3 && segments[1] == "status" {
+ let id = segments[2];
+ if id.chars().all(|c| c.is_ascii_digit()) {
+ return Some(id.to_string());
+ }
+ }
+
+ None
+ }
+
+ async fn get_guest_token(&self, force: bool) -> anyhow::Result<String> {
+ if !force {
+ let cached = self.guest_token.lock().await;
+ if let Some(ref token) = *cached {
+ return Ok(token.clone());
+ }
+ }
+
+ let response = self
+ .client
+ .post(TOKEN_URL)
+ .header("Authorization", BEARER)
+ .header("x-twitter-client-language", "en")
+ .header("x-twitter-active-user", "yes")
+ .header("Accept-Language", "en")
+ .send()
+ .await?;
+
+ if !response.status().is_success() {
+ return Err(anyhow!(
+ "Falha ao obter guest token: HTTP {}",
+ response.status()
+ ));
+ }
+
+ let json: serde_json::Value = response.json().await?;
+ let token = json
+ .get("guest_token")
+ .and_then(|v| v.as_str())
+ .ok_or_else(|| anyhow!("Guest token ausente na resposta"))?
+ .to_string();
+
+ let mut cached = self.guest_token.lock().await;
+ *cached = Some(token.clone());
+ Ok(token)
+ }
+
+ async fn request_tweet(
+ &self,
+ tweet_id: &str,
+ guest_token: &str,
+ ) -> anyhow::Result<serde_json::Value> {
+ let variables = serde_json::json!({
+ "focalTweetId": tweet_id,
+ "with_rux_injections": false,
+ "rankingMode": "Relevance",
+ "includePromotedContent": true,
+ "withCommunity": true,
+ "withQuickPromoteEligibilityTweetFields": true,
+ "withBirdwatchNotes": true,
+ "withVoice": true
+ });
+
+ let url = format!(
+ "{}?variables={}&features={}&fieldToggles={}",
+ GRAPHQL_URL,
+ urlencoding::encode(&variables.to_string()),
+ urlencoding::encode(TWEET_FEATURES),
+ urlencoding::encode(TWEET_FIELD_TOGGLES),
+ );
+
+ let cookie_val = Self::request_cookie_header(guest_token);
+ let ct0 = Self::cookie_value(&cookie_val, "ct0");
+ let has_auth_token = Self::cookie_value(&cookie_val, "auth_token").is_some();
+
+ let mut request = self
+ .client
+ .get(&url)
+ .header("Authorization", BEARER)
+ .header("x-guest-token", guest_token)
+ .header("x-twitter-client-language", "en")
+ .header("x-twitter-active-user", "yes")
+ .header("Accept-Language", "en")
+ .header("Content-Type", "application/json")
+ .header("Cookie", &cookie_val);
+ if has_auth_token {
+ request = request.header("x-twitter-auth-type", "OAuth2Session");
+ }
+ if let Some(ct0) = ct0 {
+ request = request.header("x-csrf-token", ct0);
+ }
+
+ let response = request.send().await?;
+
+ let status = response.status();
+ tracing::debug!("[twitter] graphql tweet_id={} status={}", tweet_id, status);
+
+ if status == reqwest::StatusCode::FORBIDDEN
+ || status == reqwest::StatusCode::TOO_MANY_REQUESTS
+ {
+ return Err(anyhow!("token_expired"));
+ }
+
+ if status == reqwest::StatusCode::NOT_FOUND {
+ return Err(anyhow!("Post not available"));
+ }
+
+ if !status.is_success() {
+ return Err(anyhow!("Twitter API retornou HTTP {}", status));
+ }
+
+ response.json().await.map_err(Into::into)
+ }
+
+ fn calculate_syndication_token(id: &str) -> String {
+ let num: f64 = id.parse().unwrap_or(0.0);
+ let raw = (num / 1e15) * std::f64::consts::PI;
+ let base36 = Self::f64_to_base36(raw);
+ base36
+ .replace('.', "")
+ .trim_start_matches('0')
+ .trim_end_matches('0')
+ .to_string()
+ }
+
+ fn f64_to_base36(value: f64) -> String {
+ if value == 0.0 {
+ return "0".to_string();
+ }
+
+ let integer_part = value as u64;
+ let fractional_part = value - integer_part as f64;
+
+ let mut int_str = if integer_part == 0 {
+ "0".to_string()
+ } else {
+ let mut n = integer_part;
+ let mut digits = Vec::new();
+ while n > 0 {
+ let rem = (n % 36) as u8;
+ let ch = if rem < 10 {
+ (b'0' + rem) as char
+ } else {
+ (b'a' + rem - 10) as char
+ };
+ digits.push(ch);
+ n /= 36;
+ }
+ digits.reverse();
+ digits.into_iter().collect()
+ };
+
+ if fractional_part > 0.0 {
+ int_str.push('.');
+ let mut frac = fractional_part;
+ for _ in 0..12 {
+ frac *= 36.0;
+ let digit = frac as u8;
+ let ch = if digit < 10 {
+ (b'0' + digit) as char
+ } else {
+ (b'a' + digit - 10) as char
+ };
+ int_str.push(ch);
+ frac -= digit as f64;
+ if frac <= 0.0 {
+ break;
+ }
+ }
+ }
+
+ int_str
+ }
+
+ async fn request_syndication(&self, tweet_id: &str) -> anyhow::Result<serde_json::Value> {
+ let token = Self::calculate_syndication_token(tweet_id);
+
+ let url = format!(
+ "https://cdn.syndication.twimg.com/tweet-result?id={}&token={}",
+ tweet_id, token
+ );
+
+ let mut request = self.client.get(&url);
+ if let Some(cookie) = Self::auth_cookie_string() {
+ request = request.header("Cookie", cookie);
+ }
+
+ let response = request.send().await?;
+ tracing::debug!(
+ "[twitter] syndication tweet_id={} token={} status={}",
+ tweet_id,
+ token,
+ response.status()
+ );
+
+ if !response.status().is_success() {
+ return Err(anyhow!(
+ "Syndication API retornou HTTP {}",
+ response.status()
+ ));
+ }
+
+ response.json().await.map_err(Into::into)
+ }
+
+ fn extract_graphql_media(
+ json: &serde_json::Value,
+ tweet_id: &str,
+ ) -> anyhow::Result<Vec<serde_json::Value>> {
+ let instructions = json
+ .pointer("/data/threaded_conversation_with_injections_v2/instructions")
+ .and_then(|v| v.as_array())
+ .ok_or_else(|| anyhow!("Post not available"))?;
+
+ let add_insn = instructions
+ .iter()
+ .find(|i| i.get("type").and_then(|v| v.as_str()) == Some("TimelineAddEntries"))
+ .ok_or_else(|| anyhow!("Post not available"))?;
+
+ let entry_id = format!("tweet-{}", tweet_id);
+ let entries = add_insn
+ .get("entries")
+ .and_then(|v| v.as_array())
+ .ok_or_else(|| anyhow!("Post not available"))?;
+
+ let tweet_result = entries
+ .iter()
+ .find(|e| e.get("entryId").and_then(|v| v.as_str()) == Some(&entry_id))
+ .and_then(|e| e.pointer("/content/itemContent/tweet_results/result"))
+ .ok_or_else(|| anyhow!("Post not available"))?;
+
+ let typename = tweet_result
+ .get("__typename")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ tracing::debug!(
+ "[twitter] graphql media typename={} tweet_id={}",
+ typename,
+ tweet_id
+ );
+
+ match typename {
+ "TweetUnavailable" | "TweetTombstone" => {
+ let reason = tweet_result
+ .pointer("/result/reason")
+ .or_else(|| tweet_result.get("reason"))
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if reason == "Protected" {
+ return Err(anyhow!("Post privado"));
+ }
+
+ let tombstone_text = tweet_result
+ .pointer("/tombstone/text/text")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ tracing::warn!(
+ "[twitter] graphql tombstone tweet_id={} reason='{}' tombstone_text='{}'",
+ tweet_id,
+ reason,
+ tombstone_text
+ );
+
+ if reason == "NsfwLoggedOut" || tombstone_text.starts_with("Age-restricted") {
+ return Err(anyhow!("Age-restricted content"));
+ }
+
+ Err(anyhow!("Post not available"))
+ }
+ "Tweet" | "TweetWithVisibilityResults" => {
+ let media = Self::media_arrays_from_tweet_result(tweet_result)
+ .ok_or_else(|| anyhow!("No media found in tweet"))?;
+ tracing::debug!(
+ "[twitter] graphql extracted {} media entries for tweet_id={}",
+ media.len(),
+ tweet_id
+ );
+ Ok(media)
+ }
+ _ => Err(anyhow!("Post not available")),
+ }
+ }
+
+ fn extract_syndication_media(
+ json: &serde_json::Value,
+ ) -> anyhow::Result<Vec<serde_json::Value>> {
+ let typename = json
+ .get("__typename")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+ if typename == "TweetTombstone" || typename == "TweetUnavailable" {
+ tracing::warn!("[twitter] syndication tombstone typename={}", typename);
+ return Err(anyhow!("Post not available"));
+ }
+
+ let media = json
+ .get("mediaDetails")
+ .and_then(Self::clone_media_array)
+ .or_else(|| json.get("photos").and_then(Self::clone_media_array))
+ .or_else(|| Self::find_first_array_for_key(json, "mediaDetails"))
+ .or_else(|| Self::find_first_array_for_key(json, "photos"))
+ .ok_or_else(|| anyhow!("No media found in tweet"))?;
+
+ tracing::debug!(
+ "[twitter] syndication extracted {} media entries",
+ media.len()
+ );
+ Ok(media)
+ }
+
+ fn best_video_url(media_item: &serde_json::Value) -> Option<String> {
+ let variants = media_item
+ .pointer("/video_info/variants")
+ .or_else(|| media_item.pointer("/video/variants"))
+ .and_then(|v| v.as_array())?;
+
+ let best_mp4 = variants
+ .iter()
+ .filter(|v| v.get("content_type").and_then(|c| c.as_str()) == Some("video/mp4"))
+ .max_by_key(|v| v.get("bitrate").and_then(|b| b.as_u64()).unwrap_or(0))
+ .and_then(|v| v.get("url").and_then(|u| u.as_str()))
+ .map(|s| s.to_string());
+
+ if best_mp4.is_some() {
+ return best_mp4;
+ }
+
+ variants
+ .iter()
+ .filter_map(|v| v.get("url").and_then(|u| u.as_str()))
+ .find(|url| url.contains(".m3u8") || url.contains("mpegurl"))
+ .or_else(|| {
+ variants
+ .iter()
+ .filter_map(|v| v.get("url").and_then(|u| u.as_str()))
+ .next()
+ })
+ .map(|s| s.to_string())
+ }
+
+ fn best_photo_url(media_item: &serde_json::Value) -> Option<(String, String)> {
+ let base_url = media_item
+ .get("media_url_https")
+ .or_else(|| media_item.get("media_url"))
+ .or_else(|| media_item.get("url"))
+ .and_then(|v| v.as_str())?;
+ Self::best_photo_url_from_str(base_url)
+ }
+
+ fn best_photo_url_from_str(base_url: &str) -> Option<(String, String)> {
+ let cleaned = Self::decode_html_url(base_url);
+ let extension = url::Url::parse(&cleaned)
+ .ok()
+ .and_then(|u| {
+ u.path_segments()
+ .and_then(|segments| segments.last().map(|s| s.to_string()))
+ })
+ .and_then(|filename| {
+ filename
+ .rsplit('.')
+ .next()
+ .and_then(|ext| ext.split('?').next())
+ .map(|ext| ext.to_string())
+ })
+ .filter(|ext| !ext.is_empty())
+ .unwrap_or_else(|| "jpg".to_string());
+
+ let url = if let Ok(mut parsed) = url::Url::parse(&cleaned) {
+ let existing: Vec<(String, String)> = parsed
+ .query_pairs()
+ .filter(|(key, _)| key != "name")
+ .map(|(key, value)| (key.into_owned(), value.into_owned()))
+ .collect();
+ parsed.set_query(None);
+ {
+ let mut qp = parsed.query_pairs_mut();
+ for (key, value) in existing {
+ qp.append_pair(&key, &value);
+ }
+ qp.append_pair("name", "orig");
+ }
+ parsed.to_string()
+ } else if cleaned.contains('?') {
+ format!("{}&name=orig", cleaned)
+ } else {
+ format!("{}?name=orig", cleaned)
+ };
+
+ Some((url, extension))
+ }
+
+ fn decode_html_url(raw: &str) -> String {
+ raw.replace("\\u0026", "&")
+ .replace("&amp;", "&")
+ .replace("&#38;", "&")
+ }
+
+ fn extract_html_photo_items(html: &str) -> Vec<TwitterMediaItem> {
+ let re = match Regex::new(r#"https://pbs\.twimg\.com/media/[^\s"'<>\\]+"#) {
+ Ok(re) => re,
+ Err(_) => return Vec::new(),
+ };
+ let mut seen = std::collections::HashSet::new();
+ let mut items = Vec::new();
+ for m in re.find_iter(html) {
+ let raw = m.as_str().trim_end_matches([',', ';', ')', ']']);
+ if let Some((url, extension)) = Self::best_photo_url_from_str(raw) {
+ if seen.insert(url.clone()) {
+ items.push(TwitterMediaItem {
+ media_type: TwitterMediaType::Photo,
+ url,
+ extension,
+ });
+ }
+ }
+ }
+ items
+ }
+
+ fn parse_media_items(media: &[serde_json::Value]) -> anyhow::Result<TwitterMedia> {
+ let items: Vec<TwitterMediaItem> = media
+ .iter()
+ .filter_map(|m| match Self::infer_media_type(m)? {
+ TwitterMediaType::Photo => {
+ let (url, ext) = Self::best_photo_url(m)?;
+ Some(TwitterMediaItem {
+ media_type: TwitterMediaType::Photo,
+ url,
+ extension: ext,
+ })
+ }
+ TwitterMediaType::Video => {
+ let url = Self::best_video_url(m)?;
+ let extension = if url.contains(".m3u8") || url.contains("mpegurl") {
+ "ytdlp"
+ } else {
+ "mp4"
+ };
+ Some(TwitterMediaItem {
+ media_type: TwitterMediaType::Video,
+ url,
+ extension: extension.to_string(),
+ })
+ }
+ TwitterMediaType::AnimatedGif => {
+ let url = Self::best_video_url(m)?;
+ Some(TwitterMediaItem {
+ media_type: TwitterMediaType::AnimatedGif,
+ url,
+ extension: "mp4".to_string(),
+ })
+ }
+ })
+ .collect();
+
+ if items.is_empty() {
+ return Err(anyhow!("No media found in tweet"));
+ }
+
+ if items.len() == 1 {
+ Ok(TwitterMedia::Single(items.into_iter().next().unwrap()))
+ } else {
+ Ok(TwitterMedia::Multiple(items))
+ }
+ }
+
+ fn media_type_for_item(item: &TwitterMediaItem) -> MediaType {
+ match item.media_type {
+ TwitterMediaType::Video => MediaType::Video,
+ TwitterMediaType::Photo => MediaType::Photo,
+ TwitterMediaType::AnimatedGif => MediaType::Gif,
+ }
+ }
+
+ fn media_info_from_twitter_media(
+ filename_base: String,
+ twitter_media: TwitterMedia,
+ ) -> MediaInfo {
+ match twitter_media {
+ TwitterMedia::Single(item) => {
+ let media_type = Self::media_type_for_item(&item);
+ MediaInfo {
+ title: filename_base,
+ author: String::new(),
+ platform: "twitter".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: vec![VideoQuality {
+ label: "original".to_string(),
+ width: 0,
+ height: 0,
+ url: item.url,
+ format: item.extension,
+ }],
+ media_type,
+ file_size_bytes: None,
+ }
+ }
+ TwitterMedia::Multiple(items) => {
+ let qualities: Vec<VideoQuality> = items
+ .iter()
+ .enumerate()
+ .map(|(i, item)| VideoQuality {
+ label: format!("media_{}", i + 1),
+ width: 0,
+ height: 0,
+ url: item.url.clone(),
+ format: item.extension.clone(),
+ })
+ .collect();
+
+ MediaInfo {
+ title: filename_base,
+ author: String::new(),
+ platform: "twitter".to_string(),
+ duration_seconds: None,
+ thumbnail_url: None,
+ available_qualities: qualities,
+ media_type: MediaType::Carousel,
+ file_size_bytes: None,
+ }
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl PlatformDownloader for TwitterDownloader {
+ fn name(&self) -> &str {
+ "twitter"
+ }
+
+ fn can_handle(&self, url: &str) -> bool {
+ if let Ok(parsed) = url::Url::parse(url) {
+ if let Some(host) = parsed.host_str() {
+ let host = host.to_lowercase();
+ return host == "twitter.com"
+ || host.ends_with(".twitter.com")
+ || host == "x.com"
+ || host.ends_with(".x.com")
+ || host == "vxtwitter.com"
+ || host.ends_with(".vxtwitter.com")
+ || host == "fixvx.com"
+ || host.ends_with(".fixvx.com");
+ }
+ }
+ false
+ }
+
+ async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ match self.native_get_media_info(url).await {
+ Ok(info) => Ok(info),
+ Err(native_err) => {
+ tracing::warn!(
+ "[twitter] native failed: {}, trying yt-dlp fallback",
+ native_err
+ );
+ match self.fallback_ytdlp(url).await {
+ Ok(info) => Ok(info),
+ Err(fallback_err) => {
+ tracing::warn!(
+ "[twitter] yt-dlp fallback failed after native error: {}",
+ fallback_err
+ );
+ Err(anyhow!(
+ "Twitter extraction failed. native='{}'; ytdlp='{}'",
+ native_err,
+ fallback_err
+ ))
+ }
+ }
+ }
+ }
+ }
+
+ async fn download(
+ &self,
+ info: &MediaInfo,
+ opts: &DownloadOptions,
+ progress: mpsc::Sender<ProgressUpdate>,
+ ) -> anyhow::Result<DownloadResult> {
+ if let Some(quality) = info.available_qualities.first() {
+ if quality.format == "ytdlp" {
+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
+ let mut extra_flags = Vec::new();
+ if let Some(cookie) = Self::auth_cookie_string() {
+ extra_flags.push("--add-headers".to_string());
+ extra_flags.push(format!("Cookie:{}", cookie));
+ }
+ return crate::core::ytdlp::download_video(
+ &ytdlp_path,
+ &quality.url,
+ &opts.output_dir,
+ None,
+ progress,
+ opts.download_mode.as_deref(),
+ opts.format_id.as_deref(),
+ opts.filename_template.as_deref(),
+ opts.referer.as_deref().or(Some("https://x.com/")),
+ opts.cancel_token.clone(),
+ None,
+ opts.concurrent_fragments,
+ false,
+ &extra_flags,
+ opts.audio_format.as_deref(),
+ )
+ .await;
+ }
+ }
+
+ let count = info.available_qualities.len();
+
+ if count == 0 {
+ anyhow::bail!(
+ "No downloadable media found for this tweet (it may be text-only, protected, or deleted)"
+ );
+ }
+
+ if count == 1 {
+ let quality = info.available_qualities.first().unwrap();
+ let filename = format!(
+ "{}.{}",
+ sanitize_filename::sanitize(&info.title),
+ quality.format
+ );
+ let output = opts.output_dir.join(&filename);
+
+ let bytes = direct_downloader::download_direct(
+ &self.client,
+ &quality.url,
+ &output,
+ progress,
+ Some(&opts.cancel_token),
+ )
+ .await?;
+
+ return Ok(DownloadResult {
+ file_path: output,
+ file_size_bytes: bytes,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ });
+ }
+
+ let mut total_bytes = 0u64;
+ let mut last_path = opts.output_dir.clone();
+
+ for (i, quality) in info.available_qualities.iter().enumerate() {
+ let filename = format!(
+ "{}_{}.{}",
+ sanitize_filename::sanitize(&info.title),
+ i + 1,
+ quality.format
+ );
+ let output = opts.output_dir.join(&filename);
+
+ let bytes = direct_downloader::download_direct(
+ &self.client,
+ &quality.url,
+ &output,
+ progress.clone(),
+ Some(&opts.cancel_token),
+ )
+ .await?;
+
+ total_bytes += bytes;
+ last_path = output;
+
+ let percent = ((i + 1) as f64 / count as f64) * 100.0;
+ let _ = progress.send(ProgressUpdate::percent(percent)).await;
+ }
+
+ Ok(DownloadResult {
+ file_path: last_path,
+ file_size_bytes: total_bytes,
+ duration_seconds: 0.0,
+ torrent_id: None,
+ })
+ }
+}
+
+impl TwitterDownloader {
+ async fn fallback_ytdlp(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let ytdlp_path = crate::core::ytdlp::ensure_ytdlp().await?;
+ let mut extra_flags = vec![
+ "--referer".to_string(),
+ "https://x.com/".to_string(),
+ "--add-headers".to_string(),
+ "Referer:https://x.com/".to_string(),
+ ];
+ if let Some(cookie) = Self::auth_cookie_string() {
+ extra_flags.push("--add-headers".to_string());
+ extra_flags.push(format!("Cookie:{}", cookie));
+ }
+ let json = crate::core::ytdlp::get_video_info(&ytdlp_path, url, &extra_flags).await?;
+ crate::platforms::generic_ytdlp::GenericYtdlpDownloader::parse_video_info(&json)
+ }
+
+ async fn native_get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
+ let tweet_id =
+ Self::extract_tweet_id(url).ok_or_else(|| anyhow!("Could not extract tweet ID"))?;
+ tracing::debug!(
+ "[twitter] native_get_media_info tweet_id={} url={}",
+ tweet_id,
+ url
+ );
+
+ let filename_base = format!("twitter_{}", tweet_id);
+
+ let media_items = match self.try_graphql(&tweet_id).await {
+ Ok(items) => items,
+ Err(graphql_err) => {
+ tracing::warn!(
+ "[twitter] graphql lookup failed for tweet_id={}: {}",
+ tweet_id,
+ graphql_err
+ );
+ match self.request_syndication(&tweet_id).await {
+ Ok(syndication) => match Self::extract_syndication_media(&syndication) {
+ Ok(items) => items,
+ Err(syndication_extract_err) => {
+ tracing::warn!(
+ "[twitter] syndication media extraction failed for tweet_id={}: {}",
+ tweet_id,
+ syndication_extract_err
+ );
+ match self.request_html_media(url).await {
+ Ok(items) => items,
+ Err(html_err) => {
+ return Err(anyhow!(
+ "Post not available; graphql='{}'; syndication_extract='{}'; html='{}'",
+ graphql_err,
+ syndication_extract_err,
+ html_err
+ ));
+ }
+ }
+ }
+ },
+ Err(syndication_err) => {
+ tracing::warn!(
+ "[twitter] syndication lookup failed for tweet_id={}: {}",
+ tweet_id,
+ syndication_err
+ );
+ match self.request_html_media(url).await {
+ Ok(items) => items,
+ Err(html_err) => {
+ return Err(anyhow!(
+ "Post not available; graphql='{}'; syndication='{}'; html='{}'",
+ graphql_err,
+ syndication_err,
+ html_err
+ ));
+ }
+ }
+ }
+ }
+ }
+ };
+
+ let twitter_media = Self::parse_media_items(&media_items)?;
+
+ Ok(Self::media_info_from_twitter_media(
+ filename_base,
+ twitter_media,
+ ))
+ }
+
+ async fn request_html_media(&self, url: &str) -> anyhow::Result<Vec<serde_json::Value>> {
+ let mut request = self
+ .client
+ .get(url)
+ .header("User-Agent", USER_AGENT)
+ .header("Accept-Language", "en")
+ .header("Referer", "https://x.com/");
+ if let Some(cookie) = Self::auth_cookie_string() {
+ request = request.header("Cookie", cookie);
+ }
+ let response = request.send().await?;
+ if !response.status().is_success() {
+ return Err(anyhow!("HTML request returned HTTP {}", response.status()));
+ }
+ let html = response.text().await?;
+ let items = Self::extract_html_photo_items(&html);
+ if items.is_empty() {
+ return Err(anyhow!("No photo URLs found in HTML"));
+ }
+ tracing::debug!("[twitter] html extracted {} photo entries", items.len());
+ Ok(items
+ .into_iter()
+ .map(|item| {
+ serde_json::json!({
+ "type": "photo",
+ "media_url_https": item.url,
+ })
+ })
+ .collect())
+ }
+
+ async fn try_graphql(&self, tweet_id: &str) -> anyhow::Result<Vec<serde_json::Value>> {
+ let token = self.get_guest_token(false).await?;
+
+ match self.request_tweet(tweet_id, &token).await {
+ Ok(json) => Self::extract_graphql_media(&json, tweet_id),
+ Err(e) if e.to_string() == "token_expired" => {
+ let new_token = self.get_guest_token(true).await?;
+ let json = self.request_tweet(tweet_id, &new_token).await?;
+ Self::extract_graphql_media(&json, tweet_id)
+ }
+ Err(e) => Err(e),
+ }
+ }
+}
diff --git a/src-tauri/omniget-core/src/platforms/youtube.rs b/src-tauri/omniget-core/src/platforms/youtube.rs
index 1eae88a1..f48d75dc 100644
--- a/src-tauri/omniget-core/src/platforms/youtube.rs
+++ b/src-tauri/omniget-core/src/platforms/youtube.rs
@@ -268,12 +268,9 @@ impl PlatformDownloader for YouTubeDownloader {
}
async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- let ytdlp_path = ytdlp::ensure_ytdlp().await.map_err(|e| {
- anyhow!(
- "YouTube requires yt-dlp. Failed to get yt-dlp: {}",
- e
- )
- })?;
+ let ytdlp_path = ytdlp::ensure_ytdlp()
+ .await
+ .map_err(|e| anyhow!("YouTube requires yt-dlp. Failed to get yt-dlp: {}", e))?;
Self::fetch_with_ytdlp(url, &ytdlp_path).await
}
@@ -319,6 +316,12 @@ impl PlatformDownloader for YouTubeDownloader {
};
let video_url = &selected.url;
+ let extra_flags: Vec<String> = opts
+ .custom_ytdlp_args
+ .as_deref()
+ .map(|args| args.to_vec())
+ .unwrap_or_default();
+
ytdlp::download_video(
&ytdlp_path,
video_url,
@@ -333,7 +336,7 @@ impl PlatformDownloader for YouTubeDownloader {
None,
opts.concurrent_fragments,
opts.download_subtitles,
- &[],
+ &extra_flags,
opts.audio_format.as_deref(),
)
.await
@@ -387,6 +390,12 @@ impl YouTubeDownloader {
}
});
+ let extra_flags: Vec<String> = opts
+ .custom_ytdlp_args
+ .as_deref()
+ .map(|args| args.to_vec())
+ .unwrap_or_default();
+
match ytdlp::download_video(
ytdlp_path,
&entry.url,
@@ -401,7 +410,7 @@ impl YouTubeDownloader {
None,
opts.concurrent_fragments,
opts.download_subtitles,
- &[],
+ &extra_flags,
opts.audio_format.as_deref(),
)
.await
@@ -421,8 +430,9 @@ impl YouTubeDownloader {
}
if success_count == 0 {
- return Err(last_err
- .unwrap_or_else(|| anyhow!("Playlist download finished without any files")));
+ return Err(
+ last_err.unwrap_or_else(|| anyhow!("Playlist download finished without any files"))
+ );
}
if success_count > 1 {
diff --git a/src-tauri/src/commands/bilibili_auth.rs b/src-tauri/src/commands/bilibili_auth.rs
index ff706533..266686c6 100644
--- a/src-tauri/src/commands/bilibili_auth.rs
+++ b/src-tauri/src/commands/bilibili_auth.rs
@@ -1,14 +1,14 @@
use serde::{Deserialize, Serialize};
-use crate::platforms::bilibili::api::ApiClient;
-use crate::platforms::bilibili::auth::{self, qr, sms};
-use crate::platforms::bilibili::parser;
-use crate::platforms::bilibili::preview;
-use crate::platforms::bilibili::url_kind::{self, UrlKind};
+use omniget_core::platforms::bilibili::api::ApiClient;
+use omniget_core::platforms::bilibili::auth::{self, qr, sms};
+use omniget_core::platforms::bilibili::parser;
+use omniget_core::platforms::bilibili::preview;
+use omniget_core::platforms::bilibili::url_kind::{self, UrlKind};
fn resolve_account_slug(slug: Option<String>) -> Option<String> {
slug.filter(|s| !s.is_empty())
- .or_else(crate::platforms::bilibili::active_account_slug)
+ .or_else(omniget_core::platforms::bilibili::active_account_slug)
}
fn build_anonymous_client(user_agent: Option<String>) -> Result<ApiClient, String> {
@@ -16,7 +16,7 @@ fn build_anonymous_client(user_agent: Option<String>) -> Result<ApiClient, Strin
if let Some(ua) = user_agent.filter(|s| !s.is_empty()) {
client = client.with_user_agent(ua);
}
- let _ = crate::platforms::bilibili::cookie::ensure_fresh();
+ let _ = omniget_core::platforms::bilibili::cookie::ensure_fresh();
client = client.with_anonymous_cookies();
Ok(client)
}
@@ -90,7 +90,7 @@ pub async fn bilibili_webview_login(
#[tauri::command]
pub async fn bilibili_qr_generate(user_agent: Option<String>) -> Result<qr::QrSession, String> {
- let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;
+ let _ = omniget_core::platforms::bilibili::cookie::ensure_fresh().await;
let client = build_anonymous_client(user_agent)?;
qr::generate(&client)
.await
@@ -183,7 +183,7 @@ pub async fn bilibili_preview_info(
url: String,
slug: Option<String>,
) -> Result<BilibiliPreviewSummary, String> {
- let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;
+ let _ = omniget_core::platforms::bilibili::cookie::ensure_fresh().await;
let mut client = ApiClient::new().map_err(|e| e.i18n_key().to_string())?;
client = match resolve_account_slug(slug) {
Some(s) => client.with_account(s),
@@ -260,7 +260,7 @@ pub struct BilibiliImportResult {
}
async fn run_import(slug: String, kind: UrlKind) -> Result<BilibiliImportResult, String> {
- let _ = crate::platforms::bilibili::cookie::ensure_fresh().await;
+ let _ = omniget_core::platforms::bilibili::cookie::ensure_fresh().await;
let client = ApiClient::new()
.map_err(|e| e.i18n_key().to_string())?
.with_account(&slug);
@@ -275,10 +275,12 @@ async fn run_import(slug: String, kind: UrlKind) -> Result<BilibiliImportResult,
};
let parsed = match kind_ref {
UrlKind::WatchLater => {
- crate::platforms::bilibili::parser::watch_later::parse(&client, current_page).await
+ omniget_core::platforms::bilibili::parser::watch_later::parse(&client, current_page)
+ .await
}
UrlKind::History => {
- crate::platforms::bilibili::parser::history::parse(&client, current_page).await
+ omniget_core::platforms::bilibili::parser::history::parse(&client, current_page)
+ .await
}
_ => return Err("errors.bilibili.content_unavailable".to_string()),
}
@@ -313,16 +315,18 @@ async fn run_import(slug: String, kind: UrlKind) -> Result<BilibiliImportResult,
}
#[tauri::command]
-pub async fn bilibili_import_watch_later(slug: Option<String>) -> Result<BilibiliImportResult, String> {
- let slug = resolve_account_slug(slug)
- .ok_or_else(|| "errors.bilibili.not_logged_in".to_string())?;
+pub async fn bilibili_import_watch_later(
+ slug: Option<String>,
+) -> Result<BilibiliImportResult, String> {
+ let slug =
+ resolve_account_slug(slug).ok_or_else(|| "errors.bilibili.not_logged_in".to_string())?;
run_import(slug, UrlKind::WatchLater).await
}
#[tauri::command]
pub async fn bilibili_import_history(slug: Option<String>) -> Result<BilibiliImportResult, String> {
- let slug = resolve_account_slug(slug)
- .ok_or_else(|| "errors.bilibili.not_logged_in".to_string())?;
+ let slug =
+ resolve_account_slug(slug).ok_or_else(|| "errors.bilibili.not_logged_in".to_string())?;
run_import(slug, UrlKind::History).await
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index f7aa0f61..c45d15b5 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -25,6 +25,171 @@ pub mod plugin_loader;
pub mod storage;
pub mod tray;
+struct DesktopCookieProvider;
+
+impl omniget_core::platforms::cookie_provider::CookieProvider for DesktopCookieProvider {
+ fn cookie_path_for(&self, domain: &str) -> Option<std::path::PathBuf> {
+ let root = crate::cookies::root_domain_of(domain);
+ if root.is_empty() {
+ return None;
+ }
+
+ let slug = omniget_core::core::log_hook::current_cookie_slug();
+ let path = crate::cookies::account_path_for_consumer(&root, slug.as_deref())
+ .or_else(|| crate::cookies::account_path_for_consumer(&root, None))?;
+ crate::cookies::touch_last_used(&root, slug.as_deref().unwrap_or("_default"));
+ Some(path)
+ }
+
+ fn cookie_path_for_account(&self, domain: &str, slug: &str) -> Option<std::path::PathBuf> {
+ let root = crate::cookies::root_domain_of(domain);
+ if root.is_empty() {
+ return None;
+ }
+ let path = crate::cookies::account_path_for_consumer(&root, Some(slug))?;
+ crate::cookies::touch_last_used(&root, slug);
+ Some(path)
+ }
+
+ fn manual_cookie_header(&self, domain: &str) -> Option<String> {
+ let root = crate::cookies::root_domain_of(domain);
+ if root != "x.com" && root != "twitter.com" {
+ return None;
+ }
+
+ let raw = storage::config::load_settings_standalone()
+ .advanced
+ .twitter_manual_cookie;
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+
+ let parsed = core::cookie_parser::parse_cookie_input(trimmed, "");
+ if !parsed.cookie_string.trim().is_empty() {
+ Some(parsed.cookie_string)
+ } else {
+ Some(trimmed.to_string())
+ }
+ }
+}
+
+struct DesktopBilibiliRuntimeProvider;
+
+impl omniget_core::platforms::bilibili::BilibiliRuntimeProvider for DesktopBilibiliRuntimeProvider {
+ fn active_account_slug(&self) -> Option<String> {
+ let registry = crate::cookies::load_registry();
+ let bucket = registry.buckets.get("bilibili.com")?;
+
+ if let Some(selected) = omniget_core::core::log_hook::current_cookie_slug() {
+ if bucket
+ .accounts
+ .iter()
+ .any(|a| a.slug == selected && a.slug != "_anonymous" && a.cookie_count > 0)
+ {
+ return Some(selected);
+ }
+ }
+
+ let native = bucket
+ .accounts
+ .iter()
+ .filter(|a| a.slug != "_anonymous" && a.slug != "_default" && a.cookie_count > 0)
+ .max_by_key(|a| a.last_used_at_ms.unwrap_or(a.captured_at_ms))
+ .map(|a| a.slug.clone());
+ if native.is_some() {
+ return native;
+ }
+
+ bucket
+ .accounts
+ .iter()
+ .filter(|a| a.slug == "_default" && a.cookie_count > 0)
+ .find(|a| desktop_bilibili_slug_has_session_cookie(&a.slug))
+ .map(|a| a.slug.clone())
+ }
+
+ fn settings(&self) -> omniget_core::models::settings::AppSettings {
+ storage::config::load_settings_standalone()
+ }
+
+ fn persist_account(
+ &self,
+ cookies: &[omniget_core::platforms::bilibili::BilibiliAuthCookie],
+ uname: &str,
+ source_label: &str,
+ ) -> Result<String, String> {
+ let slug = omniget_core::platforms::bilibili::auth::slug_from_uname(uname);
+ let entries: Vec<crate::extension_storage::ExtensionCookie> = cookies
+ .iter()
+ .map(|cookie| crate::extension_storage::ExtensionCookie {
+ domain: cookie.domain.clone(),
+ http_only: cookie.http_only,
+ path: cookie.path.clone(),
+ secure: cookie.secure,
+ expires: cookie.expires,
+ name: cookie.name.clone(),
+ value: cookie.value.clone(),
+ host_only: cookie.host_only,
+ same_site: cookie.same_site.clone(),
+ })
+ .collect();
+
+ crate::cookies::storage::write_account_file("bilibili.com", &slug, &entries)
+ .map_err(|e| e.to_string())?;
+
+ let mut registry = crate::cookies::storage::load_registry();
+ let now_ms = crate::cookies::storage::current_unix_ms();
+ let bucket = registry
+ .buckets
+ .entry("bilibili.com".to_string())
+ .or_insert_with(|| crate::cookies::storage::BucketEntry {
+ platform_kind: "bilibili".to_string(),
+ accounts: Vec::new(),
+ });
+ bucket.platform_kind = "bilibili".to_string();
+
+ let alias = format!("{} · {}", uname, source_label);
+ if let Some(existing) = bucket.accounts.iter_mut().find(|a| a.slug == slug) {
+ existing.captured_at_ms = now_ms;
+ existing.cookie_count = entries.len();
+ existing.source_label = Some(source_label.to_string());
+ existing.alias = alias;
+ } else {
+ bucket.accounts.push(crate::cookies::storage::AccountEntry {
+ slug: slug.clone(),
+ alias,
+ source_url: Some("https://www.bilibili.com".to_string()),
+ source_label: Some(source_label.to_string()),
+ captured_at_ms: now_ms,
+ cookie_count: entries.len(),
+ last_used_at_ms: Some(now_ms),
+ });
+ }
+
+ crate::cookies::storage::save_registry(&registry).map_err(|e| e.to_string())?;
+ Ok(slug)
+ }
+}
+
+fn desktop_bilibili_slug_has_session_cookie(slug: &str) -> bool {
+ let path = match crate::cookies::account_path_for_consumer("bilibili.com", Some(slug)) {
+ Some(p) => p,
+ None => return false,
+ };
+ let content = match std::fs::read_to_string(&path) {
+ Ok(c) => c,
+ Err(_) => return false,
+ };
+ content.lines().any(|line| {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ return false;
+ }
+ line.split('\t').nth(5) == Some("SESSDATA")
+ })
+}
+
pub struct AppState {
pub active_downloads: Arc<tokio::sync::Mutex<HashMap<u64, CancellationToken>>>,
pub active_generic_downloads:
@@ -45,13 +210,15 @@ pub fn run() {
registry.register(Arc::new(omniget_core::platforms::InstagramDownloader::new()));
registry.register(Arc::new(omniget_core::platforms::PinterestDownloader::new()));
registry.register(Arc::new(omniget_core::platforms::TikTokDownloader::new()));
- registry.register(Arc::new(platforms::twitter::TwitterDownloader::new()));
- registry.register(Arc::new(omniget_core::platforms::TwitchClipsDownloader::new()));
+ registry.register(Arc::new(omniget_core::platforms::TwitterDownloader::new()));
+ registry.register(Arc::new(
+ omniget_core::platforms::TwitchClipsDownloader::new(),
+ ));
registry.register(Arc::new(omniget_core::platforms::BlueskyDownloader::new()));
registry.register(Arc::new(omniget_core::platforms::RedditDownloader::new()));
registry.register(Arc::new(omniget_core::platforms::YouTubeDownloader::new()));
registry.register(Arc::new(omniget_core::platforms::VimeoDownloader::new()));
- registry.register(Arc::new(platforms::bilibili::BilibiliDownloader::new()));
+ registry.register(Arc::new(omniget_core::platforms::BilibiliDownloader::new()));
registry.register(Arc::new(omniget_core::platforms::DouyinDownloader::new()));
let torrent_session: Arc<tokio::sync::Mutex<Option<Arc<librqbit::Session>>>> =
Arc::new(tokio::sync::Mutex::new(None));
@@ -60,7 +227,9 @@ pub fn run() {
)));
registry.register(Arc::new(omniget_core::platforms::P2pDownloader::new()));
registry.register(Arc::new(platforms::gallerydl::GalleryDlDownloader::new()));
- registry.register(Arc::new(omniget_core::platforms::DirectFileDownloader::new()));
+ registry.register(Arc::new(
+ omniget_core::platforms::DirectFileDownloader::new(),
+ ));
registry.register(Arc::new(
platforms::generic_ytdlp::GenericYtdlpDownloader::new(),
));
@@ -137,11 +306,26 @@ pub fn run() {
},
));
}
+ {
+ let handle = app.handle().clone();
+ omniget_core::platforms::bilibili::notify::set_emitter(Box::new(
+ move |event: &str, payload: serde_json::Value| {
+ use tauri::Emitter;
+ let _ = handle.emit(event, payload);
+ },
+ ));
+ }
let settings = storage::config::load_settings(app.handle());
core::http_client::init_proxy(settings.proxy.clone());
core::http_fetcher::set_global_max_concurrent_segments(
settings.advanced.max_concurrent_segments as usize,
);
+ omniget_core::platforms::cookie_provider::set_cookie_provider(Arc::new(
+ DesktopCookieProvider,
+ ));
+ omniget_core::platforms::bilibili::set_runtime_provider(Arc::new(
+ DesktopBilibiliRuntimeProvider,
+ ));
core::ytdlp::set_per_domain_cookie_fn(|url| {
let parsed = url::Url::parse(url).ok()?;
let host = parsed.host_str()?;
@@ -201,7 +385,9 @@ pub fn run() {
}
});
core::ytdlp::set_keep_vtt_fn(|| {
- storage::config::load_settings_standalone().download.keep_vtt
+ storage::config::load_settings_standalone()
+ .download
+ .keep_vtt
});
core::ytdlp::set_translate_metadata_fn(|| {
let s = storage::config::load_settings_standalone();
diff --git a/src-tauri/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rs
index 6392b2e3..764ace1f 100644
--- a/src-tauri/src/platforms/mod.rs
+++ b/src-tauri/src/platforms/mod.rs
@@ -1,16 +1,17 @@
+pub use crate::platforms::magnet::MagnetDownloader;
pub use omniget_core::platforms::traits;
-pub use omniget_core::platforms::Platform;
pub use omniget_core::platforms::BlueskyDownloader;
pub use omniget_core::platforms::DirectFileDownloader;
pub use omniget_core::platforms::DouyinDownloader;
pub use omniget_core::platforms::GenericYtdlpDownloader;
pub use omniget_core::platforms::InstagramDownloader;
-pub use crate::platforms::magnet::MagnetDownloader;
-pub use omniget_core::platforms::PinterestDownloader;
pub use omniget_core::platforms::P2pDownloader;
+pub use omniget_core::platforms::PinterestDownloader;
+pub use omniget_core::platforms::Platform;
pub use omniget_core::platforms::RedditDownloader;
pub use omniget_core::platforms::TikTokDownloader;
pub use omniget_core::platforms::TwitchClipsDownloader;
+pub use omniget_core::platforms::TwitterDownloader;
pub use omniget_core::platforms::VimeoDownloader;
pub use omniget_core::platforms::YouTubeDownloader;
@@ -24,4 +25,4 @@ pub mod bilibili;
pub mod gallerydl;
#[cfg(not(target_os = "android"))]
pub mod generic_ytdlp;
-// Ported to omniget-core: bluesky, direct_file, douyin, instagram, pinterest, p2p, reddit, tiktok, twitch, vimeo, youtube
+// Ported to omniget-core: bluesky, direct_file, douyin, instagram, pinterest, p2p, reddit, tiktok, twitch, twitter, vimeo, youtube
diff --git a/src/lib/nav-config.test.ts b/src/lib/nav-config.test.ts
index 2f9a5f3a..822f1e37 100644
--- a/src/lib/nav-config.test.ts
+++ b/src/lib/nav-config.test.ts
@@ -17,10 +17,10 @@ describe("CORE_NAV_ITEMS", () => {
expect(downloads?.badge).toBe("downloads");
});
- it("About is in the secondary group and sorted last", () => {
+ it("About is in the app group after settings", () => {
const about = CORE_NAV_ITEMS.find((i) => i.href === "/about");
- expect(about?.group).toBe("secondary");
- expect(about?.order).toBe(999);
+ expect(about?.group).toBe("app");
+ expect(about?.order).toBe(50);
});
it("order is strictly increasing among primary items", () => {