not there yet but has potential
This commit is contained in:
131
old_src/core/config.rs
Normal file
131
old_src/core/config.rs
Normal file
@@ -0,0 +1,131 @@
|
||||
use std::{fs, io, path::PathBuf};
|
||||
|
||||
use super::paths;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub base_url: String,
|
||||
pub access_token: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub transcode_mbps: Option<u32>,
|
||||
pub transcode_default_on: Option<bool>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigError {
|
||||
NotFound(PathBuf),
|
||||
Io(io::Error),
|
||||
Parse(String),
|
||||
}
|
||||
|
||||
impl From<io::Error> for ConfigError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
Self::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config_path() -> Option<PathBuf> {
|
||||
paths::app_config_dir().map(|d| d.join("config.toml"))
|
||||
}
|
||||
|
||||
// Very small TOML-ish parser for now (no deps).
|
||||
// Format:
|
||||
// base_url = "http://..."
|
||||
// access_token = "..."
|
||||
pub fn load_config() -> Result<Config, ConfigError> {
|
||||
let path = config_path().ok_or_else(|| ConfigError::Parse("No HOME/XDG dirs".into()))?;
|
||||
if !path.exists() {
|
||||
return Err(ConfigError::NotFound(path));
|
||||
}
|
||||
|
||||
let s = fs::read_to_string(&path)?;
|
||||
parse_config(&s).map_err(ConfigError::Parse)
|
||||
}
|
||||
|
||||
fn parse_config(s: &str) -> Result<Config, String> {
|
||||
let mut base_url: Option<String> = None;
|
||||
let mut access_token: Option<String> = None;
|
||||
let mut user_id: Option<String> = None;
|
||||
let mut transcode_mbps: Option<u32> = None;
|
||||
let mut transcode_default_on: Option<bool> = None;
|
||||
|
||||
for (i, line) in s.lines().enumerate() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (k, v) = line
|
||||
.split_once('=')
|
||||
.ok_or_else(|| format!("Line {}: expected key = value", i + 1))?;
|
||||
|
||||
let key = k.trim();
|
||||
let mut val = v.trim().to_string();
|
||||
|
||||
// strip quotes if present
|
||||
if val.starts_with('"') && val.ends_with('"') && val.len() >= 2 {
|
||||
val = val[1..val.len() - 1].to_string();
|
||||
}
|
||||
|
||||
match key {
|
||||
"base_url" => base_url = Some(val),
|
||||
"access_token" => access_token = Some(val),
|
||||
"user_id" => user_id = Some(val),
|
||||
|
||||
"transcode_mbps" => {
|
||||
transcode_mbps = val.parse::<u32>().ok();
|
||||
}
|
||||
|
||||
"transcode_default_on" => {
|
||||
transcode_default_on = match val.as_str() {
|
||||
"true" => Some(true),
|
||||
"false" => Some(false),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let base_url = base_url.ok_or_else(|| "Missing base_url".to_string())?;
|
||||
|
||||
Ok(Config {
|
||||
base_url,
|
||||
access_token,
|
||||
user_id,
|
||||
transcode_mbps,
|
||||
transcode_default_on,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn save_config(cfg: &Config) -> Result<(), ConfigError> {
|
||||
let dir = paths::app_config_dir()
|
||||
.ok_or_else(|| ConfigError::Parse("No HOME/XDG dirs".into()))?;
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
|
||||
let path = dir.join("config.toml");
|
||||
|
||||
let mut out = String::new();
|
||||
|
||||
out.push_str(&format!("base_url = \"{}\"\n", cfg.base_url));
|
||||
|
||||
if let Some(t) = &cfg.access_token {
|
||||
out.push_str(&format!("access_token = \"{}\"\n", t));
|
||||
}
|
||||
|
||||
if let Some(u) = &cfg.user_id {
|
||||
out.push_str(&format!("user_id = \"{}\"\n", u));
|
||||
}
|
||||
|
||||
if let Some(m) = cfg.transcode_mbps {
|
||||
out.push_str(&format!("transcode_mbps = {}\n", m));
|
||||
}
|
||||
|
||||
if let Some(b) = cfg.transcode_default_on {
|
||||
out.push_str(&format!("transcode_default_on = {}\n", b));
|
||||
}
|
||||
|
||||
std::fs::write(path, out)?;
|
||||
Ok(())
|
||||
}
|
||||
398
old_src/core/jellyfin.rs
Normal file
398
old_src/core/jellyfin.rs
Normal file
@@ -0,0 +1,398 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::config::Config;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct JellyfinClient {
|
||||
base_url: String,
|
||||
client: reqwest::blocking::Client,
|
||||
token: String,
|
||||
}
|
||||
|
||||
pub struct LoginResult {
|
||||
pub access_token: String,
|
||||
pub user_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AuthenticateUserByName<'a> {
|
||||
#[serde(rename = "Username")]
|
||||
username: &'a str,
|
||||
#[serde(rename = "Pw")]
|
||||
pw: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AuthenticationResult {
|
||||
#[serde(rename = "AccessToken")]
|
||||
access_token: Option<String>,
|
||||
#[serde(rename = "User")]
|
||||
user: Option<UserDto>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct UserDto {
|
||||
#[serde(rename = "Id")]
|
||||
id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct ViewsResponse {
|
||||
#[serde(rename = "Items", default)]
|
||||
pub items: Vec<JfItem>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PlaylistItemsResponse {
|
||||
#[serde(rename = "Items", default)]
|
||||
items: Vec<JfItem>,
|
||||
#[serde(rename = "TotalRecordCount")]
|
||||
total_record_count: Option<usize>,
|
||||
}
|
||||
|
||||
impl JellyfinClient {
|
||||
pub fn from_config(cfg: &Config) -> Result<Self, String> {
|
||||
let token = cfg
|
||||
.access_token
|
||||
.clone()
|
||||
.ok_or_else(|| "missing access_token (need login)".to_string())?;
|
||||
|
||||
Ok(Self {
|
||||
base_url: cfg.base_url.trim_end_matches('/').to_string(),
|
||||
client: reqwest::blocking::Client::new(),
|
||||
token,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn unauthenticated(base_url: &str) -> Self {
|
||||
Self {
|
||||
base_url: base_url.trim_end_matches('/').to_string(),
|
||||
client: reqwest::blocking::Client::new(),
|
||||
token: String::new(), // unused for login
|
||||
}
|
||||
}
|
||||
|
||||
pub fn login_by_name(&self, username: &str, password: &str) -> Result<LoginResult, String> {
|
||||
let url = format!("{}/Users/AuthenticateByName", self.base_url);
|
||||
|
||||
let auth_header = format!(
|
||||
"MediaBrowser Client=\"cj-jftui\", Device=\"kitty\", DeviceId=\"cj-jftui\", Version=\"{}\"",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
);
|
||||
|
||||
let body = AuthenticateUserByName { username, pw: password };
|
||||
|
||||
let resp = self
|
||||
.client
|
||||
.post(url)
|
||||
.header("X-Emby-Authorization", auth_header)
|
||||
.json(&body)
|
||||
.send()
|
||||
.map_err(|e| format!("request failed: {e}"))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().unwrap_or_default();
|
||||
return Err(format!("login failed: {status} {text}"));
|
||||
}
|
||||
|
||||
let parsed: AuthenticationResult = resp
|
||||
.json()
|
||||
.map_err(|e| format!("bad response json: {e}"))?;
|
||||
|
||||
let token = parsed
|
||||
.access_token
|
||||
.ok_or_else(|| "missing AccessToken in response".to_string())?;
|
||||
|
||||
let user_id = parsed.user.and_then(|u| u.id);
|
||||
|
||||
Ok(LoginResult {
|
||||
access_token: token,
|
||||
user_id,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn list_views(&self, user_id: &str) -> Result<Vec<JfItem>, String> {
|
||||
let url = format!("{}/Users/{}/Views", self.base_url, user_id);
|
||||
|
||||
let resp = self
|
||||
.client
|
||||
.get(url)
|
||||
.header("X-Emby-Authorization", self.auth_header_value())
|
||||
.send()
|
||||
.map_err(|e| format!("Views request failed: {e}"))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().unwrap_or_default();
|
||||
return Err(format!("Views failed: {status} {text}"));
|
||||
}
|
||||
|
||||
let parsed: ViewsResponse = resp
|
||||
.json()
|
||||
.map_err(|e| format!("Views parse failed: {e}"))?;
|
||||
|
||||
Ok(parsed.items)
|
||||
}
|
||||
|
||||
fn auth_header_value(&self) -> String {
|
||||
// Identify as a client and include the token.
|
||||
format!(
|
||||
"MediaBrowser Client=\"cj-jftui\", Device=\"kitty\", DeviceId=\"cj-jftui\", Version=\"{}\", Token=\"{}\"",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
self.token
|
||||
)
|
||||
}
|
||||
|
||||
pub fn list_items(
|
||||
&self,
|
||||
user_id: &str,
|
||||
query: LibraryQuery,
|
||||
start_index: usize,
|
||||
limit: usize,
|
||||
) -> Result<PagedItems, String> {
|
||||
let url = format!("{}/Users/{}/Items", self.base_url, user_id);
|
||||
|
||||
let mut sort_by = "SortName";
|
||||
|
||||
if let Some(types) = query.include_item_types.as_deref() {
|
||||
if types.contains("Episode") {
|
||||
sort_by = "ParentIndexNumber,IndexNumber,SortName";
|
||||
} else if types.contains("Audio") {
|
||||
sort_by = "SortName";
|
||||
}
|
||||
}
|
||||
|
||||
let recursive = if query.recursive { "true" } else { "false" };
|
||||
|
||||
let mut req = self
|
||||
.client
|
||||
.get(url)
|
||||
.header("X-Emby-Authorization", self.auth_header_value())
|
||||
.query(&[
|
||||
("Recursive", recursive),
|
||||
("StartIndex", &start_index.to_string()),
|
||||
("Limit", &limit.to_string()),
|
||||
("Fields", "PrimaryImageAspectRatio,SortName,ProductionYear,IndexNumber,ParentIndexNumber,RunTimeTicks,Genres,Studios,Overview,SeriesName,Album,AlbumArtist,Artists,UserData"),
|
||||
("SortBy", sort_by),
|
||||
("SortOrder", "Ascending"),
|
||||
]);
|
||||
|
||||
if let Some(types) = query.include_item_types.as_deref() {
|
||||
// Jellyfin expects IncludeItemTypes as repeated query params, not CSV
|
||||
for t in types.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
req = req.query(&[("IncludeItemTypes", t)]);
|
||||
}
|
||||
}
|
||||
if let Some(parent) = query.parent_id.as_deref() {
|
||||
req = req.query(&[("ParentId", parent)]);
|
||||
}
|
||||
if let Some(term) = query.search_term.as_deref() {
|
||||
req = req.query(&[("SearchTerm", term)]);
|
||||
}
|
||||
|
||||
let resp = req.send().map_err(|e| format!("request failed: {e}"))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().unwrap_or_default();
|
||||
return Err(format!("list_items failed: {status} {text}"));
|
||||
}
|
||||
|
||||
let parsed: ItemsResponse = resp
|
||||
.json()
|
||||
.map_err(|e| format!("bad response json: {e}"))?;
|
||||
|
||||
Ok(PagedItems {
|
||||
items: parsed.items,
|
||||
total: parsed.total_record_count.unwrap_or(0),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn playlist_items(
|
||||
&self,
|
||||
user_id: &str,
|
||||
playlist_id: &str,
|
||||
start_index: usize,
|
||||
limit: usize,
|
||||
) -> Result<PagedItems, String> {
|
||||
let url = format!("{}/Playlists/{}/Items", self.base_url, playlist_id);
|
||||
|
||||
let resp = self
|
||||
.client
|
||||
.get(url)
|
||||
.header("X-Emby-Authorization", self.auth_header_value())
|
||||
.query(&[
|
||||
("UserId", user_id),
|
||||
("StartIndex", &start_index.to_string()),
|
||||
("Limit", &limit.to_string()),
|
||||
("Fields", "PrimaryImageAspectRatio,SortName,ProductionYear,IndexNumber,ParentIndexNumber,RunTimeTicks,Genres,Studios,Overview,SeriesName,Album,AlbumArtist,Artists,UserData"),
|
||||
])
|
||||
.send()
|
||||
.map_err(|e| format!("request failed: {e}"))?;
|
||||
|
||||
if !resp.status().is_success() {
|
||||
let status = resp.status();
|
||||
let text = resp.text().unwrap_or_default();
|
||||
return Err(format!("playlist_items failed: {status} {text}"));
|
||||
}
|
||||
|
||||
let parsed: PlaylistItemsResponse = resp
|
||||
.json()
|
||||
.map_err(|e| format!("bad response json: {e}"))?;
|
||||
|
||||
Ok(PagedItems {
|
||||
items: parsed.items,
|
||||
total: parsed.total_record_count.unwrap_or(0),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// What kind of library list we want.
|
||||
#[derive(Clone)]
|
||||
pub struct LibraryQuery {
|
||||
pub include_item_types: Option<String>, // e.g. Some("Movie".into())
|
||||
pub parent_id: Option<String>, // e.g. Some(series_id)
|
||||
pub search_term: Option<String>, // e.g. Some("matrix".into())
|
||||
pub recursive: bool, // true for big lists, false for drilldown
|
||||
}
|
||||
|
||||
impl LibraryQuery {
|
||||
pub fn movies() -> Self {
|
||||
Self {
|
||||
include_item_types: Some("Movie".into()),
|
||||
parent_id: None,
|
||||
search_term: None,
|
||||
recursive: true,
|
||||
}
|
||||
}
|
||||
pub fn shows() -> Self {
|
||||
Self {
|
||||
include_item_types: Some("Series".into()),
|
||||
parent_id: None,
|
||||
search_term: None,
|
||||
recursive: true,
|
||||
}
|
||||
}
|
||||
pub fn music() -> Self {
|
||||
Self {
|
||||
include_item_types: Some("Audio".into()),
|
||||
parent_id: None,
|
||||
search_term: None,
|
||||
recursive: true,
|
||||
}
|
||||
}
|
||||
|
||||
// true "All" (no filter)
|
||||
pub fn all() -> Self {
|
||||
Self {
|
||||
include_item_types: None,
|
||||
parent_id: None,
|
||||
search_term: None,
|
||||
recursive: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_parent(mut self, parent_id: impl Into<String>) -> Self {
|
||||
self.parent_id = Some(parent_id.into());
|
||||
self.recursive = false; // drilldown is usually direct children
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_search(mut self, term: impl Into<String>) -> Self {
|
||||
self.search_term = Some(term.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_item_types(mut self, types: impl Into<String>) -> Self {
|
||||
self.include_item_types = Some(types.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct PagedItems {
|
||||
pub items: Vec<JfItem>,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct JfStudio {
|
||||
#[serde(rename = "Name")]
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct JfUserData {
|
||||
#[serde(rename = "Played")]
|
||||
pub played: Option<bool>,
|
||||
|
||||
#[serde(rename = "PlaybackPositionTicks")]
|
||||
pub playback_position_ticks: Option<i64>,
|
||||
|
||||
#[serde(rename = "PlayedPercentage")]
|
||||
pub played_percentage: Option<f64>,
|
||||
|
||||
#[serde(rename = "UnplayedItemCount")]
|
||||
pub unplayed_item_count: Option<i64>,
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct JfItem {
|
||||
#[serde(rename = "Id")]
|
||||
pub id: String,
|
||||
#[serde(rename = "Name")]
|
||||
pub name: String,
|
||||
#[serde(rename = "Type")]
|
||||
pub item_type: Option<String>,
|
||||
#[serde(rename = "ProductionYear")]
|
||||
pub production_year: Option<i32>,
|
||||
|
||||
#[serde(rename = "IndexNumber")]
|
||||
pub index_number: Option<i32>,
|
||||
#[serde(rename = "ParentIndexNumber")]
|
||||
pub parent_index_number: Option<i32>,
|
||||
|
||||
// ✅ add these
|
||||
#[serde(rename = "RunTimeTicks")]
|
||||
pub run_time_ticks: Option<i64>,
|
||||
|
||||
#[serde(rename = "Genres", default)]
|
||||
pub genres: Vec<String>,
|
||||
|
||||
#[serde(rename = "Studios", default)]
|
||||
pub studios: Vec<JfStudio>,
|
||||
|
||||
#[serde(rename = "Overview")]
|
||||
pub overview: Option<String>,
|
||||
|
||||
#[serde(rename = "SeriesName")]
|
||||
pub series_name: Option<String>,
|
||||
|
||||
#[serde(rename = "Album")]
|
||||
pub album: Option<String>,
|
||||
|
||||
#[serde(rename = "AlbumArtist")]
|
||||
pub album_artist: Option<String>,
|
||||
|
||||
#[serde(rename = "Artists", default)]
|
||||
pub artists: Vec<String>,
|
||||
|
||||
#[serde(rename = "UserData")]
|
||||
pub user_data: Option<JfUserData>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ItemsResponse {
|
||||
#[serde(rename = "Items")]
|
||||
items: Vec<JfItem>,
|
||||
#[serde(rename = "TotalRecordCount")]
|
||||
total_record_count: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct StudioDto {
|
||||
#[serde(rename = "Name")]
|
||||
pub name: Option<String>,
|
||||
}
|
||||
3
old_src/core/mod.rs
Normal file
3
old_src/core/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
pub mod config;
|
||||
pub mod jellyfin;
|
||||
pub mod paths;
|
||||
35
old_src/core/paths.rs
Normal file
35
old_src/core/paths.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use std::{env, path::PathBuf};
|
||||
|
||||
pub fn home_dir() -> Option<PathBuf> {
|
||||
env::var_os("HOME").map(PathBuf::from)
|
||||
}
|
||||
|
||||
pub fn config_dir() -> Option<PathBuf> {
|
||||
// XDG first, fallback to ~/.config
|
||||
if let Some(p) = env::var_os("XDG_CONFIG_HOME").map(PathBuf::from) {
|
||||
Some(p)
|
||||
} else {
|
||||
home_dir().map(|h| h.join(".config"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cache_dir() -> Option<PathBuf> {
|
||||
// XDG first, fallback to ~/.cache
|
||||
if let Some(p) = env::var_os("XDG_CACHE_HOME").map(PathBuf::from) {
|
||||
Some(p)
|
||||
} else {
|
||||
home_dir().map(|h| h.join(".cache"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn app_config_dir() -> Option<PathBuf> {
|
||||
config_dir().map(|d| d.join("cj-jftui"))
|
||||
}
|
||||
|
||||
pub fn app_cache_dir() -> Option<PathBuf> {
|
||||
cache_dir().map(|d| d.join("cj-jftui"))
|
||||
}
|
||||
|
||||
pub fn posters_cache_dir() -> Option<PathBuf> {
|
||||
app_cache_dir().map(|d| d.join("posters"))
|
||||
}
|
||||
Reference in New Issue
Block a user