Compare commits

...

14 Commits

Author SHA1 Message Date
Thibaut Broggi 7682aa7aff
Complete documentation for class ResourceManager 2021-03-03 01:34:57 +01:00
Thibaut Broggi 67392e9862
Fix !remove function
It now works properly if we try to remove a song that's before the current one
The acknowledgment message is now displayed properly
2021-03-03 01:16:47 +01:00
Thibaut Broggi 0df2420e83
Add documentation for some getters of the Playlist class 2021-03-03 01:09:44 +01:00
Thibaut Broggi 731e19a4e1
Add documentation about class Manager 2021-03-03 01:05:03 +01:00
Arthur POULET 5f63bcac25 Merge branch 'feature/stop' 2021-03-02 23:34:01 +01:00
Arthur POULET 84ed8325bd Disable !stop for now as we still don't have .pause() on ytdl streams 2021-03-02 23:32:58 +01:00
Thibaut Broggi 03d3cd4f40
Add a reaction on a successful !play 2021-03-02 23:14:55 +01:00
Thibaut Broggi cc79cfa08e
Don't add invalid tracks to the playlist 2021-03-02 23:08:40 +01:00
Arthur POULET 568bf0ee3e Merge branch 'master' into feature/stop 2021-03-02 23:04:54 +01:00
Arthur POULET 56415e14db Improve destroy stream so it replaces is_playing 2021-03-02 23:03:46 +01:00
Thibaut Broggi 2432a7a18b
Add !goto command 2021-03-02 23:03:09 +01:00
Arthur POULET fb8e881d40 Add !stop implementation and free stream when changing current 2021-03-02 22:53:37 +01:00
Thibaut Broggi c9369b1fb3
Merge commands !play and !quick
close #1
2021-03-02 22:47:50 +01:00
Thibaut Broggi 93587129ee
Create a Manager class, which all the manager classes extends 2021-03-02 21:55:40 +01:00
8 changed files with 152 additions and 57 deletions

View File

@ -4,6 +4,8 @@
"commands": {
"p": { "target": "player", "action": "add" },
"play": { "target": "player", "action": "add" },
"q": { "target": "player", "action": "add" },
"quick": { "target": "player", "action": "add" },
"remove": { "target": "player", "action": "remove" },
@ -18,6 +20,7 @@
"next": { "target": "player", "action": "next" },
"previous": { "target": "player", "action": "prev" },
"goto": { "target": "player", "action": "goto" },
"list": { "target": "player", "action": "list" },
@ -32,9 +35,6 @@
"mvpconfig": { "target": "mvp", "action": "config" },
"mvpversion" : { "target": "mvp", "action": "version"},
"q": { "target": "resource", "action": "quick_search" },
"quick": { "target": "resource", "action": "quick_search" },
"s": { "target": "resource", "action": "search" },
"search": { "target": "resource", "action": "search" }
}

View File

@ -37,10 +37,10 @@ class GuildsManager {
if (!this.#guilds[guild_id]) {
const current_config = config[message.guild.id] || config['default']
this.#guilds[guild_id] = {
input: new InputManager(this, current_config),
player: new PlayerManager(this),
resource: new ResourceManager(this),
playlists: await new PlaylistsManager(this),
input: new InputManager(this, guild_id, current_config),
player: new PlayerManager(this, guild_id),
resource: new ResourceManager(this, guild_id),
playlists: await new PlaylistsManager(this, guild_id),
}
}
const guild_action = await this.#guilds[guild_id].input.handle_message(message)

View File

