feat(discover): suggestions learned from my own listening
A new model (internal/affinity) splits my listening into sittings (plays less than 30 minutes apart) and links the artists that are often played in the same sitting. It is built from my listening events and from the plays of artists I have no music of that an import kept, on my server, with no provider, and is built again when plays are added (migration 0032 keeps it as a cache). GET /me/suggestions gives two lists, each artist with the artists it goes with: the ones I have and did not play for two months, and the ones I played at least three times and have no music of. It needs discover_from_listening. POST /me/suggestions/wishlist puts an artist I played on my wishlist by name. Discover has a "From your listening" tab for both lists.
This commit is contained in:
parent
7b18478fe4
commit
7c961028bb
8 changed files with 2588 additions and 5 deletions
38
web/src/api/listeningSuggestions.ts
Normal file
38
web/src/api/listeningSuggestions.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { api } from '@/api/client'
|
||||
import type { components } from '@/api/schema'
|
||||
|
||||
export type ListeningSuggestions = components['schemas']['ListeningSuggestions']
|
||||
export type ListeningSuggestion = components['schemas']['ListeningSuggestion']
|
||||
|
||||
const KEY = ['me', 'suggestions']
|
||||
|
||||
/**
|
||||
* The artists suggested by how you listen: the ones you have and have not played lately, and the ones you play and
|
||||
* have no music of. Everything is worked out on the server from your own listening. It is asked for only when
|
||||
* `enabled` (when Discover may start from your listening), and the server builds the model on the first call.
|
||||
*/
|
||||
export function useListeningSuggestions({ enabled }: { enabled: boolean }) {
|
||||
return useQuery({
|
||||
queryKey: KEY,
|
||||
queryFn: () => api.get<ListeningSuggestions>('/me/suggestions', { limit: 30 }),
|
||||
enabled,
|
||||
retry: false,
|
||||
})
|
||||
}
|
||||
|
||||
/** Puts an artist you have played on your wishlist by its name, and reads the lists again. */
|
||||
export function useWishPlayedArtist() {
|
||||
const client = useQueryClient()
|
||||
return useMutation({
|
||||
mutationFn: (name: string) => api.post<{ artist_id: number }>('/me/suggestions/wishlist', { name }),
|
||||
onSuccess: () =>
|
||||
Promise.all([client.invalidateQueries({ queryKey: KEY }), client.invalidateQueries({ queryKey: ['/wishlist'] }), client.invalidateQueries({ queryKey: ['/discover/dismissed'] })]),
|
||||
})
|
||||
}
|
||||
|
||||
/** Reads the suggestions again, after the artist was wished or dismissed in another way. */
|
||||
export function useRefreshListeningSuggestions() {
|
||||
const client = useQueryClient()
|
||||
return () => client.invalidateQueries({ queryKey: KEY })
|
||||
}
|
||||
163
web/src/api/schema.d.ts
vendored
163
web/src/api/schema.d.ts
vendored
|
|
@ -1480,6 +1480,59 @@ export interface paths {
|
|||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/suggestions": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* Artists suggested by how you listen
|
||||
* @description Suggestions learned from your own listening, with no provider and nothing sent anywhere. Sonda splits your
|
||||
* history into sittings (plays less than 30 minutes apart) and links the artists that are often played in the
|
||||
* same sitting; the model is built from your listening events and from the plays of artists you have no music
|
||||
* of that an import kept (see `POST /me/import/spotify`), and is built again when plays are added. It needs
|
||||
* `discover_from_listening` in `PATCH /me/settings` (`listening_not_allowed` without it).
|
||||
*
|
||||
* `library` are artists you have, linked to what you play most, that you did not play in the last 60 days,
|
||||
* best first. `missing` are artists you have played at least three times and have no music of, the ones you play
|
||||
* most that also go with what you play now first. Each says which of the artists you play it goes with
|
||||
* (`because`) and has a `score` from 0 to 1 within its list. `artist_id` is null for an artist that does not
|
||||
* exist on this server yet. Artists you dismissed are left out.
|
||||
*/
|
||||
get: operations["getMySuggestions"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/suggestions/wishlist": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* Put a suggested artist you do not have on your wishlist
|
||||
* @description Puts an artist you have played on your wishlist by its name, for the artists of `missing` that have no
|
||||
* `artist_id`: the artist is made on this server without any music, like the ones a provider names, and has
|
||||
* no MusicBrainz id. The name must be one the model knows from your listening (`artist_not_played`). Doing it
|
||||
* twice keeps the first date. It needs `discover_from_listening` like the suggestions.
|
||||
*/
|
||||
post: operations["wishArtistFromSuggestions"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/settings": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
@ -3257,6 +3310,36 @@ export interface components {
|
|||
/** @description Whether the event counts as a listen under the current rule. */
|
||||
counted: boolean;
|
||||
};
|
||||
ListeningSuggestion: {
|
||||
name: string;
|
||||
/** @description The artist on this server, null when there is none yet. */
|
||||
artist_id: number | null;
|
||||
/** @description From 0 to 1 within its list. */
|
||||
score: number;
|
||||
/** @description How many times you played it. */
|
||||
plays: number;
|
||||
/** Format: date-time */
|
||||
last_played_at: string;
|
||||
wishlisted: boolean;
|
||||
/** @description The artists you play that it goes with, the strongest first, at most three. */
|
||||
because: {
|
||||
name: string;
|
||||
score: number;
|
||||
}[];
|
||||
};
|
||||
ListeningSuggestions: {
|
||||
library: components["schemas"]["ListeningSuggestion"][];
|
||||
missing: components["schemas"]["ListeningSuggestion"][];
|
||||
/** @description When the model was built and from how much. */
|
||||
built: {
|
||||
/** Format: date-time */
|
||||
at: string;
|
||||
plays: number;
|
||||
sessions: number;
|
||||
artists: number;
|
||||
links: number;
|
||||
};
|
||||
};
|
||||
Taste: {
|
||||
artists: components["schemas"]["TasteArtist"][];
|
||||
tags: components["schemas"]["TasteTag"][];
|
||||
|
|
@ -6532,6 +6615,86 @@ export interface operations {
|
|||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
getMySuggestions: {
|
||||
parameters: {
|
||||
query?: {
|
||||
/** @description How many artists in each list. 20 when absent or 0; values above 50 are lowered to 50. */
|
||||
limit?: number;
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description The suggestions. Both lists are empty until you have listened to something. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ListeningSuggestions"];
|
||||
};
|
||||
};
|
||||
/** @description A negative limit (`invalid_input`), or Discover is not allowed to start from your listening (`listening_not_allowed`). */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
};
|
||||
};
|
||||
wishArtistFromSuggestions: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
name: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description The artist is on your wishlist. */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
artist_id: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @description The body is not valid (`invalid_input`), or Discover is not allowed to start from your listening (`listening_not_allowed`). */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
401: components["responses"]["Unauthorized"];
|
||||
/** @description You have not played an artist with this name (`artist_not_played`). */
|
||||
404: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
getMySettings: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
|
|
|
|||
|
|
@ -585,6 +585,7 @@
|
|||
"tabs": {
|
||||
"label": "Discover sections",
|
||||
"suggestions": "Suggestions",
|
||||
"mine": "From your listening",
|
||||
"wishlist": "Wishlist",
|
||||
"dismissed": "Not interested"
|
||||
},
|
||||
|
|
@ -609,6 +610,22 @@
|
|||
"partial": "Last.fm could not be reached for some artists, so this list may be shorter.",
|
||||
"busy": "Discover is busy with another request. Try again in a moment.",
|
||||
"retryIn": "Try again in {{seconds}} s",
|
||||
"mine": {
|
||||
"needs": "These suggestions are learned from what you play. Turn on starting Discover from your listening to see them.",
|
||||
"intro": "Sonda looks at which artists you play in the same sitting, and suggests more of what goes together. It is worked out on your server from your own listening, and nothing is sent anywhere.",
|
||||
"built": "Learned from {{plays}} plays in {{sessions}} sittings, on {{when}}.",
|
||||
"nothing": "You have not played anything yet. Play some music, or import your history from Spotify, and the suggestions appear here.",
|
||||
"libraryTitle": "In your library, not played lately",
|
||||
"libraryHint": "Artists you have that go with what you play, and that you have not played for two months.",
|
||||
"libraryNone": "Nothing to bring back right now.",
|
||||
"missingTitle": "You play them, but you do not have them",
|
||||
"missingHint": "Artists you have played at least three times and have no music of here, the ones you play most that also go with what you play now first.",
|
||||
"missingNone": "No artist you play is missing from your library.",
|
||||
"lastPlayed": "Last played {{when}}",
|
||||
"plays_one": "{{count}} play",
|
||||
"plays_other": "{{count}} plays",
|
||||
"because": "Goes with {{names}}"
|
||||
},
|
||||
"marked": {
|
||||
"hideOwned": "Hide the ones I already have",
|
||||
"remove": "Remove",
|
||||
|
|
|
|||
|
|
@ -585,6 +585,7 @@
|
|||
"tabs": {
|
||||
"label": "Sezioni di Discover",
|
||||
"suggestions": "Suggerimenti",
|
||||
"mine": "Dai tuoi ascolti",
|
||||
"wishlist": "Wishlist",
|
||||
"dismissed": "Non mi interessa"
|
||||
},
|
||||
|
|
@ -609,6 +610,22 @@
|
|||
"partial": "Last.fm non era raggiungibile per alcuni artisti, quindi la lista può essere più corta.",
|
||||
"busy": "Discover è occupato con un'altra richiesta. Riprova tra poco.",
|
||||
"retryIn": "Riprova tra {{seconds}} s",
|
||||
"mine": {
|
||||
"needs": "Questi suggerimenti nascono da quello che ascolti. Attiva l'avvio di Discover dai tuoi ascolti per vederli.",
|
||||
"intro": "Sonda guarda quali artisti ascolti nella stessa sessione e propone altro di ciò che sta bene insieme. Si calcola sul tuo server dai tuoi ascolti e non viene inviato niente a nessuno.",
|
||||
"built": "Imparato da {{plays}} ascolti in {{sessions}} sessioni, il {{when}}.",
|
||||
"nothing": "Non hai ancora ascoltato niente. Ascolta un po' di musica, o importa la tua cronologia da Spotify, e qui compaiono i suggerimenti.",
|
||||
"libraryTitle": "Nella tua libreria, non ascoltati di recente",
|
||||
"libraryHint": "Artisti che hai e che stanno bene con quello che ascolti, ma che non ascolti da due mesi.",
|
||||
"libraryNone": "Per ora non c'è niente da riportare a galla.",
|
||||
"missingTitle": "Li ascolti, ma non li hai",
|
||||
"missingHint": "Artisti che hai ascoltato almeno tre volte e di cui qui non hai musica: prima quelli che ascolti di più e che stanno bene con quello che ascolti ora.",
|
||||
"missingNone": "Nessun artista che ascolti manca dalla tua libreria.",
|
||||
"lastPlayed": "Ultimo ascolto {{when}}",
|
||||
"plays_one": "{{count}} ascolto",
|
||||
"plays_other": "{{count}} ascolti",
|
||||
"because": "Sta bene con {{names}}"
|
||||
},
|
||||
"marked": {
|
||||
"hideOwned": "Nascondi quelli che ho già",
|
||||
"remove": "Togli",
|
||||
|
|
|
|||
|
|
@ -84,8 +84,10 @@ test('the arrow keys move between the tabs', async () => {
|
|||
renderPage()
|
||||
tab('Suggestions').focus()
|
||||
await userEvent.keyboard('{ArrowRight}')
|
||||
expect(tab('From your listening')).toHaveAttribute('aria-selected', 'true')
|
||||
expect(tab('From your listening')).toHaveFocus()
|
||||
await userEvent.keyboard('{ArrowRight}')
|
||||
expect(tab('Wishlist')).toHaveAttribute('aria-selected', 'true')
|
||||
expect(tab('Wishlist')).toHaveFocus()
|
||||
await userEvent.keyboard('{ArrowLeft}{ArrowLeft}')
|
||||
await userEvent.keyboard('{ArrowLeft}{ArrowLeft}{ArrowLeft}')
|
||||
expect(tab('Not interested')).toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
|
|
|||
|
|
@ -3,11 +3,13 @@ import { useTranslation } from 'react-i18next'
|
|||
import { useSearchParams } from 'react-router-dom'
|
||||
import { cn } from '@/lib/utils'
|
||||
import MarkedList from './discover/MarkedList'
|
||||
import ListeningTab from './discover/ListeningTab'
|
||||
import SuggestionsTab from './discover/SuggestionsTab'
|
||||
import PageTitle from '@/components/PageTitle'
|
||||
|
||||
const TABS = [
|
||||
{ id: 'suggestions', key: 'discover.tabs.suggestions' },
|
||||
{ id: 'mine', key: 'discover.tabs.mine' },
|
||||
{ id: 'wishlist', key: 'discover.tabs.wishlist' },
|
||||
{ id: 'dismissed', key: 'discover.tabs.dismissed' },
|
||||
] as const
|
||||
|
|
@ -67,7 +69,7 @@ export default function DiscoverPage() {
|
|||
</div>
|
||||
|
||||
<div role="tabpanel" id="discover-panel" aria-labelledby={`tab-${current}`}>
|
||||
{current === 'suggestions' ? <SuggestionsTab /> : <MarkedList key={current} kind={current} />}
|
||||
{current === 'suggestions' ? <SuggestionsTab /> : current === 'mine' ? <ListeningTab /> : <MarkedList key={current} kind={current} />}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
142
web/src/pages/discover/ListeningTab.test.tsx
Normal file
142
web/src/pages/discover/ListeningTab.test.tsx
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { beforeEach, expect, test, vi } from 'vitest'
|
||||
import { sessionStore } from '@/auth/session'
|
||||
import { initI18n } from '@/i18n'
|
||||
import { apiError, mockFetch, type MockRoutes } from '@/test/mockFetch'
|
||||
import ListeningTab from './ListeningTab'
|
||||
|
||||
const none = () => new Response(null, { status: 204 })
|
||||
|
||||
const item = (name: string, id: number | null, over: object = {}) => ({
|
||||
name,
|
||||
artist_id: id,
|
||||
score: 0.9,
|
||||
plays: 3,
|
||||
last_played_at: '2025-01-10T10:00:00Z',
|
||||
wishlisted: false,
|
||||
because: [{ name: 'Radiohead', score: 0.7 }, { name: 'Blur', score: 0.2 }],
|
||||
...over,
|
||||
})
|
||||
|
||||
const built = { at: '2026-11-15T10:00:00Z', plays: 1200, sessions: 340, artists: 80, links: 500 }
|
||||
|
||||
const suggestions = (over: object = {}) => ({ library: [item('Pixies', 2)], missing: [item('Giorgio Canali', null, { plays: 40, score: 0.6 })], built, ...over })
|
||||
|
||||
function setup(routes: MockRoutes, allowed = true) {
|
||||
const mocked = mockFetch({
|
||||
'GET /api/v1/me/settings': () => ({ discover_from_listening: allowed }),
|
||||
'GET /api/v1/me/suggestions': () => suggestions(),
|
||||
...routes,
|
||||
})
|
||||
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MemoryRouter>
|
||||
<ListeningTab />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
return mocked
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
|
||||
await initI18n()
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, email: 'tom@example.org', is_admin: false } })
|
||||
})
|
||||
|
||||
test('without permission it explains and offers the switch, and asks the server for nothing', async () => {
|
||||
const { calls } = setup({}, false)
|
||||
expect(await screen.findByText(/Turn on starting Discover from your listening/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch')).toBeInTheDocument()
|
||||
expect(calls.some((c) => c.key === 'GET /api/v1/me/suggestions')).toBe(false)
|
||||
})
|
||||
|
||||
test('the two lists say why each artist is there and when it was last played', async () => {
|
||||
setup({})
|
||||
const library = await screen.findByRole('region', { name: 'In your library, not played lately' })
|
||||
expect(within(library).getByRole('link', { name: 'Pixies' })).toHaveAttribute('href', '/artists/2')
|
||||
expect(within(library).getByText('90% match')).toBeInTheDocument()
|
||||
expect(within(library).getByText('Last played Jan 10, 2025')).toBeInTheDocument()
|
||||
expect(within(library).getByText('3 plays')).toBeInTheDocument()
|
||||
expect(within(library).getByText('Goes with Radiohead, Blur')).toBeInTheDocument()
|
||||
expect(within(library).queryByRole('button', { name: 'Wishlist' })).not.toBeInTheDocument()
|
||||
|
||||
const missing = screen.getByRole('region', { name: 'You play them, but you do not have them' })
|
||||
expect(within(missing).getByText('Giorgio Canali')).toBeInTheDocument()
|
||||
expect(within(missing).queryByRole('link', { name: 'Giorgio Canali' })).not.toBeInTheDocument()
|
||||
expect(within(missing).getByText('40 plays')).toBeInTheDocument()
|
||||
expect(within(missing).queryByRole('button', { name: 'Not interested' })).not.toBeInTheDocument() // no artist to dismiss yet
|
||||
expect(screen.getByText(/Learned from 1200 plays in 340 sittings/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('an artist that is missing goes on the wishlist by its name, and the list shows it', async () => {
|
||||
let wished = false
|
||||
const { calls } = setup({
|
||||
'GET /api/v1/me/suggestions': () => suggestions({ missing: [item('Giorgio Canali', wished ? 9 : null, { wishlisted: wished })] }),
|
||||
'POST /api/v1/me/suggestions/wishlist': () => {
|
||||
wished = true
|
||||
return { artist_id: 9 }
|
||||
},
|
||||
})
|
||||
const button = await screen.findByRole('button', { name: 'Wishlist' })
|
||||
expect(button).toHaveAttribute('aria-pressed', 'false')
|
||||
await userEvent.click(button)
|
||||
const sent = calls.filter((c) => c.key === 'POST /api/v1/me/suggestions/wishlist')
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(JSON.parse(sent[0].init.body as string)).toEqual({ name: 'Giorgio Canali' })
|
||||
expect(await screen.findByRole('button', { name: 'Wishlist', pressed: true })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('an artist already on the wishlist can be taken off', async () => {
|
||||
let wished = true
|
||||
const { calls } = setup({
|
||||
'GET /api/v1/me/suggestions': () => suggestions({ missing: [item('Giorgio Canali', 9, { wishlisted: wished })] }),
|
||||
'DELETE /api/v1/wishlist/9': () => {
|
||||
wished = false
|
||||
return none()
|
||||
},
|
||||
'GET /api/v1/wishlist': () => ({ items: [], total: 0, limit: 50, offset: 0 }),
|
||||
})
|
||||
await userEvent.click(await screen.findByRole('button', { name: 'Wishlist', pressed: true }))
|
||||
expect(await screen.findByRole('button', { name: 'Wishlist', pressed: false })).toBeInTheDocument()
|
||||
expect(calls.some((c) => c.key === 'DELETE /api/v1/wishlist/9')).toBe(true)
|
||||
})
|
||||
|
||||
test('"Not interested" dismisses the artist and the list is read again without it', async () => {
|
||||
let gone = false
|
||||
const { calls } = setup({
|
||||
'GET /api/v1/me/suggestions': () => suggestions({ library: gone ? [] : [item('Pixies', 2)] }),
|
||||
'POST /api/v1/discover/2/dismiss': () => {
|
||||
gone = true
|
||||
return none()
|
||||
},
|
||||
})
|
||||
const library = await screen.findByRole('region', { name: 'In your library, not played lately' })
|
||||
await userEvent.click(within(library).getByRole('button', { name: 'Not interested' }))
|
||||
expect(await screen.findByText('Nothing to bring back right now.')).toBeInTheDocument()
|
||||
expect(calls.some((c) => c.key === 'POST /api/v1/discover/2/dismiss')).toBe(true)
|
||||
})
|
||||
|
||||
test('with no plays yet it says what to do', async () => {
|
||||
setup({ 'GET /api/v1/me/suggestions': () => suggestions({ library: [], missing: [], built: { ...built, plays: 0, sessions: 0, artists: 0, links: 0 } }) })
|
||||
expect(await screen.findByText(/You have not played anything yet/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a list with nothing in it says so', async () => {
|
||||
setup({ 'GET /api/v1/me/suggestions': () => suggestions({ library: [], missing: [] }) })
|
||||
expect(await screen.findByText('Nothing to bring back right now.')).toBeInTheDocument()
|
||||
expect(screen.getByText('No artist you play is missing from your library.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('a server error has a way to try again', async () => {
|
||||
let fail = true
|
||||
setup({ 'GET /api/v1/me/suggestions': () => (fail ? apiError(500, 'internal', 'x') : suggestions()) })
|
||||
const retry = await screen.findByRole('button', { name: 'Try again' })
|
||||
fail = false
|
||||
await userEvent.click(retry)
|
||||
expect(await screen.findByRole('link', { name: 'Pixies' })).toBeInTheDocument()
|
||||
})
|
||||
138
web/src/pages/discover/ListeningTab.tsx
Normal file
138
web/src/pages/discover/ListeningTab.tsx
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { useTranslation } from 'react-i18next'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { ApiError } from '@/api/client'
|
||||
import { useArtistMarks, useMySettings } from '@/api/discover'
|
||||
import {
|
||||
useListeningSuggestions,
|
||||
useRefreshListeningSuggestions,
|
||||
useWishPlayedArtist,
|
||||
type ListeningSuggestion,
|
||||
} from '@/api/listeningSuggestions'
|
||||
import ListeningSwitch from '@/components/ListeningSwitch'
|
||||
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { errorMessageKey } from '@/i18n'
|
||||
|
||||
/** One artist: how well it goes with what you play, why, when you last played it, and what you can do about it. */
|
||||
function Row({ item, owned }: { item: ListeningSuggestion; owned: boolean }) {
|
||||
const { t, i18n } = useTranslation()
|
||||
const marks = useArtistMarks()
|
||||
const wish = useWishPlayedArtist()
|
||||
const refresh = useRefreshListeningSuggestions()
|
||||
const id = item.artist_id
|
||||
const when = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium' }).format(new Date(item.last_played_at))
|
||||
const failure = wish.error ?? marks.addToWishlist.error ?? marks.removeFromWishlist.error ?? marks.dismiss.error
|
||||
|
||||
function toggleWish() {
|
||||
if (item.wishlisted && id !== null) marks.removeFromWishlist.mutate(id, { onSuccess: refresh })
|
||||
else wish.mutate(item.name)
|
||||
}
|
||||
|
||||
return (
|
||||
<li className="flex flex-col gap-2 border-b border-border py-4">
|
||||
<div className="flex flex-wrap items-center gap-4">
|
||||
<div className="flex min-w-40 flex-1 flex-col">
|
||||
{owned && id !== null ? (
|
||||
<Link to={`/artists/${id}`} className="text-lg font-bold break-words hover:underline">
|
||||
{item.name}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-lg font-bold break-words">{item.name}</span>
|
||||
)}
|
||||
<div className="flex flex-wrap items-center gap-x-3 text-sm text-muted-foreground">
|
||||
<span>{t('discover.score', { percent: Math.round(item.score * 100) })}</span>
|
||||
<span>{t('discover.mine.lastPlayed', { when })}</span>
|
||||
<span>{t('discover.mine.plays', { count: item.plays })}</span>
|
||||
</div>
|
||||
{item.because.length > 0 && (
|
||||
<p className="text-sm break-words text-muted-foreground">
|
||||
{t('discover.mine.because', { names: item.because.map((b) => b.name).join(', ') })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-wrap justify-end gap-2">
|
||||
{!owned && (
|
||||
<Button variant={item.wishlisted ? 'default' : 'outline'} aria-pressed={item.wishlisted} disabled={wish.isPending} onClick={toggleWish}>
|
||||
{t('discover.wishlist')}
|
||||
</Button>
|
||||
)}
|
||||
{id !== null && (
|
||||
<Button variant="outline" onClick={() => marks.dismiss.mutate(id, { onSuccess: refresh })}>
|
||||
{t('discover.notInterested')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{failure ? (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{t(errorMessageKey(failure instanceof ApiError ? failure.code : 'unknown'))}
|
||||
</p>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
function Group({ title, hint, empty, items, owned }: { title: string; hint: string; empty: string; items: ListeningSuggestion[]; owned: boolean }) {
|
||||
return (
|
||||
<section aria-label={title} className="flex flex-col gap-2">
|
||||
<h2 className="text-xl font-bold">{title}</h2>
|
||||
<p className="max-w-xl text-sm text-muted-foreground">{hint}</p>
|
||||
{items.length === 0 ? (
|
||||
<EmptyMessage>{empty}</EmptyMessage>
|
||||
) : (
|
||||
<ul>
|
||||
{items.map((item) => (
|
||||
<Row key={item.name} item={item} owned={owned} />
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Suggestions learned from your own listening: Sonda looks at which artists you play in the same sitting, and
|
||||
* suggests the ones you have and have not played lately, and the ones you play and have no music of. It needs the
|
||||
* switch that lets Discover start from your listening; without it, this is the place to turn it on.
|
||||
*/
|
||||
export default function ListeningTab() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const settings = useMySettings()
|
||||
const allowed = settings.data?.discover_from_listening === true
|
||||
const suggestions = useListeningSuggestions({ enabled: allowed })
|
||||
|
||||
if (settings.isPending) return <Loading />
|
||||
if (!allowed) {
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="max-w-xl">{t('discover.mine.needs')}</p>
|
||||
<ListeningSwitch />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (suggestions.isError) return <ErrorMessage error={suggestions.error} onRetry={() => void suggestions.refetch()} />
|
||||
if (suggestions.isPending) return <Loading />
|
||||
|
||||
const data = suggestions.data
|
||||
const built = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(data.built.at))
|
||||
return (
|
||||
<div className="flex flex-col gap-8">
|
||||
<div className="flex max-w-xl flex-col gap-1">
|
||||
<p>{t('discover.mine.intro')}</p>
|
||||
{data.built.plays > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('discover.mine.built', { plays: data.built.plays, sessions: data.built.sessions, when: built })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{data.built.plays === 0 ? (
|
||||
<EmptyMessage>{t('discover.mine.nothing')}</EmptyMessage>
|
||||
) : (
|
||||
<>
|
||||
<Group title={t('discover.mine.libraryTitle')} hint={t('discover.mine.libraryHint')} empty={t('discover.mine.libraryNone')} items={data.library} owned />
|
||||
<Group title={t('discover.mine.missingTitle')} hint={t('discover.mine.missingHint')} empty={t('discover.mine.missingNone')} items={data.missing} owned={false} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Loading…
Reference in a new issue