diff options
| author | Bobby <[email protected]> | 2024-11-06 09:42:25 -0500 |
|---|---|---|
| committer | GitHub <[email protected]> | 2024-11-06 09:42:25 -0500 |
| commit | d92fd2a29796c9c5d6ddeb9718bf6fcd6ee5958a (patch) | |
| tree | 81961cc995661448794669617f1ed439cbe84a3d /src/services | |
| parent | b605bf220859acd767533e0ab9436ced771bb8e2 (diff) | |
| parent | 716d6d9f4f2cd1a6872e463e9877203a259478a3 (diff) | |
| download | muse-master.tar.xz muse-master.zip | |
Diffstat (limited to 'src/services')
| -rw-r--r-- | src/services/add-query-to-queue.ts | 70 | ||||
| -rw-r--r-- | src/services/config.ts | 6 | ||||
| -rw-r--r-- | src/services/get-songs.ts | 102 | ||||
| -rw-r--r-- | src/services/player.ts | 66 | ||||
| -rw-r--r-- | src/services/youtube-api.ts | 2 |
5 files changed, 165 insertions, 81 deletions
diff --git a/src/services/add-query-to-queue.ts b/src/services/add-query-to-queue.ts index 401ad90..95e16ff 100644 --- a/src/services/add-query-to-queue.ts +++ b/src/services/add-query-to-queue.ts @@ -1,6 +1,5 @@ /* eslint-disable complexity */ import {ChatInputCommandInteraction, GuildMember} from 'discord.js'; -import {URL} from 'node:url'; import {inject, injectable} from 'inversify'; import shuffle from 'array-shuffle'; import {TYPES} from '../types.js'; @@ -60,74 +59,7 @@ export default class AddQueryToQueue { await interaction.deferReply({ephemeral: queueAddResponseEphemeral}); - let 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.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'); - } - } + let [newSongs, extraMsg] = await this.getSongs.getSongs(query, playlistLimit, shouldSplitChapters); if (newSongs.length === 0) { throw new Error('no songs found'); diff --git a/src/services/config.ts b/src/services/config.ts index b6b9aea..3941a3c 100644 --- a/src/services/config.ts +++ b/src/services/config.ts @@ -5,15 +5,15 @@ import path from 'path'; import xbytes from 'xbytes'; import {ConditionalKeys} from 'type-fest'; import {ActivityType, PresenceStatusData} from 'discord.js'; -dotenv.config(); +dotenv.config({path: process.env.ENV_FILE ?? path.resolve(process.cwd(), '.env')}); export const DATA_DIR = path.resolve(process.env.DATA_DIR ? process.env.DATA_DIR : './data'); const CONFIG_MAP = { DISCORD_TOKEN: process.env.DISCORD_TOKEN, YOUTUBE_API_KEY: process.env.YOUTUBE_API_KEY, - SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID, - SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET, + SPOTIFY_CLIENT_ID: process.env.SPOTIFY_CLIENT_ID ?? '', + SPOTIFY_CLIENT_SECRET: process.env.SPOTIFY_CLIENT_SECRET ?? '', REGISTER_COMMANDS_ON_BOT: process.env.REGISTER_COMMANDS_ON_BOT === 'true', DATA_DIR, CACHE_DIR: path.join(DATA_DIR, 'cache'), diff --git a/src/services/get-songs.ts b/src/services/get-songs.ts index b957734..c48d87d 100644 --- a/src/services/get-songs.ts +++ b/src/services/get-songs.ts @@ -1,34 +1,120 @@ -import {inject, injectable} from 'inversify'; +import {inject, injectable, optional} from 'inversify'; import * as spotifyURI from 'spotify-uri'; import {SongMetadata, QueuedPlaylist, MediaSource} from './player.js'; import {TYPES} from '../types.js'; import ffmpeg from 'fluent-ffmpeg'; import YoutubeAPI from './youtube-api.js'; import SpotifyAPI, {SpotifyTrack} from './spotify-api.js'; +import {URL} from 'node:url'; @injectable() export default class { 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.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); } - async youtubeVideo(url: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> { + private async youtubeVideo(url: string, shouldSplitChapters: boolean): Promise<SongMetadata[]> { 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); } - 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); 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) => { ffmpeg(url).ffprobe((err, _) => { if (err) { diff --git a/src/services/player.ts b/src/services/player.ts index 5e284a6..b833022 100644 --- a/src/services/player.ts +++ b/src/services/player.ts @@ -20,6 +20,7 @@ import FileCacheProvider from './file-cache.js'; import debug from '../utils/debug.js'; import {getGuildSettings} from '../utils/get-guild-settings.js'; import {buildPlayingMessageEmbed} from '../utils/build-embed.js'; +import {Setting} from '@prisma/client'; export enum MediaSource { Youtube, @@ -82,6 +83,8 @@ export default class { private readonly fileCache: FileCacheProvider; private disconnectTimer: NodeJS.Timeout | null = null; + private readonly channelToSpeakingUsers: Map<string, Set<string>> = new Map(); + constructor(fileCache: FileCacheProvider, guildId: string) { this.fileCache = fileCache; this.guildId = guildId; @@ -96,9 +99,12 @@ export default class { this.voiceConnection = joinVoiceChannel({ channelId: channel.id, guildId: channel.guild.id, + selfDeaf: false, adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator, }); + const guildSettings = await getGuildSettings(this.guildId); + // Workaround to disable keepAlive this.voiceConnection.on('stateChange', (oldState, newState) => { /* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */ @@ -115,6 +121,9 @@ export default class { /* eslint-enable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call */ this.currentChannel = channel; + if (newState.status === VoiceConnectionStatus.Ready) { + this.registerVoiceActivityListener(guildSettings); + } }); } @@ -302,6 +311,63 @@ export default class { } } + registerVoiceActivityListener(guildSettings: Setting) { + const {turnDownVolumeWhenPeopleSpeak, turnDownVolumeWhenPeopleSpeakTarget} = guildSettings; + if (!turnDownVolumeWhenPeopleSpeak || !this.voiceConnection) { + return; + } + + this.voiceConnection.receiver.speaking.on('start', (userId: string) => { + if (!this.currentChannel) { + return; + } + + const member = this.currentChannel.members.get(userId); + const channelId = this.currentChannel?.id; + + if (member) { + if (!this.channelToSpeakingUsers.has(channelId)) { + this.channelToSpeakingUsers.set(channelId, new Set()); + } + + this.channelToSpeakingUsers.get(channelId)?.add(member.id); + } + + this.suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget); + }); + + this.voiceConnection.receiver.speaking.on('end', (userId: string) => { + if (!this.currentChannel) { + return; + } + + const member = this.currentChannel.members.get(userId); + const channelId = this.currentChannel.id; + if (member) { + if (!this.channelToSpeakingUsers.has(channelId)) { + this.channelToSpeakingUsers.set(channelId, new Set()); + } + + this.channelToSpeakingUsers.get(channelId)?.delete(member.id); + } + + this.suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget); + }); + } + + suppressVoiceWhenPeopleAreSpeaking(turnDownVolumeWhenPeopleSpeakTarget: number): void { + if (!this.currentChannel) { + return; + } + + const speakingUsers = this.channelToSpeakingUsers.get(this.currentChannel.id); + if (speakingUsers && speakingUsers.size > 0) { + this.setVolume(turnDownVolumeWhenPeopleSpeakTarget); + } else { + this.setVolume(this.defaultVolume); + } + } + canGoForward(skip: number) { return (this.queuePosition + skip - 1) < this.queue.length; } diff --git a/src/services/youtube-api.ts b/src/services/youtube-api.ts index 143033a..216a2c0 100644 --- a/src/services/youtube-api.ts +++ b/src/services/youtube-api.ts @@ -95,7 +95,7 @@ export default class { } if (!firstVideo) { - throw new Error('No video found.'); + return []; } return this.getVideo(firstVideo.url, shouldSplitChapters); |
