Add client.destroy();

This commit is contained in:
Amish Shah
2016-08-30 13:05:50 +01:00
parent 56352220af
commit d249aa10cc
18 changed files with 74 additions and 42 deletions

File diff suppressed because one or more lines are too long

View File

@@ -105,6 +105,8 @@ class Client extends EventEmitter {
* @type {?Number} * @type {?Number}
*/ */
this.readyTime = null; this.readyTime = null;
this._intervals = [];
this._timeouts = [];
} }
/** /**
@@ -135,6 +137,32 @@ class Client extends EventEmitter {
return this.rest.methods.loginToken(email); return this.rest.methods.loginToken(email);
} }
/**
* Destroys the client and logs out. Resolves with null if successful.
* @returns {Promise<null, Error>}
*/
destroy() {
return new Promise((resolve, reject) => {
this.manager.destroy().then(() => {
this._intervals.map(i => clearInterval(i));
this._timeouts.map(t => clearTimeout(t));
this.token = null;
this.email = null;
this.password = null;
resolve();
})
.catch(reject);
});
}
setInterval(...params) {
this._intervals.push(setInterval(...params));
}
setTimeout(...params) {
this._timeouts.push(setTimeout(...params));
}
/** /**
* Caches a user, or obtains it from the cache if it's already cached. * Caches a user, or obtains it from the cache if it's already cached.
* If the user isn't already cached, it will only be obtainable by OAuth bot accounts. * If the user isn't already cached, it will only be obtainable by OAuth bot accounts.

View File

@@ -35,7 +35,7 @@ class ClientManager {
}) })
.catch(reject); .catch(reject);
setTimeout(() => reject(Constants.Errors.TOOK_TOO_LONG), 1000 * 300); this.client.setTimeout(() => reject(Constants.Errors.TOOK_TOO_LONG), 1000 * 300);
} }
/** /**
@@ -44,13 +44,24 @@ class ClientManager {
* @returns {null} * @returns {null}
*/ */
setupKeepAlive(time) { setupKeepAlive(time) {
this.heartbeatInterval = setInterval(() => { this.heartbeatInterval = this.client.setInterval(() => {
this.client.ws.send({ this.client.ws.send({
op: Constants.OPCodes.HEARTBEAT, op: Constants.OPCodes.HEARTBEAT,
d: Date.now(), d: Date.now(),
}); });
}, time); }, time);
} }
destroy() {
return new Promise((resolve) => {
if (!this.client.user.bot) {
this.client.rest.methods.logout().then(resolve);
} else {
this.client.ws.destroy();
resolve();
}
});
}
} }
module.exports = ClientManager; module.exports = ClientManager;

View File

@@ -26,10 +26,7 @@ class ChannelDeleteAction extends Action {
} }
scheduleForDeletion(id) { scheduleForDeletion(id) {
this.timeouts.push( this.client.setTimeout(() => delete this.deleted[id], this.client.options.rest_ws_bridge_timeout);
setTimeout(() => delete this.deleted[id],
this.client.options.rest_ws_bridge_timeout)
);
} }
} }

View File

@@ -6,7 +6,6 @@ class GuildDeleteAction extends Action {
constructor(client) { constructor(client) {
super(client); super(client);
this.deleted = {}; this.deleted = {};
this.timeouts = [];
} }
handle(data) { handle(data) {
@@ -39,10 +38,7 @@ class GuildDeleteAction extends Action {
} }
scheduleForDeletion(id) { scheduleForDeletion(id) {
this.timeouts.push( this.client.setTimeout(() => delete this.deleted[id], this.client.options.rest_ws_bridge_timeout)
setTimeout(() => delete this.deleted[id],
this.client.options.rest_ws_bridge_timeout)
);
} }
} }

View File

@@ -5,7 +5,6 @@ class GuildMemberRemoveAction extends Action {
constructor(client) { constructor(client) {
super(client); super(client);
this.timeouts = [];
this.deleted = {}; this.deleted = {};
} }
@@ -39,10 +38,7 @@ class GuildMemberRemoveAction extends Action {
} }
scheduleForDeletion(guildID, userID) { scheduleForDeletion(guildID, userID) {
this.timeouts.push( this.client.setTimeout(() => delete this.deleted[guildID + userID], this.client.options.rest_ws_bridge_timeout);
setTimeout(() => delete this.deleted[guildID + userID],
this.client.options.rest_ws_bridge_timeout)
);
} }
} }

