not there yet but has potential

This commit is contained in:
2026-02-16 01:37:57 -06:00
parent aa4c4fc8e6
commit dfcf3fcf2a
7 changed files with 3425 additions and 78 deletions

131
old_src/core/config.rs Normal file
View 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
View 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
View File

@@ -0,0 +1,3 @@
pub mod config;
pub mod jellyfin;
pub mod paths;

35
old_src/core/paths.rs Normal file
View 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"))
}

2613
old_src/main.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -190,6 +190,9 @@ impl JellyfinClient {
if let Some(term) = query.search_term.as_deref() {
req = req.query(&[("SearchTerm", term)]);
}
if let Some(filters) = query.filters.as_deref() {
req = req.query(&[("Filters", filters)]);
}
let resp = req.send().map_err(|e| format!("request failed: {e}"))?;
@@ -209,6 +212,27 @@ impl JellyfinClient {
})
}
/// Returns true if there exists at least one resumable Episode under the given parent (Series or Season).
/// This is used to mark Series/Season rows as "in progress" even when Jellyfin doesn't populate
/// PlayedPercentage on those container types.
pub fn has_resumable_under(
&self,
user_id: &str,
parent_id: &str,
) -> Result<bool, String> {
// Series -> Season -> Episode, so this MUST be recursive for Series.
// Recursive=true is also fine for Season.
let mut q = LibraryQuery::all()
.with_parent(parent_id.to_string())
.with_item_types("Episode")
.with_filters("IsResumable");
q.recursive = true;
let page = self.list_items(user_id, q, 0, 1)?;
Ok(page.total > 0)
}
pub fn playlist_items(
&self,
user_id: &str,
@@ -255,6 +279,7 @@ pub struct LibraryQuery {
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
pub filters: Option<String>, // e.g. Some("IsResumable".into())
}
impl LibraryQuery {
@@ -264,6 +289,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
pub fn shows() -> Self {
@@ -272,6 +298,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
pub fn music() -> Self {
@@ -280,6 +307,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
@@ -290,6 +318,7 @@ impl LibraryQuery {
parent_id: None,
search_term: None,
recursive: true,
filters: None,
}
}
@@ -308,6 +337,11 @@ impl LibraryQuery {
self.include_item_types = Some(types.into());
self
}
pub fn with_filters(mut self, filters: impl Into<String>) -> Self {
self.filters = Some(filters.into());
self
}
}

View File

@@ -185,6 +185,9 @@ struct App {
transcode_on: bool,
transcode_mbps: u32,
// Cache: container item id -> has resumable episode under it
parent_progress: std::collections::HashMap<String, bool>,
}
#[derive(Debug)]
@@ -262,6 +265,7 @@ impl Default for App {
autoplay_prev_time_pos: None,
transcode_on: default_on,
transcode_mbps: default_mbps,
parent_progress: std::collections::HashMap::new(),
}
}
}
@@ -465,6 +469,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
match client.list_items(user_id, query.clone(), 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title,
query,
@@ -602,13 +607,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.mpv_now_playing = Some(item_name);
// If mpv running -> replace, else spawn
let url = build_jellyfin_play_url(
&cfg,
&item_id,
None,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_load_url(&cfg, mpv, &url) {
@@ -647,13 +646,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.autoplay_next_index = if selected + 1 < len { Some(selected + 1) } else { None };
// load/replace or spawn
let url = build_jellyfin_play_url(
&cfg,
&item_id,
None,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_load_url(&cfg, mpv, &url) {
@@ -706,17 +699,16 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.mpv_now_playing = Some(item_name);
let url = build_jellyfin_play_url(
&cfg,
&item_id,
start_ticks,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) {
Ok(_) => app.status = "mpv: resumed".into(),
Ok(_) => {
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&mpv.socket_path, ticks_to_seconds(t));
}
app.status = "mpv: resumed".into();
}
Err(e) => app.status = format!("mpv resume failed: {e}"),
}
} else {
@@ -724,7 +716,11 @@ fn handle_key(app: &mut App, code: KeyCode) {
Ok(mpv) => {
let rx = start_mpv_poller(mpv.socket_path.clone());
app.mpv_state_rx = Some(rx);
let sock = mpv.socket_path.clone();
app.mpv = Some(mpv);
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&sock, ticks_to_seconds(t));
}
app.status = "mpv: resumed".into();
}
Err(e) => app.status = format!("mpv spawn failed: {e}"),
@@ -757,17 +753,16 @@ fn handle_key(app: &mut App, code: KeyCode) {
app.autoplay_next_index = if selected + 1 < len { Some(selected + 1) } else { None };
app.autoplay_eof_latched = false;
let url = build_jellyfin_play_url(
&cfg,
&item_id,
start_ticks,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &item_id, app.transcode_on, app.transcode_mbps);
if let Some(mpv) = &app.mpv {
match mpv_cmd(&mpv.socket_path, &format!(r#"{{"command":["loadfile","{}","replace"]}}"#, url)) {
Ok(_) => app.status = "mpv: resumed (autoplay)".into(),
Ok(_) => {
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&mpv.socket_path, ticks_to_seconds(t));
}
app.status = "mpv: resumed (autoplay)".into();
}
Err(e) => app.status = format!("mpv resume failed: {e}"),
}
} else {
@@ -775,7 +770,11 @@ fn handle_key(app: &mut App, code: KeyCode) {
Ok(mpv) => {
let rx = start_mpv_poller(mpv.socket_path.clone());
app.mpv_state_rx = Some(rx);
let sock = mpv.socket_path.clone();
app.mpv = Some(mpv);
if let Some(t) = start_ticks {
let _ = mpv_seek_absolute(&sock, ticks_to_seconds(t));
}
app.status = "mpv: resumed (autoplay)".into();
}
Err(e) => app.status = format!("mpv spawn failed: {e}"),
@@ -849,6 +848,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
match client.list_items(user_id, query.clone(), 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title: cat,
query,
@@ -928,6 +928,7 @@ fn handle_key(app: &mut App, code: KeyCode) {
match client.playlist_items(user_id, &it.id, 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title: format!("{} > {}", title, it.name),
// store a query placeholder; playlist paging could be done later if you want
@@ -1087,6 +1088,8 @@ fn load_next_library_page(app: &mut App) {
Err(e) => { app.status = format!("Fetch failed: {e}"); finish_loading(app); return; }
};
update_parent_progress_cache(app, &client, user_id, &page.items);
if let Some(View::Library { items, total, .. }) = app.view_stack.last_mut() {
items.extend(page.items);
*total = page.total;
@@ -1101,6 +1104,33 @@ fn finish_loading(app: &mut App) {
}
}
fn update_parent_progress_cache(
app: &mut App,
client: &core::jellyfin::JellyfinClient,
user_id: &str,
new_items: &[core::jellyfin::JfItem],
) {
for it in new_items {
let ty = it.item_type.as_deref().unwrap_or("");
if ty != "Series" && ty != "Season" {
continue;
}
if app.parent_progress.contains_key(&it.id) {
continue;
}
match client.has_resumable_under(user_id, &it.id) {
Ok(has) => {
app.parent_progress.insert(it.id.clone(), has);
}
Err(_) => {
// If the server rejects the query, just leave it unknown.
}
}
}
}
fn maybe_prefetch(app: &mut App) {
const PREFETCH_ROWS: usize = 0;
@@ -1356,6 +1386,7 @@ fn ui(frame: &mut Frame, app: &App) {
render_library(
frame,
app,
title,
*start_index,
*total,
@@ -1496,6 +1527,7 @@ fn render_placeholder(frame: &mut Frame, name: &str, left: Rect, right: Rect) {
fn render_library(
frame: &mut Frame,
app: &App,
title: &str,
start_index: usize,
total: usize,
@@ -1552,7 +1584,7 @@ fn render_library(
true
})
.map(|it| {
let emoji = emoji_prefix_for(it);
let emoji = emoji_prefix_for(app, it);
let prefix = left_number_prefix(it, show_audio_track_numbers);
let year = if show_year_for(it.item_type.as_deref()) {
it.production_year.map(|y| format!(" ({y})")).unwrap_or_default()
@@ -1610,6 +1642,7 @@ fn open_children(app: &mut App, title: String, query: core::jellyfin::LibraryQue
match client.list_items(user_id, query.clone(), 0, PAGE_SIZE) {
Ok(page) => {
update_parent_progress_cache(app, &client, user_id, &page.items);
app.view_stack.push(View::Library {
title,
query,
@@ -1708,6 +1741,35 @@ fn mpv_cmd(socket: &PathBuf, cmd: &str) -> Result<(), String> {
mpv_send(socket, &format!("{cmd}\n"))
}
fn ticks_to_seconds(ticks: u64) -> f64 {
// Jellyfin ticks are 10,000,000 per second
(ticks as f64) / 10_000_000.0
}
fn mpv_seek_absolute(socket: &PathBuf, seconds: f64) -> Result<(), String> {
// Wait until mpv has loaded something real (duration becomes available),
// then issue a seek and REQUIRE a success reply.
let seek_cmd = format!(r#"{{"command":["seek",{}, "absolute"]}}"#, seconds);
let start = Instant::now();
while start.elapsed() < Duration::from_millis(2500) {
// duration being Some is a good signal that the file is actually ready
let dur = mpv_get_f64_jtui(socket, "duration", 1).ok().flatten();
if dur.is_some() {
// seek, but only accept success
if mpv_cmd_reply(socket, &seek_cmd).is_ok() {
return Ok(());
}
}
thread::sleep(Duration::from_millis(50));
}
Err("mpv seek failed (mpv never became ready or rejected seek)".into())
}
fn spawn_mpv(cfg: &core::config::Config, first_item_id: &str) -> Result<MpvSession, String> {
let token = cfg
.access_token
@@ -1972,13 +2034,7 @@ fn autoplay_tick(app: &mut App) {
};
// Load next item
let url = build_jellyfin_play_url(
&cfg,
&next_id,
None,
app.transcode_on,
app.transcode_mbps,
);
let url = build_jellyfin_play_url(&cfg, &next_id, app.transcode_on, app.transcode_mbps);
if let Err(e) = mpv_load_url(&cfg, mpv, &url) {
app.autoplay = false;
@@ -2384,28 +2440,68 @@ fn is_played(it: &core::jellyfin::JfItem) -> bool {
if it.user_data.as_ref().and_then(|u| u.played) == Some(true) {
return true;
}
// seasons/series often use percentage
match it.user_data.as_ref().and_then(|u| u.played_percentage) {
Some(p) if p >= 99.9 => true,
_ => false,
// If Jellyfin provides played percentage
if let Some(p) = it.user_data.as_ref().and_then(|u| u.played_percentage) {
if p >= 99.9 {
return true;
}
}
fn is_in_progress(it: &core::jellyfin::JfItem) -> bool {
if is_played(it) { return false; }
// Series/Season often only has UnplayedItemCount
if matches!(it.item_type.as_deref(), Some("Series" | "Season")) {
if it.user_data.as_ref().and_then(|u| u.unplayed_item_count) == Some(0) {
return true;
}
}
false
}
fn is_in_progress_with_cache(app: &App, it: &core::jellyfin::JfItem) -> bool {
if is_played(it) {
return false;
}
// movies/episodes
if playback_position_ticks(it).is_some() {
return true;
}
// seasons/series (some servers expose %)
// series/seasons: ask cache first (based on resumable episodes)
if matches!(it.item_type.as_deref(), Some("Series") | Some("Season")) {
if let Some(v) = app.parent_progress.get(&it.id) {
return *v;
}
}
// fallback: percentage-based if server provides it
match it.user_data.as_ref().and_then(|u| u.played_percentage) {
Some(p) if p > 0.1 && p < 99.9 => true,
_ => false,
}
}
fn is_in_progress(it: &core::jellyfin::JfItem) -> bool {
if is_played(it) {
return false;
}
// movies/episodes
if playback_position_ticks(it).is_some() {
return true;
}
// series/seasons (percentage-based)
match it.user_data.as_ref().and_then(|u| u.played_percentage) {
Some(p) if p > 0.1 && p < 99.9 => true,
_ => false,
}
}
fn playback_position_ticks(it: &core::jellyfin::JfItem) -> Option<u64> {
it.user_data
.as_ref()
@@ -2413,26 +2509,24 @@ fn playback_position_ticks(it: &core::jellyfin::JfItem) -> Option<u64> {
.and_then(|v| if v > 0 { Some(v as u64) } else { None })
}
fn emoji_prefix_for(it: &core::jellyfin::JfItem) -> &'static str {
// user asked: no emoji for music
fn emoji_prefix_for(app: &App, it: &core::jellyfin::JfItem) -> &'static str {
// no emoji for music
if is_music_item(it) {
return "";
}
let dl = is_downloaded(it);
let played = is_played(it);
let prog = is_in_progress(it);
let prog = is_in_progress_with_cache(app, it);
match (dl, played, prog) {
(true, true, _) => "💾",
(true, false, true) => "💾▶ ",
(true, false, false) => "💾 ",
(false, true, _) => "",
(false, false, true) => "",
(false, false, false) => "",
match (played, prog) {
(true, _) => "",
(false, true) => "🟠 ", // orange in-progress
(false, false) => "",
}
}
// --- transcoding + resume URL builder (Approach B) ---
fn clamp_mbps_to_bps(mbps: u32) -> u32 {
mbps.saturating_mul(1_000_000) // Mb/s -> bits/s
@@ -2441,39 +2535,51 @@ fn clamp_mbps_to_bps(mbps: u32) -> u32 {
fn build_jellyfin_play_url(
cfg: &core::config::Config,
item_id: &str,
start_ticks: Option<u64>,
transcode_on: bool,
transcode_mbps: u32,
) -> String {
let base = cfg.base_url.trim_end_matches('/');
if !transcode_on {
return format!("{}/Items/{}/Download", base, item_id);
}
let token = cfg
.access_token
.as_deref()
.unwrap_or(""); // if empty, server likely rejects anyway
let bps = clamp_mbps_to_bps(transcode_mbps);
// Use maxStreamingBitrate (what Jellyfin UIs commonly use)
// Use static=false (lets server do normal streaming behavior)
let mut url = format!("{}/Videos/{}/stream?static=false", base, item_id);
if !transcode_on {
// Direct stream.
//
// We intentionally keep this "static=true" so mpv can see the full timeline/duration
// (many servers provide Content-Length only for static streams).
//
// Resume is implemented via mpv seeking (not startTimeTicks in the URL) to avoid the
// Jellyfin behavior where startTimeTicks may be ignored for static streams.
return format!(
"{}/Videos/{}/stream?static=true&api_key={}",
base, item_id, token
);
}
// Transcoded stream via HLS (fixes "duration == buffered" + enables seeking).
//
// IMPORTANT: Use Jellyfin's documented query param names:
// - videoBitRate (capital R)
// - segmentContainer
//
// Resume is implemented via mpv seeking (not startTimeTicks in the URL).
let mut url = format!(
"{}/Videos/{}/master.m3u8?api_key={}&static=false",
base, item_id, token
);
url.push_str(&format!("&maxStreamingBitrate={}", bps));
// IMPORTANT:
// - enableAutoStreamCopy=true = will NOT transcode if it can direct stream
// - set to false to FORCE transcode behavior (good for testing)
//
// For now: force it so you can verify it works.
url.push_str(&format!("&videoBitrate={}", bps)); // NOTE: lower-case 'r' matches your working version
url.push_str(&format!("&audioBitrate={}", bps));
url.push_str("&enableAutoStreamCopy=false");
// Make transcode more likely / deterministic:
url.push_str("&videoCodec=h264");
url.push_str("&audioCodec=aac");
url.push_str("&transcodingContainer=mp4");
if let Some(t) = start_ticks {
url.push_str(&format!("&startTimeTicks={}", t));
}
url.push_str("&transcodingContainer=ts"); // NOTE: this is what your working build used
url
}
@@ -2481,7 +2587,6 @@ fn build_jellyfin_play_url(
fn reload_config(app: &mut App) {
if let Ok(cfg) = core::config::load_config() {
app.transcode_mbps = cfg.transcode_mbps.unwrap_or(5);
@@ -2493,8 +2598,36 @@ fn reload_config(app: &mut App) {
}
}
fn mpv_cmd_reply(socket: &PathBuf, cmd: &str) -> Result<Value, String> {
let mut stream = UnixStream::connect(socket)
.map_err(|e| format!("mpv ipc connect failed: {e}"))?;
let _ = stream.set_write_timeout(Some(Duration::from_millis(500)));
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
stream
.write_all(format!("{cmd}\n").as_bytes())
.map_err(|e| format!("mpv ipc write failed: {e}"))?;
let mut reader = BufReader::new(stream);
let mut line = String::new();
reader
.read_line(&mut line)
.map_err(|e| format!("mpv ipc read failed: {e}"))?;
if line.trim().is_empty() {
return Err("mpv ipc: empty response".into());
}
let v: Value = serde_json::from_str(line.trim())
.map_err(|e| format!("mpv json parse failed: {e} ({})", line.trim()))?;
if v.get("error").and_then(|e| e.as_str()) != Some("success") {
return Err(format!("mpv command failed: {}", line.trim()));
}
Ok(v)
}