kopuz-hooks 0.12.0

A modern, lightweight music player built with Rust and Dioxus.
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use config::AppConfig;
use dioxus::core::Runtime;
use dioxus::logger::tracing::Instrument;
use dioxus::prelude::*;
use reader::Track;
use std::collections::HashMap;
use std::time::Duration;

const NOW_PLAYING_INTERVAL_SECS: u64 = 30;
const NOW_PLAYING_MAX_IDLE_SECS: u64 = 600;

#[derive(Clone, Copy)]
pub struct ScrobbleOptions {
    pub include_librefm: bool,
    pub include_musicbrainz_ids: bool,
}

impl ScrobbleOptions {
    pub const REMOTE_NATIVE: Self = Self {
        include_librefm: true,
        include_musicbrainz_ids: false,
    };

    pub const REMOTE_WEB: Self = Self {
        include_librefm: false,
        include_musicbrainz_ids: false,
    };

    pub const LOCAL: Self = Self {
        include_librefm: false,
        include_musicbrainz_ids: true,
    };
}

#[allow(clippy::too_many_arguments)]
pub fn schedule(
    track: Track,
    item_id: Option<String>,
    config: Signal<AppConfig>,
    session_token: Signal<u64>,
    generation: u64,
    is_playing: Signal<bool>,
    active_source: Option<Signal<::server::source::ActiveSource>>,
    options: ScrobbleOptions,
    db: db::Db,
) {
    let duration_secs = track.duration;
    let threshold_secs = std::cmp::min(240, duration_secs / 2);
    let started_at = scrobble::musicbrainz::now_unix();
    let span = tracing::info_span!(
        "scrobble.submit",
        track = item_id.as_deref().unwrap_or(track.id.uid().as_str())
    );

    schedule_playing_now_heartbeat(
        &track,
        config,
        session_token,
        generation,
        is_playing,
        options,
    );

    spawn_in_scope(
        session_token.origin_scope(),
        async move {
            if duration_secs < 30 {
                tracing::info!(
                    "scrobble skipped: track too short ({duration_secs}s < 30s): {} - {}",
                    track.artist,
                    track.title
                );
                return;
            }

            if track.artist.trim().is_empty() || track.title.trim().is_empty() {
                tracing::info!(
                    "scrobble skipped: missing artist or title metadata: {:?} - {:?}",
                    track.artist,
                    track.title
                );
                return;
            }

            if let (Some(source), Some(id)) = (active_source, item_id.as_deref()) {
                let source = source.peek().clone();
                if let Err(error) = source.scrobble_now_playing(id).await {
                    tracing::warn!("now-playing scrobble failed: {}", error);
                }
            }

            let lastfm_api_key = config.read().lastfm_api_key.clone();
            let lastfm_api_secret = config.read().lastfm_api_secret.clone();
            let lastfm_session_key = config.read().lastfm_session_key.clone();
            let has_lastfm = !lastfm_api_key.is_empty() && !lastfm_api_secret.is_empty();

            if has_lastfm {
                let playing_now = scrobble::lastfm::make_playing_now(
                    &track.artist,
                    &track.title,
                    Some(&track.album),
                );
                if let Err(error) = scrobble::lastfm::submit_now_playing(
                    &lastfm_api_key,
                    &lastfm_api_secret,
                    &lastfm_session_key,
                    &playing_now,
                )
                .await
                {
                    tracing::warn!("Last.fm now playing failed: {}", error);
                }
            }

            let librefm_session_key = config.read().librefm_session_key.clone();
            let has_librefm = options.include_librefm && !librefm_session_key.is_empty();

            if has_librefm {
                let playing_now = scrobble::librefm::make_playing_now(
                    &track.artist,
                    &track.title,
                    Some(&track.album),
                );
                if let Err(error) = scrobble::librefm::submit_now_playing(
                    scrobble::librefm::API_KEY,
                    scrobble::librefm::API_SECRET,
                    &librefm_session_key,
                    &playing_now,
                )
                .await
                {
                    tracing::warn!("Libre.fm now playing failed: {}", error);
                }
            }

            let reached = wait_for_playtime(
                Duration::from_secs(threshold_secs),
                session_token,
                generation,
                is_playing,
            )
            .await;

            if !reached {
                tracing::info!(
                    "scrobble skipped: track changed before {threshold_secs}s of playback: {} - {}",
                    track.artist,
                    track.title
                );
                return;
            }

            if let (Some(source), Some(id)) = (active_source, item_id.as_deref()) {
                let source = source.peek().clone();
                match source.scrobble(id).await {
                    Ok(_) => tracing::info!("scrobbled: {} - {}", track.artist, track.title),
                    Err(error) => tracing::warn!("scrobble failed: {}", error),
                }
            }

            // Offline queue bookkeeping (issue #335): scrobbles that fail with
            // a transient error are queued with the original listen timestamp
            // (`started_at`) and resubmitted later; one success means we're
            // online, so drain the backlog.
            let mut scrobble_ok = false;

            if has_lastfm {
                let scrobble = scrobble::lastfm::make_scrobble_at(
                    &track.artist,
                    &track.title,
                    Some(&track.album),
                    started_at,
                );
                match scrobble::lastfm::submit_scrobble(
                    &lastfm_api_key,
                    &lastfm_api_secret,
                    &lastfm_session_key,
                    &scrobble,
                )
                .await
                {
                    Ok(_) => {
                        scrobble_ok = true;
                        tracing::info!("Last.fm scrobbled: {} - {}", track.artist, track.title)
                    }
                    Err(error) => {
                        tracing::warn!("Last.fm scrobble failed: {}", error);
                        if scrobble::queue::is_transient(&error) {
                            scrobble::queue::enqueue(
                                &db,
                                scrobble::queue::ScrobbleService::LastFm,
                                &track.artist,
                                &track.title,
                                Some(&track.album),
                                started_at,
                                None,
                            )
                            .await;
                        }
                    }
                }
            }

            if has_librefm {
                let scrobble = scrobble::librefm::make_scrobble_at(
                    &track.artist,
                    &track.title,
                    Some(&track.album),
                    started_at,
                );
                match scrobble::librefm::submit_scrobble(
                    scrobble::librefm::API_KEY,
                    scrobble::librefm::API_SECRET,
                    &librefm_session_key,
                    &scrobble,
                )
                .await
                {
                    Ok(_) => {
                        scrobble_ok = true;
                        tracing::info!("Libre.fm scrobbled: {} - {}", track.artist, track.title)
                    }
                    Err(error) => {
                        tracing::warn!("Libre.fm scrobble failed: {}", error);
                        if scrobble::queue::is_transient(&error) {
                            scrobble::queue::enqueue(
                                &db,
                                scrobble::queue::ScrobbleService::LibreFm,
                                &track.artist,
                                &track.title,
                                Some(&track.album),
                                started_at,
                                None,
                            )
                            .await;
                        }
                    }
                }
            }

            let token = config.read().musicbrainz_token.clone();
            if !token.trim().is_empty() {
                let info = listen_additional_info(&track, options.include_musicbrainz_ids);
                let queued_info: serde_json::Map<String, serde_json::Value> = info
                    .iter()
                    .map(|(k, v)| ((*k).to_string(), v.clone()))
                    .collect();
                let listen = scrobble::musicbrainz::make_listen(
                    &track.artist,
                    &track.title,
                    Some(&track.album),
                    Some(info),
                    started_at,
                );
                match scrobble::musicbrainz::submit_listens(&token, vec![listen], "single").await {
                    Ok(_) => {
                        scrobble_ok = true;
                        tracing::info!("MusicBrainz scrobbled: {} - {}", track.artist, track.title)
                    }
                    Err(error) => {
                        tracing::warn!("MusicBrainz scrobble failed: {}", error);
                        if scrobble::queue::is_transient(&error) {
                            scrobble::queue::enqueue(
                                &db,
                                scrobble::queue::ScrobbleService::ListenBrainz,
                                &track.artist,
                                &track.title,
                                Some(&track.album),
                                started_at,
                                Some(queued_info),
                            )
                            .await;
                        }
                    }
                }
            }

            // One success means we're online again: flush queued scrobbles.
            if scrobble_ok {
                let musicbrainz_token = config.read().musicbrainz_token.clone();
                let creds = scrobble::queue::Credentials {
                    lastfm: has_lastfm.then(|| {
                        (
                            lastfm_api_key.clone(),
                            lastfm_api_secret.clone(),
                            lastfm_session_key.clone(),
                        )
                    }),
                    librefm_session_key: has_librefm.then(|| librefm_session_key.clone()),
                    listenbrainz_token: (!musicbrainz_token.trim().is_empty())
                        .then(|| musicbrainz_token.clone()),
                };
                scrobble::queue::drain(&db, &creds).await;
            }
        }
        .instrument(span),
    );
}