@ -1,3 +1,4 @@
const { Manager } = require('./manager')
const { Playlist } = require('./playlist')
const { GuildAction } = require('./guild_action')
@ -23,15 +24,15 @@ const ONE_SECOND = 1000
* are met.
*
* @class
* @extends Manager
*/
class InputManager {
class InputManager extends Manager {
#config
#triggers
#gmanager
constructor(gmanager, config) {
constructor(gmanager, guild_id, config) {
super(...arguments)
this.#config = config
this.#gmanager = gmanager
this.#triggers = []
}

28
src/manager.js Normal file
View File

@ -0,0 +1,28 @@
/**
* An abstract class that is meant to be extended by actual managers.<br />
* Managers are classes that have actions, which are used by the {@link GuildsManager} according to the configuration file.
*/
class Manager {
#gmanager
#guild_id
/**
* @param {GuildsManager} gmanager An instance of GuildsManager
* @param {string} guild_id The id of the Discord guild this managers is working on
*/
constructor(gmanager, guild_id) {
this.#gmanager = gmanager
this.#guild_id = guild_id
}
/**
* Retrieves another manager related to the same Discord guild
* @param {"input"|"player"|"playlist"|"resource"} name The name of the manager to retrieve
* @returns {InputManager|PlayerManager|PlaylistsManager|ResourceManager} The associated manager instance
*/
get_manager(name) {
return this.#gmanager.get_manager(this.#guild_id, name)
}
}
module.exports = { Manager }

View File

@ -1,5 +1,6 @@
const ytdl = require('ytdl-core')
const { Manager } = require('./manager')
const { Playlist } = require('./playlist');
const LOOP_VALUES = {
full: 2,
@ -23,14 +24,14 @@ const LOOP_NAMES = {
/**
* @class
* @extends Manager
*/
class PlayerManager {
class PlayerManager extends Manager {
#voice
#dispatcher
#playlist
#gmanager
#is_playing
#loop
#current_stream
get_playlist() { return this.#playlist }
set_playlist(playlist) {
@ -38,15 +39,26 @@ class PlayerManager {
return this
}
constructor(gmanager) {
this.#gmanager = gmanager
constructor() {
super(...arguments)
this.#voice = null
this.#dispatcher = null
this.#playlist = new Playlist()
this.#is_playing = false
this.#current_stream = null
this.#loop = 2
}
/**
* @private
* @description ensure that the current stream is removed
*/
#destroyStream() {
if (this.#current_stream) {
this.#current_stream.destroy()
this.#current_stream = null
}
}
// https://www.youtube.com/watch?v=Yom8nNqmxvQ
/**
* Stream the given track from YouTube
@ -55,9 +67,10 @@ class PlayerManager {
async stream(track) {
if (!track) return this
track.update_play_count()
this.#is_playing = true
const stream = ytdl(track.get_url(), { filter: 'audioonly' })
this.#dispatcher = this.#voice.play(stream)
this.#destroyStream()
this.#current_stream = stream
this.#dispatcher.on('finish', () => {
if (this.#loop === 1) {
this.stream(track)
@ -65,11 +78,21 @@ class PlayerManager {
this.next()
}
})
return this;
return this
}
is_connected(channel) {}
/**
* @returns true if this is connected to a voice chan
*/
is_connected() {
return Boolean(this.#voice)
}
/**
* Connects to a voice channel and ensure basic configuration of self (deaf etc.)
*
* @param {Discord.VoiceChannel} channel to be joined
*/
async connect(channel) {
this.#voice = await channel.join()
this.#voice.voice.setSelfDeaf(true)
@ -78,7 +101,7 @@ class PlayerManager {
async leave({ message, params }) {
if (this.#voice) {
this.#voice.channel.leave()
this.#is_playing = false
this.#destroyStream()
this.#playlist = new Playlist()
}
}
@ -90,7 +113,7 @@ class PlayerManager {
confirm_msg.react("⏏️")
confirm_msg.awaitReactions(async (r, u) => {
if (r.emoji.name === "💾" && u.id !== confirm_msg.author.id) {
const current_playlist = this.#gmanager.get_manager(message, 'playlists')
const current_playlist = this.get_manager('playlists')
if (await current_playlist.register({ message, params: [] })) {
this.#clear_confirmed({ message, params })
}
@ -103,7 +126,7 @@ class PlayerManager {
}
async #clear_confirmed({ message, params }) {
this.#is_playing = false
this.#destroyStream()
this.#playlist = new Playlist()
}
@ -142,14 +165,17 @@ class PlayerManager {
} else {
await this.connect(message.member.voice.channel)
if (params[0]) {
if (!/^http/.test(params[0])) {
message.channel.send(':warning: !play only supports url now, please use !quick for quick search')
const track = /^https?:\/\//.test(params[0])
? await this.get_manager('resource').get_metadata(params[0])
: (await this.get_manager('resource').get_search_results(params))[0]
if (!track) {
message.channel.send(':warning: Something went wrong. That\'s not supposed to happen...')
} else {
const track = await this.#gmanager.get_manager(message.guild.id, 'resource').get_metadata(params[0])
message.react('👌')
this.#playlist.push(track)
}
}
if (!this.#is_playing) {
if (!this.#current_stream) {
const track = this.#playlist.get_current_track()
this.stream(track)
}
@ -166,7 +192,7 @@ class PlayerManager {
if (!isNaN(id_to_remove)) {
const track = this.#playlist.get_track_by_index(index_to_remove)
if (track && this.#playlist.delete(index_to_remove)) {
message.channel.send(`:white_check_mark: The track ${id_to_remove} \`${track.full_title}\` has been removed`)
message.channel.send(`:white_check_mark: The track ${id_to_remove} \`${track.get_full_title()}\` has been removed`)
} else {
message.channel.send(`:warning: The track ${id_to_remove} has not been removed or found`)
}
@ -176,18 +202,27 @@ class PlayerManager {
async next() {
const track = this.#playlist.next({ loop: this.#loop }).get_current_track();
if (track) {
this.stream(track)
await this.stream(track)
} else {
this.#is_playing = false;
this.#destroyStream()
}
}
async prev() {
const track = this.#playlist.previous({ loop: this.#loop }).get_current_track();
if (track) {
this.stream(track)
await this.stream(track)
} else {
this.#is_playing = false;
this.#destroyStream()
}
}
async goto({ message, params }) {
if (this.#playlist.goto(parseInt(params[0]))) {
this.stream(this.#playlist.get_current_track())
message.react('👌')
} else {
message.channel.send(`:warning: Could not find track at index \`${params}\`.`)
}
}

View File

@ -84,10 +84,25 @@ class Playlist {
return this
}
goto(idx) {
if (this.#tracks[idx - 1] == null) {
return false
}
this.#current_index = idx - 1
return true
}
/**
* @returns {Track|null} The track that is currenly played, or <code>null</code> if it doesn't exist
*/
get_current_track() {
return this.#tracks[this.#current_index] ?? null
}
/**
* @param {number} track_index The index of the track to be retrieved
* @returns {Track|null} The track that is looked for, or <code>null</code> if it doesn't exist
*/
get_track_by_index(track_index) {
return this.#tracks[track_index] ?? null
}
@ -111,7 +126,12 @@ class Playlist {
* @returns {boolean} <code>true</code> if the element was successfully removed, <code>false</code> otherwise
*/
delete(track_index) {
if (track_index >= this.#tracks.length) return false
if (track_index >= this.#tracks.length) {
return false
}
if (track_index < this.#current_index) {
this.#current_index -= 1
}
delete this.#tracks[track_index]
this.#tracks = this.#tracks.filter(Boolean)
this.#touched = true

View File

@ -1,23 +1,26 @@
const fs = require('fs').promises
const ytdl = require('ytdl-core')
const { Manager } = require('./manager')
const { Playlist } = require('./playlist');
const { youtube_instance } = require('../src/youtube');
class PlaylistsManager {
/**
* @extends Manager
*/
class PlaylistsManager extends Manager {
#playlists
#gmanager
#filepath
constructor(gmanager, { filepath = "playlists_manager.db", data = null } = {}) {
constructor(gmanager, guild_id, { filepath = "playlists_manager.db", data = null } = {}) {
return (async () => {
super(...arguments)
const playlists = data || await PlaylistsManager.readFile(filepath)
Object.entries(playlists).forEach(([title, tracks]) => {
playlists[title] = new Playlist({ tracks, name: title })
})
this.#playlists = playlists
this.#filepath = filepath
this.#gmanager = gmanager
return this
})()
@ -37,7 +40,7 @@ class PlaylistsManager {
}
async register({ message, params }) {
const player = this.#gmanager.get_manager(message, 'player')
const player = this.get_manager('player')
if (params[0] || player.get_playlist().is_named()) {
const playlist_title = params[0] || player.get_playlist().get_name()
this.#playlists[playlist_title] = player.get_playlist().clone()
@ -52,7 +55,7 @@ class PlaylistsManager {
}
async load({ message, params }) {
const player = this.#gmanager.get_manager(message, 'player')
const player = this.get_manager('player')
const playlist_title = params[0] // TODO handle long names with spaces...
const named_playlist = { title: playlist_title, playlist: this.#playlists[playlist_title] }
// const playlist_id = params[0]

View File

@ -1,26 +1,38 @@
const { Manager } = require('./manager')
const { GuildAction } = require('./guild_action')
const { Track } = require('./track')
const { youtube_instance } = require("./youtube")
/**
* @class
* The {@link Manager} that manage resources. Its main goal is to search resources and get their metadata.<br />
* Note that it only works for YouTube videos for now.
* @extends Manager
*/
class ResourceManager {
#gmanager
class ResourceManager extends Manager {
#awaiting_answers
constructor(gmanager) {
this.#gmanager = gmanager
constructor() {
super(...arguments)
this.#awaiting_answers = []
}
/**
* Performs a research, depending on the search terms it's been asked for
* @param {string|string[]} query The search terms
* @returns {Track[]} An array of objects representing the search results.
*/
async get_search_results(query) {
if (query instanceof Array)
query = query.join(' ')
return await youtube_instance.search_track(query)
}
/**
* Do a research and send the search results back to the Discord channel it's been asked for
* @param {GuildAction}
* @return {Track[]} An array of objects representing the search results.
*/
async search({ message, params }) {
const tracks = await youtube_instance.search_track(params.join(' '))
const tracks = await this.get_search_results(params)
if (tracks.length === 0) {
message.channel.send(':warning: Something went wrong. Please try again')
} else {
@ -28,7 +40,7 @@ class ResourceManager {
.slice(0, 10)
.map((track, i) => (i + 1) + ' ' + track)
.join('\n')
const input_manager = this.#gmanager.get_manager(message.guild.id, 'input')
const input_manager = this.get_manager('input')
// TODO: 2000 chars limit
// TODO: find a better syntaxic coloration than js
const own_message = await message.channel.send('```js\n' + text_res + '```')
@ -50,9 +62,12 @@ class ResourceManager {
})
input_manager.add_trigger(trigger)
}
return tracks
}
/**
* Choose a track given its id in a search result. Note that this only works right after a call to the {@link ResourceManager#search} action.
* @param {GuildAction}
*/
async search_confirm({ message, params }) {
// TODO: update this so that it can be more relient on the Trigger received
const id = parseInt(message.content)
@ -66,20 +81,13 @@ class ResourceManager {
} else {
// TODO: calling the add method is a bit ugly, we can probably do better...
const action = new GuildAction({ message, params: [answer.search_results[id - 1].get_url()] })
this.#gmanager.get_manager(message.guild.id, 'player').add(action)
this.get_manager('player').add(action)
message.react('👌')
}
}
async quick_search({ message, params }) {
const tracks = await youtube_instance.search_track(params.join(' '))
const action = new GuildAction({ message, params: [tracks[0].get_url()] })
this.#gmanager.get_manager(message.guild.id, 'player').add(action)
}
/**
* Given the url of a song, get is metadata. <br />
* Note that it only works for YouTube videos for now.
* Given the url of a song, get its metadata.
* @param {string} url
* @returns {Track}
*/