mirror of
https://github.com/BluemediaDev/muse.git
synced 2025-06-27 17:22:42 +02:00
Merge pull request #1092 from sofushn/master
feat: allow running without spotify
This commit is contained in:
commit
07bfd32cb3
7 changed files with 180 additions and 145 deletions
|
@ -1,7 +1,7 @@
|
||||||
import {AutocompleteInteraction, ChatInputCommandInteraction} from 'discord.js';
|
import {AutocompleteInteraction, ChatInputCommandInteraction} from 'discord.js';
|
||||||
import {URL} from 'url';
|
import {URL} from 'url';
|
||||||
import {SlashCommandBuilder} from '@discordjs/builders';
|
import {SlashCommandBuilder, SlashCommandSubcommandsOnlyBuilder} from '@discordjs/builders';
|
||||||
import {inject, injectable} from 'inversify';
|
import {inject, injectable, optional} from 'inversify';
|
||||||
import Spotify from 'spotify-web-api-node';
|
import Spotify from 'spotify-web-api-node';
|
||||||
import Command from './index.js';
|
import Command from './index.js';
|
||||||
import {TYPES} from '../types.js';
|
import {TYPES} from '../types.js';
|
||||||
|
@ -13,12 +13,29 @@ import AddQueryToQueue from '../services/add-query-to-queue.js';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export default class implements Command {
|
export default class implements Command {
|
||||||
public readonly slashCommand = new SlashCommandBuilder()
|
public readonly slashCommand: Partial<SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder> & Pick<SlashCommandBuilder, 'toJSON'>;
|
||||||
|
|
||||||
|
public requiresVC = true;
|
||||||
|
|
||||||
|
private readonly spotify?: Spotify;
|
||||||
|
private readonly cache: KeyValueCacheProvider;
|
||||||
|
private readonly addQueryToQueue: AddQueryToQueue;
|
||||||
|
|
||||||
|
constructor(@inject(TYPES.ThirdParty) @optional() thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue) {
|
||||||
|
this.spotify = thirdParty?.spotify;
|
||||||
|
this.cache = cache;
|
||||||
|
this.addQueryToQueue = addQueryToQueue;
|
||||||
|
|
||||||
|
const queryDescription = thirdParty === undefined
|
||||||
|
? 'YouTube URL or search query'
|
||||||
|
: 'YouTube URL, Spotify URL, or search query';
|
||||||
|
|
||||||
|
this.slashCommand = new SlashCommandBuilder()
|
||||||
.setName('play')
|
.setName('play')
|
||||||
.setDescription('play a song')
|
.setDescription('play a song')
|
||||||
.addStringOption(option => option
|
.addStringOption(option => option
|
||||||
.setName('query')
|
.setName('query')
|
||||||
.setDescription('YouTube URL, Spotify URL, or search query')
|
.setDescription(queryDescription)
|
||||||
.setAutocomplete(true)
|
.setAutocomplete(true)
|
||||||
.setRequired(true))
|
.setRequired(true))
|
||||||
.addBooleanOption(option => option
|
.addBooleanOption(option => option
|
||||||
|
@ -33,17 +50,6 @@ export default class implements Command {
|
||||||
.addBooleanOption(option => option
|
.addBooleanOption(option => option
|
||||||
.setName('skip')
|
.setName('skip')
|
||||||
.setDescription('skip the currently playing track'));
|
.setDescription('skip the currently playing track'));
|
||||||
|
|
||||||
public requiresVC = true;
|
|
||||||
|
|
||||||
private readonly spotify: Spotify;
|
|
||||||
private readonly cache: KeyValueCacheProvider;
|
|
||||||
private readonly addQueryToQueue: AddQueryToQueue;
|
|
||||||
|
|
||||||
constructor(@inject(TYPES.ThirdParty) thirdParty: ThirdParty, @inject(TYPES.KeyValueCache) cache: KeyValueCacheProvider, @inject(TYPES.Services.AddQueryToQueue) addQueryToQueue: AddQueryToQueue) {
|
|
||||||
this.spotify = thirdParty.spotify;
|
|
||||||
this.cache = cache;
|
|
||||||
this.addQueryToQueue = addQueryToQueue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async execute(interaction: ChatInputCommandInteraction): Promise<void> {
|
public async execute(interaction: ChatInputCommandInteraction): Promise<void> {
|
||||||
|
|
|
@ -57,11 +57,20 @@ container.bind<Client>(TYPES.Client).toConstantValue(new Client({intents}));
|
||||||
// Managers
|
// Managers
|
||||||
container.bind<PlayerManager>(TYPES.Managers.Player).to(PlayerManager).inSingletonScope();
|
container.bind<PlayerManager>(TYPES.Managers.Player).to(PlayerManager).inSingletonScope();
|
||||||
|
|
||||||
|
// Config values
|
||||||
|
container.bind(TYPES.Config).toConstantValue(new ConfigProvider());
|
||||||
|
|
||||||
// Services
|
// Services
|
||||||
container.bind<GetSongs>(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope();
|
container.bind<GetSongs>(TYPES.Services.GetSongs).to(GetSongs).inSingletonScope();
|
||||||
container.bind<AddQueryToQueue>(TYPES.Services.AddQueryToQueue).to(AddQueryToQueue).inSingletonScope();
|
container.bind<AddQueryToQueue>(TYPES.Services.AddQueryToQueue).to(AddQueryToQueue).inSingletonScope();
|
||||||
container.bind<YoutubeAPI>(TYPES.Services.YoutubeAPI).to(YoutubeAPI).inSingletonScope();
|
container.bind<YoutubeAPI>(TYPES.Services.YoutubeAPI).to(YoutubeAPI).inSingletonScope();
|
||||||
|
|
||||||
|
// Only instanciate spotify dependencies if the Spotify client ID and secret are set
|
||||||
|
const config = container.get<ConfigProvider>(TYPES.Config);
|
||||||
|
if (config.SPOTIFY_CLIENT_ID !== '' && config.SPOTIFY_CLIENT_SECRET !== '') {
|
||||||
container.bind<SpotifyAPI>(TYPES.Services.SpotifyAPI).to(SpotifyAPI).inSingletonScope();
|
container.bind<SpotifyAPI>(TYPES.Services.SpotifyAPI).to(SpotifyAPI).inSingletonScope();
|
||||||
|
container.bind(TYPES.ThirdParty).to(ThirdParty);
|
||||||
|
}
|
||||||
|
|
||||||
// Commands
|
// Commands
|
||||||
[
|
[
|
||||||
|
@ -91,12 +100,7 @@ container.bind<SpotifyAPI>(TYPES.Services.SpotifyAPI).to(SpotifyAPI).inSingleton
|
||||||
container.bind<Command>(TYPES.Command).to(command).inSingletonScope();
|
container.bind<Command>(TYPES.Command).to(command).inSingletonScope();
|
||||||
});
|
});
|
||||||
|
|
||||||
// Config values
|
|
||||||
container.bind(TYPES.Config).toConstantValue(new ConfigProvider());
|
|
||||||
|
|
||||||
// Static libraries
|
// Static libraries
|
||||||
container.bind(TYPES.ThirdParty).to(ThirdParty);
|
|
||||||
|
|
||||||
container.bind(TYPES.FileCache).to(FileCacheProvider);
|
container.bind(TYPES.FileCache).to(FileCacheProvider);
|
||||||
container.bind(TYPES.KeyValueCache).to(KeyValueCacheProvider);
|
container.bind(TYPES.KeyValueCache).to(KeyValueCacheProvider);
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
/* eslint-disable complexity */
|
/* eslint-disable complexity */
|
||||||
import {ChatInputCommandInteraction, GuildMember} from 'discord.js';
|
import {ChatInputCommandInteraction, GuildMember} from 'discord.js';
|
||||||
import {URL} from 'node:url';
|
|
||||||
import {inject, injectable} from 'inversify';
|
import {inject, injectable} from 'inversify';
|
||||||
import shuffle from 'array-shuffle';
|
import shuffle from 'array-shuffle';
|
||||||
import {TYPES} from '../types.js';
|
import {TYPES} from '../types.js';
|
||||||
|
@ -60,74 +59,7 @@ export default class AddQueryToQueue {
|
||||||
|
|
||||||
await interaction.deferReply({ephemeral: queueAddResponseEphemeral});
|
await interaction.deferReply({ephemeral: queueAddResponseEphemeral});
|
||||||
|
|
||||||
let newSongs: SongMetadata[] = [];
|
let [newSongs, extraMsg] = await this.getSongs.getSongs(query, playlistLimit, shouldSplitChapters);
|
||||||
let extraMsg = '';
|
|
||||||
|
|
||||||
// Test if it's a complete URL
|
|
||||||
try {
|
|
||||||
const url = new URL(query);
|
|
||||||
|
|
||||||
const YOUTUBE_HOSTS = [
|
|
||||||
'www.youtube.com',
|
|
||||||
'youtu.be',
|
|
||||||
'youtube.com',
|
|
||||||
'music.youtube.com',
|
|
||||||
'www.music.youtube.com',
|
|
||||||
];
|
|
||||||
|
|
||||||
if (YOUTUBE_HOSTS.includes(url.host)) {
|
|
||||||
// YouTube source
|
|
||||||
if (url.searchParams.get('list')) {
|
|
||||||
// YouTube playlist
|
|
||||||
newSongs.push(...await this.getSongs.youtubePlaylist(url.searchParams.get('list')!, shouldSplitChapters));
|
|
||||||
} else {
|
|
||||||
const songs = await this.getSongs.youtubeVideo(url.href, shouldSplitChapters);
|
|
||||||
|
|
||||||
if (songs) {
|
|
||||||
newSongs.push(...songs);
|
|
||||||
} else {
|
|
||||||
throw new Error('that doesn\'t exist');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') {
|
|
||||||
const [convertedSongs, nSongsNotFound, totalSongs] = await this.getSongs.spotifySource(query, playlistLimit, shouldSplitChapters);
|
|
||||||
|
|
||||||
if (totalSongs > playlistLimit) {
|
|
||||||
extraMsg = `a random sample of ${playlistLimit} songs was taken`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (totalSongs > playlistLimit && nSongsNotFound !== 0) {
|
|
||||||
extraMsg += ' and ';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (nSongsNotFound !== 0) {
|
|
||||||
if (nSongsNotFound === 1) {
|
|
||||||
extraMsg += '1 song was not found';
|
|
||||||
} else {
|
|
||||||
extraMsg += `${nSongsNotFound.toString()} songs were not found`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
newSongs.push(...convertedSongs);
|
|
||||||
} else {
|
|
||||||
const song = await this.getSongs.httpLiveStream(query);
|
|
||||||
|
|
||||||
if (song) {
|
|
||||||
newSongs.push(song);
|
|
||||||
} else {
|
|
||||||
throw new Error('that doesn\'t exist');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_: unknown) {
|
|
||||||
// Not a URL, must search YouTube
|
|
||||||
const songs = await this.getSongs.youtubeVideoSearch(query, shouldSplitChapters);
|
|
||||||
|
|
||||||
if (songs) {
|
|
||||||
newSongs.push(...songs);
|
|
||||||
} else {
|
|
||||||
throw new Error('that doesn\'t exist');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (newSongs.length === 0) {
|
if (newSongs.length === 0) {
|
||||||
throw new Error('no songs found');
|
throw new Error('no songs found');
|
||||||
|
|
|
@ -12,8 +12,8 @@ export const DATA_DIR = path.resolve(process.env.DATA_DIR ? process.env.DATA_DIR
|
||||||
const CONFIG_MAP = {
|
const CONFIG_MAP = {
|
||||||
DISCORD_TOKEN: process.env.DISCORD_TOKEN,
|
DISCORD_TOKEN: process.env.DISCORD_TOKEN,
|
||||||
YOUTUBE_API_KEY: process.env.YOUTUBE_API_KEY,
|
YOUTUBE_API_KEY: process.env.YOUTUBE_API_KEY,
|
||||||
SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID,
|
SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID ?? '',
|
||||||
SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET,
|
SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET ?? '',
|
||||||
REGISTER_COMMANDS_ON_BOT: process.env.REGISTER_COMMANDS_ON_BOT === 'true',
|
REGISTER_COMMANDS_ON_BOT: process.env.REGISTER_COMMANDS_ON_BOT === 'true',
|
||||||
DATA_DIR,
|
DATA_DIR,
|
||||||
CACHE_DIR: path.join(DATA_DIR, 'cache'),
|
CACHE_DIR: path.join(DATA_DIR, 'cache'),
|
||||||
|
|
|
@ -1,34 +1,120 @@
|
||||||
import {inject, injectable} from 'inversify';
|
import {inject, injectable, optional} from 'inversify';
|
||||||
import * as spotifyURI from 'spotify-uri';
|
import * as spotifyURI from 'spotify-uri';
|
||||||
import {SongMetadata, QueuedPlaylist, MediaSource} from './player.js';
|
import {SongMetadata, QueuedPlaylist, MediaSource} from './player.js';
|
||||||
import {TYPES} from '../types.js';
|
import {TYPES} from '../types.js';
|
||||||
import ffmpeg from 'fluent-ffmpeg';
|
import ffmpeg from 'fluent-ffmpeg';
|
||||||
import YoutubeAPI from './youtube-api.js';
|
import YoutubeAPI from './youtube-api.js';
|
||||||
import SpotifyAPI, {SpotifyTrack} from './spotify-api.js';
|
import SpotifyAPI, {SpotifyTrack} from './spotify-api.js';
|
||||||
|
import {URL} from 'node:url';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
export default class {
|
export default class {
|
||||||
private readonly youtubeAPI: YoutubeAPI;
|
private readonly youtubeAPI: YoutubeAPI;
|
||||||
private readonly spotifyAPI: SpotifyAPI;
|
private readonly spotifyAPI?: SpotifyAPI;
|
||||||
|
|
||||||
constructor(@inject(TYPES.Services.YoutubeAPI) youtubeAPI: YoutubeAPI, @inject(TYPES.Services.SpotifyAPI) spotifyAPI: SpotifyAPI) {
|
constructor(@inject(TYPES.Services.YoutubeAPI) youtubeAPI: YoutubeAPI, @inject(TYPES.Services.SpotifyAPI) @optional() spotifyAPI?: SpotifyAPI) {
|
||||||
this.youtubeAPI = youtubeAPI;
|
this.youtubeAPI = youtubeAPI;
|
||||||
this.spotifyAPI = spotifyAPI;
|
this.spotifyAPI = spotifyAPI;
|
||||||
}
|
}
|
||||||
|
|
||||||
async youtubeVideoSearch(query: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
|
async getSongs(query: string, playlistLimit: number, shouldSplitChapters: boolean): Promise<[SongMetadata[], string]> {
|
||||||
|
const newSongs: SongMetadata[] = [];
|
||||||
|
let extraMsg = '';
|
||||||
|
|
||||||
|
// Test if it's a complete URL
|
||||||
|
try {
|
||||||
|
const url = new URL(query);
|
||||||
|
|
||||||
|
const YOUTUBE_HOSTS = [
|
||||||
|
'www.youtube.com',
|
||||||
|
'youtu.be',
|
||||||
|
'youtube.com',
|
||||||
|
'music.youtube.com',
|
||||||
|
'www.music.youtube.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
if (YOUTUBE_HOSTS.includes(url.host)) {
|
||||||
|
// YouTube source
|
||||||
|
if (url.searchParams.get('list')) {
|
||||||
|
// YouTube playlist
|
||||||
|
newSongs.push(...await this.youtubePlaylist(url.searchParams.get('list')!, shouldSplitChapters));
|
||||||
|
} else {
|
||||||
|
const songs = await this.youtubeVideo(url.href, shouldSplitChapters);
|
||||||
|
|
||||||
|
if (songs) {
|
||||||
|
newSongs.push(...songs);
|
||||||
|
} else {
|
||||||
|
throw new Error('that doesn\'t exist');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (url.protocol === 'spotify:' || url.host === 'open.spotify.com') {
|
||||||
|
if (this.spotifyAPI === undefined) {
|
||||||
|
throw new Error('Spotify is not enabled!');
|
||||||
|
}
|
||||||
|
|
||||||
|
const [convertedSongs, nSongsNotFound, totalSongs] = await this.spotifySource(query, playlistLimit, shouldSplitChapters);
|
||||||
|
|
||||||
|
if (totalSongs > playlistLimit) {
|
||||||
|
extraMsg = `a random sample of ${playlistLimit} songs was taken`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (totalSongs > playlistLimit && nSongsNotFound !== 0) {
|
||||||
|
extraMsg += ' and ';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nSongsNotFound !== 0) {
|
||||||
|
if (nSongsNotFound === 1) {
|
||||||
|
extraMsg += '1 song was not found';
|
||||||
|
} else {
|
||||||
|
extraMsg += `${nSongsNotFound.toString()} songs were not found`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
newSongs.push(...convertedSongs);
|
||||||
|
} else {
|
||||||
|
const song = await this.httpLiveStream(query);
|
||||||
|
|
||||||
|
if (song) {
|
||||||
|
newSongs.push(song);
|
||||||
|
} else {
|
||||||
|
throw new Error('that doesn\'t exist');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
if (err instanceof Error && err.message === 'Spotify is not enabled!') {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Not a URL, must search YouTube
|
||||||
|
const songs = await this.youtubeVideoSearch(query, shouldSplitChapters);
|
||||||
|
|
||||||
|
if (songs) {
|
||||||
|
newSongs.push(...songs);
|
||||||
|
} else {
|
||||||
|
throw new Error('that doesn\'t exist');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [newSongs, extraMsg];
|
||||||
|
}
|
||||||
|
|
||||||
|
private async youtubeVideoSearch(query: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
|
||||||
return this.youtubeAPI.search(query, shouldSplitChapters);
|
return this.youtubeAPI.search(query, shouldSplitChapters);
|
||||||
}
|
}
|
||||||
|
|
||||||
async youtubeVideo(url: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
|
private async youtubeVideo(url: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
|
||||||
return this.youtubeAPI.getVideo(url, shouldSplitChapters);
|
return this.youtubeAPI.getVideo(url, shouldSplitChapters);
|
||||||
}
|
}
|
||||||
|
|
||||||
async youtubePlaylist(listId: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
|
private async youtubePlaylist(listId: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> {
|
||||||
return this.youtubeAPI.getPlaylist(listId, shouldSplitChapters);
|
return this.youtubeAPI.getPlaylist(listId, shouldSplitChapters);
|
||||||
}
|
}
|
||||||
|
|
||||||
async spotifySource(url: string, playlistLimit: number, shouldSplitChapters: boolean): Promise<[SongMetadata[], number, number]> {
|
private async spotifySource(url: string, playlistLimit: number, shouldSplitChapters: boolean): Promise<[SongMetadata[], number, number]> {
|
||||||
|
if (this.spotifyAPI === undefined) {
|
||||||
|
return [[], 0, 0];
|
||||||
|
}
|
||||||
|
|
||||||
const parsed = spotifyURI.parse(url);
|
const parsed = spotifyURI.parse(url);
|
||||||
|
|
||||||
switch (parsed.type) {
|
switch (parsed.type) {
|
||||||
|
@ -58,7 +144,7 @@ export default class {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async httpLiveStream(url: string): Promise<SongMetadata> {
|
private async httpLiveStream(url: string): Promise<SongMetadata> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
ffmpeg(url).ffprobe((err, _) => {
|
ffmpeg(url).ffprobe((err, _) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
|
|
|
@ -95,7 +95,7 @@ export default class {
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!firstVideo) {
|
if (!firstVideo) {
|
||||||
throw new Error('No video found.');
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.getVideo(firstVideo.url, shouldSplitChapters);
|
return this.getVideo(firstVideo.url, shouldSplitChapters);
|
||||||
|
|
|
@ -14,28 +14,18 @@ const filterDuplicates = <T extends {name: string}>(items: T[]) => {
|
||||||
return results;
|
return results;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: SpotifyWebApi, limit = 10): Promise<APIApplicationCommandOptionChoice[]> => {
|
const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify?: SpotifyWebApi, limit = 10): Promise<APIApplicationCommandOptionChoice[]> => {
|
||||||
const [youtubeSuggestions, spotifyResults] = await Promise.all([
|
// Only search Spotify if enabled
|
||||||
getYouTubeSuggestionsFor(query),
|
const spotifySuggestionPromise = spotify === undefined
|
||||||
spotify.search(query, ['track', 'album'], {limit: 5}),
|
? undefined
|
||||||
]);
|
: spotify.search(query, ['album', 'track'], {limit});
|
||||||
|
|
||||||
|
const youtubeSuggestions = await getYouTubeSuggestionsFor(query);
|
||||||
|
|
||||||
const totalYouTubeResults = youtubeSuggestions.length;
|
const totalYouTubeResults = youtubeSuggestions.length;
|
||||||
|
const numOfYouTubeSuggestions = Math.min(limit, totalYouTubeResults);
|
||||||
|
|
||||||
const spotifyAlbums = filterDuplicates(spotifyResults.body.albums?.items ?? []);
|
let suggestions: APIApplicationCommandOptionChoice[] = [];
|
||||||
const spotifyTracks = filterDuplicates(spotifyResults.body.tracks?.items ?? []);
|
|
||||||
|
|
||||||
const totalSpotifyResults = spotifyAlbums.length + spotifyTracks.length;
|
|
||||||
|
|
||||||
// Number of results for each source should be roughly the same.
|
|
||||||
// If we don't have enough Spotify suggestions, prioritize YouTube results.
|
|
||||||
const maxSpotifySuggestions = Math.floor(limit / 2);
|
|
||||||
const numOfSpotifySuggestions = Math.min(maxSpotifySuggestions, totalSpotifyResults);
|
|
||||||
|
|
||||||
const maxYouTubeSuggestions = limit - numOfSpotifySuggestions;
|
|
||||||
const numOfYouTubeSuggestions = Math.min(maxYouTubeSuggestions, totalYouTubeResults);
|
|
||||||
|
|
||||||
const suggestions: APIApplicationCommandOptionChoice[] = [];
|
|
||||||
|
|
||||||
suggestions.push(
|
suggestions.push(
|
||||||
...youtubeSuggestions
|
...youtubeSuggestions
|
||||||
|
@ -46,10 +36,26 @@ const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: Spotif
|
||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
|
|
||||||
|
if (spotify !== undefined && spotifySuggestionPromise !== undefined) {
|
||||||
|
const spotifyResponse = (await spotifySuggestionPromise).body;
|
||||||
|
const spotifyAlbums = filterDuplicates(spotifyResponse.albums?.items ?? []);
|
||||||
|
const spotifyTracks = filterDuplicates(spotifyResponse.tracks?.items ?? []);
|
||||||
|
|
||||||
|
const totalSpotifyResults = spotifyAlbums.length + spotifyTracks.length;
|
||||||
|
|
||||||
|
// Number of results for each source should be roughly the same.
|
||||||
|
// If we don't have enough Spotify suggestions, prioritize YouTube results.
|
||||||
|
const maxSpotifySuggestions = Math.floor(limit / 2);
|
||||||
|
const numOfSpotifySuggestions = Math.min(maxSpotifySuggestions, totalSpotifyResults);
|
||||||
|
|
||||||
const maxSpotifyAlbums = Math.floor(numOfSpotifySuggestions / 2);
|
const maxSpotifyAlbums = Math.floor(numOfSpotifySuggestions / 2);
|
||||||
const numOfSpotifyAlbums = Math.min(maxSpotifyAlbums, spotifyResults.body.albums?.items.length ?? 0);
|
const numOfSpotifyAlbums = Math.min(maxSpotifyAlbums, spotifyResponse.albums?.items.length ?? 0);
|
||||||
const maxSpotifyTracks = numOfSpotifySuggestions - numOfSpotifyAlbums;
|
const maxSpotifyTracks = numOfSpotifySuggestions - numOfSpotifyAlbums;
|
||||||
|
|
||||||
|
// Make room for spotify results
|
||||||
|
const maxYouTubeSuggestions = limit - numOfSpotifySuggestions;
|
||||||
|
suggestions = suggestions.slice(0, maxYouTubeSuggestions);
|
||||||
|
|
||||||
suggestions.push(
|
suggestions.push(
|
||||||
...spotifyAlbums.slice(0, maxSpotifyAlbums).map(album => ({
|
...spotifyAlbums.slice(0, maxSpotifyAlbums).map(album => ({
|
||||||
name: `Spotify: 💿 ${album.name}${album.artists.length > 0 ? ` - ${album.artists[0].name}` : ''}`,
|
name: `Spotify: 💿 ${album.name}${album.artists.length > 0 ? ` - ${album.artists[0].name}` : ''}`,
|
||||||
|
@ -63,6 +69,7 @@ const getYouTubeAndSpotifySuggestionsFor = async (query: string, spotify: Spotif
|
||||||
value: `spotify:track:${track.id}`,
|
value: `spotify:track:${track.id}`,
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return suggestions;
|
return suggestions;
|
||||||
};
|
};
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue