This commit is contained in:
hydrabolt
2016-04-16 22:58:49 +01:00
commit 9956e43c8e
43 changed files with 1634 additions and 0 deletions

34
src/client/Client.js Normal file
View File

@@ -0,0 +1,34 @@
'use strict';
const EventEmitter = require('events').EventEmitter;
const MergeDefault = require('../util/MergeDefault');
const Constants = require('../util/Constants');
const RESTManager = require('./rest/RestManager');
const ClientDataStore = require('../structures/DataStore/ClientDataStore');
const ClientManager = require('./ClientManager');
const WebSocketManager = require('./websocket/WebSocketManager');
class Client extends EventEmitter{
constructor(options) {
super();
this.options = MergeDefault(Constants.DefaultOptions, options);
this.rest = new RESTManager(this);
this.store = new ClientDataStore(this);
this.manager = new ClientManager(this);
this.ws = new WebSocketManager(this);
}
login(email, password) {
if (password) {
// login with email and password
return this.rest.methods.LoginEmailPassword(email, password);
} else {
// login with token
return this.rest.methods.LoginToken(email);
}
}
}
module.exports = Client;

View File

@@ -0,0 +1,34 @@
'use strict';
const Constants = require('../util/Constants');
class ClientManager {
constructor(client) {
this.client = client;
this.heartbeatInterval = null;
}
connectToWebSocket(token, resolve, reject) {
this.client.store.token = token;
this.client.rest.methods.GetGateway()
.then(gateway => {
this.client.ws.connect(gateway);
this.client.once(Constants.Events.READY, () => resolve(token));
})
.catch(reject);
setTimeout(() => reject(Constants.Errors.TOOK_TOO_LONG), 1000 * 15);
}
setupKeepAlive(time) {
this.heartbeatInterval = setInterval(() => {
this.client.ws.send({
op: Constants.OPCodes.HEARTBEAT,
d: Date.now(),
});
}, time);
}
}
module.exports = ClientManager;

View File

@@ -0,0 +1,53 @@
'use strict';
const request = require('superagent');
const Constants = require('../../util/Constants');
const UserAgentManager = require('./UserAgentManager');
const RESTMethods = require('./RESTMethods');
class RESTManager{
constructor(client) {
this.client = client;
this.queue = [];
this.userAgentManager = new UserAgentManager(this);
this.methods = new RESTMethods(this);
}
makeRequest(method, url, auth, data, file) {
/*
file is {file, name}
*/
let apiRequest = request[method](url);
if (auth) {
if (this.client.store.token) {
apiRequest.set('authorization', this.client.store.token);
} else {
throw Constants.Errors.NO_TOKEN;
}
}
if (data) {
apiRequest.send(data);
}
if (file) {
apiRequest.attach('file', file.file, file.name);
}
apiRequest.set('User-Agent', this.userAgentManager.userAgent);
return new Promise((resolve, reject) => {
apiRequest.end((err, res) => {
if (err) {
reject(err);
} else {
resolve(res ? res.body || {} : {});
}
});
});
}
};
module.exports = RESTManager;

View File

@@ -0,0 +1,37 @@
'use strict';
const Constants = require('../../util/Constants');
class RESTMethods{
constructor(restManager) {
this.rest = restManager;
}
LoginEmailPassword(email, password) {
return new Promise((resolve, reject) => {
this.rest.makeRequest('post', Constants.Endpoints.LOGIN, false, { email, password })
.then(data => {
this.rest.client.manager.connectToWebSocket(data.token, resolve, reject);
})
.catch(reject);
});
}
LoginToken(token) {
return new Promise((resolve, reject) => {
this.rest.client.manager.connectToWebSocket(token, resolve, reject);
});
}
GetGateway() {
return new Promise((resolve, reject) => {
this.rest.makeRequest('get', Constants.Endpoints.GATEWAY, true)
.then(res => resolve(res.url))
.catch(reject);
});
}
}
module.exports = RESTMethods;

