about summary refs log tree commit diff stats
path: root/pkgs/by-name/mp/mpdpopm/src/playcounts.rs
blob: 7d646b4c1cfb2098d47c62a51cb5861cb72283bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// Copyright (C) 2020-2025 Michael herstine <sp1ff@pobox.com>
//
// This file is part of mpdpopm.
//
// mpdpopm is free software: you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// mpdpopm is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along with mpdpopm.  If not,
// see <http://www.gnu.org/licenses/>.

//! playcounts -- managing play counts & lastplayed times
//!
//! # Introduction
//!
//! Play counts & last played timestamps are maintained so long as [PlayState::update] is called
//! regularly (every few seconds, say). For purposes of library maintenance, however, they can be
//! set explicitly:
//!
//! - `setpc PLAYCOUNT( TRACK)?`
//! - `setlp LASTPLAYED( TRACK)?`
//!

use crate::clients::{Client, PlayerStatus};
use crate::storage::{last_played, play_count, skipped};

use anyhow::{Context, Error, Result, anyhow};
use tracing::{debug, info};

use std::time::SystemTime;

/// Current server state in terms of the play status (stopped/paused/playing, current track, elapsed
/// time in current track, &c)
#[derive(Debug)]
pub struct PlayState {
    /// Last known server status
    last_server_stat: PlayerStatus,

    /// true if we have already incremented the last known track's playcount
    have_incr_play_count: bool,

    /// Percentage threshold, expressed as a number between zero & one, for considering a song to
    /// have been played
    played_thresh: f64,
    last_song_was_skipped: bool,
}

impl PlayState {
    /// Create a new PlayState instance; async because it will reach out to the mpd server
    /// to get current status.
    pub async fn new(
        client: &mut Client,
        played_thresh: f64,
    ) -> std::result::Result<PlayState, Error> {
        Ok(PlayState {
            last_server_stat: client.status().await?,
            have_incr_play_count: false,
            last_song_was_skipped: false,
            played_thresh,
        })
    }

    /// Retrieve a copy of the last known player status
    pub fn last_status(&self) -> PlayerStatus {
        self.last_server_stat.clone()
    }

    /// Poll the server-- update our status; maybe increment the current track's play count; the
    /// caller must arrange to have this method invoked periodically to keep our state fresh
    pub async fn update(&mut self, client: &mut Client) -> Result<()> {
        let new_stat = client
            .status()
            .await
            .context("Failed to get client status")?;

        match (&self.last_server_stat, &new_stat) {
            (PlayerStatus::Play(last), PlayerStatus::Play(curr))
            | (PlayerStatus::Pause(last), PlayerStatus::Play(curr))
            | (PlayerStatus::Play(last), PlayerStatus::Pause(curr))
            | (PlayerStatus::Pause(last), PlayerStatus::Pause(curr)) => {
                // Last we knew, we were playing, and we're playing now.
                if last.songid != curr.songid {
                    debug!("New songid-- resetting PC incremented flag.");

                    if !self.have_incr_play_count {
                        // We didn't mark the previous song as played.
                        // As such, the user must have skipped it :(
                        self.last_song_was_skipped = true;
                    }

                    self.have_incr_play_count = false;
                } else if last.elapsed > curr.elapsed
                    && self.have_incr_play_count
                    && curr.elapsed / curr.duration <= 0.1
                {
                    debug!("Re-play-- resetting PC incremented flag.");
                    self.have_incr_play_count = false;
                }
            }
            (PlayerStatus::Stopped, PlayerStatus::Play(_))
            | (PlayerStatus::Stopped, PlayerStatus::Pause(_))
            | (PlayerStatus::Pause(_), PlayerStatus::Stopped)
            | (PlayerStatus::Play(_), PlayerStatus::Stopped) => {
                self.have_incr_play_count = false;
            }
            (PlayerStatus::Stopped, PlayerStatus::Stopped) => (),
        }

        match &new_stat {
            PlayerStatus::Play(curr) => {
                let pct = curr.played_pct();
                debug!("Updating status: {:.3}% complete.", 100.0 * pct);
                if !self.have_incr_play_count && pct >= self.played_thresh {
                    info!(
                        "Increment play count for '{}' (songid: {}) at {} played.",
                        curr.file.display(),
                        curr.songid,
                        curr.elapsed / curr.duration
                    );

                    let file = curr.file.to_str().ok_or_else(|| {
                        anyhow!("Failed to parse path as utf8: `{}`", curr.file.display())
                    })?;

                    let curr_pc = play_count::get(client, file).await?.unwrap_or_default();

                    debug!("Current PC is {}.", curr_pc);

                    last_played::set(
                        client,
                        file,
                        SystemTime::now()
                            .duration_since(SystemTime::UNIX_EPOCH)
                            .context("Failed to get system time")?
                            .as_secs(),
                    )
                    .await?;
                    self.have_incr_play_count = true;

                    play_count::set(client, file, curr_pc + 1).await?;
                } else if self.last_song_was_skipped {
                    self.last_song_was_skipped = false;
                    let last = self
                        .last_server_stat
                        .current_song()
                        .expect("To exist, as it was skipped");

                    info!(
                        "Marking '{}' (songid: {}) as skipped at {}.",
                        last.file.display(),
                        last.songid,
                        last.elapsed / last.duration
                    );

                    let file = last.file.to_str().ok_or_else(|| {
                        anyhow!("Failed to parse path as utf8: `{}`", last.file.display())
                    })?;

                    let skip_count = skipped::get(client, file).await?.unwrap_or_default();
                    skipped::set(client, file, skip_count + 1).await?;
                }
            }
            PlayerStatus::Pause(_) | PlayerStatus::Stopped => (),
        };

        self.last_server_stat = new_stat;
        Ok(()) // No need to update the DB
    }
}

