feat: separate Miruro and YouTube browser interfaces
This commit is contained in:
@@ -39,11 +39,11 @@ tubular --player /path/to/terebi "japanese podcast"
|
||||
tubular --help
|
||||
```
|
||||
|
||||
Startup shows a centered **YouTube / Miruro** selector. Use `j` / `k` or arrows to select and Enter to open that provider's existing browser; Esc, `q`, or Ctrl-C quits without opening a browser. Navigation, confirmation and Esc use the configured `selector.select.next`, `selector.select.previous`, `selector.open` and `selector.close` bindings; quit/interrupt bindings also apply. An initial CLI query searches whichever provider you select. `--miruro` bypasses the chooser; `--help` and `--default-config` remain noninteractive.
|
||||
Startup shows a centered **YouTube / Miruro** selector. Use `j` / `k` or arrows to select and Enter to open that provider's separate interface; Esc, `q`, or Ctrl-C quits without opening a browser. Navigation, confirmation and Esc use the configured `selector.select.next`, `selector.select.previous`, `selector.open` and `selector.close` bindings; quit/interrupt bindings also apply. An initial CLI query searches whichever provider you select. `--miruro` bypasses the chooser; `--help` and `--default-config` remain noninteractive.
|
||||
|
||||
After selection, the browser starts in **normal mode**. Press `i` to type a search; Enter submits a changed query and returns to normal mode. Esc returns without submitting.
|
||||
|
||||
Selecting a video launches:
|
||||
Selecting a YouTube video launches:
|
||||
|
||||
```sh
|
||||
terebi --new-instance --url 'https://www.youtube.com/watch?v=VIDEO_ID' \
|
||||
@@ -52,16 +52,33 @@ terebi --new-instance --url 'https://www.youtube.com/watch?v=VIDEO_ID' \
|
||||
|
||||
Each selection opens an independent player instance without replacing existing playback. Tubular creates a private reporting session and consumes Terebi's progress records independently of the launcher. `--player` overrides the Terebi CLI executable; it is not a generic mpv/IINA adapter. Tubular reports launcher failures, while later streaming/playback errors appear in Terebi. Quitting Tubular leaves launched players running.
|
||||
|
||||
### Miruro episodes
|
||||
### Miruro browser
|
||||
|
||||
Choose **Miruro** at startup, use `--miruro` to start directly, or reach the permanent **Miruro** tab with Tab / Shift-Tab. Press `i` to edit its search and Enter to submit. Autocomplete returns at most eight catalog titles, without pagination. Enter on a title loads its returned episodes; Enter on an episode resolves a fresh direct **ssub / sun** HLS source and launches Terebi with a private source document. `/` still opens YouTube Search.
|
||||
Choose **Miruro** at startup or use `--miruro` to start directly. Its interface is **catalog → series → episodes**, without YouTube's Search/Feed tabs, channel controls or category selectors.
|
||||
|
||||
Episodes support watch later, saved videos, currently watching, and watched status. Only episodes—not catalog titles—can be saved. Reopening a saved episode resolves new URLs; identity is the opaque Miruro catalog ID plus its returned episode number. Miruro entries appear in combined collections, not YouTube channel categories. Channel/tag actions and YouTube thumbnails/extraction do not apply.
|
||||
Catalog autocomplete returns at most eight anime titles, without pagination. Titles show the available format, status, season/year and planned/listed episode counts; the metadata pane shows the selected title's synopsis and other returned facts. The series screen lists only actual returned episodes—not planned or absolute episode numbers—with titles, dates and durations when supplied. Selected episode details appear first in the metadata pane, above the series synopsis. Listed counts do not guarantee that a supported Sun source is available.
|
||||
|
||||
| Key | Miruro action |
|
||||
| --- | --- |
|
||||
| `i` / `/` | Edit the catalog query; Enter searches, Esc cancels |
|
||||
| `j` / `k`, ↓ / ↑; `g` / `G`, Home / End | Select a title or episode |
|
||||
| Enter | Open a series, or resolve a fresh direct **ssub / sun** source and play the episode |
|
||||
| `-` / `+` | Back / forward through cached screens, preserving query and selection |
|
||||
| `w` / `v` | Save the selected episode to watch later / saved episodes |
|
||||
| `W` / `V` / `C` | Open Miruro's offline watch-later / saved / currently-watching episodes |
|
||||
| `f` | Cycle All / Unwatched / Watched in watch later |
|
||||
| `x` / `X` | Remove the selected / confirm removal of visible episodes from the active collection |
|
||||
| `d` | Focus/unfocus the synopsis/metadata pane; `j` / `k` and page keys scroll while focused |
|
||||
| Esc | Cancel input/help or return focus to the episode/title list |
|
||||
| `r` | Refresh the active screen and reload configured keys |
|
||||
| `?` / `q` | Keyboard help / quit |
|
||||
|
||||
These actions reuse the existing `[keys]` configuration; live hints and help omit unsupported YouTube actions. Only episodes—not catalog titles—can be saved. Reopening a saved episode resolves new URLs; identity is the opaque Miruro catalog ID plus its returned episode number. Each interface shows only its provider's collections, while playback, watched state and storage remain shared. Episode markers show saved/watch-later/currently-watching membership and acknowledged watched status; Terebi owns resume positions.
|
||||
|
||||
Stream and external VTT subtitle headers are supplied explicitly; Terebi selects the source's declared default subtitle. Sources requiring media redirects, cross-origin HLS, proxies, iframe playback, or provider-specific playlist rewriting fail explicitly. No provider/language fallback or automatic expired-source refresh is performed.
|
||||
|
||||
|
||||
## Controls
|
||||
## YouTube controls
|
||||
|
||||
These are the default bindings. Overrides in `[keys]` replace an action's bindings; the live hints and `?` reference show the configured keys.
|
||||
|
||||
@@ -70,9 +87,9 @@ These are the default bindings. Overrides in `[keys]` replace an action's bindin
|
||||
| Key | Action |
|
||||
| --- | --- |
|
||||
| `j` / `k`, ↓ / ↑ | Select the next / previous video |
|
||||
| Enter | Open a Miruro catalog title's episodes, or launch the selected video/episode in Terebi |
|
||||
| Enter | Launch the selected video in Terebi |
|
||||
| `g` / Home, `G` / End | Select the first / last loaded video |
|
||||
| `i` | Edit the current category/combined feed or Miruro search; other views use general YouTube Search |
|
||||
| `i` | Edit the current category/combined feed search; other views use general YouTube Search |
|
||||
| `/` | Go directly to general YouTube Search |
|
||||
| `F` (Shift-F) | Go directly to the subscription Feed |
|
||||
| `d` | Open video info; press again for the full description, again to return to info |
|
||||
@@ -217,7 +234,7 @@ Category entries accept `@handles`, HTTPS YouTube channel URLs, or canonical `UC
|
||||
|
||||
Video tables color channel names **cyan** when the creator belongs to at least one category. Untagged registrations keep the default text color; selected rows retain their black-on-cyan highlight. Membership is matched by channel ID or handle, not the displayed name, and updates after saving tags or reloading config.
|
||||
|
||||
- **Search**, **Feed**, and **Miruro** are permanent tabs. Feed combines all YouTube `[channels]` registrations, including untagged channels, plus channels entered directly in categories, without duplicates.
|
||||
- **Search** and **Feed** are permanent YouTube tabs. Feed combines all YouTube `[channels]` registrations, including untagged channels, plus channels entered directly in categories, without duplicates.
|
||||
- Browsing an unpinned category, combined-category feed, channel, watch-later list, or saved-video list uses one shared temporary tab; choosing another replaces it. Pinned categories keep their own tabs, marked with a dimmed `p`.
|
||||
- Removing a channel from a category does **not** unsubscribe it from Feed. To unsubscribe, remove its `[channels]` mappings and category references, then press `r`.
|
||||
- Temporary tabs do not survive restarting; saved categories and pins do. Hidden views retain loaded rows, selection, and pagination during the session.
|
||||
@@ -226,9 +243,9 @@ Bulk editing refuses to clear all tags when a target has no `[channels]` registr
|
||||
|
||||
## Watch later
|
||||
|
||||
Watch later is **one collection**, deduplicated by YouTube video ID or stable Miruro episode identity. Category lists are derived from saved YouTube videos' channel identities and the **current** subscription categories: adding or removing a channel from a category changes its watch-later list after saving tags or reloading config with `r`. Miruro episodes appear only in the combined list. No category memberships are stored on individual videos.
|
||||
Watch later is **one stored collection**, deduplicated by YouTube video ID or stable Miruro episode identity, with provider-specific views. In YouTube, category lists are derived from saved videos' channel identities and the **current** subscription categories: adding or removing a channel from a category changes its watch-later list after saving tags or reloading config with `r`. Its combined list contains only YouTube videos. Miruro uses the flat episode lists described above. No category memberships are stored on individual videos.
|
||||
|
||||
`W` opens a searchable collection selector from any video view or preview. The All categories (combined) entry comes first, followed by configured categories; it remains available even when there are no categories. Navigate with `j` / `k` or arrows in normal mode, or press `i` to filter by name and use arrows / `Ctrl-j` / `Ctrl-k` while typing. `Enter` browses the selected match; with no matches it does nothing. `Esc` returns to normal mode, then closes the selector without navigating. Reopening clears the search. `Alt-w` still opens the current category's watch later directly.
|
||||
In YouTube, `W` opens a searchable collection selector from any video view or preview. The All categories (combined) entry comes first, followed by configured categories; it remains available even when there are no categories. Navigate with `j` / `k` or arrows in normal mode, or press `i` to filter by name and use arrows / `Ctrl-j` / `Ctrl-k` while typing. `Enter` browses the selected match; with no matches it does nothing. `Esc` returns to normal mode, then closes the selector without navigating. Reopening clears the search. `Alt-w` still opens the current category's watch later directly.
|
||||
|
||||
Moving between watch-later scopes carries the current All/Unwatched/Watched filter to the destination, including cached lists; back navigation restores the originating category list. Choosing the current list does not add history. The border title shows the active filter. Lists use saved title, creator, and publication metadata without fetching video lists, so they also work offline.
|
||||
|
||||
@@ -254,9 +271,9 @@ Progress sessions survive Tubular exit so later player reports can be recovered
|
||||
|
||||
## Saved videos
|
||||
|
||||
Saved videos is a separate collection from watch later, deduplicated by YouTube video ID or stable Miruro episode identity. It uses the same offline title, creator, and publication metadata; YouTube entries follow **current channel category memberships**, not categories stored on individual videos. Miruro episodes appear in All categories (combined).
|
||||
Saved videos is a separate stored collection from watch later, deduplicated by YouTube video ID or stable Miruro episode identity, with provider-specific views. It uses offline saved metadata; YouTube entries follow **current channel category memberships**, not categories stored on individual videos. Its All categories (combined) list contains only YouTube videos; Miruro opens a flat saved-episode list.
|
||||
|
||||
`V` opens the same searchable selector for saved videos, with **All categories (combined)** first and configured categories beneath it. `Alt-v` opens the current category's saved videos directly. `Alt-w` / `Alt-v` retain the explicit category when switching between category-scoped collection lists; without a current category, they leave the view unchanged. All four shortcuts work in normal mode and previews, not text-entry fields or modal selectors. Both collections share the existing temporary-tab and back/forward history behavior.
|
||||
In YouTube, `V` opens the same searchable selector for saved videos, with **All categories (combined)** first and configured categories beneath it. `Alt-v` opens the current category's saved videos directly. `Alt-w` / `Alt-v` retain the explicit category when switching between category-scoped collection lists; without a current category, they leave the view unchanged. All four shortcuts work in normal mode and previews, not text-entry fields or modal selectors. Both collections share the existing temporary-tab and back/forward history behavior.
|
||||
|
||||
Saved lists have no watched filter. Individual and bulk removal use the shared collection-list controls below.
|
||||
|
||||
@@ -266,7 +283,7 @@ The collection is persisted independently in `saved-videos.toml` beside `config.
|
||||
|
||||
## Currently watching
|
||||
|
||||
`C` opens one combined, offline list of started but unfinished videos. It uses the shared temporary tab and back/forward navigation; configure the shortcut with `view.watching.browse`.
|
||||
`C` opens an offline list of the current provider's started but unfinished videos/episodes. YouTube uses its shared temporary tab; Miruro uses a cached episode-list screen. Both support back/forward navigation; configure the shortcut with `view.watching.browse`.
|
||||
|
||||
A validated, acknowledged **positive playback position** adds the video—not merely launching Terebi or receiving position zero. Reaching the existing eligible **95% watched threshold** automatically removes it. Already-watched videos never enter. Unknown-duration or ineligible playback can appear but stays unfinished unless a later eligible report marks it watched or you remove it.
|
||||
|
||||
@@ -278,9 +295,9 @@ Use `x` for individual removal or `X` for bulk confirmation. Removal neither mar
|
||||
|
||||
Removal controls apply **only in watch-later, saved-video, and currently-watching views**, including previews opened from those lists. Search, Feed, Miruro catalog/episode browsing, ordinary channel/category views, and their previews do not expose removal actions or hints. Text fields and selectors retain their normal controls.
|
||||
|
||||
`x` immediately removes only the selected video from the active collection. `X` snapshots the current list and opens bulk confirmation: watch later uses the current category and All/Unwatched/Watched filter; saved videos uses the current category's entire saved list; Currently watching uses its entire combined list. An empty list does not open confirmation.
|
||||
`x` immediately removes only the selected video/episode from the active collection. `X` snapshots the current provider's visible list and opens bulk confirmation: YouTube watch later uses the current category and All/Unwatched/Watched filter, and saved videos uses the current category's entire saved list; Miruro uses its flat list and any active watch-later filter. Currently watching uses the current provider's entire list. An empty list does not open confirmation. Neither interface's removal controls touch the other provider's entries.
|
||||
|
||||
The prompt names the collection, category, count, and applicable filter. **`y` or Enter confirms; `n` or Esc cancels.** Only the snapshotted IDs are removed, even if membership or watched status changes while confirmation is open.
|
||||
The YouTube prompt names the collection, category, count and applicable filter; Miruro names the collection and episode count, with the active filter in the screen header. **`y` confirms; `n` or Esc cancels.** Miruro also accepts Enter to confirm. Only the snapshotted IDs are removed, even if membership or watched status changes while confirmation is open.
|
||||
|
||||
Removal changes only the active collection. Matching views update, while other collections and global watched status remain untouched.
|
||||
|
||||
|
||||
+14
-4
@@ -431,7 +431,7 @@ Wrapper-extraction verification, before TUI integration: `cargo test --locked` p
|
||||
|
||||
## Tubular → Terebi integration
|
||||
|
||||
`tubular` offers a centered YouTube/Miruro startup selector; an initial query follows the chosen provider. `tubular --miruro "apothecary"` bypasses it and starts the permanent Miruro search tab directly. Catalog Enter opens actual returned episodes; episode Enter resolves fresh sources off-thread. Autocomplete is limited to eight titles, without invented pagination. One worker handles bounded network work; changing views/queries invalidates stale responses rather than launching obsolete selections. Canonical title/slug rules follow the [deployed helper][link-helpers], including Unicode NFD normalization.
|
||||
`tubular` offers a centered YouTube/Miruro startup selector; an initial query follows the chosen provider. `tubular --miruro "apothecary"` bypasses it and starts the dedicated Miruro interface directly. `src/miruro_ui.rs` owns catalog → series → episodes navigation, synopsis/metadata presentation, cached screen history and flat episode collections; YouTube retains its separate Search/Feed/category interface. Catalog Enter opens actual returned episodes; episode Enter resolves fresh sources off-thread. Autocomplete is limited to eight titles, without invented pagination. `src/miruro_browser.rs` supplies native catalog/series/episode models and one worker for bounded network work; changing views/queries or episode selections invalidates stale source responses rather than launching obsolete selections. Canonical title/slug rules follow the [deployed helper][link-helpers], including Unicode NFD normalization.
|
||||
|
||||
Titles normalizing to an empty slug fail explicitly; the wrapper does not guess an alternative detail route. This does not reject accented Latin titles, which use NFD decomposition.
|
||||
|
||||
@@ -474,7 +474,7 @@ Tubular validates the version, namespace, media ID, episode, event and numeric f
|
||||
|
||||
Matching acknowledged positive positions admit currently-watching entries. Watched status retains `completion_eligible && duration_seconds > 0 && position_seconds / duration_seconds >= 0.95`; null duration is ineligible. Seeking near the end can satisfy it. Launch/window closure alone cannot. Duplicate records, partial trailing lines and later reports recovered after Tubular restart retain the existing session-consumption behavior.
|
||||
|
||||
Watch later, saved videos, currently watching and watched state accept stable episode keys `miruro:<opaque ID>:<canonical episode>`. Catalog rows (`miruro-series:<ID>`) are not saveable/playable episode identities. Saved episode playback resolves fresh sources; CDN addresses/tokens never become collection keys. Miruro has no YouTube channel identity, so category/tag/channel actions and YouTube extraction/thumbnails are excluded; its episodes use combined collections.
|
||||
Watch later, saved videos, currently watching and watched state accept stable episode keys `miruro:<opaque ID>:<canonical episode>`. Catalog results use opaque media IDs in native `Media` rows, not fabricated video/episode keys; they are not saveable/playable episode identities. Saved episode playback resolves fresh sources; CDN addresses/tokens never become collection keys. Playback and persisted state remain shared, but each interface filters collections before display, selection, counts and removal. Miruro has no YouTube channel identity, so its flat episode lists exclude category/tag/channel actions and YouTube extraction/thumbnails. Planned/listed counts are metadata, not a claim of supported source availability; only actual returned episode numbers are offered for playback.
|
||||
|
||||
### Integration verification
|
||||
|
||||
@@ -484,11 +484,21 @@ The private source document retained Origin/Referer headers and nine VTT tracks
|
||||
|
||||
After Tubular exited successfully, its independent GUI continued appending matching v2 progress and the private source file remained byte-for-byte unchanged. That player/session was intentionally retained for the user's visible subtitle/seek check; no source cleanup was attempted while playback remained active.
|
||||
|
||||
Final integrated checks passed: `cargo fmt --check`, all **175 tests**, `cargo clippy --locked --all-targets -- -D warnings`, `cargo build --locked`, and the built executable's `--help`. Regressions cover v1 compatibility, v2 identity/95%/null-duration boundaries, restart/partial-report recovery, source/session permissions and retention, collection routing, stale responses and canonical Unicode slugging. The installed Terebi CLI was older and lacked `--source-file`; the explicit developer-bundle override avoided changing that installation.
|
||||
Initial integrated checks passed: `cargo fmt --check`, all **175 tests**, `cargo clippy --locked --all-targets -- -D warnings`, `cargo build --locked`, and the built executable's `--help`. Regressions cover v1 compatibility, v2 identity/95%/null-duration boundaries, restart/partial-report recovery, source/session permissions and retention, collection routing, stale responses and canonical Unicode slugging. The installed Terebi CLI was older and lacked `--source-file`; the explicit developer-bundle override avoided changing that installation.
|
||||
|
||||
Startup provider-selection verification: **176 tests**, formatting, Clippy and build passed. Actual terminal runs showed the centered selector, routed both provider choices into their existing interfaces, carried an initial query into Miruro autocomplete, honored remapped selector keys, canceled on an encoded terminal Escape event, and preserved direct `--miruro` startup and noninteractive help/default-config. Bare Escape-byte injection in the automated terminal remained ambiguous; the complete terminal key encoding was exercised instead.
|
||||
|
||||
This run proves Tubular-to-Terebi launch, acknowledged playback/progress consumption and independent lifetime—not visible subtitle rendering, perceived A/V synchronization, or seeks through the user's installed release. English subtitle appearance/synchronization before and after seeking still requires a visible-app check.
|
||||
Those initial integration runs prove Tubular-to-Terebi launch, acknowledged playback/progress consumption and independent lifetime—not visible subtitle rendering, perceived A/V synchronization, or seeks through the user's installed release. English subtitle appearance/synchronization before and after seeking still requires a visible-app check.
|
||||
|
||||
### Dedicated-interface verification
|
||||
|
||||
The cutover passed **181 tests**, formatting, Clippy with warnings denied and build. Regressions cover cached catalog/series navigation, real episode identities, stale source rejection, provider-scoped collections and filtered removal, matching v2 completion, validated private source sessions, sanitized input/errors and configured controls.
|
||||
|
||||
Actual terminal runs exercised both chooser routes and direct `--miruro` startup. Miruro showed eight catalog titles with anime metadata, two returned episodes rather than the twelve planned episodes, selected-episode synopsis/date/duration above series metadata, cached back/forward selection and dedicated keyboard help. YouTube retained Search/Feed and its existing video/collection controls. Mixed-provider fixtures showed only the selected provider's entries; removing two Miruro saved episodes left the YouTube sentinel and both Miruro watch-later entries intact, including after restarting into YouTube. Configured F8/F9 controls were exercised; replaced default quit/interrupt keys no longer forced an exit.
|
||||
|
||||
A freshly resolved episode-2 source retained nine VTT tracks with English default, explicit stream/subtitle header names and the expected opaque episode identity. Terebi's existing `resolved-playback-check` decoded video/audio, advanced playback and passed default-VTT/forward/backward acknowledged cue checks. It also emitted three redacted FFmpeg error lines; their cause was not established. Session/source/report modes were `0700`/`0600`/`0600`; the source hash remained unchanged after Tubular exited.
|
||||
|
||||
The independent GUI accepted that launch and opened its private report, but the report remained empty: no GUI ready state, advancing GUI progress or current-watching admission is claimed for this run. The visible window needs a human check for a startup prompt or playback error, plus subtitle/seek synchronization. The native diagnostic's pass is not a GUI sign-off. Its active private session was retained rather than deleted.
|
||||
|
||||
## Remaining research questions
|
||||
|
||||
|
||||
+81
-372
File diff suppressed because one or more lines are too long
+139
-70
@@ -8,13 +8,56 @@ use std::{
|
||||
use tubular::miruro::{Client, Detail, Identity, SourceDocument};
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Media {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
// Retain optional/null metadata exactly as returned; it is not a Video.
|
||||
pub metadata: Value,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Episode {
|
||||
pub identity: Identity,
|
||||
pub title: Option<String>,
|
||||
pub synopsis: Option<String>,
|
||||
pub aired_on: Option<String>,
|
||||
pub duration_seconds: Option<u64>,
|
||||
pub metadata: Value,
|
||||
}
|
||||
|
||||
impl Episode {
|
||||
pub fn snapshot(&self, media: &Media) -> Video {
|
||||
video(
|
||||
self.identity.key(),
|
||||
format!(
|
||||
"{} · Episode {}{}",
|
||||
media.title,
|
||||
self.identity.episode,
|
||||
self.title
|
||||
.as_ref()
|
||||
.map(|title| format!(" · {title}"))
|
||||
.unwrap_or_default()
|
||||
),
|
||||
self.aired_on.clone(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Series {
|
||||
pub media: Media,
|
||||
pub episodes: Vec<Episode>,
|
||||
}
|
||||
|
||||
pub enum Request {
|
||||
Search(String),
|
||||
Episodes { media_id: String, slug: String },
|
||||
Source(Video),
|
||||
}
|
||||
pub enum Response {
|
||||
Rows(Vec<(Video, String)>),
|
||||
Catalog(Vec<Media>),
|
||||
Series(Series),
|
||||
Source(Video, Box<SourceDocument>),
|
||||
}
|
||||
|
||||
@@ -35,12 +78,12 @@ impl Worker {
|
||||
let result = match request {
|
||||
Request::Search(query) => client
|
||||
.search(&query)
|
||||
.and_then(catalog_rows)
|
||||
.map(Response::Rows),
|
||||
.and_then(catalog)
|
||||
.map(Response::Catalog),
|
||||
Request::Episodes { media_id, slug } => client
|
||||
.detail(&media_id, &slug)
|
||||
.and_then(|detail| episode_rows(&media_id, detail))
|
||||
.map(Response::Rows),
|
||||
.and_then(|detail| series(&media_id, detail))
|
||||
.map(Response::Series),
|
||||
Request::Source(video) => Identity::from_key(&video.id)
|
||||
.and_then(|id| {
|
||||
client.source_document(&id.media_id, id.episode, &video.title)
|
||||
@@ -89,9 +132,6 @@ impl Worker {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_miruro(video: &Video) -> bool {
|
||||
video.id.starts_with("miruro:") || video.id.starts_with("miruro-series:")
|
||||
}
|
||||
fn invalid(message: &str) -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, message)
|
||||
}
|
||||
@@ -162,38 +202,48 @@ fn video(id: String, title: String, date: Option<String>) -> Video {
|
||||
publication_date: date,
|
||||
}
|
||||
}
|
||||
pub fn catalog_rows(items: Vec<Value>) -> io::Result<Vec<(Video, String)>> {
|
||||
fn media(metadata: Value) -> io::Result<Media> {
|
||||
let id = metadata
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| invalid("Miruro catalog ID is missing"))?
|
||||
.to_owned();
|
||||
Identity::new(id.clone(), 1)?;
|
||||
Ok(Media {
|
||||
id,
|
||||
title: title(&metadata)?,
|
||||
metadata,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn catalog(items: Vec<Value>) -> io::Result<Vec<Media>> {
|
||||
if items.len() > 8 {
|
||||
return Err(invalid("Miruro autocomplete exceeded eight results"));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
items
|
||||
.into_iter()
|
||||
.map(|media| {
|
||||
let id = media
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| invalid("Miruro catalog ID is missing"))?;
|
||||
Identity::new(id.to_owned(), 1)?;
|
||||
let title = title(&media)?;
|
||||
let description = media
|
||||
.get("description")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or(
|
||||
"Catalog title: Enter opens returned episodes; only episodes can be saved.",
|
||||
)
|
||||
.to_owned();
|
||||
Ok((
|
||||
video(format!("miruro-series:{id}"), title, None),
|
||||
description,
|
||||
))
|
||||
.map(|item| {
|
||||
let media = media(item)?;
|
||||
if !seen.insert(media.id.clone()) {
|
||||
return Err(invalid("Miruro returned duplicate catalog IDs"));
|
||||
}
|
||||
Ok(media)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
pub fn episode_rows(media_id: &str, detail: Detail) -> io::Result<Vec<(Video, String)>> {
|
||||
let series = title(&detail.media)?;
|
||||
|
||||
pub fn series(media_id: &str, detail: Detail) -> io::Result<Series> {
|
||||
let media = media(detail.media)?;
|
||||
if media.id != media_id {
|
||||
return Err(invalid("Miruro detail ID did not match the requested ID"));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
detail
|
||||
let episodes = detail
|
||||
.episodes
|
||||
.into_iter()
|
||||
.map(|episode| {
|
||||
let number = episode
|
||||
.map(|metadata| {
|
||||
let number = metadata
|
||||
.get("episode_number")
|
||||
.and_then(Value::as_u64)
|
||||
.and_then(|n| u32::try_from(n).ok())
|
||||
@@ -202,27 +252,23 @@ pub fn episode_rows(media_id: &str, detail: Detail) -> io::Result<Vec<(Video, St
|
||||
if !seen.insert(number) {
|
||||
return Err(invalid("Miruro returned duplicate episode numbers"));
|
||||
}
|
||||
let label = episode.get("title").and_then(Value::as_str).unwrap_or("");
|
||||
let title = format!(
|
||||
"{series} · Episode {number}{}",
|
||||
if label.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" · {label}")
|
||||
}
|
||||
);
|
||||
let description = episode
|
||||
.get("synopsis")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("Episode metadata unavailable.")
|
||||
.to_owned();
|
||||
let date = episode
|
||||
.get("aired_on")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned);
|
||||
Ok((video(identity.key(), title, date), description))
|
||||
let text = |field| {
|
||||
metadata
|
||||
.get(field)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_owned)
|
||||
};
|
||||
Ok(Episode {
|
||||
identity,
|
||||
title: text("title"),
|
||||
synopsis: text("synopsis"),
|
||||
aired_on: text("aired_on"),
|
||||
duration_seconds: metadata.get("duration_seconds").and_then(Value::as_u64),
|
||||
metadata,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
Ok(Series { media, episodes })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -230,24 +276,47 @@ mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn catalog_and_actual_episode_numbers_remain_distinct() {
|
||||
let media = serde_json::json!({"id":"opaque_ID", "title":{"english":"The Apothecary Diaries", "romaji":"Kusuriya no Hitorigoto"}});
|
||||
let rows = catalog_rows(vec![media.clone()]).unwrap();
|
||||
assert_eq!(rows[0].0.id, "miruro-series:opaque_ID");
|
||||
assert!(Identity::from_key(&rows[0].0.id).is_err());
|
||||
let episodes = episode_rows(
|
||||
"opaque_ID",
|
||||
Detail {
|
||||
media,
|
||||
episodes: vec![
|
||||
serde_json::json!({"episode_number":3,"absolute_number":49,"title":"Returned"}),
|
||||
],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let identity = Identity::from_key(&episodes[0].0.id).unwrap();
|
||||
assert_eq!(identity.episode, 3);
|
||||
assert_eq!(identity.media_id, "opaque_ID");
|
||||
assert!(episodes[0].0.channel_id.is_none());
|
||||
let media = serde_json::json!({"id":"opaque_ID", "title":{"english":"The Apothecary Diaries", "romaji":"Kusuriya no Hitorigoto"}, "episode_count":12, "episode_counts":{"sub":null}, "episode_duration_minutes":null});
|
||||
let rows = catalog(vec![media.clone()]).unwrap();
|
||||
assert_eq!(rows[0].id, "opaque_ID");
|
||||
assert!(rows[0].metadata["episode_counts"]["sub"].is_null());
|
||||
assert!(catalog(vec![media.clone(), media.clone()]).is_err());
|
||||
let episode = serde_json::json!({"episode_number":3,"absolute_number":49,"title":"Returned","synopsis":"Actual synopsis","aired_on":"2026-10-02","duration_seconds":1500});
|
||||
let detail = || Detail {
|
||||
media: media.clone(),
|
||||
episodes: vec![episode.clone()],
|
||||
};
|
||||
let data = series("opaque_ID", detail()).unwrap();
|
||||
assert_eq!(data.episodes.len(), 1);
|
||||
assert_eq!(data.episodes[0].identity.episode, 3);
|
||||
assert_eq!(data.episodes[0].identity.media_id, "opaque_ID");
|
||||
assert_eq!(data.episodes[0].duration_seconds, Some(1500));
|
||||
assert_eq!(
|
||||
data.episodes[0].synopsis.as_deref(),
|
||||
Some("Actual synopsis")
|
||||
);
|
||||
assert!(data.episodes[0].snapshot(&data.media).channel_id.is_none());
|
||||
assert!(series("other", detail()).is_err());
|
||||
assert!(
|
||||
series(
|
||||
"opaque_ID",
|
||||
Detail {
|
||||
media: media.clone(),
|
||||
episodes: vec![episode.clone(), episode]
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
series(
|
||||
"opaque_ID",
|
||||
Detail {
|
||||
media,
|
||||
episodes: vec![serde_json::json!({"absolute_number":49})]
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(slug("薬屋").is_err());
|
||||
assert_eq!(slug(" A Test!! -- Title ").unwrap(), "a-test-title");
|
||||
assert_eq!(slug(" --Title-- ").unwrap(), "-title-");
|
||||
|
||||
+1793
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user