Scrobbles: untangle 'Artist • Album • YouTube Music' sent as the artist (Sonos)

2355fcd · gmorell · 2026-11-19 04:48

6 files +40 -0

Files changed

modified lib/final_track/scrobbles.ex
+22 −0
@@ -100,6 +100,8 @@ defmodule FinalTrack.Scrobbles do
100 100 {:ok, track} <- text(params, "track", true),
101 101 {:ok, album} <- text(params, "album", false),
102 102 {:ok, album_artist} <- text(params, "albumArtist", false) do
103 + {artist, album} = untangle_artist(artist, album)
104 +
103 105 {:ok,
104 106 %{
105 107 artist: artist,
@@ -114,6 +116,26 @@ defmodule FinalTrack.Scrobbles do
114 116
115 117 def validate_play(_), do: {:error, "body must be a JSON object"}
116 118
119 + # Some players hand media sessions a subtitle rather than an artist: Sonos
120 + # casting YouTube Music sends "Cage The Elephant • Tell Me I'm Pretty •
121 + # YouTube Music". When the last "•" segment is a known service, drop it;
122 + # what's left is the artist, then the album (kept unless one was sent).
123 + @services ~w(youtubemusic)
124 + defp untangle_artist(artist, album) do
125 + parts = artist |> String.split(~r/\s+[•·]\s+/u) |> Enum.map(&String.trim/1)
126 +
127 + with [_, _ | _] <- parts,
128 + service = List.last(parts),
129 + true <- (service |> String.downcase() |> String.replace(~r/\s+/u, "")) in @services do
130 + case Enum.drop(parts, -1) do
131 + [name] -> {name, album}
132 + [name, from_album | _] -> {name, album || from_album}
133 + end
134 + else
135 + _ -> {artist, album}
136 + end
137 + end
138 +
117 139 defp text(params, key, required?) do
118 140 case Map.get(params, key) do
119 141 nil when required? ->
modified test/final_track/scrobbles_test.exs
+18 −0
@@ -8,6 +8,24 @@ defmodule FinalTrack.ScrobblesTest do
8 8 alias FinalTrack.Scrobbles.{NowPlaying, Scrobble}
9 9
10 10 describe "validate_play/1" do
11 + test "untangles a YouTube Music subtitle sent as the artist" do
12 + artist = "Cage The Elephant • Tell Me I'm Pretty • YouTube Music"
13 +
14 + assert {:ok, %{artist: "Cage The Elephant", album: "Tell Me I'm Pretty"}} =
15 + Scrobbles.validate_play(%{"artist" => artist, "track" => "Cry Baby"})
16 +
17 + # An album the client sent wins; no album segment leaves it alone.
18 + assert {:ok, %{artist: "Cage The Elephant", album: "Sent"}} =
19 + Scrobbles.validate_play(%{"artist" => artist, "track" => "t", "album" => "Sent"})
20 +
21 + assert {:ok, %{artist: "Justice", album: nil}} =
22 + Scrobbles.validate_play(%{"artist" => "Justice • YouTube Music", "track" => "t"})
23 +
24 + # A "•" without a known service is left as sent.
25 + assert {:ok, %{artist: "A • B"}} =
26 + Scrobbles.validate_play(%{"artist" => "A • B", "track" => "t"})
27 + end
28 +
11 29 test "picks out and cleans the fields" do
12 30 assert {:ok, play} =
13 31 Scrobbles.validate_play(%{

Parents: b28bd36