7.4 KiB · text History 6c56e6c
//! One player's scrobble timing, as a state machine. Port of
//! scropple-android's `ScrobbleSession`: pure logic, all time passed in.
//!
//! The rule (Last.fm's): a track longer than 30s scrobbles once it has been
//! *played* for half its length or 4 minutes, whichever is less. "Played" is
//! time spent playing, so pauses don't count towards it.
//!
//! Where the Android session calls closures, this one returns what should
//! happen ([`Effect`]s), which keeps it pure and its tests direct.

use super::Track;

pub const MIN_TRACK_MS: u64 = 30_000;
pub const MAX_THRESHOLD_MS: u64 = 240_000;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
    /// Playing now: tell the backends.
    NowPlaying(Track),
    /// Qualified as a play that started at this Unix time (seconds).
    Scrobble(Track, i64),
}

#[derive(Debug, Default)]
pub struct Session {
    track: Option<Track>,
    played_ms: u64,
    playing: bool,
    last_tick_ms: u64,
    started_epoch: i64,
    now_playing_sent: bool,
    scrobbled: bool,
}

impl Session {
    pub fn new() -> Self {
        Self::default()
    }

    /// New or refreshed metadata.
    pub fn on_track(&mut self, track: Track, mono_ms: u64, epoch: i64) -> Vec<Effect> {
        if self.track.as_ref().map(Track::key) == Some(track.key()) {
            // Same track, refreshed fields (a late duration, say).
            self.track = Some(track);
            return vec![];
        }

        self.played_ms = 0;
        self.last_tick_ms = mono_ms;
        self.started_epoch = if self.playing { epoch } else { 0 };
        self.now_playing_sent = false;
        self.scrobbled = false;

        let mut effects = vec![];
        if self.playing && track.is_scrobbleable() {
            effects.push(Effect::NowPlaying(track.clone()));
            self.now_playing_sent = true;
        }
        self.track = Some(track);
        effects
    }

    /// Playback started or stopped (pause or stop).
    pub fn on_state(&mut self, playing: bool, mono_ms: u64, epoch: i64) -> Vec<Effect> {
        self.accumulate(mono_ms);
        self.playing = playing;
        self.last_tick_ms = mono_ms;

        let Some(track) = self.track.clone() else {
            return vec![];
        };

        let mut effects = vec![];
        if playing {
            if self.started_epoch == 0 {
                self.started_epoch = epoch;
            }
            if !self.now_playing_sent && track.is_scrobbleable() {
                effects.push(Effect::NowPlaying(track.clone()));
                self.now_playing_sent = true;
            }
        }
        effects.extend(self.maybe_scrobble(&track));
        effects
    }

    /// Periodic tick, so the threshold is reached during unbroken playback.
    pub fn tick(&mut self, mono_ms: u64) -> Vec<Effect> {
        self.accumulate(mono_ms);
        self.last_tick_ms = mono_ms;
        match self.track.clone() {
            Some(track) => self.maybe_scrobble(&track).into_iter().collect(),
            None => vec![],
        }
    }

    fn accumulate(&mut self, mono_ms: u64) {
        if self.playing && mono_ms > self.last_tick_ms {
            self.played_ms += mono_ms - self.last_tick_ms;
        }
    }

    fn maybe_scrobble(&mut self, track: &Track) -> Option<Effect> {
        if self.scrobbled || !track.is_scrobbleable() {
            return None;
        }
        let dur = track.duration_ms;
        if (1..=MIN_TRACK_MS).contains(&dur) {
            return None; // too short to count
        }
        let threshold = if dur == 0 {
            MAX_THRESHOLD_MS
        } else {
            (dur / 2).min(MAX_THRESHOLD_MS)
        };
        if self.played_ms >= threshold {
            self.scrobbled = true;
            return Some(Effect::Scrobble(track.clone(), self.started_epoch));
        }
        None
    }
}

#[cfg(test)]
mod tests {
    //! Ported from scropple-android's `ScrobbleSessionTest`.
    use super::*;