View File

@@ -0,0 +1,24 @@
'use strict';
const Constants = require('../../util/Constants');
class UserAgentManager{
constructor(restManager) {
this.restManager = restManager;
this._userAgent = {
url: 'https://github.com/hydrabolt/discord.js',
version: Constants.Package.version,
};
}
set(info) {
this._userAgent.url = info.url || 'https://github.com/hydrabolt/discord.js';
this._userAgent.version = info.version || Constants.Package.version;
}
get userAgent() {
return `DiscordBot (${this._userAgent.url}, ${this._userAgent.version})`;
}
}
module.exports = UserAgentManager;

View File

@@ -0,0 +1,79 @@
'use strict';
const WebSocket = require('ws');
const Constants = require('../../util/Constants');
const zlib = require('zlib');
const PacketManager = require('./packets/WebSocketPacketManager');
class WebSocketManager {
constructor(client) {
this.client = client;
this.ws = null;
this.packetManager = new PacketManager(this);
this.emittedReady = false;
}
connect(gateway) {
gateway += `/?v=${this.client.options.protocol_version}`;
this.ws = new WebSocket(gateway);
this.ws.onopen = () => this.EventOpen();
this.ws.onclose = () => this.EventClose();
this.ws.onmessage = (e) => this.EventMessage(e);
this.ws.onerror = (e) => this.EventError(e);
}
send(data) {
this.ws.send(JSON.stringify(data));
}
EventOpen() {
let payload = this.client.options.ws;
payload.token = this.client.store.token;
this.send({
op: Constants.OPCodes.IDENTIFY,
d: payload,
});
}
EventClose() {
}
EventMessage(event) {
let packet;
try {
if (event.binary) {
event.data = zlib.inflateSync(event.data).toString();
}
packet = JSON.parse(event.data);
} catch (e) {
return this.EventError(Constants.Errors.BAD_WS_MESSAGE);
}
this.packetManager.handle(packet);
}
EventError(e) {
}
checkIfReady() {
if (!this.emittedReady) {
let unavailableCount = 0;
for (let guildID in this.client.store.data.guilds) {
unavailableCount += this.client.store.data.guilds[guildID].available ? 0 : 1;
}
if (unavailableCount === 0) {
this.client.emit(Constants.Events.READY);
this.emittedReady = true;
}
}
}
}
module.exports = WebSocketManager;

View File

@@ -0,0 +1,44 @@
'use strict';
const Constants = require('../../../util/Constants');
class WebSocketPacketManager {
constructor(websocketManager) {
this.ws = websocketManager;
this.handlers = {};
this.register(Constants.WSEvents.READY, 'Ready');
this.register(Constants.WSEvents.GUILD_CREATE, 'GuildCreate');
this.register(Constants.WSEvents.GUILD_DELETE, 'GuildDelete');
this.register(Constants.WSEvents.GUILD_UPDATE, 'GuildUpdate');
this.register(Constants.WSEvents.GUILD_BAN_ADD, 'GuildBanAdd');
this.register(Constants.WSEvents.GUILD_BAN_REMOVE, 'GuildBanRemove');
this.register(Constants.WSEvents.GUILD_MEMBER_ADD, 'GuildMemberAdd');
this.register(Constants.WSEvents.GUILD_MEMBER_REMOVE, 'GuildMemberRemove');
this.register(Constants.WSEvents.GUILD_MEMBER_UPDATE, 'GuildMemberUpdate');
this.register(Constants.WSEvents.CHANNEL_CREATE, 'ChannelCreate');
this.register(Constants.WSEvents.CHANNEL_DELETE, 'ChannelDelete');
this.register(Constants.WSEvents.CHANNEL_UPDATE, 'ChannelUpdate');
}
get client() {
return this.ws.client;
}
register(event, handle) {
let Handler = require(`./handlers/${handle}`);
this.handlers[event] = new Handler(this);
}
handle(packet) {
if (this.handlers[packet.t]) {
return this.handlers[packet.t].handle(packet);
}
return false;
}
}
module.exports = WebSocketPacketManager;

