use std::path::Path;
use serde_json::Value;
use crate::error::Error;
#[derive(Debug, Clone)]
pub enum CookieSource {
File(std::path::PathBuf),
Inline(String),
}
impl CookieSource {
pub fn get_cookie(&self) -> Result<String, Error> {
match self {
CookieSource::File(path) => {
if !path.exists() {
return Err(Error::CookieFileNotFound(path.clone()));
}
let content = std::fs::read_to_string(path)?;
let json: Value = serde_json::from_str(&content)?;
let sessdata = json["SESSDATA"]
.as_str()
.ok_or_else(|| Error::AuthenticationFailed)?;
let buvid3 = json["buvid3"]
.as_str()
.unwrap_or("");
Ok(format!("SESSDATA={}; buvid3={}", sessdata, buvid3))
}
CookieSource::Inline(cookie) => Ok(cookie.clone()),
}
}
}
impl From<&str> for CookieSource {
fn from(s: &str) -> Self {
if s.contains("SESSDATA=") || s.contains("buvid3=") {
CookieSource::Inline(s.to_string())
} else {
CookieSource::File(std::path::PathBuf::from(s))
}
}
}
impl From<String> for CookieSource {
fn from(s: String) -> Self {
s.as_str().into()
}
}
impl From<&Path> for CookieSource {
fn from(p: &Path) -> Self {
CookieSource::File(p.to_path_buf())
}
}