ListenBrainz and Last.fm backends; scropple login

0463cca · gmorell · 2026-11-19 20:30

16 files +1231 -221
Message
{commit_body(@commit)}

Files changed

modified Cargo.lock
+81 −0
@@ -148,6 +148,15 @@ version = "2.13.2"
148 148 source = "registry+https://github.com/rust-lang/crates.io-index"
149 149 checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
150 150
151 +[[package]]
152 +name = "block-buffer"
153 +version = "0.10.4"
154 +source = "registry+https://github.com/rust-lang/crates.io-index"
155 +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
156 +dependencies = [
157 + "generic-array",
158 +]
159 +
151 160 [[package]]
152 161 name = "bumpalo"
153 162 version = "3.20.4"
@@ -285,6 +294,26 @@ dependencies = [
285 294 "libc",
286 295 ]
287 296
297 +[[package]]
298 +name = "crypto-common"
299 +version = "0.1.7"
300 +source = "registry+https://github.com/rust-lang/crates.io-index"
301 +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
302 +dependencies = [
303 + "generic-array",
304 + "typenum",
305 +]
306 +
307 +[[package]]
308 +name = "digest"
309 +version = "0.10.7"
310 +source = "registry+https://github.com/rust-lang/crates.io-index"
311 +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
312 +dependencies = [
313 + "block-buffer",
314 + "crypto-common",
315 +]
316 +
288 317 [[package]]
289 318 name = "directories"
290 319 version = "6.0.0"
@@ -495,6 +524,16 @@ dependencies = [
495 524 "slab",
496 525 ]
497 526
527 +[[package]]
528 +name = "generic-array"
529 +version = "0.14.7"
530 +source = "registry+https://github.com/rust-lang/crates.io-index"
531 +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
532 +dependencies = [
533 + "typenum",
534 + "version_check",
535 +]
536 +
498 537 [[package]]
499 538 name = "getrandom"
500 539 version = "0.2.17"
@@ -916,6 +955,16 @@ dependencies = [
916 955 "regex-automata",
917 956 ]
918 957
958 +[[package]]
959 +name = "md-5"
960 +version = "0.10.6"
961 +source = "registry+https://github.com/rust-lang/crates.io-index"
962 +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
963 +dependencies = [
964 + "cfg-if",
965 + "digest",
966 +]
967 +
919 968 [[package]]
920 969 name = "memchr"
921 970 version = "2.8.3"
@@ -1186,6 +1235,7 @@ dependencies = [
1186 1235 "rustls-platform-verifier",
1187 1236 "serde",
1188 1237 "serde_json",
1238 + "serde_urlencoded",
1189 1239 "sync_wrapper",
1190 1240 "tokio",
1191 1241 "tokio-rustls",
@@ -1345,6 +1395,12 @@ version = "1.0.23"
1345 1395 source = "registry+https://github.com/rust-lang/crates.io-index"
1346 1396 checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
1347 1397
1398 +[[package]]
1399 +name = "ryu"
1400 +version = "1.0.23"
1401 +source = "registry+https://github.com/rust-lang/crates.io-index"
1402 +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
1403 +
1348 1404 [[package]]
1349 1405 name = "same-file"
1350 1406 version = "1.0.6"
@@ -1371,6 +1427,7 @@ dependencies = [
1371 1427 "clap",
1372 1428 "directories",
1373 1429 "futures-util",
1430 + "md-5",
1374 1431 "reqwest",
1375 1432 "rusqlite",
1376 1433 "serde",
@@ -1474,6 +1531,18 @@ dependencies = [
1474 1531 "serde_core",
1475 1532 ]
1476 1533
1534 +[[package]]
1535 +name = "serde_urlencoded"
1536 +version = "0.7.1"
1537 +source = "registry+https://github.com/rust-lang/crates.io-index"
1538 +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
1539 +dependencies = [
1540 + "form_urlencoded",
1541 + "itoa",
1542 + "ryu",
1543 + "serde",
1544 +]
1545 +
1477 1546 [[package]]
1478 1547 name = "sharded-slab"
1479 1548 version = "0.1.7"
@@ -1866,6 +1935,12 @@ version = "0.2.5"
1866 1935 source = "registry+https://github.com/rust-lang/crates.io-index"
1867 1936 checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
1868 1937
1938 +[[package]]
1939 +name = "typenum"
1940 +version = "1.20.1"
1941 +source = "registry+https://github.com/rust-lang/crates.io-index"
1942 +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
1943 +
1869 1944 [[package]]
1870 1945 name = "uds_windows"
1871 1946 version = "1.2.1"
@@ -1945,6 +2020,12 @@ version = "0.2.15"
1945 2020 source = "registry+https://github.com/rust-lang/crates.io-index"
1946 2021 checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
1947 2022
2023 +[[package]]
2024 +name = "version_check"
2025 +version = "0.9.5"
2026 +source = "registry+https://github.com/rust-lang/crates.io-index"
2027 +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
2028 +
1948 2029 [[package]]
1949 2030 name = "walkdir"
1950 2031 version = "2.5.0"
modified Cargo.toml
+6 −5
@@ -2,7 +2,7 @@
2 2 name = "scropple-linux"
3 3 version = "0.1.0"
4 4 edition = "2024"
5 −description = "Scrobble what Linux media players play (MPRIS over D-Bus) to Scropple-compatible backends"
5 +description = "Scrobble what Linux media players play (MPRIS over D-Bus) to Scropple servers, ListenBrainz and Last.fm"
6 6 license = "GPL-3.0-or-later"
7 7 repository = "https://gg.neiam.co/r/neiam/scropple-linux"
8 8
@@ -15,7 +15,8 @@ anyhow = "1.0.104"
15 15 clap = { version = "4.6.8", features = ["derive"] }
16 16 directories = "6.0.0"
17 17 futures-util = "0.3.34"
18 −reqwest = { version = "0.13.5", default-features = false, features = ["json", "rustls"] }
18 +md-5 = "0.10.6"
19 +reqwest = { version = "0.13.5", default-features = false, features = ["json", "form", "query", "rustls"] }
19 20 rusqlite = { version = "0.43.0", features = ["bundled"] }
20 21 serde = { version = "1.0.229", features = ["derive"] }
21 22 serde_json = "1.0.154"
@@ -42,8 +43,8 @@ priority = "optional"
42 43 depends = "$auto"
43 44 extended-description = """
44 45 Follows media players on the session bus (MPRIS 2) and scrobbles what
45 −they play to Scropple-compatible servers such as final_track, with an
46 −offline queue. Runs as a systemd user service: after installing,
46 +they play to Scropple servers such as final_track, to ListenBrainz and to
47 +Last.fm, with an offline queue. Runs as a systemd user service: after installing,
47 48 `scropple init`, then `systemctl --user enable --now scropple`.
48 49 """
49 50 assets = [
@@ -55,7 +56,7 @@ assets = [
55 56
56 57 [package.metadata.generate-rpm]
57 58 name = "scropple"
58 −summary = "Scrobble what Linux media players play (MPRIS) to Scropple-compatible servers"
59 +summary = "Scrobble what Linux media players play (MPRIS) to Scropple servers, ListenBrainz and Last.fm"
59 60 assets = [
60 61 { source = "target/release/scropple", dest = "/usr/bin/scropple", mode = "755" },
61 62 { source = "packaging/scropple.service", dest = "/usr/lib/systemd/user/scropple.service", mode = "644" },
modified README.md
+48 −7
@@ -3,8 +3,12 @@
3 3 Scrobbles what your Linux media players play. It follows players over
4 4 **MPRIS** on the session bus — Spotify, Strawberry, Rhythmbox, Elisa, VLC,
5 5 mpv (with its `mpris` script), and anything else that speaks it — and sends
6 −what you play to **Scropple-compatible backends**: final_track, ircd's
7 −ScrobbleServ, anything that takes the Scropple HTTP backend's JSON.
6 +what you play to any number of backends at once:
7 +
8 +- **Scropple servers**: final_track, ircd's ScrobbleServ, anything that
9 + takes the Scropple HTTP backend's JSON;
10 +- **ListenBrainz**, or another server speaking its API;
11 +- **Last.fm**.
8 12
9 13 The desktop sibling of [scropple-android](https://gg.neiam.co/r/neiam/scropple-android),
10 14 with the same rules for what counts as a play.
@@ -39,8 +43,8 @@ The package installs `/usr/bin/scropple` and the user unit; then, as you:
39 43
40 44 ```sh
41 45 scropple init # config + empty token file
42 −$EDITOR ~/.config/scropple/config.toml
43 −$EDITOR ~/.config/scropple/finaltrack.token
46 +$EDITOR ~/.config/scropple/config.toml # your backend(s)
47 +scropple login finaltrack # and each other backend
44 48 scropple check
45 49 systemctl --user enable --now scropple
46 50 ```
@@ -53,7 +57,7 @@ install -Dm755 target/release/scropple ~/.local/bin/scropple
53 57
54 58 scropple init # the example config, and an empty token file (0600)
55 59 $EDITOR ~/.config/scropple/config.toml # your backend(s)
56 −$EDITOR ~/.config/scropple/finaltrack.token # a token from the Scrobbling page
60 +scropple login finaltrack # paste a token from its Scrobbling page
57 61
58 62 scropple check # config and tokens readable?
59 63
@@ -63,6 +67,42 @@ systemctl --user enable --now scropple
63 67 journalctl --user -u scropple -f
64 68 ```
65 69
70 +## Backends
71 +
72 +Each `[[backend]]` in the config gets every scrobble, with its own queue.
73 +`type` says what it speaks (`scropple` when left out), and `scropple login
74 +NAME` signs it in, saving the token to its `token_file` (0600):
75 +
76 +| `type` | `url` | Signing in |
77 +|---|---|---|
78 +| `scropple` | required: the server | paste a token from its Scrobbling page |
79 +| `listenbrainz` | defaults to `https://api.listenbrainz.org` | paste your user token from [listenbrainz.org/settings](https://listenbrainz.org/settings/); it's checked before it's saved |
80 +| `lastfm` | defaults to Last.fm's API | Last.fm opens in your browser to allow Scropple; the session key is saved. No password is involved. |
81 +
82 +```toml
83 +[[backend]]
84 +name = "listenbrainz"
85 +type = "listenbrainz"
86 +token_file = "listenbrainz.token"
87 +
88 +[[backend]]
89 +name = "lastfm"
90 +type = "lastfm"
91 +token_file = "lastfm.session"
92 +```
93 +
94 +Last.fm calls are signed with an **API key and secret** belonging to an
95 +application registered at
96 +[last.fm/api/account/create](https://www.last.fm/api/account/create). A
97 +build can carry them, from `SCROPPLE_LASTFM_API_KEY` and
98 +`SCROPPLE_LASTFM_API_SECRET` at compile time; otherwise (or to use your
99 +own) set `api_key` and `api_secret_file` (or `api_secret`) on the backend.
100 +`scropple check` says which it's using.
101 +
102 +A backend that isn't signed in yet keeps its scrobbles queued until it is
103 +(restart scropple after `login`). Last.fm may accept a call but ignore some
104 +plays (more than two weeks old, say); those are logged, not retried.
105 +
66 106 ## What counts as a play
67 107
68 108 As on Android (and Last.fm): a track scrobbles once it's been **played** for
@@ -97,7 +137,8 @@ what you name (`allow`).
97 137 | `scropple` / `scropple run` | the daemon |
98 138 | `scropple players` | every player on the bus, what it's playing, whether it would scrobble |
99 139 | `scropple init [--force]` | write the example config to the config path, and an empty private token file |
100 −| `scropple check` | the config and tokens |
140 +| `scropple check` | the config, and whether each backend is signed in |
141 +| `scropple login NAME` | sign a backend in, saving its token |
101 142 | `scropple queue` | scrobbles waiting, per backend |
102 143
103 144 `--config PATH` for another config. `RUST_LOG=scropple_linux=debug` logs
@@ -119,7 +160,7 @@ podman build --target packages --output type=local,dest=./dist -f packaging/Dock
119 160 |---|---|
120 161 | `engine` | what counts as a play: `Session` (one player's timing, ported from scropple-android's `ScrobbleSession`, with its tests), `Filter`, `Engine` |
121 162 | `mpris` | following players on the bus, metadata → tracks |
122 −| `backend` | the Scropple HTTP contract |
163 +| `backend` | `scropple` (the Scropple HTTP contract), `listenbrainz`, `lastfm` (signing, error codes, the desktop sign-in flow) |
123 164 | `queue` | scrobbles waiting, in SQLite |
124 165 | `daemon` | the wiring |
125 166
modified contrib/config.example.toml
+19 −0
@@ -29,3 +29,22 @@ token_file = "finaltrack.token"
29 29 # name = "ircd"
30 30 # url = "https://irc.example.org"
31 31 # token_file = "ircd.token"
32 +
33 +# ListenBrainz: `scropple login listenbrainz` asks for the user token from
34 +# https://listenbrainz.org/settings/ and saves it here. `url` points it at
35 +# another server speaking the ListenBrainz API.
36 +# [[backend]]
37 +# name = "listenbrainz"
38 +# type = "listenbrainz"
39 +# token_file = "listenbrainz.token"
40 +
41 +# Last.fm: `scropple login lastfm` opens Last.fm in your browser to allow
42 +# Scropple, then saves the session key here; no password is involved.
43 +# A build without a Last.fm API key built in needs one of your own, from
44 +# https://www.last.fm/api/account/create:
45 +# [[backend]]
46 +# name = "lastfm"
47 +# type = "lastfm"
48 +# token_file = "lastfm.session"
49 +# api_key = "..."
50 +# api_secret_file = "lastfm.secret"
deleted src/backend.rs
+0 −171
@@ -1,171 +0,0 @@
1 −//! The Scropple HTTP backend contract (final_track, ircd's ScrobbleServ,
2 −//! scropple-android's `HttpBackend`): `POST {url}/api/v1/now-playing` with
3 −//! one play, `POST {url}/api/v1/scrobble` with an array, bearer token.
4 −
5 −use serde::{Deserialize, Serialize};
6 −use std::time::Duration;
7 −
8 −use crate::engine::Track;
9 −
10 −/// One play as the API takes it.
11 −#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12 −#[serde(rename_all = "camelCase")]
13 −pub struct Play {
14 − pub artist: String,
15 − pub track: String,
16 − #[serde(skip_serializing_if = "Option::is_none")]
17 − pub album: Option<String>,
18 − #[serde(skip_serializing_if = "Option::is_none")]
19 − pub album_artist: Option<String>,
20 − #[serde(skip_serializing_if = "Option::is_none")]
21 − pub duration_sec: Option<u64>,
22 − /// When the play started, Unix seconds (absent for now-playing).
23 − #[serde(skip_serializing_if = "Option::is_none")]
24 − pub timestamp: Option<i64>,
25 −}
26 −
27 −impl Play {
28 − pub fn from_track(t: &Track, started: Option<i64>) -> Self {
29 − Self {
30 − artist: t.artist.clone(),
31 − track: t.title.clone(),
32 − album: t.album.clone(),
33 − album_artist: t.album_artist.clone(),
34 − duration_sec: (t.duration_ms > 0).then(|| t.duration_ms.div_ceil(1000)),
35 − timestamp: started.filter(|&s| s > 0),
36 − }
37 − }
38 −}
39 −
40 −#[derive(Debug)]
41 −pub enum SendError {
42 − /// Worth trying again later: the network, a 5xx, 408/429, or a 401/403
43 − /// (a token being fixed shouldn't cost the plays waiting for it).
44 − Retry(String),
45 − /// The server refused the plays themselves (a 4xx such as 422): drop them.
46 − Rejected(String),
47 −}
48 −
49 −impl std::fmt::Display for SendError {
50 − fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 − match self {
52 − SendError::Retry(m) => write!(f, "will retry: {m}"),
53 − SendError::Rejected(m) => write!(f, "rejected: {m}"),
54 − }
55 − }
56 −}
57 −
58 −pub struct HttpBackend {
59 − pub name: String,
60 − base: String,
61 − token: String,
62 − client: reqwest::Client,
63 −}
64 −
65 −impl HttpBackend {
66 − pub fn new(name: &str, base: &str, token: &str) -> Self {
67 − let client = reqwest::Client::builder()
68 − .user_agent(concat!("scropple-linux/", env!("CARGO_PKG_VERSION")))
69 − .timeout(Duration::from_secs(20))
70 − .build()
71 − .expect("an HTTP client");
72 − Self {
73 − name: name.to_string(),
74 − base: base.trim_end_matches('/').to_string(),
75 − token: token.to_string(),
76 − client,
77 − }
78 − }
79 −
80 − pub async fn now_playing(&self, play: &Play) -> Result<(), SendError> {
81 − self.post("/api/v1/now-playing", play).await
82 − }
83 −
84 − pub async fn scrobble(&self, plays: &[Play]) -> Result<(), SendError> {
85 − self.post("/api/v1/scrobble", plays).await
86 − }
87 −
88 − async fn post<B: Serialize + ?Sized>(&self, path: &str, body: &B) -> Result<(), SendError> {
89 − let resp = self
90 − .client
91 − .post(format!("{}{}", self.base, path))
92 − .bearer_auth(&self.token)
93 − .json(body)
94 − .send()
95 − .await
96 − .map_err(|e| SendError::Retry(e.to_string()))?;
97 −
98 − classify(resp.status().as_u16(), || {
99 − format!("HTTP {} from {}{}", resp.status(), self.base, path)
100 − })
101 − }
102 −}
103 −
104 −/// What a status means for the plays sent.
105 −pub fn classify(status: u16, describe: impl FnOnce() -> String) -> Result<(), SendError> {
106 − match status {
107 − 200..=299 => Ok(()),
108 − 401 | 403 | 408 | 429 | 500..=599 => Err(SendError::Retry(describe())),
109 − _ => Err(SendError::Rejected(describe())),
110 − }
111 −}
112 −
113 −#[cfg(test)]
114 −mod tests {
115 − use super::*;
116 −
117 − #[test]
118 − fn plays_serialize_as_the_api_takes_them() {
119 − let t = Track {
120 − artist: "Pink Floyd".into(),
121 − title: "Time".into(),
122 − album: Some("The Dark Side of the Moon".into()),
123 − album_artist: None,
124 − duration_ms: 412_500,
125 − player: "spotify".into(),
126 − };
127 − let json = serde_json::to_value(Play::from_track(&t, Some(1_763_494_445))).unwrap();
128 − assert_eq!(
129 − json,
130 − serde_json::json!({
131 − "artist": "Pink Floyd",
132 − "track": "Time",
133 − "album": "The Dark Side of the Moon",
134 − "durationSec": 413,
135 − "timestamp": 1_763_494_445
136 − })
137 − );
138 −
139 − let now = serde_json::to_value(Play::from_track(
140 − &Track {
141 − duration_ms: 0,
142 − album: None,
143 − ..t
144 − },
145 − None,
146 − ))
147 − .unwrap();
148 − assert_eq!(
149 − now,
150 − serde_json::json!({"artist": "Pink Floyd", "track": "Time"})
151 − );
152 − }
153 −
154 − #[test]
155 − fn statuses() {
156 − assert!(classify(200, String::new).is_ok());
157 − assert!(classify(204, String::new).is_ok());
158 − for s in [401, 403, 408, 429, 500, 503] {
159 − assert!(
160 − matches!(classify(s, String::new), Err(SendError::Retry(_))),
161 − "{s}"
162 − );
163 − }
164 − for s in [400, 404, 422] {
165 − assert!(
166 − matches!(classify(s, String::new), Err(SendError::Rejected(_))),
167 − "{s}"
168 − );
169 − }
170 − }
171 −}
added src/backend/lastfm.rs
+288 −0

Click to load diff…

added src/backend/listenbrainz.rs
+173 −0

Click to load diff…

added src/backend/mod.rs
+253 −0

Click to load diff…

added src/backend/scropple.rs
+52 −0

Click to load diff…

modified src/config.rs
+204 −10

Click to load diff…

modified src/daemon.rs
+13 −13

Click to load diff…

modified src/lib.rs
+4 −2

Click to load diff…

modified src/main.rs
+90 −13

Click to load diff…

Parents: 6c56e6c