Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

feat(playback): add real-time mpv tracking, progress resume, and resilient history reconciliation

Samir Hossains07e40a3e67a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d03d867..dc58057 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,11 @@
## [Unreleased]
### Added
+- **Playback Tracking & Watch History Progress**:
+ - Added real-time playback position tracking for `mpv` with injected tracker script (`moviebox_tracker.lua`) and 5-second periodic state auto-save to disk.
+ - Added automatic startup state reconciliation (`reconcile_pending_playback_states`) ensuring watched progress is preserved even when closing the terminal or killing tmux mid-playback.
+ - Added two-tone smooth scrub line progress bars (`━─────── 1% (2h 18m left) • Watched 11h ago`) and completion status badges (`[✓ Completed]`, `[✓ Watched]`) in `/history` and Details screens.
+ - Added cross-provider title-based history deduplication and auto-resume from the last watched position.
- **Addon Mode (Community HTTP Addons)**:
- Added full support for community HTTP addon manifests (`/manifest.json`, `/catalog`, `/meta`, `/stream`) with dedicated `Ctrl+A` mode switching.
- Pre-installed and locked Cinemeta out-of-the-box as the default core metadata provider with zero API keys required.
diff --git a/docs/architecture.md b/docs/architecture.md
index 4a5eb26..442c720 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -111,6 +111,8 @@ interval, forwarding them into the action channel (capacity 128).
- `addons_config.json` — installed HTTP community addons in the config dir.
- `tv_config.json` — user M3U playlist sources (URLs or file paths) in the config dir.
- `history.json` — watch history in the system data dir.
+- `playback/` — temporary playback states for session crash/kill reconciliation in the system data dir.
+- `scripts/` — bundled player scripts (`moviebox_tracker.lua`) in the system data dir.
- Cache lives under the system cache dir, keyed per provider.
- Logs live under the system data dir with rotation.
diff --git a/docs/config.md b/docs/config.md
index 6de25f8..1508fb5 100644
--- a/docs/config.md
+++ b/docs/config.md
@@ -24,6 +24,8 @@ macOS `~/Library/Application Support/moviebox-tui`, Linux `~/.config/moviebox-tu
- `addons_config.json` — list of installed HTTP addons in the config directory (see [addons-mode.md](addons-mode.md)).
- `tv_config.json` — list of M3U playlist sources in the config directory (see [tv-mode.md](tv-mode.md)).
- `history.json` — watch history in the system data directory (`dirs::data_dir()/moviebox-tui/`).
+- `playback/` — temporary playback states in the system data directory for resilient progress tracking.
+- `scripts/` — bundled player scripts (`moviebox_tracker.lua`) in the system data directory.
- `iptv_cache/` — legacy TV image cache directory that `ClearCache` still removes.
## Environment variables
diff --git a/docs/modules.md b/docs/modules.md
index 4db0211..a50c92a 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -34,6 +34,9 @@ src/
player.rs Player detection (OnceLock) and command construction for
mpv / VLC / IINA / Android intent, subtitle args, headers,
terminal-sized window.
+ player/
+ tracker.rs Injected Lua tracker script (`moviebox_tracker.lua`) and
+ periodic 5-second playback state auto-saving.
providers/
mod.rs Module declarations.
diff --git a/docs/players.md b/docs/players.md
index 62e8d97..a96848a 100644
--- a/docs/players.md
+++ b/docs/players.md
@@ -21,9 +21,9 @@ detected player and saves the chosen player as the next default unless
| Player | Invocation | Notes |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
-| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Flatpak mpv is launched via `flatpak run`. |
-| VLC | `vlc --width=W --height=H --play-and-exit [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | |
-| IINA | `iina-cli --keep-running --no-stdin --mpv-autofit=.. --mpv-http-header-fields=.. --mpv-sub-files=.. <url>` | Uses the bundled `iina-cli`; falls back to `open -a IINA <url>` only if the CLI is absent. |
+| mpv | `mpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [--start=..] [--script=..] [--script-opts=..] [--http-header-fields=..] [--sub-file=..] <url>` | Window sized to the terminal. Injects `moviebox_tracker.lua` for position tracking and resume. Flatpak mpv is launched via `flatpak run`. |
+| VLC | `vlc --width=W --height=H --play-and-exit [--start-time=..] [--http-referrer=..] [--http-user-agent=..] [--sub-file=..] <url>` | Supports start time resume via `--start-time`. |
+| IINA | `iina-cli --keep-running --no-stdin --mpv-autofit=.. [--mpv-start=..] --mpv-http-header-fields=.. --mpv-sub-files=.. <url>` | Uses the bundled `iina-cli`; falls back to `open -a IINA <url>` only if the CLI is absent. |
| Android / Proot | `termux-open --chooser --content-type video/* <url>` (or absolute `/system/bin/am start` fallback, ensuring `.so` injections are dropped) | Opens an app chooser on the device. Device-specific chooser behavior should be confirmed for each release. |
Window size is derived from the live terminal size times the font cell size reported
@@ -46,9 +46,17 @@ player cannot satisfy a source's headers.
headers. On failure a status is shown and playback continues without subtitles.
- Temp files are cleaned up after the player exits and purged at startup if stale.
+## Playback Tracking & Resume
+
+When launching media with in-progress watch history, the player command automatically
+includes the starting position (`--start` / `--mpv-start` / `--start-time`). For `mpv`,
+`src/player/tracker.rs` writes a companion tracker script (`moviebox_tracker.lua`) that
+observes `time-pos` and `duration`, periodically saving playback state every 5 seconds to
+the local data directory. On startup or after player exit, pending playback states are
+reconciled into `history.json`.
+
## Spawning
`launch_player` spawns the player with null stdin/stdout, piped stderr, and its own
process group (Unix) or no-console flag (Windows). A blocking task reads stderr and
reports a crash if the process exits non-zero within a few seconds with output.
-Watch history is marked on launch.
diff --git a/src/history.rs b/src/history.rs
index 6419b6a..7f58243 100644
--- a/src/history.rs
+++ b/src/history.rs
@@ -14,6 +14,129 @@ pub struct WatchHistoryItem {
pub season: usize,
pub episode: usize,
pub timestamp: u64,
+ #[serde(default)]
+ pub duration_seconds: Option<u64>,
+ #[serde(default)]
+ pub progress_seconds: u64,
+ #[serde(default)]
+ pub completed: bool,
+}
+
+impl WatchHistoryItem {
+ pub fn is_in_progress(&self) -> bool {
+ if self.completed {
+ return false;
+ }
+ if self.progress_seconds < 30 {
+ return false;
+ }
+ if let Some(dur) = self.duration_seconds {
+ if dur > 0 && self.progress_seconds >= (dur as f64 * 0.90) as u64 {
+ return false;
+ }
+ }
+ true
+ }
+
+ pub fn progress_percentage(&self) -> Option<f32> {
+ self.duration_seconds
+ .filter(|&d| d > 0)
+ .map(|d| ((self.progress_seconds as f32 / d as f32) * 100.0).clamp(0.0, 100.0))
+ }
+
+ pub fn progress_bar_parts(&self, width: usize) -> (String, String) {
+ let pct = self.progress_percentage().unwrap_or(0.0) / 100.0;
+ let filled = if pct > 0.0 {
+ ((width as f32 * pct).round() as usize).max(1).min(width)
+ } else {
+ 0
+ };
+ let empty = width.saturating_sub(filled);
+ ("━".repeat(filled), "─".repeat(empty))
+ }
+
+ pub fn progress_bar(&self, width: usize) -> String {
+ let (filled, empty) = self.progress_bar_parts(width);
+ format!("{filled}{empty}")
+ }
+
+ pub fn formatted_progress(&self) -> String {
+ let pos = format_time(self.progress_seconds);
+ if let Some(dur) = self.duration_seconds {
+ if dur > 0 {
+ return format!("{} / {}", pos, format_time(dur));
+ }
+ }
+ pos
+ }
+
+ pub fn formatted_remaining(&self) -> Option<String> {
+ let dur = self.duration_seconds?;
+ if dur <= self.progress_seconds {
+ return None;
+ }
+ let remaining = dur.saturating_sub(self.progress_seconds);
+ if remaining < 60 {
+ Some("< 1m left".to_string())
+ } else if remaining < 3600 {
+ Some(format!("{}m left", remaining / 60))
+ } else {
+ let h = remaining / 3600;
+ let m = (remaining % 3600) / 60;
+ if m == 0 {
+ Some(format!("{h}h left"))
+ } else {
+ Some(format!("{h}h {m}m left"))
+ }
+ }
+ }
+
+ pub fn formatted_relative_time(&self) -> String {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+ if self.timestamp == 0 || now < self.timestamp {
+ return "recently".to_string();
+ }
+ let delta = now - self.timestamp;
+ if delta < 60 {
+ "just now".to_string()
+ } else if delta < 3600 {
+ format!("{}m ago", delta / 60)
+ } else if delta < 86400 {
+ format!("{}h ago", delta / 3600)
+ } else if delta < 172800 {
+ "Yesterday".to_string()
+ } else if delta < 604800 {
+ format!("{}d ago", delta / 86400)
+ } else {
+ format!("{}w ago", delta / 604800)
+ }
+ }
+}
+
+fn format_time(secs: u64) -> String {
+ let h = secs / 3600;
+ let m = (secs % 3600) / 60;
+ let s = secs % 60;
+ if h > 0 {
+ format!("{h}:{m:02}:{s:02}")
+ } else {
+ format!("{m}:{s:02}")
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PendingPlaybackState {
+ pub provider: String,
+ pub subject_id: String,
+ pub season: usize,
+ pub episode: usize,
+ pub progress_seconds: u64,
+ pub duration_seconds: Option<u64>,
+ pub completed: bool,
+ pub timestamp: u64,
}
#[derive(Default, Clone, Serialize, Deserialize)]
@@ -26,18 +149,28 @@ pub struct HistoryManager {
impl HistoryManager {
pub fn new() -> Self {
- if let Some(path) = Self::history_file_path() {
+ let mut history = if let Some(path) = Self::history_file_path() {
if path.exists() {
if let Ok(content) = fs::read_to_string(&path) {
- if let Ok(mut history) = serde_json::from_str::<Self>(&content) {
- history.hydrate_watched_index();
- return history;
+ if let Ok(mut hist) = serde_json::from_str::<Self>(&content) {
+ hist.hydrate_watched_index();
+ hist
+ } else {
+ let _ = fs::remove_file(&path);
+ Self::default()
}
+ } else {
+ Self::default()
}
- let _ = fs::remove_file(path);
+ } else {
+ Self::default()
}
- }
- Self::default()
+ } else {
+ Self::default()
+ };
+
+ history.reconcile_pending_playback_states();
+ history
}
fn history_file_path() -> Option<PathBuf> {
@@ -50,6 +183,16 @@ impl HistoryManager {
Some(path)
}
+ pub fn playback_state_dir() -> Option<PathBuf> {
+ let mut path = dirs::data_dir()?;
+ path.push(crate::config::APP_NAME);
+ path.push("playback");
+ if !path.exists() {
+ let _ = fs::create_dir_all(&path);
+ }
+ Some(path)
+ }
+
pub fn save(&self) {
if let Some(path) = Self::history_file_path() {
if let Ok(content) = serde_json::to_string(self) {
@@ -61,7 +204,10 @@ impl HistoryManager {
}
fn key(provider: &str, subject_id: &str, season: usize, episode: usize) -> String {
- format!("{provider}::{subject_id}::{season}::{episode}")
+ let canon_provider = crate::providers::models::ProviderKind::parse(provider)
+ .map(|p| p.cache_key())
+ .unwrap_or(provider);
+ format!("{canon_provider}::{subject_id}::{season}::{episode}")
}
pub fn is_same_show(a: &WatchHistoryItem, b: &WatchHistoryItem) -> bool {
@@ -71,12 +217,11 @@ impl HistoryManager {
(Some(pa), Some(pb)) => pa == pb,
_ => a.provider.trim().eq_ignore_ascii_case(b.provider.trim()),
};
- if !same_provider {
- return false;
- }
- if !a.subject_id.is_empty() && a.subject_id == b.subject_id {
+
+ if same_provider && !a.subject_id.is_empty() && a.subject_id == b.subject_id {
return true;
}
+
let clean_a = crate::providers::moviebox::clean_moviebox_title(&a.title);
let clean_b = crate::providers::moviebox::clean_moviebox_title(&b.title);
if !clean_a.is_empty() && clean_a.eq_ignore_ascii_case(&clean_b) {
@@ -90,16 +235,17 @@ impl HistoryManager {
self.watched = self
.recent
.iter()
+ .filter(|item| item.completed)
.map(|item| Self::key(&item.provider, &item.subject_id, item.season, item.episode))
.collect();
} else {
- for item in &self.recent {
- self.watched.insert(Self::key(
- &item.provider,
- &item.subject_id,
- item.season,
- item.episode,
- ));
+ for item in &mut self.recent {
+ let key = Self::key(&item.provider, &item.subject_id, item.season, item.episode);
+ if self.watched.contains(&key) {
+ item.completed = true;
+ } else if item.completed {
+ self.watched.insert(key);
+ }
}
}
self.consolidate_recent();
@@ -138,7 +284,50 @@ impl HistoryManager {
}
}
+ pub fn get_item(
+ &self,
+ provider: &str,
+ subject_id: &str,
+ season: usize,
+ episode: usize,
+ title: Option<&str>,
+ ) -> Option<&WatchHistoryItem> {
+ self.recent.iter().find(|i| {
+ let same_provider = crate::providers::models::ProviderKind::parse(&i.provider)
+ .zip(crate::providers::models::ProviderKind::parse(provider))
+ .map_or_else(
+ || i.provider.trim().eq_ignore_ascii_case(provider.trim()),
+ |(p1, p2)| p1 == p2,
+ );
+
+ if same_provider && i.subject_id == subject_id {
+ if i.stype == 1 {
+ return true;
+ }
+ if i.season == season && i.episode == episode {
+ return true;
+ }
+ }
+
+ if let Some(t) = title {
+ let clean_i = crate::providers::moviebox::clean_moviebox_title(&i.title);
+ let clean_t = crate::providers::moviebox::clean_moviebox_title(t);
+ if !clean_i.is_empty() && clean_i.eq_ignore_ascii_case(&clean_t) {
+ if i.stype == 1 {
+ return true;
+ }
+ if i.season == season && i.episode == episode {
+ return true;
+ }
+ }
+ }
+
+ false
+ })
+ }
+
pub fn mark_watched(&mut self, mut item: WatchHistoryItem) {
+ item.completed = true;
let key = Self::key(&item.provider, &item.subject_id, item.season, item.episode);
self.watched.insert(key);
@@ -162,6 +351,73 @@ impl HistoryManager {
}
}
+ pub fn update_progress(
+ &mut self,
+ mut item: WatchHistoryItem,
+ progress: u64,
+ duration: Option<u64>,
+ completed: bool,
+ ) {
+ item.progress_seconds = progress;
+ item.duration_seconds = duration;
+ item.completed = completed;
+ item.timestamp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+
+ let key = Self::key(&item.provider, &item.subject_id, item.season, item.episode);
+ if completed {
+ self.watched.insert(key);
+ } else {
+ self.watched.remove(&key);
+ }
+
+ if item.cover_url.is_none() {
+ if let Some(existing) = self
+ .recent
+ .iter()
+ .find(|i| Self::is_same_show(i, &item))
+ .and_then(|i| i.cover_url.clone())
+ {
+ item.cover_url = Some(existing);
+ }
+ }
+
+ self.recent.retain(|i| !Self::is_same_show(i, &item));
+ self.recent.push(item);
+
+ if self.recent.len() > 100 {
+ let excess = self.recent.len() - 100;
+ self.recent.drain(0..excess);
+ }
+ self.save();
+ }
+
+ pub fn remove(&mut self, provider: &str, subject_id: &str, season: usize, episode: usize) {
+ let key = Self::key(provider, subject_id, season, episode);
+ self.watched.remove(&key);
+ self.recent.retain(|i| {
+ let same_provider = crate::providers::models::ProviderKind::parse(&i.provider)
+ .zip(crate::providers::models::ProviderKind::parse(provider))
+ .map_or_else(
+ || i.provider.trim().eq_ignore_ascii_case(provider.trim()),
+ |(p1, p2)| p1 == p2,
+ );
+ !(same_provider
+ && i.subject_id == subject_id
+ && i.season == season
+ && i.episode == episode)
+ });
+ self.save();
+ }
+
+ pub fn clear(&mut self) {
+ self.watched.clear();
+ self.recent.clear();
+ self.save();
+ }
+
pub fn update_cover_url(&mut self, subject_id: &str, cover_url: &str) {
let mut modified = false;
for item in &mut self.recent {
@@ -183,6 +439,79 @@ impl HistoryManager {
episode: usize,
) -> bool {
let key = Self::key(provider, subject_id, season, episode);
- self.watched.contains(&key)
+ if self.watched.contains(&key) {
+ return true;
+ }
+ if let Some(item) = self.get_item(provider, subject_id, season, episode, None) {
+ return item.completed;
+ }
+ false
+ }
+
+ pub fn reconcile_pending_playback_states(&mut self) {
+ let Some(dir) = Self::playback_state_dir() else {
+ return;
+ };
+ let Ok(entries) = fs::read_dir(&dir) else {
+ return;
+ };
+
+ let mut modified = false;
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.extension().and_then(|e| e.to_str()) == Some("json") {
+ if let Ok(content) = fs::read_to_string(&path) {
+ if let Ok(state) = serde_json::from_str::<PendingPlaybackState>(&content) {
+ if let Some(existing) = self.recent.iter_mut().find(|i| {
+ let same_provider =
+ crate::providers::models::ProviderKind::parse(&i.provider)
+ .zip(crate::providers::models::ProviderKind::parse(
+ &state.provider,
+ ))
+ .map_or_else(
+ || {
+ i.provider
+ .trim()
+ .eq_ignore_ascii_case(state.provider.trim())
+ },
+ |(p1, p2)| p1 == p2,
+ );
+ if !same_provider {
+ return false;
+ }
+ if i.subject_id == state.subject_id {
+ if i.stype == 1 {
+ return true;
+ }
+ return i.season == state.season && i.episode == state.episode;
+ }
+ false
+ }) {
+ existing.progress_seconds = state.progress_seconds;
+ existing.duration_seconds = state.duration_seconds;
+ existing.completed = state.completed;
+ existing.timestamp = state.timestamp;
+ let key = Self::key(
+ &existing.provider,
+ &existing.subject_id,
+ existing.season,
+ existing.episode,
+ );
+ if existing.completed {
+ self.watched.insert(key);
+ } else {
+ self.watched.remove(&key);
+ }
+ modified = true;
+ }
+ }
+ }
+ let _ = fs::remove_file(&path);
+ }
+ }
+
+ if modified {
+ self.save();
+ }
}
}
diff --git a/src/player.rs b/src/player.rs
index 3918149..1a9c623 100644
--- a/src/player.rs
+++ b/src/player.rs
@@ -1,3 +1,5 @@
+pub mod tracker;
+
use std::{path::Path, process::Command};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -92,11 +94,21 @@ pub fn command(
subtitle: Option<&str>,
headers: &[(String, String)],
window: Option<(u32, u32)>,
+ resume_seconds: Option<u64>,
+ tracker: Option<(&str, &str, usize, usize)>,
) -> Command {
match kind {
- PlayerKind::Mpv => mpv_command(url, subtitle, headers, false, window),
- PlayerKind::Iina => iina_command(url, subtitle, headers, window),
- PlayerKind::Vlc => vlc_command(url, subtitle, headers, window),
+ PlayerKind::Mpv => mpv_command(
+ url,
+ subtitle,
+ headers,
+ false,
+ window,
+ resume_seconds,
+ tracker,
+ ),
+ PlayerKind::Iina => iina_command(url, subtitle, headers, window, resume_seconds, tracker),
+ PlayerKind::Vlc => vlc_command(url, subtitle, headers, window, resume_seconds),
PlayerKind::AndroidIntent => android_intent_command(url),
}
}
@@ -141,6 +153,8 @@ fn mpv_command(
headers: &[(String, String)],
iina: bool,
window: Option<(u32, u32)>,
+ resume_seconds: Option<u64>,
+ tracker: Option<(&str, &str, usize, usize)>,
) -> Command {
let fallback = if cfg!(target_os = "windows") {
"mpv.exe"
@@ -173,6 +187,27 @@ fn mpv_command(
command.arg("--idle=no").arg("--keep-open=no");
}
+ if let Some(start) = resume_seconds {
+ if start > 0 {
+ command.arg(format!("{prefix}start={start}"));
+ }
+ }
+
+ if let Some((provider, subject_id, season, episode)) = tracker {
+ if let Some(script_path) = tracker::ensure_tracker_script() {
+ command.arg(format!("{prefix}script={}", script_path.display()));
+ if let Some(state_file) =
+ tracker::state_file_path(provider, subject_id, season, episode)
+ {
+ let opts = format!(
+ "moviebox-provider={provider},moviebox-subject_id={subject_id},moviebox-season={season},moviebox-episode={episode},moviebox-state_file={}",
+ state_file.display()
+ );
+ command.arg(format!("{prefix}script-opts={opts}"));
+ }
+ }
+ }
+
if !headers.is_empty() {
let fields = headers
.iter()
@@ -211,6 +246,8 @@ fn iina_command(
subtitle: Option<&str>,
headers: &[(String, String)],
window: Option<(u32, u32)>,
+ resume_seconds: Option<u64>,
+ tracker: Option<(&str, &str, usize, usize)>,
) -> Command {
let configured = configured_executable("MOVIEBOX_IINA_PATH");
let cli_global = std::path::Path::new("/Applications/IINA.app/Contents/MacOS/iina-cli");
@@ -236,7 +273,15 @@ fn iina_command(
Command::new("iina")
};
- let mpv = mpv_command(url, subtitle, headers, true, window);
+ let mpv = mpv_command(
+ url,
+ subtitle,
+ headers,
+ true,
+ window,
+ resume_seconds,
+ tracker,
+ );
for arg in mpv.get_args() {
command.arg(arg);
}
@@ -249,8 +294,18 @@ fn iina_command(
subtitle: Option<&str>,
headers: &[(String, String)],
window: Option<(u32, u32)>,
+ resume_seconds: Option<u64>,
+ tracker: Option<(&str, &str, usize, usize)>,
) -> Command {
- mpv_command(url, subtitle, headers, false, window)
+ mpv_command(
+ url,
+ subtitle,
+ headers,
+ false,
+ window,
+ resume_seconds,
+ tracker,
+ )
}
fn vlc_command(
@@ -258,6 +313,7 @@ fn vlc_command(
subtitle: Option<&str>,
headers: &[(String, String)],
window: Option<(u32, u32)>,
+ resume_seconds: Option<u64>,
) -> Command {
let fallback = if cfg!(target_os = "windows") {
"vlc.exe"
@@ -286,6 +342,12 @@ fn vlc_command(
}
command.arg("--play-and-exit");
+ if let Some(start) = resume_seconds {
+ if start > 0 {
+ command.arg(format!("--start-time={start}"));
+ }
+ }
+
for (name, value) in headers {
if name.eq_ignore_ascii_case("referer") {
command.arg(format!("--http-referrer={value}"));
diff --git a/src/player/tracker.rs b/src/player/tracker.rs
new file mode 100644
index 0000000..a7757f7
--- /dev/null
+++ b/src/player/tracker.rs
@@ -0,0 +1,105 @@
+use std::fs;
+use std::path::PathBuf;
+
+const TRACKER_LUA_CONTENT: &str = r#"local options = require 'mp.options'
+
+local opts = {
+ provider = "",
+ subject_id = "",
+ season = 0,
+ episode = 0,
+ state_file = "",
+}
+options.read_options(opts, "moviebox")
+
+local last_pos = 0
+local last_dur = 0
+
+mp.observe_property("time-pos", "number", function(name, val)
+ if val then
+ last_pos = val
+ end
+end)
+
+mp.observe_property("duration", "number", function(name, val)
+ if val then
+ last_dur = val
+ end
+end)
+
+local function write_state(force_completed)
+ if opts.state_file == "" then return end
+ if last_dur <= 0 and last_pos <= 0 then return end
+
+ local completed = force_completed or (last_dur > 0 and last_pos >= (0.90 * last_dur))
+ local now = os.time()
+
+ local json = string.format(
+ '{"provider":%q,"subject_id":%q,"season":%d,"episode":%d,"progress_seconds":%d,"duration_seconds":%d,"completed":%s,"timestamp":%d}',
+ opts.provider,
+ opts.subject_id,
+ tonumber(opts.season) or 0,
+ tonumber(opts.episode) or 0,
+ math.floor(last_pos + 0.5),
+ math.floor(last_dur + 0.5),
+ completed and "true" or "false",
+ now
+ )
+
+ local f = io.open(opts.state_file, "w")
+ if f then
+ f:write(json)
+ f:close()
+ end
+end
+
+mp.register_event("end-file", function(event)
+ if event and event.reason == "eof" then
+ write_state(true)
+ end
+end)
+
+mp.register_event("shutdown", function()
+ write_state(false)
+end)
+
+mp.add_periodic_timer(5, function()
+ write_state(false)
+end)
+"#;
+
+pub fn ensure_tracker_script() -> Option<PathBuf> {
+ let mut path = dirs::data_dir()?;
+ path.push(crate::config::APP_NAME);
+ path.push("scripts");
+ if !path.exists() {
+ let _ = fs::create_dir_all(&path);
+ }
+ path.push("moviebox_tracker.lua");
+ if !path.exists()
+ || fs::read_to_string(&path)
+ .map(|c| c != TRACKER_LUA_CONTENT)
+ .unwrap_or(true)
+ {
+ let _ = fs::write(&path, TRACKER_LUA_CONTENT.as_bytes());
+ }
+ Some(path)
+}
+
+pub fn state_file_path(
+ provider: &str,
+ subject_id: &str,
+ season: usize,
+ episode: usize,
+) -> Option<PathBuf> {
+ let mut path = dirs::data_dir()?;
+ path.push(crate::config::APP_NAME);
+ path.push("playback");
+ if !path.exists() {
+ let _ = fs::create_dir_all(&path);
+ }
+ let sanitized_id = subject_id.replace(['/', '\\', ':', ' '], "_");
+ let filename = format!("{provider}_{sanitized_id}_{season}_{episode}.json");
+ path.push(filename);
+ Some(path)
+}
diff --git a/src/tui/action.rs b/src/tui/action.rs
index 183fb9e..67e5ddb 100644
--- a/src/tui/action.rs
+++ b/src/tui/action.rs
@@ -132,5 +132,12 @@ pub enum Action {
crate::providers::models::PlaybackSource,
),
MarkWatched(crate::history::WatchHistoryItem),
+ UpdateProgress {
+ item: crate::history::WatchHistoryItem,
+ progress: u64,
+ duration: Option<u64>,
+ completed: bool,
+ },
+ ReconcileHistory,
PlayerCrashed(Option<i32>, String),
}
diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rs
index 1fd5d39..0f94550 100644
--- a/src/tui/app/keyboard.rs
+++ b/src/tui/app/keyboard.rs
@@ -210,7 +210,9 @@ impl App {
};
if !query.is_empty() {
- if query.starts_with('/') {
+ if query.trim().eq_ignore_ascii_case("/history") {
+ self.state.search_query = "/history".to_string();
+ } else if query.starts_with('/') {
self.state.search_query.clear();
} else {
self.state.search_query = query.clone();
diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rs
index 70f9872..86a15ce 100644
--- a/src/tui/app/playback.rs
+++ b/src/tui/app/playback.rs
@@ -4,6 +4,63 @@ use crate::tui::{action::Action, overlay::NotificationKind, state::Screen};
pub(crate) use crate::service::extract_cover_url;
+fn parse_duration_seconds(d: &str) -> Option<u64> {
+ let s = d.trim();
+ if s.is_empty() || s.eq_ignore_ascii_case("n/a") {
+ return None;
+ }
+ if s.contains(':') {
+ let parts: Vec<&str> = s.split(':').collect();
+ if parts.len() == 2 {
+ let m: u64 = parts[0].trim().parse().ok()?;
+ let s: u64 = parts[1].trim().parse().ok()?;
+ return Some(m * 60 + s);
+ } else if parts.len() == 3 {
+ let h: u64 = parts[0].trim().parse().ok()?;
+ let m: u64 = parts[1].trim().parse().ok()?;
+ let s: u64 = parts[2].trim().parse().ok()?;
+ return Some(h * 3600 + m * 60 + s);
+ }
+ }
+ let mut total = 0u64;
+ let mut current_num = String::new();
+ let mut found_any = false;
+ for c in s.chars() {
+ if c.is_ascii_digit() {
+ current_num.push(c);
+ } else if c == 'h' || c == 'H' {
+ if let Ok(n) = current_num.parse::<u64>() {
+ total += n * 3600;
+ found_any = true;
+ }
+ current_num.clear();
+ } else if c == 'm' || c == 'M' {
+ if let Ok(n) = current_num.parse::<u64>() {
+ total += n * 60;
+ found_any = true;
+ }
+ current_num.clear();
+ } else if c == 's' || c == 'S' {
+ if let Ok(n) = current_num.parse::<u64>() {
+ total += n;
+ found_any = true;
+ }
+ current_num.clear();
+ }
+ }
+ if !current_num.is_empty() && !found_any {
+ if let Ok(n) = current_num.parse::<u64>() {
+ total += n * 60;
+ found_any = true;
+ }
+ }
+ if found_any && total > 0 {
+ Some(total)
+ } else {
+ None
+ }
+}
+
impl App {
fn preferred_playback_player(
&self,
@@ -25,6 +82,7 @@ impl App {
let mut cover_url = None;
let mut stype = 1;
let mut release_year = "Unknown".to_string();
+ let mut duration_seconds = None;
if let Some(details) = &self.state.selected_details {
if let Some(t) = details.get("title").and_then(|t| t.as_str()) {
@@ -41,6 +99,9 @@ impl App {
} else if let Some(y) = details.get("year").and_then(|y| y.as_i64()) {
release_year = y.to_string();
}
+ if let Some(d) = details.get("duration").and_then(|v| v.as_str()) {
+ duration_seconds = parse_duration_seconds(d);
+ }
}
if cover_url.is_none() {
@@ -55,6 +116,11 @@ impl App {
if cover_url.is_none() {
if let Some(preview) = &self.state.search_preview {
cover_url = extract_cover_url(preview);
+ if duration_seconds.is_none() {
+ if let Some(d) = preview.get("duration").and_then(|v| v.as_str()) {
+ duration_seconds = parse_duration_seconds(d);
+ }
+ }
}
}
@@ -88,6 +154,9 @@ impl App {
season,
episode,
timestamp,
+ duration_seconds,
+ progress_seconds: 0,
+ completed: false,
})
}
@@ -99,6 +168,30 @@ impl App {
headers: Vec<(String, String)>,
) {
let history_item = self.build_watch_history_item();
+ let resume_seconds = if let Some(item) = &history_item {
+ self.state
+ .history
+ .get_item(
+ &item.provider,
+ &item.subject_id,
+ item.season,
+ item.episode,
+ Some(&item.title),
+ )
+ .filter(|existing| existing.is_in_progress())
+ .map(|existing| existing.progress_seconds)
+ } else {
+ None
+ };
+
+ let tracker_opts = history_item.as_ref().map(|item| {
+ (
+ item.provider.clone(),
+ item.subject_id.clone(),
+ item.season,
+ item.episode,
+ )
+ });
let sender = self.action_sender.clone();
let cell_size = self
@@ -145,12 +238,18 @@ impl App {
}
}
+ let tracker_ref = tracker_opts
+ .as_ref()
+ .map(|(p, s, se, ep)| (p.as_str(), s.as_str(), *se, *ep));
+
let mut command = crate::tui::player::command(
kind,
&link,
local_subtitle.as_deref(),
&headers,
window,
+ resume_seconds,
+ tracker_ref,
);
command.stdin(std::process::Stdio::null());
command.stdout(std::process::Stdio::null());
@@ -169,9 +268,6 @@ impl App {
match command.spawn() {
Ok(mut child) => {
- if let Some(item) = history_item {
- sender.send(Action::MarkWatched(item)).ok();
- }
let start_time = std::time::Instant::now();
let stderr_stream = child.stderr.take();
@@ -193,6 +289,31 @@ impl App {
sender
.send(Action::PlayerCrashed(status.code(), clean_error))
.ok();
+ } else {
+ sender.send(Action::ReconcileHistory).ok();
+
+ if let Some(item) = history_item {
+ let elapsed = start_time.elapsed().as_secs();
+ if elapsed >= 30 {
+ let duration = item.duration_seconds;
+ let completed = duration.is_some_and(|d| {
+ d > 0 && elapsed >= (d as f64 * 0.90) as u64
+ });
+ let progress = if let Some(d) = duration {
+ elapsed.min(d)
+ } else {
+ elapsed
+ };
+ sender
+ .send(Action::UpdateProgress {
+ item,
+ progress,
+ duration,
+ completed,
+ })
+ .ok();
+ }
+ }
}
}
@@ -546,6 +667,19 @@ impl App {
let history = self.state.history.clone();
tokio::task::spawn_blocking(move || history.save());
}
+ Action::UpdateProgress {
+ item,
+ progress,
+ duration,
+ completed,
+ } => {
+ self.state
+ .history
+ .update_progress(item, progress, duration, completed);
+ }
+ Action::ReconcileHistory => {
+ self.state.history.reconcile_pending_playback_states();
+ }
Action::PlayerCrashed(code, error_msg) => {
let code_str = code
.map(|c| c.to_string())
diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rs
index 91aa7f1..04e7943 100644
--- a/src/tui/app/requests.rs
+++ b/src/tui/app/requests.rs
@@ -175,6 +175,7 @@ impl App {
"No watch history found.",
);
} else {
+ self.state.search_query = "/history".to_string();
recent.sort_by_key(|b| std::cmp::Reverse(b.timestamp));
for item in recent {
diff --git a/src/tui/app/run.rs b/src/tui/app/run.rs
index 67f96ec..dda7c8c 100644
--- a/src/tui/app/run.rs
+++ b/src/tui/app/run.rs
@@ -224,6 +224,8 @@ impl App {
| Action::LaunchPlayback(..)
| Action::LaunchPlayer(..)
| Action::MarkWatched(..)
+ | Action::UpdateProgress { .. }
+ | Action::ReconcileHistory
| Action::PlayerCrashed(..) => {
self.handle_playback(action).await;
}
diff --git a/src/tui/commands.rs b/src/tui/commands.rs
index d7817ac..63afb8c 100644
--- a/src/tui/commands.rs
+++ b/src/tui/commands.rs
@@ -89,12 +89,18 @@ impl SlashCommand {
}
}
- pub fn description(self, _state: &AppState) -> &'static str {
+ pub fn description(self, state: &AppState) -> &'static str {
match self {
Self::Browse => "Curated, rated & most-watched views",
Self::History => "Watch history",
Self::List => "Show all TV channels",
- Self::Config => "Configure IPTV playlists",
+ Self::Config => {
+ if state.is_addon_mode {
+ "Configure HTTP addons"
+ } else {
+ "Configure IPTV playlists"
+ }
+ }
Self::DownloadDir => "View or change download folder",
Self::Theme => "Theme picker",
Self::Update => "Check for newer release",
@@ -119,7 +125,11 @@ impl SlashCommand {
|| (state.addons_enabled && state.is_addon_mode)
}
Self::History => state.streaming_enabled && !state.is_tv_mode && !state.is_addon_mode,
- Self::List | Self::Config => state.tv_enabled && state.is_tv_mode,
+ Self::List => state.tv_enabled && state.is_tv_mode,
+ Self::Config => {
+ (state.tv_enabled && state.is_tv_mode)
+ || (state.addons_enabled && state.is_addon_mode)
+ }
Self::EnableBdix => {
state.streaming_enabled
&& !state.is_tv_mode
diff --git a/src/tui/screens/details.rs b/src/tui/screens/details.rs
index cd394d6..3749b7f 100644
--- a/src/tui/screens/details.rs
+++ b/src/tui/screens/details.rs
@@ -377,6 +377,30 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
if !duration_str.is_empty() {
metadata.push(duration.to_string());
}
+ let subject_id = state.active_subject_id.as_deref().unwrap_or("");
+ let provider = subject_provider(state, subject_id).cache_key();
+ if type_val == 1 {
+ if let Some(hist) = state
+ .history
+ .get_item(provider, subject_id, 0, 0, Some(&title))
+ {
+ if hist.is_in_progress() {
+ let p_bar = hist.progress_bar(8);
+ let pct = hist
+ .progress_percentage()
+ .map(|p| format!("{:.0}%", p))
+ .unwrap_or_default();
+ let rem = hist
+ .formatted_remaining()
+ .map(|r| format!(" • {r}"))
+ .unwrap_or_default();
+ metadata.push(format!("{p_bar} {pct}{rem}"));
+ } else if hist.completed {
+ metadata.push("[✓ Watched]".to_string());
+ }
+ }
+ }
+ metadata.retain(|s| !s.trim().is_empty());
let meta_line = Line::from(vec![Span::styled(
metadata.join(" • "),
metadata_style(theme),
@@ -653,10 +677,31 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
ep_numbers
.iter()
.map(|&ep| {
- if state.history.is_watched(provider, subject_id, se_num, ep) {
- ListItem::new(format!("Episode {}", ep)).style(theme.text_dim)
+ if let Some(hist) =
+ state
+ .history
+ .get_item(provider, subject_id, se_num, ep, Some(&title))
+ {
+ if hist.completed {
+ ListItem::new(format!("✓ Episode {}", ep)).style(theme.text_dim)
+ } else if hist.is_in_progress() {
+ let pct = hist
+ .progress_percentage()
+ .map(|p| format!(" ({:.0}%)", p))
+ .unwrap_or_default();
+ let remaining = hist
+ .formatted_remaining()
+ .map(|r| format!(" • {r}"))
+ .unwrap_or_default();
+ ListItem::new(format!("▶ Episode {}{pct}{remaining}", ep))
+ .style(theme.accent)
+ } else {
+ ListItem::new(format!(" Episode {}", ep)).style(theme.text)
+ }
+ } else if state.history.is_watched(provider, subject_id, se_num, ep) {
+ ListItem::new(format!("✓ Episode {}", ep)).style(theme.text_dim)
} else {
- ListItem::new(format!("Episode {}", ep)).style(theme.text)
+ ListItem::new(format!(" Episode {}", ep)).style(theme.text)
}
})
.collect()
diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rs
index ef1819c..9ce1178 100644
--- a/src/tui/screens/home.rs
+++ b/src/tui/screens/home.rs
@@ -685,21 +685,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
};
let is_history = state.search_query.trim().to_lowercase() == "/history";
- if is_history {
- let mut extra = vec![];
- if res.season > 0 {
- extra.push(format!("S{:02}E{:02}", res.season, res.episode));
- }
- extra.push(res.provider.to_string());
-
- if !extra.is_empty() {
- if type_tag.is_empty() {
- type_tag = extra.join(" • ");
- } else {
- type_tag = format!("{} • {}", type_tag, extra.join(" • "));
- }
- }
- } else if type_tag.is_empty() {
+ if !is_history && type_tag.is_empty() {
type_tag = "Unknown".to_string();
}
@@ -713,59 +699,126 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)
let mut info_spans = vec![];
- macro_rules! push_year {
- () => {
- if res.release_year != "Unknown" && !res.release_year.is_empty() {
+ if is_history {
+ if !type_tag.is_empty() {
+ info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+ if res.season > 0 {
+ info_spans.push(ratatui::text::Span::styled(
+ format!("S{:02}E{:02}", res.season, res.episode),
+ theme.text,
+ ));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+
+ if let Some(hist) = state.history.get_item(
+ res.provider.cache_key(),
+ &res.id,
+ res.season,
+ res.episode,
+ Some(&res.title),
+ ) {
+ if hist.is_in_progress() {
+ let (filled, empty) = hist.progress_bar_parts(8);
+ info_spans.push(ratatui::text::Span::styled(
+ filled,
+ theme.accent.add_modifier(ratatui::style::Modifier::BOLD),
+ ));
+ info_spans.push(ratatui::text::Span::styled(empty, theme.text_dim));
+
+ let pct = hist
+ .progress_percentage()
+ .map(|p| format!(" {:.0}%", p))
+ .unwrap_or_default();
+ info_spans.push(ratatui::text::Span::styled(pct, theme.text));
+
+ if let Some(r) = hist.formatted_remaining() {
+ info_spans.push(ratatui::text::Span::styled(
+ format!(" ({r})"),
+ theme.text_dim,
+ ));
+ }
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ info_spans.push(ratatui::text::Span::styled(
+ format!("Watched {}", hist.formatted_relative_time()),
+ theme.text_dim,
+ ));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ } else if hist.completed {
info_spans
- .push(ratatui::text::Span::styled(&res.release_year, theme.text));
+ .push(ratatui::text::Span::styled("[✓ Completed]", theme.text_dim));
info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
- }
- };
- }
-
- if is_selected {
- if let Some(meta) = &state.search_preview {
- let rating = meta
- .get("imdbRating")
- .or_else(|| meta.get("imdbRatingValue"))
- .and_then(|v| v.as_str());
- if let Some(r) = rating {
- let star = if state.basic_terminal { "* " } else { "★ " };
- info_spans.push(ratatui::text::Span::styled(star, theme.rating));
- info_spans.push(ratatui::text::Span::styled(r, theme.text));
+ info_spans.push(ratatui::text::Span::styled(
+ format!("Watched {}", hist.formatted_relative_time()),
+ theme.text_dim,
+ ));
info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
}
- push_year!();
+ }
- let mut g_names = vec![];
- if let Some(genres) = meta.get("genres").and_then(|g| g.as_array()) {
- g_names = genres
- .iter()
- .filter_map(|g| {
- g.get("name")
- .and_then(|n| n.as_str())
- .map(|s| s.to_string())
- })
- .collect();
- }
- if !g_names.is_empty() {
- info_spans
- .push(ratatui::text::Span::styled(g_names.join(" • "), theme.text));
+ info_spans.push(ratatui::text::Span::styled(
+ res.provider.to_string(),
+ theme.text,
+ ));
+ } else {
+ macro_rules! push_year {
+ () => {
+ if res.release_year != "Unknown" && !res.release_year.is_empty() {
+ info_spans
+ .push(ratatui::text::Span::styled(&res.release_year, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+ };
+ }
+
+ if is_selected {
+ if let Some(meta) = &state.search_preview {
+ let rating = meta
+ .get("imdbRating")
+ .or_else(|| meta.get("imdbRatingValue"))
+ .and_then(|v| v.as_str());
+ if let Some(r) = rating {
+ let star = if state.basic_terminal { "* " } else { "★ " };
+ info_spans.push(ratatui::text::Span::styled(star, theme.rating));
+ info_spans.push(ratatui::text::Span::styled(r, theme.text));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+ push_year!();
+
+ let mut g_names = vec![];
+ if let Some(genres) = meta.get("genres").and_then(|g| g.as_array()) {
+ g_names = genres
+ .iter()
+ .filter_map(|g| {
+ g.get("name")
+ .and_then(|n| n.as_str())
+ .map(|s| s.to_string())
+ })
+ .collect();
+ }
+ if !g_names.is_empty() {
+ info_spans.push(ratatui::text::Span::styled(
+ g_names.join(" • "),
+ theme.text,
+ ));
+ info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ }
+ info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
+ } else if state.preview_loading {
+ push_year!();
+ info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
+ info_spans
+ .push(ratatui::text::Span::styled("Loading...", theme.text_dim));
+ } else {
+ push_year!();
+ info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
}
- info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
- } else if state.preview_loading {
- push_year!();
- info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
- info_spans.push(ratatui::text::Span::styled(" • ", theme.text_dim));
- info_spans.push(ratatui::text::Span::styled("Loading...", theme.text_dim));
} else {
push_year!();
info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
}
- } else {
- push_year!();
- info_spans.push(ratatui::text::Span::styled(&type_tag, theme.text));
}
if text_layout[2].height > 0 && !info_spans.is_empty() {