Skip to content

Unofficial YouTube Music / Spotify Premium client for Android, built in Liquid Glass. Audio effects, Spotify Connect, listening history, 8 languages. Rust core on librespot.

Report what was listened to, so the account has a history

Lelonioa0f3c797ba59
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 4c58a9e..97fa72a 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -156,7 +156,13 @@
"Bash(git apply *)",
"Bash(cp app/src/main/java/dev/emanuele/spot/data/SpotifyApi.kt /private/tmp/claude-501/-Users-emanuele-Progetto-Spotify/f8b439da-53e4-49c2-8d23-91a1d07d3cdc/scratchpad/SpotifyApi.bak)",
"Bash(cp app/src/main/java/dev/emanuele/spot/ui/MainViewModel.kt /private/tmp/claude-501/-Users-emanuele-Progetto-Spotify/f8b439da-53e4-49c2-8d23-91a1d07d3cdc/scratchpad/MainViewModel.bak)",
- "Bash(cp app/src/main/java/dev/emanuele/spot/ui/MainActivity.kt /private/tmp/claude-501/-Users-emanuele-Progetto-Spotify/f8b439da-53e4-49c2-8d23-91a1d07d3cdc/scratchpad/MainActivity.bak)"
+ "Bash(cp app/src/main/java/dev/emanuele/spot/ui/MainActivity.kt /private/tmp/claude-501/-Users-emanuele-Progetto-Spotify/f8b439da-53e4-49c2-8d23-91a1d07d3cdc/scratchpad/MainActivity.bak)",
+ "Bash(git checkout *)",
+ "Bash(gh api *)",
+ "Bash(curl -s \"https://api.github.com/search/code?q=EventService+repo:librespot-org/librespot-java\")",
+ "Bash(curl -s \"https://api.github.com/repos/librespot-org/librespot-java/git/trees/master?recursive=1\")",
+ "Bash(rm -rf lsj)",
+ "Bash(git clone *)"
]
}
}
diff --git a/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin b/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin
index 69e8256..88886eb 100644
--- a/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin
+++ b/app/.cxx/Debug/286k5v33/arm64-v8a/configure_fingerprint.bin
@@ -2,27 +2,27 @@ C/C++ Structured Logc
a
_/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/additional_project_files.txtC
A
-?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint  �댍�3  ��߈�3`
+?com.android.build.gradle.internal.cxx.io.EncodedFileFingerPrint  �����3  ��߈�3`
^
-\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build.json  �댍�3� ��߈�3e
+\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build.json  �����3� ��߈�3e
c
-a/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build_mini.json  �댍�3� ��߈�3R
+a/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/android_gradle_build_mini.json  �����3� ��߈�3R
P
-N/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja  �댍�3� ��߈�3V
+N/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja  �����3� ��߈�3V
T
-R/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja.txt  �댍�3[
+R/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build.ninja.txt  �����3[
Y
-W/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build_file_index.txt  �댍�3 @ ��߈�3\
+W/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/build_file_index.txt  �����3 @ ��߈�3\
Z
-X/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json  �댍�3֚ ��߈�3`
+X/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json  �����3֚ ��߈�3`
^
-\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json.bin  �댍�3 �" ��߈�3f
+\/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/compile_commands.json.bin  �����3 �" ��߈�3f
d
-b/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/metadata_generation_command.txt  �댍�3
+b/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/metadata_generation_command.txt  ���3
� ��߈�3Y
W
-U/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/prefab_config.json  �댍�3  ( ��߈�3^
+U/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/prefab_config.json  Χ���3  ( ��߈�3^
\
-Z/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/symbol_folder_index.txt  �댍�3  Y ��߈�3D
+Z/Users/emanuele/Progetto Spotify/app/.cxx/Debug/286k5v33/arm64-v8a/symbol_folder_index.txt  Χ���3  Y ��߈�3D
B
-@/Users/emanuele/Progetto Spotify/app/src/main/cpp/CMakeLists.txt  �댍�3 � �Ȅ��3
\ No newline at end of file
+@/Users/emanuele/Progetto Spotify/app/src/main/cpp/CMakeLists.txt  Χ���3 � �Ȅ��3
\ No newline at end of file
diff --git a/native/src/engine.rs b/native/src/engine.rs
index a2531a0..f737b6a 100644
--- a/native/src/engine.rs
+++ b/native/src/engine.rs
@@ -19,6 +19,7 @@ use librespot_playback::{
mixer::{softmixer::SoftMixer, Mixer, MixerConfig},
player::{Player, PlayerEvent},
};
+use crate::events::{self, EndReason, EventService, Listen};
use once_cell::sync::OnceCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
@@ -258,7 +259,13 @@ pub fn start(
log::info!("connect device stopped");
});
- spawn_event_pump(&rt, player.clone(), listener, device_name.to_string());
+ spawn_event_pump(
+ &rt,
+ player.clone(),
+ listener,
+ device_name.to_string(),
+ session.clone(),
+ );
*guard = Some(Engine {
rt,
@@ -279,7 +286,13 @@ pub fn start(
/// migrates between workers, so its `GlobalRef` could be released on a detached
/// thread, where JNI cannot free it ("Dropping a GlobalRef in a detached
/// thread").
-fn spawn_event_pump(rt: &Runtime, player: Arc<Player>, listener: GlobalRef, device_name: String) {
+fn spawn_event_pump(
+ rt: &Runtime,
+ player: Arc<Player>,
+ listener: GlobalRef,
+ device_name: String,
+ session: Session,
+) {
let mut events = player.get_player_event_channel();
// Keep the player alive for as long as we are reading its events.
let _ = rt;
@@ -299,7 +312,12 @@ fn spawn_event_pump(rt: &Runtime, player: Arc<Player>, listener: GlobalRef, devi
}
log::info!("event pump started for device {device_name}");
+ // What the account's listening history is built from; see events.rs.
+ let mut history = History::new(session);
+
while let Some(event) = events.blocking_recv() {
+ history.observe(&event);
+
let (kind, uri, position_ms) = match event {
PlayerEvent::Playing {
track_id,
@@ -341,6 +359,175 @@ fn spawn_event_pump(rt: &Runtime, player: Arc<Player>, listener: GlobalRef, devi
.expect("failed to spawn the event pump thread");
}
+/// Turns the player's events into the three Spotify wants for a listen.
+///
+/// Kept beside the pump rather than inside `events` because only here is the
+/// order of things known: a track is "finished" when the next one starts, when
+/// the player stops, or when it runs off the end, and only one of those is an
+/// event that says so.
+struct History {
+ events: EventService,
+ session_id: String,
+ /// The context every listen is attributed to, once one has been started.
+ context_uri: String,
+ current: Option<Playing>,
+ /// Durations seen so far, by track URI.
+ ///
+ /// `TrackChanged` is the only event carrying one and it arrives *before*
+ /// the track starts, so there is nothing to attach it to yet. Held here
+ /// until the matching `Playing` shows up. Without this the transition
+ /// reported the played time as the track's length — a three-minute song
+ /// skipped at forty seconds went to Spotify as a forty-second song played
+ /// to the end, and nothing about that was going to be believed.
+ durations: std::collections::HashMap<String, u32>,
+}
+
+struct Playing {
+ uri: String,
+ hex: String,
+ playback_id: String,
+ start_ms: u32,
+ position_ms: u32,
+ duration_ms: u32,
+ started_at: u128,
+ reason_start: &'static str,
+}
+
+impl History {
+ fn new(session: Session) -> Self {
+ let session_id = session.session_id();
+ History {
+ events: EventService::new(session),
+ session_id: if session_id.is_empty() {
+ events::random_id()
+ } else {
+ session_id
+ },
+ context_uri: String::new(),
+ current: None,
+ durations: std::collections::HashMap::new(),
+ }
+ }
+
+ fn observe(&mut self, event: &PlayerEvent) {
+ match event {
+ PlayerEvent::TrackChanged { audio_item } => {
+ // Kept for whenever this track starts; see `durations`. The map
+ // is bounded by the queue, and a queue is not unbounded.
+ if audio_item.duration_ms > 0 {
+ self.durations
+ .insert(audio_item.uri.clone(), audio_item.duration_ms);
+ }
+ if let Some(playing) = self.current.as_mut() {
+ if playing.uri == audio_item.uri {
+ playing.duration_ms = audio_item.duration_ms;
+ }
+ }
+ }
+
+ PlayerEvent::Playing {
+ track_id,
+ position_ms,
+ ..
+ } => self.start(uri_string(track_id), *position_ms),
+
+ PlayerEvent::Paused { position_ms, .. }
+ | PlayerEvent::PositionChanged { position_ms, .. }
+ | PlayerEvent::Seeked { position_ms, .. } => {
+ if let Some(playing) = self.current.as_mut() {
+ playing.position_ms = *position_ms;
+ }
+ }
+
+ // Ran to the end: the one that counts as a full listen.
+ PlayerEvent::EndOfTrack { .. } => self.finish(EndReason::TrackDone),
+ PlayerEvent::Stopped { .. } => self.finish(EndReason::EndPlay),
+ _ => {}
+ }
+ }
+
+ fn start(&mut self, uri: String, position_ms: u32) {
+ if let Some(playing) = self.current.as_ref() {
+ // Un-pausing and seeking both arrive as `Playing` on a track that is
+ // already open, and neither is a new listen.
+ if playing.uri == uri {
+ if let Some(playing) = self.current.as_mut() {
+ playing.position_ms = position_ms;
+ }
+ return;
+ }
+ // A different track without an end event: something skipped.
+ self.finish(EndReason::Forward);
+ }
+
+ let hex = hex_id(&uri);
+ if hex.is_empty() {
+ return;
+ }
+
+ // A context is opened once and every track played inside it is
+ // attributed to it. Playing a track on its own makes the track its own
+ // context, which is what the official client does too.
+ if self.context_uri.is_empty() {
+ self.context_uri = uri.clone();
+ self.events
+ .new_session(&self.session_id, &self.context_uri, 1);
+ }
+
+ let playback_id = events::random_id();
+ self.events.new_playback(&playback_id, &self.session_id);
+
+ let duration_ms = self.durations.get(&uri).copied().unwrap_or(0);
+ self.current = Some(Playing {
+ uri,
+ hex,
+ playback_id,
+ start_ms: position_ms,
+ position_ms,
+ duration_ms,
+ started_at: events::now_ms(),
+ reason_start: "playbtn",
+ });
+ }
+
+ fn finish(&mut self, reason: EndReason) {
+ let Some(playing) = self.current.take() else {
+ return;
+ };
+ // Running off the end means the whole track was heard, whatever the
+ // last position report happened to say.
+ let end_ms = match reason {
+ EndReason::TrackDone if playing.duration_ms > 0 => playing.duration_ms,
+ _ => playing.position_ms.max(playing.start_ms),
+ };
+ let duration_ms = if playing.duration_ms > 0 {
+ playing.duration_ms
+ } else {
+ end_ms
+ };
+
+ self.events.track_transition(&Listen {
+ track_hex: &playing.hex,
+ playback_id: &playing.playback_id,
+ context_uri: &self.context_uri,
+ start_ms: playing.start_ms,
+ end_ms,
+ duration_ms,
+ reason_start: playing.reason_start,
+ reason_end: reason,
+ started_at: playing.started_at,
+ });
+ }
+}
+
+/// A track's gid in hex, which is what the events carry — not the base62 id.
+fn hex_id(uri: &str) -> String {
+ match SpotifyUri::from_uri(uri) {
+ Ok(SpotifyUri::Track { id }) => id.to_base16().unwrap_or_default(),
+ _ => String::new(),
+ }
+}
+
fn uri_string(uri: &SpotifyUri) -> String {
uri.to_uri().unwrap_or_default()
}
diff --git a/native/src/events.rs b/native/src/events.rs
new file mode 100644
index 0000000..e58779f
--- /dev/null
+++ b/native/src/events.rs
@@ -0,0 +1,302 @@
+//! Telling Spotify what was listened to.
+//!
+//! Playback through librespot never appeared in the account's history, and the
+//! reason is not a setting: Spotify builds "recently played" from *events* the
+//! client posts, and librespot posts none. It publishes its Connect state, so
+//! the servers know the device exists and what it is doing, but nothing in that
+//! path counts as a listen — verified on the device by starting a track through
+//! the Web API and watching the history stay unchanged while the audio played.
+//!
+//! The wire format is not documented by Spotify. It is taken from
+//! librespot-java's `EventService` (Apache-2.0, by devgianlu), reimplemented
+//! here rather than copied: events are Mercury POSTs to
+//! `hm://event-service/v1/events`, whose body is a list of fields separated by
+//! `0x09` and beginning with a numeric event id and a second constant nobody
+//! has a name for.
+//!
+//! Three events make up one listen:
+//!
+//! * `557` — a new *session*, meaning a context was started.
+//! * `558` — a new *playback*, meaning a track began within it.
+//! * `12` — the transition off that track, carrying how far it got. This is the
+//! one Spotify counts.
+//!
+//! The Rust Mercury client has neither POST nor header fields, so both were
+//! added to the vendored copy of librespot-core; see native/vendor/README.md.
+//! An event that fails is a missing history entry, never a failed playback, so
+//! nothing here is allowed to break anything.
+
+use librespot_core::session::Session;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+/// Separates fields in an event body.
+const SEP: u8 = 0x09;
+
+const EVENT_URI: &str = "hm://event-service/v1/events";
+
+/// One event, built field by field.
+struct Event {
+ body: Vec<u8>,
+}
+
+impl Event {
+ /// `id` and `unknown` identify the kind; see the module note.
+ fn new(id: &str, unknown: &str) -> Self {
+ let mut event = Event {
+ body: id.as_bytes().to_vec(),
+ };
+ event.field(unknown);
+ event
+ }
+
+ fn field(&mut self, value: &str) -> &mut Self {
+ self.body.push(SEP);
+ self.body.extend_from_slice(value.as_bytes());
+ self
+ }
+
+ fn number(&mut self, value: impl ToString) -> &mut Self {
+ self.field(&value.to_string())
+ }
+}
+
+/// What ended a track, in Spotify's own vocabulary.
+#[derive(Clone, Copy)]
+pub enum EndReason {
+ /// Played to the end.
+ TrackDone,
+ /// Skipped forwards.
+ Forward,
+ /// Skipped backwards.
+ Backward,
+ /// Playback stopped without another track following.
+ EndPlay,
+}
+
+impl EndReason {
+ fn as_str(self) -> &'static str {
+ match self {
+ EndReason::TrackDone => "trackdone",
+ EndReason::Forward => "fwdbtn",
+ EndReason::Backward => "backbtn",
+ EndReason::EndPlay => "endplay",
+ }
+ }
+}
+
+/// Everything one finished track needs to be reported.
+pub struct Listen<'a> {
+ /// The track's id in hex — its gid, not the base62 in the URI.
+ pub track_hex: &'a str,
+ pub playback_id: &'a str,
+ pub context_uri: &'a str,
+ /// Where playback started within the track, in milliseconds.
+ pub start_ms: u32,
+ /// Where it stopped. This is what decides whether it counts as a listen.
+ pub end_ms: u32,
+ pub duration_ms: u32,
+ pub reason_start: &'a str,
+ pub reason_end: EndReason,
+ /// Wall clock at the moment the track started, in milliseconds.
+ pub started_at: u128,
+}
+
+/// Posts the events that make up the account's listening history.
+pub struct EventService {
+ session: Session,
+ transitions: AtomicU64,
+}
+
+impl EventService {
+ pub fn new(session: Session) -> Self {
+ EventService {
+ session,
+ transitions: AtomicU64::new(0),
+ }
+ }
+
+ /// A context was started — a playlist, an album, a single track.
+ pub fn new_session(&self, session_id: &str, context_uri: &str, context_size: usize) {
+ let mut event = Event::new("557", "3");
+ event
+ .field(session_id)
+ .field(context_uri)
+ .field(context_uri)
+ .number(now_ms())
+ .field("")
+ .number(context_size)
+ // The context's own URL, which the client uses to page through it.
+ .field(&format!("context://{context_uri}"));
+ self.post(event);
+ }
+
+ /// A track began within that context.
+ pub fn new_playback(&self, playback_id: &str, session_id: &str) {
+ let mut event = Event::new("558", "1");
+ event.field(playback_id).field(session_id).number(now_ms());
+ self.post(event);
+ }
+
+ /// A track ended. The one event Spotify turns into history.
+ pub fn track_transition(&self, listen: &Listen) {
+ let device_id = self.session.device_id().to_string();
+ let count = self.transitions.fetch_add(1, Ordering::Relaxed);
+
+ // Several of these are timings the official client measures and we do
+ // not: how long the audio key took, how much was decrypted, how far the
+ // decoder read ahead. Zero is what librespot-java sends when it has no
+ // figure either, and Spotify has never rejected an event over them —
+ // what it reads is the track, the context and how much was played.
+ let mut event = Event::new("12", "38");
+ event
+ .number(count)
+ .field(&device_id)
+ .field(listen.playback_id)
+ .field("00000000000000000000000000000000")
+ // How playback began, and how it ended.
+ .field("unknown")
+ .field(listen.reason_start)
+ .field("unknown")
+ .field(listen.reason_end.as_str())
+ // Bytes decoded, bytes total.
+ .number(0)
+ .number(0)
+ // Where it stopped, twice.
+ .number(listen.end_ms)
+ .number(listen.end_ms)
+ .number(listen.duration_ms)
+ // Decrypt time, crossfade overlap, and two constants.
+ .number(0)
+ .number(0)
+ .field("0")
+ .field("0")
+ // Whether it started from the beginning, and where from.
+ .field(if listen.start_ms == 0 { "0" } else { "1" })
+ .number(listen.start_ms)
+ .field("0")
+ .field("-1")
+ .field("context")
+ // Audio key timing.
+ .number(0)
+ .field("0")
+ .field("0")
+ .field("0")
+ .field("0")
+ .field("0")
+ .number(listen.end_ms)
+ .number(listen.end_ms)
+ .field("0")
+ .number(BITRATE)
+ .field(listen.context_uri)
+ .field(ENCODING)
+ .field(listen.track_hex)
+ .field("")
+ .field("0")
+ .number(listen.started_at)
+ .field("0")
+ .field("context")
+ .field(REFERRER)
+ .field(FEATURE_VERSION)
+ .field("com.spotify")
+ .field("none")
+ .field("none")
+ // Which device sent the last command. Ours: playback is started
+ // here, not by a phone across the room.
+ .field(&device_id)
+ .field("na")
+ .field("none");
+ self.post(event);
+ }
+
+ /// Posts the event and logs what Spotify made of it.
+ ///
+ /// The reply matters more than it looks: a well-formed packet the server
+ /// silently drops and a rejected one are indistinguishable without it, and
+ /// this whole format is reverse-engineered. Upstream's Mercury client has
+ /// neither POST nor header fields, so both were added to the vendored copy.
+ fn post(&self, event: Event) {
+ let body = event.body;
+ let fields = vec![
+ ("Accept-Language".to_string(), b"en".to_vec()),
+ (
+ "X-ClientTimeStamp".to_string(),
+ now_ms().to_string().into_bytes(),
+ ),
+ ];
+
+ let request = match self.session.mercury().post(EVENT_URI, body.clone(), fields) {
+ Ok(request) => request,
+ Err(e) => {
+ log::warn!("event not sent: {e}");
+ return;
+ }
+ };
+
+ // Waited for on the engine's runtime rather than on the caller's
+ // thread: this is called from the player's event pump, and blocking
+ // there would hold up every other event behind a network round trip.
+ // The event's kind, never its body. The body carries the track, the
+ // context and the time — the user's listening, in a log any app holding
+ // READ_LOGS can read.
+ let kind = kind_of(&body);
+ let Ok(handle) = crate::engine::runtime_handle() else {
+ return;
+ };
+ handle.spawn(async move {
+ match request.await {
+ Ok(response) if response.status_code == 200 => {
+ log::debug!("event {kind} accepted")
+ }
+ Ok(response) => log::warn!("event {kind} refused: {}", response.status_code),
+ Err(e) => log::warn!("event {kind} failed: {e}"),
+ }
+ });
+ }
+}
+
+/// The event's numeric kind, which is all that may be logged; see [EventService::post].
+fn kind_of(body: &[u8]) -> String {
+ body.split(|byte| *byte == SEP)
+ .next()
+ .map(|id| String::from_utf8_lossy(id).to_string())
+ .unwrap_or_default()
+}
+
+pub fn now_ms() -> u128 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0)
+}
+
+/// A 32-character hex id, which is the shape Spotify uses for both of these.
+pub fn random_id() -> String {
+ let mut id = String::with_capacity(32);
+ for _ in 0..4 {
+ // Exactly eight characters per part: Spotify's ids are 32 long, and a
+ // u64 printed as hex ran to sixteen when the value was large enough,
+ // which made every id a different length.
+ let part = (SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.subsec_nanos() as u64)
+ .unwrap_or(0)
+ ^ rand_seed()) as u32;
+ id.push_str(&format!("{part:08x}"));
+ }
+ id
+}
+
+fn rand_seed() -> u64 {
+ use std::collections::hash_map::RandomState;
+ use std::hash::{BuildHasher, Hasher};
+ RandomState::new().build_hasher().finish()
+}
+
+/// 160 kbps, the ordinary quality this client asks for.
+const BITRATE: u32 = 160_000;
+const ENCODING: &str = "vorbis";
+
+/// Where the play came from, in the client's own vocabulary.
+const REFERRER: &str = "unknown";
+const FEATURE_VERSION: &str = "harmony:4.21.0";
diff --git a/native/src/lib.rs b/native/src/lib.rs
index e2aa91d..30ded4b 100644
--- a/native/src/lib.rs
+++ b/native/src/lib.rs
@@ -7,6 +7,7 @@
mod catalog;
mod engine;
+mod events;
mod ffi;
mod sink;
diff --git a/native/vendor/README.md b/native/vendor/README.md
index 837cdb0..26ed1ed 100644
--- a/native/vendor/README.md
+++ b/native/vendor/README.md
@@ -7,9 +7,26 @@ Copy of [`librespot-core` 0.8.0](https://github.com/librespot-org/librespot)
`native/Cargo.toml` so that `librespot-playback` and `librespot-metadata`
resolve to this copy as well.
-### The patch
+### The patches
-One line, in `src/config.rs`:
+#### 1. `src/mercury` — POST with header fields
+
+Spotify builds the account's listening history from events posted to
+`hm://event-service/v1/events`, and that request is a POST carrying
+`Accept-Language` and `X-ClientTimeStamp` as Mercury header fields. Upstream's
+Mercury client has neither: no POST method, and `MercuryRequest` has nowhere to
+put a header field. Both were added — a `MercuryMethod::Post`, a `user_fields`
+list on the request, and a `post()` on the manager.
+
+The alternative was building the packet by hand and calling `send_packet`
+directly, which works but throws the reply away: the sequence number would not
+be in Mercury's pending table, so there is no way to see whether Spotify
+accepted the event. On a format this app reverse-engineered, that answer is
+worth the patch.
+
+#### 2. `src/config.rs` — the advertised OS
+
+One line:
```rust
-pub const OS: &str = std::env::consts::OS;
diff --git a/native/vendor/librespot-core/src/mercury/mod.rs b/native/vendor/librespot-core/src/mercury/mod.rs
index b32aeb1..200de24 100644
--- a/native/vendor/librespot-core/src/mercury/mod.rs
+++ b/native/vendor/librespot-core/src/mercury/mod.rs
@@ -82,6 +82,7 @@ impl MercuryManager {
uri: uri.into(),
content_type: None,
payload: Vec::new(),
+ user_fields: Vec::new(),
})
}
@@ -95,6 +96,23 @@ impl MercuryManager {
uri: uri.into(),
content_type: None,
payload: vec![data],
+ user_fields: Vec::new(),
+ })
+ }
+
+ /// LOCAL CHANGE: a POST with header fields, for the event service.
+ pub fn post<T: Into<String>>(
+ &self,
+ uri: T,
+ data: Vec<u8>,
+ user_fields: Vec<(String, Vec<u8>)>,
+ ) -> Result<MercuryFuture<MercuryResponse>, Error> {
+ self.request(MercuryRequest {
+ method: MercuryMethod::Post,
+ uri: uri.into(),
+ content_type: None,
+ payload: vec![data],
+ user_fields,
})
}
@@ -113,6 +131,7 @@ impl MercuryManager {
uri: uri.clone(),
content_type: None,
payload: Vec::new(),
+ user_fields: Vec::new(),
});
let manager = self.clone();
diff --git a/native/vendor/librespot-core/src/mercury/types.rs b/native/vendor/librespot-core/src/mercury/types.rs
index 3cc8d8b..c0208eb 100644
--- a/native/vendor/librespot-core/src/mercury/types.rs
+++ b/native/vendor/librespot-core/src/mercury/types.rs
@@ -12,6 +12,10 @@ pub enum MercuryMethod {
Sub,
Unsub,
Send,
+ // LOCAL CHANGE: Spotify's event service — the one the listening history is
+ // built from — takes a POST carrying header fields, and neither the method
+ // nor the fields could be expressed with the upstream request type.
+ Post,
}
#[derive(Debug)]
@@ -20,6 +24,8 @@ pub struct MercuryRequest {
pub uri: String,
pub content_type: Option<String>,
pub payload: Vec<Vec<u8>>,
+ /// LOCAL CHANGE: header fields, as the event service requires.
+ pub user_fields: Vec<(String, Vec<u8>)>,
}
#[derive(Debug, Clone)]
@@ -56,6 +62,7 @@ impl std::fmt::Display for MercuryMethod {
MercuryMethod::Sub => "SUB",
MercuryMethod::Unsub => "UNSUB",
MercuryMethod::Send => "SEND",
+ MercuryMethod::Post => "POST",
};
write!(f, "{s}")
}
@@ -65,7 +72,7 @@ impl MercuryMethod {
pub fn command(&self) -> PacketType {
use PacketType::*;
match *self {
- MercuryMethod::Get | MercuryMethod::Send => MercuryReq,
+ MercuryMethod::Get | MercuryMethod::Send | MercuryMethod::Post => MercuryReq,
MercuryMethod::Sub => MercurySub,
MercuryMethod::Unsub => MercuryUnsub,
}
@@ -88,6 +95,13 @@ impl MercuryRequest {
header.set_content_type(content_type.clone());
}
+ for (key, value) in &self.user_fields {
+ let mut field = protocol::mercury::UserField::new();
+ field.set_key(key.clone());
+ field.set_value(value.clone());
+ header.user_fields.push(field);
+ }
+
packet.write_u16::<BigEndian>(header.compute_size() as u16)?;
header.write_to_writer(&mut packet)?;