View File

@@ -0,0 +1,14 @@
'use strict';
class AbstractHandler {
constructor(packetManager) {
this.packetManager = packetManager;
}
handle(packet) {
}
}
module.exports = AbstractHandler;

View File

@@ -0,0 +1,28 @@
'use strict';
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');
class ChannelCreateHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let channel = client.store.NewChannel(data);
}
};
module.exports = ChannelCreateHandler;

View File

@@ -0,0 +1,31 @@
'use strict';
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');
class ChannelDeleteHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let channel = client.store.get('channels', data.id);
if (channel) {
client.store.KillChannel(channel);
}
}
};
module.exports = ChannelDeleteHandler;

View File

@@ -0,0 +1,33 @@
'use strict';
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 {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let channel = client.store.get('channels', data.id);
if (channel) {
client.store.UpdateChannel(channel, data);
}
}
};
module.exports = ChannelUpdateHandler;

View File

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

View File

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

View File

@@ -0,0 +1,38 @@
'use strict';
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 {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let guild = client.store.get('guilds', data.id);
if (guild) {
if (!guild.available && !data.unavailable) {
// a newly available guild
guild.setup(data);
this.packetManager.ws.checkIfReady();
}
} else {
// a new guild
client.store.NewGuild(data);
}
}
};
module.exports = GuildCreateHandler;

View File

@@ -0,0 +1,41 @@
'use strict';
const AbstractHandler = require('./AbstractHandler');
const Structure = name => require(`../../../../structures/${name}`);
const ClientUser = Structure('ClientUser');
const Guild = Structure('Guild');
const Constants = require('../../../../util/Constants');
class GuildDeleteHandler extends AbstractHandler {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let guild = client.store.get('guilds', data.id);
if (guild) {
if (guild.available && data.unavailable) {
// guild is unavailable
guild.available = false;
client.emit(Constants.Events.GUILD_UNAVAILABLE, guild);
} else {
// delete guild
client.store.KillGuild(guild);
}
} else {
// it's not there! :(
client.emit('warn', 'guild deleted but not cached in first place. missed packet?');
}
}
};
module.exports = GuildDeleteHandler;

View File

@@ -0,0 +1,32 @@
'use strict';
// ##untested handler##
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 {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id);
if (guild) {
guild._addMember(data);
}
}
};
module.exports = GuildMemberAddHandler;

View File

@@ -0,0 +1,33 @@
'use strict';
// ##untested handler##
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 {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id);
let user = client.store.get('users', data.user.id);
if (guild && user) {
guild._removeMember(user);
}
}
};
module.exports = GuildMemberRemoveHandler;

View File

@@ -0,0 +1,33 @@
'use strict';
// ##untested handler##
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 {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let guild = client.store.get('guilds', data.guild_id);
let user = client.store.get('users', data.user.id);
if (guild) {
guild._updateMember(user, data);
}
}
};
module.exports = GuildMemberUpdateHandler;

View File

@@ -0,0 +1,32 @@
'use strict';
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 {
constructor(packetManager) {
super(packetManager);
}
handle(packet) {
let data = packet.d;
let client = this.packetManager.client;
let guild = client.store.get('guilds', data.id);
if (guild) {
client.store.UpdateGuild(guild, data);
}
}
};
module.exports = GuildUpdateHandler;

View File

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

15
src/index.js Normal file
View File

@@ -0,0 +1,15 @@
'use strict';
const entries = require('object.entries');
const values = require('object.values');
const Client = require('./client/Client');
if (!Object.entries) {
entries.shim();
}
if (!Object.values) {
values.shim();
}
exports.Client = Client;

16
src/structures/Channel.js Normal file
View File

@@ -0,0 +1,16 @@
'use strict';
class Channel {
constructor(client, data) {
this.client = client;
if (data) {
this.setup(data);
}
}
setup(data) {
this.id = data.id;
}
}
module.exports = Channel;

View File

@@ -0,0 +1,17 @@
'use strict';
const User = require('./User');
class ClientUser extends User {
constructor(client, data) {
super(client, data);
}
setup(data) {
super.setup(data);
this.verified = data.verified;
this.email = data.email;
}
}
module.exports = ClientUser;

View File

@@ -0,0 +1,17 @@
'use strict';
const Channel = require('./Channel');
const User = require('./User');
class DMChannel extends Channel{
constructor(client, data) {
super(client, data);
}
setup(data) {
this.recipient = this.client.store.add('users', new User(this.client, data.recipient));
this.lastMessageID = data.last_message_id;
}
}
module.exports = DMChannel;

91
src/structures/Guild.js Normal file
View File

@@ -0,0 +1,91 @@
'use strict';
const User = require('./User');
const GuildDataStore = require('./datastore/GuildDataStore');
const TextChannel = require('./TextChannel');
const VoiceChannel = require('./VoiceChannel');
const Constants = require('../Util/Constants');
class Guild {
constructor(client, data) {
this.client = client;
this.store = new GuildDataStore();
if (!data) {
return;
}
if (data.unavailable) {
this.available = false;
this.id = data.id;
} else {
this.available = true;
this.setup(data);
}
}
_addMember(guildUser) {
let user = this.client.store.NewUser(guildUser.user);
this.store.memberData[user.id] = {
deaf: guildUser.deaf,
mute: guildUser.mute,
joinDate: new Date(guildUser.joined_at),
roles: guildUser.roles,
};
if (this.client.ws.emittedReady) {
this.client.emit(Constants.Events.GUILD_MEMBER_ADD, this, user);
}
}
_updateMember(currentUser, newData) {
let oldRoles = this.store.memberData[currentUser.id].roles;
this.store.currentUser[currentUser.id].roles = newData.roles;
if (this.client.ws.emittedReady) {
this.client.emit(Constants.Events.GUILD_MEMBER_ROLES_UPDATE, this, oldRoles, this.store.memberData[currentUser.id].roles);
}
}
_removeMember(guildUser) {
this.store.remove('members', guildUser);
if (this.client.ws.emittedReady) {
this.client.emit(Constants.Events.GUILD_MEMBER_REMOVE, this, guildUser);
}
}
setup(data) {
this.id = data.id;
this.available = !data.unavailable;
this.splash = data.splash;
this.region = data.region;
this.ownerID = data.owner_id;
this.name = data.name;
this.memberCount = data.member_count;
this.large = data.large;
this.joinDate = new Date(data.joined_at);
this.icon = data.icon;
this.features = data.features;
this.emojis = data.emojis;
this.afkTimeout = data.afk_timeout;
this.afkChannelID = data.afk_channel_id;
this.embedEnabled = data.embed_enabled;
this.embedChannelID = data.embed_channel_id;
this.verificationLevel = data.verification_level;
this.features = data.features || [];
if (data.members) {
this.store.clear('members');
for (let guildUser of data.members) {
this._addMember(guildUser);
}
}
if (data.channels) {
this.store.clear('channels');
for (let channel of data.channels) {
this.client.store.NewChannel(channel, this);
}
}
}
}
module.exports = Guild;

View File

@@ -0,0 +1,9 @@
'use strict';
class Message {
constructor() {
}
}
module.exports = Message;

View File

@@ -0,0 +1,22 @@
'use strict';
const Channel = require('./Channel');
class ServerChannel extends Channel{
constructor(guild, data) {
super(guild.client, data);
this.guild = guild;
}
setup(data) {
super.setup(data);
this.type = data.type;
this.topic = data.topic;
this.position = data.position;
this.permissionOverwrites = data.permission_overwrites;
this.name = data.name;
this.lastMessageID = data.last_message_id;
}
}
module.exports = ServerChannel;