View File

@@ -5,7 +5,6 @@ class GuildRoleDeleteAction extends Action {
constructor(client) { constructor(client) {
super(client); super(client);
this.timeouts = [];
this.deleted = {}; this.deleted = {};
} }
@@ -37,10 +36,7 @@ class GuildRoleDeleteAction extends Action {
} }
scheduleForDeletion(guildID, roleID) { scheduleForDeletion(guildID, roleID) {
this.timeouts.push( this.client.setTimeout(() => delete this.deleted[guildID + roleID], this.client.options.rest_ws_bridge_timeout)
setTimeout(() => delete this.deleted[guildID + roleID],
this.client.options.rest_ws_bridge_timeout)
);
} }
} }

View File

@@ -4,7 +4,6 @@ class MessageDeleteAction extends Action {
constructor(client) { constructor(client) {
super(client); super(client);
this.timeouts = [];
this.deleted = {}; this.deleted = {};
} }
@@ -33,10 +32,8 @@ class MessageDeleteAction extends Action {
} }
scheduleForDeletion(channelID, messageID) { scheduleForDeletion(channelID, messageID) {
this.timeouts.push( this.client.setTimeout(
setTimeout(() => delete this.deleted[channelID + messageID], () => delete this.deleted[channelID + messageID], this.client.options.rest_ws_bridge_timeout);
this.client.options.rest_ws_bridge_timeout)
);
} }
} }

View File

