ESLint stuff...

This commit is contained in:
Amish Shah
2016-08-13 14:44:49 +01:00
parent 53d767ec04
commit b8db4c4f4b
74 changed files with 2574 additions and 2956 deletions

16
.eslintrc.js Normal file
View File

@@ -0,0 +1,16 @@
module.exports = {
"extends": "airbnb",
"plugins": [
"react",
"jsx-a11y",
"import"
],
"rules" : {
"max-len": [2, 120, 2],
"no-underscore-dangle": 0,
"global-require": 0,
"guard-for-in": 0,
"no-restricted-syntax": 0,
"no-param-reassign": 0,
}
};

View File

@@ -4,7 +4,7 @@
"description": "A way to interface with the Discord API", "description": "A way to interface with the Discord API",
"main": "./src/index", "main": "./src/index",
"scripts": { "scripts": {
"test": "jscs src && node test/random" "test": "node test/random"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -34,6 +34,11 @@
"devDependencies": { "devDependencies": {
"babel-preset-es2015": "^6.6.0", "babel-preset-es2015": "^6.6.0",
"babel-preset-stage-3": "^6.5.0", "babel-preset-stage-3": "^6.5.0",
"eslint": "^3.3.0",
"eslint-config-airbnb": "^10.0.1",
"eslint-plugin-import": "^1.13.0",
"eslint-plugin-jsx-a11y": "^2.1.0",
"eslint-plugin-react": "^6.0.0",
"grunt": "^0.4.5", "grunt": "^0.4.5",
"grunt-babel": "^6.0.0", "grunt-babel": "^6.0.0",
"grunt-browserify": "^4.0.1", "grunt-browserify": "^4.0.1",

View File

@@ -1,10 +1,8 @@
'use strict';
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
const MergeDefault = require('../util/MergeDefault'); const mergeDefault = require('../util/MergeDefault');
const Constants = require('../util/Constants'); const Constants = require('../util/Constants');
const RESTManager = require('./rest/RestManager'); const RESTManager = require('./rest/RESTManager');
const ClientDataStore = require('../structures/DataStore/ClientDataStore'); const ClientDataStore = require('../structures/datastore/ClientDataStore');
const ClientManager = require('./ClientManager'); const ClientManager = require('./ClientManager');
const ClientDataResolver = require('./ClientDataResolver'); const ClientDataResolver = require('./ClientDataResolver');
const WebSocketManager = require('./websocket/WebSocketManager'); const WebSocketManager = require('./websocket/WebSocketManager');
@@ -17,11 +15,11 @@ const ActionsManager = require('./actions/ActionsManager');
* const client = new Discord.Client(); * const client = new Discord.Client();
* ``` * ```
*/ */
class Client extends EventEmitter{ class Client extends EventEmitter {
constructor(options) { constructor(options) {
super(); super();
this.options = MergeDefault(Constants.DefaultOptions, options); this.options = mergeDefault(Constants.DefaultOptions, options);
this.rest = new RESTManager(this); this.rest = new RESTManager(this);
this.store = new ClientDataStore(this); this.store = new ClientDataStore(this);
this.manager = new ClientManager(this); this.manager = new ClientManager(this);
@@ -44,11 +42,10 @@ class Client extends EventEmitter{
login(email, password) { login(email, password) {
if (password) { if (password) {
// login with email and password // login with email and password
return this.rest.methods.LoginEmailPassword(email, password); return this.rest.methods.loginEmailPassword(email, password);
} else {
// login with token
return this.rest.methods.LoginToken(email);
} }
// login with token
return this.rest.methods.loginToken(email);
} }
/** /**

View File

@@ -1,15 +1,10 @@
'use strict'; const getStructure = name => require(`../structures/${name}`);
const Structure = name => require(`../structures/${name}`); const User = getStructure('User');
const Message = getStructure('Message');
const User = Structure('User'); const Guild = getStructure('Guild');
const Message = Structure('Message'); const Channel = getStructure('Channel');
const Guild = Structure('Guild'); const GuildMember = getStructure('GuildMember');
const Channel = Structure('Channel');
const ServerChannel = Structure('ServerChannel');
const TextChannel = Structure('TextChannel');
const VoiceChannel = Structure('VoiceChannel');
const GuildMember = Structure('GuildMember');
function $string(obj) { function $string(obj) {
return (typeof obj === 'string' || obj instanceof String); return (typeof obj === 'string' || obj instanceof String);
@@ -21,33 +16,36 @@ class ClientDataResolver {
this.client = client; this.client = client;
} }
ResolveUser(user) { resolveUser(user) {
if (user instanceof User) { if (user instanceof User) {
return user; return user;
}else if ($string(user)) { } else if ($string(user)) {
return this.client.store.get('users', user); return this.client.store.get('users', user);
}else if (user instanceof Message) { } else if (user instanceof Message) {
return user.author; return user.author;
}else if (user instanceof Guild) { } else if (user instanceof Guild) {
return user.owner; return user.owner;
} }
return null; return null;
} }
ResolveGuild(guild) { resolveGuild(guild) {
if (guild instanceof Guild) { if (guild instanceof Guild) {
return guild; return guild;
} }
return null;
} }
ResolveGuildMember(guild, user) { resolveGuildMember($guild, $user) {
let guild = $guild;
let user = $user;
if (user instanceof GuildMember) { if (user instanceof GuildMember) {
return user; return user;
} }
guild = this.ResolveGuild(guild); guild = this.resolveGuild(guild);
user = this.ResolveUser(user); user = this.resolveUser(user);
if (!guild || !user) { if (!guild || !user) {
return null; return null;
@@ -56,15 +54,15 @@ class ClientDataResolver {
return guild.store.get('members', user.id); return guild.store.get('members', user.id);
} }
ResolveBase64(data) { resolveBase64(data) {
if (data instanceof Buffer) { if (data instanceof Buffer) {
return 'data:image/jpg;base64,' + data.toString('base64'); return `data:image/jpg;base64,${data.toString('base64')}`;
} }
return data; return data;
} }
ResolveChannel(channel) { resolveChannel(channel) {
if (channel instanceof Channel) { if (channel instanceof Channel) {
return channel; return channel;
} }
@@ -72,9 +70,11 @@ class ClientDataResolver {
if ($string(channel)) { if ($string(channel)) {
return this.client.store.get('channels', channel); return this.client.store.get('channels', channel);
} }
return null;
} }
ResolveString(data) { resolveString(data) {
if (data instanceof String) { if (data instanceof String) {
return data; return data;
} }

View File

@@ -1,5 +1,3 @@
'use strict';
const Constants = require('../util/Constants'); const Constants = require('../util/Constants');
class ClientManager { class ClientManager {
@@ -11,7 +9,7 @@ class ClientManager {
connectToWebSocket(token, resolve, reject) { connectToWebSocket(token, resolve, reject) {
this.client.store.token = token; this.client.store.token = token;
this.client.rest.methods.GetGateway() this.client.rest.methods.getGateway()
.then(gateway => { .then(gateway => {
this.client.ws.connect(gateway); this.client.ws.connect(gateway);
this.client.once(Constants.Events.READY, () => resolve(token)); this.client.once(Constants.Events.READY, () => resolve(token));

View File

@@ -1,5 +1,3 @@
'use strict';
/* /*
ABOUT ACTIONS ABOUT ACTIONS
@@ -19,9 +17,9 @@ class GenericAction {
} }
handle(data) { handle(data) {
return data;
} }
}; }
module.exports = GenericAction; module.exports = GenericAction;

View File

@@ -1,5 +1,3 @@
'use strict';
const requireAction = name => require(`./${name}`); const requireAction = name => require(`./${name}`);
class ActionsManager { class ActionsManager {
@@ -22,7 +20,7 @@ class ActionsManager {
} }
register(name) { register(name) {
let Action = requireAction(name); const Action = requireAction(name);
this[name] = new Action(this.client); this[name] = new Action(this.client);
} }
} }

View File

@@ -1,23 +1,15 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants');
const Message = require('../../structures/Message');
class ChannelCreateAction extends Action { class ChannelCreateAction extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
let client = this.client; const client = this.client;
let channel = client.store.NewChannel(data); const channel = client.store.newChannel(data);
return { return {
channel, channel,
}; };
} }
}; }
module.exports = ChannelCreateAction; module.exports = ChannelCreateAction;

View File

@@ -1,8 +1,4 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants');
const Message = require('../../structures/Message');
class ChannelDeleteAction extends Action { class ChannelDeleteAction extends Action {
@@ -13,19 +9,15 @@ class ChannelDeleteAction extends Action {
} }
handle(data) { handle(data) {
let client = this.client; const client = this.client;
let channel = client.store.get('channels', data.id); let channel = client.store.get('channels', data.id);
if (channel) { if (channel) {
client.store.killChannel(channel);
client.store.KillChannel(channel);
this.deleted[channel.id] = channel; this.deleted[channel.id] = channel;
this.scheduleForDeletion(channel.id); this.scheduleForDeletion(channel.id);
} else if (this.deleted[data.id]) { } else if (this.deleted[data.id]) {
channel = this.deleted[data.id]; channel = this.deleted[data.id];
} }
return { return {
@@ -39,6 +31,6 @@ class ChannelDeleteAction extends Action {
this.client.options.rest_ws_bridge_timeout) this.client.options.rest_ws_bridge_timeout)
); );
} }
}; }
module.exports = ChannelDeleteAction; module.exports = ChannelDeleteAction;

View File

@@ -1,23 +1,15 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject'); const cloneObject = require('../../util/CloneObject');
const Message = require('../../structures/Message');
class ChannelUpdateAction extends Action { class ChannelUpdateAction extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
const client = this.client;
let client = this.client; const channel = client.store.get('channels', data.id);
let channel = client.store.get('channels', data.id);
if (channel) { if (channel) {
let oldChannel = CloneObject(channel); const oldChannel = cloneObject(channel);
channel.setup(data); channel.setup(data);
if (!oldChannel.equals(data)) { if (!oldChannel.equals(data)) {
client.emit(Constants.Events.CHANNEL_UPDATE, oldChannel, channel); client.emit(Constants.Events.CHANNEL_UPDATE, oldChannel, channel);
@@ -34,6 +26,6 @@ class ChannelUpdateAction extends Action {
updated: null, updated: null,
}; };
} }
}; }
module.exports = ChannelUpdateAction; module.exports = ChannelUpdateAction;

View File

@@ -1,8 +1,5 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const Message = require('../../structures/Message');
class GuildDeleteAction extends Action { class GuildDeleteAction extends Action {
@@ -13,8 +10,7 @@ class GuildDeleteAction extends Action {
} }
handle(data) { handle(data) {
const client = this.client;
let client = this.client;
let guild = client.store.get('guilds', data.id); let guild = client.store.get('guilds', data.id);
if (guild) { if (guild) {
@@ -28,12 +24,11 @@ class GuildDeleteAction extends Action {
return { return {
guild: null, guild: null,
}; };
} else { }
// delete guild // delete guild
client.store.remove('guilds', guild); client.store.remove('guilds', guild);
this.deleted[guild.id] = guild; this.deleted[guild.id] = guild;
this.scheduleForDeletion(guild.id); this.scheduleForDeletion(guild.id);
}
} else if (this.deleted[data.id]) { } else if (this.deleted[data.id]) {
guild = this.deleted[data.id]; guild = this.deleted[data.id];
} }
@@ -49,6 +44,6 @@ class GuildDeleteAction extends Action {
this.client.options.rest_ws_bridge_timeout) this.client.options.rest_ws_bridge_timeout)
); );
} }
}; }
module.exports = GuildDeleteAction; module.exports = GuildDeleteAction;

View File

@@ -1,8 +1,5 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const Message = require('../../structures/Message');
class GuildMemberRemoveAction extends Action { class GuildMemberRemoveAction extends Action {
@@ -13,8 +10,8 @@ class GuildMemberRemoveAction extends Action {
} }
handle(data) { handle(data) {
let client = this.client; const client = this.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
if (guild) { if (guild) {
let member = guild.store.get('members', data.user.id); let member = guild.store.get('members', data.user.id);
if (member) { if (member) {
@@ -46,6 +43,6 @@ class GuildMemberRemoveAction extends Action {
this.client.options.rest_ws_bridge_timeout) this.client.options.rest_ws_bridge_timeout)
); );
} }
}; }
module.exports = GuildMemberRemoveAction; module.exports = GuildMemberRemoveAction;

View File

@@ -1,23 +1,16 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const Role = require('../../structures/Role'); const Role = require('../../structures/Role');
class GuildRoleCreate extends Action { class GuildRoleCreate extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
const client = this.client;
let client = this.client; const guild = client.store.get('guilds', data.guild_id);
let guild = client.store.get('guilds', data.guild_id);
if (guild) { if (guild) {
let already = guild.store.get('roles', data.role.id); const already = guild.store.get('roles', data.role.id);
let role = new Role(guild, data.role); const role = new Role(guild, data.role);
guild.store.add('roles', role); guild.store.add('roles', role);
if (!already) { if (!already) {
@@ -33,6 +26,6 @@ class GuildRoleCreate extends Action {
role: null, role: null,
}; };
} }
}; }
module.exports = GuildRoleCreate; module.exports = GuildRoleCreate;

View File

@@ -1,8 +1,5 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const Message = require('../../structures/Message');
class GuildRoleDeleteAction extends Action { class GuildRoleDeleteAction extends Action {
@@ -13,8 +10,8 @@ class GuildRoleDeleteAction extends Action {
} }
handle(data) { handle(data) {
let client = this.client; const client = this.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
if (guild) { if (guild) {
let exists = guild.store.get('roles', data.role_id); let exists = guild.store.get('roles', data.role_id);
@@ -45,6 +42,6 @@ class GuildRoleDeleteAction extends Action {
this.client.options.rest_ws_bridge_timeout) this.client.options.rest_ws_bridge_timeout)
); );
} }
}; }
module.exports = GuildRoleDeleteAction; module.exports = GuildRoleDeleteAction;

View File

@@ -1,29 +1,21 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject'); const cloneObject = require('../../util/CloneObject');
const Message = require('../../structures/Message');
class GuildRoleUpdateAction extends Action { class GuildRoleUpdateAction extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
const client = this.client;
const guild = client.store.get('guilds', data.guild_id);
let client = this.client; const roleData = data.role;
let guild = client.store.get('guilds', data.guild_id);
let roleData = data.role;
if (guild) { if (guild) {
let oldRole; let oldRole;
let existingRole = guild.store.get('roles', roleData.id); const existingRole = guild.store.get('roles', roleData.id);
// exists and not the same // exists and not the same
if (existingRole && !existingRole.equals(roleData)) { if (existingRole && !existingRole.equals(roleData)) {
oldRole = CloneObject(existingRole); oldRole = cloneObject(existingRole);
existingRole.setup(data.role); existingRole.setup(data.role);
client.emit(Constants.Events.GUILD_ROLE_UPDATE, guild, oldRole, existingRole); client.emit(Constants.Events.GUILD_ROLE_UPDATE, guild, oldRole, existingRole);
} }
@@ -39,6 +31,6 @@ class GuildRoleUpdateAction extends Action {
updated: null, updated: null,
}; };
} }
}; }
module.exports = GuildRoleUpdateAction; module.exports = GuildRoleUpdateAction;

View File

@@ -1,9 +1,6 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject'); const cloneObject = require('../../util/CloneObject');
const Message = require('../../structures/Message');
class GuildUpdateAction extends Action { class GuildUpdateAction extends Action {
@@ -14,12 +11,11 @@ class GuildUpdateAction extends Action {
} }
handle(data) { handle(data) {
const client = this.client;
let client = this.client; const guild = client.store.get('guilds', data.id);
let guild = client.store.get('guilds', data.id);
if (guild) { if (guild) {
let oldGuild = CloneObject(guild); const oldGuild = cloneObject(guild);
guild.setup(data); guild.setup(data);
if (!oldGuild.equals(data)) { if (!oldGuild.equals(data)) {
@@ -37,6 +33,6 @@ class GuildUpdateAction extends Action {
updated: null, updated: null,
}; };
} }
}; }
module.exports = GuildUpdateAction; module.exports = GuildUpdateAction;

View File

@@ -1,22 +1,14 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants');
const Message = require('../../structures/Message'); const Message = require('../../structures/Message');
class MessageCreateAction extends Action { class MessageCreateAction extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
const client = this.client;
let client = this.client; const channel = client.store.get('channels', data.channel_id);
let channel = client.store.get('channels', data.channel_id);
if (channel) { if (channel) {
let message = channel._cacheMessage(new Message(channel, data, client)); const message = channel._cacheMessage(new Message(channel, data, client));
return { return {
m: message, m: message,
}; };
@@ -26,6 +18,6 @@ class MessageCreateAction extends Action {
m: null, m: null,
}; };
} }
}; }
module.exports = MessageCreateAction; module.exports = MessageCreateAction;

View File

@@ -1,8 +1,4 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants');
const Message = require('../../structures/Message');
class MessageDeleteAction extends Action { class MessageDeleteAction extends Action {
@@ -13,21 +9,17 @@ class MessageDeleteAction extends Action {
} }
handle(data) { handle(data) {
let client = this.client; const client = this.client;
let channel = client.store.get('channels', data.channel_id); const channel = client.store.get('channels', data.channel_id);
if (channel) { if (channel) {
let message = channel.store.get('messages', data.id); let message = channel.store.get('messages', data.id);
if (message) { if (message) {
channel.store.remove('messages', message.id); channel.store.remove('messages', message.id);
this.deleted[channel.id + message.id] = message; this.deleted[channel.id + message.id] = message;
this.scheduleForDeletion(channel.id, message.id); this.scheduleForDeletion(channel.id, message.id);
} else if (this.deleted[channel.id + data.id]) { } else if (this.deleted[channel.id + data.id]) {
message = this.deleted[channel.id + data.id]; message = this.deleted[channel.id + data.id];
} }
return { return {
@@ -46,6 +38,6 @@ class MessageDeleteAction extends Action {
this.client.options.rest_ws_bridge_timeout) this.client.options.rest_ws_bridge_timeout)
); );
} }
}; }
module.exports = MessageDeleteAction; module.exports = MessageDeleteAction;

View File

@@ -1,31 +1,23 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject'); const cloneObject = require('../../util/CloneObject');
const Message = require('../../structures/Message');
class MessageUpdateAction extends Action { class MessageUpdateAction extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
const client = this.client;
let client = this.client; const channel = client.store.get('channels', data.channel_id);
let channel = client.store.get('channels', data.channel_id);
if (channel) { if (channel) {
let message = channel.store.get('messages', data.id); const message = channel.store.get('messages', data.id);
if (message && !message.equals(data, true)) { if (message && !message.equals(data, true)) {
let oldMessage = CloneObject(message); const oldMessage = cloneObject(message);
message.patch(data); message.patch(data);
client.emit(Constants.Events.MESSAGE_UPDATE, oldMessage, message);
return { return {
old: oldMessage, old: oldMessage,
updated: message, updated: message,
}; };
client.emit(Constants.Events.MESSAGE_UPDATE, oldMessage, message);
} }
return { return {
@@ -39,6 +31,6 @@ class MessageUpdateAction extends Action {
updated: null, updated: null,
}; };
} }
}; }
module.exports = MessageUpdateAction; module.exports = MessageUpdateAction;

View File

@@ -1,19 +1,11 @@
'use strict';
const Action = require('./Action'); const Action = require('./Action');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject'); const cloneObject = require('../../util/CloneObject');
const Message = require('../../structures/Message');
class UserUpdateAction extends Action { class UserUpdateAction extends Action {
constructor(client) {
super(client);
}
handle(data) { handle(data) {
const client = this.client;
let client = this.client;
if (client.store.user) { if (client.store.user) {
if (client.store.user.equals(data)) { if (client.store.user.equals(data)) {
@@ -23,7 +15,7 @@ class UserUpdateAction extends Action {
}; };
} }
let oldUser = CloneObject(client.store.user); const oldUser = cloneObject(client.store.user);
client.store.user.setup(data); client.store.user.setup(data);
client.emit(Constants.Events.USER_UPDATE, oldUser, client.store.user); client.emit(Constants.Events.USER_UPDATE, oldUser, client.store.user);
@@ -39,6 +31,6 @@ class UserUpdateAction extends Action {
updated: null, updated: null,
}; };
} }
}; }
module.exports = UserUpdateAction; module.exports = UserUpdateAction;

View File

@@ -1,11 +1,9 @@
'use strict';
const request = require('superagent'); const request = require('superagent');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const UserAgentManager = require('./UserAgentManager'); const UserAgentManager = require('./UserAgentManager');
const RESTMethods = require('./RESTMethods'); const RESTMethods = require('./RESTMethods');
class RESTManager{ class RESTManager {
constructor(client) { constructor(client) {
this.client = client; this.client = client;
@@ -16,19 +14,25 @@ class RESTManager{
} }
addRequestToQueue(method, url, auth, data, file, resolve, reject) { addRequestToQueue(method, url, auth, data, file, resolve, reject) {
let endpoint = url.replace(/\/[0-9]+/g, '/:id'); const endpoint = url.replace(/\/[0-9]+/g, '/:id');
let rateLimitedEndpoint = this.rateLimitedEndpoints[endpoint]; const rateLimitedEndpoint = this.rateLimitedEndpoints[endpoint];
rateLimitedEndpoint.queue = rateLimitedEndpoint.queue || []; rateLimitedEndpoint.queue = rateLimitedEndpoint.queue || [];
rateLimitedEndpoint.queue.push({ rateLimitedEndpoint.queue.push({
method, url, auth, data, file, resolve, reject, method,
url,
auth,
data,
file,
resolve,
reject,
}); });
} }
processQueue(endpoint) { processQueue(endpoint) {
let rateLimitedEndpoint = this.rateLimitedEndpoints[endpoint]; const rateLimitedEndpoint = this.rateLimitedEndpoints[endpoint];
// prevent multiple queue processes // prevent multiple queue processes
if (!rateLimitedEndpoint.timeout) { if (!rateLimitedEndpoint.timeout) {
@@ -39,7 +43,7 @@ class RESTManager{
clearTimeout(rateLimitedEndpoint.timeout); clearTimeout(rateLimitedEndpoint.timeout);
rateLimitedEndpoint.timeout = null; rateLimitedEndpoint.timeout = null;
for (let item of rateLimitedEndpoint.queue) { for (const item of rateLimitedEndpoint.queue) {
this.makeRequest(item.method, item.url, item.auth, item.data, item.file) this.makeRequest(item.method, item.url, item.auth, item.data, item.file)
.then(item.resolve) .then(item.resolve)
.catch(item.reject); .catch(item.reject);
@@ -48,13 +52,14 @@ class RESTManager{
rateLimitedEndpoint.queue = []; rateLimitedEndpoint.queue = [];
} }
makeRequest(method, url, auth, data, file, fromQueue) { makeRequest(method, url, auth, data, file) {
/* /*
file is {file, name} file is {file, name}
*/ */
let apiRequest = request[method](url); console.log(url);
const apiRequest = request[method](url);
let endpoint = url.replace(/\/[0-9]+/g, '/:id'); const endpoint = url.replace(/\/[0-9]+/g, '/:id');
if (this.rateLimitedEndpoints[endpoint] && this.rateLimitedEndpoints[endpoint].timeout) { if (this.rateLimitedEndpoints[endpoint] && this.rateLimitedEndpoints[endpoint].timeout) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -83,7 +88,7 @@ class RESTManager{
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
apiRequest.end((err, res) => { apiRequest.end((err, res) => {
if (err) { if (err) {
let retry = res.headers['retry-after'] || res.headers['Retry-After']; const retry = res.headers['retry-after'] || res.headers['Retry-After'];
if (retry) { if (retry) {
this.rateLimitedEndpoints[endpoint] = {}; this.rateLimitedEndpoints[endpoint] = {};
this.addRequestToQueue(method, url, auth, data, file, resolve, reject); this.addRequestToQueue(method, url, auth, data, file, resolve, reject);
@@ -100,6 +105,6 @@ class RESTManager{
}); });
}); });
} }
}; }
module.exports = RESTManager; module.exports = RESTManager;

View File

@@ -1,50 +1,55 @@
'use strict';
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const Structure = name => require('../../structures/' + name);
const User = Structure('User');
const GuildMember = Structure('GuildMember');
const Message = Structure('Message');
class RESTMethods{ const getStructure = name => require(`../../structures/${name}`);
const User = getStructure('User');
const GuildMember = getStructure('GuildMember');
class RESTMethods {
constructor(restManager) { constructor(restManager) {
this.rest = restManager; this.rest = restManager;
} }
LoginEmailPassword(email, password) { loginEmailPassword(email, password) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.client.store.email = email; this.rest.client.store.email = email;
this.rest.client.store.password = password; this.rest.client.store.password = password;
this.rest.makeRequest('post', Constants.Endpoints.LOGIN, false, { email, password }) this.rest.makeRequest('post', Constants.Endpoints.login, false, { email, password })
.then(data => { .then(data => {
this.rest.client.manager.connectToWebSocket(data.token, resolve, reject); this.rest.client.manager.connectToWebSocket(data.token, resolve, reject);
}) })
.catch(reject); .catch(reject);
}); });
} }
LoginToken(token) { loginToken(token) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.client.manager.connectToWebSocket(token, resolve, reject); this.rest.client.manager.connectToWebSocket(token, resolve, reject);
}); });
} }
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)
.then(res => resolve(res.url)) .then(res => resolve(res.url))
.catch(reject); .catch(reject);
}); });
} }
SendMessage(channel, content, tts, nonce) { sendMessage($channel, content, tts, nonce) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const $this = this;
let channel = $channel;
var _this = this; function req() {
$this.rest.makeRequest('post', Constants.Endpoints.channelMessages(channel.id), true, {
content, tts, nonce,
})
.then(data => resolve($this.rest.client.actions.MessageCreate.handle(data).m))
.catch(reject);
}
if (channel instanceof User || channel instanceof GuildMember) { if (channel instanceof User || channel instanceof GuildMember) {
this.CreateDM(channel).then(chan => { this.createDM(channel).then(chan => {
channel = chan; channel = chan;
req(); req();
}) })
@@ -52,21 +57,13 @@ class RESTMethods{
} else { } else {
req(); req();
} }
function req() {
_this.rest.makeRequest('post', Constants.Endpoints.CHANNEL_MESSAGES(channel.id), true, {
content, tts, nonce,
})
.then(data => resolve(_this.rest.client.actions.MessageCreate.handle(data).m))
.catch(reject);
}
}); });
} }
DeleteMessage(message) { deleteMessage(message) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('del', Constants.Endpoints.CHANNEL_MESSAGE(message.channel.id, message.id), true) this.rest.makeRequest('del', Constants.Endpoints.channelMessage(message.channel.id, message.id), true)
.then(data => { .then(() => {
resolve(this.rest.client.actions.MessageDelete.handle({ resolve(this.rest.client.actions.MessageDelete.handle({
id: message.id, id: message.id,
channel_id: message.channel.id, channel_id: message.channel.id,
@@ -76,9 +73,9 @@ class RESTMethods{
}); });
} }
UpdateMessage(message, content) { updateMessage(message, content) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('patch', Constants.Endpoints.CHANNEL_MESSAGE(message.channel.id, message.id), true, { this.rest.makeRequest('patch', Constants.Endpoints.channelMessage(message.channel.id, message.id), true, {
content, content,
}) })
.then(data => { .then(data => {
@@ -88,9 +85,9 @@ class RESTMethods{
}); });
} }
CreateChannel(guild, channelName, channelType) { createChannel(guild, channelName, channelType) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('post', Constants.Endpoints.GUILD_CHANNELS(guild.id), true, { this.rest.makeRequest('post', Constants.Endpoints.guildChannels(guild.id), true, {
name: channelName, name: channelName,
type: channelType, type: channelType,
}) })
@@ -101,24 +98,23 @@ class RESTMethods{
}); });
} }
GetExistingDM(recipient) { getExistingDM(recipient) {
let dmChannel = this.rest.client.store.getAsArray('channels') const dmChannel = this.rest.client.store.getAsArray('channels')
.filter(channel => channel.recipient) .filter(channel => channel.recipient)
.filter(channel => channel.recipient.id === recipient.id); .filter(channel => channel.recipient.id === recipient.id);
return dmChannel[0]; return dmChannel[0];
} }
CreateDM(recipient) { createDM(recipient) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const dmChannel = this.getExistingDM(recipient);
let dmChannel = this.GetExistingDM(recipient);
if (dmChannel) { if (dmChannel) {
return resolve(dmChannel); return resolve(dmChannel);
} }
this.rest.makeRequest('post', Constants.Endpoints.USER_CHANNELS(this.rest.client.store.user.id), true, { return this.rest.makeRequest('post', Constants.Endpoints.userChannels(this.rest.client.store.user.id), true, {
recipient_id: recipient.id, recipient_id: recipient.id,
}) })
.then(data => resolve(this.rest.client.actions.ChannelCreate.handle(data).channel)) .then(data => resolve(this.rest.client.actions.ChannelCreate.handle(data).channel))
@@ -126,14 +122,16 @@ class RESTMethods{
}); });
} }
DeleteChannel(channel) { deleteChannel($channel) {
let channel = $channel;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (channel instanceof User || channel instanceof GuildMember) { if (channel instanceof User || channel instanceof GuildMember) {
channel = this.GetExistingDM(channel); channel = this.getExistingDM(channel);
} }
this.rest.makeRequest('del', Constants.Endpoints.CHANNEL(channel.id), true) this.rest.makeRequest('del', Constants.Endpoints.channel(channel.id), true)
.then(data => { .then($data => {
const data = $data;
data.id = channel.id; data.id = channel.id;
resolve(this.rest.client.actions.ChannelDelete.handle(data).channel); resolve(this.rest.client.actions.ChannelDelete.handle(data).channel);
}) })
@@ -141,69 +139,70 @@ class RESTMethods{
}); });
} }
UpdateChannel(channel, data) { updateChannel(channel, $data) {
const data = $data;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
data.name = (data.name || channel.name).trim(); data.name = (data.name || channel.name).trim();
data.topic = data.topic || channel.topic; data.topic = data.topic || channel.topic;
data.position = data.position || channel.position; data.position = data.position || channel.position;
data.bitrate = data.bitrate || channel.bitrate; data.bitrate = data.bitrate || channel.bitrate;
this.rest.makeRequest('patch', Constants.Endpoints.CHANNEL(channel.id), true, data) this.rest.makeRequest('patch', Constants.Endpoints.channel(channel.id), true, data)
.then(data => { .then(newData => {
resolve(this.rest.client.actions.ChannelUpdate.handle(data).updated); resolve(this.rest.client.actions.ChannelUpdate.handle(newData).updated);
}) })
.catch(reject); .catch(reject);
}); });
} }
LeaveGuild(guild) { leaveGuild(guild) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('del', Constants.Endpoints.ME_GUILD(guild.id), true) this.rest.makeRequest('del', Constants.Endpoints.meGuild(guild.id), true)
.then(() => { .then(() => {
resolve(this.rest.client.actions.GuildDelete.handle({ id:guild.id }).guild); resolve(this.rest.client.actions.GuildDelete.handle({ id: guild.id }).guild);
}) })
.catch(reject); .catch(reject);
}); });
} }
// untested but probably will work // untested but probably will work
DeleteGuild(guild) { deleteGuild(guild) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('del', Constants.Endpoints.GUILD(guild.id), true) this.rest.makeRequest('del', Constants.Endpoints.guild(guild.id), true)
.then(() => { .then(() => {
resolve(this.rest.client.actions.GuildDelete.handle({ id:guild.id }).guild); resolve(this.rest.client.actions.GuildDelete.handle({ id: guild.id }).guild);
}) })
.catch(reject); .catch(reject);
}); });
} }
UpdateCurrentUser(_data) { updateCurrentUser(_data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let user = this.rest.client.store.user; const user = this.rest.client.store.user;
let data = {}; const data = {};
data.username = _data.username || user.username; data.username = _data.username || user.username;
data.avatar = this.rest.client.resolver.ResolveBase64(_data.avatar) || user.avatar; data.avatar = this.rest.client.resolver.resolveBase64(_data.avatar) || user.avatar;
if (!user.bot) { if (!user.bot) {
data.password = this.rest.client.store.password; data.password = this.rest.client.store.password;
data.email = _data.email || this.rest.client.store.email; data.email = _data.email || this.rest.client.store.email;
data.new_password = _data.newPassword; data.new_password = _data.newPassword;
} }
this.rest.makeRequest('patch', Constants.Endpoints.ME, true, data) this.rest.makeRequest('patch', Constants.Endpoints.me, true, data)
.then(data => resolve(this.rest.client.actions.UserUpdate.handle(data).updated)) .then(newData => resolve(this.rest.client.actions.UserUpdate.handle(newData).updated))
.catch(reject); .catch(reject);
}); });
} }
UpdateGuild(guild, _data) { updateGuild(guild, _data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
/* /*
can contain: can contain:
name, region, verificationLevel, afkChannel, afkTimeout, icon, owner, splash name, region, verificationLevel, afkChannel, afkTimeout, icon, owner, splash
*/ */
let data = {}; const data = {};
if (_data.name) { if (_data.name) {
data.name = _data.name; data.name = _data.name;
@@ -218,7 +217,7 @@ class RESTMethods{
} }
if (_data.afkChannel) { if (_data.afkChannel) {
data.afk_channel_id = this.rest.client.resolver.ResolveChannel(_data.afkChannel).id; data.afk_channel_id = this.rest.client.resolver.resolveChannel(_data.afkChannel).id;
} }
if (_data.afkTimeout) { if (_data.afkTimeout) {
@@ -226,26 +225,26 @@ class RESTMethods{
} }
if (_data.icon) { if (_data.icon) {
data.icon = this.rest.client.resolver.ResolveBase64(_data.icon); data.icon = this.rest.client.resolver.resolveBase64(_data.icon);
} }
if (_data.owner) { if (_data.owner) {
data.owner_id = this.rest.client.resolver.ResolveUser(_data.owner).id; data.owner_id = this.rest.client.resolver.resolveUser(_data.owner).id;
} }
if (_data.splash) { if (_data.splash) {
data.splash = this.rest.client.resolver.ResolveBase64(_data.splash); data.splash = this.rest.client.resolver.resolveBase64(_data.splash);
} }
this.rest.makeRequest('patch', Constants.Endpoints.GUILD(guild.id), true, data) this.rest.makeRequest('patch', Constants.Endpoints.guild(guild.id), true, data)
.then(data => resolve(this.rest.client.actions.GuildUpdate.handle(data).updated)) .then(newData => resolve(this.rest.client.actions.GuildUpdate.handle(newData).updated))
.catch(reject); .catch(reject);
}); });
} }
KickGuildMember(guild, member) { kickGuildMember(guild, member) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('del', Constants.Endpoints.GUILD_MEMBER(guild.id, member.id), true) this.rest.makeRequest('del', Constants.Endpoints.guildMember(guild.id, member.id), true)
.then(() => { .then(() => {
resolve(this.rest.client.actions.GuildMemberRemove.handle({ resolve(this.rest.client.actions.GuildMemberRemove.handle({
guild_id: guild.id, guild_id: guild.id,
@@ -256,9 +255,9 @@ class RESTMethods{
}); });
} }
CreateGuildRole(guild) { createGuildRole(guild) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('post', Constants.Endpoints.GUILD_ROLES(guild.id), true) this.rest.makeRequest('post', Constants.Endpoints.guildRoles(guild.id), true)
.then(role => { .then(role => {
resolve(this.rest.client.actions.GuildRoleCreate.handle({ resolve(this.rest.client.actions.GuildRoleCreate.handle({
guild_id: guild.id, guild_id: guild.id,
@@ -269,9 +268,9 @@ class RESTMethods{
}); });
} }
DeleteGuildRole(role) { deleteGuildRole(role) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.rest.makeRequest('del', Constants.Endpoints.GUILD_ROLE(role.guild.id, role.id), true) this.rest.makeRequest('del', Constants.Endpoints.guildRole(role.guild.id, role.id), true)
.then(() => { .then(() => {
resolve(this.rest.client.actions.GuildRoleDelete.handle({ resolve(this.rest.client.actions.GuildRoleDelete.handle({
guild_id: role.guild.id, guild_id: role.guild.id,
@@ -282,14 +281,14 @@ class RESTMethods{
}); });
} }
UpdateGuildRole(role, _data) { updateGuildRole(role, _data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
/* /*
can contain: can contain:
name, position, permissions, color, hoist name, position, permissions, color, hoist
*/ */
let data = {}; const data = {};
data.name = _data.name || role.name; data.name = _data.name || role.name;
data.position = _data.position || role.position; data.position = _data.position || role.position;
@@ -313,8 +312,8 @@ class RESTMethods{
} else { } else {
data.permissions = role.permissions; data.permissions = role.permissions;
} }
console.log(data);
this.rest.makeRequest('patch', Constants.Endpoints.GUILD_ROLE(role.guild.id, role.id), true, data) this.rest.makeRequest('patch', Constants.Endpoints.guildRole(role.guild.id, role.id), true, data)
.then(_role => { .then(_role => {
resolve(this.rest.client.actions.GuildRoleUpdate.handle({ resolve(this.rest.client.actions.GuildRoleUpdate.handle({
role: _role, role: _role,

View File

@@ -1,8 +1,6 @@
'use strict';
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
class UserAgentManager{ class UserAgentManager {
constructor(restManager) { constructor(restManager) {
this.restManager = restManager; this.restManager = restManager;
this._userAgent = { this._userAgent = {

View File

@@ -1,5 +1,3 @@
'use strict';
const WebSocket = require('ws'); const WebSocket = require('ws');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const zlib = require('zlib'); const zlib = require('zlib');
@@ -18,13 +16,12 @@ class WebSocketManager {
connect(gateway) { connect(gateway) {
this.status = Constants.Status.CONNECTING; this.status = Constants.Status.CONNECTING;
this.store.gateway = gateway; this.store.gateway = `${gateway}/?v=${this.client.options.protocol_version}`;
gateway += `/?v=${this.client.options.protocol_version}`;
this.ws = new WebSocket(gateway); this.ws = new WebSocket(gateway);
this.ws.onopen = () => this.EventOpen(); this.ws.onopen = () => this.eventOpen();
this.ws.onclose = () => this.EventClose(); this.ws.onclose = () => this.eventClose();
this.ws.onmessage = (e) => this.EventMessage(e); this.ws.onmessage = (e) => this.eventMessage(e);
this.ws.onerror = (e) => this.EventError(e); this.ws.onerror = (e) => this.eventError(e);
} }
send(data) { send(data) {
@@ -33,7 +30,7 @@ class WebSocketManager {
} }
} }
EventOpen() { eventOpen() {
if (this.reconnecting) { if (this.reconnecting) {
this._sendResume(); this._sendResume();
} else { } else {
@@ -42,7 +39,7 @@ class WebSocketManager {
} }
_sendResume() { _sendResume() {
let payload = { const payload = {
token: this.client.store.token, token: this.client.store.token,
session_id: this.store.sessionID, session_id: this.store.sessionID,
seq: this.store.sequence, seq: this.store.sequence,
@@ -56,7 +53,7 @@ class WebSocketManager {
_sendNewIdentify() { _sendNewIdentify() {
this.reconnecting = false; this.reconnecting = false;
let payload = this.client.options.ws; const payload = this.client.options.ws;
payload.token = this.client.store.token; payload.token = this.client.store.token;
this.send({ this.send({
@@ -65,14 +62,15 @@ class WebSocketManager {
}); });
} }
EventClose() { eventClose() {
if (!this.reconnecting) { if (!this.reconnecting) {
this.tryReconnect(); this.tryReconnect();
} }
} }
EventMessage(event) { eventMessage($event) {
let packet; let packet;
const event = $event;
try { try {
if (event.binary) { if (event.binary) {
event.data = zlib.inflateSync(event.data).toString(); event.data = zlib.inflateSync(event.data).toString();
@@ -80,13 +78,13 @@ class WebSocketManager {
packet = JSON.parse(event.data); packet = JSON.parse(event.data);
} catch (e) { } catch (e) {
return this.EventError(Constants.Errors.BAD_WS_MESSAGE); return this.eventError(Constants.Errors.BAD_WS_MESSAGE);
} }
this.packetManager.handle(packet); return this.packetManager.handle(packet);
} }
EventError(e) { EventError() {
this.tryReconnect(); this.tryReconnect();
} }
@@ -94,7 +92,7 @@ class WebSocketManager {
if (this.status !== Constants.Status.READY) { if (this.status !== Constants.Status.READY) {
let unavailableCount = 0; let unavailableCount = 0;
for (let guildID in this.client.store.data.guilds) { for (const guildID in this.client.store.data.guilds) {
unavailableCount += this.client.store.data.guilds[guildID].available ? 0 : 1; unavailableCount += this.client.store.data.guilds[guildID].available ? 0 : 1;
} }

View File

@@ -1,5 +1,3 @@
'use strict';
const Constants = require('../../../util/Constants'); const Constants = require('../../../util/Constants');
const BeforeReadyWhitelist = [ const BeforeReadyWhitelist = [
@@ -45,15 +43,15 @@ class WebSocketPacketManager {
} }
register(event, handle) { register(event, handle) {
let Handler = require(`./handlers/${handle}`); const Handler = require(`./handlers/${handle}`);
this.handlers[event] = new Handler(this); this.handlers[event] = new Handler(this);
} }
handleQueue() { handleQueue() {
for (let packetIndex in this.queue) { this.queue.forEach((element, index) => {
this.handle(this.queue[packetIndex]); this.handle(this.queue[index]);
this.queue.splice(packetIndex, 1); this.queue.splice(index, 1);
} });
} }
setSequence(s) { setSequence(s) {
@@ -63,16 +61,15 @@ class WebSocketPacketManager {
} }
handle(packet) { handle(packet) {
if (packet.op === Constants.OPCodes.RECONNECT) { if (packet.op === Constants.OPCodes.RECONNECT) {
this.setSequence(packet.s); this.setSequence(packet.s);
this.ws.tryReconnect(); this.ws.tryReconnect();
return; return false;
} }
if (packet.op === Constants.OPCodes.INVALID_SESSION) { if (packet.op === Constants.OPCodes.INVALID_SESSION) {
this.ws._sendNewIdentify(); this.ws._sendNewIdentify();
return; return false;
} }
if (this.ws.reconnecting) { if (this.ws.reconnecting) {
@@ -85,7 +82,7 @@ class WebSocketPacketManager {
if (this.ws.status !== Constants.Status.READY) { if (this.ws.status !== Constants.Status.READY) {
if (BeforeReadyWhitelist.indexOf(packet.t) === -1) { if (BeforeReadyWhitelist.indexOf(packet.t) === -1) {
this.queue.push(packet); this.queue.push(packet);
return; return false;
} }
} }

View File

@@ -1,5 +1,3 @@
'use strict';
class AbstractHandler { class AbstractHandler {
constructor(packetManager) { constructor(packetManager) {
@@ -7,7 +5,7 @@ class AbstractHandler {
} }
handle(packet) { handle(packet) {
return packet;
} }
} }

View File

@@ -1,32 +1,20 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const DMChannel = Structure('DMChannel');
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
class ChannelCreateHandler extends AbstractHandler { class ChannelCreateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.ChannelCreate.handle(data); const response = client.actions.ChannelCreate.handle(data);
if (response.channel) { if (response.channel) {
client.emit(Constants.Events.CHANNEL_CREATE, response.channel); client.emit(Constants.Events.CHANNEL_CREATE, response.channel);
} }
} }
}; }
module.exports = ChannelCreateHandler; module.exports = ChannelCreateHandler;

View File

@@ -1,31 +1,20 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const ServerChannel = Structure('ServerChannel');
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
class ChannelDeleteHandler extends AbstractHandler { class ChannelDeleteHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.ChannelDelete.handle(data); const response = client.actions.ChannelDelete.handle(data);
if (response.channel) { if (response.channel) {
client.emit(Constants.Events.CHANNEL_DELETE, response.channel); client.emit(Constants.Events.CHANNEL_DELETE, response.channel);
} }
} }
}; }
module.exports = ChannelDeleteHandler; module.exports = ChannelDeleteHandler;

View File

@@ -1,28 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const ServerChannel = Structure('ServerChannel');
const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
class ChannelUpdateHandler extends AbstractHandler { class ChannelUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
client.actions.ChannelUpdate.handle(data); client.actions.ChannelUpdate.handle(data);
} }
}; }
module.exports = ChannelUpdateHandler; module.exports = ChannelUpdateHandler;

View File

@@ -1,33 +1,22 @@
'use strict';
// ##untested handler## // ##untested handler##
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
class GuildBanAddHandler extends AbstractHandler { class GuildBanAddHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
let user = client.store.get('users', data.user.id); const user = client.store.get('users', data.user.id);
if (guild && user) { if (guild && user) {
client.emit(Constants.Events.GUILD_BAN_ADD, guild, user); client.emit(Constants.Events.GUILD_BAN_ADD, guild, user);
} }
} }
}; }
module.exports = GuildBanAddHandler; module.exports = GuildBanAddHandler;

View File

@@ -1,33 +1,23 @@
'use strict';
// ##untested handler## // ##untested handler##
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
class GuildBanRemoveHandler extends AbstractHandler { class GuildBanRemoveHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
let user = client.store.get('users', data.user.id); const user = client.store.get('users', data.user.id);
if (guild && user) { if (guild && user) {
client.emit(Constants.Events.GUILD_BAN_REMOVE, guild, user); client.emit(Constants.Events.GUILD_BAN_REMOVE, guild, user);
} }
} }
}; }
module.exports = GuildBanRemoveHandler; module.exports = GuildBanRemoveHandler;

View File

@@ -1,24 +1,12 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants');
class GuildCreateHandler extends AbstractHandler { class GuildCreateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.id); const guild = client.store.get('guilds', data.id);
if (guild) { if (guild) {
if (!guild.available && !data.unavailable) { if (!guild.available && !data.unavailable) {
@@ -28,11 +16,10 @@ class GuildCreateHandler extends AbstractHandler {
} }
} else { } else {
// a new guild // a new guild
client.store.NewGuild(data); client.store.newGuild(data);
}
} }
} }
};
module.exports = GuildCreateHandler; module.exports = GuildCreateHandler;

View File

@@ -1,31 +1,19 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
class GuildDeleteHandler extends AbstractHandler { class GuildDeleteHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.GuildDelete.handle(data); const response = client.actions.GuildDelete.handle(data);
if (response.guild) { if (response.guild) {
client.emit(Constants.Events.GUILD_DELETE, response.guild); client.emit(Constants.Events.GUILD_DELETE, response.guild);
} }
} }
}; }
module.exports = GuildDeleteHandler; module.exports = GuildDeleteHandler;

View File

@@ -1,32 +1,20 @@
'use strict';
// ##untested handler## // ##untested handler##
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants');
class GuildMemberAddHandler extends AbstractHandler { class GuildMemberAddHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
if (guild) { if (guild) {
guild._addMember(data); guild._addMember(data);
} }
} }
}; }
module.exports = GuildMemberAddHandler; module.exports = GuildMemberAddHandler;

View File

@@ -1,28 +1,16 @@
'use strict';
// ##untested handler## // ##untested handler##
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants');
class GuildMemberRemoveHandler extends AbstractHandler { class GuildMemberRemoveHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.GuildMemberRemove.handle(data); client.actions.GuildMemberRemove.handle(data);
} }
}; }
module.exports = GuildMemberRemoveHandler; module.exports = GuildMemberRemoveHandler;

View File

@@ -1,35 +1,23 @@
'use strict';
// ##untested handler## // ##untested handler##
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants');
class GuildMemberUpdateHandler extends AbstractHandler { class GuildMemberUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
if (guild) { if (guild) {
let member = guild.store.get('members', data.user.id); const member = guild.store.get('members', data.user.id);
if (member) { if (member) {
guild._updateMember(member, data); guild._updateMember(member, data);
} }
} }
} }
}; }
module.exports = GuildMemberUpdateHandler; module.exports = GuildMemberUpdateHandler;

View File

@@ -1,26 +1,18 @@
'use strict';
// ##untested## // ##untested##
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
class GuildMembersChunkHandler extends AbstractHandler { class GuildMembersChunkHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
let members = []; const members = [];
if (guild) { if (guild) {
for (let member of guild.members) { for (const member of guild.members) {
members.push(guild._addMember(member, true)); members.push(guild._addMember(member, true));
} }
} }
@@ -28,6 +20,6 @@ class GuildMembersChunkHandler extends AbstractHandler {
client.emit(Constants.Events.GUILD_MEMBERS_CHUNK, guild, members); client.emit(Constants.Events.GUILD_MEMBERS_CHUNK, guild, members);
} }
}; }
module.exports = GuildMembersChunkHandler; module.exports = GuildMembersChunkHandler;

View File

@@ -1,25 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants');
const Role = Structure('Role');
const Guild = Structure('Guild');
class GuildRoleCreateHandler extends AbstractHandler { class GuildRoleCreateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.GuildRoleCreate.handle(data); client.actions.GuildRoleCreate.handle(data);
} }
}; }
module.exports = GuildRoleCreateHandler; module.exports = GuildRoleCreateHandler;

View File

@@ -1,25 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants');
const Role = Structure('Role');
const Guild = Structure('Guild');
class GuildRoleDeleteHandler extends AbstractHandler { class GuildRoleDeleteHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.GuildRoleDelete.handle(data); client.actions.GuildRoleDelete.handle(data);
} }
}; }
module.exports = GuildRoleDeleteHandler; module.exports = GuildRoleDeleteHandler;

View File

@@ -1,26 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
const Role = Structure('Role');
const Guild = Structure('Guild');
class GuildRoleUpdateHandler extends AbstractHandler { class GuildRoleUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.GuildRoleUpdate.handle(data); client.actions.GuildRoleUpdate.handle(data);
} }
}; }
module.exports = GuildRoleUpdateHandler; module.exports = GuildRoleUpdateHandler;

View File

@@ -1,28 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
class GuildUpdateHandler extends AbstractHandler { class GuildUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.GuildUpdate.handle(data);
client.actions.GuildUpdate.handle(data);
} }
}; }
module.exports = GuildUpdateHandler; module.exports = GuildUpdateHandler;

View File

@@ -1,29 +1,19 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
const Message = Structure('Message');
const Guild = Structure('Guild');
class MessageCreateHandler extends AbstractHandler { class MessageCreateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.MessageCreate.handle(data); const response = client.actions.MessageCreate.handle(data);
if (response.m) { if (response.m) {
client.emit(Constants.Events.MESSAGE_CREATE, response.m); client.emit(Constants.Events.MESSAGE_CREATE, response.m);
} }
} }
}; }
module.exports = MessageCreateHandler; module.exports = MessageCreateHandler;

View File

@@ -1,29 +1,19 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
const Message = Structure('Message');
const Guild = Structure('Guild');
class MessageDeleteHandler extends AbstractHandler { class MessageDeleteHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.MessageDelete.handle(data); const response = client.actions.MessageDelete.handle(data);
if (response.m) { if (response.m) {
client.emit(Constants.Events.MESSAGE_DELETE, response.m); client.emit(Constants.Events.MESSAGE_DELETE, response.m);
} }
} }
}; }
module.exports = MessageDeleteHandler; module.exports = MessageDeleteHandler;

View File

@@ -1,27 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
const Message = Structure('Message');
const Guild = Structure('Guild');
class MessageUpdateHandler extends AbstractHandler { class MessageUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.MessageUpdate.handle(data);
client.actions.MessageUpdate.handle(data);
} }
}; }
module.exports = MessageUpdateHandler; module.exports = MessageUpdateHandler;

View File

@@ -1,41 +1,32 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject'); const cloneObject = require('../../../../util/CloneObject');
const Role = Structure('User');
class PresenceUpdateHandler extends AbstractHandler { class PresenceUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let user = client.store.get('users', data.user.id); let user = client.store.get('users', data.user.id);
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
function makeUser(user) { function makeUser(newUser) {
return client.store.NewUser(user); return client.store.newUser(newUser);
} }
// step 1 // step 1
if (!user) { if (!user) {
if (data.user.username) { if (data.user.username) {
user = makeUser(data.user); user = makeUser(data.user);
}else { } else {
return; return;
} }
} }
if (guild) { if (guild) {
let memberInGuild = guild.store.get('members', user.id); const memberInGuild = guild.store.get('members', user.id);
if (!memberInGuild) { if (!memberInGuild) {
let member = guild._addMember({ const member = guild._addMember({
user, user,
roles: data.roles, roles: data.roles,
deaf: false, deaf: false,
@@ -54,7 +45,7 @@ class PresenceUpdateHandler extends AbstractHandler {
data.user.status = data.status || user.status; data.user.status = data.status || user.status;
data.user.game = data.game; data.user.game = data.game;
let same = ( const same = (
data.user.username === user.username && data.user.username === user.username &&
data.user.id === user.id && data.user.id === user.id &&
data.user.discriminator === user.discriminator && data.user.discriminator === user.discriminator &&
@@ -64,12 +55,12 @@ class PresenceUpdateHandler extends AbstractHandler {
); );
if (!same) { if (!same) {
let oldUser = CloneObject(user); const oldUser = cloneObject(user);
user.setup(data.user); user.setup(data.user);
client.emit(Constants.Events.PRESENCE_UPDATE, oldUser, user); client.emit(Constants.Events.PRESENCE_UPDATE, oldUser, user);
} }
} }
}; }
module.exports = PresenceUpdateHandler; module.exports = PresenceUpdateHandler;

View File

@@ -1,39 +1,30 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser'); const getStructure = name => require(`../../../../structures/${name}`);
const Guild = Structure('Guild'); const ClientUser = getStructure('ClientUser');
const DMChannel = Structure('DMChannel');
class ReadyHandler extends AbstractHandler { class ReadyHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
client.manager.setupKeepAlive(data.heartbeat_interval); client.manager.setupKeepAlive(data.heartbeat_interval);
client.store.user = client.store.add('users', new ClientUser(client, data.user)); client.store.user = client.store.add('users', new ClientUser(client, data.user));
for (let guild of data.guilds) { for (const guild of data.guilds) {
client.store.NewGuild(guild); client.store.newGuild(guild);
} }
for (let privateDM of data.private_channels) { for (const privateDM of data.private_channels) {
client.store.NewChannel(privateDM); client.store.newChannel(privateDM);
} }
this.packetManager.ws.store.sessionID = data.session_id; this.packetManager.ws.store.sessionID = data.session_id;
this.packetManager.ws.checkIfReady(); this.packetManager.ws.checkIfReady();
} }
}; }
module.exports = ReadyHandler; module.exports = ReadyHandler;

View File

@@ -1,9 +1,5 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants'); const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
class TypingData { class TypingData {
constructor(since, lastTimestamp, _timeout) { constructor(since, lastTimestamp, _timeout) {
@@ -24,28 +20,12 @@ class TypingData {
class TypingStartHandler extends AbstractHandler { class TypingStartHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let channel = client.store.get('channels', data.channel_id); const channel = client.store.get('channels', data.channel_id);
let user = client.store.get('users', data.user_id); const user = client.store.get('users', data.user_id);
let timestamp = new Date(data.timestamp * 1000); const timestamp = new Date(data.timestamp * 1000);
if (channel && user) {
if (channel.typingMap[user.id]) {
// already typing, renew
let mapping = channel.typingMap[user.id];
mapping.lastTimestamp = timestamp;
mapping.resetTimeout(tooLate());
} else {
channel.typingMap[user.id] = new TypingData(timestamp, timestamp, tooLate());
client.emit(Constants.Events.TYPING_START, channel, user);
}
}
function tooLate() { function tooLate() {
return setTimeout(() => { return setTimeout(() => {
@@ -53,8 +33,20 @@ class TypingStartHandler extends AbstractHandler {
delete channel.typingMap[user.id]; delete channel.typingMap[user.id];
}, 6000); }, 6000);
} }
if (channel && user) {
if (channel.typingMap[user.id]) {
// already typing, renew
const mapping = channel.typingMap[user.id];
mapping.lastTimestamp = timestamp;
mapping.resetTimeout(tooLate());
} else {
channel.typingMap[user.id] = new TypingData(timestamp, timestamp, tooLate());
client.emit(Constants.Events.TYPING_START, channel, user);
}
}
} }
}; }
module.exports = TypingStartHandler; module.exports = TypingStartHandler;

View File

@@ -1,28 +1,14 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const CloneObject = name => require(`../../../../util/CloneObject`);
const Constants = require(`../../../../util/Constants`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const DMChannel = Structure('DMChannel');
class UserUpdateHandler extends AbstractHandler { class UserUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let response = client.actions.UserUpdate.handle(data);
client.actions.UserUpdate.handle(data);
} }
}; }
module.exports = UserUpdateHandler; module.exports = UserUpdateHandler;

View File

@@ -1,28 +1,19 @@
'use strict';
const AbstractHandler = require('./AbstractHandler'); const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const Constants = require('../../../../util/Constants');
const CloneObject = require('../../../../util/CloneObject');
const Role = Structure('User'); const Constants = require('../../../../util/Constants');
const cloneObject = require('../../../../util/CloneObject');
class VoiceStateUpdateHandler extends AbstractHandler { class VoiceStateUpdateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) { handle(packet) {
let data = packet.d; const data = packet.d;
let client = this.packetManager.client; const client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id); const guild = client.store.get('guilds', data.guild_id);
if (guild) { if (guild) {
let member = guild.store.get('members', data.user_id); const member = guild.store.get('members', data.user_id);
let channel = guild.store.get('channels', data.channel_id);
if (member) { if (member) {
let oldVoiceChannelMember = CloneObject(member); const oldVoiceChannelMember = cloneObject(member);
if (member.voiceChannel && member.voiceChannel.id !== data.channel_id) { if (member.voiceChannel && member.voiceChannel.id !== data.channel_id) {
member.voiceChannel.store.remove('members', oldVoiceChannelMember); member.voiceChannel.store.remove('members', oldVoiceChannelMember);
} }
@@ -38,6 +29,6 @@ class VoiceStateUpdateHandler extends AbstractHandler {
} }
} }
}; }
module.exports = VoiceStateUpdateHandler; module.exports = VoiceStateUpdateHandler;

View File

@@ -1,5 +1,3 @@
'use strict';
const values = require('object.values'); const values = require('object.values');
const Client = require('./client/Client'); const Client = require('./client/Client');

View File

@@ -1,5 +1,3 @@
'use strict';
class Channel { class Channel {
constructor(client, data, guild) { constructor(client, data, guild) {
this.client = client; this.client = client;
@@ -19,7 +17,7 @@ class Channel {
} }
delete() { delete() {
return this.client.rest.methods.DeleteChannel(this); return this.client.rest.methods.deleteChannel(this);
} }
} }

View File

@@ -1,12 +1,6 @@
'use strict';
const User = require('./User'); const User = require('./User');
class ClientUser extends User { class ClientUser extends User {
constructor(client, data) {
super(client, data);
}
setup(data) { setup(data) {
super.setup(data); super.setup(data);
this.verified = data.verified; this.verified = data.verified;
@@ -14,23 +8,23 @@ class ClientUser extends User {
} }
setUsername(username) { setUsername(username) {
return this.client.rest.methods.UpdateCurrentUser({ username, }); return this.client.rest.methods.updateCurrentUser({ username });
} }
setEmail(email) { setEmail(email) {
return this.client.rest.methods.UpdateCurrentUser({ email, }); return this.client.rest.methods.updateCurrentUser({ email });
} }
setPassword(password) { setPassword(password) {
return this.client.rest.methods.UpdateCurrentUser({ password, }); return this.client.rest.methods.updateCurrentUser({ password });
} }
setAvatar(avatar) { setAvatar(avatar) {
return this.client.rest.methods.UpdateCurrentUser({ avatar, }); return this.client.rest.methods.updateCurrentUser({ avatar });
} }
edit(data) { edit(data) {
return this.client.rest.methods.UpdateCurrentUser(data); return this.client.rest.methods.updateCurrentUser(data);
} }
} }

View File

@@ -1,24 +1,22 @@
'use strict';
const Channel = require('./Channel'); const Channel = require('./Channel');
const TextBasedChannel = require('./interface/TextBasedChannel'); const TextBasedChannel = require('./interface/TextBasedChannel');
const User = require('./User'); const User = require('./User');
const TextChannelDataStore = require('./datastore/TextChannelDataStore'); const TextChannelDataStore = require('./datastore/TextChannelDataStore');
class DMChannel extends Channel{ class DMChannel extends Channel {
constructor(client, data) { constructor(client, data) {
super(client, data); super(client, data);
this.store = new TextChannelDataStore(); this.store = new TextChannelDataStore();
} }
_cacheMessage(message) { _cacheMessage(message) {
let maxSize = this.client.options.max_message_cache; const maxSize = this.client.options.max_message_cache;
if (maxSize === 0) { if (maxSize === 0) {
// saves on performance // saves on performance
return; return;
} }
let storeKeys = Object.keys(this.store); const storeKeys = Object.keys(this.store);
if (storeKeys.length >= maxSize) { if (storeKeys.length >= maxSize) {
this.store.remove(storeKeys[0]); this.store.remove(storeKeys[0]);
} }

View File

@@ -1,6 +1,4 @@
'use strict'; const Constants = require('../util/Constants');
const Constants = require('../Util/Constants');
class EvaluatedPermissions { class EvaluatedPermissions {
constructor(member, permissions) { constructor(member, permissions) {
@@ -9,8 +7,8 @@ class EvaluatedPermissions {
} }
serialize() { serialize() {
let serializedPermissions = {}; const serializedPermissions = {};
for (let permissionName in Constants.PermissionFlags) { for (const permissionName in Constants.PermissionFlags) {
serializedPermissions[permissionName] = this.hasPermission(permissionName); serializedPermissions[permissionName] = this.hasPermission(permissionName);
} }

View File

@@ -1,20 +1,16 @@
'use strict';
const User = require('./User'); const User = require('./User');
const GuildMember = require('./GuildMember'); const GuildMember = require('./GuildMember');
const GuildDataStore = require('./datastore/GuildDataStore'); const GuildDataStore = require('./datastore/GuildDataStore');
const TextChannel = require('./TextChannel'); const Constants = require('../util/Constants');
const VoiceChannel = require('./VoiceChannel');
const Constants = require('../Util/Constants');
const Role = require('./Role'); const Role = require('./Role');
function arraysEqual(a, b) { function arraysEqual(a, b) {
if (a === b) return true; if (a === b) return true;
if (a.length !== b.length) return false; if (a.length !== b.length) return false;
for (let itemInd in a) { for (const itemInd in a) {
let item = a[itemInd]; const item = a[itemInd];
let ind = b.indexOf(item); const ind = b.indexOf(item);
if (ind) { if (ind) {
b.splice(ind, 1); b.splice(ind, 1);
} }
@@ -43,11 +39,11 @@ class Guild {
_addMember(guildUser, noEvent) { _addMember(guildUser, noEvent) {
if (!(guildUser.user instanceof User)) { if (!(guildUser.user instanceof User)) {
guildUser.user = this.client.store.NewUser(guildUser.user); guildUser.user = this.client.store.newUser(guildUser.user);
} }
guildUser.joined_at = guildUser.joined_at || 0; guildUser.joined_at = guildUser.joined_at || 0;
let member = this.store.add('members', new GuildMember(this, guildUser)); const member = this.store.add('members', new GuildMember(this, guildUser));
if (this.client.ws.status === Constants.Status.READY && !noEvent) { if (this.client.ws.status === Constants.Status.READY && !noEvent) {
this.client.emit(Constants.Events.GUILD_MEMBER_ADD, this, member); this.client.emit(Constants.Events.GUILD_MEMBER_ADD, this, member);
} }
@@ -56,7 +52,7 @@ class Guild {
} }
_updateMember(member, data) { _updateMember(member, data) {
let oldRoles = member.roles; const oldRoles = member.roles;
member._roles = data.roles; member._roles = data.roles;
if (this.client.ws.status === Constants.Status.READY) { if (this.client.ws.status === Constants.Status.READY) {
@@ -77,7 +73,7 @@ class Guild {
} }
member(user) { member(user) {
return this.client.resolver.ResolveGuildMember(this, user); return this.client.resolver.resolveGuildMember(this, user);
} }
equals(data) { equals(data) {
@@ -128,7 +124,7 @@ class Guild {
if (data.members) { if (data.members) {
this.store.clear('members'); this.store.clear('members');
for (let guildUser of data.members) { for (const guildUser of data.members) {
this._addMember(guildUser); this._addMember(guildUser);
} }
} }
@@ -137,8 +133,8 @@ class Guild {
if (data.channels) { if (data.channels) {
this.store.clear('channels'); this.store.clear('channels');
for (let channel of data.channels) { for (const channel of data.channels) {
this.client.store.NewChannel(channel, this); this.client.store.newChannel(channel, this);
} }
} }
@@ -146,14 +142,14 @@ class Guild {
if (data.roles) { if (data.roles) {
this.store.clear('roles'); this.store.clear('roles');
for (let role of data.roles) { for (const role of data.roles) {
this.store.add('roles', new Role(this, role)); this.store.add('roles', new Role(this, role));
} }
} }
if (data.presences) { if (data.presences) {
for (let presence of data.presences) { for (const presence of data.presences) {
let user = this.client.store.get('users', presence.user.id); const user = this.client.store.get('users', presence.user.id);
if (user) { if (user) {
user.status = presence.status; user.status = presence.status;
user.game = presence.game; user.game = presence.game;
@@ -162,8 +158,8 @@ class Guild {
} }
if (data.voice_states) { if (data.voice_states) {
for (let voiceState of data.voice_states) { for (const voiceState of data.voice_states) {
let member = this.store.get('members', voiceState.user_id); const member = this.store.get('members', voiceState.user_id);
if (member) { if (member) {
member.serverMute = voiceState.mute; member.serverMute = voiceState.mute;
member.serverDeaf = voiceState.deaf; member.serverDeaf = voiceState.deaf;
@@ -177,55 +173,55 @@ class Guild {
} }
createChannel(name, type) { createChannel(name, type) {
return this.client.rest.methods.CreateChannel(this, name, type); return this.client.rest.methods.createChannel(this, name, type);
} }
createRole() { createRole() {
return this.client.rest.methods.CreateGuildRole(this); return this.client.rest.methods.createGuildRole(this);
} }
leave() { leave() {
return this.client.rest.methods.LeaveGuild(this); return this.client.rest.methods.leaveGuild(this);
} }
delete() { delete() {
return this.client.rest.methods.DeleteGuild(this); return this.client.rest.methods.deleteGuild(this);
} }
edit(data) { edit(data) {
return this.client.rest.methods.UpdateGuild(this, data); return this.client.rest.methods.updateGuild(this, data);
} }
setName(name) { setName(name) {
return this.edit({ name, }); return this.edit({ name });
} }
setRegion(region) { setRegion(region) {
return this.edit({ region, }); return this.edit({ region });
} }
setVerificationLevel(verificationLevel) { setVerificationLevel(verificationLevel) {
return this.edit({ verificationLevel, }); return this.edit({ verificationLevel });
} }
setAFKChannel(afkchannel) { setAFKChannel(afkChannel) {
return this.edit({ afkChannel, }); return this.edit({ afkChannel });
} }
setAFKTimeout(afkTimeout) { setAFKTimeout(afkTimeout) {
return this.edit({ afkTimeout, }); return this.edit({ afkTimeout });
} }
setIcon(icon) { setIcon(icon) {
return this.edit({ icon, }); return this.edit({ icon });
} }
setOwner(owner) { setOwner(owner) {
return this.edit({ owner, }); return this.edit({ owner });
} }
setSplash(splash) { setSplash(splash) {
return this.edit({ splash, }); return this.edit({ splash });
} }
get channels() { return this.store.getAsArray('channels'); } get channels() { return this.store.getAsArray('channels'); }

View File

@@ -1,5 +1,3 @@
'use strict';
const TextBasedChannel = require('./interface/TextBasedChannel'); const TextBasedChannel = require('./interface/TextBasedChannel');
class GuildMember { class GuildMember {
@@ -26,15 +24,15 @@ class GuildMember {
} }
get roles() { get roles() {
let list = []; const list = [];
let everyoneRole = this.guild.store.get('roles', this.guild.id); const everyoneRole = this.guild.store.get('roles', this.guild.id);
if (everyoneRole) { if (everyoneRole) {
list.push(everyoneRole); list.push(everyoneRole);
} }
for (let roleID of this._roles) { for (const roleID of this._roles) {
let role = this.guild.store.get('roles', roleID); const role = this.guild.store.get('roles', roleID);
if (role) { if (role) {
list.push(role); list.push(role);
} }
@@ -60,11 +58,11 @@ class GuildMember {
} }
deleteDM() { deleteDM() {
return this.client.rest.methods.DeleteChannel(this); return this.client.rest.methods.deleteChannel(this);
} }
kick() { kick() {
return this.client.rest.methods.KickGuildMember(this.guild, this); return this.client.rest.methods.kickGuildMember(this.guild, this);
} }
} }

View File

@@ -1,5 +1,3 @@
'use strict';
class Message { class Message {
constructor(channel, data, client) { constructor(channel, data, client) {
this.channel = channel; this.channel = channel;
@@ -15,7 +13,7 @@ class Message {
} }
setup(data) { setup(data) {
this.author = this.client.store.NewUser(data.author); this.author = this.client.store.newUser(data.author);
this.content = data.content; this.content = data.content;
this.timestamp = new Date(data.timestamp); this.timestamp = new Date(data.timestamp);
this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp) : null; this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
@@ -26,61 +24,70 @@ class Message {
this.attachments = data.attachments; this.attachments = data.attachments;
this.mentions = []; this.mentions = [];
this.id = data.id; this.id = data.id;
for (let mention of data.mentions) { for (const mention of data.mentions) {
let user = this.client.store.get('users', mention.id); let user = this.client.store.get('users', mention.id);
if (user) { if (user) {
this.mentions.push(user); this.mentions.push(user);
} else { } else {
user = this.client.store.NewUser(mention); user = this.client.store.newUser(mention);
this.mentions.push(user); this.mentions.push(user);
} }
} }
} }
patch(data) { patch(data) {
if (data.author) if (data.author) {
this.author = this.client.store.get('users', data.author.id); this.author = this.client.store.get('users', data.author.id);
if (data.content) }
if (data.content) {
this.content = data.content; this.content = data.content;
if (data.timestamp) }
if (data.timestamp) {
this.timestamp = new Date(data.timestamp); this.timestamp = new Date(data.timestamp);
if (data.edited_timestamp) }
if (data.edited_timestamp) {
this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp) : null; this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp) : null;
if (data.tts) }
if (data.tts) {
this.tts = data.tts; this.tts = data.tts;
if (data.mention_everyone) }
if (data.mention_everyone) {
this.mentionEveryone = data.mention_everyone; this.mentionEveryone = data.mention_everyone;
if (data.nonce) }
if (data.nonce) {
this.nonce = data.nonce; this.nonce = data.nonce;
if (data.embeds) }
if (data.embeds) {
this.embeds = data.embeds; this.embeds = data.embeds;
if (data.attachments) }
if (data.attachments) {
this.attachments = data.attachments; this.attachments = data.attachments;
}
if (data.mentions) { if (data.mentions) {
for (let mention of data.mentions) { for (const mention of data.mentions) {
let user = this.client.store.get('users', mention.id); let user = this.client.store.get('users', mention.id);
if (user) { if (user) {
this.mentions.push(user); this.mentions.push(user);
} else { } else {
user = this.client.store.NewUser(mention); user = this.client.store.newUser(mention);
this.mentions.push(user); this.mentions.push(user);
} }
} }
} }
if (data.id) if (data.id) {
this.id = data.id; this.id = data.id;
} }
}
equals(message, rawData) { equals(message, rawData) {
const embedUpdate = !message.author && !message.attachments;
let embedUpdate = !message.author && !message.attachments;
if (embedUpdate) { if (embedUpdate) {
let base = this.id === message.id && const base = this.id === message.id &&
this.embeds.length === message.embeds.length; this.embeds.length === message.embeds.length;
return base; return base;
} else { }
let base = this.id === message.id && let base = this.id === message.id &&
this.author.id === message.author.id && this.author.id === message.author.id &&
this.content === message.content && this.content === message.content &&
@@ -91,20 +98,19 @@ class Message {
if (base && rawData) { if (base && rawData) {
base = this.mentionEveryone === message.mentionEveryone && base = this.mentionEveryone === message.mentionEveryone &&
this.timestamp.getTime() === new Date(data.timestamp).getTime() && this.timestamp.getTime() === new Date(rawData.timestamp).getTime() &&
this.editedTimestamp === new Date(data.edited_timestamp).getTime(); this.editedTimestamp === new Date(rawData.edited_timestamp).getTime();
} }
return base; return base;
} }
}
delete() { delete() {
return this.client.rest.methods.DeleteMessage(this); return this.client.rest.methods.deleteMessage(this);
} }
edit(content) { edit(content) {
return this.client.rest.methods.UpdateMessage(this, content); return this.client.rest.methods.updateMessage(this, content);
} }
} }

View File

@@ -1,5 +1,3 @@
'use strict';
class PermissionOverwrites { class PermissionOverwrites {
constructor(serverChannel, data) { constructor(serverChannel, data) {
this.channel = serverChannel; this.channel = serverChannel;

View File

@@ -1,6 +1,4 @@
'use strict'; const Constants = require('../util/Constants');
const Constants = require('../Util/Constants');
class Role { class Role {
constructor(guild, data) { constructor(guild, data) {
@@ -34,36 +32,36 @@ class Role {
} }
delete() { delete() {
return this.client.rest.methods.DeleteGuildRole(this); return this.client.rest.methods.deleteGuildRole(this);
} }
edit(data) { edit(data) {
return this.client.rest.methods.UpdateGuildRole(this, data); return this.client.rest.methods.updateGuildRole(this, data);
} }
setName(name) { setName(name) {
return this.client.rest.methods.UpdateGuildRole(this, {name,}); return this.client.rest.methods.updateGuildRole(this, { name });
} }
setColor(color) { setColor(color) {
return this.client.rest.methods.UpdateGuildRole(this, {color,}); return this.client.rest.methods.updateGuildRole(this, { color });
} }
setHoist(hoist) { setHoist(hoist) {
return this.client.rest.methods.UpdateGuildRole(this, {hoist,}); return this.client.rest.methods.updateGuildRole(this, { hoist });
} }
setPosition(position) { setPosition(position) {
return this.client.rest.methods.UpdateGuildRole(this, {position,}); return this.client.rest.methods.updateGuildRole(this, { position });
} }
setPermissions(permissions) { setPermissions(permissions) {
return this.client.rest.methods.UpdateGuildRole(this, {permissions,}); return this.client.rest.methods.updateGuildRole(this, { permissions });
} }
serialize() { serialize() {
let serializedPermissions = {}; const serializedPermissions = {};
for (let permissionName in Constants.PermissionFlags) { for (const permissionName in Constants.PermissionFlags) {
serializedPermissions[permissionName] = this.hasPermission(permissionName); serializedPermissions[permissionName] = this.hasPermission(permissionName);
} }

View File

@@ -1,5 +1,3 @@
'use strict';
const Channel = require('./Channel'); const Channel = require('./Channel');
const PermissionOverwrites = require('./PermissionOverwrites'); const PermissionOverwrites = require('./PermissionOverwrites');
const EvaluatedPermissions = require('./EvaluatedPermissions'); const EvaluatedPermissions = require('./EvaluatedPermissions');
@@ -9,9 +7,9 @@ function arraysEqual(a, b) {
if (a === b) return true; if (a === b) return true;
if (a.length !== b.length) return false; if (a.length !== b.length) return false;
for (let itemInd in a) { for (const itemInd in a) {
let item = a[itemInd]; const item = a[itemInd];
let ind = b.indexOf(item); const ind = b.indexOf(item);
if (ind) { if (ind) {
b.splice(ind, 1); b.splice(ind, 1);
} }
@@ -20,7 +18,7 @@ function arraysEqual(a, b) {
return b.length === 0; return b.length === 0;
} }
class ServerChannel extends Channel{ class ServerChannel extends Channel {
constructor(guild, data) { constructor(guild, data) {
super(guild.client, data, guild); super(guild.client, data, guild);
} }
@@ -35,7 +33,7 @@ class ServerChannel extends Channel{
this.ow = data.permission_overwrites; this.ow = data.permission_overwrites;
this.permissionOverwrites = []; this.permissionOverwrites = [];
if (data.permission_overwrites) { if (data.permission_overwrites) {
for (let overwrite of data.permission_overwrites) { for (const overwrite of data.permission_overwrites) {
this.permissionOverwrites.push(new PermissionOverwrites(this, overwrite)); this.permissionOverwrites.push(new PermissionOverwrites(this, overwrite));
} }
} }
@@ -52,8 +50,8 @@ class ServerChannel extends Channel{
if (base) { if (base) {
if (other.permission_overwrites) { if (other.permission_overwrites) {
let thisIDSet = this.permissionOverwrites.map(overwrite => overwrite.id); const thisIDSet = this.permissionOverwrites.map(overwrite => overwrite.id);
let otherIDSet = other.permission_overwrites.map(overwrite => overwrite.id); const otherIDSet = other.permission_overwrites.map(overwrite => overwrite.id);
if (arraysEqual(thisIDSet, otherIDSet)) { if (arraysEqual(thisIDSet, otherIDSet)) {
base = true; base = true;
} else { } else {
@@ -68,45 +66,45 @@ class ServerChannel extends Channel{
} }
permissionsFor(member) { permissionsFor(member) {
member = this.client.resolver.ResolveGuildMember(this.guild, member); member = this.client.resolver.resolveGuildMember(this.guild, member);
if (member) { if (member) {
if (this.guild.owner.id === member.id) { if (this.guild.owner.id === member.id) {
return new EvaluatedPermissions(member, Constants.ALL_PERMISSIONS); return new EvaluatedPermissions(member, Constants.ALL_PERMISSIONS);
} }
let roles = member.roles; const roles = member.roles;
let permissions = 0; let permissions = 0;
let overwrites = this.overwritesFor(member, true); const overwrites = this.overwritesFor(member, true);
for (let role of roles) { for (const role of roles) {
permissions |= role.permissions; permissions |= role.permissions;
} }
for (let overwrite of overwrites.role.concat(overwrites.member)) { for (const overwrite of overwrites.role.concat(overwrites.member)) {
permissions = permissions & ~overwrite.denyData; permissions &= ~overwrite.denyData;
permissions = permissions | overwrite.allowData; permissions |= overwrite.allowData;
} }
if (!!(permissions & (Constants.PermissionFlags.MANAGE_ROLES))) { const admin = Boolean(permissions & (Constants.PermissionFlags.MANAGE_ROLES));
if (admin) {
permissions = Constants.ALL_PERMISSIONS; permissions = Constants.ALL_PERMISSIONS;
} }
return new EvaluatedPermissions(member, permissions); return new EvaluatedPermissions(member, permissions);
} }
return null;
} }
overwritesFor(member, verified) { overwritesFor(member, verified) {
// for speed // for speed
if (!verified) if (!verified) member = this.client.resolver.resolveGuildMember(this.guild, member);
member = this.client.resolver.ResolveGuildMember(this.guild, member);
if (member) { if (member) {
let found = []; const memberRoles = member._roles;
let memberRoles = member._roles;
let roleOverwrites = []; const roleOverwrites = [];
let memberOverwrites = []; const memberOverwrites = [];
for (let overwrite of this.permissionOverwrites) { for (const overwrite of this.permissionOverwrites) {
if (overwrite.id === member.id) { if (overwrite.id === member.id) {
memberOverwrites.push(overwrite); memberOverwrites.push(overwrite);
} else if (memberRoles.indexOf(overwrite.id) > -1) { } else if (memberRoles.indexOf(overwrite.id) > -1) {
@@ -124,23 +122,23 @@ class ServerChannel extends Channel{
} }
edit(data) { edit(data) {
return this.client.rest.methods.UpdateChannel(this, data); return this.client.rest.methods.updateChannel(this, data);
} }
setName(name) { setName(name) {
return this.client.rest.methods.UpdateChannel(this, { name, }); return this.client.rest.methods.updateChannel(this, { name });
} }
setPosition(position) { setPosition(position) {
return this.rest.client.rest.methods.UpdateChannel(this, { position, }); return this.rest.client.rest.methods.updateChannel(this, { position });
} }
setTopic(topic) { setTopic(topic) {
return this.rest.client.rest.methods.UpdateChannel(this, { topic, }); return this.rest.client.rest.methods.updateChannel(this, { topic });
} }
setBitrate() { setBitrate(bitrate) {
return this.rest.client.rest.methods.UpdateChannel(this, { bitrate, }); return this.rest.client.rest.methods.updateChannel(this, { bitrate });
} }
toString() { toString() {

View File

@@ -1,5 +1,3 @@
'use strict';
const ServerChannel = require('./ServerChannel'); const ServerChannel = require('./ServerChannel');
const TextChannelDataStore = require('./datastore/TextChannelDataStore'); const TextChannelDataStore = require('./datastore/TextChannelDataStore');
const TextBasedChannel = require('./interface/TextBasedChannel'); const TextBasedChannel = require('./interface/TextBasedChannel');
@@ -12,13 +10,13 @@ class TextChannel extends ServerChannel {
} }
_cacheMessage(message) { _cacheMessage(message) {
let maxSize = this.client.options.max_message_cache; const maxSize = this.client.options.max_message_cache;
if (maxSize === 0) { if (maxSize === 0) {
// saves on performance // saves on performance
return; return null;
} }
let storeKeys = Object.keys(this.store); const storeKeys = Object.keys(this.store);
if (storeKeys.length >= maxSize) { if (storeKeys.length >= maxSize) {
this.store.remove(storeKeys[0]); this.store.remove(storeKeys[0]);
} }

View File

@@ -1,5 +1,3 @@
'use strict';
const TextBasedChannel = require('./interface/TextBasedChannel'); const TextBasedChannel = require('./interface/TextBasedChannel');
/** /**
@@ -60,7 +58,7 @@ class User {
* @return {Promise<DMChannel>} * @return {Promise<DMChannel>}
*/ */
deleteDM() { deleteDM() {
return this.client.rest.methods.DeleteChannel(this); return this.client.rest.methods.deleteChannel(this);
} }
equals(user) { equals(user) {

View File

@@ -1,5 +1,3 @@
'use strict';
const ServerChannel = require('./ServerChannel'); const ServerChannel = require('./ServerChannel');
const VoiceChannelDataStore = require('./datastore/VoiceChannelDataStore'); const VoiceChannelDataStore = require('./datastore/VoiceChannelDataStore');

View File

@@ -1,6 +1,4 @@
'use strict'; class AbstractDataStore {
class AbstractDataStore{
constructor() { constructor() {
this.data = {}; this.data = {};
} }
@@ -12,9 +10,9 @@ class AbstractDataStore{
add(location, object) { add(location, object) {
if (this.data[location][object.id]) { if (this.data[location][object.id]) {
return this.data[location][object.id]; return this.data[location][object.id];
} else {
return this.data[location][object.id] = object;
} }
this.data[location][object.id] = object;
return object;
} }
clear(location) { clear(location) {
@@ -22,13 +20,12 @@ class AbstractDataStore{
} }
remove(location, object) { remove(location, object) {
let id = (typeof object === 'string' || object instanceof String) ? object : object.id; const id = (typeof object === 'string' || object instanceof String) ? object : object.id;
if (this.data[location][id]) { if (this.data[location][id]) {
delete this.data[location][id]; delete this.data[location][id];
return true; return true;
} else {
return false;
} }
return false;
} }
get(location, value) { get(location, value) {

View File

@@ -1,8 +1,6 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore'); const AbstractDataStore = require('./AbstractDataStore');
const Constants = require('../../util/Constants'); const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject'); const cloneObject = require('../../util/CloneObject');
const Guild = require('../Guild'); const Guild = require('../Guild');
const User = require('../User'); const User = require('../User');
const DMChannel = require('../DMChannel'); const DMChannel = require('../DMChannel');
@@ -10,7 +8,7 @@ const TextChannel = require('../TextChannel');
const VoiceChannel = require('../VoiceChannel'); const VoiceChannel = require('../VoiceChannel');
const ServerChannel = require('../ServerChannel'); const ServerChannel = require('../ServerChannel');
class ClientDataStore extends AbstractDataStore{ class ClientDataStore extends AbstractDataStore {
constructor(client) { constructor(client) {
super(); super();
@@ -30,9 +28,9 @@ class ClientDataStore extends AbstractDataStore{
return this.client.ws.status === Constants.Status.READY; return this.client.ws.status === Constants.Status.READY;
} }
NewGuild(data) { newGuild(data) {
let already = this.get('guilds', data.id); const already = this.get('guilds', data.id);
let guild = this.add('guilds', new Guild(this.client, data)); const guild = this.add('guilds', new Guild(this.client, data));
if (this.pastReady && !already) { if (this.pastReady && !already) {
this.client.emit(Constants.Events.GUILD_CREATE, guild); this.client.emit(Constants.Events.GUILD_CREATE, guild);
} }
@@ -40,22 +38,23 @@ class ClientDataStore extends AbstractDataStore{
return guild; return guild;
} }
NewUser(data) { newUser(data) {
return this.add('users', new User(this.client, data)); return this.add('users', new User(this.client, data));
} }
NewChannel(data, guild) { newChannel(data, $guild) {
let already = this.get('channels', data.id); let guild = $guild;
const already = this.get('channels', data.id);
let channel; let channel;
if (data.is_private) { if (data.is_private) {
channel = new DMChannel(this.client, data); channel = new DMChannel(this.client, data);
}else { } else {
guild = guild || this.get('guilds', data.guild_id); guild = guild || this.get('guilds', data.guild_id);
if (guild) { if (guild) {
if (data.type === 'text') { if (data.type === 'text') {
channel = new TextChannel(guild, data); channel = new TextChannel(guild, data);
guild.store.add('channels', channel); guild.store.add('channels', channel);
}else if (data.type === 'voice') { } else if (data.type === 'voice') {
channel = new VoiceChannel(guild, data); channel = new VoiceChannel(guild, data);
guild.store.add('channels', channel); guild.store.add('channels', channel);
} }
@@ -69,37 +68,37 @@ class ClientDataStore extends AbstractDataStore{
return this.add('channels', channel); return this.add('channels', channel);
} }
return null;
} }
KillGuild(guild) { killGuild(guild) {
let already = this.get('guilds', guilds.id); const already = this.get('guilds', guild.id);
this.remove('guilds', guild); this.remove('guilds', guild);
if (already && this.pastReady) { if (already && this.pastReady) {
this.client.emit(Constants.Events.GUILD_DELETE, guild); this.client.emit(Constants.Events.GUILD_DELETE, guild);
} }
} }
KillUser(user) { killUser(user) {
this.remove('users', user); this.remove('users', user);
} }
KillChannel(channel) { killChannel(channel) {
this.remove('channels', channel); this.remove('channels', channel);
if (channel instanceof ServerChannel) { if (channel instanceof ServerChannel) {
channel.guild.store.remove('channels', channel); channel.guild.store.remove('channels', channel);
} }
} }
UpdateGuild(currentGuild, newData) { updateGuild(currentGuild, newData) {
let oldGuild = CloneObject(currentGuild); const oldGuild = cloneObject(currentGuild);
currentGuild.setup(newData); currentGuild.setup(newData);
if (this.pastReady) { if (this.pastReady) {
this.client.emit(Constants.Events.GUILD_UPDATE, oldGuild, currentGuild); this.client.emit(Constants.Events.GUILD_UPDATE, oldGuild, currentGuild);
} }
} }
UpdateChannel(currentChannel, newData) { updateChannel(currentChannel, newData) {
let oldChannel = CloneObject(currentChannel);
currentChannel.setup(newData); currentChannel.setup(newData);
} }
} }

View File

@@ -1,8 +1,6 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore'); const AbstractDataStore = require('./AbstractDataStore');
class GuildDataStore extends AbstractDataStore{ class GuildDataStore extends AbstractDataStore {
constructor() { constructor() {
super(); super();

View File

@@ -1,8 +1,6 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore'); const AbstractDataStore = require('./AbstractDataStore');
class TextChannelDataStore extends AbstractDataStore{ class TextChannelDataStore extends AbstractDataStore {
constructor() { constructor() {
super(); super();
this.register('messages'); this.register('messages');

View File

@@ -1,8 +1,6 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore'); const AbstractDataStore = require('./AbstractDataStore');
class VoiceChannelDataStore extends AbstractDataStore{ class VoiceChannelDataStore extends AbstractDataStore {
constructor() { constructor() {
super(); super();
this.register('members'); this.register('members');

View File

@@ -1,8 +1,6 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore'); const AbstractDataStore = require('./AbstractDataStore');
class WebSocketManagerDataStore extends AbstractDataStore{ class WebSocketManagerDataStore extends AbstractDataStore {
constructor() { constructor() {
super(); super();
this.sessionID = null; this.sessionID = null;

View File

@@ -1,15 +1,12 @@
'use strict'; function sendMessage(content, options = {}) {
return this.client.rest.methods.sendMessage(this, content, options.tts);
function sendMessage(content, options) {
options = options || {};
return this.client.rest.methods.SendMessage(this, content, options.tts);
} }
function sendTTSMessage(content, options) { function sendTTSMessage(content) {
options = options || {}; return this.client.rest.methods.sendMessage(this, content, true);
return this.client.rest.methods.SendMessage(this, content, true);
} }
exports.applyToClass = structure => { exports.applyToClass = structure => {
structure.prototype.sendMessage = sendMessage; structure.prototype.sendMessage = sendMessage;
structure.prototype.sendTTSMessage = sendTTSMessage;
}; };

View File

@@ -1,6 +1,5 @@
'use strict'; module.exports = function cloneObject(obj) {
module.exports = function CloneObject(obj) { const cloned = Object.create(obj);
var cloned = Object.create(obj);
Object.assign(cloned, obj); Object.assign(cloned, obj);
return cloned; return cloned;

View File

@@ -1,6 +1,4 @@
'use strict'; exports.DefaultOptions = {
const DefaultOptions = exports.DefaultOptions = {
ws: { ws: {
large_threshold: 250, large_threshold: 250,
compress: true, compress: true,
@@ -17,16 +15,16 @@ const DefaultOptions = exports.DefaultOptions = {
rest_ws_bridge_timeout: 5000, rest_ws_bridge_timeout: 5000,
}; };
const Status = exports.Status = { exports.Status = {
READY: 0, READY: 0,
CONNECTING: 1, CONNECTING: 1,
RECONNECTING: 2, RECONNECTING: 2,
IDLE: 3, IDLE: 3,
}; };
const Package = exports.Package = require('../../package.json'); exports.Package = require('../../package.json');
const Errors = exports.Errors = { exports.Errors = {
NO_TOKEN: new Error('request to use token, but token was unavailable to the client'), NO_TOKEN: new Error('request to use token, but token was unavailable to the client'),
NO_BOT_ACCOUNT: new Error('you should ideally be using a bot account!'), NO_BOT_ACCOUNT: new Error('you should ideally be using a bot account!'),
BAD_WS_MESSAGE: new Error('a bad message was received from the websocket - bad compression or not json'), BAD_WS_MESSAGE: new Error('a bad message was received from the websocket - bad compression or not json'),
@@ -38,41 +36,41 @@ const API = 'https://discordapp.com/api';
const Endpoints = exports.Endpoints = { const Endpoints = exports.Endpoints = {
// general endpoints // general endpoints
LOGIN: `${API}/auth/login`, login: `${API}/auth/login`,
LOGOUT: `${API}/auth/logout`, logout: `${API}/auth/logout`,
ME: `${API}/users/@me`, me: `${API}/users/@me`,
ME_GUILD: (guildID) => `${Endpoints.ME}/guilds/${guildID}`, meGuild: (guildID) => `${Endpoints.me}/guilds/${guildID}`,
GATEWAY: `${API}/gateway`, gateway: `${API}/gateway`,
USER_CHANNELS: (userID) => `${API}/users/${userID}/channels`, userChannels: (userID) => `${API}/users/${userID}/channels`,
AVATAR: (userID, avatar) => `${API}/users/${userID}/avatars/${avatar}.jpg`, avatar: (userID, avatar) => `${API}/users/${userID}/avatars/${avatar}.jpg`,
INVITE: (id) => `${API}/invite/${id}`, invite: (id) => `${API}/invite/${id}`,
// guilds // guilds
GUILDS: `${API}/guilds`, guilds: `${API}/guilds`,
GUILD: (guildID) => `${Endpoints.GUILDS}/${guildID}`, guild: (guildID) => `${Endpoints.guilds}/${guildID}`,
GUILD_ICON: (guildID, hash) => `${Endpoints.GUILD(guildID)}/icons/${hash}.jpg`, guildIcon: (guildID, hash) => `${Endpoints.guild(guildID)}/icons/${hash}.jpg`,
GUILD_PRUNE: (guildID) => `${Endpoints.GUILD(guildID)}/prune`, guildPrune: (guildID) => `${Endpoints.guild(guildID)}/prune`,
GUILD_EMBED: (guildID) => `${Endpoints.GUILD(guildID)}/embed`, guildEmbed: (guildID) => `${Endpoints.guild(guildID)}/embed`,
GUILD_INVITES: (guildID) => `${Endpoints.GUILD(guildID)}/invites`, guildInvites: (guildID) => `${Endpoints.guild(guildID)}/invites`,
GUILD_ROLES: (guildID) => `${Endpoints.GUILD(guildID)}/roles`, guildRoles: (guildID) => `${Endpoints.guild(guildID)}/roles`,
GUILD_ROLE: (guildID, roleID) => `${Endpoints.GUILD_ROLES(guildID)}/${roleID}`, guildRole: (guildID, roleID) => `${Endpoints.guildRoles(guildID)}/${roleID}`,
GUILD_BANS: (guildID) => `${Endpoints.GUILD(guildID)}/bans`, guildBans: (guildID) => `${Endpoints.guild(guildID)}/bans`,
GUILD_INTEGRATIONS: (guildID) => `${Endpoints.GUILD(guildID)}/integrations`, guildIntegrations: (guildID) => `${Endpoints.guild(guildID)}/integrations`,
GUILD_MEMBERS: (guildID) => `${Endpoints.GUILD(guildID)}/members`, guildMembers: (guildID) => `${Endpoints.guild(guildID)}/members`,
GUILD_MEMBER: (guildID, memberID) => `${Endpoints.GUILD_MEMBERS(guildID)}/${memberID}`, guildMember: (guildID, memberID) => `${Endpoints.guildMembers(guildID)}/${memberID}`,
GUILD_CHANNELS: (guildID) => `${Endpoints.GUILD(guildID)}/channels`, guildChannels: (guildID) => `${Endpoints.guild(guildID)}/channels`,
// channels // channels
CHANNELS: `${API}/channels`, channels: `${API}/channels`,
CHANNEL: (channelID) => `${Endpoints.CHANNELS}/${channelID}`, channel: (channelID) => `${Endpoints.channels}/${channelID}`,
CHANNEL_MESSAGES: (channelID) => `${Endpoints.CHANNEL(channelID)}/messages`, channelMessages: (channelID) => `${Endpoints.channel(channelID)}/messages`,
CHANNEL_INVITES: (channelID) => `${Endpoints.CHANNEL(channelID)}/invites`, channelInvites: (channelID) => `${Endpoints.channel(channelID)}/invites`,
CHANNEL_TYPING: (channelID) => `${Endpoints.CHANNEL(channelID)}/typing`, channelTyping: (channelID) => `${Endpoints.channel(channelID)}/typing`,
CHANNEL_PERMISSIONS: (channelID) => `${Endpoints.CHANNEL(channelID)}/permissions`, channelPermissions: (channelID) => `${Endpoints.channel(channelID)}/permissions`,
CHANNEL_MESSAGE: (channelID, messageID) => `${Endpoints.CHANNEL_MESSAGES(channelID)}/${messageID}`, channelMessage: (channelID, messageID) => `${Endpoints.channelMessage(channelID)}/${messageID}`,
}; };
const OPCodes = exports.OPCodes = { exports.OPCodes = {
DISPATCH: 0, DISPATCH: 0,
HEARTBEAT: 1, HEARTBEAT: 1,
IDENTIFY: 2, IDENTIFY: 2,
@@ -85,7 +83,7 @@ const OPCodes = exports.OPCodes = {
INVALID_SESSION: 9, INVALID_SESSION: 9,
}; };
const Events = exports.Events = { exports.Events = {
READY: 'ready', READY: 'ready',
GUILD_CREATE: 'guildCreate', GUILD_CREATE: 'guildCreate',
GUILD_DELETE: 'guildDelete', GUILD_DELETE: 'guildDelete',
@@ -116,7 +114,7 @@ const Events = exports.Events = {
MESSAGE_UPDATE: 'messageUpdate', MESSAGE_UPDATE: 'messageUpdate',
}; };
const WSEvents = exports.WSEvents = { exports.WSEvents = {
CHANNEL_CREATE: 'CHANNEL_CREATE', CHANNEL_CREATE: 'CHANNEL_CREATE',
CHANNEL_DELETE: 'CHANNEL_DELETE', CHANNEL_DELETE: 'CHANNEL_DELETE',
CHANNEL_UPDATE: 'CHANNEL_UPDATE', CHANNEL_UPDATE: 'CHANNEL_UPDATE',
@@ -175,10 +173,10 @@ const PermissionFlags = exports.PermissionFlags = {
let _ALL_PERMISSIONS = 0; let _ALL_PERMISSIONS = 0;
for (let key in PermissionFlags) { for (const key in PermissionFlags) {
_ALL_PERMISSIONS |= PermissionFlags[key]; _ALL_PERMISSIONS |= PermissionFlags[key];
} }
const ALL_PERMISSIONS = exports.ALL_PERMISSIONS = _ALL_PERMISSIONS; exports.ALL_PERMISSIONS = _ALL_PERMISSIONS;
const DEFAULT_PERMISSIONS = exports.DEFAULT_PERMISSIONS = 36953089; exports.DEFAULT_PERMISSIONS = 36953089;

View File

@@ -1,5 +1,3 @@
'use strict';
module.exports = function merge(def, given) { module.exports = function merge(def, given) {
if (!given) { if (!given) {
return def; return def;
@@ -7,8 +5,8 @@ module.exports = function merge(def, given) {
given = given || {}; given = given || {};
for (var key in def) { for (const key in def) {
if (!given.hasOwnProperty(key)) { if (!{}.hasOwnProperty.call(given, key)) {
given[key] = def[key]; given[key] = def[key];
} else if (given[key] === Object(given[key])) { } else if (given[key] === Object(given[key])) {
given[key] = merge(def[key], given[key]); given[key] = merge(def[key], given[key]);

View File

@@ -3,7 +3,7 @@
const Discord = require('../'); const Discord = require('../');
const request = require('superagent'); const request = require('superagent');
let client = new Discord.Client(); const client = new Discord.Client();
client.login(require('./auth.json').token).then(token => console.log('logged in with token ' + token)).catch(console.log); client.login(require('./auth.json').token).then(token => console.log('logged in with token ' + token)).catch(console.log);
@@ -43,10 +43,10 @@ client.on('guildRoleCreate', (guild, role) => {
console.log('new role', role.name, 'in', guild.name); console.log('new role', role.name, 'in', guild.name);
role.edit({ role.edit({
permissions: ['DEAFEN_MEMBERS'], permissions: ['DEAFEN_MEMBERS'],
name: 'deafen' name: 'deafen',
}).then(role2 => { }).then(role2 => {
console.log('role replace from ' + role.name + ' to ' + role2.name); console.log('role replace from ' + role.name + ' to ' + role2.name);
}).catch(console.log) }).catch(console.log);
}); });
client.on('guildRoleDelete', (guild, role) => { client.on('guildRoleDelete', (guild, role) => {