Skip to content

Commit

Permalink
Convert clients to EventEmitter, record all guilds in sharding amanger
Browse files Browse the repository at this point in the history
  • Loading branch information
synzen committed Dec 28, 2018
1 parent 0f5b96f commit d300b52
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
9 changes: 6 additions & 3 deletions structs/Client.js
Expand Up @@ -11,6 +11,7 @@ const dbOps = require('../util/dbOps.js')
const configCheck = require('../util/configCheck.js')
const connectDb = require('../rss/db/connect.js')
const ClientSharded = require('./ClientSharded.js')
const EventEmitter = require('events')
const DISABLED_EVENTS = ['TYPING_START', 'MESSAGE_DELETE', 'MESSAGE_UPDATE', 'PRESENCE_UPDATE', 'VOICE_STATE_UPDATE', 'VOICE_SERVER_UPDATE', 'USER_NOTE_UPDATE', 'CHANNEL_PINS_UPDATE']
const SHARDED_OPTIONS = { respawn: false }
const STATES = {
Expand Down Expand Up @@ -62,8 +63,9 @@ function readSchedulesFromFile () {
}
}

class Client {
class Client extends EventEmitter {
constructor (configOverrides, customSchedules) {
super()
// Override from file first
try {
const fileConfigOverride = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'settings', 'configOverride.json')))
Expand All @@ -89,7 +91,7 @@ class Client {
this.state = STATES.STOPPED
}

login (token) {
login (token, noChildren) {
if (this.bot) return log.general.error('Cannot login when already logged in')
if (token instanceof Discord.Client) return this._defineBot(token) // May also be the client
else if (token instanceof Discord.ShardingManager) return new ClientSharded(token)
Expand All @@ -98,7 +100,7 @@ class Client {
client.login(token)
.then(tok => this._defineBot(client))
.catch(err => {
if (err.message.includes('too many guilds')) return new ClientSharded(new Discord.ShardingManager('./server.js', SHARDED_OPTIONS), this.configOverrides)
if (!noChildren && err.message.includes('too many guilds')) new ClientSharded(new Discord.ShardingManager('./server.js', SHARDED_OPTIONS), this.configOverrides).run()
else {
log.general.error(`Discord.RSS unable to login, retrying in 10 minutes`, err)
setTimeout(() => this.login.bind(this)(token), 600000)
Expand Down Expand Up @@ -265,6 +267,7 @@ class Client {
}
listeners.createManagers(storage.bot)
if (callback) callback()
this.emit('finishInit')
}

disableCommands () {
Expand Down
30 changes: 25 additions & 5 deletions structs/ClientSharded.js
Expand Up @@ -6,6 +6,7 @@ const dbOps = require('../util/dbOps.js')
const log = require('../util/logger.js')
const dbRestore = require('../commands/controller/dbrestore.js')
const handleError = (err, message) => log.general.error(`Sharding Manager broadcast message handling error for message type ${message.type}`, err, true)
const EventEmitter = require('events');

function overrideConfigs (configOverrides) {
// Config overrides must be manually done for it to be changed in the original object (config)
Expand All @@ -20,11 +21,13 @@ function overrideConfigs (configOverrides) {
}
}

class ClientSharded {
class ClientSharded extends EventEmitter {
constructor (shardingManager, configOverrides) {
super()
if (shardingManager.respawn !== false) throw new Error(`Discord.RSS requires ShardingManager's respawn option to be false`)
overrideConfigs(configOverrides)
this.missingGuildRss = new Map()
this.guildStore = new Map()
this.missingGuildsCounter = {} // Object with guild IDs as keys and number as value
this.refreshTimes = [config.feeds.refreshTimeMinutes]
this.activeshardIds = []
Expand All @@ -36,9 +39,11 @@ class ClientSharded {
this.shardsDone = 0 // Shards that have reported that they're done initializing
this.shardingManager = shardingManager
this.shardingManager.on('message', this.messageHandler.bind(this))
}

run () {
connectDb().then(() => {
if (shardingManager.shards.size === 0) shardingManager.spawn(config.advanced.shards) // They may have already been spawned with a predefined ShardingManager
// shardingManager.shards.forEach((val, key) => this.activeshardIds.push(key))
if (this.shardingManager.shards.size === 0) this.shardingManager.spawn(config.advanced.shards) // They may have already been spawned with a predefined ShardingManager
}).catch(err => log.general.error(`ClientSharded db connection`, err))
}

Expand All @@ -51,7 +56,9 @@ class ClientSharded {
case 'shardReady': this._shardReadyEvent(message); break
case 'initComplete': this._initCompleteEvent(message); break
case 'scheduleComplete': this._scheduleCompleteEvent(message); break
case 'addCustomSchedule': this._addCustomSchedule(message); break
case 'addCustomSchedule': this._addCustomScheduleEvent(message); break
case 'guildRss.update': this._updateGuildRssEvent(message); break
case 'guildRss.remove': this._removeGuildRssEvent(message); break
case 'dbRestore': this._dbRestoreEvent(message)
}
}
Expand All @@ -67,6 +74,9 @@ class ClientSharded {
}
}
_initCompleteEvent (message) {
// Set the active guilds
for (const guildId in message.guilds) this.guildStore.set(guildId, message.guilds[guildId])

// Account for missing guilds
const missing = message.missingGuilds
for (var guildId in missing) {
Expand Down Expand Up @@ -98,6 +108,8 @@ class ClientSharded {
.catch(err => log.init.warning(`(G: ${guildId}) Guild deletion error based on missing guild declared by the Sharding Manager`, err))
})
this.createIntervals()
this.emit('finishInit')
require('../../drss-web/index.js')(this.guildStore)
})
.catch(err => {
console.log(err)
Expand All @@ -122,7 +134,7 @@ class ClientSharded {
}
}

_addCustomSchedule (message) {
_addCustomScheduleEvent (message) {
const refreshTime = message.schedule.refreshTimeMinutes
if (this.refreshTimes.includes(refreshTime)) return
this.refreshTimes.push(refreshTime)
Expand All @@ -135,6 +147,14 @@ class ClientSharded {
}, refreshTime * 60000)) // Convert minutes to ms
}

_updateGuildRssEvent (message) {
this.guildStore.set(message.guildRss.id, message.guildRss)
}

_removeGuildRssEvent (message) {
this.guildStore.delete(message.guildRss.id)
}

_dbRestoreEvent (message) {
this.scheduleIntervals.forEach(it => clearInterval(it))
this.shardingManager.broadcast({ _drss: true, type: 'stop' })
Expand Down

0 comments on commit d300b52

Please sign in to comment.