View File

@@ -0,0 +1,13 @@
'use strict';
const ServerChannel = require('./ServerChannel');
const TextChannelDataStore = require('./datastore/TextChannelDataStore');
class TextChannel extends ServerChannel {
constructor(guild, data) {
super(guild, data);
this.store = new TextChannelDataStore();
}
}
module.exports = TextChannel;

20
src/structures/User.js Normal file
View File

@@ -0,0 +1,20 @@
'use strict';
class User {
constructor(client, data) {
this.client = client;
if (data) {
this.setup(data);
}
}
setup(data) {
this.username = data.username;
this.id = data.id;
this.discriminator = data.discriminator;
this.avatar = data.avatar;
this.bot = Boolean(data.bot);
}
}
module.exports = User;

View File

@@ -0,0 +1,16 @@
'use strict';
const ServerChannel = require('./ServerChannel');
class VoiceChannel extends ServerChannel {
constructor(guild, data) {
super(guild, data);
}
setup(data) {
super.setup(data);
this.bitrate = data.bitrate;
}
}
module.exports = VoiceChannel;

View File

@@ -0,0 +1,43 @@
'use strict';
class AbstractDataStore{
constructor() {
this.data = {};
}
register(name) {
this.data[name] = {};
}
add(location, object) {
if (this.data[location][object.id]) {
return this.data[location][object.id];
} else {
return this.data[location][object.id] = object;
}
}
clear(location) {
this.data[location] = {};
}
remove(location, object) {
let id = (typeof object === 'string' || object instanceof String) ? object : object.id;
if (this.data[location][id]) {
delete this.data[location][id];
return true;
} else {
return false;
}
}
get(location, value) {
return this.data[location][value];
}
getAsArray(location) {
return Object.values(this.data[location]);
}
}
module.exports = AbstractDataStore;

View File

@@ -0,0 +1,111 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore');
const Constants = require('../../util/Constants');
const CloneObject = require('../../util/CloneObject');
const Guild = require('../Guild');
const User = require('../User');
const DMChannel = require('../DMChannel');
const TextChannel = require('../TextChannel');
const VoiceChannel = require('../VoiceChannel');
const ServerChannel = require('../ServerChannel');
class ClientDataStore extends AbstractDataStore{
constructor(client) {
super();
this.client = client;
this.token = null;
this.session = null;
this.user = null;
this.register('users');
this.register('guilds');
this.register('channels');
}
get pastReady() {
return this.client.ws.emittedReady;
}
NewGuild(data) {
let already = this.get('guilds', data.id);
let guild = this.add('guilds', new Guild(this.client, data));
if (this.pastReady && !already) {
this.client.emit(Constants.Events.GUILD_CREATE, guild);
}
return guild;
}
NewUser(data) {
return this.add('users', new User(this.client, data));
}
NewChannel(data, guild) {
let already = this.get('channels', data.id);
let channel;
if (data.is_private) {
channel = new DMChannel(this.client, data);
}else {
guild = guild || this.get('guilds', data.guild_id);
if (guild) {
if (data.type === 'text') {
channel = new TextChannel(guild, data);
guild.store.add('channels', channel);
}else if (data.type === 'voice') {
channel = new VoiceChannel(guild, data);
guild.store.add('channels', channel);
}
}
}
if (channel) {
if (this.pastReady && !already) {
this.client.emit(Constants.Events.CHANNEL_CREATE, channel);
}
return this.add('channels', channel);
}
}
KillGuild(guild) {
let already = this.get('guilds', guilds.id);
this.remove('guilds', guild);
if (already && this.pastReady) {
this.client.emit(Constants.Events.GUILD_DELETE, guild);
}
}
KillUser(user) {
this.remove('users', user);
}
KillChannel(channel) {
let already = this.get('channels', channel.id);
this.remove('channels', channel);
if (channel instanceof ServerChannel) {
channel.guild.store.remove('channels', channel);
}
if (already && this.pastReady) {
this.client.emit(Constants.Events.CHANNEL_DELETE, channel);
}
}
UpdateGuild(currentGuild, newData) {
let oldGuild = CloneObject(currentGuild);
currentGuild.setup(newData);
if (this.pastReady) {
this.client.emit(Constants.Events.GUILD_UPDATE, oldGuild, currentGuild);
}
}
UpdateChannel(currentChannel, newData) {
let oldChannel = CloneObject(currentChannel);
currentChannel.setup(newData);
this.client.emit(Constants.Events.CHANNEL_UPDATE, oldChannel, currentChannel);
}
}
module.exports = ClientDataStore;

View File

@@ -0,0 +1,16 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore');
class GuildDataStore extends AbstractDataStore{
constructor() {
super();
this.memberData = {};
this.register('members');
this.register('channels');
}
}
module.exports = GuildDataStore;

View File

@@ -0,0 +1,12 @@
'use strict';
const AbstractDataStore = require('./AbstractDataStore');
class TextChannelDataStore extends AbstractDataStore{
constructor() {
super();
this.register('messages');
}
}
module.exports = TextChannelDataStore;

7
src/util/CloneObject.js Normal file
View File

@@ -0,0 +1,7 @@
'use strict';
module.exports = function CloneObject(obj) {
var cloned = Object.create(obj);
Object.assign(cloned, obj);
return cloned;
};

118
src/util/Constants.js Normal file
View File

@@ -0,0 +1,118 @@
const DefaultOptions = exports.DefaultOptions = {
ws: {
large_threshold: 250,
compress: true,
properties: {
$os: process ? process.platform : 'discord.js',
$browser: 'discord.js',
$device: 'discord.js',
$referrer: '',
$referring_domain: '',
},
},
protocol_version: 4,
};
const Package = exports.Package = require('../../package.json');
const Errors = exports.Errors = {
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!'),
BAD_WS_MESSAGE: new Error('a bad message was received from the websocket - bad compression or not json'),
TOOK_TOO_LONG: new Error('something took too long to do'),
};
const API = 'https://discordapp.com/api';
const Endpoints = exports.Endpoints = {
// general endpoints
LOGIN: `${API}/auth/login`,
LOGOUT: `${API}/auth/logout`,
ME: `${API}/users/@me`,
ME_GUILD: (guildID) => `${Endpoints.ME}/guilds/${guildID}`,
GATEWAY: `${API}/gateway`,
USER_CHANNELS: (userID) => `${API}/users/${userID}/channels`,
AVATAR: (userID, avatar) => `${API}/users/${userID}/avatars/${avatar}.jpg`,
INVITE: (id) => `${API}/invite/${id}`,
// guilds
GUILDS: `${API}/guilds`,
GUILD: (guildID) => `${Endpoints.GUILDS}/${guildID}`,
GUILD_ICON: (guildID, hash) => `${Endpoints.GUILD(guildID)}/icons/${hash}.jpg`,
GUILD_PRUNE: (guildID) => `${Endpoints.GUILD(guildID)}/prune`,
GUILD_EMBED: (guildID) => `${Endpoints.GUILD(guildID)}/embed`,
GUILD_INVITES: (guildID) => `${Endpoints.GUILD(guildID)}/invites`,
GUILD_ROLES: (guildID) => `${Endpoints.GUILD(guildID)}/roles`,
GUILD_BANS: (guildID) => `${Endpoints.GUILD(guildID)}/bans`,
GUILD_INTEGRATIONS: (guildID) => `${Endpoints.GUILD(guildID)}/integrations`,
GUILD_MEMBERS: (guildID) => `${Endpoints.GUILD(guildID)}/members`,
GUILD_CHANNELS: (guildID) => `${Endpoints.GUILD(guildID)}/channels`,
// channels
CHANNELS: `${API}/channels`,
CHANNEL: (channelID) => `${Endpoints.CHANNELS}/${channelID}`,
CHANNEL_MESSAGES: (channelID) => `${Endpoints.CHANNEL(channelID)}/messages`,
CHANNEL_INVITES: (channelID) => `${Endpoints.CHANNEL(channelID)}/invites`,
CHANNEL_TYPING: (channelID) => `${Endpoints.CHANNEL(channelID)}/typing`,
CHANNEL_PERMISSIONS: (channelID) => `${Endpoints.CHANNEL(channelID)}/permissions`,
CHANNEL_MESSAGE: (channelID, messageID) => `${Endpoints.CHANNEL_MESSAGES(channelID)}/${messageID}`,
};
const OPCodes = exports.OPCodes = {
DISPATCH: 0,
HEARTBEAT: 1,
IDENTIFY: 2,
STATUS_UPDATE: 3,
VOICE_STATE_UPDATE: 4,
VOICE_GUILD_PING: 5,
RESUME: 6,
RECONNECT: 7,
REQUEST_GUILD_MEMBERS: 8,
INVALID_SESSION: 9,
};
const Events = exports.Events = {
READY: 'ready',
GUILD_CREATE: 'guildCreate',
GUILD_DELETE: 'guildDelete',
GUILD_UNAVAILABLE: 'guildUnavailable',
GUILD_AVAILABLE: 'guildAvailable',
GUILD_UPDATE: 'guildUpdate',
GUILD_BAN_ADD: 'guildBanAdd',
GUILD_BAN_REMOVE: 'guildBanRemove',
GUILD_MEMBER_ADD: 'guildMemberAdd',
GUILD_MEMBER_REMOVE: 'guildMemberRemove',
GUILD_MEMBER_ROLES_UPDATE: 'guildMemberRolesUpdate',
CHANNEL_CREATE: 'channelCreate',
CHANNEL_DELETE: 'channelDelete',
CHANNEL_UPDATE: 'channelUpdate',
WARN: 'warn',
};
const WSEvents = exports.WSEvents = {
CHANNEL_CREATE: 'CHANNEL_CREATE',
CHANNEL_DELETE: 'CHANNEL_DELETE',
CHANNEL_UPDATE: 'CHANNEL_UPDATE',
MESSAGE_CREATE: 'MESSAGE_CREATE',
MESSAGE_DELETE: 'MESSAGE_DELETE',
MESSAGE_UPDATE: 'MESSAGE_UPDATE',
PRESENCE_UPDATE: 'PRESENCE_UPDATE',
READY: 'READY',
GUILD_BAN_ADD: 'GUILD_BAN_ADD',
GUILD_BAN_REMOVE: 'GUILD_BAN_REMOVE',
GUILD_CREATE: 'GUILD_CREATE',
GUILD_DELETE: 'GUILD_DELETE',
GUILD_MEMBER_ADD: 'GUILD_MEMBER_ADD',
GUILD_MEMBER_REMOVE: 'GUILD_MEMBER_REMOVE',
GUILD_MEMBER_UPDATE: 'GUILD_MEMBER_UPDATE',
GUILD_MEMBERS_CHUNK: 'GUILD_MEMBERS_CHUNK',
GUILD_ROLE_CREATE: 'GUILD_ROLE_CREATE',
GUILD_ROLE_DELETE: 'GUILD_ROLE_DELETE',
GUILD_ROLE_UPDATE: 'GUILD_ROLE_UPDATE',
GUILD_UPDATE: 'GUILD_UPDATE',
TYPING: 'TYPING_START',
USER_UPDATE: 'USER_UPDATE',
VOICE_STATE_UPDATE: 'VOICE_STATE_UPDATE',
FRIEND_ADD: 'RELATIONSHIP_ADD',
FRIEND_REMOVE: 'RELATIONSHIP_REMOVE',
};

19
src/util/MergeDefault.js Normal file
View File

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