Files
smart-home-tablet/app/api/voice/tools/spotify/route.ts
Cosmo 9bea298687
Some checks failed
Deploy / deploy (push) Failing after 1m40s
feat: Spotify integration (OAuth + voice tools)
2026-05-01 11:02:11 +00:00

79 lines
3.0 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { getAccessToken } from '@/lib/spotify-client'
async function spotifyFetch(path: string, method = 'GET', body?: any) {
const token = await getAccessToken()
const res = await fetch(`https://api.spotify.com/v1${path}`, {
method,
headers: {
Authorization: `Bearer ${token}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
},
...(body ? { body: JSON.stringify(body) } : {}),
})
if (res.status === 204) return { success: true }
if (!res.ok) {
const err = await res.text()
throw new Error(`Spotify API ${res.status}: ${err}`)
}
return res.json().catch(() => ({ success: true }))
}
export async function GET() {
// Get current playback state
const data = await spotifyFetch('/me/player')
if (!data || !data.item) return NextResponse.json({ playing: false })
return NextResponse.json({
playing: data.is_playing,
track: data.item.name,
artist: data.item.artists?.map((a: any) => a.name).join(', '),
album: data.item.album?.name,
volume: data.volume_percent,
device: data.device?.name,
})
}
export async function POST(req: NextRequest) {
const body = await req.json()
const { action, query, volume } = body
switch (action) {
case 'play':
if (query) {
// Search first
const search = await spotifyFetch(`/search?q=${encodeURIComponent(query)}&type=track,artist,playlist&limit=1`)
const track = search.tracks?.items?.[0]
const artist = search.artists?.items?.[0]
if (track) {
await spotifyFetch('/me/player/play', 'PUT', { uris: [track.uri] })
return NextResponse.json({ success: true, playing: track.name, artist: track.artists?.[0]?.name })
} else if (artist) {
// Play top tracks of artist
const top = await spotifyFetch(`/artists/${artist.id}/top-tracks?market=RU`)
const uris = top.tracks?.slice(0, 10).map((t: any) => t.uri) || []
await spotifyFetch('/me/player/play', 'PUT', { uris })
return NextResponse.json({ success: true, playing: `${artist.name} — топ треки` })
}
return NextResponse.json({ error: 'not found' }, { status: 404 })
} else {
await spotifyFetch('/me/player/play', 'PUT')
return NextResponse.json({ success: true })
}
case 'pause':
await spotifyFetch('/me/player/pause', 'PUT')
return NextResponse.json({ success: true })
case 'next':
await spotifyFetch('/me/player/next', 'POST')
return NextResponse.json({ success: true })
case 'previous':
await spotifyFetch('/me/player/previous', 'POST')
return NextResponse.json({ success: true })
case 'volume':
await spotifyFetch(`/me/player/volume?volume_percent=${Math.min(100, Math.max(0, volume || 50))}`, 'PUT')
return NextResponse.json({ success: true, volume })
default:
return NextResponse.json({ error: 'unknown action' }, { status: 400 })
}
}