@@ -30,6 +30,10 @@ class RESTMethods {
}); });
} }
logout() {
return this.rest.makeRequest('post', Constants.Endpoints.logout, true);
}
getGateway() { getGateway() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('get', Constants.Endpoints.gateway, true) this.rest.makeRequest('get', Constants.Endpoints.gateway, true)

View File

@@ -53,7 +53,7 @@ class SequentialRequestHandler extends RequestHandler {
} }
if (err) { if (err) {
if (err.status === 429) { if (err.status === 429) {
setTimeout(() => { this.restManager.client.setTimeout(() => {
this.waiting = false; this.waiting = false;
this.globalLimit = false; this.globalLimit = false;
resolve(); resolve();
@@ -73,7 +73,7 @@ class SequentialRequestHandler extends RequestHandler {
const data = res && res.body ? res.body : {}; const data = res && res.body ? res.body : {};
item.resolve(data); item.resolve(data);
if (this.requestRemaining === 0) { if (this.requestRemaining === 0) {
setTimeout(() => { this.restManager.client.setTimeout(() => {
this.waiting = false; this.waiting = false;
resolve(data); resolve(data);
}, (this.requestResetTime - Date.now()) + this.timeDifference + 1000); }, (this.requestResetTime - Date.now()) + this.timeDifference + 1000);

View File

@@ -66,7 +66,7 @@ class VoiceConnectionWebSocket extends EventEmitter {
} }
_setHeartbeat(interval) { _setHeartbeat(interval) {
this.heartbeat = setInterval(() => { this.heartbeat = this.voiceConnection.manager.client.setInterval(() => {
this.send({ this.send({
op: Constants.VoiceOPCodes.HEARTBEAT, op: Constants.VoiceOPCodes.HEARTBEAT,
d: null, d: null,

View File

@@ -70,7 +70,7 @@ class StreamDispatcher extends EventEmitter {
} }
if (this.paused) { if (this.paused) {
data.timestamp = (data.timestamp + 4294967295) ? data.timestamp + 960 : 0; data.timestamp = (data.timestamp + 4294967295) ? data.timestamp + 960 : 0;
return setTimeout(() => this._send(), data.length * 10); return this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10);
} }
const bufferLength = 1920 * data.channels; const bufferLength = 1920 * data.channels;
this._setSpeaking(true); this._setSpeaking(true);
@@ -78,7 +78,7 @@ class StreamDispatcher extends EventEmitter {
if (!buffer) { if (!buffer) {
data.missed++; data.missed++;
return setTimeout(() => this._send(), data.length * 10); return this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10);
} }
data.missed = 0; data.missed = 0;
@@ -97,7 +97,7 @@ class StreamDispatcher extends EventEmitter {
const nextTime = data.startTime + (data.count * data.length); const nextTime = data.startTime + (data.count * data.length);
setTimeout(() => this._send(), data.length + (nextTime - Date.now())); this.player.connection.manager.client.setTimeout(() => this._send(), data.length + (nextTime - Date.now()));
} catch (e) { } catch (e) {
this._triggerTerminalState('error', e); this._triggerTerminalState('error', e);
} }

View File

@@ -76,11 +76,17 @@ class WebSocketManager {
this.doQueue(); this.doQueue();
} }
destroy() {
this.ws.close(1000);
this._queue = [];
this.status = Constants.Status.IDLE;
}
doQueue() { doQueue() {
const item = this._queue[0]; const item = this._queue[0];
if (this.ws.readyState === WebSocket.OPEN && item) { if (this.ws.readyState === WebSocket.OPEN && item) {
if (this._remaining === 0) { if (this._remaining === 0) {
return setTimeout(() => { return this.client.setTimeout(() => {
this.doQueue(); this.doQueue();
}, 1000); }, 1000);
} }
@@ -88,7 +94,7 @@ class WebSocketManager {
this.ws.send(item); this.ws.send(item);
this._queue.shift(); this._queue.shift();
this.doQueue(); this.doQueue();
setTimeout(() => this._remaining++, 1000); this.client.setTimeout(() => this._remaining++, 1000);
} }
} }
@@ -144,11 +150,10 @@ class WebSocketManager {
* @returns {null} * @returns {null}
*/ */
eventClose(event) { eventClose(event) {
console.log(event.code);
if (event.code === 4004) { if (event.code === 4004) {
throw Constants.Errors.BAD_LOGIN; throw Constants.Errors.BAD_LOGIN;
} }
if (!this.reconnecting) { if (!this.reconnecting && event.code !== 1000) {
this.tryReconnect(); this.tryReconnect();
} }
} }

View File

@@ -28,7 +28,7 @@ class TypingStartHandler extends AbstractHandler {
const timestamp = new Date(data.timestamp * 1000); const timestamp = new Date(data.timestamp * 1000);
function tooLate() { function tooLate() {
return setTimeout(() => { return client.setTimeout(() => {
client.emit(Constants.Events.TYPING_STOP, channel, user, channel.typingMap[user.id]); client.emit(Constants.Events.TYPING_STOP, channel, user, channel.typingMap[user.id]);
delete channel.typingMap[user.id]; delete channel.typingMap[user.id];
}, 6000); }, 6000);

View File

@@ -599,7 +599,7 @@ class Guild {
}, },
}); });
this._checkChunks(); this._checkChunks();
setTimeout(() => reject(new Error('members not here in time')), 120 * 1000); this.client.setTimeout(() => reject(new Error('members not here in time')), 120 * 1000);
}); });
} }

View File

@@ -243,7 +243,7 @@ class Message {
*/ */
delete(timeout = 0) { delete(timeout = 0) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
setTimeout(() => { this.client.setTimeout(() => {
this.client.rest.methods.deleteMessage(this) this.client.rest.methods.deleteMessage(this)
.then(resolve) .then(resolve)
.catch(reject); .catch(reject);

View File

@@ -151,7 +151,7 @@ class TextBasedChannel {
setTyping(typing) { setTyping(typing) {
clearInterval(this.client.user._typing.get(this.id)); clearInterval(this.client.user._typing.get(this.id));
if (typing) { if (typing) {
this.client.user._typing.set(this.id, setInterval(() => { this.client.user._typing.set(this.id, this.client.setInterval(() => {
this.client.rest.methods.sendTyping(this.id); this.client.rest.methods.sendTyping(this.id);
}, 4000)); }, 4000));
this.client.rest.methods.sendTyping(this.id); this.client.rest.methods.sendTyping(this.id);

View File

@@ -6,7 +6,9 @@ const fs = require('fs');
const client = new Discord.Client({ fetch_all_members: false }); const client = new Discord.Client({ fetch_all_members: false });
client.login(require('./auth.json').token).then(token => console.log('logged in with token ' + token)).catch(console.log); const { email, password, token } = require('./auth.json');
client.login(token).then(atoken => console.log('logged in with token ' + atoken)).catch(console.log);
client.on('ready', () => { client.on('ready', () => {
console.log('ready!'); console.log('ready!');