Commit 58bcf90a authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Wire real save-to-library action into TelegramLink chat music list

The chat-detail view listed found songs as read-only metadata with no
way to actually keep them. It now calls the existing /music/tag
pipeline per song (Save button -> spinner -> Saved, with the real
identified title/artist swapped in), so browsing a linked chat can
actually grow the user's library instead of just previewing it.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 69fd45e8
Pipeline #1104 canceled with stage
...@@ -110,9 +110,9 @@ const BACKEND_TODO: WorkItem[] = [ ...@@ -110,9 +110,9 @@ const BACKEND_TODO: WorkItem[] = [
note: 'AcoustID candidates carry a score, but it\'s embedded in a source string ("AcoustID (72%)"), not a queryable field - and Shazam candidates carry no score at all. Needs a schema decision, not just a passthrough.', note: 'AcoustID candidates carry a score, but it\'s embedded in a source string ("AcoustID (72%)"), not a queryable field - and Shazam candidates carry no score at all. Needs a schema decision, not just a passthrough.',
}, },
{ {
item: 'Telegram chat scanning: auto-scan approved chats, tag + save songs', item: 'Telegram chat scanning: auto-scan approved chats, tag + save songs in bulk',
status: 'needs-design', status: 'needs-design',
note: 'A materially bigger scan-everything design than the current one-chat-at-a-time /auth/telegram/chats/{id}/music lookup.', note: 'Manually tagging one found song at a time now works end to end (browse a chat, hit Save, POST /music/tag). This item is specifically the bigger scan-everything-automatically design - still undone.',
}, },
{ {
item: 'Proxy-aware IP detection for the rate limiters', item: 'Proxy-aware IP detection for the rate limiters',
...@@ -129,7 +129,7 @@ const FRONTEND_DONE: DoneGroup[] = [ ...@@ -129,7 +129,7 @@ const FRONTEND_DONE: DoneGroup[] = [
items: [ items: [
'Login page: username/password + register, toggled in place', 'Login page: username/password + register, toggled in place',
'Route guards redirect to /login when signed out instead of showing a blank page', 'Route guards redirect to /login when signed out instead of showing a blank page',
'Telegram linking page: phone + code, then browse linked chats and the music found in each', 'Telegram linking page: phone + code, then browse linked chats and save any found song to the library (tags via /music/tag, one song at a time)',
], ],
}, },
{ area: 'Soundmarks', items: ['Nearby page: dark-themed map, tier-aware display, proposals + voting UI'] }, { area: 'Soundmarks', items: ['Nearby page: dark-themed map, tier-aware display, proposals + voting UI'] },
...@@ -266,7 +266,7 @@ export function Roadmap() { ...@@ -266,7 +266,7 @@ export function Roadmap() {
['9', 'Feature areas'], ['9', 'Feature areas'],
['0', 'Critical security gaps'], ['0', 'Critical security gaps'],
['229', 'Backend tests'], ['229', 'Backend tests'],
['178', 'Frontend tests'], ['180', 'Frontend tests'],
['4', 'Pages w/ zero tests'], ['4', 'Pages w/ zero tests'],
].map(([n, l]) => ( ].map(([n, l]) => (
<div key={l}> <div key={l}>
......
...@@ -7,9 +7,25 @@ import { AuthProvider } from '../context/AuthContext' ...@@ -7,9 +7,25 @@ import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext' import { PlayerProvider } from '../context/PlayerContext'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import * as authApi from '../api/auth' import * as authApi from '../api/auth'
import * as musicApi from '../api/music'
const CHAT = { id: 1, title: 'Music Sharing', type: 'group' } const CHAT = { id: 1, title: 'Music Sharing', type: 'group' }
const MUSIC = { message_id: 1, title: 'Invisible', artist: 'Duran Duran', duration: 200, file_name: 'invisible.mp3' } const MUSIC = { message_id: 1, title: 'Invisible', artist: 'Duran Duran', duration: 200, file_name: 'invisible.mp3' }
const TAG_RESPONSE = {
status: 'success',
download_url: '/files/invisible-tagged.mp3',
metadata: {
library_song_id: 42,
title: 'Invisible (Remastered)',
artist: 'Duran Duran',
album: 'Notorious',
genre: 'Pop',
year: '1986',
has_lyrics: true,
lyrics: null,
cover_art: null,
},
}
function renderPage() { function renderPage() {
return render( return render(
...@@ -164,4 +180,41 @@ describe('TelegramLink', () => { ...@@ -164,4 +180,41 @@ describe('TelegramLink', () => {
expect(await screen.findByText('Linked. Tap a chat to see the music found in it.')).toBeInTheDocument() expect(await screen.findByText('Linked. Tap a chat to see the music found in it.')).toBeInTheDocument()
}) })
it('saves a found song to the library and shows the identified title/artist', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC] })
const tagFromChat = vi.spyOn(musicApi, 'tagFromChat').mockResolvedValue(TAG_RESPONSE)
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: /Save/ }))
expect(tagFromChat).toHaveBeenCalledWith(1, 1)
expect(await screen.findByText('Saved')).toBeInTheDocument()
expect(screen.getByText('Invisible (Remastered)')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /Save/ })).not.toBeInTheDocument()
})
it('shows an inline error when saving a song fails, and lets you retry', async () => {
vi.spyOn(authApi, 'getChats').mockResolvedValue({ status: 'success', chats: [CHAT] })
vi.spyOn(authApi, 'getChatMusic').mockResolvedValue({ status: 'success', music: [MUSIC] })
const tagFromChat = vi
.spyOn(musicApi, 'tagFromChat')
.mockRejectedValueOnce(new ApiError(500, 'Could not identify this track', null))
.mockResolvedValueOnce(TAG_RESPONSE)
renderPage()
await userEvent.click(await screen.findByText('Music Sharing'))
await screen.findByText('Invisible')
await userEvent.click(screen.getByRole('button', { name: /Save/ }))
expect(await screen.findByText('Could not identify this track')).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: /Save/ }))
expect(await screen.findByText('Saved')).toBeInTheDocument()
expect(tagFromChat).toHaveBeenCalledTimes(2)
})
}) })
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { MessageCircle, Music2 } from 'lucide-react' import { Check, Download, MessageCircle, Music2 } from 'lucide-react'
import { import {
getChatMusic, getChatMusic,
getChats, getChats,
...@@ -8,6 +8,7 @@ import { ...@@ -8,6 +8,7 @@ import {
type Chat, type Chat,
type ChatMusic, type ChatMusic,
} from '../api/auth' } from '../api/auth'
import { tagFromChat, type TagMetadata } from '../api/music'
import { ApiError } from '../api/client' import { ApiError } from '../api/client'
import { Layout } from '../components/Layout' import { Layout } from '../components/Layout'
import { Button } from '../components/ui/Button' import { Button } from '../components/ui/Button'
...@@ -33,6 +34,10 @@ export function TelegramLink() { ...@@ -33,6 +34,10 @@ export function TelegramLink() {
const [musicLoading, setMusicLoading] = useState(false) const [musicLoading, setMusicLoading] = useState(false)
const [musicError, setMusicError] = useState<string | null>(null) const [musicError, setMusicError] = useState<string | null>(null)
const [savingId, setSavingId] = useState<number | null>(null)
const [savedMeta, setSavedMeta] = useState<Record<number, TagMetadata>>({})
const [saveErrors, setSaveErrors] = useState<Record<number, string>>({})
function loadChats() { function loadChats() {
setChatsError(null) setChatsError(null)
getChats() getChats()
...@@ -99,12 +104,35 @@ export function TelegramLink() { ...@@ -99,12 +104,35 @@ export function TelegramLink() {
setMusic(null) setMusic(null)
setMusicError(null) setMusicError(null)
setMusicLoading(true) setMusicLoading(true)
setSavedMeta({})
setSaveErrors({})
getChatMusic(chat.id) getChatMusic(chat.id)
.then((res) => setMusic(res.music)) .then((res) => setMusic(res.music))
.catch((err) => setMusicError(err instanceof ApiError ? err.message : 'Failed to load music from this chat')) .catch((err) => setMusicError(err instanceof ApiError ? err.message : 'Failed to load music from this chat'))
.finally(() => setMusicLoading(false)) .finally(() => setMusicLoading(false))
} }
async function handleSave(m: ChatMusic) {
if (!selectedChat) return
setSavingId(m.message_id)
setSaveErrors((prev) => {
const next = { ...prev }
delete next[m.message_id]
return next
})
try {
const res = await tagFromChat(selectedChat.id, m.message_id)
setSavedMeta((prev) => ({ ...prev, [m.message_id]: res.metadata }))
} catch (err) {
setSaveErrors((prev) => ({
...prev,
[m.message_id]: err instanceof ApiError ? err.message : 'Failed to save this song',
}))
} finally {
setSavingId(null)
}
}
if (step === 'checking') { if (step === 'checking') {
return ( return (
<Layout title="Link Telegram"> <Layout title="Link Telegram">
...@@ -194,17 +222,40 @@ export function TelegramLink() { ...@@ -194,17 +222,40 @@ export function TelegramLink() {
<EmptyState icon={Music2} message="No music found in this chat." /> <EmptyState icon={Music2} message="No music found in this chat." />
)} )}
<ul className="divide-y divide-neutral-800/80"> <ul className="divide-y divide-neutral-800/80">
{music?.map((m) => ( {music?.map((m) => {
const saved = savedMeta[m.message_id]
const saveError = saveErrors[m.message_id]
const saving = savingId === m.message_id
return (
<li key={m.message_id} className="flex items-center gap-4 px-2 py-3"> <li key={m.message_id} className="flex items-center gap-4 px-2 py-3">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600"> <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-md bg-neutral-800 text-neutral-600">
<Music2 size={18} strokeWidth={1.75} /> <Music2 size={18} strokeWidth={1.75} />
</div> </div>
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<p className="truncate font-medium text-white">{m.title}</p> <p className="truncate font-medium text-white">{saved ? saved.title : m.title}</p>
<p className="truncate text-sm text-neutral-400">{m.artist}</p> <p className="truncate text-sm text-neutral-400">{saved ? saved.artist : m.artist}</p>
{saveError && <p className="mt-1 text-xs text-red-400">{saveError}</p>}
</div> </div>
{saved ? (
<span className="flex shrink-0 items-center gap-1 text-sm text-emerald-400">
<Check size={16} strokeWidth={2} />
Saved
</span>
) : (
<Button
variant="ghost"
size="sm"
disabled={saving}
onClick={() => handleSave(m)}
className="shrink-0 gap-1.5"
>
<Download size={14} strokeWidth={2} />
{saving ? 'Saving…' : 'Save'}
</Button>
)}
</li> </li>
))} )
})}
</ul> </ul>
</Layout> </Layout>
) )
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment