Skip to main content

#
jellytau_lib/player/
session.rs

    1use super::media::MediaItem;
    2/**
    3 * Media Session Management
    4 *
    5 * Tracks high-level playback context (Audio/Movie/TvShow/Idle) that persists
    6 * beyond individual playback states. Enables persistent UI (miniplayer) and
    7 * proper transitions between content types.
    8 *
    9 * See docs/architecture/01-rust-backend.md for the state machine diagram.
    10 */
    11use log::info;
    12use serde::{Deserialize, Serialize};
    13
    14/// Media session type tracking the high-level playback context
    15#[derive(specta::Type, Debug, Clone, Serialize, Deserialize, PartialEq)]
    16#[serde(tag = "type", rename_all = "snake_case")]
    17pub enum MediaSessionType {
    18    /// No active session - browsing library
    19    Idle,
    20
    21    /// Audio playback session (music, audiobooks, podcasts)
    22    /// Persists until explicitly dismissed
    23    Audio {
    24        /// Last/current track being played
    25        last_item: Option<MediaItem>,
    26        /// True = playing/paused, False = stopped/ended
    27        is_active: bool,
    28    },
    29
    30    /// Movie playback (single video, auto-dismiss on end)
    31    Movie {
    32        /// Currently loaded movie
    33        item: MediaItem,
    34        /// True = playing/paused, False = ended
    35        is_active: bool,
    36    },
    37
    38    /// TV show playback (supports next episode auto-advance)
    39    TvShow {
    40        /// Currently loaded episode
    41        item: MediaItem,
    42        /// Series ID for fetching next episodes
    43        series_id: String,
    44        /// True = playing/paused, False = ended
    45        is_active: bool,
    46    },
    47}
    48
    49impl MediaSessionType {
    50    /// Check if this is an active session (any type except Idle)
    51    #[allow(dead_code)]
    52    pub fn is_active_session(&self) -> bool {
    53        !matches!(self, MediaSessionType::Idle)
    54    }
    55
    56    /// Check if playback is currently active within the session
    57    #[allow(dead_code)]
    58    pub fn is_playing_or_paused(&self) -> bool {
    59        match self {
    60            MediaSessionType::Audio { is_active, .. } => *is_active,
    61            MediaSessionType::Movie { is_active, .. } => *is_active,
    62            MediaSessionType::TvShow { is_active, .. } => *is_active,
    63            MediaSessionType::Idle => false,
    64        }
    65    }
    66
    67    /// Get the current media item if any
    68    #[allow(dead_code)]
    69    pub fn current_item(&self) -> Option<&MediaItem> {
    70        match self {
    71            MediaSessionType::Audio { last_item, .. } => last_item.as_ref(),
    72            MediaSessionType::Movie { item, .. } => Some(item),
    73            MediaSessionType::TvShow { item, .. } => Some(item),
    74            MediaSessionType::Idle => None,
    75        }
    76    }
    77}
    78
    79/// Manages media session state transitions
    80pub struct MediaSessionManager {
    81    current: MediaSessionType,
    82}
    83
    84#[allow(dead_code)]
    85impl MediaSessionManager {
    86    pub fn new() -> Self {
    87        Self {
    88            current: MediaSessionType::Idle,
    89        }
    90    }
    91
    92    /// Get the current session state
    93    pub fn current(&self) -> &MediaSessionType {
    94        &self.current
    95    }
    96
    97    /// Start an audio session with a queue
    98    /// Transitions: Idle → Audio(active), Any → Audio(active)
    99    pub fn start_audio_session(&mut self, first_item: MediaItem) {
    100        info!(
    101            "[MediaSession] Starting audio session: {}",
    102            first_item.title
    103        );
    104        self.current = MediaSessionType::Audio {
    105            last_item: Some(first_item),
    106            is_active: true,
    107        };
    108    }
    109
    110    /// Update audio session with new track (during playback)
    111    pub fn update_audio_track(&mut self, item: MediaItem) {
    112        if let MediaSessionType::Audio {
    113            last_item,
    114            is_active,
    115        } = &mut self.current
    116        {
    117            info!("[MediaSession] Updating audio track: {}", item.title);
    118            *last_item = Some(item);
    119            *is_active = true;
    120        }
    121    }
    122
    123    /// Mark audio session as inactive (playback ended, queue finished)
    124    /// Session persists for resume
    125    pub fn audio_session_inactive(&mut self) {
    126        if let MediaSessionType::Audio { is_active, .. } = &mut self.current {
    127            info!("[MediaSession] Audio session now inactive (queue ended)");
    128            *is_active = false;
    129        }
    130    }
    131
    132    /// Resume audio session
    133    pub fn resume_audio_session(&mut self) {
    134        if let MediaSessionType::Audio { is_active, .. } = &mut self.current {
    135            info!("[MediaSession] Resuming audio session");
    136            *is_active = true;
    137        }
    138    }
    139
    140    /// Start a movie session
    141    /// Transitions: Any → Movie(active)
    142    pub fn start_movie_session(&mut self, item: MediaItem) {
    143        info!("[MediaSession] Starting movie session: {}", item.title);
    144        self.current = MediaSessionType::Movie {
    145            item,
    146            is_active: true,
    147        };
    148    }
    149
    150    /// Mark movie session as inactive (playback ended)
    151    /// Movie sessions auto-dismiss to Idle
    152    pub fn movie_session_ended(&mut self) {
    153        if matches!(self.current, MediaSessionType::Movie { .. }) {
    154            info!("[MediaSession] Movie ended, transitioning to Idle");
    155            self.current = MediaSessionType::Idle;
    156        }
    157    }
    158
    159    /// Start a TV show session
    160    /// Transitions: Any → TvShow(active)
    161    pub fn start_tv_session(&mut self, item: MediaItem, series_id: String) {
    162        info!("[MediaSession] Starting TV show session: {}", item.title);
    163        self.current = MediaSessionType::TvShow {
    164            item,
    165            series_id,
    166            is_active: true,
    167        };
    168    }
    169
    170    /// Mark TV show session as inactive (episode ended, awaiting next)
    171    pub fn tv_session_episode_ended(&mut self) {
    172        if let MediaSessionType::TvShow { is_active, .. } = &mut self.current {
    173            info!("[MediaSession] Episode ended, awaiting next episode");
    174            *is_active = false;
    175        }
    176    }
    177
    178    /// Advance to next episode in TV session
    179    pub fn tv_session_next_episode(&mut self, next_item: MediaItem) {
    180        if let MediaSessionType::TvShow {
    181            item, is_active, ..
    182        } = &mut self.current
    183        {
    184            info!(
    185                "[MediaSession] Advancing to next episode: {}",
    186                next_item.title
    187            );
    188            *item = next_item;
    189            *is_active = true;
    190        }
    191    }
    192
    193    /// End TV show session (series complete or user dismissed)
    194    pub fn tv_session_ended(&mut self) {
    195        if matches!(self.current, MediaSessionType::TvShow { .. }) {
    196            info!("[MediaSession] TV show session ended, transitioning to Idle");
    197            self.current = MediaSessionType::Idle;
    198        }
    199    }
    200
    201    /// Dismiss/clear current session (user action)
    202    /// Transitions: Any → Idle
    203    pub fn dismiss(&mut self) {
    204        info!("[MediaSession] Dismissing session: {:?}", self.current);
    205        self.current = MediaSessionType::Idle;
    206    }
    207
    208    /// Check if we should show miniplayer
    209    pub fn should_show_miniplayer(&self) -> bool {
    210        matches!(self.current, MediaSessionType::Audio { .. })
    211    }
    212
    213    /// Check if we should show video player
    214    pub fn should_show_video_player(&self) -> bool {
    215        matches!(
    216            self.current,
    217            MediaSessionType::Movie { .. } | MediaSessionType::TvShow { .. }
    218        )
    219    }
    220}
    221
    222impl Default for MediaSessionManager {
    223    fn default() -> Self {
    224        Self::new()
    225    }
    226}
    227
    228#[cfg(test)]
    229mod tests {
    230    use super::*;
    231    use crate::player::media::MediaSource;
    232
    233    fn create_test_audio_item(title: &str) -> MediaItem {
    234        MediaItem {
    235            // Audio and direct-URL items never negotiate a transport.
    236            transport: None,
    237            id: title.to_string(),
    238            title: title.to_string(),
    239            name: Some(title.to_string()),
    240            artist: Some("Test Artist".to_string()),
    241            album: Some("Test Album".to_string()),
    242            album_name: Some("Test Album".to_string()),
    243            album_id: None,
    244            artist_items: None,
    245            artists: Some(vec!["Test Artist".to_string()]),
    246            primary_image_tag: None,
    247            image_id: None,
    248            item_type: Some("Audio".to_string()),
    249            playlist_id: None,
    250            duration: Some(180.0),
    251            artwork_url: None,
    252            media_type: crate::player::media::MediaType::Audio,
    253            source: MediaSource::DirectUrl {
    254                url: "http://example.com/audio.mp3".to_string(),
    255            },
    256            video_codec: None,
    257            needs_transcoding: false,
    258            video_width: None,
    259            video_height: None,
    260            subtitles: vec![],
    261            series_id: None,
    262            server_id: None,
    263        }
    264    }
    265
    266    fn create_test_movie_item(title: &str) -> MediaItem {
    267        MediaItem {
    268            // Audio and direct-URL items never negotiate a transport.
    269            transport: None,
    270            id: title.to_string(),
    271            title: title.to_string(),
    272            name: Some(title.to_string()),
    273            artist: None,
    274            album: None,
    275            album_name: None,
    276            album_id: None,
    277            artist_items: None,
    278            artists: None,
    279            primary_image_tag: None,
    280            image_id: None,
    281            item_type: Some("Movie".to_string()),
    282            playlist_id: None,
    283            duration: Some(7200.0),
    284            artwork_url: None,
    285            media_type: crate::player::media::MediaType::Video,
    286            source: MediaSource::DirectUrl {
    287                url: "http://example.com/movie.mp4".to_string(),
    288            },
    289            video_codec: None,
    290            needs_transcoding: false,
    291            video_width: None,
    292            video_height: None,
    293            subtitles: vec![],
    294            series_id: None,
    295            server_id: None,
    296        }
    297    }
    298
    299    #[test]
    300    fn test_initial_state_is_idle() {
    301        let manager = MediaSessionManager::new();
    302        assert_eq!(manager.current(), &MediaSessionType::Idle);
    303    }
    304
    305    #[test]
    306    fn test_audio_session_lifecycle() {
    307        let mut manager = MediaSessionManager::new();
    308
    309        // Start audio session
    310        let track = create_test_audio_item("Track 1");
    311        manager.start_audio_session(track.clone());
    312
    313        assert!(matches!(
    314            manager.current(),
    315            MediaSessionType::Audio {
    316                is_active: true,
    317                ..
    318            }
    319        ));
    320        assert!(manager.should_show_miniplayer());
    321
    322        // Update to next track
    323        let track2 = create_test_audio_item("Track 2");
    324        manager.update_audio_track(track2);
    325        assert!(manager.current().is_playing_or_paused());
    326
    327        // Queue ends, session goes inactive
    328        manager.audio_session_inactive();
    329        assert!(matches!(
    330            manager.current(),
    331            MediaSessionType::Audio {
    332                is_active: false,
    333                ..
    334            }
    335        ));
    336        assert!(manager.should_show_miniplayer()); // Still shows!
    337
    338        // Resume
    339        manager.resume_audio_session();
    340        assert!(manager.current().is_playing_or_paused());
    341
    342        // Dismiss
    343        manager.dismiss();
    344        assert_eq!(manager.current(), &MediaSessionType::Idle);
    345        assert!(!manager.should_show_miniplayer());
    346    }
    347
    348    #[test]
    349    fn test_movie_session_auto_dismiss() {
    350        let mut manager = MediaSessionManager::new();
    351
    352        let movie = create_test_movie_item("Test Movie");
    353        manager.start_movie_session(movie);
    354
    355        assert!(matches!(
    356            manager.current(),
    357            MediaSessionType::Movie {
    358                is_active: true,
    359                ..
    360            }
    361        ));
    362        assert!(manager.should_show_video_player());
    363
    364        // Movie ends, auto-dismiss to Idle
    365        manager.movie_session_ended();
    366        assert_eq!(manager.current(), &MediaSessionType::Idle);
    367    }
    368
    369    #[test]
    370    fn test_session_replacement() {
    371        let mut manager = MediaSessionManager::new();
    372
    373        // Start with audio
    374        let track = create_test_audio_item("Track 1");
    375        manager.start_audio_session(track);
    376        assert!(manager.should_show_miniplayer());
    377
    378        // Switch to movie (replaces audio session)
    379        let movie = create_test_movie_item("Test Movie");
    380        manager.start_movie_session(movie);
    381        assert!(!manager.should_show_miniplayer());
    382        assert!(manager.should_show_video_player());
    383    }
    384}