Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 3 additions & 38 deletions packages/backend/src/services/SpotifyAuthService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { errorLog } from '@lucky/shared/utils'
// Single implementation lives in shared: the bot needs the same
// client-credentials token for /album album resolution.
export { getSpotifyClientToken } from '@lucky/shared/utils'

export type SpotifyTokenResponse = {
accessToken: string
Expand Down Expand Up @@ -89,44 +92,6 @@ export async function exchangeCodeForToken(
}
}

let cachedClientToken: { token: string; expiresAt: number } | null = null

export async function getSpotifyClientToken(): Promise<string | null> {
if (cachedClientToken && Date.now() < cachedClientToken.expiresAt) {
return cachedClientToken.token
}
const clientId = process.env.SPOTIFY_CLIENT_ID
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET
if (!clientId || !clientSecret) return null

const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64')
try {
const data = await fetchJson<{
access_token?: string
expires_in?: number
}>('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
Authorization: `Basic ${auth}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: 'grant_type=client_credentials',
})
if (!data?.access_token) return null
cachedClientToken = {
token: data.access_token,
expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000 - 30_000,
}
return cachedClientToken.token
} catch (error) {
errorLog({
message: 'Spotify client-credentials token request failed',
error,
})
return null
}
}

export function isSpotifyAuthConfigured(): boolean {
return !!(
process.env.SPOTIFY_CLIENT_ID &&
Expand Down
206 changes: 206 additions & 0 deletions packages/bot/src/functions/music/commands/album.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals'

jest.mock('discord-player', () => ({
QueryType: {
AUTO: 'AUTO',
SPOTIFY_SEARCH: 'SPOTIFY_SEARCH',
SPOTIFY_SONG: 'SPOTIFY_SONG',
},
}))

jest.mock('../../../utils/general/interactionReply', () => ({
interactionReply: jest.fn(),
}))

jest.mock('../../../utils/general/embeds', () => ({
createErrorEmbed: jest.fn((title: string, desc?: string) => ({
title,
description: desc,
})),
createSuccessEmbed: jest.fn((title: string, desc?: string) => ({
title,
description: desc,
})),
createWarningEmbed: jest.fn((title: string, desc?: string) => ({
title,
description: desc,
})),
}))

jest.mock('../../../services/musicManagement/queueResolver', () => ({
resolveGuildQueue: jest.fn(),
}))

jest.mock('../../../services/musicManagement/queueManipulation', () => ({
moveUserTrackToPriority: jest.fn(),
}))

jest.mock('@lucky/shared/utils/general/errorSanitizer', () => ({
createUserFriendlyError: jest.fn(() => 'User friendly error'),
}))

jest.mock('../../../utils/command/commandValidations', () => ({
requireVoiceChannel: jest.fn(async () => true),
requireDJRole: jest.fn(async () => true),
}))

const searchSpotifyAlbumsMock = jest.fn()

jest.mock('@lucky/shared/utils', () => ({
errorLog: jest.fn(),
warnLog: jest.fn(),
searchSpotifyAlbums: (...args: unknown[]) =>
searchSpotifyAlbumsMock(...args),
}))

jest.mock('@lucky/shared/utils/guards', () => ({
assertDefined: jest.fn((value: unknown) => value),
}))

jest.mock('@lucky/shared/config', () => ({
ENVIRONMENT_CONFIG: { PLAYER: { CONNECTION_TIMEOUT: 30_000 } },
}))

jest.mock('@lucky/shared/services', () => ({
featureToggleService: { isEnabled: jest.fn(async () => true) },
}))

import albumCommand from './album'
import { interactionReply } from '../../../utils/general/interactionReply'
import { resolveGuildQueue } from '../../../services/musicManagement/queueResolver'

const ALBUM_URL = 'https://open.spotify.com/album/0ETFjACtuP2ADo6LFhL6HN'

const createTrack = (title: string) => ({
title,
author: 'The Beatles',
url: `https://open.spotify.com/track/${encodeURIComponent(title)}`,
requestedBy: undefined as unknown,
})

const createInteraction = (query: string, artist: string | null = null) => ({
guildId: 'guild-1',
user: { id: 'user-1', username: 'tester' },
member: { voice: { channel: { id: 'voice-1' } } },
channel: { id: 'text-1' },
options: {
getString: jest.fn((name: string) =>
name === 'artist' ? artist : query,
),
},
deferReply: jest.fn(async () => undefined),
})

const lastReply = () =>
(interactionReply as jest.Mock).mock.calls.at(-1)?.[0] as {
content: { embeds: { title: string; description?: string }[] }
}

describe('album command album resolution', () => {
beforeEach(() => {
jest.clearAllMocks()
;(resolveGuildQueue as jest.Mock).mockReturnValue({
queue: { addTrack: jest.fn() },
})
})

it('resolves a text query to an album URL before searching', async () => {
// Pre-fix this query went to SPOTIFY_SEARCH, which can only return
// tracks, so searchResult.playlist was always null and the command
// always answered "No album found".
searchSpotifyAlbumsMock.mockResolvedValue([
{
id: 'a1',
name: 'Abbey Road',
artist: 'The Beatles',
url: ALBUM_URL,
},
])
const search = jest.fn(async () => ({
tracks: [createTrack('Come Together'), createTrack('Something')],
playlist: { title: 'Abbey Road' },
}))
const play = jest.fn(async () => ({
track: createTrack('Come Together'),
}))

await albumCommand.execute({
client: { player: { search, play } },
interaction: createInteraction('Abbey Road'),
} as never)

expect(searchSpotifyAlbumsMock).toHaveBeenCalledWith('Abbey Road', 1)
expect(search).toHaveBeenCalledTimes(1)
expect(search.mock.calls[0][0]).toBe(ALBUM_URL)
expect(search.mock.calls[0][1]).toMatchObject({ searchEngine: 'AUTO' })
expect(lastReply().content.embeds[0].title).not.toBe('No album found')
})

it('folds the artist option into the album lookup', async () => {
searchSpotifyAlbumsMock.mockResolvedValue([
{
id: 'a1',
name: 'Abbey Road',
artist: 'The Beatles',
url: ALBUM_URL,
},
])
const search = jest.fn(async () => ({
tracks: [createTrack('Come Together')],
playlist: { title: 'Abbey Road' },
}))

await albumCommand.execute({
client: {
player: {
search,
play: jest.fn(async () => ({ track: null })),
},
},
interaction: createInteraction('Abbey Road', 'The Beatles'),
} as never)

expect(searchSpotifyAlbumsMock).toHaveBeenCalledWith(
'Abbey Road The Beatles',
1,
)
})

it('passes a Spotify album URL straight through without a lookup', async () => {
const search = jest.fn(async () => ({
tracks: [createTrack('Come Together')],
playlist: { title: 'Abbey Road' },
}))

await albumCommand.execute({
client: {
player: {
search,
play: jest.fn(async () => ({ track: null })),
},
},
interaction: createInteraction(ALBUM_URL),
} as never)

expect(searchSpotifyAlbumsMock).not.toHaveBeenCalled()
expect(search.mock.calls[0][0]).toBe(ALBUM_URL)
})

it('reports an actionable message when no album matches', async () => {
searchSpotifyAlbumsMock.mockResolvedValue([])
const search = jest.fn()

await albumCommand.execute({
client: { player: { search, play: jest.fn() } },
interaction: createInteraction('zzzz not an album'),
} as never)

expect(search).not.toHaveBeenCalled()
const embed = lastReply().content.embeds[0]
expect(embed.title).toBe('No album found')
// The old copy told users to try "a more specific album search",
// which no text query could ever satisfy.
expect(embed.description).not.toContain('more specific album search')
expect(embed.description).toContain('zzzz not an album')
})
})
53 changes: 42 additions & 11 deletions packages/bot/src/functions/music/commands/album.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
createWarningEmbed,
} from '../../../utils/general/embeds'
import { interactionReply } from '../../../utils/general/interactionReply'
import { errorLog } from '@lucky/shared/utils'
import { errorLog, warnLog, searchSpotifyAlbums } from '@lucky/shared/utils'
import { createUserFriendlyError } from '@lucky/shared/utils/general/errorSanitizer'
import { assertDefined } from '@lucky/shared/utils/guards'
import { ENVIRONMENT_CONFIG } from '@lucky/shared/config'
Expand Down Expand Up @@ -111,16 +111,43 @@
}