fn schedule_playing_now_heartbeat(
    track: &Track,
    config: Signal<AppConfig>,
    session_token: Signal<u64>,
    generation: u64,
    is_playing: Signal<bool>,
    options: ScrobbleOptions,
) {
    if track.duration < 30 {
        return;
    }

    let token = config.read().musicbrainz_token.clone();
    if token.trim().is_empty() {
        return;
    }

    let track = track.clone();
    let include_ids = options.include_musicbrainz_ids;
    let span = tracing::info_span!("scrobble.playing_now", track = track.id.uid().as_str());

    spawn_in_scope(
        session_token.origin_scope(),
        async move {
            let mut announced = false;
            let mut idle_secs: u64 = 0;
            loop {
                if *session_token.read() != generation {
                    return;
                }

                if *is_playing.read() {
                    idle_secs = 0;
                    let now_info = listen_additional_info(&track, include_ids);
                    let playing_now = scrobble::musicbrainz::make_playing_now(
                        &track.artist,
                        &track.title,
                        Some(&track.album),
                        Some(now_info),
                    );
                    let sent = scrobble::musicbrainz::submit_listens(
                        &token,
                        vec![playing_now],
                        "playing_now",
                    )
                    .await
                    .is_ok();
                    if sent && !announced {
                        announced = true;
                        tracing::info!(
                            "ListenBrainz playing now: {} - {}",
                            track.artist,
                            track.title
                        );
                    }
                } else {
                    idle_secs += NOW_PLAYING_INTERVAL_SECS;
                    if idle_secs >= NOW_PLAYING_MAX_IDLE_SECS {
                        return;
                    }
                }

                tokio::time::sleep(Duration::from_secs(NOW_PLAYING_INTERVAL_SECS)).await;
            }
        }
        .instrument(span),
    );
}

