Skip to content
This repository has been archived by the owner on May 16, 2022. It is now read-only.

Commit

Permalink
Some standard fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
pedrofracassi committed Apr 29, 2020
1 parent eedcb4a commit 053f9ae
Show file tree
Hide file tree
Showing 11 changed files with 1,009 additions and 1,010 deletions.
18 changes: 9 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ Sentry.init({ dsn: process.env.SENTRY_DSN })
const MusicManager = require('./structures/MusicManager')
const manager = new MusicManager()
manager.connect().then(async () => {
const [ song ] = await manager.getSongs('ytsearch:30 sec video')
// const player = await manager.lavalink.join({
// guild: '445203868624748555',
// channel: '701928171519344801',
// node: '1'
// }, { selfdeaf: true })
const [song] = await manager.getSongs('ytsearch:30 sec video')
// const player = await manager.lavalink.join({
// guild: '445203868624748555',
// channel: '701928171519344801',
// node: '1'
// }, { selfdeaf: true })

console.log(song)
console.log(song)

// await player.play(song)
// player.once("error", error => console.error(error))
// await player.play(song)
// player.once("error", error => console.error(error))
})
165 changes: 82 additions & 83 deletions src/structures/MusicManager.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const Client = require('./discord/Client')
const LavacordManager = require('./lavacord/Manager')
const MusicPlayer = require('./lavacord/MusicPlayer')
const Song = require('./lavacord/Song')
const APIController = require('./http/APIController')

const fetch = require('node-fetch')
Expand All @@ -13,89 +12,89 @@ const dnsLookup = promisify(lookup)