#[cfg(test)]
mod player_state_tests {
    use super::*;
    use crate::clients::test_mock::Mock;

    /// "Smoke" tests for player state
    #[tokio::test]
    async fn player_state_smoke() {
        let mock = Box::new(Mock::new(&[
            (
                "status",
                "repeat: 0
random: 1
single: 0
consume: 1
playlist: 2
playlistlength: 66
mixrampdb: 0.000000
state: stop
xfade: 5
song: 51
songid: 52
nextsong: 11
nextsongid: 12
OK
",
            ),
            (
                "status",
                "volume: 100
repeat: 0
random: 1
single: 0
consume: 1
playlist: 2
playlistlength: 66
mixrampdb: 0.000000
state: play
xfade: 5
song: 51
songid: 52
time: 5:228
elapsed: 5.337
bitrate: 192
duration: 227.637
audio: 44100:24:2
nextsong: 11
nextsongid: 12
OK
",
            ),
            (
                "playlistid 52",
                "file: E/Enya - Wild Child.mp3
Last-Modified: 2008-11-09T00:06:30Z
Artist: Enya
Title: Wild Child
Album: A Day Without Rain (Japanese Retail)
Date: 2000
Genre: Celtic
Time: 228
duration: 227.637
Pos: 51
Id: 52
OK
",
            ),
            (
                "status",
                "volume: 100
repeat: 0
random: 1
single: 0
consume: 1
playlist: 2
playlistlength: 66
mixrampdb: 0.000000
state: play
xfade: 5
song: 51
songid: 52
time: 5:228
elapsed: 200
bitrate: 192
duration: 227.637
audio: 44100:24:2
nextsong: 11
nextsongid: 12
OK
",
            ),
            (
                "playlistid 52",
                "file: E/Enya - Wild Child.mp3
Last-Modified: 2008-11-09T00:06:30Z
Artist: Enya
Title: Wild Child
Album: A Day Without Rain (Japanese Retail)
Date: 2000
Genre: Celtic
Time: 228
duration: 227.637
Pos: 51
Id: 52
OK
",
            ),
            (
                "sticker get song \"E/Enya - Wild Child.mp3\" unwoundstack.com:playcount",
                "sticker: unwoundstack.com:playcount=11\nOK\n",
            ),
            (
                &format!(
                    "sticker set song \"E/Enya - Wild Child.mp3\" unwoundstack.com:lastplayed {}",
                    SystemTime::now()
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .unwrap()
                        .as_secs()
                ),
                "OK\n",
            ),
            (
                "sticker set song \"E/Enya - Wild Child.mp3\" unwoundstack.com:playcount 12",
                "OK\n",
            ),
        ]));

        let mut cli = Client::new(mock).unwrap();
        let mut ps = PlayState::new(&mut cli, 0.6).await.unwrap();
        let check = match ps.last_status() {
            PlayerStatus::Play(_) | PlayerStatus::Pause(_) => false,
            PlayerStatus::Stopped => true,
        };
        assert!(check);

        ps.update(&mut cli).await.unwrap();
        ps.update(&mut cli).await.unwrap()
    }
}