fn listen_additional_info(
    track: &Track,
    include_ids: bool,
) -> HashMap<&'static str, serde_json::Value> {
    let mut map = HashMap::new();
    map.insert("media_player", serde_json::Value::from("kopuz"));
    map.insert("submission_client", serde_json::Value::from("kopuz"));
    map.insert(
        "submission_client_version",
        serde_json::Value::from(env!("CARGO_PKG_VERSION")),
    );
    if track.duration > 0 {
        map.insert(
            "duration_ms",
            serde_json::Value::from(track.duration * 1000),
        );
    }

    if include_ids {
        if let Some(mbid) = &track.musicbrainz_release_id {
            map.insert("release_mbid", serde_json::Value::from(mbid.as_str()));
        }
        if let Some(mbid) = &track.musicbrainz_recording_id {
            map.insert("recording_mbid", serde_json::Value::from(mbid.as_str()));
        }
        if let Some(mbid) = &track.musicbrainz_track_id {
            map.insert("track_mbid", serde_json::Value::from(mbid.as_str()));
        }
    }

    map
}

fn spawn_in_scope(scope: ScopeId, fut: impl std::future::Future<Output = ()> + 'static) {
    Runtime::current().in_scope(scope, || {
        spawn(fut);
    });
}

async fn wait_for_playtime(
    threshold: Duration,
    session_token: Signal<u64>,
    generation: u64,
    is_playing: Signal<bool>,
) -> bool {
    let tick = Duration::from_secs(1);
    let mut played = Duration::ZERO;

    while played < threshold {
        tokio::time::sleep(tick).await;

        if *session_token.read() != generation {
            return false;
        }

        if *is_playing.read() {
            played += tick;
        }
    }

    true
}