// TODO: Create SongProvider class
class MusicManager {
constructor (clientOptions, lavacordOptions = {}) {
this.clientOptions = clientOptions || {}
this.lavacordOptions = Object.assign({
Player: MusicPlayer
}, lavacordOptions)

this.handleClientError = this.handleClientError.bind(this)
}

connect () {
return this.connectClient()
.then(() => this.connectLavalink())
.then(() => this.startHTTPServer())
constructor (clientOptions, lavacordOptions = {}) {
this.clientOptions = clientOptions || {}
this.lavacordOptions = Object.assign({
Player: MusicPlayer
}, lavacordOptions)

this.handleClientError = this.handleClientError.bind(this)
}

connect () {
return this.connectClient()
.then(() => this.connectLavalink())
.then(() => this.startHTTPServer())
}

// Discord
connectClient () {
const CLUSTER_ID = process.env.INDEX_CLUSTER_ID_FROM_ONE ? parseInt(process.env.CLUSTER_ID) - 1 : parseInt(process.env.CLUSTER_ID)
const maxShards = parseInt(process.env.MAX_SHARDS)
const firstShardID = maxShards ? 0 : CLUSTER_ID * parseInt(process.env.SHARDS_PER_CLUSTER)
const lastShardID = maxShards ? maxShards - 1 : ((CLUSTER_ID + 1) * parseInt(process.env.SHARDS_PER_CLUSTER)) - 1

this.client = new Client(process.env.DISCORD_TOKEN, Object.assign({
compress: true,
userId: process.env.USER_ID,
firstShardID,
lastShardID,
maxShards: maxShards || parseInt(process.env.SHARDS_PER_CLUSTER) * parseInt(process.env.MAX_CLUSTERS)
}, this.clientOptions))

this.client.on('error', this.handleClientError)

return this.client.connect()
}

handleClientError (...args) {
console.error('CLIENT', ...args)
}

// Lavalink
async connectLavalink () {
const nodes = await this.lavalinkNodes()
this.lavalink = new LavacordManager(this.client, nodes, this.lavacordOptions)
return this.lavalink.connect()
}

async lavalinkNodes () {
let lavalinkNodes
try {
lavalinkNodes = require.main.require('../lavalink_nodes.json')
} catch (err) {}

if (!lavalinkNodes) {
const addresses = await dnsLookup('tasks.lavalink', { all: true })
lavalinkNodes = addresses.map((host, i) => ({
id: i++,
host,
port: process.env.LAVALINK_PORT,
password: process.env.LAVALINK_PASSWORD
}))
}

// Discord
connectClient () {
const CLUSTER_ID = process.env.INDEX_CLUSTER_ID_FROM_ONE ? parseInt(process.env.CLUSTER_ID) - 1 : parseInt(process.env.CLUSTER_ID)
const maxShards = parseInt(process.env.MAX_SHARDS)
const firstShardID = maxShards ? 0 : CLUSTER_ID * parseInt(process.env.SHARDS_PER_CLUSTER)
const lastShardID = maxShards ? maxShards - 1 : ((CLUSTER_ID + 1) * parseInt(process.env.SHARDS_PER_CLUSTER)) - 1

this.client = new Client(process.env.DISCORD_TOKEN, Object.assign({
compress: true,
userId: process.env.USER_ID,
firstShardID,
lastShardID,
maxShards: maxShards || parseInt(process.env.SHARDS_PER_CLUSTER) * parseInt(process.env.MAX_CLUSTERS)
}, this.clientOptions))

this.client.on('error', this.handleClientError)

return this.client.connect()
}

handleClientError (...args) {
console.error('CLIENT', ...args)
}

// Lavalink
async connectLavalink () {
const nodes = await this.lavalinkNodes()
this.lavalink = new LavacordManager(this.client, nodes, this.lavacordOptions)
return this.lavalink.connect()
}

async lavalinkNodes () {
let lavalinkNodes
try {
lavalinkNodes = require.main.require('../lavalink_nodes.json')
} catch (err) {}

if (!lavalinkNodes) {
const addresses = await dnsLookup('tasks.lavalink', { all: true })
lavalinkNodes = addresses.map((host, i) => ({
id: i++,
host,
port: process.env.LAVALINK_PORT,
password: process.env.LAVALINK_PASSWORD
}))
}

return lavalinkNodes
}

getSongs (search) {
const [ node ] = this.lavalink.idealNodes
const params = new URLSearchParams()
params.append('identifier', search)
return fetch(`http://${node.host}:${node.port}/loadtracks?${params}`, { headers: { Authorization: node.password } })
.then(res => res.json())
.then(data => data.tracks)
.catch(err => {
console.error(err)
return []
})
}

// HTTP
startHTTPServer () {
this.api = new APIController(this)
return this.api.start(process.env.PORT)
}
return lavalinkNodes
}

getSongs (search) {
const [node] = this.lavalink.idealNodes
const params = new URLSearchParams()
params.append('identifier', search)
return fetch(`http://${node.host}:${node.port}/loadtracks?${params}`, { headers: { Authorization: node.password } })
.then(res => res.json())
.then(data => data.tracks)
.catch(err => {
console.error(err)
return []
})
}

// HTTP
startHTTPServer () {
this.api = new APIController(this)
return this.api.start(process.env.PORT)
}
}

module.exports = MusicManager
module.exports = MusicManager
94 changes: 47 additions & 47 deletions src/structures/discord/Bucket.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
class Bucket {
constructor(tokenLimit, interval, options = {}) {
this.tokenLimit = tokenLimit
this.interval = interval
this.latencyRef = options.latencyRef || { latency: 0 }
this.lastReset = this.tokens = this.lastSend = 0
this.reservedTokens = options.reservedTokens || 0
this._queue = []
}
constructor (tokenLimit, interval, options = {}) {
this.tokenLimit = tokenLimit
this.interval = interval
this.latencyRef = options.latencyRef || { latency: 0 }
this.lastReset = this.tokens = this.lastSend = 0
this.reservedTokens = options.reservedTokens || 0
this._queue = []
}

queue(func, priority=false) {
if(priority) {
this._queue.unshift({func, priority})
} else {
this._queue.push({func, priority})
}
this.check()
queue (func, priority = false) {
if (priority) {
this._queue.unshift({ func, priority })
} else {
this._queue.push({ func, priority })
}
this.check()
}

check() {
if(this.timeout || this._queue.length === 0) {
return
}
if(this.lastReset + this.interval + this.tokenLimit * this.latencyRef.latency < Date.now()) {
this.lastReset = Date.now()
this.tokens = Math.max(0, this.tokens - this.tokenLimit)
}
check () {
if (this.timeout || this._queue.length === 0) {
return
}
if (this.lastReset + this.interval + this.tokenLimit * this.latencyRef.latency < Date.now()) {
this.lastReset = Date.now()
this.tokens = Math.max(0, this.tokens - this.tokenLimit)
}

let val;
const tokensAvailable = this.tokens < this.tokenLimit
const unreservedTokensAvailable = this.tokens < (this.tokenLimit - this.reservedTokens)
while(this._queue.length > 0 && (unreservedTokensAvailable || (tokensAvailable && this._queue[0].priority))) {
this.tokens++
const item = this._queue.shift()
val = this.latencyRef.latency - Date.now() + this.lastSend
if(this.latencyRef.latency === 0 || val <= 0) {
item.func()
this.lastSend = Date.now()
} else {
setTimeout(() => {
item.func()
}, val)
this.lastSend = Date.now() + val
}
}
let val
const tokensAvailable = this.tokens < this.tokenLimit
const unreservedTokensAvailable = this.tokens < (this.tokenLimit - this.reservedTokens)
while (this._queue.length > 0 && (unreservedTokensAvailable || (tokensAvailable && this._queue[0].priority))) {
this.tokens++
const item = this._queue.shift()
val = this.latencyRef.latency - Date.now() + this.lastSend
if (this.latencyRef.latency === 0 || val <= 0) {
item.func()
this.lastSend = Date.now()
} else {
setTimeout(() => {
item.func()
}, val)
this.lastSend = Date.now() + val
}
}

if(this._queue.length > 0 && !this.timeout) {
this.timeout = setTimeout(() => {
this.timeout = null
this.check()
}, this.tokens < this.tokenLimit ? this.latencyRef.latency : Math.max(0, this.lastReset + this.interval + this.tokenLimit * this.latencyRef.latency - Date.now()))
}
if (this._queue.length > 0 && !this.timeout) {
this.timeout = setTimeout(() => {
this.timeout = null
this.check()
}, this.tokens < this.tokenLimit ? this.latencyRef.latency : Math.max(0, this.lastReset + this.interval + this.tokenLimit * this.latencyRef.latency - Date.now()))
}
}
}

module.exports = Bucket
module.exports = Bucket
Loading

0 comments on commit 053f9ae

Please sign in to comment.