    fn track(duration_ms: u64) -> Track {
        Track {
            artist: "Pink Floyd".into(),
            title: "Time".into(),
            album: Some("The Dark Side of the Moon".into()),
            album_artist: None,
            duration_ms,
            player: "example".into(),
        }
    }

    fn scrobbles(effects: &[Effect]) -> usize {
        effects
            .iter()
            .filter(|e| matches!(e, Effect::Scrobble(..)))
            .count()
    }

    #[test]
    fn now_playing_is_emitted_when_playback_starts() {
        let mut s = Session::new();
        assert!(s.on_track(track(200_000), 0, 1_000).is_empty()); // not playing yet
        let effects = s.on_state(true, 0, 1_000);
        assert!(matches!(&effects[..], [Effect::NowPlaying(t)] if t.title == "Time"));
    }

    #[test]
    fn scrobbles_after_half_the_duration_of_actual_playback() {
        let mut s = Session::new();
        s.on_track(track(200_000), 0, 1_000); // 200s track -> threshold 100s
        s.on_state(true, 0, 1_000);
        assert_eq!(scrobbles(&s.tick(50_000)), 0); // only 50s played
        let effects = s.tick(100_001);
        assert!(matches!(&effects[..], [Effect::Scrobble(_, 1_000)])); // start epoch
    }

    #[test]
    fn paused_time_does_not_count_toward_the_threshold() {
        let mut s = Session::new();
        s.on_track(track(200_000), 0, 1_000);
        s.on_state(true, 0, 1_000);
        s.on_state(false, 60_000, 1_060); // played 60s, then pause
        assert_eq!(scrobbles(&s.tick(1_000_000)), 0); // a long pause
        s.on_state(true, 1_000_000, 2_000);
        assert_eq!(scrobbles(&s.tick(1_041_000)), 1); // +41s = 101s played
    }

    #[test]
    fn tracks_under_30_seconds_never_scrobble() {
        let mut s = Session::new();
        s.on_track(track(20_000), 0, 1_000);
        s.on_state(true, 0, 1_000);
        assert_eq!(scrobbles(&s.tick(60_000)), 0);
    }

    #[test]
    fn scrobble_fires_only_once_per_track() {
        let mut s = Session::new();
        s.on_track(track(200_000), 0, 1_000);
        s.on_state(true, 0, 1_000);
        let mut n = scrobbles(&s.tick(150_000));
        n += scrobbles(&s.tick(180_000));
        assert_eq!(n, 1);
    }

    #[test]
    fn unknown_duration_scrobbles_after_four_minutes() {
        let mut s = Session::new();
        s.on_track(track(0), 0, 1_000);
        s.on_state(true, 0, 1_000);
        assert_eq!(scrobbles(&s.tick(239_000)), 0);
        assert_eq!(scrobbles(&s.tick(240_001)), 1);
    }

    // Beyond the Android tests:

    #[test]
    fn a_new_track_while_playing_restarts_the_clock() {
        let mut s = Session::new();
        s.on_track(track(200_000), 0, 1_000);
        s.on_state(true, 0, 1_000);
        s.tick(90_000);
        let mut next = track(200_000);
        next.title = "Money".into();
        let effects = s.on_track(next, 90_000, 1_090);
        assert!(matches!(&effects[..], [Effect::NowPlaying(t)] if t.title == "Money"));
        assert_eq!(scrobbles(&s.tick(150_000)), 0); // 60s of Money
        assert!(matches!(&s.tick(190_001)[..], [Effect::Scrobble(t, 1_090)] if t.title == "Money"));
    }

    #[test]
    fn refreshed_metadata_for_the_same_track_keeps_the_clock() {
        let mut s = Session::new();
        s.on_track(track(0), 0, 1_000);
        s.on_state(true, 0, 1_000);
        s.tick(90_000);
        // The duration arrives late: 200s, threshold 100s, 90s already played.
        assert!(s.on_track(track(200_000), 90_000, 1_090).is_empty());
        assert_eq!(scrobbles(&s.tick(100_001)), 1);
    }
}