try {
const isUrl = isSpotifyAlbumUrl(query)
const searchEngine = isUrl
? QueryType.AUTO
: QueryType.SPOTIFY_SEARCH
const searchQuery =
!isUrl && artistFilter ? `${query} ${artistFilter}` : query

const searchResult = await client.player.search(searchQuery, {
// A free-text query cannot reach an extractor's album branch: every
// search QueryType hits a *track* search and responds with
// `createResponse(null, tracks)`, so `searchResult.playlist` was
// always null and every text query failed (#2050). Resolve the
// query to an album URL first, then run the URL path that works.
let albumUrl = isSpotifyAlbumUrl(query) ? query : null

if (!albumUrl) {
const albumQuery = artistFilter
? `${query} ${artistFilter}`
: query
const [match] = await searchSpotifyAlbums(albumQuery, 1)
if (!match) {
warnLog({
message:
'Album query did not resolve to a Spotify album',
data: { query, artistFilter },
})
await interactionReply({
interaction,
content: {
embeds: [
createErrorEmbed(
'No album found',
`No album matched **${query}**${artistFilter ? ` by **${artistFilter}**` : ''}. Try the full album title, or paste a Spotify album URL.`,

Check warning on line 138 in packages/bot/src/functions/music/commands/album.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this code to not use nested template literals.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Lucky&issues=AaAlWpnfCOb4kPNI8Wdp&open=AaAlWpnfCOb4kPNI8Wdp&pullRequest=2053
),
],
},
})
return
}
albumUrl = match.url
}

const searchResult = await client.player.search(albumUrl, {
requestedBy: interaction.user,
searchEngine,
searchEngine: QueryType.AUTO,
})

if (!searchResult?.tracks.length) {
Expand All @@ -139,13 +166,17 @@
}

if (!searchResult.playlist) {
warnLog({
message: 'Resolved album URL returned no playlist',
data: { query, albumUrl },
})
await interactionReply({
interaction,
content: {
embeds: [
createErrorEmbed(
'No album found',
'Please provide a Spotify album URL or a more specific album search.',
'Spotify returned tracks but no album listing. Try again, or paste a Spotify album URL.',
),
],
},
Expand Down
Loading
Loading