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.

feat(bilibili): add URL detection and WBI key management

Tonho6c87faac1849
diff --git a/src-tauri/src/core/db.rs b/src-tauri/src/core/db.rs
new file mode 100644
index 00000000..0935ba12
--- /dev/null
+++ b/src-tauri/src/core/db.rs
@@ -0,0 +1,59 @@
+use std::path::PathBuf;
+use std::sync::{Mutex, OnceLock};
+
+use rusqlite::Connection;
+
+const DB_FILE: &str = "omniget.db";
+
+fn db_path() -> Option<PathBuf> {
+ crate::core::paths::app_data_dir().map(|d| d.join(DB_FILE))
+}
+
+fn open() -> Option<Connection> {
+ let path = db_path()?;
+ if let Some(parent) = path.parent() {
+ if let Err(e) = std::fs::create_dir_all(parent) {
+ tracing::warn!("[db] create_dir_all failed: {}", e);
+ return None;
+ }
+ }
+ match Connection::open(&path) {
+ Ok(conn) => {
+ let _ = conn.pragma_update(None, "journal_mode", "WAL");
+ let _ = conn.pragma_update(None, "synchronous", "NORMAL");
+ let _ = conn.busy_timeout(std::time::Duration::from_secs(5));
+ Some(conn)
+ }
+ Err(e) => {
+ tracing::error!("[db] failed to open {}: {}", path.display(), e);
+ None
+ }
+ }
+}
+
+fn handle() -> Option<&'static Mutex<Connection>> {
+ static CONN: OnceLock<Option<Mutex<Connection>>> = OnceLock::new();
+ CONN.get_or_init(|| open().map(Mutex::new)).as_ref()
+}
+
+/// Runs `f` with the shared connection under a short-lived lock. Returns
+/// `None` (and logs) if the database is unavailable or the closure errors, so
+/// callers degrade gracefully exactly like the previous JSON stores did on IO
+/// failure rather than panicking.
+pub fn with_conn<T>(f: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Option<T> {
+ let mutex = handle()?;
+ let guard = match mutex.lock() {
+ Ok(g) => g,
+ Err(e) => {
+ tracing::error!("[db] mutex poisoned: {}", e);
+ return None;
+ }
+ };
+ match f(&guard) {
+ Ok(v) => Some(v),
+ Err(e) => {
+ tracing::warn!("[db] query failed: {}", e);
+ None
+ }
+ }
+}
diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rs
index 12685787..1ad7e61e 100644
--- a/src-tauri/src/core/mod.rs
+++ b/src-tauri/src/core/mod.rs
@@ -20,6 +20,7 @@ pub use omniget_core::core::ytdlp;
pub mod awake;
pub mod channel_poller;
pub mod channels;
+pub mod db;
pub mod download_log;
pub mod events;
pub mod host_limiter;
diff --git a/src-tauri/src/core/queue.rs b/src-tauri/src/core/queue.rs
index e3b41603..139e0851 100644
--- a/src-tauri/src/core/queue.rs
+++ b/src-tauri/src/core/queue.rs
@@ -438,6 +438,7 @@ impl DownloadQueue {
item.file_path = file_path;
item.file_size_bytes = file_size_bytes;
item.speed_bytes_per_sec = 0.0;
+ item.eta_seconds = None;
crate::core::recovery::remove(id);
if !item.external {
@@ -493,6 +494,12 @@ impl DownloadQueue {
eta_seconds: Option<u64>,
) {
if let Some(item) = self.items.iter_mut().find(|i| i.id == id) {
+ if item.status != QueueStatus::Active {
+ if torrent_id.is_some() && item.torrent_id.is_none() {
+ item.torrent_id = torrent_id;
+ }
+ return;
+ }
item.percent = percent;
item.speed_bytes_per_sec = speed;
item.downloaded_bytes = downloaded;
@@ -514,6 +521,7 @@ impl DownloadQueue {
}
item.status = QueueStatus::Paused;
item.speed_bytes_per_sec = 0.0;
+ item.eta_seconds = None;
return true;
}
}
@@ -544,6 +552,7 @@ impl DownloadQueue {
}
item.status = QueueStatus::Paused;
item.speed_bytes_per_sec = 0.0;
+ item.eta_seconds = None;
paused.push((item.id, item.torrent_id));
}
}
@@ -1181,29 +1190,75 @@ async fn spawn_download_inner(
let total_bytes = info.file_size_bytes;
let item_title = info.title.clone();
let item_platform = platform_name.clone();
- let (tx, mut rx) = mpsc::channel::<f64>(32);
+ let (tx, mut rx) = mpsc::channel::<omniget_core::models::progress::ProgressUpdate>(32);
let app_progress = app.clone();
let queue_progress = queue.clone();
let torrent_id_slot_progress = torrent_id_slot.clone();
let progress_forwarder = tokio::spawn(async move {
+ const STALL_AFTER: std::time::Duration = std::time::Duration::from_secs(6);
+
let mut last_bytes: u64 = 0;
let mut last_time = std::time::Instant::now();
let mut throttle = ProgressThrottle::new(250);
let mut current_speed: f64 = 0.0;
+ let mut last_percent: f64 = 0.0;
+ let mut last_advance = std::time::Instant::now();
+ let mut stalled = false;
+
+ loop {
+ let update = tokio::select! {
+ msg = rx.recv() => match msg {
+ Some(u) => u,
+ None => break,
+ },
+ _ = tokio::time::sleep(std::time::Duration::from_secs(2)) => {
+ if !stalled && last_advance.elapsed() >= STALL_AFTER {
+ stalled = true;
+ current_speed = 0.0;
+ {
+ let mut q = queue_progress.lock().await;
+ let tid = { *torrent_id_slot_progress.lock().await };
+ q.update_progress(
+ item_id, last_percent, 0.0, last_bytes, total_bytes, tid, None,
+ );
+ }
+ let _ = app_progress.emit(
+ "queue-item-progress",
+ &QueueItemProgress {
+ id: item_id,
+ title: item_title.clone(),
+ platform: item_platform.clone(),
+ percent: last_percent,
+ speed_bytes_per_sec: 0.0,
+ downloaded_bytes: last_bytes,
+ total_bytes,
+ phase: "stalled".to_string(),
+ eta_seconds: None,
+ },
+ );
+ }
+ continue;
+ }
+ };
- while let Some(percent) = rx.recv().await {
- if !throttle.should_emit() && percent < 100.0 {
+ let percent = update.percent;
+ if !throttle.should_emit() && percent < 100.0 && !update.has_real_metrics() {
continue;
}
let now = std::time::Instant::now();
let clamped = percent.max(0.0);
- let downloaded_bytes = total_bytes
- .map(|total| (clamped / 100.0 * total as f64) as u64)
- .unwrap_or(0);
+ let resolved_total = update.total_bytes.or(total_bytes);
+ let downloaded_bytes = update.downloaded_bytes.unwrap_or_else(|| {
+ resolved_total
+ .map(|total| (clamped / 100.0 * total as f64) as u64)
+ .unwrap_or(last_bytes)
+ });
- if total_bytes.is_some() && downloaded_bytes > last_bytes {
+ if let Some(real) = update.speed_bps {
+ current_speed = real;
+ } else if downloaded_bytes > last_bytes {
let dt = now.duration_since(last_time).as_secs_f64();
if dt > 0.1 {
let instant_speed = (downloaded_bytes - last_bytes) as f64 / dt;
@@ -1215,8 +1270,14 @@ async fn spawn_download_inner(
}
}
+ if downloaded_bytes > last_bytes || clamped > last_percent || update.speed_bps.is_some()
+ {
+ last_advance = now;
+ stalled = false;
+ }
last_bytes = downloaded_bytes;
last_time = now;
+ last_percent = clamped;
let phase = match percent {
p if p < -1.5 => "connecting",
@@ -1226,19 +1287,20 @@ async fn spawn_download_inner(
_ => "starting",
};
- let eta_seconds = omniget_core::core::ytdlp::get_eta(item_id).or_else(|| {
- if current_speed > 0.0 {
- total_bytes.and_then(|total| {
- if downloaded_bytes >= total {
- None
- } else {
- Some(((total - downloaded_bytes) as f64 / current_speed) as u64)
- }
- })
- } else {
- None
- }
- });
+ let eta_seconds = update
+ .eta_seconds
+ .or_else(|| omniget_core::core::ytdlp::get_eta(item_id))
+ .or_else(|| {
+ if current_speed > 0.0 {
+ resolved_total.and_then(|total| {
+ (total > downloaded_bytes).then(|| {
+ ((total - downloaded_bytes) as f64 / current_speed) as u64
+ })
+ })
+ } else {
+ None
+ }
+ });
{
let mut q = queue_progress.lock().await;
@@ -1248,7 +1310,7 @@ async fn spawn_download_inner(
clamped,
current_speed,
downloaded_bytes,
- total_bytes,
+ resolved_total,
tid,
eta_seconds,
);
@@ -1263,7 +1325,7 @@ async fn spawn_download_inner(
percent: clamped,
speed_bytes_per_sec: current_speed,
downloaded_bytes,
- total_bytes,
+ total_bytes: resolved_total,
phase: phase.to_string(),
eta_seconds,
},
diff --git a/src-tauri/src/core/queue_history.rs b/src-tauri/src/core/queue_history.rs
index 53fe25a2..a9c554f3 100644
--- a/src-tauri/src/core/queue_history.rs
+++ b/src-tauri/src/core/queue_history.rs
@@ -1,10 +1,9 @@
-use std::collections::VecDeque;
-use std::io::Write;
use std::path::PathBuf;
-use std::sync::{Mutex, OnceLock};
+use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};
+use crate::core::db;
use crate::core::queue::QueueKind;
const HISTORY_FILE: &str = "download-history.json";
@@ -38,98 +37,144 @@ struct HistoryFile {
entries: Vec<HistoryEntry>,
}
-fn store() -> &'static Mutex<VecDeque<HistoryEntry>> {
- static STORE: OnceLock<Mutex<VecDeque<HistoryEntry>>> = OnceLock::new();
- STORE.get_or_init(|| Mutex::new(VecDeque::new()))
+fn schema(conn: &Connection) -> rusqlite::Result<()> {
+ conn.execute_batch(
+ "CREATE TABLE IF NOT EXISTS history (
+ id INTEGER PRIMARY KEY,
+ url TEXT NOT NULL,
+ platform TEXT NOT NULL,
+ title TEXT NOT NULL,
+ file_path TEXT,
+ file_size_bytes INTEGER,
+ total_bytes INTEGER,
+ success INTEGER NOT NULL,
+ error TEXT,
+ completed_at INTEGER NOT NULL,
+ thumbnail_url TEXT,
+ kind TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_history_completed
+ ON history (completed_at DESC, id DESC);",
+ )
}
-fn file_path() -> Option<PathBuf> {
+fn db_upsert(conn: &Connection, e: &HistoryEntry) -> rusqlite::Result<()> {
+ let kind = e
+ .kind
+ .as_ref()
+ .and_then(|k| serde_json::to_string(k).ok());
+ conn.execute(
+ "INSERT OR REPLACE INTO history
+ (id, url, platform, title, file_path, file_size_bytes, total_bytes,
+ success, error, completed_at, thumbnail_url, kind)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12)",
+ params![
+ e.id as i64,
+ e.url,
+ e.platform,
+ e.title,
+ e.file_path,
+ e.file_size_bytes.map(|v| v as i64),
+ e.total_bytes.map(|v| v as i64),
+ e.success as i64,
+ e.error,
+ e.completed_at,
+ e.thumbnail_url,
+ kind,
+ ],
+ )?;
+ conn.execute(
+ "DELETE FROM history WHERE id NOT IN
+ (SELECT id FROM history ORDER BY completed_at DESC, id DESC LIMIT ?1)",
+ params![MAX_HISTORY_ENTRIES as i64],
+ )?;
+ Ok(())
+}
+
+fn row_to_entry(row: &rusqlite::Row) -> rusqlite::Result<HistoryEntry> {
+ let id: i64 = row.get(0)?;
+ let file_size: Option<i64> = row.get(5)?;
+ let total: Option<i64> = row.get(6)?;
+ let success: i64 = row.get(7)?;
+ let kind_text: Option<String> = row.get(11)?;
+ Ok(HistoryEntry {
+ id: id as u64,
+ url: row.get(1)?,
+ platform: row.get(2)?,
+ title: row.get(3)?,
+ file_path: row.get(4)?,
+ file_size_bytes: file_size.map(|v| v as u64),
+ total_bytes: total.map(|v| v as u64),
+ success: success != 0,
+ error: row.get(8)?,
+ completed_at: row.get(9)?,
+ thumbnail_url: row.get(10)?,
+ kind: kind_text.and_then(|t| serde_json::from_str(&t).ok()),
+ })
+}
+
+fn db_list(conn: &Connection) -> rusqlite::Result<Vec<HistoryEntry>> {
+ let mut stmt = conn.prepare(
+ "SELECT id, url, platform, title, file_path, file_size_bytes, total_bytes,
+ success, error, completed_at, thumbnail_url, kind
+ FROM history ORDER BY completed_at DESC, id DESC",
+ )?;
+ let rows = stmt.query_map([], row_to_entry)?;
+ rows.collect()
+}
+
+fn json_path() -> Option<PathBuf> {
crate::core::paths::app_data_dir().map(|d| d.join(HISTORY_FILE))
}
-fn write_to_disk(entries: &VecDeque<HistoryEntry>) {
- let Some(path) = file_path() else { return };
- let Some(parent) = path.parent() else { return };
- if let Err(e) = std::fs::create_dir_all(parent) {
- tracing::warn!("[history] create_dir_all failed: {}", e);
+fn import_legacy_json(conn: &Connection) {
+ let Some(path) = json_path() else { return };
+ let Ok(content) = std::fs::read_to_string(&path) else {
return;
- }
- let file_data = HistoryFile {
- entries: entries.iter().cloned().collect(),
};
- let serialized = match serde_json::to_string_pretty(&file_data) {
- Ok(s) => s,
- Err(e) => {
- tracing::warn!("[history] serialize failed: {}", e);
- return;
+ match serde_json::from_str::<HistoryFile>(&content) {
+ Ok(parsed) => {
+ for entry in parsed.entries.into_iter().take(MAX_HISTORY_ENTRIES) {
+ let _ = db_upsert(conn, &entry);
+ }
+ tracing::info!("[history] imported legacy JSON into SQLite");
}
- };
- let tmp = path.with_extension("json.tmp");
- let write_result = (|| -> std::io::Result<()> {
- let mut f = std::fs::File::create(&tmp)?;
- f.write_all(serialized.as_bytes())?;
- f.sync_all()?;
- Ok(())
- })();
- if let Err(e) = write_result {
- tracing::warn!("[history] write tmp failed: {}", e);
- let _ = std::fs::remove_file(&tmp);
- return;
- }
- if let Err(e) = std::fs::rename(&tmp, &path) {
- tracing::warn!("[history] rename failed: {}", e);
- let _ = std::fs::remove_file(&tmp);
+ Err(e) => tracing::warn!("[history] legacy JSON parse failed: {}", e),
}
+ let _ = std::fs::rename(&path, path.with_extension("json.imported"));
}
pub fn init_from_disk() {
- let Some(path) = file_path() else { return };
- let content = match std::fs::read_to_string(&path) {
- Ok(c) => c,
- Err(_) => return,
- };
- let parsed: HistoryFile = match serde_json::from_str(&content) {
- Ok(v) => v,
- Err(e) => {
- tracing::warn!("[history] parse failed: {}", e);
- return;
- }
- };
- let mut guard = store().lock().unwrap();
- guard.clear();
- for entry in parsed.entries.into_iter().take(MAX_HISTORY_ENTRIES) {
- guard.push_back(entry);
- }
+ db::with_conn(|c| {
+ schema(c)?;
+ Ok(())
+ });
+ db::with_conn(|c| {
+ import_legacy_json(c);
+ Ok(())
+ });
}
pub fn record(entry: HistoryEntry) {
- let mut guard = store().lock().unwrap();
- guard.retain(|e| e.id != entry.id);
- guard.push_back(entry);
- while guard.len() > MAX_HISTORY_ENTRIES {
- guard.pop_front();
- }
- write_to_disk(&guard);
+ db::with_conn(|c| db_upsert(c, &entry));
}
pub fn list() -> Vec<HistoryEntry> {
- let guard = store().lock().unwrap();
- guard.iter().rev().cloned().collect()
+ db::with_conn(db_list).unwrap_or_default()
}
pub fn remove(id: u64) {
- let mut guard = store().lock().unwrap();
- let before = guard.len();
- guard.retain(|e| e.id != id);
- if guard.len() != before {
- write_to_disk(&guard);
- }
+ db::with_conn(|c| {
+ c.execute("DELETE FROM history WHERE id = ?1", params![id as i64])?;
+ Ok(())
+ });
}
pub fn clear_all() {
- let mut guard = store().lock().unwrap();
- guard.clear();
- write_to_disk(&guard);
+ db::with_conn(|c| {
+ c.execute("DELETE FROM history", [])?;
+ Ok(())
+ });
}
pub fn now_unix_seconds() -> i64 {
@@ -138,3 +183,82 @@ pub fn now_unix_seconds() -> i64 {
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn mk(id: u64, completed_at: i64) -> HistoryEntry {
+ HistoryEntry {
+ id,
+ url: format!("https://x.test/{}", id),
+ platform: "youtube".into(),
+ title: format!("Video {}", id),
+ file_path: Some(format!("/tmp/{}.mp4", id)),
+ file_size_bytes: Some(1234),
+ total_bytes: Some(2000),
+ success: true,
+ error: None,
+ completed_at,
+ thumbnail_url: None,
+ kind: Some(QueueKind::Video),
+ }
+ }
+
+ fn conn() -> Connection {
+ let c = Connection::open_in_memory().unwrap();
+ schema(&c).unwrap();
+ c
+ }
+
+ #[test]
+ fn upsert_list_roundtrip_newest_first() {
+ let c = conn();
+ db_upsert(&c, &mk(1, 100)).unwrap();
+ db_upsert(&c, &mk(2, 200)).unwrap();
+ let list = db_list(&c).unwrap();
+ assert_eq!(list.len(), 2);
+ assert_eq!(list[0].id, 2);
+ assert_eq!(list[1].id, 1);
+ assert_eq!(list[0].kind, Some(QueueKind::Video));
+ }
+
+ #[test]
+ fn upsert_replaces_same_id() {
+ let c = conn();
+ db_upsert(&c, &mk(1, 100)).unwrap();
+ let mut e = mk(1, 150);
+ e.title = "Renamed".into();
+ db_upsert(&c, &e).unwrap();
+ let list = db_list(&c).unwrap();
+ assert_eq!(list.len(), 1);
+ assert_eq!(list[0].title, "Renamed");
+ }
+
+ #[test]
+ fn prune_keeps_only_max_entries() {
+ let c = conn();
+ for i in 0..(MAX_HISTORY_ENTRIES as u64 + 25) {
+ db_upsert(&c, &mk(i + 1, i as i64)).unwrap();
+ }
+ let list = db_list(&c).unwrap();
+ assert_eq!(list.len(), MAX_HISTORY_ENTRIES);
+ assert_eq!(list[0].id, MAX_HISTORY_ENTRIES as u64 + 25);
+ }
+
+ #[test]
+ fn import_legacy_json_round_trips() {
+ let c = conn();
+ let file = HistoryFile {
+ entries: vec![mk(7, 70), mk(8, 80)],
+ };
+ let json = serde_json::to_string(&file).unwrap();
+ let parsed: HistoryFile = serde_json::from_str(&json).unwrap();
+ for e in parsed.entries {
+ db_upsert(&c, &e).unwrap();
+ }
+ let list = db_list(&c).unwrap();
+ assert_eq!(list.len(), 2);
+ assert_eq!(list[0].id, 8);
+ }
+}
diff --git a/src-tauri/src/platforms/bilibili/api.rs b/src-tauri/src/platforms/bilibili/api.rs
new file mode 100644
index 00000000..07d7569a
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/api.rs
@@ -0,0 +1,332 @@
+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 = 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);
+ 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 = 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::cookies::account_path_for_consumer("bilibili.com", Some(slug))?;
+ let content = std::fs::read_to_string(&path).ok()?;
+ let mut pairs: Vec<String> = Vec::new();
+ for line in content.lines() {
+ let line = line.trim();
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ let mut parts = line.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("; "))
+ }
+}
diff --git a/src-tauri/src/platforms/bilibili/auth/captcha.rs b/src-tauri/src/platforms/bilibili/auth/captcha.rs
new file mode 100644
index 00000000..4937a743
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/auth/mod.rs b/src-tauri/src/platforms/bilibili/auth/mod.rs
new file mode 100644
index 00000000..cac45d05
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/auth/mod.rs
@@ -0,0 +1,152 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use super::api::{ApiClient, BilibiliError, Result};
+
+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> {
+ use crate::extension_storage::ExtensionCookie;
+
+ let slug = slug_from_uname(uname);
+ 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<ExtensionCookie> = cookies
+ .iter()
+ .map(|(name, value)| ExtensionCookie {
+ 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();
+
+ 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)
+}
diff --git a/src-tauri/src/platforms/bilibili/auth/qr.rs b/src-tauri/src/platforms/bilibili/auth/qr.rs
new file mode 100644
index 00000000..a2a89eeb
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/auth/qr.rs
@@ -0,0 +1,139 @@
+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/src/platforms/bilibili/auth/sms.rs b/src-tauri/src/platforms/bilibili/auth/sms.rs
new file mode 100644
index 00000000..07cac076
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/auth/sms.rs
@@ -0,0 +1,141 @@
+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/src/platforms/bilibili/cdn.rs b/src-tauri/src/platforms/bilibili/cdn.rs
new file mode 100644
index 00000000..51e0ef24
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/cdn.rs
@@ -0,0 +1,133 @@
+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/src/platforms/bilibili/cookie.rs b/src-tauri/src/platforms/bilibili/cookie.rs
new file mode 100644
index 00000000..409abb21
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/cookie.rs
@@ -0,0 +1,360 @@
+use std::io::Cursor;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use rand::RngExt;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use sha2::Sha256;
+use hmac::{Hmac, Mac};
+
+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 root = crate::core::paths::app_data_dir()?;
+ Some(root.join("cookies").join("bilibili.com").join("_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::cookies::account_path_for_consumer("bilibili.com", Some(ANONYMOUS_SLUG))
+ .unwrap_or_else(|| {
+ let root = crate::core::paths::app_data_dir().unwrap_or_default();
+ root.join("cookies")
+ .join("bilibili.com")
+ .join(format!("{}.txt", ANONYMOUS_SLUG))
+ });
+ 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/src/platforms/bilibili/cover.rs b/src-tauri/src/platforms/bilibili/cover.rs
new file mode 100644
index 00000000..ebb8e6fb
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/danmaku/ass/lanes.rs b/src-tauri/src/platforms/bilibili/danmaku/ass/lanes.rs
new file mode 100644
index 00000000..00a6c539
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/danmaku/ass/mod.rs b/src-tauri/src/platforms/bilibili/danmaku/ass/mod.rs
new file mode 100644
index 00000000..b8595f5d
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/danmaku/ass/render.rs b/src-tauri/src/platforms/bilibili/danmaku/ass/render.rs
new file mode 100644
index 00000000..70f87a70
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/danmaku/ass/render.rs
@@ -0,0 +1,258 @@
+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/src/platforms/bilibili/danmaku/json.rs b/src-tauri/src/platforms/bilibili/danmaku/json.rs
new file mode 100644
index 00000000..1cffea56
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/danmaku/mod.rs b/src-tauri/src/platforms/bilibili/danmaku/mod.rs
new file mode 100644
index 00000000..e76e592d
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/danmaku/mod.rs
@@ -0,0 +1,74 @@
+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/src/platforms/bilibili/danmaku/xml.rs b/src-tauri/src/platforms/bilibili/danmaku/xml.rs
new file mode 100644
index 00000000..c36e427a
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/engine/fetch.rs b/src-tauri/src/platforms/bilibili/engine/fetch.rs
new file mode 100644
index 00000000..4a73dba2
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/engine/fetch.rs
@@ -0,0 +1,90 @@
+use std::path::Path;
+use std::time::Duration;
+
+use omniget_core::core::http_fetcher::{HttpFetcher, HttpFetcherConfig, HttpFetcherResult};
+use omniget_core::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> {
+ 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/src/platforms/bilibili/legacy.rs b/src-tauri/src/platforms/bilibili/legacy.rs
new file mode 100644
index 00000000..257c201d
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/legacy.rs
@@ -0,0 +1,287 @@
+use omniget_core::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/src/platforms/bilibili/mod.rs b/src-tauri/src/platforms/bilibili/mod.rs
index ab822e2e..3597154c 100644
--- a/src-tauri/src/platforms/bilibili/mod.rs
+++ b/src-tauri/src/platforms/bilibili/mod.rs
@@ -1,15 +1,30 @@
-use std::collections::HashSet;
+use std::path::PathBuf;
+
+use omniget_core::models::progress::ProgressUpdate;
use anyhow::anyhow;
use async_trait::async_trait;
use tokio::sync::mpsc;
-use crate::core::ytdlp;
-use crate::models::media::{
- DownloadOptions, DownloadResult, MediaInfo, MediaType, VideoQuality as MediaVideoQuality,
-};
+use crate::models::media::{DownloadOptions, DownloadResult, MediaInfo, MediaType};
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;
+
pub struct BilibiliDownloader;
impl Default for BilibiliDownloader {
@@ -22,28 +37,180 @@ impl BilibiliDownloader {
pub fn new() -> Self {
Self
}
+}
- 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;
- }
+pub fn has_active_account() -> bool {
+ let registry = crate::cookies::load_registry();
+ let bucket = match registry.buckets.get("bilibili.com") {
+ Some(b) => b,
+ None => return false,
+ };
+ bucket
+ .accounts
+ .iter()
+ .any(|a| !a.slug.starts_with('_') && a.cookie_count > 0)
+}
+
+fn active_account_slug() -> Option<String> {
+ let registry = crate::cookies::load_registry();
+ let bucket = registry.buckets.get("bilibili.com")?;
+ bucket
+ .accounts
+ .iter()
+ .filter(|a| !a.slug.starts_with('_') && a.cookie_count > 0)
+ .max_by_key(|a| a.last_used_at_ms.unwrap_or(a.captured_at_ms))
+ .map(|a| a.slug.clone())
+}
+
+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;
}
- false
}
- fn bilibili_extra_flags() -> Vec<String> {
- vec![
- "--referer".to_string(),
- "https://www.bilibili.com".to_string(),
- ]
+ 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 = crate::storage::config::load_settings_standalone();
+ 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,
}
}
@@ -66,260 +233,32 @@ impl PlatformDownloader for BilibiliDownloader {
}
async fn get_media_info(&self, url: &str) -> anyhow::Result<MediaInfo> {
- let ytdlp_path = ytdlp::find_ytdlp_cached()
- .await
- .ok_or_else(|| anyhow!("yt-dlp not found"))?;
-
- let extra = Self::bilibili_extra_flags();
-
- if Self::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,
- })
+ legacy::get_media_info(url).await
}
async fn download(
&self,
info: &MediaInfo,
opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
+ progress: mpsc::Sender<ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
- let _ = progress.send(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 self
- .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
- }
-}
-
-impl BilibiliDownloader {
- async fn download_playlist(
- &self,
- info: &MediaInfo,
- opts: &DownloadOptions,
- progress: mpsc::Sender<f64>,
- 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::<f64>(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 / 100.0) / total_f * 100.0;
- let _ = progress_clone.send(overall).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;
- }
+ 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) => {
- tracing::error!("[bilibili] playlist item {} failed: {}", i + 1, e);
+ let msg = e.to_string();
+ if msg.contains("errors.bilibili.not_logged_in") {
+ notify::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;
}
}
}
-
- let _ = progress.send(100.0).await;
- Ok(last_result)
+ legacy::download(info, opts, progress).await
}
}
diff --git a/src-tauri/src/platforms/bilibili/naming.rs b/src-tauri/src/platforms/bilibili/naming.rs
new file mode 100644
index 00000000..3647c2e6
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/nfo.rs b/src-tauri/src/platforms/bilibili/nfo.rs
new file mode 100644
index 00000000..72f909e8
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/nfo.rs
@@ -0,0 +1,274 @@
+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/src/platforms/bilibili/notify.rs b/src-tauri/src/platforms/bilibili/notify.rs
new file mode 100644
index 00000000..eecf832f
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/parser/watch_later.rs b/src-tauri/src/platforms/bilibili/parser/watch_later.rs
new file mode 100644
index 00000000..7f812668
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/parser/watch_later.rs
@@ -0,0 +1,106 @@
+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() {
+ 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/src/platforms/bilibili/preview.rs b/src-tauri/src/platforms/bilibili/preview.rs
new file mode 100644
index 00000000..7f113281
--- /dev/null
+++ b/src-tauri/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/src/platforms/bilibili/url_kind.rs b/src-tauri/src/platforms/bilibili/url_kind.rs
new file mode 100644
index 00000000..44b5f0b8
--- /dev/null
+++ b/src-tauri/src/platforms/bilibili/url_kind.rs
@@ -0,0 +1,454 @@
+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/src/platforms/bilibili/wbi.rs b/src-tauri/src/platforms/bilibili/wbi.rs
new file mode 100644
index 00000000..4088fdff
--- /dev/null
+++ b/src-tauri/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/src/platforms/mod.rs b/src-tauri/src/platforms/mod.rs
index 25ab522f..7de9ebc9 100644
--- a/src-tauri/src/platforms/mod.rs
+++ b/src-tauri/src/platforms/mod.rs
@@ -13,6 +13,8 @@ pub mod bilibili;
#[cfg(not(target_os = "android"))]
pub mod douyin;
#[cfg(not(target_os = "android"))]
+pub mod gallerydl;
+#[cfg(not(target_os = "android"))]
pub mod generic_ytdlp;
#[cfg(not(target_os = "android"))]
pub mod instagram;
diff --git a/src-tauri/src/platforms/noop.rs b/src-tauri/src/platforms/noop.rs
index 181b262b..2221e7f0 100644
--- a/src-tauri/src/platforms/noop.rs
+++ b/src-tauri/src/platforms/noop.rs
@@ -37,7 +37,7 @@ impl PlatformDownloader for NoopDownloader {
&self,
_info: &MediaInfo,
_opts: &DownloadOptions,
- _progress: tokio::sync::mpsc::Sender<f64>,
+ _progress: tokio::sync::mpsc::Sender<omniget_core::models::progress::ProgressUpdate>,
) -> anyhow::Result<DownloadResult> {
Err(anyhow::anyhow!(
"NoopDownloader cannot drive download; this item is driven by an external plugin"