diff --git a/lib/Client/Client.js b/lib/Client/Client.js index cb5f0b420..b05b509de 100644 --- a/lib/Client/Client.js +++ b/lib/Client/Client.js @@ -1,517 +1,1292 @@ -"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _InternalClient=require("./InternalClient");var _InternalClient2=_interopRequireDefault(_InternalClient);var _events=require("events");var _events2=_interopRequireDefault(_events);var _StructuresPMChannel=require("../Structures/PMChannel");var _StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel); // This utility function creates an anonymous error handling wrapper function +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _InternalClient = require("./InternalClient"); + +var _InternalClient2 = _interopRequireDefault(_InternalClient); + +var _events = require("events"); + +var _events2 = _interopRequireDefault(_events); + +var _StructuresPMChannel = require("../Structures/PMChannel"); + +var _StructuresPMChannel2 = _interopRequireDefault(_StructuresPMChannel); + +// This utility function creates an anonymous error handling wrapper function // for a given callback. It is used to allow error handling inside the callback // and using other means. -function errorCallback(callback){return function(error){callback(error);throw error;};} // This utility function creates an anonymous handler function to separate the +function errorCallback(callback) { + return function (error) { + callback(error); + throw error; + }; +} + +// This utility function creates an anonymous handler function to separate the // error and the data arguments inside a callback and return the data if it is // eventually done (for promise propagation). -function dataCallback(callback){return function(data){callback(null,data);return data;};} /** +function dataCallback(callback) { + return function (data) { + callback(null, data); + return data; + }; +} + +/** * Used to interface with the Discord API. - */var Client=(function(_EventEmitter){_inherits(Client,_EventEmitter); /** - * Used to instantiate Discord.Client - * @param {ClientOptions} [options] options that should be passed to the Client. - * @example - * // creates a new Client that will try to reconnect whenever it is disconnected. - * var client = new Discord.Client({ - * revive : true - * }); - */function Client(){var options=arguments.length <= 0 || arguments[0] === undefined?{}:arguments[0];_classCallCheck(this,Client);_EventEmitter.call(this); /** - * Options that were passed to the client when it was instantiated. - * @readonly - * @type {ClientOptions} - */this.options = options || {};this.options.compress = options.compress || !process.browser;this.options.revive = options.revive || false;this.options.rateLimitAsError = options.rateLimitAsError || false;this.options.largeThreshold = options.largeThreshold || 250;this.options.maxCachedMessages = options.maxCachedMessages || 1000; /** - * Internal Client that the Client wraps around. - * @readonly - * @type {InternalClient} - */this.internal = new _InternalClient2["default"](this);} /** - * The users that the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache} a Cache of the Users - * @readonly - * @example - * // log usernames of the users that the client is aware of - * for(var user of client.users){ - * console.log(user.username); - * } - */ /** - * Log the client in using a token. If you want to use methods such as `client.setUsername` or `client.setAvatar`, you must also pass the email and password parameters. - * @param {string} token A valid token that can be used to authenticate the account. - * @param {string} [email] Email of the Discord Account. - * @param {string} [password] Password of the Discord Account. - * @param {function(err: Error, token: string)} [callback] callback callback to the method - * @returns {Promise} Resolves with the token if the login was successful, otherwise it rejects with an error. - * @example - * // log the client in - callback - * client.login("token123", null, null, function(error, token){ - * if(!error){ - * console.log(token); - * } - * }); - * @example - * // log the client in - promise - * client.login("token123") - * .then(token => console.log(token)) - * .catch(err => console.log(err)); - */Client.prototype.loginWithToken = function loginWithToken(token){var email=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var password=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, token*/{}:arguments[3];if(typeof email === "function"){ // email is the callback -callback = email;email = null;password = null;}return this.internal.loginWithToken(token,email,password).then(dataCallback(callback),errorCallback(callback));}; /** - * Log the client in using an email and password. - * @param {string} email Email of the Discord Account. - * @param {string} password Password of the Discord Account. - * @param {function(err: Error, token: string)} [callback] callback callback to the method - * @returns {Promise} Resolves with the token if the login was successful, otherwise it rejects with an error. - * @example - * // log the client in - callback - * client.login("jeff@gmail.com", "password", function(error, token){ - * if(!error){ - * console.log(token); - * } - * }); - * @example - * // log the client in - promise - * client.login("jeff@gmail.com", "password") - * .then(token => console.log(token)) - * .catch(err => console.log(err)); - */Client.prototype.login = function login(email,password){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, token*/{}:arguments[2];return this.internal.login(email,password).then(dataCallback(callback),errorCallback(callback));}; /** - * Logs the client out gracefully and closes all WebSocket connections. Client still retains its Caches. - * @param {function(err: Error)} [callback] callback callback to the method - * @returns {Promise} Resolves with null if the logout was successful, otherwise it rejects with an error. - * @example - * // log the client out - callback - * client.logout(function(error){ - * if(error){ - * console.log("Couldn't log out."); - * }else{ - * console.log("Logged out!"); - * } - * }); - * @example - * // log the client out - promise - * client.logout() - * .then(() => console.log("Logged out!")) - * .catch(error => console.log("Couldn't log out.")); - */Client.prototype.logout = function logout(){var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.logout().then(dataCallback(callback),errorCallback(callback));}; /** - * Similar to log out but this should be used if you know you aren't going to be creating the Client again later in your program. - * @param {function(err: Error)} [callback] callback callback to the method - * @returns {Promise} Resolves with null if the destruction was successful, otherwise it rejects with an error. - * @example - * // destroy the client - callback - * client.destroy(function(error){ - * if(error){ - * console.log("Couldn't destroy client."); - * }else{ - * console.log("Client destroyed!"); - * } - * }); - * @example - * // destroy the client - promise - * client.destroy() - * .then(() => console.log("Client destroyed!")) - * .catch(error => console.log("Couldn't destroy client.")); - */Client.prototype.destroy = function destroy(){var _this=this;var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.logout().then(function(){return _this.internal.disconnected(true);}).then(dataCallback(callback),errorCallback(callback));}; /** - * Sends a text message to the specified destination. - * @param {TextChannelResolvable} destination where the message should be sent - * @param {StringResolvable} content message you want to send - * @param {MessageOptions} [options] options you want to apply to the message - * @param {function(err: Error, msg: Message)} [callback] to the method - * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. - * @example - * // sending messages - * client.sendMessage(channel, "Hi there!"); - * client.sendMessage(user, "This is a PM message!"); - * client.sendMessage(server, "This message was sent to the #general channel of the server!"); - * client.sendMessage(channel, "This message is TTS.", {tts : true}); - * @example - * // callbacks - * client.sendMessage(channel, "Hi there!", function(err, msg){ - * if(err){ - * console.log("Couldn't send message"); - * }else{ - * console.log("Message sent!"); - * } - * }); - * @example - * // promises - * client.sendMessage(channel, "Hi there!") - * .then(msg => console.log("Message sent!")) - * .catch(err => console.log("Couldn't send message")); - */Client.prototype.sendMessage = function sendMessage(destination,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, msg*/{}:arguments[3];if(typeof options === "function"){ // options is the callback -callback = options;options = {};}if(typeof content === "object" && content.file){ // content has file -options = content;content = "";}return this.internal.sendMessage(destination,content,options).then(dataCallback(callback),errorCallback(callback));}; /** - * Sends a TTS text message to the specified destination. - * @param {TextChannelResolvable} destination where the message should be sent - * @param {StringResolvable} content message you want to send - * @param {function(err: Error, msg: Message)} [callback] to the method - * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. - * @example - * // sending messages - * client.sendTTSMessage(channel, "This message is TTS."); - * @example - * // callbacks - * client.sendTTSMessage(channel, "Hi there!", function(err, msg){ - * if(err){ - * console.log("Couldn't send message"); - * }else{ - * console.log("Message sent!"); - * } - * }); - * @example - * // promises - * client.sendTTSMessage(channel, "Hi there!") - * .then(msg => console.log("Message sent!")) - * .catch(err => console.log("Couldn't send message")); - */Client.prototype.sendTTSMessage = function sendTTSMessage(destination,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, msg*/{}:arguments[2];return this.sendMessage(destination,content,{tts:true}).then(dataCallback(callback),errorCallback(callback));}; /** - * Replies to the author of a message in the same channel the message was sent. - * @param {MessageResolvable} message the message to reply to - * @param {StringResolvable} content message you want to send - * @param {MessageOptions} [options] options you want to apply to the message - * @param {function(err: Error, msg: Message)} [callback] to the method - * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. - * @example - * // reply to messages - * client.reply(message, "Hello there!"); - * client.reply(message, "Hello there, this is a TTS reply!", {tts:true}); - * @example - * // callbacks - * client.reply(message, "Hi there!", function(err, msg){ - * if(err){ - * console.log("Couldn't send message"); - * }else{ - * console.log("Message sent!"); - * } - * }); - * @example - * // promises - * client.reply(message, "Hi there!") - * .then(msg => console.log("Message sent!")) - * .catch(err => console.log("Couldn't send message")); - */Client.prototype.reply = function reply(message,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, msg*/{}:arguments[3];if(typeof options === "function"){ // options is the callback -callback = options;options = {};}var msg=this.internal.resolver.resolveMessage(message);if(msg){if(!(msg.channel instanceof _StructuresPMChannel2["default"])){content = msg.author + ", " + content;}return this.internal.sendMessage(msg,content,options).then(dataCallback(callback),errorCallback(callback));}var err=new Error("Destination not resolvable to a message!");callback(err);return Promise.reject(err);}; /** - * Replies to the author of a message in the same channel the message was sent using TTS. - * @param {MessageResolvable} message the message to reply to - * @param {StringResolvable} content message you want to send - * @param {function(err: Error, msg: Message)} [callback] to the method - * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. - * @example - * // reply to messages - * client.replyTTS(message, "Hello there, this is a TTS reply!"); - * @example - * // callbacks - * client.replyTTS(message, "Hi there!", function(err, msg){ - * if(err){ - * console.log("Couldn't send message"); - * }else{ - * console.log("Message sent!"); - * } - * }); - * @example - * // promises - * client.replyTTS(message, "Hi there!") - * .then(msg => console.log("Message sent!")) - * .catch(err => console.log("Couldn't send message")); - */Client.prototype.replyTTS = function replyTTS(message,content){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, msg*/{}:arguments[2];return this.reply(message,content,{tts:true}).then(dataCallback(callback),errorCallback(callback));}; /** - * Deletes a message (if the client has permission to) - * @param {MessageResolvable} message the message to delete - * @param {MessageDeletionOptions} [options] options to apply when deleting the message - * @param {function(err: Error)} [callback] callback to the method - * @returns {Promise} Resolves with null if the deletion was successful, otherwise rejects with an Error. - * @example - * // deleting messages - * client.deleteMessage(message); - * client.deleteMessage(message, {wait:5000}); //deletes after 5 seconds - * @example - * // deleting messages - callback - * client.deleteMessage(message, function(err){ - * if(err){ - * console.log("couldn't delete"); - * } - * }); - * @example - * // deleting messages - promise - * client.deleteMessage(message) - * .then(() => console.log("deleted!")) - * .catch(err => console.log("couldn't delete")); - */Client.prototype.deleteMessage = function deleteMessage(message){var options=arguments.length <= 1 || arguments[1] === undefined?{}:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];if(typeof options === "function"){ // options is the callback -callback = options;options = {};}return this.internal.deleteMessage(message,options).then(dataCallback(callback),errorCallback(callback));}; /** - * Edits a previously sent message (if the client has permission to) - * @param {MessageResolvable} message the message to edit - * @param {StringResolvable} content the new content of the message - * @param {MessageOptions} [options] options to apply to the message - * @param {function(err: Error, msg: Message)} [callback] callback to the method - * @returns {Promise} Resolves with the newly edited message if successful, otherwise rejects with an Error. - * @example - * // editing messages - * client.updateMessage(message, "This is an edit!"); - * @example - * // editing messages - callback - * client.updateMessage(message, "This is an edit!", function(err, msg){ - * if(err){ - * console.log("couldn't edit"); - * } - * }); - * @example - * // editing messages - promise - * client.updateMessage(message, "This is an edit!") - * .then(msg => console.log("edited!")) - * .catch(err => console.log("couldn't edit")); - */Client.prototype.updateMessage = function updateMessage(message,content){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, msg*/{}:arguments[3];if(typeof options === "function"){ // options is the callback -callback = options;options = {};}return this.internal.updateMessage(message,content,options).then(dataCallback(callback),errorCallback(callback));}; /** - * Gets the logs of a channel with a specified limit, starting from the most recent message. - * @param {TextChannelResolvable} where the channel to get the logs of - * @param {Number} [limit=50] Integer, the maximum amount of messages to retrieve - * @param {ChannelLogsOptions} [options] options to use when getting the logs - * @param {function(err: Error, logs: Array)} [callback] callback to the method - * @returns {Promise, Error>} Resolves with an array of messages if successful, otherwise rejects with an error. - * @example - * // log content of last 500 messages in channel - callback - * client.getChannelLogs(channel, 500, function(err, logs){ - * if(!err){ - * for(var message of logs){ - * console.log(message.content); - * } - * } - * }); - * @example - * // log content of last 500 messages in channel - promise - * client.getChannelLogs(channel, 500) - * .then(logs => { - * for(var message of logs){ - * console.log(message.content); - * } - * }) - * .catch(err => console.log("couldn't fetch logs")); - */Client.prototype.getChannelLogs = function getChannelLogs(where){var limit=arguments.length <= 1 || arguments[1] === undefined?50:arguments[1];var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, logs*/{}:arguments[3];if(typeof options === "function"){ // options is the callback -callback = options;options = {};}else if(typeof limit === "function"){ // options is the callback -callback = limit;limit = 50;}return this.internal.getChannelLogs(where,limit,options).then(dataCallback(callback),errorCallback(callback));}; /** - * Gets the banned users of a server (if the client has permission to) - * @param {ServerResolvable} server server to get banned users of - * @param {function(err: Error, bans: Array)} [callback] callback to the method - * @returns {Promise, Error>} Resolves with an array of users if the request was successful, otherwise rejects with an error. - * @example - * // loop through banned users - callback - * client.getBans(server, function(err, bans){ - * if(!err){ - * for(var user of bans){ - * console.log(user.username + " was banned from " + server.name); - * } - * } - * }); - * @example - * // loop through banned users - promise - * client.getBans(server) - * .then(bans => { - * for(var user of bans){ - * console.log(user.username + " was banned from " + server.name); - * } - * }) - * .catch(err => console.log("couldn't get bans")); - */Client.prototype.getBans = function getBans(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, bans*/{}:arguments[1];return this.internal.getBans(server).then(dataCallback(callback),errorCallback(callback));}; /** - * Sends a file (embedded if possible) to the specified channel. - * @param {TextChannelResolvable} destination channel to send the file to - * @param {FileResolvable} attachment the file to send - * @param {string} name name of the file, especially including the extension - * @param {function(err: Error, msg: Message)} [callback] callback to the method - * @returns {Promise} resolves with the sent file as a message if successful, otherwise rejects with an error - * @example - * // send a file - callback - * client.sendFile(channel, new Buffer("Hello this a text file"), "file.txt", function(err, msg){ - * if(err){ - * console.log("Couldn't send file!"); - * } - * }); - * @example - * // send a file - promises - * client.sendFile(channel, "C:/path/to/file.txt", "file.txt") - * .then(msg => console.log("sent file!")) - * .catch(err => console.log("couldn't send file!")); - */Client.prototype.sendFile = function sendFile(destination,attachment,name,content){var callback=arguments.length <= 4 || arguments[4] === undefined?function() /*err, m*/{}:arguments[4];if(typeof content === "function"){ // content is the callback -callback = content;content = undefined; // Will get resolved into original filename in internal -}if(typeof name === "function"){ // name is the callback -callback = name;name = undefined; // Will get resolved into original filename in internal -}return this.internal.sendFile(destination,attachment,name,content).then(dataCallback(callback),errorCallback(callback));}; /** - * Client accepts the specified invite to join a server. If the Client is already in the server, the promise/callback resolve immediately. - * @param {InviteIDResolvable} invite invite to the server - * @param {function(err: Error, server: Server)} [callback] callback to the method. - * @returns {Promise} resolves with the newly joined server if succesful, rejects with an error if not. - * @example - * // join a server - callback - * client.joinServer("https://discord.gg/0BwZcrFhUKZ55bJL", function(err, server){ - * if(!err){ - * console.log("Joined " + server.name); - * } - * }); - * @example - * // join a server - promises - * client.joinServer("https://discord.gg/0BwZcrFhUKZ55bJL") - * .then(server => console.log("Joined " + server.name)) - * .catch(err => console.log("Couldn't join!")); - */Client.prototype.joinServer = function joinServer(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, srv*/{}:arguments[1];return this.internal.joinServer(invite).then(dataCallback(callback),errorCallback(callback));}; /** - * Creates a Discord Server and joins it - * @param {string} name the name of the server - * @param {region} [region=london] the region of the server - * @param {function(err: Error, server: Server)} [callback] callback to the method - * @returns {Promise} resolves with the newly created server if successful, rejects with an error if not. - * @example - * //creating a server - callback - * client.createServer("discord.js", "london", function(err, server){ - * if(err){ - * console.log("could not create server"); - * } - * }); - * @example - * //creating a server - promises - * client.createServer("discord.js", "london") - * .then(server => console.log("Made server!")) - * .catch(error => console.log("Couldn't make server!")); - */Client.prototype.createServer = function createServer(name){var region=arguments.length <= 1 || arguments[1] === undefined?"london":arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, srv*/{}:arguments[2];return this.internal.createServer(name,region).then(dataCallback(callback),errorCallback(callback));}; /** - * Leaves a Discord Server - * @param {ServerResolvable} server the server to leave - * @param {function(err: Error)} [callback] callback to the method - * @returns {Promise} resolves null if successful, otherwise rejects with an error. - */Client.prototype.leaveServer = function leaveServer(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.leaveServer(server).then(dataCallback(callback),errorCallback(callback));}; // def updateServer -Client.prototype.updateServer = function updateServer(server,options,region){var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, srv*/{}:arguments[3];if(typeof region === "function"){ // region is the callback -callback = region;region = undefined;}else if(region && typeof options === "string"){options = {name:options,region:region};}return this.internal.updateServer(server,options).then(dataCallback(callback),errorCallback(callback));}; /** - * Deletes a Discord Server - * @param {ServerResolvable} server the server to leave - * @param {function(err: Error)} [callback] callback to the method - * @returns {Promise} resolves null if successful, otherwise rejects with an error. - */Client.prototype.deleteServer = function deleteServer(server){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteServer(server).then(dataCallback(callback),errorCallback(callback));}; // def createChannel -Client.prototype.createChannel = function createChannel(server,name){var type=arguments.length <= 2 || arguments[2] === undefined?"text":arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, channel*/{}:arguments[3];if(typeof type === "function"){ // options is the callback -callback = type;type = "text";}return this.internal.createChannel(server,name,type).then(dataCallback(callback),errorCallback(callback));}; // def deleteChannel -Client.prototype.deleteChannel = function deleteChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteChannel(channel).then(dataCallback(callback),errorCallback(callback));}; // def banMember -Client.prototype.banMember = function banMember(user,server){var length=arguments.length <= 2 || arguments[2] === undefined?1:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];if(typeof length === "function"){ // length is the callback -callback = length;length = 1;}return this.internal.banMember(user,server,length).then(dataCallback(callback),errorCallback(callback));}; // def unbanMember -Client.prototype.unbanMember = function unbanMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.unbanMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def kickMember -Client.prototype.kickMember = function kickMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.kickMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def moveMember -Client.prototype.moveMember = function moveMember(user,channel){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.moveMember(user,channel).then(dataCallback(callback),errorCallback(callback));}; // def muteMember -Client.prototype.muteMember = function muteMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.muteMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def unmuteMember -Client.prototype.unmuteMember = function unmuteMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.unmuteMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def deafenMember -Client.prototype.deafenMember = function deafenMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.deafenMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def undeafenMember -Client.prototype.undeafenMember = function undeafenMember(user,server){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.undeafenMember(user,server).then(dataCallback(callback),errorCallback(callback));}; // def createRole -Client.prototype.createRole = function createRole(server){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, role*/{}:arguments[2];if(typeof data === "function"){ // data is the callback -callback = data;data = null;}return this.internal.createRole(server,data).then(dataCallback(callback),errorCallback(callback));}; // def updateRole -Client.prototype.updateRole = function updateRole(role){var data=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, role*/{}:arguments[2];if(typeof data === "function"){ // data is the callback -callback = data;data = null;}return this.internal.updateRole(role,data).then(dataCallback(callback),errorCallback(callback));}; // def deleteRole -Client.prototype.deleteRole = function deleteRole(role){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteRole(role).then(dataCallback(callback),errorCallback(callback));}; // def addMemberToRole -Client.prototype.addMemberToRole = function addMemberToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.addMemberToRole(member,role).then(dataCallback(callback),errorCallback(callback));}; // def addUserToRole -Client.prototype.addUserToRole = function addUserToRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.addMemberToRole(member,role,callback);}; // def addUserToRole -Client.prototype.memberHasRole = function memberHasRole(member,role){return this.internal.memberHasRole(member,role);}; // def addUserToRole -Client.prototype.userHasRole = function userHasRole(member,role){return this.memberHasRole(member,role);}; // def removeMemberFromRole -Client.prototype.removeMemberFromRole = function removeMemberFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.removeMemberFromRole(member,role).then(dataCallback(callback),errorCallback(callback));}; // def removeUserFromRole -Client.prototype.removeUserFromRole = function removeUserFromRole(member,role){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.removeMemberFromRole(member,role,callback);}; // def createInvite -Client.prototype.createInvite = function createInvite(chanServ,options){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, invite*/{}:arguments[2];if(typeof options === "function"){ // options is the callback -callback = options;options = undefined;}return this.internal.createInvite(chanServ,options).then(dataCallback(callback),errorCallback(callback));}; // def deleteInvite -Client.prototype.deleteInvite = function deleteInvite(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.deleteInvite(invite).then(dataCallback(callback),errorCallback(callback));}; // def getInvite -Client.prototype.getInvite = function getInvite(invite){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, inv*/{}:arguments[1];return this.internal.getInvite(invite).then(dataCallback(callback),errorCallback(callback));}; // def getInvites -Client.prototype.getInvites = function getInvites(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, inv*/{}:arguments[1];return this.internal.getInvites(channel).then(dataCallback(callback),errorCallback(callback));}; // def overwritePermissions -Client.prototype.overwritePermissions = function overwritePermissions(channel,role){var options=arguments.length <= 2 || arguments[2] === undefined?{}:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];return this.internal.overwritePermissions(channel,role,options).then(dataCallback(callback),errorCallback(callback));}; // def setStatus -Client.prototype.setStatus = function setStatus(idleStatus,game){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];if(typeof game === "function"){ // game is the callback -callback = game;game = null;}else if(typeof idleStatus === "function"){ // idleStatus is the callback -callback = idleStatus;game = null;}return this.internal.setStatus(idleStatus,game).then(dataCallback(callback),errorCallback(callback));}; // def sendTyping -Client.prototype.sendTyping = function sendTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.sendTyping(channel).then(dataCallback(callback),errorCallback(callback));}; // def setChannelTopic -Client.prototype.setChannelTopic = function setChannelTopic(channel,topic){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelTopic(channel,topic).then(dataCallback(callback),errorCallback(callback));}; // def setChannelName -Client.prototype.setChannelName = function setChannelName(channel,name){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelName(channel,name).then(dataCallback(callback),errorCallback(callback));}; // def setChannelNameAndTopic -Client.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(channel,name,topic){var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, {}*/{}:arguments[3];return this.internal.setChannelNameAndTopic(channel,name,topic).then(dataCallback(callback),errorCallback(callback));}; // def setChannelPosition -Client.prototype.setChannelPosition = function setChannelPosition(channel,position){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.setChannelPosition(channel,position).then(dataCallback(callback),errorCallback(callback));}; // def updateChannel -Client.prototype.updateChannel = function updateChannel(channel,data){var callback=arguments.length <= 2 || arguments[2] === undefined?function() /*err, {}*/{}:arguments[2];return this.internal.updateChannel(channel,data).then(dataCallback(callback),errorCallback(callback));}; // def startTyping -Client.prototype.startTyping = function startTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.startTyping(channel).then(dataCallback(callback),errorCallback(callback));}; // def stopTyping -Client.prototype.stopTyping = function stopTyping(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.stopTyping(channel).then(dataCallback(callback),errorCallback(callback));}; // def updateDetails -Client.prototype.updateDetails = function updateDetails(details){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.updateDetails(details).then(dataCallback(callback),errorCallback(callback));}; // def setUsername -Client.prototype.setUsername = function setUsername(name){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.setUsername(name).then(dataCallback(callback),errorCallback(callback));}; // def setAvatar -Client.prototype.setAvatar = function setAvatar(avatar){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.setAvatar(avatar).then(dataCallback(callback),errorCallback(callback));}; // def joinVoiceChannel -Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, channel*/{}:arguments[1];return this.internal.joinVoiceChannel(channel).then(dataCallback(callback),errorCallback(callback));}; // def leaveVoiceChannel -Client.prototype.leaveVoiceChannel = function leaveVoiceChannel(chann){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.leaveVoiceChannel(chann).then(dataCallback(callback),errorCallback(callback));}; // def addFriend -Client.prototype.addFriend = function addFriend(user){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.addFriend(user).then(dataCallback(callback),errorCallback(callback));}; // def removeFriend -Client.prototype.removeFriend = function removeFriend(user){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.internal.removeFriend(user).then(dataCallback(callback),errorCallback(callback));}; // def awaitResponse -Client.prototype.awaitResponse = function awaitResponse(msg){var toSend=arguments.length <= 1 || arguments[1] === undefined?null:arguments[1];var _this2=this;var options=arguments.length <= 2 || arguments[2] === undefined?null:arguments[2];var callback=arguments.length <= 3 || arguments[3] === undefined?function() /*err, newMsg*/{}:arguments[3];var ret;if(toSend){if(typeof toSend === "function"){ // (msg, callback) -callback = toSend;toSend = null;options = null;}else { // (msg, toSend, ...) -if(options){if(typeof options === "function"){ //(msg, toSend, callback) -callback = options;options = null;ret = this.sendMessage(msg,toSend);}else { //(msg, toSend, options, callback) -ret = this.sendMessage(msg,toSend,options);}}else { // (msg, toSend) promise -ret = this.sendMessage(msg,toSend);}}}if(!ret){ret = Promise.resolve();} // (msg) promise -return ret.then(function(){return _this2.internal.awaitResponse(msg);}).then(dataCallback(callback),errorCallback(callback));};Client.prototype.setStatusIdle = function setStatusIdle(){var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.setStatus("idle").then(dataCallback(callback),errorCallback(callback));};Client.prototype.setStatusOnline = function setStatusOnline(){var callback=arguments.length <= 0 || arguments[0] === undefined?function() /*err, {}*/{}:arguments[0];return this.internal.setStatus("online").then(dataCallback(callback),errorCallback(callback));};Client.prototype.setStatusActive = function setStatusActive(callback){return this.setStatusOnline(callback);};Client.prototype.setStatusHere = function setStatusHere(callback){return this.setStatusOnline(callback);};Client.prototype.setStatusAvailable = function setStatusAvailable(callback){return this.setStatusOnline(callback);};Client.prototype.setStatusAway = function setStatusAway(callback){return this.setStatusIdle(callback);};Client.prototype.setPlayingGame = function setPlayingGame(game){var callback=arguments.length <= 1 || arguments[1] === undefined?function() /*err, {}*/{}:arguments[1];return this.setStatus(null,game,callback);}; //def forceFetchUsers -Client.prototype.forceFetchUsers = function forceFetchUsers(callback){return this.internal.forceFetchUsers().then(callback);};_createClass(Client,[{key:"users",get:function get(){return this.internal.users;} /** - * The server channels the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache} a Cache of the Server Channels - * @readonly - * @example - * // log the names of the channels and the server they belong to - * for(var channel of client.channels){ - * console.log(`${channel.name} is part of ${channel.server.name}`) - * } - */},{key:"channels",get:function get(){return this.internal.channels;} /** - * The servers the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache} a Cache of the Servers - * @readonly - * @example - * // log the names of the servers - * for(var server of client.servers){ - * console.log(server.name) - * } - */},{key:"servers",get:function get(){return this.internal.servers;} /** - * The PM/DM chats the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache} a Cache of the PM/DM Channels. - * @readonly - * @example - * // log the names of the users the client is participating in a PM with - * for(var pm of client.privateChannels){ - * console.log(`Participating in a DM with ${pm.recipient}`) - * } - */},{key:"privateChannels",get:function get(){return this.internal.private_channels;} /** - * The friends that the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache|null} a Cache of friend Users (or null if bot account) - * @readonly - * @example - * // log names of the friends that the client is aware of - * for(var user of client.friends){ - * console.log(user.username); - * } - */},{key:"friends",get:function get(){return this.internal.friends;} /** - * The incoming friend requests that the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache|null} a Cache of incoming friend request Users (or null if bot account) - * @readonly - * @example - * // log names of the incoming friend requests that the client is aware of - * for(var user of client.incomingFriendRequests){ - * console.log(user.username); - * } - */},{key:"incomingFriendRequests",get:function get(){return this.internal.incoming_friend_requests;} /** - * The outgoing friend requests that the Client is aware of. Only available after `ready` event has been emitted. - * @type {Cache} a Cache of outgoing friend request Users - * @readonly - * @example - * // log names of the outgoing friend requests that the client is aware of - * for(var user of client.outgoingFriendRequests){ - * console.log(user.username); - * } - */},{key:"outgoingFriendRequests",get:function get(){return this.internal.outgoing_friend_requests;} /** - * A cache of active voice connection of the Client, or null if not applicable. Only available after `ready` event has been emitted. - * @type {Cache} a Cache of Voice Connections - */},{key:"voiceConnections",get:function get(){return this.internal.voiceConnections;} /** - * The first voice connection the bot has connected to. Available for backwards compatibility. - * @type {VoiceConnection} first voice connection - */},{key:"voiceConnection",get:function get(){return this.internal.voiceConnection;} /** - * Unix timestamp of when the Client first emitted the `ready `event. Only available after `ready` event has been emitted. - * @type {Number} timestamp of ready time - * @example - * // output when the client was ready - * console.log("I was first ready at " + client.readyTime); - */},{key:"readyTime",get:function get(){return this.internal.readyTime;} /** - * How long the client has been ready for in milliseconds. Only available after `ready` event has been emitted. - * @type {Number} number in milliseconds representing uptime of the client - * @example - * // log how long the client has been up for - * console.log("I have been online for " + client.uptime + " milliseconds"); - */},{key:"uptime",get:function get(){return this.internal.uptime;} /** - * A User object that represents the account the client is logged into. Only available after `ready` event has been emitted. - * @type {User} user representing logged in account of client. - * @example - * // log username of logged in account of client - * console.log("Logged in as " + client.user.username); - */},{key:"user",get:function get(){return this.internal.user;} /** - * Object containing user-agent information required for API requests. If not modified, it will use discord.js's defaults. - * @type {UserAgent} - * @example - * // log the stringified user-agent: - * console.log(client.userAgent.full); - */},{key:"userAgent",get:function get(){return this.internal.userAgent;}, /** - * Set the user-agent information provided. Follows the UserAgent typedef format excluding the `full` property. - * @type {UserAgent} - */set:function set(userAgent){this.internal.userAgent = userAgent;}}]);return Client;})(_events2["default"]);exports["default"] = Client;module.exports = exports["default"]; + */ + +var Client = (function (_EventEmitter) { + _inherits(Client, _EventEmitter); + + /** + * Used to instantiate Discord.Client + * @param {ClientOptions} [options] options that should be passed to the Client. + * @example + * // creates a new Client that will try to reconnect whenever it is disconnected. + * var client = new Discord.Client({ + * revive : true + * }); + */ + + function Client() { + var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; + + _classCallCheck(this, Client); + + _EventEmitter.call(this); + /** + * Options that were passed to the client when it was instantiated. + * @readonly + * @type {ClientOptions} + */ + this.options = options || {}; + this.options.compress = options.compress || !process.browser; + this.options.revive = options.revive || false; + this.options.rateLimitAsError = options.rateLimitAsError || false; + this.options.largeThreshold = options.largeThreshold || 250; + this.options.maxCachedMessages = options.maxCachedMessages || 1000; + /** + * Internal Client that the Client wraps around. + * @readonly + * @type {InternalClient} + */ + this.internal = new _InternalClient2["default"](this); + } + + /** + * The users that the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache} a Cache of the Users + * @readonly + * @example + * // log usernames of the users that the client is aware of + * for(var user of client.users){ + * console.log(user.username); + * } + */ + + /** + * Log the client in using a token. If you want to use methods such as `client.setUsername` or `client.setAvatar`, you must also pass the email and password parameters. + * @param {string} token A valid token that can be used to authenticate the account. + * @param {string} [email] Email of the Discord Account. + * @param {string} [password] Password of the Discord Account. + * @param {function(err: Error, token: string)} [callback] callback callback to the method + * @returns {Promise} Resolves with the token if the login was successful, otherwise it rejects with an error. + * @example + * // log the client in - callback + * client.login("token123", null, null, function(error, token){ + * if(!error){ + * console.log(token); + * } + * }); + * @example + * // log the client in - promise + * client.login("token123") + * .then(token => console.log(token)) + * .catch(err => console.log(err)); + */ + + Client.prototype.loginWithToken = function loginWithToken(token) { + var email = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var password = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, token*/{} : arguments[3]; + + if (typeof email === "function") { + // email is the callback + callback = email; + email = null; + password = null; + } + + return this.internal.loginWithToken(token, email, password).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Log the client in using an email and password. + * @param {string} email Email of the Discord Account. + * @param {string} password Password of the Discord Account. + * @param {function(err: Error, token: string)} [callback] callback callback to the method + * @returns {Promise} Resolves with the token if the login was successful, otherwise it rejects with an error. + * @example + * // log the client in - callback + * client.login("jeff@gmail.com", "password", function(error, token){ + * if(!error){ + * console.log(token); + * } + * }); + * @example + * // log the client in - promise + * client.login("jeff@gmail.com", "password") + * .then(token => console.log(token)) + * .catch(err => console.log(err)); + */ + + Client.prototype.login = function login(email, password) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, token*/{} : arguments[2]; + + return this.internal.login(email, password).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Logs the client out gracefully and closes all WebSocket connections. Client still retains its Caches. + * @param {function(err: Error)} [callback] callback callback to the method + * @returns {Promise} Resolves with null if the logout was successful, otherwise it rejects with an error. + * @example + * // log the client out - callback + * client.logout(function(error){ + * if(error){ + * console.log("Couldn't log out."); + * }else{ + * console.log("Logged out!"); + * } + * }); + * @example + * // log the client out - promise + * client.logout() + * .then(() => console.log("Logged out!")) + * .catch(error => console.log("Couldn't log out.")); + */ + + Client.prototype.logout = function logout() { + var callback = arguments.length <= 0 || arguments[0] === undefined ? function () /*err, {}*/{} : arguments[0]; + + return this.internal.logout().then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Similar to log out but this should be used if you know you aren't going to be creating the Client again later in your program. + * @param {function(err: Error)} [callback] callback callback to the method + * @returns {Promise} Resolves with null if the destruction was successful, otherwise it rejects with an error. + * @example + * // destroy the client - callback + * client.destroy(function(error){ + * if(error){ + * console.log("Couldn't destroy client."); + * }else{ + * console.log("Client destroyed!"); + * } + * }); + * @example + * // destroy the client - promise + * client.destroy() + * .then(() => console.log("Client destroyed!")) + * .catch(error => console.log("Couldn't destroy client.")); + */ + + Client.prototype.destroy = function destroy() { + var _this = this; + + var callback = arguments.length <= 0 || arguments[0] === undefined ? function () /*err, {}*/{} : arguments[0]; + + return this.internal.logout().then(function () { + return _this.internal.disconnected(true); + }).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Sends a text message to the specified destination. + * @param {TextChannelResolvable} destination where the message should be sent + * @param {StringResolvable} content message you want to send + * @param {MessageOptions} [options] options you want to apply to the message + * @param {function(err: Error, msg: Message)} [callback] to the method + * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. + * @example + * // sending messages + * client.sendMessage(channel, "Hi there!"); + * client.sendMessage(user, "This is a PM message!"); + * client.sendMessage(server, "This message was sent to the #general channel of the server!"); + * client.sendMessage(channel, "This message is TTS.", {tts : true}); + * @example + * // callbacks + * client.sendMessage(channel, "Hi there!", function(err, msg){ + * if(err){ + * console.log("Couldn't send message"); + * }else{ + * console.log("Message sent!"); + * } + * }); + * @example + * // promises + * client.sendMessage(channel, "Hi there!") + * .then(msg => console.log("Message sent!")) + * .catch(err => console.log("Couldn't send message")); + */ + + Client.prototype.sendMessage = function sendMessage(destination, content) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, msg*/{} : arguments[3]; + + if (typeof options === "function") { + // options is the callback + callback = options; + options = {}; + } + if (typeof content === "object" && content.file) { + // content has file + options = content; + content = ""; + } + + return this.internal.sendMessage(destination, content, options).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Sends a TTS text message to the specified destination. + * @param {TextChannelResolvable} destination where the message should be sent + * @param {StringResolvable} content message you want to send + * @param {function(err: Error, msg: Message)} [callback] to the method + * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. + * @example + * // sending messages + * client.sendTTSMessage(channel, "This message is TTS."); + * @example + * // callbacks + * client.sendTTSMessage(channel, "Hi there!", function(err, msg){ + * if(err){ + * console.log("Couldn't send message"); + * }else{ + * console.log("Message sent!"); + * } + * }); + * @example + * // promises + * client.sendTTSMessage(channel, "Hi there!") + * .then(msg => console.log("Message sent!")) + * .catch(err => console.log("Couldn't send message")); + */ + + Client.prototype.sendTTSMessage = function sendTTSMessage(destination, content) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, msg*/{} : arguments[2]; + + return this.sendMessage(destination, content, { tts: true }).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Replies to the author of a message in the same channel the message was sent. + * @param {MessageResolvable} message the message to reply to + * @param {StringResolvable} content message you want to send + * @param {MessageOptions} [options] options you want to apply to the message + * @param {function(err: Error, msg: Message)} [callback] to the method + * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. + * @example + * // reply to messages + * client.reply(message, "Hello there!"); + * client.reply(message, "Hello there, this is a TTS reply!", {tts:true}); + * @example + * // callbacks + * client.reply(message, "Hi there!", function(err, msg){ + * if(err){ + * console.log("Couldn't send message"); + * }else{ + * console.log("Message sent!"); + * } + * }); + * @example + * // promises + * client.reply(message, "Hi there!") + * .then(msg => console.log("Message sent!")) + * .catch(err => console.log("Couldn't send message")); + */ + + Client.prototype.reply = function reply(message, content) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, msg*/{} : arguments[3]; + + if (typeof options === "function") { + // options is the callback + callback = options; + options = {}; + } + + var msg = this.internal.resolver.resolveMessage(message); + if (msg) { + if (!(msg.channel instanceof _StructuresPMChannel2["default"])) { + content = msg.author + ", " + content; + } + return this.internal.sendMessage(msg, content, options).then(dataCallback(callback), errorCallback(callback)); + } + var err = new Error("Destination not resolvable to a message!"); + callback(err); + return Promise.reject(err); + }; + + /** + * Replies to the author of a message in the same channel the message was sent using TTS. + * @param {MessageResolvable} message the message to reply to + * @param {StringResolvable} content message you want to send + * @param {function(err: Error, msg: Message)} [callback] to the method + * @returns {Promise} Resolves with a Message if successful, otherwise rejects with an Error. + * @example + * // reply to messages + * client.replyTTS(message, "Hello there, this is a TTS reply!"); + * @example + * // callbacks + * client.replyTTS(message, "Hi there!", function(err, msg){ + * if(err){ + * console.log("Couldn't send message"); + * }else{ + * console.log("Message sent!"); + * } + * }); + * @example + * // promises + * client.replyTTS(message, "Hi there!") + * .then(msg => console.log("Message sent!")) + * .catch(err => console.log("Couldn't send message")); + */ + + Client.prototype.replyTTS = function replyTTS(message, content) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, msg*/{} : arguments[2]; + + return this.reply(message, content, { tts: true }).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Deletes a message (if the client has permission to) + * @param {MessageResolvable} message the message to delete + * @param {MessageDeletionOptions} [options] options to apply when deleting the message + * @param {function(err: Error)} [callback] callback to the method + * @returns {Promise} Resolves with null if the deletion was successful, otherwise rejects with an Error. + * @example + * // deleting messages + * client.deleteMessage(message); + * client.deleteMessage(message, {wait:5000}); //deletes after 5 seconds + * @example + * // deleting messages - callback + * client.deleteMessage(message, function(err){ + * if(err){ + * console.log("couldn't delete"); + * } + * }); + * @example + * // deleting messages - promise + * client.deleteMessage(message) + * .then(() => console.log("deleted!")) + * .catch(err => console.log("couldn't delete")); + */ + + Client.prototype.deleteMessage = function deleteMessage(message) { + var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + if (typeof options === "function") { + // options is the callback + callback = options; + options = {}; + } + + return this.internal.deleteMessage(message, options).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Edits a previously sent message (if the client has permission to) + * @param {MessageResolvable} message the message to edit + * @param {StringResolvable} content the new content of the message + * @param {MessageOptions} [options] options to apply to the message + * @param {function(err: Error, msg: Message)} [callback] callback to the method + * @returns {Promise} Resolves with the newly edited message if successful, otherwise rejects with an Error. + * @example + * // editing messages + * client.updateMessage(message, "This is an edit!"); + * @example + * // editing messages - callback + * client.updateMessage(message, "This is an edit!", function(err, msg){ + * if(err){ + * console.log("couldn't edit"); + * } + * }); + * @example + * // editing messages - promise + * client.updateMessage(message, "This is an edit!") + * .then(msg => console.log("edited!")) + * .catch(err => console.log("couldn't edit")); + */ + + Client.prototype.updateMessage = function updateMessage(message, content) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, msg*/{} : arguments[3]; + + if (typeof options === "function") { + // options is the callback + callback = options; + options = {}; + } + + return this.internal.updateMessage(message, content, options).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Gets the logs of a channel with a specified limit, starting from the most recent message. + * @param {TextChannelResolvable} where the channel to get the logs of + * @param {Number} [limit=50] Integer, the maximum amount of messages to retrieve + * @param {ChannelLogsOptions} [options] options to use when getting the logs + * @param {function(err: Error, logs: Array)} [callback] callback to the method + * @returns {Promise, Error>} Resolves with an array of messages if successful, otherwise rejects with an error. + * @example + * // log content of last 500 messages in channel - callback + * client.getChannelLogs(channel, 500, function(err, logs){ + * if(!err){ + * for(var message of logs){ + * console.log(message.content); + * } + * } + * }); + * @example + * // log content of last 500 messages in channel - promise + * client.getChannelLogs(channel, 500) + * .then(logs => { + * for(var message of logs){ + * console.log(message.content); + * } + * }) + * .catch(err => console.log("couldn't fetch logs")); + */ + + Client.prototype.getChannelLogs = function getChannelLogs(where) { + var limit = arguments.length <= 1 || arguments[1] === undefined ? 50 : arguments[1]; + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, logs*/{} : arguments[3]; + + if (typeof options === "function") { + // options is the callback + callback = options; + options = {}; + } else if (typeof limit === "function") { + // options is the callback + callback = limit; + limit = 50; + } + + return this.internal.getChannelLogs(where, limit, options).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Gets the banned users of a server (if the client has permission to) + * @param {ServerResolvable} server server to get banned users of + * @param {function(err: Error, bans: Array)} [callback] callback to the method + * @returns {Promise, Error>} Resolves with an array of users if the request was successful, otherwise rejects with an error. + * @example + * // loop through banned users - callback + * client.getBans(server, function(err, bans){ + * if(!err){ + * for(var user of bans){ + * console.log(user.username + " was banned from " + server.name); + * } + * } + * }); + * @example + * // loop through banned users - promise + * client.getBans(server) + * .then(bans => { + * for(var user of bans){ + * console.log(user.username + " was banned from " + server.name); + * } + * }) + * .catch(err => console.log("couldn't get bans")); + */ + + Client.prototype.getBans = function getBans(server) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, bans*/{} : arguments[1]; + + return this.internal.getBans(server).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Sends a file (embedded if possible) to the specified channel. + * @param {TextChannelResolvable} destination channel to send the file to + * @param {FileResolvable} attachment the file to send + * @param {string} name name of the file, especially including the extension + * @param {function(err: Error, msg: Message)} [callback] callback to the method + * @returns {Promise} resolves with the sent file as a message if successful, otherwise rejects with an error + * @example + * // send a file - callback + * client.sendFile(channel, new Buffer("Hello this a text file"), "file.txt", function(err, msg){ + * if(err){ + * console.log("Couldn't send file!"); + * } + * }); + * @example + * // send a file - promises + * client.sendFile(channel, "C:/path/to/file.txt", "file.txt") + * .then(msg => console.log("sent file!")) + * .catch(err => console.log("couldn't send file!")); + */ + + Client.prototype.sendFile = function sendFile(destination, attachment, name, content) { + var callback = arguments.length <= 4 || arguments[4] === undefined ? function () /*err, m*/{} : arguments[4]; + + if (typeof content === "function") { + // content is the callback + callback = content; + content = undefined; // Will get resolved into original filename in internal + } + if (typeof name === "function") { + // name is the callback + callback = name; + name = undefined; // Will get resolved into original filename in internal + } + + return this.internal.sendFile(destination, attachment, name, content).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Client accepts the specified invite to join a server. If the Client is already in the server, the promise/callback resolve immediately. + * @param {InviteIDResolvable} invite invite to the server + * @param {function(err: Error, server: Server)} [callback] callback to the method. + * @returns {Promise} resolves with the newly joined server if succesful, rejects with an error if not. + * @example + * // join a server - callback + * client.joinServer("https://discord.gg/0BwZcrFhUKZ55bJL", function(err, server){ + * if(!err){ + * console.log("Joined " + server.name); + * } + * }); + * @example + * // join a server - promises + * client.joinServer("https://discord.gg/0BwZcrFhUKZ55bJL") + * .then(server => console.log("Joined " + server.name)) + * .catch(err => console.log("Couldn't join!")); + */ + + Client.prototype.joinServer = function joinServer(invite) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, srv*/{} : arguments[1]; + + return this.internal.joinServer(invite).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Creates a Discord Server and joins it + * @param {string} name the name of the server + * @param {region} [region=london] the region of the server + * @param {function(err: Error, server: Server)} [callback] callback to the method + * @returns {Promise} resolves with the newly created server if successful, rejects with an error if not. + * @example + * //creating a server - callback + * client.createServer("discord.js", "london", function(err, server){ + * if(err){ + * console.log("could not create server"); + * } + * }); + * @example + * //creating a server - promises + * client.createServer("discord.js", "london") + * .then(server => console.log("Made server!")) + * .catch(error => console.log("Couldn't make server!")); + */ + + Client.prototype.createServer = function createServer(name) { + var region = arguments.length <= 1 || arguments[1] === undefined ? "london" : arguments[1]; + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, srv*/{} : arguments[2]; + + return this.internal.createServer(name, region).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Leaves a Discord Server + * @param {ServerResolvable} server the server to leave + * @param {function(err: Error)} [callback] callback to the method + * @returns {Promise} resolves null if successful, otherwise rejects with an error. + */ + + Client.prototype.leaveServer = function leaveServer(server) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.leaveServer(server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def updateServer + + Client.prototype.updateServer = function updateServer(server, options, region) { + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, srv*/{} : arguments[3]; + + if (typeof region === "function") { + // region is the callback + callback = region; + region = undefined; + } else if (region && typeof options === "string") { + options = { + name: options, + region: region + }; + } + + return this.internal.updateServer(server, options).then(dataCallback(callback), errorCallback(callback)); + }; + + /** + * Deletes a Discord Server + * @param {ServerResolvable} server the server to leave + * @param {function(err: Error)} [callback] callback to the method + * @returns {Promise} resolves null if successful, otherwise rejects with an error. + */ + + Client.prototype.deleteServer = function deleteServer(server) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.deleteServer(server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def createChannel + + Client.prototype.createChannel = function createChannel(server, name) { + var type = arguments.length <= 2 || arguments[2] === undefined ? "text" : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, channel*/{} : arguments[3]; + + if (typeof type === "function") { + // options is the callback + callback = type; + type = "text"; + } + + return this.internal.createChannel(server, name, type).then(dataCallback(callback), errorCallback(callback)); + }; + + // def deleteChannel + + Client.prototype.deleteChannel = function deleteChannel(channel) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.deleteChannel(channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def banMember + + Client.prototype.banMember = function banMember(user, server) { + var length = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, {}*/{} : arguments[3]; + + if (typeof length === "function") { + // length is the callback + callback = length; + length = 1; + } + + return this.internal.banMember(user, server, length).then(dataCallback(callback), errorCallback(callback)); + }; + + // def unbanMember + + Client.prototype.unbanMember = function unbanMember(user, server) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.unbanMember(user, server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def kickMember + + Client.prototype.kickMember = function kickMember(user, server) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.kickMember(user, server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def moveMember + + Client.prototype.moveMember = function moveMember(user, channel) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.moveMember(user, channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def muteMember + + Client.prototype.muteMember = function muteMember(user, server) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.muteMember(user, server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def unmuteMember + + Client.prototype.unmuteMember = function unmuteMember(user, server) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.unmuteMember(user, server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def deafenMember + + Client.prototype.deafenMember = function deafenMember(user, server) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.deafenMember(user, server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def undeafenMember + + Client.prototype.undeafenMember = function undeafenMember(user, server) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.undeafenMember(user, server).then(dataCallback(callback), errorCallback(callback)); + }; + + // def createRole + + Client.prototype.createRole = function createRole(server) { + var data = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, role*/{} : arguments[2]; + + if (typeof data === "function") { + // data is the callback + callback = data; + data = null; + } + + return this.internal.createRole(server, data).then(dataCallback(callback), errorCallback(callback)); + }; + + // def updateRole + + Client.prototype.updateRole = function updateRole(role) { + var data = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, role*/{} : arguments[2]; + + if (typeof data === "function") { + // data is the callback + callback = data; + data = null; + } + return this.internal.updateRole(role, data).then(dataCallback(callback), errorCallback(callback)); + }; + + // def deleteRole + + Client.prototype.deleteRole = function deleteRole(role) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.deleteRole(role).then(dataCallback(callback), errorCallback(callback)); + }; + + // def addMemberToRole + + Client.prototype.addMemberToRole = function addMemberToRole(member, role) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.addMemberToRole(member, role).then(dataCallback(callback), errorCallback(callback)); + }; + + // def addUserToRole + + Client.prototype.addUserToRole = function addUserToRole(member, role) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.addMemberToRole(member, role, callback); + }; + + // def addUserToRole + + Client.prototype.memberHasRole = function memberHasRole(member, role) { + return this.internal.memberHasRole(member, role); + }; + + // def addUserToRole + + Client.prototype.userHasRole = function userHasRole(member, role) { + return this.memberHasRole(member, role); + }; + + // def removeMemberFromRole + + Client.prototype.removeMemberFromRole = function removeMemberFromRole(member, role) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.removeMemberFromRole(member, role).then(dataCallback(callback), errorCallback(callback)); + }; + + // def removeUserFromRole + + Client.prototype.removeUserFromRole = function removeUserFromRole(member, role) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.removeMemberFromRole(member, role, callback); + }; + + // def createInvite + + Client.prototype.createInvite = function createInvite(chanServ, options) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, invite*/{} : arguments[2]; + + if (typeof options === "function") { + // options is the callback + callback = options; + options = undefined; + } + + return this.internal.createInvite(chanServ, options).then(dataCallback(callback), errorCallback(callback)); + }; + + // def deleteInvite + + Client.prototype.deleteInvite = function deleteInvite(invite) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.deleteInvite(invite).then(dataCallback(callback), errorCallback(callback)); + }; + + // def getInvite + + Client.prototype.getInvite = function getInvite(invite) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, inv*/{} : arguments[1]; + + return this.internal.getInvite(invite).then(dataCallback(callback), errorCallback(callback)); + }; + + // def getInvites + + Client.prototype.getInvites = function getInvites(channel) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, inv*/{} : arguments[1]; + + return this.internal.getInvites(channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def overwritePermissions + + Client.prototype.overwritePermissions = function overwritePermissions(channel, role) { + var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, {}*/{} : arguments[3]; + + return this.internal.overwritePermissions(channel, role, options).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setStatus + + Client.prototype.setStatus = function setStatus(idleStatus, game) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + if (typeof game === "function") { + // game is the callback + callback = game; + game = null; + } else if (typeof idleStatus === "function") { + // idleStatus is the callback + callback = idleStatus; + game = null; + } + + return this.internal.setStatus(idleStatus, game).then(dataCallback(callback), errorCallback(callback)); + }; + + // def sendTyping + + Client.prototype.sendTyping = function sendTyping(channel) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.sendTyping(channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setChannelTopic + + Client.prototype.setChannelTopic = function setChannelTopic(channel, topic) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.setChannelTopic(channel, topic).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setChannelName + + Client.prototype.setChannelName = function setChannelName(channel, name) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.setChannelName(channel, name).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setChannelNameAndTopic + + Client.prototype.setChannelNameAndTopic = function setChannelNameAndTopic(channel, name, topic) { + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, {}*/{} : arguments[3]; + + return this.internal.setChannelNameAndTopic(channel, name, topic).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setChannelPosition + + Client.prototype.setChannelPosition = function setChannelPosition(channel, position) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.setChannelPosition(channel, position).then(dataCallback(callback), errorCallback(callback)); + }; + + // def updateChannel + + Client.prototype.updateChannel = function updateChannel(channel, data) { + var callback = arguments.length <= 2 || arguments[2] === undefined ? function () /*err, {}*/{} : arguments[2]; + + return this.internal.updateChannel(channel, data).then(dataCallback(callback), errorCallback(callback)); + }; + + // def startTyping + + Client.prototype.startTyping = function startTyping(channel) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.startTyping(channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def stopTyping + + Client.prototype.stopTyping = function stopTyping(channel) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.stopTyping(channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def updateDetails + + Client.prototype.updateDetails = function updateDetails(details) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.updateDetails(details).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setUsername + + Client.prototype.setUsername = function setUsername(name) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.setUsername(name).then(dataCallback(callback), errorCallback(callback)); + }; + + // def setAvatar + + Client.prototype.setAvatar = function setAvatar(avatar) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.setAvatar(avatar).then(dataCallback(callback), errorCallback(callback)); + }; + + // def joinVoiceChannel + + Client.prototype.joinVoiceChannel = function joinVoiceChannel(channel) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, channel*/{} : arguments[1]; + + return this.internal.joinVoiceChannel(channel).then(dataCallback(callback), errorCallback(callback)); + }; + + // def leaveVoiceChannel + + Client.prototype.leaveVoiceChannel = function leaveVoiceChannel(chann) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.leaveVoiceChannel(chann).then(dataCallback(callback), errorCallback(callback)); + }; + + // def addFriend + + Client.prototype.addFriend = function addFriend(user) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.addFriend(user).then(dataCallback(callback), errorCallback(callback)); + }; + + // def removeFriend + + Client.prototype.removeFriend = function removeFriend(user) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.internal.removeFriend(user).then(dataCallback(callback), errorCallback(callback)); + }; + + // def awaitResponse + + Client.prototype.awaitResponse = function awaitResponse(msg) { + var toSend = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; + + var _this2 = this; + + var options = arguments.length <= 2 || arguments[2] === undefined ? null : arguments[2]; + var callback = arguments.length <= 3 || arguments[3] === undefined ? function () /*err, newMsg*/{} : arguments[3]; + + var ret; + + if (toSend) { + if (typeof toSend === "function") { + // (msg, callback) + callback = toSend; + toSend = null; + options = null; + } else { + // (msg, toSend, ...) + if (options) { + if (typeof options === "function") { + //(msg, toSend, callback) + callback = options; + options = null; + ret = this.sendMessage(msg, toSend); + } else { + //(msg, toSend, options, callback) + ret = this.sendMessage(msg, toSend, options); + } + } else { + // (msg, toSend) promise + ret = this.sendMessage(msg, toSend); + } + } + } + + if (!ret) { + ret = Promise.resolve(); + } + // (msg) promise + return ret.then(function () { + return _this2.internal.awaitResponse(msg); + }).then(dataCallback(callback), errorCallback(callback)); + }; + + Client.prototype.setStatusIdle = function setStatusIdle() { + var callback = arguments.length <= 0 || arguments[0] === undefined ? function () /*err, {}*/{} : arguments[0]; + + return this.internal.setStatus("idle").then(dataCallback(callback), errorCallback(callback)); + }; + + Client.prototype.setStatusOnline = function setStatusOnline() { + var callback = arguments.length <= 0 || arguments[0] === undefined ? function () /*err, {}*/{} : arguments[0]; + + return this.internal.setStatus("online").then(dataCallback(callback), errorCallback(callback)); + }; + + Client.prototype.setStatusActive = function setStatusActive(callback) { + return this.setStatusOnline(callback); + }; + + Client.prototype.setStatusHere = function setStatusHere(callback) { + return this.setStatusOnline(callback); + }; + + Client.prototype.setStatusAvailable = function setStatusAvailable(callback) { + return this.setStatusOnline(callback); + }; + + Client.prototype.setStatusAway = function setStatusAway(callback) { + return this.setStatusIdle(callback); + }; + + Client.prototype.setPlayingGame = function setPlayingGame(game) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function () /*err, {}*/{} : arguments[1]; + + return this.setStatus(null, game, callback); + }; + + //def forceFetchUsers + + Client.prototype.forceFetchUsers = function forceFetchUsers(callback) { + return this.internal.forceFetchUsers().then(callback); + }; + + _createClass(Client, [{ + key: "users", + get: function get() { + return this.internal.users; + } + + /** + * The server channels the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache} a Cache of the Server Channels + * @readonly + * @example + * // log the names of the channels and the server they belong to + * for(var channel of client.channels){ + * console.log(`${channel.name} is part of ${channel.server.name}`) + * } + */ + }, { + key: "channels", + get: function get() { + return this.internal.channels; + } + + /** + * The servers the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache} a Cache of the Servers + * @readonly + * @example + * // log the names of the servers + * for(var server of client.servers){ + * console.log(server.name) + * } + */ + }, { + key: "servers", + get: function get() { + return this.internal.servers; + } + + /** + * The PM/DM chats the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache} a Cache of the PM/DM Channels. + * @readonly + * @example + * // log the names of the users the client is participating in a PM with + * for(var pm of client.privateChannels){ + * console.log(`Participating in a DM with ${pm.recipient}`) + * } + */ + }, { + key: "privateChannels", + get: function get() { + return this.internal.private_channels; + } + + /** + * The friends that the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache|null} a Cache of friend Users (or null if bot account) + * @readonly + * @example + * // log names of the friends that the client is aware of + * for(var user of client.friends){ + * console.log(user.username); + * } + */ + }, { + key: "friends", + get: function get() { + return this.internal.friends; + } + + /** + * The incoming friend requests that the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache|null} a Cache of incoming friend request Users (or null if bot account) + * @readonly + * @example + * // log names of the incoming friend requests that the client is aware of + * for(var user of client.incomingFriendRequests){ + * console.log(user.username); + * } + */ + }, { + key: "incomingFriendRequests", + get: function get() { + return this.internal.incoming_friend_requests; + } + + /** + * The outgoing friend requests that the Client is aware of. Only available after `ready` event has been emitted. + * @type {Cache} a Cache of outgoing friend request Users + * @readonly + * @example + * // log names of the outgoing friend requests that the client is aware of + * for(var user of client.outgoingFriendRequests){ + * console.log(user.username); + * } + */ + }, { + key: "outgoingFriendRequests", + get: function get() { + return this.internal.outgoing_friend_requests; + } + + /** + * A cache of active voice connection of the Client, or null if not applicable. Only available after `ready` event has been emitted. + * @type {Cache} a Cache of Voice Connections + */ + }, { + key: "voiceConnections", + get: function get() { + return this.internal.voiceConnections; + } + + /** + * The first voice connection the bot has connected to. Available for backwards compatibility. + * @type {VoiceConnection} first voice connection + */ + }, { + key: "voiceConnection", + get: function get() { + return this.internal.voiceConnection; + } + + /** + * Unix timestamp of when the Client first emitted the `ready `event. Only available after `ready` event has been emitted. + * @type {Number} timestamp of ready time + * @example + * // output when the client was ready + * console.log("I was first ready at " + client.readyTime); + */ + }, { + key: "readyTime", + get: function get() { + return this.internal.readyTime; + } + + /** + * How long the client has been ready for in milliseconds. Only available after `ready` event has been emitted. + * @type {Number} number in milliseconds representing uptime of the client + * @example + * // log how long the client has been up for + * console.log("I have been online for " + client.uptime + " milliseconds"); + */ + }, { + key: "uptime", + get: function get() { + return this.internal.uptime; + } + + /** + * A User object that represents the account the client is logged into. Only available after `ready` event has been emitted. + * @type {User} user representing logged in account of client. + * @example + * // log username of logged in account of client + * console.log("Logged in as " + client.user.username); + */ + }, { + key: "user", + get: function get() { + return this.internal.user; + } + + /** + * Object containing user-agent information required for API requests. If not modified, it will use discord.js's defaults. + * @type {UserAgent} + * @example + * // log the stringified user-agent: + * console.log(client.userAgent.full); + */ + }, { + key: "userAgent", + get: function get() { + return this.internal.userAgent; + }, + + /** + * Set the user-agent information provided. Follows the UserAgent typedef format excluding the `full` property. + * @type {UserAgent} + */ + set: function set(userAgent) { + this.internal.userAgent = userAgent; + } + }]); + + return Client; +})(_events2["default"]); + +exports["default"] = Client; +module.exports = exports["default"]; diff --git a/lib/Client/ConnectionState.js b/lib/Client/ConnectionState.js index 6dcfb4ded..b17e17a5e 100644 --- a/lib/Client/ConnectionState.js +++ b/lib/Client/ConnectionState.js @@ -1 +1,11 @@ -"use strict";exports.__esModule = true;exports["default"] = {IDLE:0,LOGGING_IN:1,LOGGED_IN:2,READY:3,DISCONNECTED:4};module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; +exports["default"] = { + IDLE: 0, + LOGGING_IN: 1, + LOGGED_IN: 2, + READY: 3, + DISCONNECTED: 4 +}; +module.exports = exports["default"]; diff --git a/lib/Client/Resolver/Resolver.js b/lib/Client/Resolver/Resolver.js index 0a2ad1009..9e2a45456 100644 --- a/lib/Client/Resolver/Resolver.js +++ b/lib/Client/Resolver/Resolver.js @@ -1,32 +1,333 @@ -"use strict"; /* global Buffer */ /** +"use strict"; +/* global Buffer */ + +/** * Resolves supplied data type to a Channel. If a String, it should be a Channel ID. * @typedef {(Channel|Server|Message|User|String)} ChannelResolvable -*/ /** +*/ +/** * Resolves supplied data type to a TextChannel or PMChannel. If a String, it should be a Channel ID. * @typedef {(TextChannel|PMChannel|Server|Message|User|String)} TextChannelResolvable -*/ /** +*/ +/** * If given an array, turns it into a newline-separated string. * @typedef {(String|Array)} StringResolvable -*/ /** +*/ +/** * Resolves supplied data type to a Message. If a channel, it is the latest message from that channel. * @typedef {(Message|TextChannel|PMChannel)} MessageResolvable -*/ /** +*/ +/** * Resolves supplied data type to a Server. If a String, it should be the server's ID. * @typedef {(Server|ServerChannel|Message|String)} ServerResolvable - */ /** + */ +/** * Resolves supplied data type to something that can be attached to a message. If a String, it can be an URL or a path to a local file. * @typedef {(String|ReadableStream|Buffer)} FileResolvable - */ /** + */ +/** * Resolves supplied data type to an invite ID. If a String, it should be an ID or a direct URL to the invite. * @typedef {(Invite|String)} InviteIDResolvable - */exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _fs=require("fs");var _fs2=_interopRequireDefault(_fs);var _superagent=require("superagent");var _superagent2=_interopRequireDefault(_superagent);var _StructuresUser=require("../../Structures/User");var _StructuresUser2=_interopRequireDefault(_StructuresUser);var _StructuresChannel=require("../../Structures/Channel");var _StructuresChannel2=_interopRequireDefault(_StructuresChannel);var _StructuresTextChannel=require("../../Structures/TextChannel");var _StructuresTextChannel2=_interopRequireDefault(_StructuresTextChannel);var _StructuresVoiceChannel=require("../../Structures/VoiceChannel");var _StructuresVoiceChannel2=_interopRequireDefault(_StructuresVoiceChannel);var _StructuresServerChannel=require("../../Structures/ServerChannel");var _StructuresServerChannel2=_interopRequireDefault(_StructuresServerChannel);var _StructuresPMChannel=require("../../Structures/PMChannel");var _StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel);var _StructuresRole=require("../../Structures/Role");var _StructuresRole2=_interopRequireDefault(_StructuresRole);var _StructuresServer=require("../../Structures/Server");var _StructuresServer2=_interopRequireDefault(_StructuresServer);var _StructuresMessage=require("../../Structures/Message");var _StructuresMessage2=_interopRequireDefault(_StructuresMessage);var _StructuresInvite=require("../../Structures/Invite");var _StructuresInvite2=_interopRequireDefault(_StructuresInvite);var _VoiceVoiceConnection=require("../../Voice/VoiceConnection");var _VoiceVoiceConnection2=_interopRequireDefault(_VoiceVoiceConnection);var Resolver=(function(){function Resolver(internal){_classCallCheck(this,Resolver);this.internal = internal;}Resolver.prototype.resolveToBase64 = function resolveToBase64(resource){if(resource instanceof Buffer){resource = resource.toString("base64");resource = "data:image/jpg;base64," + resource;}return resource;};Resolver.prototype.resolveInviteID = function resolveInviteID(resource){if(resource instanceof _StructuresInvite2["default"]){return resource.id;}if(typeof resource === "string" || resource instanceof String){if(resource.indexOf("http") === 0){var split=resource.split("/");return split.pop();}return resource;}return null;};Resolver.prototype.resolveServer = function resolveServer(resource){if(resource instanceof _StructuresServer2["default"]){return resource;}if(resource instanceof _StructuresServerChannel2["default"]){return resource.server;}if(resource instanceof String || typeof resource === "string"){return this.internal.servers.get("id",resource);}if(resource instanceof _StructuresMessage2["default"]){if(resource.channel instanceof _StructuresTextChannel2["default"]){return resource.channel.server;}}return null;};Resolver.prototype.resolveRole = function resolveRole(resource){if(resource instanceof _StructuresRole2["default"]){return resource;}if(resource instanceof String || typeof resource === "string"){var role=null;for(var _iterator=this.internal.servers,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var server=_ref;if(role = server.roles.get("id",resource)){return role;}}}return null;};Resolver.prototype.resolveFile = function resolveFile(resource){if(typeof resource === "string" || resource instanceof String){if(/^https?:\/\//.test(resource)){return new Promise(function(resolve,reject){_superagent2["default"].get(resource).buffer().parse(function(res,cb){res.setEncoding("binary");res.data = "";res.on("data",function(chunk){res.data += chunk;});res.on("end",function(){cb(null,new Buffer(res.data,"binary"));});}).end(function(err,res){if(err){return reject(err);}return resolve(res.body);});});}else {return Promise.resolve(resource);}}return Promise.resolve(resource);};Resolver.prototype.resolveMentions = function resolveMentions(resource){ // resource is a string -var _mentions=[];var changed=resource;for(var _iterator2=resource.match(/<@[0-9]+>/g) || [],_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var mention=_ref2;var userID=mention.substring(2,mention.length - 1);var user=this.internal.client.users.get("id",userID);if(user){_mentions.push(user);changed = changed.replace(new RegExp(mention,"g"),"@" + user.username);}}return [_mentions,changed];};Resolver.prototype.resolveString = function resolveString(resource){ // accepts Array, Channel, Server, User, Message, String and anything -// toString()-able -if(resource instanceof Array){resource = resource.join("\n");}return resource.toString();};Resolver.prototype.resolveUser = function resolveUser(resource){ /* - accepts a Message, Channel, Server, String ID, User, PMChannel - */if(resource instanceof _StructuresUser2["default"]){return resource;}if(resource instanceof _StructuresMessage2["default"]){return resource.author;}if(resource instanceof _StructuresTextChannel2["default"]){var lmsg=resource.lastMessage;if(lmsg){return lmsg.author;}}if(resource instanceof _StructuresServer2["default"]){return resource.owner;}if(resource instanceof _StructuresPMChannel2["default"]){return resource.recipient;}if(resource instanceof String || typeof resource === "string"){return this.internal.users.get("id",resource);}return null;};Resolver.prototype.resolveMessage = function resolveMessage(resource){ // accepts a Message, PMChannel & TextChannel -if(resource instanceof _StructuresTextChannel2["default"] || resource instanceof _StructuresPMChannel2["default"]){return resource.lastMessage;}if(resource instanceof _StructuresMessage2["default"]){return resource;}return null;};Resolver.prototype.resolveChannel = function resolveChannel(resource){ /* - accepts a Message, Channel, VoiceConnection, Server, String ID, User - */if(resource instanceof _StructuresMessage2["default"]){return Promise.resolve(resource.channel);}if(resource instanceof _StructuresChannel2["default"]){return Promise.resolve(resource);}if(resource instanceof _VoiceVoiceConnection2["default"]){return Promise.resolve(resource.voiceChannel);}if(resource instanceof _StructuresServer2["default"]){return Promise.resolve(resource.defaultChannel);}if(resource instanceof String || typeof resource === "string"){var user=this.internal.users.get("id",resource);if(user){resource = user;}else {return Promise.resolve(this.internal.channels.get("id",resource) || this.internal.private_channels.get("id",resource));}}if(resource instanceof _StructuresUser2["default"]){ // see if a PM exists -for(var _iterator3=this.internal.private_channels,_isArray3=Array.isArray(_iterator3),_i3=0,_iterator3=_isArray3?_iterator3:_iterator3[Symbol.iterator]();;) {var _ref3;if(_isArray3){if(_i3 >= _iterator3.length)break;_ref3 = _iterator3[_i3++];}else {_i3 = _iterator3.next();if(_i3.done)break;_ref3 = _i3.value;}var pmchat=_ref3;if(pmchat.recipient.equals(resource)){return Promise.resolve(pmchat);}} // PM does not exist :\ -return this.internal.startPM(resource);}var error=new Error("Could not resolve channel");error.resource = resource;return Promise.reject(error);};return Resolver;})();exports["default"] = Resolver;module.exports = exports["default"]; + */ + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var _fs = require("fs"); + +var _fs2 = _interopRequireDefault(_fs); + +var _superagent = require("superagent"); + +var _superagent2 = _interopRequireDefault(_superagent); + +var _StructuresUser = require("../../Structures/User"); + +var _StructuresUser2 = _interopRequireDefault(_StructuresUser); + +var _StructuresChannel = require("../../Structures/Channel"); + +var _StructuresChannel2 = _interopRequireDefault(_StructuresChannel); + +var _StructuresTextChannel = require("../../Structures/TextChannel"); + +var _StructuresTextChannel2 = _interopRequireDefault(_StructuresTextChannel); + +var _StructuresVoiceChannel = require("../../Structures/VoiceChannel"); + +var _StructuresVoiceChannel2 = _interopRequireDefault(_StructuresVoiceChannel); + +var _StructuresServerChannel = require("../../Structures/ServerChannel"); + +var _StructuresServerChannel2 = _interopRequireDefault(_StructuresServerChannel); + +var _StructuresPMChannel = require("../../Structures/PMChannel"); + +var _StructuresPMChannel2 = _interopRequireDefault(_StructuresPMChannel); + +var _StructuresRole = require("../../Structures/Role"); + +var _StructuresRole2 = _interopRequireDefault(_StructuresRole); + +var _StructuresServer = require("../../Structures/Server"); + +var _StructuresServer2 = _interopRequireDefault(_StructuresServer); + +var _StructuresMessage = require("../../Structures/Message"); + +var _StructuresMessage2 = _interopRequireDefault(_StructuresMessage); + +var _StructuresInvite = require("../../Structures/Invite"); + +var _StructuresInvite2 = _interopRequireDefault(_StructuresInvite); + +var _VoiceVoiceConnection = require("../../Voice/VoiceConnection"); + +var _VoiceVoiceConnection2 = _interopRequireDefault(_VoiceVoiceConnection); + +var Resolver = (function () { + function Resolver(internal) { + _classCallCheck(this, Resolver); + + this.internal = internal; + } + + Resolver.prototype.resolveToBase64 = function resolveToBase64(resource) { + if (resource instanceof Buffer) { + resource = resource.toString("base64"); + resource = "data:image/jpg;base64," + resource; + } + return resource; + }; + + Resolver.prototype.resolveInviteID = function resolveInviteID(resource) { + if (resource instanceof _StructuresInvite2["default"]) { + return resource.id; + } + if (typeof resource === "string" || resource instanceof String) { + if (resource.indexOf("http") === 0) { + var split = resource.split("/"); + return split.pop(); + } + return resource; + } + return null; + }; + + Resolver.prototype.resolveServer = function resolveServer(resource) { + if (resource instanceof _StructuresServer2["default"]) { + return resource; + } + if (resource instanceof _StructuresServerChannel2["default"]) { + return resource.server; + } + if (resource instanceof String || typeof resource === "string") { + return this.internal.servers.get("id", resource); + } + if (resource instanceof _StructuresMessage2["default"]) { + if (resource.channel instanceof _StructuresTextChannel2["default"]) { + return resource.channel.server; + } + } + return null; + }; + + Resolver.prototype.resolveRole = function resolveRole(resource) { + if (resource instanceof _StructuresRole2["default"]) { + return resource; + } + if (resource instanceof String || typeof resource === "string") { + var role = null; + for (var _iterator = this.internal.servers, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var server = _ref; + + if (role = server.roles.get("id", resource)) { + return role; + } + } + } + return null; + }; + + Resolver.prototype.resolveFile = function resolveFile(resource) { + if (typeof resource === "string" || resource instanceof String) { + if (/^https?:\/\//.test(resource)) { + return new Promise(function (resolve, reject) { + _superagent2["default"].get(resource).buffer().parse(function (res, cb) { + res.setEncoding("binary"); + res.data = ""; + res.on("data", function (chunk) { + res.data += chunk; + }); + res.on("end", function () { + cb(null, new Buffer(res.data, "binary")); + }); + }).end(function (err, res) { + if (err) { + return reject(err); + } + return resolve(res.body); + }); + }); + } else { + return Promise.resolve(resource); + } + } + return Promise.resolve(resource); + }; + + Resolver.prototype.resolveMentions = function resolveMentions(resource) { + // resource is a string + var _mentions = []; + var changed = resource; + for (var _iterator2 = resource.match(/<@[0-9]+>/g) || [], _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var mention = _ref2; + + var userID = mention.substring(2, mention.length - 1); + var user = this.internal.client.users.get("id", userID); + if (user) { + _mentions.push(user); + changed = changed.replace(new RegExp(mention, "g"), "@" + user.username); + } + } + return [_mentions, changed]; + }; + + Resolver.prototype.resolveString = function resolveString(resource) { + + // accepts Array, Channel, Server, User, Message, String and anything + // toString()-able + + if (resource instanceof Array) { + resource = resource.join("\n"); + } + + return resource.toString(); + }; + + Resolver.prototype.resolveUser = function resolveUser(resource) { + /* + accepts a Message, Channel, Server, String ID, User, PMChannel + */ + if (resource instanceof _StructuresUser2["default"]) { + return resource; + } + if (resource instanceof _StructuresMessage2["default"]) { + return resource.author; + } + if (resource instanceof _StructuresTextChannel2["default"]) { + var lmsg = resource.lastMessage; + if (lmsg) { + return lmsg.author; + } + } + if (resource instanceof _StructuresServer2["default"]) { + return resource.owner; + } + if (resource instanceof _StructuresPMChannel2["default"]) { + return resource.recipient; + } + if (resource instanceof String || typeof resource === "string") { + return this.internal.users.get("id", resource); + } + + return null; + }; + + Resolver.prototype.resolveMessage = function resolveMessage(resource) { + // accepts a Message, PMChannel & TextChannel + + if (resource instanceof _StructuresTextChannel2["default"] || resource instanceof _StructuresPMChannel2["default"]) { + return resource.lastMessage; + } + if (resource instanceof _StructuresMessage2["default"]) { + return resource; + } + + return null; + }; + + Resolver.prototype.resolveChannel = function resolveChannel(resource) { + /* + accepts a Message, Channel, VoiceConnection, Server, String ID, User + */ + + if (resource instanceof _StructuresMessage2["default"]) { + return Promise.resolve(resource.channel); + } + if (resource instanceof _StructuresChannel2["default"]) { + return Promise.resolve(resource); + } + if (resource instanceof _VoiceVoiceConnection2["default"]) { + return Promise.resolve(resource.voiceChannel); + } + if (resource instanceof _StructuresServer2["default"]) { + return Promise.resolve(resource.defaultChannel); + } + if (resource instanceof String || typeof resource === "string") { + var user = this.internal.users.get("id", resource); + if (user) { + resource = user; + } else { + return Promise.resolve(this.internal.channels.get("id", resource) || this.internal.private_channels.get("id", resource)); + } + } + if (resource instanceof _StructuresUser2["default"]) { + // see if a PM exists + for (var _iterator3 = this.internal.private_channels, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var pmchat = _ref3; + + if (pmchat.recipient.equals(resource)) { + return Promise.resolve(pmchat); + } + } + + // PM does not exist :\ + return this.internal.startPM(resource); + } + var error = new Error("Could not resolve channel"); + error.resource = resource; + return Promise.reject(error); + }; + + return Resolver; +})(); + +exports["default"] = Resolver; +module.exports = exports["default"]; diff --git a/lib/Constants.js b/lib/Constants.js index 76ee073fa..a4d8caa8a 100644 --- a/lib/Constants.js +++ b/lib/Constants.js @@ -1,8 +1,141 @@ -"use strict";exports.__esModule = true;var API="https://discordapp.com/api";exports.API = API;var Endpoints={ // general endpoints -LOGIN:API + "/auth/login",LOGOUT:API + "/auth/logout",ME:API + "/users/@me",ME_SERVER:function ME_SERVER(serverID){return Endpoints.ME + "/guilds/" + serverID;},GATEWAY:API + "/gateway",USER_CHANNELS:function USER_CHANNELS(userID){return API + "/users/" + userID + "/channels";},AVATAR:function AVATAR(userID,avatar){return API + "/users/" + userID + "/avatars/" + avatar + ".jpg";},INVITE:function INVITE(id){return API + "/invite/" + id;}, // servers -SERVERS:API + "/guilds",SERVER:function SERVER(serverID){return Endpoints.SERVERS + "/" + serverID;},SERVER_ICON:function SERVER_ICON(serverID,hash){return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg";},SERVER_PRUNE:function SERVER_PRUNE(serverID){return Endpoints.SERVER(serverID) + "/prune";},SERVER_EMBED:function SERVER_EMBED(serverID){return Endpoints.SERVER(serverID) + "/embed";},SERVER_INVITES:function SERVER_INVITES(serverID){return Endpoints.SERVER(serverID) + "/invites";},SERVER_ROLES:function SERVER_ROLES(serverID){return Endpoints.SERVER(serverID) + "/roles";},SERVER_BANS:function SERVER_BANS(serverID){return Endpoints.SERVER(serverID) + "/bans";},SERVER_INTEGRATIONS:function SERVER_INTEGRATIONS(serverID){return Endpoints.SERVER(serverID) + "/integrations";},SERVER_MEMBERS:function SERVER_MEMBERS(serverID){return Endpoints.SERVER(serverID) + "/members";},SERVER_CHANNELS:function SERVER_CHANNELS(serverID){return Endpoints.SERVER(serverID) + "/channels";}, // channels -CHANNELS:API + "/channels",CHANNEL:function CHANNEL(channelID){return Endpoints.CHANNELS + "/" + channelID;},CHANNEL_MESSAGES:function CHANNEL_MESSAGES(channelID){return Endpoints.CHANNEL(channelID) + "/messages";},CHANNEL_INVITES:function CHANNEL_INVITES(channelID){return Endpoints.CHANNEL(channelID) + "/invites";},CHANNEL_TYPING:function CHANNEL_TYPING(channelID){return Endpoints.CHANNEL(channelID) + "/typing";},CHANNEL_PERMISSIONS:function CHANNEL_PERMISSIONS(channelID){return Endpoints.CHANNEL(channelID) + "/permissions";},CHANNEL_MESSAGE:function CHANNEL_MESSAGE(channelID,messageID){return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID;}, // friends -FRIENDS:API + "/users/@me/relationships"};exports.Endpoints = Endpoints;var Permissions={ // general -createInstantInvite:1 << 0,kickMembers:1 << 1,banMembers:1 << 2,manageRoles:1 << 3,managePermissions:1 << 3,manageChannels:1 << 4,manageChannel:1 << 4,manageServer:1 << 5, // text -readMessages:1 << 10,sendMessages:1 << 11,sendTTSMessages:1 << 12,manageMessages:1 << 13,embedLinks:1 << 14,attachFiles:1 << 15,readMessageHistory:1 << 16,mentionEveryone:1 << 17, // voice -voiceConnect:1 << 20,voiceSpeak:1 << 21,voiceMuteMembers:1 << 22,voiceDeafenMembers:1 << 23,voiceMoveMembers:1 << 24,voiceUseVAD:1 << 25};exports.Permissions = Permissions;var PacketType={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",SERVER_BAN_ADD:"GUILD_BAN_ADD",SERVER_BAN_REMOVE:"GUILD_BAN_REMOVE",SERVER_CREATE:"GUILD_CREATE",SERVER_DELETE:"GUILD_DELETE",SERVER_MEMBER_ADD:"GUILD_MEMBER_ADD",SERVER_MEMBER_REMOVE:"GUILD_MEMBER_REMOVE",SERVER_MEMBER_UPDATE:"GUILD_MEMBER_UPDATE",SERVER_MEMBERS_CHUNK:"GUILD_MEMBERS_CHUNK",SERVER_ROLE_CREATE:"GUILD_ROLE_CREATE",SERVER_ROLE_DELETE:"GUILD_ROLE_DELETE",SERVER_ROLE_UPDATE:"GUILD_ROLE_UPDATE",SERVER_UPDATE:"GUILD_UPDATE",TYPING:"TYPING_START",USER_UPDATE:"USER_UPDATE",VOICE_STATE_UPDATE:"VOICE_STATE_UPDATE",FRIEND_ADD:"RELATIONSHIP_ADD",FRIEND_REMOVE:"RELATIONSHIP_REMOVE"};exports.PacketType = PacketType; +"use strict"; + +exports.__esModule = true; +var API = "https://discordapp.com/api"; +exports.API = API; +var Endpoints = { + // general endpoints + LOGIN: API + "/auth/login", + LOGOUT: API + "/auth/logout", + ME: API + "/users/@me", + ME_SERVER: function ME_SERVER(serverID) { + return Endpoints.ME + "/guilds/" + serverID; + }, + GATEWAY: API + "/gateway", + USER_CHANNELS: function USER_CHANNELS(userID) { + return API + "/users/" + userID + "/channels"; + }, + AVATAR: function AVATAR(userID, avatar) { + return API + "/users/" + userID + "/avatars/" + avatar + ".jpg"; + }, + INVITE: function INVITE(id) { + return API + "/invite/" + id; + }, + + // servers + SERVERS: API + "/guilds", + SERVER: function SERVER(serverID) { + return Endpoints.SERVERS + "/" + serverID; + }, + SERVER_ICON: function SERVER_ICON(serverID, hash) { + return Endpoints.SERVER(serverID) + "/icons/" + hash + ".jpg"; + }, + SERVER_PRUNE: function SERVER_PRUNE(serverID) { + return Endpoints.SERVER(serverID) + "/prune"; + }, + SERVER_EMBED: function SERVER_EMBED(serverID) { + return Endpoints.SERVER(serverID) + "/embed"; + }, + SERVER_INVITES: function SERVER_INVITES(serverID) { + return Endpoints.SERVER(serverID) + "/invites"; + }, + SERVER_ROLES: function SERVER_ROLES(serverID) { + return Endpoints.SERVER(serverID) + "/roles"; + }, + SERVER_BANS: function SERVER_BANS(serverID) { + return Endpoints.SERVER(serverID) + "/bans"; + }, + SERVER_INTEGRATIONS: function SERVER_INTEGRATIONS(serverID) { + return Endpoints.SERVER(serverID) + "/integrations"; + }, + SERVER_MEMBERS: function SERVER_MEMBERS(serverID) { + return Endpoints.SERVER(serverID) + "/members"; + }, + SERVER_CHANNELS: function SERVER_CHANNELS(serverID) { + return Endpoints.SERVER(serverID) + "/channels"; + }, + + // channels + CHANNELS: API + "/channels", + CHANNEL: function CHANNEL(channelID) { + return Endpoints.CHANNELS + "/" + channelID; + }, + CHANNEL_MESSAGES: function CHANNEL_MESSAGES(channelID) { + return Endpoints.CHANNEL(channelID) + "/messages"; + }, + CHANNEL_INVITES: function CHANNEL_INVITES(channelID) { + return Endpoints.CHANNEL(channelID) + "/invites"; + }, + CHANNEL_TYPING: function CHANNEL_TYPING(channelID) { + return Endpoints.CHANNEL(channelID) + "/typing"; + }, + CHANNEL_PERMISSIONS: function CHANNEL_PERMISSIONS(channelID) { + return Endpoints.CHANNEL(channelID) + "/permissions"; + }, + CHANNEL_MESSAGE: function CHANNEL_MESSAGE(channelID, messageID) { + return Endpoints.CHANNEL_MESSAGES(channelID) + "/" + messageID; + }, + + // friends + FRIENDS: API + "/users/@me/relationships" +}; + +exports.Endpoints = Endpoints; +var Permissions = { + // general + createInstantInvite: 1 << 0, + kickMembers: 1 << 1, + banMembers: 1 << 2, + manageRoles: 1 << 3, + managePermissions: 1 << 3, + manageChannels: 1 << 4, + manageChannel: 1 << 4, + manageServer: 1 << 5, + // text + readMessages: 1 << 10, + sendMessages: 1 << 11, + sendTTSMessages: 1 << 12, + manageMessages: 1 << 13, + embedLinks: 1 << 14, + attachFiles: 1 << 15, + readMessageHistory: 1 << 16, + mentionEveryone: 1 << 17, + // voice + voiceConnect: 1 << 20, + voiceSpeak: 1 << 21, + voiceMuteMembers: 1 << 22, + voiceDeafenMembers: 1 << 23, + voiceMoveMembers: 1 << 24, + voiceUseVAD: 1 << 25 + +}; + +exports.Permissions = Permissions; +var PacketType = { + 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", + SERVER_BAN_ADD: "GUILD_BAN_ADD", + SERVER_BAN_REMOVE: "GUILD_BAN_REMOVE", + SERVER_CREATE: "GUILD_CREATE", + SERVER_DELETE: "GUILD_DELETE", + SERVER_MEMBER_ADD: "GUILD_MEMBER_ADD", + SERVER_MEMBER_REMOVE: "GUILD_MEMBER_REMOVE", + SERVER_MEMBER_UPDATE: "GUILD_MEMBER_UPDATE", + SERVER_MEMBERS_CHUNK: "GUILD_MEMBERS_CHUNK", + SERVER_ROLE_CREATE: "GUILD_ROLE_CREATE", + SERVER_ROLE_DELETE: "GUILD_ROLE_DELETE", + SERVER_ROLE_UPDATE: "GUILD_ROLE_UPDATE", + SERVER_UPDATE: "GUILD_UPDATE", + TYPING: "TYPING_START", + USER_UPDATE: "USER_UPDATE", + VOICE_STATE_UPDATE: "VOICE_STATE_UPDATE", + FRIEND_ADD: "RELATIONSHIP_ADD", + FRIEND_REMOVE: "RELATIONSHIP_REMOVE" +}; +exports.PacketType = PacketType; diff --git a/lib/Structures/Channel.js b/lib/Structures/Channel.js index df9292ac9..627e4095b 100644 --- a/lib/Structures/Channel.js +++ b/lib/Structures/Channel.js @@ -1 +1,45 @@ -"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _UtilEquality=require("../Util/Equality");var _UtilEquality2=_interopRequireDefault(_UtilEquality);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var Channel=(function(_Equality){_inherits(Channel,_Equality);function Channel(data,client){_classCallCheck(this,Channel);_Equality.call(this);this.id = data.id;this.client = client;}Channel.prototype["delete"] = function _delete(){return this.client.deleteChannel.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(Channel,[{key:"isPrivate",get:function get(){return !this.server;}}]);return Channel;})(_UtilEquality2["default"]);exports["default"] = Channel;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _UtilEquality = require("../Util/Equality"); + +var _UtilEquality2 = _interopRequireDefault(_UtilEquality); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var Channel = (function (_Equality) { + _inherits(Channel, _Equality); + + function Channel(data, client) { + _classCallCheck(this, Channel); + + _Equality.call(this); + this.id = data.id; + this.client = client; + } + + Channel.prototype["delete"] = function _delete() { + return this.client.deleteChannel.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + _createClass(Channel, [{ + key: "isPrivate", + get: function get() { + return !this.server; + } + }]); + + return Channel; +})(_UtilEquality2["default"]); + +exports["default"] = Channel; +module.exports = exports["default"]; diff --git a/lib/Structures/ChannelPermissions.js b/lib/Structures/ChannelPermissions.js index b8ba80312..81773a75e 100644 --- a/lib/Structures/ChannelPermissions.js +++ b/lib/Structures/ChannelPermissions.js @@ -1,7 +1,78 @@ -"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _Constants=require("../Constants");var ChannelPermissions=(function(){function ChannelPermissions(permissions){_classCallCheck(this,ChannelPermissions);this.permissions = permissions;}ChannelPermissions.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general -createInstantInvite:hp(_Constants.Permissions.createInstantInvite),kickMembers:hp(_Constants.Permissions.kickMembers),banMembers:hp(_Constants.Permissions.banMembers),managePermissions:hp(_Constants.Permissions.managePermissions),manageChannel:hp(_Constants.Permissions.manageChannel),manageServer:hp(_Constants.Permissions.manageServer), // text -readMessages:hp(_Constants.Permissions.readMessages),sendMessages:hp(_Constants.Permissions.sendMessages),sendTTSMessages:hp(_Constants.Permissions.sendTTSMessages),manageMessages:hp(_Constants.Permissions.manageMessages),embedLinks:hp(_Constants.Permissions.embedLinks),attachFiles:hp(_Constants.Permissions.attachFiles),readMessageHistory:hp(_Constants.Permissions.readMessageHistory),mentionEveryone:hp(_Constants.Permissions.mentionEveryone), // voice -voiceConnect:hp(_Constants.Permissions.voiceConnect),voiceSpeak:hp(_Constants.Permissions.voiceSpeak),voiceMuteMembers:hp(_Constants.Permissions.voiceMuteMembers),voiceDeafenMembers:hp(_Constants.Permissions.voiceDeafenMembers),voiceMoveMembers:hp(_Constants.Permissions.voiceMoveMembers),voiceUseVAD:hp(_Constants.Permissions.voiceUseVAD)};};ChannelPermissions.prototype.serialize = function serialize(){ // ;n; -return this.serialise();};ChannelPermissions.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = _Constants.Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed -if(!!(this.permissions & _Constants.Permissions.manageRoles)){ // manageRoles allowed, they have all permissions -return true;}}return !!(this.permissions & perm);};return ChannelPermissions;})();exports["default"] = ChannelPermissions;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var _Constants = require("../Constants"); + +var ChannelPermissions = (function () { + function ChannelPermissions(permissions) { + _classCallCheck(this, ChannelPermissions); + + this.permissions = permissions; + } + + ChannelPermissions.prototype.serialise = function serialise(explicit) { + var _this = this; + + var hp = function hp(perm) { + return _this.hasPermission(perm, explicit); + }; + + return { + // general + createInstantInvite: hp(_Constants.Permissions.createInstantInvite), + kickMembers: hp(_Constants.Permissions.kickMembers), + banMembers: hp(_Constants.Permissions.banMembers), + managePermissions: hp(_Constants.Permissions.managePermissions), + manageChannel: hp(_Constants.Permissions.manageChannel), + manageServer: hp(_Constants.Permissions.manageServer), + // text + readMessages: hp(_Constants.Permissions.readMessages), + sendMessages: hp(_Constants.Permissions.sendMessages), + sendTTSMessages: hp(_Constants.Permissions.sendTTSMessages), + manageMessages: hp(_Constants.Permissions.manageMessages), + embedLinks: hp(_Constants.Permissions.embedLinks), + attachFiles: hp(_Constants.Permissions.attachFiles), + readMessageHistory: hp(_Constants.Permissions.readMessageHistory), + mentionEveryone: hp(_Constants.Permissions.mentionEveryone), + // voice + voiceConnect: hp(_Constants.Permissions.voiceConnect), + voiceSpeak: hp(_Constants.Permissions.voiceSpeak), + voiceMuteMembers: hp(_Constants.Permissions.voiceMuteMembers), + voiceDeafenMembers: hp(_Constants.Permissions.voiceDeafenMembers), + voiceMoveMembers: hp(_Constants.Permissions.voiceMoveMembers), + voiceUseVAD: hp(_Constants.Permissions.voiceUseVAD) + }; + }; + + ChannelPermissions.prototype.serialize = function serialize() { + // ;n; + return this.serialise(); + }; + + ChannelPermissions.prototype.hasPermission = function hasPermission(perm) { + var explicit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + if (perm instanceof String || typeof perm === "string") { + perm = _Constants.Permissions[perm]; + } + if (!perm) { + return false; + } + if (!explicit) { + // implicit permissions allowed + if (!!(this.permissions & _Constants.Permissions.manageRoles)) { + // manageRoles allowed, they have all permissions + return true; + } + } + return !!(this.permissions & perm); + }; + + return ChannelPermissions; +})(); + +exports["default"] = ChannelPermissions; +module.exports = exports["default"]; diff --git a/lib/Structures/Invite.js b/lib/Structures/Invite.js index 8d39a8e8f..77b4be4db 100644 --- a/lib/Structures/Invite.js +++ b/lib/Structures/Invite.js @@ -1 +1,47 @@ -"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Invite=(function(){function Invite(data,chan,client){_classCallCheck(this,Invite);this.maxAge = data.max_age;this.code = data.code;if(chan){this.channel = chan;this.server = chan.server;}else {this.channel = data.channel;this.server = data.guild;}this.revoked = data.revoked;this.createdAt = Date.parse(data.created_at);this.temporary = data.temporary;this.uses = data.uses;this.maxUses = data.max_uses;if(data.inviter){this.inviter = client.internal.users.get("id",data.inviter.id);}this.xkcd = data.xkcdpass;}Invite.prototype.toString = function toString(){return "https://discord.gg/" + this.code;};Invite.prototype["delete"] = function _delete(){return this.client.deleteInvite.apply(this.client,reg(this,arguments));};Invite.prototype.join = function join(){return this.client.joinServer.apply(this.client,reg(this,arguments));};return Invite;})();exports["default"] = Invite;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Invite = (function () { + function Invite(data, chan, client) { + _classCallCheck(this, Invite); + + this.maxAge = data.max_age; + this.code = data.code; + if (chan) { + this.channel = chan; + this.server = chan.server; + } else { + this.channel = data.channel; + this.server = data.guild; + } + this.revoked = data.revoked; + this.createdAt = Date.parse(data.created_at); + this.temporary = data.temporary; + this.uses = data.uses; + this.maxUses = data.max_uses; + if (data.inviter) { + this.inviter = client.internal.users.get("id", data.inviter.id); + } + this.xkcd = data.xkcdpass; + } + + Invite.prototype.toString = function toString() { + return "https://discord.gg/" + this.code; + }; + + Invite.prototype["delete"] = function _delete() { + return this.client.deleteInvite.apply(this.client, reg(this, arguments)); + }; + + Invite.prototype.join = function join() { + return this.client.joinServer.apply(this.client, reg(this, arguments)); + }; + + return Invite; +})(); + +exports["default"] = Invite; +module.exports = exports["default"]; diff --git a/lib/Structures/Message.js b/lib/Structures/Message.js index c9eb759c5..c706badf9 100644 --- a/lib/Structures/Message.js +++ b/lib/Structures/Message.js @@ -1,8 +1,141 @@ -"use strict"; /** +"use strict"; + +/** * Options that can be applied to a message before sending it. * @typedef {(object)} MessageOptions * @property {boolean} [tts=false] Whether or not the message should be sent as text-to-speech. -*/exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _User=require("./User");var _User2=_interopRequireDefault(_User);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var _UtilEquality=require("../Util/Equality");var _UtilEquality2=_interopRequireDefault(_UtilEquality);var Message=(function(_Equality){_inherits(Message,_Equality);function Message(data,channel,client){var _this=this;_classCallCheck(this,Message);_Equality.call(this);this.channel = channel;this.client = client;this.nonce = data.nonce;this.attachments = data.attachments;this.tts = data.tts;this.embeds = data.embeds;this.timestamp = Date.parse(data.timestamp);this.everyoneMentioned = data.mention_everyone || data.everyoneMentioned;this.id = data.id;if(data.edited_timestamp){this.editedTimestamp = Date.parse(data.edited_timestamp);}if(data.author instanceof _User2["default"]){this.author = data.author;}else {this.author = client.internal.users.add(new _User2["default"](data.author,client));}this.content = data.content;var mentionData=client.internal.resolver.resolveMentions(data.content);this.cleanContent = mentionData[1];this.mentions = [];mentionData[0].forEach(function(mention){ // this is .add and not .get because it allows the bot to cache -// users from messages from logs who may have left the server and were -// not previously cached. -if(mention instanceof _User2["default"]){_this.mentions.push(mention);}else {_this.mentions.push(client.internal.users.add(new _User2["default"](mention,client)));}});}Message.prototype.isMentioned = function isMentioned(user){user = this.client.internal.resolver.resolveUser(user);if(!user){return false;}for(var _iterator=this.mentions,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var mention=_ref;if(mention.id == user.id){return true;}}return false;};Message.prototype.toString = function toString(){return this.content;};Message.prototype["delete"] = function _delete(){return this.client.deleteMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.update = function update(){return this.client.updateMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.edit = function edit(){return this.client.updateMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.reply = function reply(){return this.client.reply.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Message.prototype.replyTTS = function replyTTS(){return this.client.replyTTS.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(Message,[{key:"sender",get:function get(){return this.author;}}]);return Message;})(_UtilEquality2["default"]);exports["default"] = Message;module.exports = exports["default"]; +*/ + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _UtilCache = require("../Util/Cache"); + +var _UtilCache2 = _interopRequireDefault(_UtilCache); + +var _User = require("./User"); + +var _User2 = _interopRequireDefault(_User); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var _UtilEquality = require("../Util/Equality"); + +var _UtilEquality2 = _interopRequireDefault(_UtilEquality); + +var Message = (function (_Equality) { + _inherits(Message, _Equality); + + function Message(data, channel, client) { + var _this = this; + + _classCallCheck(this, Message); + + _Equality.call(this); + this.channel = channel; + this.client = client; + this.nonce = data.nonce; + this.attachments = data.attachments; + this.tts = data.tts; + this.embeds = data.embeds; + this.timestamp = Date.parse(data.timestamp); + this.everyoneMentioned = data.mention_everyone || data.everyoneMentioned; + this.id = data.id; + + if (data.edited_timestamp) { + this.editedTimestamp = Date.parse(data.edited_timestamp); + } + + if (data.author instanceof _User2["default"]) { + this.author = data.author; + } else { + this.author = client.internal.users.add(new _User2["default"](data.author, client)); + } + + this.content = data.content; + + var mentionData = client.internal.resolver.resolveMentions(data.content); + this.cleanContent = mentionData[1]; + this.mentions = []; + + mentionData[0].forEach(function (mention) { + // this is .add and not .get because it allows the bot to cache + // users from messages from logs who may have left the server and were + // not previously cached. + if (mention instanceof _User2["default"]) { + _this.mentions.push(mention); + } else { + _this.mentions.push(client.internal.users.add(new _User2["default"](mention, client))); + } + }); + } + + Message.prototype.isMentioned = function isMentioned(user) { + user = this.client.internal.resolver.resolveUser(user); + if (!user) { + return false; + } + for (var _iterator = this.mentions, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var mention = _ref; + + if (mention.id == user.id) { + return true; + } + } + return false; + }; + + Message.prototype.toString = function toString() { + return this.content; + }; + + Message.prototype["delete"] = function _delete() { + return this.client.deleteMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Message.prototype.update = function update() { + return this.client.updateMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Message.prototype.edit = function edit() { + return this.client.updateMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Message.prototype.reply = function reply() { + return this.client.reply.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Message.prototype.replyTTS = function replyTTS() { + return this.client.replyTTS.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + _createClass(Message, [{ + key: "sender", + get: function get() { + return this.author; + } + }]); + + return Message; +})(_UtilEquality2["default"]); + +exports["default"] = Message; +module.exports = exports["default"]; diff --git a/lib/Structures/PMChannel.js b/lib/Structures/PMChannel.js index 9afa32f3e..ecbcb77d0 100644 --- a/lib/Structures/PMChannel.js +++ b/lib/Structures/PMChannel.js @@ -1 +1,90 @@ -"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _Channel2=require("./Channel");var _Channel3=_interopRequireDefault(_Channel2);var _User=require("./User");var _User2=_interopRequireDefault(_User);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var PMChannel=(function(_Channel){_inherits(PMChannel,_Channel);function PMChannel(data,client){_classCallCheck(this,PMChannel);_Channel.call(this,data,client);this.type = data.type || "text";this.lastMessageID = data.last_message_id || data.lastMessageID;this.messages = new _UtilCache2["default"]("id",client.options.maxCachedMessages);this.recipient = this.client.internal.users.add(new _User2["default"](data.recipient,this.client));} /* warning! may return null */PMChannel.prototype.toString = function toString(){return this.recipient.toString();};PMChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.send = function send(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendTTS = function sendTTS(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.sendFile = function sendFile(){return this.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.startTyping = function startTyping(){return this.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.stopTyping = function stopTyping(){return this.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};PMChannel.prototype.getLogs = function getLogs(){return this.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(PMChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return PMChannel;})(_Channel3["default"]);exports["default"] = PMChannel;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _Channel2 = require("./Channel"); + +var _Channel3 = _interopRequireDefault(_Channel2); + +var _User = require("./User"); + +var _User2 = _interopRequireDefault(_User); + +var _UtilCache = require("../Util/Cache"); + +var _UtilCache2 = _interopRequireDefault(_UtilCache); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var PMChannel = (function (_Channel) { + _inherits(PMChannel, _Channel); + + function PMChannel(data, client) { + _classCallCheck(this, PMChannel); + + _Channel.call(this, data, client); + + this.type = data.type || "text"; + this.lastMessageID = data.last_message_id || data.lastMessageID; + this.messages = new _UtilCache2["default"]("id", client.options.maxCachedMessages); + this.recipient = this.client.internal.users.add(new _User2["default"](data.recipient, this.client)); + } + + /* warning! may return null */ + + PMChannel.prototype.toString = function toString() { + return this.recipient.toString(); + }; + + PMChannel.prototype.sendMessage = function sendMessage() { + return this.client.sendMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.send = function send() { + return this.client.sendMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.sendTTSMessage = function sendTTSMessage() { + return this.client.sendTTSMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.sendTTS = function sendTTS() { + return this.client.sendTTSMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.sendFile = function sendFile() { + return this.client.sendFile.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.startTyping = function startTyping() { + return this.client.startTyping.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.stopTyping = function stopTyping() { + return this.client.stopTyping.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + PMChannel.prototype.getLogs = function getLogs() { + return this.client.getChannelLogs.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + _createClass(PMChannel, [{ + key: "lastMessage", + get: function get() { + return this.messages.get("id", this.lastMessageID); + } + }]); + + return PMChannel; +})(_Channel3["default"]); + +exports["default"] = PMChannel; +module.exports = exports["default"]; diff --git a/lib/Structures/PermissionOverwrite.js b/lib/Structures/PermissionOverwrite.js index 7a6c593b2..6682c168a 100644 --- a/lib/Structures/PermissionOverwrite.js +++ b/lib/Structures/PermissionOverwrite.js @@ -1,6 +1,89 @@ -"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _Constants=require("../Constants");var PermissionOverwrite=(function(){function PermissionOverwrite(data){_classCallCheck(this,PermissionOverwrite);this.id = data.id;this.type = data.type; // member or role -this.deny = data.deny;this.allow = data.allow;} // returns an array of allowed permissions -PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray){var _this=this;allowedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){_this.allow |= 1 << permission;}});};PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray){var _this2=this;deniedArray.forEach(function(permission){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){_this2.deny |= 1 << permission;}});};_createClass(PermissionOverwrite,[{key:"allowed",get:function get(){var allowed=[];for(var permName in _Constants.Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites. -continue;}if(!!(this.allow & _Constants.Permissions[permName])){allowed.push(permName);}}return allowed;} // returns an array of denied permissions -},{key:"denied",get:function get(){var denied=[];for(var permName in _Constants.Permissions) {if(permName === "manageRoles" || permName === "manageChannels"){ // these permissions do not exist in overwrites. -continue;}if(!!(this.deny & _Constants.Permissions[permName])){denied.push(permName);}}return denied;}}]);return PermissionOverwrite;})();exports["default"] = PermissionOverwrite;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var _Constants = require("../Constants"); + +var PermissionOverwrite = (function () { + function PermissionOverwrite(data) { + _classCallCheck(this, PermissionOverwrite); + + this.id = data.id; + this.type = data.type; // member or role + this.deny = data.deny; + this.allow = data.allow; + } + + // returns an array of allowed permissions + + PermissionOverwrite.prototype.setAllowed = function setAllowed(allowedArray) { + var _this = this; + + allowedArray.forEach(function (permission) { + if (permission instanceof String || typeof permission === "string") { + permission = _Constants.Permissions[permission]; + } + if (permission) { + _this.allow |= 1 << permission; + } + }); + }; + + PermissionOverwrite.prototype.setDenied = function setDenied(deniedArray) { + var _this2 = this; + + deniedArray.forEach(function (permission) { + if (permission instanceof String || typeof permission === "string") { + permission = _Constants.Permissions[permission]; + } + if (permission) { + _this2.deny |= 1 << permission; + } + }); + }; + + _createClass(PermissionOverwrite, [{ + key: "allowed", + get: function get() { + var allowed = []; + for (var permName in _Constants.Permissions) { + if (permName === "manageRoles" || permName === "manageChannels") { + // these permissions do not exist in overwrites. + continue; + } + + if (!!(this.allow & _Constants.Permissions[permName])) { + allowed.push(permName); + } + } + return allowed; + } + + // returns an array of denied permissions + }, { + key: "denied", + get: function get() { + var denied = []; + for (var permName in _Constants.Permissions) { + if (permName === "manageRoles" || permName === "manageChannels") { + // these permissions do not exist in overwrites. + continue; + } + + if (!!(this.deny & _Constants.Permissions[permName])) { + denied.push(permName); + } + } + return denied; + } + }]); + + return PermissionOverwrite; +})(); + +exports["default"] = PermissionOverwrite; +module.exports = exports["default"]; diff --git a/lib/Structures/Role.js b/lib/Structures/Role.js index ea5bf2536..79eed38df 100644 --- a/lib/Structures/Role.js +++ b/lib/Structures/Role.js @@ -1,4 +1,13 @@ -"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _Constants=require("../Constants");var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser"); /* +"use strict"; +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var _Constants = require("../Constants"); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +/* example data @@ -9,15 +18,155 @@ example data id: '110007368451915776', hoist: false, color: 0 } -*/var DefaultRole=[_Constants.Permissions.createInstantInvite,_Constants.Permissions.readMessages,_Constants.Permissions.readMessageHistory,_Constants.Permissions.sendMessages,_Constants.Permissions.sendTTSMessages,_Constants.Permissions.embedLinks,_Constants.Permissions.attachFiles,_Constants.Permissions.readMessageHistory,_Constants.Permissions.mentionEveryone,_Constants.Permissions.voiceConnect,_Constants.Permissions.voiceSpeak,_Constants.Permissions.voiceUseVAD].reduce(function(previous,current){return previous | current;},0);var Role=(function(){function Role(data,server,client){_classCallCheck(this,Role);this.position = data.position || -1;this.permissions = data.permissions || (data.name === "@everyone"?DefaultRole:0);this.name = data.name || "@everyone";this.managed = data.managed || false;this.id = data.id;this.hoist = data.hoist || false;this.color = data.color || 0;this.server = server;this.client = client;}Role.prototype.serialise = function serialise(explicit){var _this=this;var hp=function hp(perm){return _this.hasPermission(perm,explicit);};return { // general -createInstantInvite:hp(_Constants.Permissions.createInstantInvite),kickMembers:hp(_Constants.Permissions.kickMembers),banMembers:hp(_Constants.Permissions.banMembers),manageRoles:hp(_Constants.Permissions.manageRoles),manageChannels:hp(_Constants.Permissions.manageChannels),manageServer:hp(_Constants.Permissions.manageServer), // text -readMessages:hp(_Constants.Permissions.readMessages),sendMessages:hp(_Constants.Permissions.sendMessages),sendTTSMessages:hp(_Constants.Permissions.sendTTSMessages),manageMessages:hp(_Constants.Permissions.manageMessages),embedLinks:hp(_Constants.Permissions.embedLinks),attachFiles:hp(_Constants.Permissions.attachFiles),readMessageHistory:hp(_Constants.Permissions.readMessageHistory),mentionEveryone:hp(_Constants.Permissions.mentionEveryone), // voice -voiceConnect:hp(_Constants.Permissions.voiceConnect),voiceSpeak:hp(_Constants.Permissions.voiceSpeak),voiceMuteMembers:hp(_Constants.Permissions.voiceMuteMembers),voiceDeafenMembers:hp(_Constants.Permissions.voiceDeafenMembers),voiceMoveMembers:hp(_Constants.Permissions.voiceMoveMembers),voiceUseVAD:hp(_Constants.Permissions.voiceUseVAD)};};Role.prototype.serialize = function serialize(){ // ;n; -return this.serialise();};Role.prototype.hasPermission = function hasPermission(perm){var explicit=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];if(perm instanceof String || typeof perm === "string"){perm = _Constants.Permissions[perm];}if(!perm){return false;}if(!explicit){ // implicit permissions allowed -if(!!(this.permissions & _Constants.Permissions.manageRoles)){ // manageRoles allowed, they have all permissions -return true;}} // e.g. -// !!(36953089 & Permissions.manageRoles) = not allowed to manage roles -// !!(36953089 & (1 << 21)) = voice speak allowed -return !!(this.permissions & perm);};Role.prototype.setPermission = function setPermission(permission,value){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){ // valid permission -if(value){this.permissions |= permission;}else {this.permissions &= ~permission;}}};Role.prototype.setPermissions = function setPermissions(obj){var _this2=this;obj.forEach(function(value,permission){if(permission instanceof String || typeof permission === "string"){permission = _Constants.Permissions[permission];}if(permission){ // valid permission -_this2.setPermission(permission,value);}});};Role.prototype.colorAsHex = function colorAsHex(){var val=this.color.toString(16);while(val.length < 6) {val = "0" + val;}return "#" + val;};Role.prototype["delete"] = function _delete(){return this.client.deleteRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Role.prototype.edit = function edit(){return this.client.updateRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Role.prototype.update = function update(){return this.client.updateRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Role.prototype.addMember = function addMember(member,callback){return this.client.addMemberToRole.apply(this.client,[member,this,callback]);};Role.prototype.addUser = function addUser(member,callback){return this.client.addUserToRole.apply(this.client,[member,this,callback]);};Role.prototype.removeMember = function removeMember(member,callback){return this.client.removeMemberFromRole.apply(this.client,[member,this,callback]);};Role.prototype.removeUser = function removeUser(member,callback){return this.client.removeUserFromRole.apply(this.client,[member,this,callback]);};return Role;})();exports["default"] = Role;module.exports = exports["default"]; +*/ + +var DefaultRole = [_Constants.Permissions.createInstantInvite, _Constants.Permissions.readMessages, _Constants.Permissions.readMessageHistory, _Constants.Permissions.sendMessages, _Constants.Permissions.sendTTSMessages, _Constants.Permissions.embedLinks, _Constants.Permissions.attachFiles, _Constants.Permissions.readMessageHistory, _Constants.Permissions.mentionEveryone, _Constants.Permissions.voiceConnect, _Constants.Permissions.voiceSpeak, _Constants.Permissions.voiceUseVAD].reduce(function (previous, current) { + return previous | current; +}, 0); + +var Role = (function () { + function Role(data, server, client) { + _classCallCheck(this, Role); + + this.position = data.position || -1; + this.permissions = data.permissions || (data.name === "@everyone" ? DefaultRole : 0); + this.name = data.name || "@everyone"; + this.managed = data.managed || false; + this.id = data.id; + this.hoist = data.hoist || false; + this.color = data.color || 0; + this.server = server; + this.client = client; + } + + Role.prototype.serialise = function serialise(explicit) { + var _this = this; + + var hp = function hp(perm) { + return _this.hasPermission(perm, explicit); + }; + + return { + // general + createInstantInvite: hp(_Constants.Permissions.createInstantInvite), + kickMembers: hp(_Constants.Permissions.kickMembers), + banMembers: hp(_Constants.Permissions.banMembers), + manageRoles: hp(_Constants.Permissions.manageRoles), + manageChannels: hp(_Constants.Permissions.manageChannels), + manageServer: hp(_Constants.Permissions.manageServer), + // text + readMessages: hp(_Constants.Permissions.readMessages), + sendMessages: hp(_Constants.Permissions.sendMessages), + sendTTSMessages: hp(_Constants.Permissions.sendTTSMessages), + manageMessages: hp(_Constants.Permissions.manageMessages), + embedLinks: hp(_Constants.Permissions.embedLinks), + attachFiles: hp(_Constants.Permissions.attachFiles), + readMessageHistory: hp(_Constants.Permissions.readMessageHistory), + mentionEveryone: hp(_Constants.Permissions.mentionEveryone), + // voice + voiceConnect: hp(_Constants.Permissions.voiceConnect), + voiceSpeak: hp(_Constants.Permissions.voiceSpeak), + voiceMuteMembers: hp(_Constants.Permissions.voiceMuteMembers), + voiceDeafenMembers: hp(_Constants.Permissions.voiceDeafenMembers), + voiceMoveMembers: hp(_Constants.Permissions.voiceMoveMembers), + voiceUseVAD: hp(_Constants.Permissions.voiceUseVAD) + }; + }; + + Role.prototype.serialize = function serialize() { + // ;n; + return this.serialise(); + }; + + Role.prototype.hasPermission = function hasPermission(perm) { + var explicit = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + + if (perm instanceof String || typeof perm === "string") { + perm = _Constants.Permissions[perm]; + } + if (!perm) { + return false; + } + if (!explicit) { + // implicit permissions allowed + if (!!(this.permissions & _Constants.Permissions.manageRoles)) { + // manageRoles allowed, they have all permissions + return true; + } + } + // e.g. + // !!(36953089 & Permissions.manageRoles) = not allowed to manage roles + // !!(36953089 & (1 << 21)) = voice speak allowed + + return !!(this.permissions & perm); + }; + + Role.prototype.setPermission = function setPermission(permission, value) { + if (permission instanceof String || typeof permission === "string") { + permission = _Constants.Permissions[permission]; + } + if (permission) { + // valid permission + if (value) { + this.permissions |= permission; + } else { + this.permissions &= ~permission; + } + } + }; + + Role.prototype.setPermissions = function setPermissions(obj) { + var _this2 = this; + + obj.forEach(function (value, permission) { + if (permission instanceof String || typeof permission === "string") { + permission = _Constants.Permissions[permission]; + } + if (permission) { + // valid permission + _this2.setPermission(permission, value); + } + }); + }; + + Role.prototype.colorAsHex = function colorAsHex() { + var val = this.color.toString(16); + while (val.length < 6) { + val = "0" + val; + } + return "#" + val; + }; + + Role.prototype["delete"] = function _delete() { + return this.client.deleteRole.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Role.prototype.edit = function edit() { + return this.client.updateRole.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Role.prototype.update = function update() { + return this.client.updateRole.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Role.prototype.addMember = function addMember(member, callback) { + return this.client.addMemberToRole.apply(this.client, [member, this, callback]); + }; + + Role.prototype.addUser = function addUser(member, callback) { + return this.client.addUserToRole.apply(this.client, [member, this, callback]); + }; + + Role.prototype.removeMember = function removeMember(member, callback) { + return this.client.removeMemberFromRole.apply(this.client, [member, this, callback]); + }; + + Role.prototype.removeUser = function removeUser(member, callback) { + return this.client.removeUserFromRole.apply(this.client, [member, this, callback]); + }; + + return Role; +})(); + +exports["default"] = Role; +module.exports = exports["default"]; diff --git a/lib/Structures/Server.js b/lib/Structures/Server.js index cb4cbc9a0..968c17cad 100644 --- a/lib/Structures/Server.js +++ b/lib/Structures/Server.js @@ -1,5 +1,408 @@ -"use strict"; /** +"use strict"; + +/** * Types of region for a server, include: `us-west`, `us-east`, `us-south`, `us-central`, `singapore`, `london`, `sydney`, `amsterdam` and `frankfurt` * @typedef {(string)} region - */exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _UtilEquality=require("../Util/Equality");var _UtilEquality2=_interopRequireDefault(_UtilEquality);var _Constants=require("../Constants");var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _User=require("./User");var _User2=_interopRequireDefault(_User);var _TextChannel=require("./TextChannel");var _TextChannel2=_interopRequireDefault(_TextChannel);var _VoiceChannel=require("./VoiceChannel");var _VoiceChannel2=_interopRequireDefault(_VoiceChannel);var _Role=require("./Role");var _Role2=_interopRequireDefault(_Role);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var strictKeys=["region","ownerID","name","id","icon","afkTimeout","afkChannelID"];var Server=(function(_Equality){_inherits(Server,_Equality);function Server(data,client){var _this=this;_classCallCheck(this,Server);_Equality.call(this);var self=this;this.client = client;this.region = data.region;this.ownerID = data.owner_id || data.ownerID;this.name = data.name;this.id = data.id;this.members = new _UtilCache2["default"]();this.channels = new _UtilCache2["default"]();this.roles = new _UtilCache2["default"]();this.icon = data.icon;this.afkTimeout = data.afkTimeout;this.afkChannelID = data.afk_channel_id || data.afkChannelID;this.memberMap = data.memberMap || {};this.memberCount = data.member_count || data.memberCount;this.large = data.large || this.memberCount > 250;var self=this;if(data.roles instanceof _UtilCache2["default"]){data.roles.forEach(function(role){return _this.roles.add(role);});}else {data.roles.forEach(function(dataRole){_this.roles.add(new _Role2["default"](dataRole,_this,client));});}if(data.members instanceof _UtilCache2["default"]){data.members.forEach(function(member){return _this.members.add(member);});}else {data.members.forEach(function(dataUser){_this.memberMap[dataUser.user.id] = {roles:dataUser.roles.map(function(pid){return self.roles.get("id",pid);}),mute:dataUser.mute,self_mute:dataUser.self_mute,deaf:dataUser.deaf,self_deaf:dataUser.self_deaf,joinedAt:Date.parse(dataUser.joined_at)};_this.members.add(client.internal.users.add(new _User2["default"](dataUser.user,client)));});}if(data.channels instanceof _UtilCache2["default"]){data.channels.forEach(function(channel){return _this.channels.add(channel);});}else {data.channels.forEach(function(dataChannel){if(dataChannel.type === "text"){_this.channels.add(client.internal.channels.add(new _TextChannel2["default"](dataChannel,client,_this)));}else {_this.channels.add(client.internal.channels.add(new _VoiceChannel2["default"](dataChannel,client,_this)));}});}if(data.presences){for(var _iterator=data.presences,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var presence=_ref;var user=client.internal.users.get("id",presence.user.id);if(user){user.status = presence.status;user.game = presence.game;}}}if(data.voice_states){for(var _iterator2=data.voice_states,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var voiceState=_ref2;var _user=this.members.get("id",voiceState.user_id);var channel=this.channels.get("id",voiceState.channel_id);if(_user && channel){this.eventVoiceJoin(_user,channel);}else {this.client.emit("warn","user doesn't exist even though READY expects them to");}}}}Server.prototype.detailsOf = function detailsOf(user){user = this.client.internal.resolver.resolveUser(user);if(user){return this.memberMap[user.id] || {};}else {return {};}};Server.prototype.detailsOfUser = function detailsOfUser(user){return this.detailsOf(user);};Server.prototype.detailsOfMember = function detailsOfMember(user){return this.detailsOf(user);};Server.prototype.details = function details(user){return this.detailsOf(user);};Server.prototype.rolesOfUser = function rolesOfUser(user){user = this.client.internal.resolver.resolveUser(user);if(user){return this.memberMap[user.id]?this.memberMap[user.id].roles:[];}else {return [];}};Server.prototype.rolesOfMember = function rolesOfMember(member){return this.rolesOfUser(member);};Server.prototype.rolesOf = function rolesOf(user){return this.rolesOfUser(user);};Server.prototype.toString = function toString(){return this.name;};Server.prototype.eventVoiceJoin = function eventVoiceJoin(user,channel){ // removes from other speaking channels first -var oldChannel=this.eventVoiceLeave(user);if(oldChannel.id){this.client.emit("voiceLeave",oldChannel,user);}channel.members.add(user);user.voiceChannel = channel;this.client.emit("voiceJoin",channel,user);};Server.prototype.eventVoiceStateUpdate = function eventVoiceStateUpdate(channel,user,data){if(!user.voiceChannel || user.voiceChannel.id !== channel.id){return this.eventVoiceJoin(user,channel);}if(!this.memberMap[user.id]){this.memberMap[user.id] = {};}var oldState={mute:this.memberMap[user.id].mute,self_mute:this.memberMap[user.id].self_mute,deaf:this.memberMap[user.id].deaf,self_deaf:this.memberMap[user.id].self_deaf};this.memberMap[user.id].mute = data.mute;this.memberMap[user.id].self_mute = data.self_mute;this.memberMap[user.id].deaf = data.deaf;this.memberMap[user.id].self_deaf = data.self_deaf;if(oldState.mute !== undefined && (oldState.mute != data.mute || oldState.self_mute != data.self_mute || oldState.deaf != data.deaf || oldState.self_deaf != data.self_deaf)){this.client.emit("voiceStateUpdate",channel,user,oldState,this.memberMap[user.id]);}else {this.eventVoiceJoin(user,channel);}};Server.prototype.eventVoiceLeave = function eventVoiceLeave(user){for(var _iterator3=this.channels.getAll("type","voice"),_isArray3=Array.isArray(_iterator3),_i3=0,_iterator3=_isArray3?_iterator3:_iterator3[Symbol.iterator]();;) {var _ref3;if(_isArray3){if(_i3 >= _iterator3.length)break;_ref3 = _iterator3[_i3++];}else {_i3 = _iterator3.next();if(_i3.done)break;_ref3 = _i3.value;}var chan=_ref3;if(chan.members.has(user)){chan.members.remove(user);user.voiceChannel = null;return chan;}}return {server:this};};Server.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof Server){for(var _iterator4=strictKeys,_isArray4=Array.isArray(_iterator4),_i4=0,_iterator4=_isArray4?_iterator4:_iterator4[Symbol.iterator]();;) {var _ref4;if(_isArray4){if(_i4 >= _iterator4.length)break;_ref4 = _iterator4[_i4++];}else {_i4 = _iterator4.next();if(_i4.done)break;_ref4 = _i4.value;}var key=_ref4;if(obj[key] !== this[key]){return false;}}}else {return false;}return true;};Server.prototype.leave = function leave(){return this.client.leaveServer.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Server.prototype["delete"] = function _delete(){return this.client.leaveServer.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Server.prototype.createInvite = function createInvite(){return this.client.createInvite.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Server.prototype.createRole = function createRole(){return this.client.createRole.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Server.prototype.banMember = function banMember(user,tlength,callback){return this.client.banMember.apply(this.client,[user,this,tlength,callback]);};Server.prototype.banUser = function banUser(user,tlength,callback){return this.client.banMember.apply(this.client,[user,this,tlength,callback]);};Server.prototype.ban = function ban(user,tlength,callback){return this.client.banMember.apply(this.client,[user,this,tlength,callback]);};Server.prototype.unbanMember = function unbanMember(user,callback){return this.client.unbanMember.apply(this.client,[user,this,callback]);};Server.prototype.unbanUser = function unbanUser(user,callback){return this.client.unbanMember.apply(this.client,[user,this,callback]);};Server.prototype.unban = function unban(user,callback){return this.client.unbanMember.apply(this.client,[user,this,callback]);};Server.prototype.kickMember = function kickMember(user,callback){return this.client.kickMember.apply(this.client,[user,this,callback]);};Server.prototype.kickUser = function kickUser(user,callback){return this.client.kickMember.apply(this.client,[user,this,callback]);};Server.prototype.kick = function kick(user,callback){return this.client.kickMember.apply(this.client,[user,this,callback]);};Server.prototype.getBans = function getBans(){return this.client.getBans.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Server.prototype.createChannel = function createChannel(){return this.client.createChannel.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};Server.prototype.membersWithRole = function membersWithRole(role){return this.members.filter(function(m){return m.hasRole(role);});};Server.prototype.usersWithRole = function usersWithRole(role){return this.membersWithRole(role);};_createClass(Server,[{key:"iconURL",get:function get(){if(!this.icon){return null;}else {return _Constants.Endpoints.SERVER_ICON(this.id,this.icon);}}},{key:"afkChannel",get:function get(){return this.channels.get("id",this.afkChannelID);}},{key:"defaultChannel",get:function get(){return this.channels.get("id",this.id);}},{key:"generalChannel",get:function get(){return this.defaultChannel;}},{key:"general",get:function get(){return this.defaultChannel;}},{key:"owner",get:function get(){return this.members.get("id",this.ownerID);}}]);return Server;})(_UtilEquality2["default"]);exports["default"] = Server;module.exports = exports["default"]; + */ + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _UtilEquality = require("../Util/Equality"); + +var _UtilEquality2 = _interopRequireDefault(_UtilEquality); + +var _Constants = require("../Constants"); + +var _UtilCache = require("../Util/Cache"); + +var _UtilCache2 = _interopRequireDefault(_UtilCache); + +var _User = require("./User"); + +var _User2 = _interopRequireDefault(_User); + +var _TextChannel = require("./TextChannel"); + +var _TextChannel2 = _interopRequireDefault(_TextChannel); + +var _VoiceChannel = require("./VoiceChannel"); + +var _VoiceChannel2 = _interopRequireDefault(_VoiceChannel); + +var _Role = require("./Role"); + +var _Role2 = _interopRequireDefault(_Role); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var strictKeys = ["region", "ownerID", "name", "id", "icon", "afkTimeout", "afkChannelID"]; + +var Server = (function (_Equality) { + _inherits(Server, _Equality); + + function Server(data, client) { + var _this = this; + + _classCallCheck(this, Server); + + _Equality.call(this); + + var self = this; + this.client = client; + + this.region = data.region; + this.ownerID = data.owner_id || data.ownerID; + this.name = data.name; + this.id = data.id; + this.members = new _UtilCache2["default"](); + this.channels = new _UtilCache2["default"](); + this.roles = new _UtilCache2["default"](); + this.icon = data.icon; + this.afkTimeout = data.afkTimeout; + this.afkChannelID = data.afk_channel_id || data.afkChannelID; + this.memberMap = data.memberMap || {}; + this.memberCount = data.member_count || data.memberCount; + this.large = data.large || this.memberCount > 250; + + var self = this; + + if (data.roles instanceof _UtilCache2["default"]) { + data.roles.forEach(function (role) { + return _this.roles.add(role); + }); + } else { + data.roles.forEach(function (dataRole) { + _this.roles.add(new _Role2["default"](dataRole, _this, client)); + }); + } + + if (data.members instanceof _UtilCache2["default"]) { + data.members.forEach(function (member) { + return _this.members.add(member); + }); + } else { + data.members.forEach(function (dataUser) { + _this.memberMap[dataUser.user.id] = { + roles: dataUser.roles.map(function (pid) { + return self.roles.get("id", pid); + }), + mute: dataUser.mute, + self_mute: dataUser.self_mute, + deaf: dataUser.deaf, + self_deaf: dataUser.self_deaf, + joinedAt: Date.parse(dataUser.joined_at) + }; + _this.members.add(client.internal.users.add(new _User2["default"](dataUser.user, client))); + }); + } + + if (data.channels instanceof _UtilCache2["default"]) { + data.channels.forEach(function (channel) { + return _this.channels.add(channel); + }); + } else { + data.channels.forEach(function (dataChannel) { + if (dataChannel.type === "text") { + _this.channels.add(client.internal.channels.add(new _TextChannel2["default"](dataChannel, client, _this))); + } else { + _this.channels.add(client.internal.channels.add(new _VoiceChannel2["default"](dataChannel, client, _this))); + } + }); + } + + if (data.presences) { + for (var _iterator = data.presences, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var presence = _ref; + + var user = client.internal.users.get("id", presence.user.id); + if (user) { + user.status = presence.status; + user.game = presence.game; + } + } + } + + if (data.voice_states) { + for (var _iterator2 = data.voice_states, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var voiceState = _ref2; + + var _user = this.members.get("id", voiceState.user_id); + var channel = this.channels.get("id", voiceState.channel_id); + if (_user && channel) { + this.eventVoiceJoin(_user, channel); + } else { + this.client.emit("warn", "user doesn't exist even though READY expects them to"); + } + } + } + } + + Server.prototype.detailsOf = function detailsOf(user) { + user = this.client.internal.resolver.resolveUser(user); + if (user) { + return this.memberMap[user.id] || {}; + } else { + return {}; + } + }; + + Server.prototype.detailsOfUser = function detailsOfUser(user) { + return this.detailsOf(user); + }; + + Server.prototype.detailsOfMember = function detailsOfMember(user) { + return this.detailsOf(user); + }; + + Server.prototype.details = function details(user) { + return this.detailsOf(user); + }; + + Server.prototype.rolesOfUser = function rolesOfUser(user) { + user = this.client.internal.resolver.resolveUser(user); + if (user) { + return this.memberMap[user.id] ? this.memberMap[user.id].roles : []; + } else { + return []; + } + }; + + Server.prototype.rolesOfMember = function rolesOfMember(member) { + return this.rolesOfUser(member); + }; + + Server.prototype.rolesOf = function rolesOf(user) { + return this.rolesOfUser(user); + }; + + Server.prototype.toString = function toString() { + return this.name; + }; + + Server.prototype.eventVoiceJoin = function eventVoiceJoin(user, channel) { + // removes from other speaking channels first + var oldChannel = this.eventVoiceLeave(user); + if (oldChannel.id) { + this.client.emit("voiceLeave", oldChannel, user); + } + + channel.members.add(user); + user.voiceChannel = channel; + this.client.emit("voiceJoin", channel, user); + }; + + Server.prototype.eventVoiceStateUpdate = function eventVoiceStateUpdate(channel, user, data) { + if (!user.voiceChannel || user.voiceChannel.id !== channel.id) { + return this.eventVoiceJoin(user, channel); + } + if (!this.memberMap[user.id]) { + this.memberMap[user.id] = {}; + } + var oldState = { + mute: this.memberMap[user.id].mute, + self_mute: this.memberMap[user.id].self_mute, + deaf: this.memberMap[user.id].deaf, + self_deaf: this.memberMap[user.id].self_deaf + }; + this.memberMap[user.id].mute = data.mute; + this.memberMap[user.id].self_mute = data.self_mute; + this.memberMap[user.id].deaf = data.deaf; + this.memberMap[user.id].self_deaf = data.self_deaf; + if (oldState.mute !== undefined && (oldState.mute != data.mute || oldState.self_mute != data.self_mute || oldState.deaf != data.deaf || oldState.self_deaf != data.self_deaf)) { + this.client.emit("voiceStateUpdate", channel, user, oldState, this.memberMap[user.id]); + } else { + this.eventVoiceJoin(user, channel); + } + }; + + Server.prototype.eventVoiceLeave = function eventVoiceLeave(user) { + for (var _iterator3 = this.channels.getAll("type", "voice"), _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { + var _ref3; + + if (_isArray3) { + if (_i3 >= _iterator3.length) break; + _ref3 = _iterator3[_i3++]; + } else { + _i3 = _iterator3.next(); + if (_i3.done) break; + _ref3 = _i3.value; + } + + var chan = _ref3; + + if (chan.members.has(user)) { + chan.members.remove(user); + user.voiceChannel = null; + return chan; + } + } + return { server: this }; + }; + + Server.prototype.equalsStrict = function equalsStrict(obj) { + if (obj instanceof Server) { + for (var _iterator4 = strictKeys, _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { + var _ref4; + + if (_isArray4) { + if (_i4 >= _iterator4.length) break; + _ref4 = _iterator4[_i4++]; + } else { + _i4 = _iterator4.next(); + if (_i4.done) break; + _ref4 = _i4.value; + } + + var key = _ref4; + + if (obj[key] !== this[key]) { + return false; + } + } + } else { + return false; + } + return true; + }; + + Server.prototype.leave = function leave() { + return this.client.leaveServer.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Server.prototype["delete"] = function _delete() { + return this.client.leaveServer.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Server.prototype.createInvite = function createInvite() { + return this.client.createInvite.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Server.prototype.createRole = function createRole() { + return this.client.createRole.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Server.prototype.banMember = function banMember(user, tlength, callback) { + return this.client.banMember.apply(this.client, [user, this, tlength, callback]); + }; + + Server.prototype.banUser = function banUser(user, tlength, callback) { + return this.client.banMember.apply(this.client, [user, this, tlength, callback]); + }; + + Server.prototype.ban = function ban(user, tlength, callback) { + return this.client.banMember.apply(this.client, [user, this, tlength, callback]); + }; + + Server.prototype.unbanMember = function unbanMember(user, callback) { + return this.client.unbanMember.apply(this.client, [user, this, callback]); + }; + + Server.prototype.unbanUser = function unbanUser(user, callback) { + return this.client.unbanMember.apply(this.client, [user, this, callback]); + }; + + Server.prototype.unban = function unban(user, callback) { + return this.client.unbanMember.apply(this.client, [user, this, callback]); + }; + + Server.prototype.kickMember = function kickMember(user, callback) { + return this.client.kickMember.apply(this.client, [user, this, callback]); + }; + + Server.prototype.kickUser = function kickUser(user, callback) { + return this.client.kickMember.apply(this.client, [user, this, callback]); + }; + + Server.prototype.kick = function kick(user, callback) { + return this.client.kickMember.apply(this.client, [user, this, callback]); + }; + + Server.prototype.getBans = function getBans() { + return this.client.getBans.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Server.prototype.createChannel = function createChannel() { + return this.client.createChannel.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + Server.prototype.membersWithRole = function membersWithRole(role) { + return this.members.filter(function (m) { + return m.hasRole(role); + }); + }; + + Server.prototype.usersWithRole = function usersWithRole(role) { + return this.membersWithRole(role); + }; + + _createClass(Server, [{ + key: "iconURL", + get: function get() { + if (!this.icon) { + return null; + } else { + return _Constants.Endpoints.SERVER_ICON(this.id, this.icon); + } + } + }, { + key: "afkChannel", + get: function get() { + return this.channels.get("id", this.afkChannelID); + } + }, { + key: "defaultChannel", + get: function get() { + return this.channels.get("id", this.id); + } + }, { + key: "generalChannel", + get: function get() { + return this.defaultChannel; + } + }, { + key: "general", + get: function get() { + return this.defaultChannel; + } + }, { + key: "owner", + get: function get() { + return this.members.get("id", this.ownerID); + } + }]); + + return Server; +})(_UtilEquality2["default"]); + +exports["default"] = Server; +module.exports = exports["default"]; diff --git a/lib/Structures/ServerChannel.js b/lib/Structures/ServerChannel.js index 025e7462c..77bfc37a2 100644 --- a/lib/Structures/ServerChannel.js +++ b/lib/Structures/ServerChannel.js @@ -1 +1,142 @@ -"use strict";exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _Channel2=require("./Channel");var _Channel3=_interopRequireDefault(_Channel2);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _PermissionOverwrite=require("./PermissionOverwrite");var _PermissionOverwrite2=_interopRequireDefault(_PermissionOverwrite);var _ChannelPermissions=require("./ChannelPermissions");var _ChannelPermissions2=_interopRequireDefault(_ChannelPermissions);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var ServerChannel=(function(_Channel){_inherits(ServerChannel,_Channel);function ServerChannel(data,client,server){var _this=this;_classCallCheck(this,ServerChannel);_Channel.call(this,data,client);this.name = data.name;this.type = data.type;this.position = data.position;this.permissionOverwrites = data.permissionOverwrites || new _UtilCache2["default"]();this.server = server;if(!data.permissionOverwrites){data.permission_overwrites.forEach(function(permission){_this.permissionOverwrites.add(new _PermissionOverwrite2["default"](permission));});}}ServerChannel.prototype.permissionsOf = function permissionsOf(user){user = this.client.internal.resolver.resolveUser(user);if(user){if(this.server.ownerID === user.id){return new _ChannelPermissions2["default"](4294967295);}var everyoneRole=this.server.roles.get("name","@everyone");var userRoles=[everyoneRole].concat(this.server.rolesOf(user) || []);var userRolesID=userRoles.map(function(v){return v.id;});var roleOverwrites=[],memberOverwrites=[];this.permissionOverwrites.forEach(function(overwrite){if(overwrite.type === "member" && overwrite.id === user.id){memberOverwrites.push(overwrite);}else if(overwrite.type === "role" && ~userRolesID.indexOf(overwrite.id)){roleOverwrites.push(overwrite);}});var permissions=0;for(var _iterator=userRoles,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var serverRole=_ref;permissions |= serverRole.permissions;}for(var _iterator2=roleOverwrites.concat(memberOverwrites),_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var overwrite=_ref2;permissions = permissions & ~overwrite.deny;permissions = permissions | overwrite.allow;}return new _ChannelPermissions2["default"](permissions);}else {return null;}};ServerChannel.prototype.permsOf = function permsOf(user){return this.permissionsOf(user);};ServerChannel.prototype.mention = function mention(){return "<#" + this.id + ">";};ServerChannel.prototype.toString = function toString(){return this.mention();};ServerChannel.prototype.setName = function setName(){return this.client.setChannelName.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};ServerChannel.prototype.setPosition = function setPosition(){return this.client.setChannelPosition.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};return ServerChannel;})(_Channel3["default"]);exports["default"] = ServerChannel;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _Channel2 = require("./Channel"); + +var _Channel3 = _interopRequireDefault(_Channel2); + +var _UtilCache = require("../Util/Cache"); + +var _UtilCache2 = _interopRequireDefault(_UtilCache); + +var _PermissionOverwrite = require("./PermissionOverwrite"); + +var _PermissionOverwrite2 = _interopRequireDefault(_PermissionOverwrite); + +var _ChannelPermissions = require("./ChannelPermissions"); + +var _ChannelPermissions2 = _interopRequireDefault(_ChannelPermissions); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var ServerChannel = (function (_Channel) { + _inherits(ServerChannel, _Channel); + + function ServerChannel(data, client, server) { + var _this = this; + + _classCallCheck(this, ServerChannel); + + _Channel.call(this, data, client); + this.name = data.name; + this.type = data.type; + this.position = data.position; + this.permissionOverwrites = data.permissionOverwrites || new _UtilCache2["default"](); + this.server = server; + if (!data.permissionOverwrites) { + data.permission_overwrites.forEach(function (permission) { + _this.permissionOverwrites.add(new _PermissionOverwrite2["default"](permission)); + }); + } + } + + ServerChannel.prototype.permissionsOf = function permissionsOf(user) { + user = this.client.internal.resolver.resolveUser(user); + if (user) { + if (this.server.ownerID === user.id) { + return new _ChannelPermissions2["default"](4294967295); + } + var everyoneRole = this.server.roles.get("id", this.server.id); + + var userRoles = [everyoneRole].concat(this.server.rolesOf(user) || []); + var userRolesID = userRoles.filter(function (v) { + return !!v; + }).map(function (v) { + return v.id; + }); + var roleOverwrites = [], + memberOverwrites = []; + + this.permissionOverwrites.forEach(function (overwrite) { + if (overwrite.type === "member" && overwrite.id === user.id) { + memberOverwrites.push(overwrite); + } else if (overwrite.type === "role" && ~userRolesID.indexOf(overwrite.id)) { + roleOverwrites.push(overwrite); + } + }); + + var permissions = 0; + + for (var _iterator = userRoles, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var serverRole = _ref; + + permissions |= serverRole.permissions; + } + + for (var _iterator2 = roleOverwrites.concat(memberOverwrites), _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var overwrite = _ref2; + + permissions = permissions & ~overwrite.deny; + permissions = permissions | overwrite.allow; + } + + return new _ChannelPermissions2["default"](permissions); + } else { + return null; + } + }; + + ServerChannel.prototype.permsOf = function permsOf(user) { + return this.permissionsOf(user); + }; + + ServerChannel.prototype.mention = function mention() { + return "<#" + this.id + ">"; + }; + + ServerChannel.prototype.toString = function toString() { + return this.mention(); + }; + + ServerChannel.prototype.setName = function setName() { + return this.client.setChannelName.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + ServerChannel.prototype.setPosition = function setPosition() { + return this.client.setChannelPosition.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + return ServerChannel; +})(_Channel3["default"]); + +exports["default"] = ServerChannel; +module.exports = exports["default"]; diff --git a/lib/Structures/TextChannel.js b/lib/Structures/TextChannel.js index e3620376e..876640cbc 100644 --- a/lib/Structures/TextChannel.js +++ b/lib/Structures/TextChannel.js @@ -1 +1,93 @@ -"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _ServerChannel2=require("./ServerChannel");var _ServerChannel3=_interopRequireDefault(_ServerChannel2);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var TextChannel=(function(_ServerChannel){_inherits(TextChannel,_ServerChannel);function TextChannel(data,client,server){_classCallCheck(this,TextChannel);_ServerChannel.call(this,data,client,server);this.topic = data.topic;this.lastMessageID = data.last_message_id || data.lastMessageID;this.messages = new _UtilCache2["default"]("id",client.options.maxCachedMessages);} /* warning! may return null */TextChannel.prototype.setTopic = function setTopic(){return this.client.setChannelTopic.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.setNameAndTopic = function setNameAndTopic(){return this.client.setChannelNameAndTopic.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.update = function update(){return this.client.updateChannel.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.send = function send(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendTTS = function sendTTS(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.sendFile = function sendFile(){return this.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.getLogs = function getLogs(){return this.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.startTyping = function startTyping(){return this.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};TextChannel.prototype.stopTyping = function stopTyping(){return this.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};_createClass(TextChannel,[{key:"lastMessage",get:function get(){return this.messages.get("id",this.lastMessageID);}}]);return TextChannel;})(_ServerChannel3["default"]);exports["default"] = TextChannel;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _ServerChannel2 = require("./ServerChannel"); + +var _ServerChannel3 = _interopRequireDefault(_ServerChannel2); + +var _UtilCache = require("../Util/Cache"); + +var _UtilCache2 = _interopRequireDefault(_UtilCache); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var TextChannel = (function (_ServerChannel) { + _inherits(TextChannel, _ServerChannel); + + function TextChannel(data, client, server) { + _classCallCheck(this, TextChannel); + + _ServerChannel.call(this, data, client, server); + + this.topic = data.topic; + this.lastMessageID = data.last_message_id || data.lastMessageID; + this.messages = new _UtilCache2["default"]("id", client.options.maxCachedMessages); + } + + /* warning! may return null */ + + TextChannel.prototype.setTopic = function setTopic() { + return this.client.setChannelTopic.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.setNameAndTopic = function setNameAndTopic() { + return this.client.setChannelNameAndTopic.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.update = function update() { + return this.client.updateChannel.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.sendMessage = function sendMessage() { + return this.client.sendMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.send = function send() { + return this.client.sendMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.sendTTSMessage = function sendTTSMessage() { + return this.client.sendTTSMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.sendTTS = function sendTTS() { + return this.client.sendTTSMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.sendFile = function sendFile() { + return this.client.sendFile.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.getLogs = function getLogs() { + return this.client.getChannelLogs.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.startTyping = function startTyping() { + return this.client.startTyping.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + TextChannel.prototype.stopTyping = function stopTyping() { + return this.client.stopTyping.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + _createClass(TextChannel, [{ + key: "lastMessage", + get: function get() { + return this.messages.get("id", this.lastMessageID); + } + }]); + + return TextChannel; +})(_ServerChannel3["default"]); + +exports["default"] = TextChannel; +module.exports = exports["default"]; diff --git a/lib/Structures/User.js b/lib/Structures/User.js index d87cf6641..b698d4901 100644 --- a/lib/Structures/User.js +++ b/lib/Structures/User.js @@ -1 +1,124 @@ -"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _UtilEquality=require("../Util/Equality");var _UtilEquality2=_interopRequireDefault(_UtilEquality);var _Constants=require("../Constants");var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var User=(function(_Equality){_inherits(User,_Equality);function User(data,client){_classCallCheck(this,User);_Equality.call(this);this.client = client;this.username = data.username;this.discriminator = data.discriminator;this.id = data.id;this.avatar = data.avatar;this.bot = !!data.bot;this.status = data.status || "offline";this.game = data.game || null;this.typing = {since:null,channel:null};this.voiceChannel = null;this.voiceState = {};}User.prototype.mention = function mention(){return "<@" + this.id + ">";};User.prototype.toString = function toString(){return this.mention();};User.prototype.equalsStrict = function equalsStrict(obj){if(obj instanceof User)return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && (this.game === obj.game || this.game && obj.game && this.game.name === obj.game.name);else return false;};User.prototype.equals = function equals(obj){if(obj instanceof User)return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar;else return false;};User.prototype.sendMessage = function sendMessage(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.send = function send(){return this.client.sendMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendTTSMessage = function sendTTSMessage(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendTTS = function sendTTS(){return this.client.sendTTSMessage.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.sendFile = function sendFile(){return this.client.sendFile.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.startTyping = function startTyping(){return this.client.startTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.stopTyping = function stopTyping(){return this.client.stopTyping.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.addTo = function addTo(role,callback){return this.client.addMemberToRole.apply(this.client,[this,role,callback]);};User.prototype.removeFrom = function removeFrom(role,callback){return this.client.removeMemberFromRole.apply(this.client,[this,role,callback]);};User.prototype.getLogs = function getLogs(){return this.client.getChannelLogs.apply(this.client,_UtilArgumentRegulariser.reg(this,arguments));};User.prototype.hasRole = function hasRole(role){return this.client.memberHasRole.apply(this.client,[this,role]);};_createClass(User,[{key:"avatarURL",get:function get(){if(!this.avatar){return null;}else {return _Constants.Endpoints.AVATAR(this.id,this.avatar);}}},{key:"name",get:function get(){return this.username;}}]);return User;})(_UtilEquality2["default"]);exports["default"] = User;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _UtilEquality = require("../Util/Equality"); + +var _UtilEquality2 = _interopRequireDefault(_UtilEquality); + +var _Constants = require("../Constants"); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var User = (function (_Equality) { + _inherits(User, _Equality); + + function User(data, client) { + _classCallCheck(this, User); + + _Equality.call(this); + this.client = client; + this.username = data.username; + this.discriminator = data.discriminator; + this.id = data.id; + this.avatar = data.avatar; + this.bot = !!data.bot; + this.status = data.status || "offline"; + this.game = data.game || null; + this.typing = { + since: null, + channel: null + }; + this.voiceChannel = null; + this.voiceState = {}; + } + + User.prototype.mention = function mention() { + return "<@" + this.id + ">"; + }; + + User.prototype.toString = function toString() { + return this.mention(); + }; + + User.prototype.equalsStrict = function equalsStrict(obj) { + if (obj instanceof User) return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && (this.game === obj.game || this.game && obj.game && this.game.name === obj.game.name);else return false; + }; + + User.prototype.equals = function equals(obj) { + if (obj instanceof User) return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar;else return false; + }; + + User.prototype.sendMessage = function sendMessage() { + return this.client.sendMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.send = function send() { + return this.client.sendMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.sendTTSMessage = function sendTTSMessage() { + return this.client.sendTTSMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.sendTTS = function sendTTS() { + return this.client.sendTTSMessage.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.sendFile = function sendFile() { + return this.client.sendFile.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.startTyping = function startTyping() { + return this.client.startTyping.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.stopTyping = function stopTyping() { + return this.client.stopTyping.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.addTo = function addTo(role, callback) { + return this.client.addMemberToRole.apply(this.client, [this, role, callback]); + }; + + User.prototype.removeFrom = function removeFrom(role, callback) { + return this.client.removeMemberFromRole.apply(this.client, [this, role, callback]); + }; + + User.prototype.getLogs = function getLogs() { + return this.client.getChannelLogs.apply(this.client, _UtilArgumentRegulariser.reg(this, arguments)); + }; + + User.prototype.hasRole = function hasRole(role) { + return this.client.memberHasRole.apply(this.client, [this, role]); + }; + + _createClass(User, [{ + key: "avatarURL", + get: function get() { + if (!this.avatar) { + return null; + } else { + return _Constants.Endpoints.AVATAR(this.id, this.avatar); + } + } + }, { + key: "name", + get: function get() { + return this.username; + } + }]); + + return User; +})(_UtilEquality2["default"]); + +exports["default"] = User; +module.exports = exports["default"]; diff --git a/lib/Structures/VoiceChannel.js b/lib/Structures/VoiceChannel.js index f755af4bc..cbc8ee4f6 100644 --- a/lib/Structures/VoiceChannel.js +++ b/lib/Structures/VoiceChannel.js @@ -1 +1,41 @@ -"use strict";exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _ServerChannel2=require("./ServerChannel");var _ServerChannel3=_interopRequireDefault(_ServerChannel2);var _UtilCache=require("../Util/Cache");var _UtilCache2=_interopRequireDefault(_UtilCache);var _UtilArgumentRegulariser=require("../Util/ArgumentRegulariser");var VoiceChannel=(function(_ServerChannel){_inherits(VoiceChannel,_ServerChannel);function VoiceChannel(data,client,server){_classCallCheck(this,VoiceChannel);_ServerChannel.call(this,data,client,server);this.members = data.members || new _UtilCache2["default"]();}VoiceChannel.prototype.join = function join(){var callback=arguments.length <= 0 || arguments[0] === undefined?function(){}:arguments[0];return this.client.joinVoiceChannel.apply(this.client,[this,callback]);};return VoiceChannel;})(_ServerChannel3["default"]);exports["default"] = VoiceChannel;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _ServerChannel2 = require("./ServerChannel"); + +var _ServerChannel3 = _interopRequireDefault(_ServerChannel2); + +var _UtilCache = require("../Util/Cache"); + +var _UtilCache2 = _interopRequireDefault(_UtilCache); + +var _UtilArgumentRegulariser = require("../Util/ArgumentRegulariser"); + +var VoiceChannel = (function (_ServerChannel) { + _inherits(VoiceChannel, _ServerChannel); + + function VoiceChannel(data, client, server) { + _classCallCheck(this, VoiceChannel); + + _ServerChannel.call(this, data, client, server); + this.members = data.members || new _UtilCache2["default"](); + } + + VoiceChannel.prototype.join = function join() { + var callback = arguments.length <= 0 || arguments[0] === undefined ? function () {} : arguments[0]; + + return this.client.joinVoiceChannel.apply(this.client, [this, callback]); + }; + + return VoiceChannel; +})(_ServerChannel3["default"]); + +exports["default"] = VoiceChannel; +module.exports = exports["default"]; diff --git a/lib/Util/ArgumentRegulariser.js b/lib/Util/ArgumentRegulariser.js index 3afa86308..cee9d5a57 100644 --- a/lib/Util/ArgumentRegulariser.js +++ b/lib/Util/ArgumentRegulariser.js @@ -1 +1,8 @@ -"use strict";exports.__esModule = true;exports.reg = reg;function reg(c,a){return [c].concat(Array.prototype.slice.call(a));} +"use strict"; + +exports.__esModule = true; +exports.reg = reg; + +function reg(c, a) { + return [c].concat(Array.prototype.slice.call(a)); +} diff --git a/lib/Util/Cache.js b/lib/Util/Cache.js index 16a83706e..cd614d175 100644 --- a/lib/Util/Cache.js +++ b/lib/Util/Cache.js @@ -1 +1,149 @@ -"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var discrimS=Symbol();var discrimCacheS=Symbol();var Cache=(function(_Array){_inherits(Cache,_Array);function Cache(discrim,limit){_classCallCheck(this,Cache);_Array.call(this);this[discrimS] = discrim || "id";this[discrimCacheS] = {};this.limit = limit;}Cache.prototype.get = function get(key,value){if(typeof key === 'function'){var valid=key;key = null;}else if(key === this[discrimS] && typeof value === "string"){return this[discrimCacheS][value] || null;}else if(value && value.constructor.name === 'RegExp'){var valid=function valid(item){return value.test(item);};}else if(typeof value !== 'function'){var valid=function valid(item){return item == value;};}for(var _iterator=this,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var item=_ref;if(valid(key == null?item:item[key])){return item;}}return null;};Cache.prototype.has = function has(object){return !!this.get(this[discrimS],object[this[discrimS]]);};Cache.prototype.getAll = function getAll(key,value){var found=new Cache(this[discrimS]);if(typeof key === 'function'){var valid=key;key = null;}else if(value && value.constructor.name === 'RegExp'){var valid=function valid(item){return value.test(item);};}else if(typeof value !== 'function'){var valid=function valid(item){return item == value;};}for(var _iterator2=this,_isArray2=Array.isArray(_iterator2),_i2=0,_iterator2=_isArray2?_iterator2:_iterator2[Symbol.iterator]();;) {var _ref2;if(_isArray2){if(_i2 >= _iterator2.length)break;_ref2 = _iterator2[_i2++];}else {_i2 = _iterator2.next();if(_i2.done)break;_ref2 = _i2.value;}var item=_ref2;if(valid(key == null?item:item[key])){found.add(item);}}return found;};Cache.prototype.add = function add(data){var cacheKey=data[this[discrimS]];if(this[discrimCacheS][cacheKey]){return this[discrimCacheS][cacheKey];}if(this.limit && this.length >= this.limit){this.splice(0,1);}this.push(data);this[discrimCacheS][cacheKey] = data;return data;};Cache.prototype.update = function update(old,data){var obj=this[discrimCacheS][old[this[discrimS]]];if(obj){for(var key in data) {if(data.hasOwnProperty(key)){obj[key] = data[key];}}return obj;}return false;};Cache.prototype.random = function random(){return this[Math.floor(Math.random() * this.length)];};Cache.prototype.remove = function remove(data){delete this[discrimCacheS][data[this[discrimS]]];for(var i in this) {if(this[i][this[discrimS]] === data[this[discrimS]]){this.splice(i,1);return true;}}return false;};return Cache;})(Array);exports["default"] = Cache;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var discrimS = Symbol(); +var discrimCacheS = Symbol(); + +var Cache = (function (_Array) { + _inherits(Cache, _Array); + + function Cache(discrim, limit) { + _classCallCheck(this, Cache); + + _Array.call(this); + this[discrimS] = discrim || "id"; + this[discrimCacheS] = {}; + this.limit = limit; + } + + Cache.prototype.get = function get(key, value) { + if (typeof key === 'function') { + var valid = key; + key = null; + } else if (key === this[discrimS] && typeof value === "string") { + return this[discrimCacheS][value] || null; + } else if (value && value.constructor.name === 'RegExp') { + var valid = function valid(item) { + return value.test(item); + }; + } else if (typeof value !== 'function') { + var valid = function valid(item) { + return item == value; + }; + } + + for (var _iterator = this, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var item = _ref; + + if (valid(key == null ? item : item[key])) { + return item; + } + } + + return null; + }; + + Cache.prototype.has = function has(object) { + return !!this.get(this[discrimS], object[this[discrimS]]); + }; + + Cache.prototype.getAll = function getAll(key, value) { + var found = new Cache(this[discrimS]); + + if (typeof key === 'function') { + var valid = key; + key = null; + } else if (value && value.constructor.name === 'RegExp') { + var valid = function valid(item) { + return value.test(item); + }; + } else if (typeof value !== 'function') { + var valid = function valid(item) { + return item == value; + }; + } + + for (var _iterator2 = this, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { + var _ref2; + + if (_isArray2) { + if (_i2 >= _iterator2.length) break; + _ref2 = _iterator2[_i2++]; + } else { + _i2 = _iterator2.next(); + if (_i2.done) break; + _ref2 = _i2.value; + } + + var item = _ref2; + + if (valid(key == null ? item : item[key])) { + found.add(item); + } + } + + return found; + }; + + Cache.prototype.add = function add(data) { + var cacheKey = data[this[discrimS]]; + if (this[discrimCacheS][cacheKey]) { + return this[discrimCacheS][cacheKey]; + } + if (this.limit && this.length >= this.limit) { + this.splice(0, 1); + } + this.push(data); + this[discrimCacheS][cacheKey] = data; + return data; + }; + + Cache.prototype.update = function update(old, data) { + var obj = this[discrimCacheS][old[this[discrimS]]]; + if (obj) { + for (var key in data) { + if (data.hasOwnProperty(key)) { + obj[key] = data[key]; + } + } + return obj; + } + return false; + }; + + Cache.prototype.random = function random() { + return this[Math.floor(Math.random() * this.length)]; + }; + + Cache.prototype.remove = function remove(data) { + delete this[discrimCacheS][data[this[discrimS]]]; + for (var i in this) { + if (this[i][this[discrimS]] === data[this[discrimS]]) { + this.splice(i, 1); + return true; + } + } + return false; + }; + + return Cache; +})(Array); + +exports["default"] = Cache; +module.exports = exports["default"]; diff --git a/lib/Util/Equality.js b/lib/Util/Equality.js index bd131dd79..6c4f7caf7 100644 --- a/lib/Util/Equality.js +++ b/lib/Util/Equality.js @@ -8,5 +8,38 @@ instances sometimes. Instead, use objectThatExtendsEquality.equals() -*/"use strict";exports.__esModule = true;var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if("value" in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var Equality=(function(){function Equality(){_classCallCheck(this,Equality);}Equality.prototype.equals = function equals(object){return object && object[this.eqDiscriminator] === this[this.eqDiscriminator];};Equality.prototype.equalsStrict = function equalsStrict(object){ // override per class type -return;};_createClass(Equality,[{key:"eqDiscriminator",get:function get(){return "id";}}]);return Equality;})();exports["default"] = Equality;module.exports = exports["default"]; +*/ +"use strict"; + +exports.__esModule = true; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Equality = (function () { + function Equality() { + _classCallCheck(this, Equality); + } + + Equality.prototype.equals = function equals(object) { + return object && object[this.eqDiscriminator] === this[this.eqDiscriminator]; + }; + + Equality.prototype.equalsStrict = function equalsStrict(object) { + // override per class type + return; + }; + + _createClass(Equality, [{ + key: "eqDiscriminator", + get: function get() { + return "id"; + } + }]); + + return Equality; +})(); + +exports["default"] = Equality; +module.exports = exports["default"]; diff --git a/lib/Util/TokenCacher-shim.js b/lib/Util/TokenCacher-shim.js index edd0d2397..f483e9575 100644 --- a/lib/Util/TokenCacher-shim.js +++ b/lib/Util/TokenCacher-shim.js @@ -1,2 +1,29 @@ // Shim for the token cacher in the browser. -"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var TokenCacher=(function(){function TokenCacher(){_classCallCheck(this,TokenCacher);}TokenCacher.prototype.setToken = function setToken(){};TokenCacher.prototype.save = function save(){};TokenCacher.prototype.getToken = function getToken(){return null;};TokenCacher.prototype.init = function init(ind){this.done = true;};return TokenCacher;})();exports["default"] = TokenCacher;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var TokenCacher = (function () { + function TokenCacher() { + _classCallCheck(this, TokenCacher); + } + + TokenCacher.prototype.setToken = function setToken() {}; + + TokenCacher.prototype.save = function save() {}; + + TokenCacher.prototype.getToken = function getToken() { + return null; + }; + + TokenCacher.prototype.init = function init(ind) { + this.done = true; + }; + + return TokenCacher; +})(); + +exports["default"] = TokenCacher; +module.exports = exports["default"]; diff --git a/lib/Util/TokenCacher.js b/lib/Util/TokenCacher.js index 0a5b82b3e..5e177104b 100644 --- a/lib/Util/TokenCacher.js +++ b/lib/Util/TokenCacher.js @@ -1,12 +1,157 @@ -"use strict"; /* global process */exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _fs=require("fs");var _fs2=_interopRequireDefault(_fs);var _events=require("events");var _events2=_interopRequireDefault(_events);var _crypto=require("crypto");var _crypto2=_interopRequireDefault(_crypto);var savePaths=[process.env.APPDATA || (process.platform == "darwin"?process.env.HOME + "Library/Preference":"/var/local"),process.env[process.platform == "win32"?"USERPROFILE":"HOME"],process.cwd()];var algo="aes-256-ctr";function secureEmail(email,password){return new Buffer(_crypto2["default"].createHash("sha256").update(email + password,"utf8").digest()).toString("hex");}function exists(path){ // Node deprecated the `fs.exists` method apparently... -try{_fs2["default"].accessSync(path);return true;}catch(e) {return false;}}var TokenCacher=(function(_EventEmitter){_inherits(TokenCacher,_EventEmitter);function TokenCacher(client,options){_classCallCheck(this,TokenCacher);_EventEmitter.call(this);this.client = client;this.savePath = null;this.error = false;this.done = false;this.data = {};}TokenCacher.prototype.setToken = function setToken(){var email=arguments.length <= 0 || arguments[0] === undefined?"":arguments[0];var password=arguments.length <= 1 || arguments[1] === undefined?"":arguments[1];var token=arguments.length <= 2 || arguments[2] === undefined?"":arguments[2];email = secureEmail(email,password);var cipher=_crypto2["default"].createCipher(algo,password);var crypted=cipher.update("valid" + token,"utf8","hex");crypted += cipher.final("hex");this.data[email] = crypted;this.save();};TokenCacher.prototype.save = function save(){_fs2["default"].writeFile(this.savePath,JSON.stringify(this.data));};TokenCacher.prototype.getToken = function getToken(){var email=arguments.length <= 0 || arguments[0] === undefined?"":arguments[0];var password=arguments.length <= 1 || arguments[1] === undefined?"":arguments[1];email = secureEmail(email,password);if(this.data[email]){try{var decipher=_crypto2["default"].createDecipher(algo,password);var dec=decipher.update(this.data[email],"hex","utf8");dec += decipher.final("utf8");return dec.indexOf("valid") === 0?dec.substr(5):false;}catch(e) { // not a valid token -return null;}}else {return null;}};TokenCacher.prototype.init = function init(ind){var _this=this;var self=this;var savePath=savePaths[ind]; // Use one async function at the beginning, so the entire function is async, -// then later use only sync functions to increase readability -_fs2["default"].stat(savePath,function(err,dirStats){ // Directory does not exist. -if(err)error(err);else {try{var storeDirPath=savePath + "/.discordjs";var filePath=storeDirPath + "/tokens.json";if(!exists(storeDirPath)){ // First, make sure the directory exists, otherwise the next -// call will fail. -_fs2["default"].mkdirSync(storeDirPath);}if(!exists(filePath)){ // This will create an empty file if the file doesn't exist, and error -// if it does exist. We previously checked that it doesn't exist so we -// can do this safely. -_fs2["default"].closeSync(_fs2["default"].openSync(filePath,'wx'));}var data=_fs2["default"].readFileSync(filePath);try{_this.data = JSON.parse(data);_this.savePath = filePath;_this.emit('ready');_this.done = true;}catch(e) { // not valid JSON, make it valid and then write -_fs2["default"].writeFileSync(filePath,'{}');_this.savePath = filePath;_this.emit("ready");_this.done = true;}}catch(e) {error(e);}}});function error(e){ind++;if(!savePaths[ind]){self.emit("error");self.error = e;self.done = true;}else {self.init(ind);}}};return TokenCacher;})(_events2["default"]);exports["default"] = TokenCacher;module.exports = exports["default"]; +"use strict"; +/* global process */ + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _fs = require("fs"); + +var _fs2 = _interopRequireDefault(_fs); + +var _events = require("events"); + +var _events2 = _interopRequireDefault(_events); + +var _crypto = require("crypto"); + +var _crypto2 = _interopRequireDefault(_crypto); + +var savePaths = [process.env.APPDATA || (process.platform == "darwin" ? process.env.HOME + "Library/Preference" : "/var/local"), process.env[process.platform == "win32" ? "USERPROFILE" : "HOME"], process.cwd()]; + +var algo = "aes-256-ctr"; + +function secureEmail(email, password) { + return new Buffer(_crypto2["default"].createHash("sha256").update(email + password, "utf8").digest()).toString("hex"); +} + +function exists(path) { + // Node deprecated the `fs.exists` method apparently... + try { + _fs2["default"].accessSync(path); + return true; + } catch (e) { + return false; + } +} + +var TokenCacher = (function (_EventEmitter) { + _inherits(TokenCacher, _EventEmitter); + + function TokenCacher(client, options) { + _classCallCheck(this, TokenCacher); + + _EventEmitter.call(this); + this.client = client; + this.savePath = null; + this.error = false; + this.done = false; + this.data = {}; + } + + TokenCacher.prototype.setToken = function setToken() { + var email = arguments.length <= 0 || arguments[0] === undefined ? "" : arguments[0]; + var password = arguments.length <= 1 || arguments[1] === undefined ? "" : arguments[1]; + var token = arguments.length <= 2 || arguments[2] === undefined ? "" : arguments[2]; + + email = secureEmail(email, password); + var cipher = _crypto2["default"].createCipher(algo, password); + var crypted = cipher.update("valid" + token, "utf8", "hex"); + crypted += cipher.final("hex"); + this.data[email] = crypted; + this.save(); + }; + + TokenCacher.prototype.save = function save() { + _fs2["default"].writeFile(this.savePath, JSON.stringify(this.data)); + }; + + TokenCacher.prototype.getToken = function getToken() { + var email = arguments.length <= 0 || arguments[0] === undefined ? "" : arguments[0]; + var password = arguments.length <= 1 || arguments[1] === undefined ? "" : arguments[1]; + + email = secureEmail(email, password); + + if (this.data[email]) { + + try { + var decipher = _crypto2["default"].createDecipher(algo, password); + var dec = decipher.update(this.data[email], "hex", "utf8"); + dec += decipher.final("utf8"); + return dec.indexOf("valid") === 0 ? dec.substr(5) : false; + } catch (e) { + // not a valid token + return null; + } + } else { + return null; + } + }; + + TokenCacher.prototype.init = function init(ind) { + var _this = this; + + var self = this; + var savePath = savePaths[ind]; + + // Use one async function at the beginning, so the entire function is async, + // then later use only sync functions to increase readability + _fs2["default"].stat(savePath, function (err, dirStats) { + // Directory does not exist. + if (err) error(err);else { + try { + var storeDirPath = savePath + "/.discordjs"; + var filePath = storeDirPath + "/tokens.json"; + + if (!exists(storeDirPath)) { + // First, make sure the directory exists, otherwise the next + // call will fail. + _fs2["default"].mkdirSync(storeDirPath); + } + if (!exists(filePath)) { + // This will create an empty file if the file doesn't exist, and error + // if it does exist. We previously checked that it doesn't exist so we + // can do this safely. + _fs2["default"].closeSync(_fs2["default"].openSync(filePath, 'wx')); + } + + var data = _fs2["default"].readFileSync(filePath); + try { + _this.data = JSON.parse(data); + _this.savePath = filePath; + _this.emit('ready'); + _this.done = true; + } catch (e) { + // not valid JSON, make it valid and then write + _fs2["default"].writeFileSync(filePath, '{}'); + _this.savePath = filePath; + _this.emit("ready"); + _this.done = true; + } + } catch (e) { + error(e); + } + } + }); + + function error(e) { + ind++; + if (!savePaths[ind]) { + self.emit("error"); + self.error = e; + self.done = true; + } else { + self.init(ind); + } + } + }; + + return TokenCacher; +})(_events2["default"]); + +exports["default"] = TokenCacher; +module.exports = exports["default"]; diff --git a/lib/Voice/AudioEncoder.js b/lib/Voice/AudioEncoder.js index 9fc368fcf..1c28fc99e 100644 --- a/lib/Voice/AudioEncoder.js +++ b/lib/Voice/AudioEncoder.js @@ -1,3 +1,207 @@ -"use strict";exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _child_process=require("child_process");var _child_process2=_interopRequireDefault(_child_process); // no opus! -var _VolumeTransformer=require("./VolumeTransformer");var _VolumeTransformer2=_interopRequireDefault(_VolumeTransformer);var opus;try{opus = require("node-opus");}catch(e) {}var AudioEncoder=(function(){function AudioEncoder(){_classCallCheck(this,AudioEncoder);if(opus){this.opus = new opus.OpusEncoder(48000,2);}this.choice = false;this.sanityCheckPassed = undefined;}AudioEncoder.prototype.sanityCheck = function sanityCheck(){var _opus=this.opus;var encodeZeroes=function encodeZeroes(){try{var zeroes=new Buffer(1920);zeroes.fill(0);return _opus.encode(zeroes,1920).readUIntBE(0,3);}catch(err) {return false;}};if(this.sanityCheckPassed === undefined)this.sanityCheckPassed = encodeZeroes() === 16056318;return this.sanityCheckPassed;};AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer){return this.opus.encode(buffer,1920);};AudioEncoder.prototype.getCommand = function getCommand(force){if(this.choice && force)return choice;var choices=["avconv","ffmpeg"];for(var _iterator=choices,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var choice=_ref;var p=_child_process2["default"].spawnSync(choice);if(!p.error){this.choice = choice;return choice;}}return "help";};AudioEncoder.prototype.encodeStream = function encodeStream(stream,options){var _this=this;return new Promise(function(resolve,reject){_this.volume = new _VolumeTransformer2["default"](options.volume);var enc=_child_process2["default"].spawn(_this.getCommand(),['-i','-','-f','s16le','-ar','48000','-ss',options.seek || 0,'-ac',2,'pipe:1']);stream.pipe(enc.stdin);var ffmpegErrors="";enc.stdout.pipe(_this.volume);enc.stderr.on("data",function(data){ffmpegErrors += "\n" + new Buffer(data).toString().trim();});enc.once("exit",function(code,signal){if(code){reject(new Error("FFMPEG: " + ffmpegErrors));}});_this.volume.once("readable",function(){resolve({proc:enc,stream:_this.volume,instream:stream,channels:2});});_this.volume.on("end",function(){reject("end");});_this.volume.on("close",function(){reject("close");});});};AudioEncoder.prototype.encodeFile = function encodeFile(file,options){var _this2=this;return new Promise(function(resolve,reject){_this2.volume = new _VolumeTransformer2["default"](options.volume);var enc=_child_process2["default"].spawn(_this2.getCommand(),['-i',file,'-f','s16le','-ar','48000','-ss',options.seek || 0,'-ac',2,'pipe:1']);var ffmpegErrors="";enc.stdout.pipe(_this2.volume);enc.stderr.on("data",function(data){ffmpegErrors += "\n" + new Buffer(data).toString().trim();});enc.once("exit",function(code,signal){if(code){reject(new Error("FFMPEG: " + ffmpegErrors));}});_this2.volume.once("readable",function(){resolve({proc:enc,stream:_this2.volume,channels:2});});_this2.volume.on("end",function(){reject("end");});_this2.volume.on("close",function(){reject("close");});});};AudioEncoder.prototype.encodeArbitraryFFmpeg = function encodeArbitraryFFmpeg(ffmpegOptions){var _this3=this;return new Promise(function(resolve,reject){_this3.volume = new _VolumeTransformer2["default"](1); // add options discord.js needs -var options=ffmpegOptions.concat(['-f','s16le','-ar','48000','-ac',2,'pipe:1']);var enc=_child_process2["default"].spawn(_this3.getCommand(),options);var ffmpegErrors="";enc.stdout.pipe(_this3.volume);enc.stderr.on("data",function(data){ffmpegErrors += "\n" + new Buffer(data).toString().trim();});enc.once("exit",function(code,signal){if(code){reject(new Error("FFMPEG: " + ffmpegErrors));}});_this3.volume.once("readable",function(){resolve({proc:enc,stream:_this3.volume,channels:2});});_this3.volume.on("end",function(){reject("end");});_this3.volume.on("close",function(){reject("close");});});};return AudioEncoder;})();exports["default"] = AudioEncoder;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var _child_process = require("child_process"); + +var _child_process2 = _interopRequireDefault(_child_process); + +// no opus! + +var _VolumeTransformer = require("./VolumeTransformer"); + +var _VolumeTransformer2 = _interopRequireDefault(_VolumeTransformer); + +var opus; +try { + opus = require("node-opus"); +} catch (e) {} + +var AudioEncoder = (function () { + function AudioEncoder() { + _classCallCheck(this, AudioEncoder); + + if (opus) { + this.opus = new opus.OpusEncoder(48000, 2); + } + this.choice = false; + this.sanityCheckPassed = undefined; + } + + AudioEncoder.prototype.sanityCheck = function sanityCheck() { + var _opus = this.opus; + var encodeZeroes = function encodeZeroes() { + try { + var zeroes = new Buffer(1920); + zeroes.fill(0); + return _opus.encode(zeroes, 1920).readUIntBE(0, 3); + } catch (err) { + return false; + } + }; + if (this.sanityCheckPassed === undefined) this.sanityCheckPassed = encodeZeroes() === 16056318; + return this.sanityCheckPassed; + }; + + AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer) { + + return this.opus.encode(buffer, 1920); + }; + + AudioEncoder.prototype.getCommand = function getCommand(force) { + if (this.choice && force) return choice; + + var choices = ["avconv", "ffmpeg"]; + + for (var _iterator = choices, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { + var _ref; + + if (_isArray) { + if (_i >= _iterator.length) break; + _ref = _iterator[_i++]; + } else { + _i = _iterator.next(); + if (_i.done) break; + _ref = _i.value; + } + + var choice = _ref; + + var p = _child_process2["default"].spawnSync(choice); + if (!p.error) { + this.choice = choice; + return choice; + } + } + + return "help"; + }; + + AudioEncoder.prototype.encodeStream = function encodeStream(stream, options) { + var _this = this; + + return new Promise(function (resolve, reject) { + _this.volume = new _VolumeTransformer2["default"](options.volume); + + var enc = _child_process2["default"].spawn(_this.getCommand(), ['-i', '-', '-f', 's16le', '-ar', '48000', '-ss', options.seek || 0, '-ac', 2, 'pipe:1']); + + stream.pipe(enc.stdin); + + var ffmpegErrors = ""; + + enc.stdout.pipe(_this.volume); + enc.stderr.on("data", function (data) { + ffmpegErrors += "\n" + new Buffer(data).toString().trim(); + }); + enc.once("exit", function (code, signal) { + if (code) { + reject(new Error("FFMPEG: " + ffmpegErrors)); + } + }); + + _this.volume.once("readable", function () { + resolve({ + proc: enc, + stream: _this.volume, + instream: stream, + channels: 2 + }); + }); + + _this.volume.on("end", function () { + reject("end"); + }); + + _this.volume.on("close", function () { + reject("close"); + }); + }); + }; + + AudioEncoder.prototype.encodeFile = function encodeFile(file, options) { + var _this2 = this; + + return new Promise(function (resolve, reject) { + _this2.volume = new _VolumeTransformer2["default"](options.volume); + + var enc = _child_process2["default"].spawn(_this2.getCommand(), ['-i', file, '-f', 's16le', '-ar', '48000', '-ss', options.seek || 0, '-ac', 2, 'pipe:1']); + + var ffmpegErrors = ""; + + enc.stdout.pipe(_this2.volume); + enc.stderr.on("data", function (data) { + ffmpegErrors += "\n" + new Buffer(data).toString().trim(); + }); + enc.once("exit", function (code, signal) { + if (code) { + reject(new Error("FFMPEG: " + ffmpegErrors)); + } + }); + + _this2.volume.once("readable", function () { + resolve({ + proc: enc, + stream: _this2.volume, + channels: 2 + }); + }); + + _this2.volume.on("end", function () { + reject("end"); + }); + + _this2.volume.on("close", function () { + reject("close"); + }); + }); + }; + + AudioEncoder.prototype.encodeArbitraryFFmpeg = function encodeArbitraryFFmpeg(ffmpegOptions) { + var _this3 = this; + + return new Promise(function (resolve, reject) { + _this3.volume = new _VolumeTransformer2["default"](1); + + // add options discord.js needs + var options = ffmpegOptions.concat(['-f', 's16le', '-ar', '48000', '-ac', 2, 'pipe:1']); + var enc = _child_process2["default"].spawn(_this3.getCommand(), options); + + var ffmpegErrors = ""; + + enc.stdout.pipe(_this3.volume); + enc.stderr.on("data", function (data) { + ffmpegErrors += "\n" + new Buffer(data).toString().trim(); + }); + enc.once("exit", function (code, signal) { + if (code) { + reject(new Error("FFMPEG: " + ffmpegErrors)); + } + }); + + _this3.volume.once("readable", function () { + resolve({ + proc: enc, + stream: _this3.volume, + channels: 2 + }); + }); + + _this3.volume.on("end", function () { + reject("end"); + }); + + _this3.volume.on("close", function () { + reject("close"); + }); + }); + }; + + return AudioEncoder; +})(); + +exports["default"] = AudioEncoder; +module.exports = exports["default"]; diff --git a/lib/Voice/StreamIntent.js b/lib/Voice/StreamIntent.js index 8218edfe1..37b981a14 100644 --- a/lib/Voice/StreamIntent.js +++ b/lib/Voice/StreamIntent.js @@ -1,2 +1,28 @@ -"use strict"; // represents an intent of streaming music -exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _events=require("events");var _events2=_interopRequireDefault(_events);var StreamIntent=(function(_EventEmitter){_inherits(StreamIntent,_EventEmitter);function StreamIntent(){_classCallCheck(this,StreamIntent);_EventEmitter.call(this);}return StreamIntent;})(_events2["default"]);exports["default"] = StreamIntent;module.exports = exports["default"]; +"use strict"; +// represents an intent of streaming music +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _events = require("events"); + +var _events2 = _interopRequireDefault(_events); + +var StreamIntent = (function (_EventEmitter) { + _inherits(StreamIntent, _EventEmitter); + + function StreamIntent() { + _classCallCheck(this, StreamIntent); + + _EventEmitter.call(this); + } + + return StreamIntent; +})(_events2["default"]); + +exports["default"] = StreamIntent; +module.exports = exports["default"]; diff --git a/lib/Voice/VoiceConnection.js b/lib/Voice/VoiceConnection.js index 735fe0747..0d5168acc 100644 --- a/lib/Voice/VoiceConnection.js +++ b/lib/Voice/VoiceConnection.js @@ -1,14 +1,490 @@ -"use strict"; /* +"use strict"; +/* Major credit to izy521 who is the creator of https://github.com/izy521/discord.io, without his help voice chat in discord.js would not have been possible! -*/exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _ws=require("ws");var _ws2=_interopRequireDefault(_ws);var _dns=require("dns");var _dns2=_interopRequireDefault(_dns);var _dgram=require("dgram");var _dgram2=_interopRequireDefault(_dgram);var _AudioEncoder=require("./AudioEncoder");var _AudioEncoder2=_interopRequireDefault(_AudioEncoder);var _VoicePacket=require("./VoicePacket");var _VoicePacket2=_interopRequireDefault(_VoicePacket);var _VolumeTransformer=require("./VolumeTransformer");var _VolumeTransformer2=_interopRequireDefault(_VolumeTransformer);var _StreamIntent=require("./StreamIntent");var _StreamIntent2=_interopRequireDefault(_StreamIntent);var _events=require("events");var _events2=_interopRequireDefault(_events);var _unpipe=require("unpipe");var _unpipe2=_interopRequireDefault(_unpipe);var MODE_xsalsa20_poly1305="xsalsa20_poly1305";var MODE_plain="plain";var VoiceConnection=(function(_EventEmitter){_inherits(VoiceConnection,_EventEmitter);function VoiceConnection(channel,client,session,token,server,endpoint){_classCallCheck(this,VoiceConnection);_EventEmitter.call(this);this.id = channel.id;this.voiceChannel = channel;this.client = client;this.session = session;this.token = token;this.server = server;this.endpoint = endpoint.split(":")[0];this.vWS = null; // vWS means voice websocket -this.ready = false;this.vWSData = {};this.encoder = new _AudioEncoder2["default"]();this.udp = null;this.playingIntent = null;this.playing = false;this.streamTime = 0;this.streamProc = null;this.KAI = null;this.timestamp = 0;this.sequence = 0;this.mode = null;this.secret = null;this.volume = new _VolumeTransformer2["default"]();this.paused = false;this.init();}VoiceConnection.prototype.destroy = function destroy(){this.stopPlaying();if(this.KAI){clearInterval(this.KAI);}this.vWS.close();this.udp.close();this.client.internal.sendWS({op:4,d:{guild_id:this.server.id,channel_id:null,self_mute:true,self_deaf:false}});this.client.internal.voiceConnections.remove(this);};VoiceConnection.prototype.stopPlaying = function stopPlaying(){this.playing = false;this.playingIntent = null;if(this.instream){ //not all streams implement these... -//and even file stream don't seem to implement them properly... -_unpipe2["default"](this.instream);if(this.instream.end){this.instream.end();}if(this.instream.destroy){this.instream.destroy();}this.instream = null;}if(this.streamProc){this.streamProc.stdin.pause();this.streamProc.kill("SIGINT");this.streamProc = null;}};VoiceConnection.prototype.playStream = function playStream(stream){var channels=arguments.length <= 1 || arguments[1] === undefined?2:arguments[1];var self=this,startTime=Date.now(),count=0,length=20,retStream=new _StreamIntent2["default"](),onWarning=false;this.volume = stream;this.playing = true;this.playingIntent = retStream;function send(){if(self.paused){startTime += Date.now() - (startTime + count * length);setTimeout(send,length);return;}if(!self.playingIntent || !self.playing){self.setSpeaking(false);retStream.emit("end");return;}try{var buffer=stream.read(1920 * channels);if(!buffer){if(onWarning){self.setSpeaking(false);retStream.emit("end");return;}else {onWarning = true;setTimeout(send,length * 10); // give chance for some data in 200ms to appear -return;}}if(buffer.length !== 1920 * channels){var newBuffer=new Buffer(1920 * channels).fill(0);buffer.copy(newBuffer);buffer = newBuffer;}count++;self.sequence + 1 < 65535?self.sequence += 1:self.sequence = 0;self.timestamp + 960 < 4294967295?self.timestamp += 960:self.timestamp = 0;self.sendBuffer(buffer,self.sequence,self.timestamp,function(e){});var nextTime=startTime + count * length;self.streamTime = count * length;setTimeout(send,length + (nextTime - Date.now()));if(!self.playing)self.setSpeaking(true);retStream.emit("time",self.streamTime);}catch(e) {retStream.emit("error",e);}}self.setSpeaking(true);send();return retStream;};VoiceConnection.prototype.setSpeaking = function setSpeaking(value){this.playing = value;if(this.vWS.readyState === _ws2["default"].OPEN)this.vWS.send(JSON.stringify({op:5,d:{speaking:value,delay:0}}));};VoiceConnection.prototype.sendPacket = function sendPacket(packet){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;self.playing = true;try{if(self.vWS.readyState === _ws2["default"].OPEN)self.udp.send(packet,0,packet.length,self.vWSData.port,self.endpoint,callback);}catch(e) {self.playing = false;callback(e);return false;}};VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer,sequence,timestamp,callback){var self=this;self.playing = true;try{if(!self.encoder.opus){self.playing = false;throw new Error("node-opus not found! Perhaps you didn't install it.");return;}if(!self.encoder.sanityCheck()){self.playing = false;throw new Error("node-opus sanity check failed! Try re-installing node-opus.");return;}var buffer=self.encoder.opusBuffer(rawbuffer);var packet=new _VoicePacket2["default"](buffer,sequence,timestamp,self.vWSData.ssrc,self.secret);return self.sendPacket(packet,callback);}catch(e) {self.playing = false;self.emit("error",e);return false;}};VoiceConnection.prototype.playFile = function playFile(stream){var _this=this;var options=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,str){}:arguments[2];var self=this;self.stopPlaying();if(typeof options === "function"){ // options is the callback -callback = options;}if(typeof options !== "object"){options = {};}options.volume = options.volume !== undefined?options.volume:this.getVolume();return new Promise(function(resolve,reject){_this.encoder.encodeFile(stream,options)["catch"](error).then(function(data){self.streamProc = data.proc;var intent=self.playStream(data.stream,2);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playRawStream = function playRawStream(stream){var _this2=this;var options=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,str){}:arguments[2];var self=this;self.stopPlaying();if(typeof options === "function"){ // options is the callback -callback = options;}if(typeof options !== "object"){options = {};}options.volume = options.volume !== undefined?options.volume:this.getVolume();return new Promise(function(resolve,reject){_this2.encoder.encodeStream(stream,options)["catch"](error).then(function(data){self.streamProc = data.proc;self.instream = data.instream;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playArbitraryFFmpeg = function playArbitraryFFmpeg(ffmpegOptions){var _this3=this;var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,str){}:arguments[1];var self=this;self.stopPlaying();if(typeof options === "function"){ // options is the callback -callback = options;}if(typeof options !== "object"){options = {};}options.volume = options.volume !== undefined?options.volume:this.getVolume();return new Promise(function(resolve,reject){_this3.encoder.encodeArbitraryFFmpeg(ffmpegOptions)["catch"](error).then(function(data){self.streamProc = data.proc;self.instream = data.instream;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.init = function init(){var _this4=this;var self=this;_dns2["default"].lookup(this.endpoint,function(err,address,family){var vWS=self.vWS = new _ws2["default"]("wss://" + _this4.endpoint,null,{rejectUnauthorized:false});_this4.endpoint = address;var udpClient=self.udp = _dgram2["default"].createSocket("udp4");var firstPacket=true;var discordIP="",discordPort="";udpClient.bind({exclusive:true});udpClient.on('message',function(msg,rinfo){var buffArr=JSON.parse(JSON.stringify(msg)).data;if(firstPacket === true){for(var i=4;i < buffArr.indexOf(0,i);i++) {discordIP += String.fromCharCode(buffArr[i]);}discordPort = msg.readUIntLE(msg.length - 2,2).toString(10);var modes=self.vWSData.modes;var mode=MODE_xsalsa20_poly1305;if(modes.indexOf(MODE_xsalsa20_poly1305) < 0){mode = MODE_plain;self.client.emit("debug","Encrypted mode not reported as supported by the server, using 'plain'");}vWS.send(JSON.stringify({"op":1,"d":{"protocol":"udp","data":{"address":discordIP,"port":Number(discordPort),"mode":mode}}}));firstPacket = false;}});vWS.on("open",function(){vWS.send(JSON.stringify({op:0,d:{server_id:self.server.id,user_id:self.client.internal.user.id,session_id:self.session,token:self.token}}));});var KAI;vWS.on("message",function(msg){var data=JSON.parse(msg);switch(data.op){case 2:self.vWSData = data.d;self.KAI = KAI = self.client.internal.intervals.misc["voiceKAI"] = setInterval(function(){if(vWS && vWS.readyState === _ws2["default"].OPEN)vWS.send(JSON.stringify({op:3,d:null}));},data.d.heartbeat_interval);var udpPacket=new Buffer(70);udpPacket.writeUIntBE(data.d.ssrc,0,4);udpClient.send(udpPacket,0,udpPacket.length,data.d.port,self.endpoint,function(err){if(err)self.emit("error",err);});break;case 4:if(data.d.secret_key && data.d.secret_key.length > 0){var buffer=new ArrayBuffer(data.d.secret_key.length);self.secret = new Uint8Array(buffer);for(var i=0;i < _this4.secret.length;i++) {self.secret[i] = data.d.secret_key[i];}}self.ready = true;self.mode = data.d.mode;self.emit("ready",self);break;}});});};VoiceConnection.prototype.wrapVolume = function wrapVolume(stream){stream.pipe(this.volume);return this.volume;};VoiceConnection.prototype.setVolume = function setVolume(volume){this.volume.set(volume);};VoiceConnection.prototype.getVolume = function getVolume(){return this.volume.get();};VoiceConnection.prototype.mute = function mute(){this.lastVolume = this.volume.get();this.setVolume(0);};VoiceConnection.prototype.unmute = function unmute(){this.setVolume(this.lastVolume);this.lastVolume = undefined;};VoiceConnection.prototype.pause = function pause(){this.paused = true;this.setSpeaking(false);this.playingIntent.emit("pause");};VoiceConnection.prototype.resume = function resume(){this.paused = false;this.setSpeaking(true);this.playingIntent.emit("resume");};return VoiceConnection;})(_events2["default"]);exports["default"] = VoiceConnection;module.exports = exports["default"]; +*/ + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var _ws = require("ws"); + +var _ws2 = _interopRequireDefault(_ws); + +var _dns = require("dns"); + +var _dns2 = _interopRequireDefault(_dns); + +var _dgram = require("dgram"); + +var _dgram2 = _interopRequireDefault(_dgram); + +var _AudioEncoder = require("./AudioEncoder"); + +var _AudioEncoder2 = _interopRequireDefault(_AudioEncoder); + +var _VoicePacket = require("./VoicePacket"); + +var _VoicePacket2 = _interopRequireDefault(_VoicePacket); + +var _VolumeTransformer = require("./VolumeTransformer"); + +var _VolumeTransformer2 = _interopRequireDefault(_VolumeTransformer); + +var _StreamIntent = require("./StreamIntent"); + +var _StreamIntent2 = _interopRequireDefault(_StreamIntent); + +var _events = require("events"); + +var _events2 = _interopRequireDefault(_events); + +var _unpipe = require("unpipe"); + +var _unpipe2 = _interopRequireDefault(_unpipe); + +var MODE_xsalsa20_poly1305 = "xsalsa20_poly1305"; +var MODE_plain = "plain"; + +var VoiceConnection = (function (_EventEmitter) { + _inherits(VoiceConnection, _EventEmitter); + + function VoiceConnection(channel, client, session, token, server, endpoint) { + _classCallCheck(this, VoiceConnection); + + _EventEmitter.call(this); + this.id = channel.id; + this.voiceChannel = channel; + this.client = client; + this.session = session; + this.token = token; + this.server = server; + this.endpoint = endpoint.split(":")[0]; + this.vWS = null; // vWS means voice websocket + this.ready = false; + this.vWSData = {}; + this.encoder = new _AudioEncoder2["default"](); + this.udp = null; + this.playingIntent = null; + this.playing = false; + this.streamTime = 0; + this.streamProc = null; + this.KAI = null; + this.timestamp = 0; + this.sequence = 0; + + this.mode = null; + this.secret = null; + + this.volume = new _VolumeTransformer2["default"](); + this.paused = false; + this.init(); + } + + VoiceConnection.prototype.destroy = function destroy() { + this.stopPlaying(); + if (this.KAI) { + clearInterval(this.KAI); + } + this.vWS.close(); + this.udp.close(); + this.client.internal.sendWS({ + op: 4, + d: { + guild_id: this.server.id, + channel_id: null, + self_mute: true, + self_deaf: false + } + }); + this.client.internal.voiceConnections.remove(this); + }; + + VoiceConnection.prototype.stopPlaying = function stopPlaying() { + this.playing = false; + this.playingIntent = null; + if (this.instream) { + //not all streams implement these... + //and even file stream don't seem to implement them properly... + _unpipe2["default"](this.instream); + if (this.instream.end) { + this.instream.end(); + } + if (this.instream.destroy) { + this.instream.destroy(); + } + this.instream = null; + } + if (this.streamProc) { + this.streamProc.stdin.pause(); + this.streamProc.kill("SIGINT"); + this.streamProc = null; + } + }; + + VoiceConnection.prototype.playStream = function playStream(stream) { + var channels = arguments.length <= 1 || arguments[1] === undefined ? 2 : arguments[1]; + + var self = this, + startTime = Date.now(), + count = 0, + length = 20, + retStream = new _StreamIntent2["default"](), + onWarning = false; + + this.volume = stream; + this.playing = true; + this.playingIntent = retStream; + + function send() { + if (self.paused) { + startTime += Date.now() - (startTime + count * length); + setTimeout(send, length); + return; + } + if (!self.playingIntent || !self.playing) { + self.setSpeaking(false); + retStream.emit("end"); + return; + } + try { + + var buffer = stream.read(1920 * channels); + + if (!buffer) { + if (onWarning) { + self.setSpeaking(false); + retStream.emit("end"); + return; + } else { + onWarning = true; + setTimeout(send, length * 10); // give chance for some data in 200ms to appear + return; + } + } + + if (buffer.length !== 1920 * channels) { + var newBuffer = new Buffer(1920 * channels).fill(0); + buffer.copy(newBuffer); + buffer = newBuffer; + } + + count++; + self.sequence + 1 < 65535 ? self.sequence += 1 : self.sequence = 0; + self.timestamp + 960 < 4294967295 ? self.timestamp += 960 : self.timestamp = 0; + + self.sendBuffer(buffer, self.sequence, self.timestamp, function (e) {}); + + var nextTime = startTime + count * length; + + self.streamTime = count * length; + + setTimeout(send, length + (nextTime - Date.now())); + + if (!self.playing) self.setSpeaking(true); + + retStream.emit("time", self.streamTime); + } catch (e) { + retStream.emit("error", e); + } + } + self.setSpeaking(true); + send(); + + return retStream; + }; + + VoiceConnection.prototype.setSpeaking = function setSpeaking(value) { + this.playing = value; + if (this.vWS.readyState === _ws2["default"].OPEN) this.vWS.send(JSON.stringify({ + op: 5, + d: { + speaking: value, + delay: 0 + } + })); + }; + + VoiceConnection.prototype.sendPacket = function sendPacket(packet) { + var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1]; + + var self = this; + self.playing = true; + try { + if (self.vWS.readyState === _ws2["default"].OPEN) self.udp.send(packet, 0, packet.length, self.vWSData.port, self.endpoint, callback); + } catch (e) { + self.playing = false; + callback(e); + return false; + } + }; + + VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer, sequence, timestamp, callback) { + var self = this; + self.playing = true; + try { + if (!self.encoder.opus) { + self.playing = false; + throw new Error("node-opus not found! Perhaps you didn't install it."); + return; + } + + if (!self.encoder.sanityCheck()) { + self.playing = false; + throw new Error("node-opus sanity check failed! Try re-installing node-opus."); + return; + } + + var buffer = self.encoder.opusBuffer(rawbuffer); + var packet = new _VoicePacket2["default"](buffer, sequence, timestamp, self.vWSData.ssrc, self.secret); + return self.sendPacket(packet, callback); + } catch (e) { + self.playing = false; + self.emit("error", e); + return false; + } + }; + + VoiceConnection.prototype.playFile = function playFile(stream) { + var _this = this; + + var options = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, str) {} : arguments[2]; + + var self = this; + self.stopPlaying(); + if (typeof options === "function") { + // options is the callback + callback = options; + } + if (typeof options !== "object") { + options = {}; + } + options.volume = options.volume !== undefined ? options.volume : this.getVolume(); + return new Promise(function (resolve, reject) { + _this.encoder.encodeFile(stream, options)["catch"](error).then(function (data) { + self.streamProc = data.proc; + var intent = self.playStream(data.stream, 2); + resolve(intent); + callback(null, intent); + }); + function error() { + var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; + + reject(e); + callback(e); + } + }); + }; + + VoiceConnection.prototype.playRawStream = function playRawStream(stream) { + var _this2 = this; + + var options = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; + var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, str) {} : arguments[2]; + + var self = this; + self.stopPlaying(); + if (typeof options === "function") { + // options is the callback + callback = options; + } + if (typeof options !== "object") { + options = {}; + } + options.volume = options.volume !== undefined ? options.volume : this.getVolume(); + return new Promise(function (resolve, reject) { + _this2.encoder.encodeStream(stream, options)["catch"](error).then(function (data) { + self.streamProc = data.proc; + self.instream = data.instream; + var intent = self.playStream(data.stream); + resolve(intent); + callback(null, intent); + }); + function error() { + var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; + + reject(e); + callback(e); + } + }); + }; + + VoiceConnection.prototype.playArbitraryFFmpeg = function playArbitraryFFmpeg(ffmpegOptions) { + var _this3 = this; + + var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, str) {} : arguments[1]; + + var self = this; + self.stopPlaying(); + if (typeof options === "function") { + // options is the callback + callback = options; + } + if (typeof options !== "object") { + options = {}; + } + options.volume = options.volume !== undefined ? options.volume : this.getVolume(); + return new Promise(function (resolve, reject) { + _this3.encoder.encodeArbitraryFFmpeg(ffmpegOptions)["catch"](error).then(function (data) { + self.streamProc = data.proc; + self.instream = data.instream; + var intent = self.playStream(data.stream); + resolve(intent); + callback(null, intent); + }); + function error() { + var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; + + reject(e); + callback(e); + } + }); + }; + + VoiceConnection.prototype.init = function init() { + var _this4 = this; + + var self = this; + _dns2["default"].lookup(this.endpoint, function (err, address, family) { + var vWS = self.vWS = new _ws2["default"]("wss://" + _this4.endpoint, null, { rejectUnauthorized: false }); + _this4.endpoint = address; + var udpClient = self.udp = _dgram2["default"].createSocket("udp4"); + + var firstPacket = true; + + var discordIP = "", + discordPort = ""; + + udpClient.bind({ exclusive: true }); + udpClient.on('message', function (msg, rinfo) { + var buffArr = JSON.parse(JSON.stringify(msg)).data; + if (firstPacket === true) { + for (var i = 4; i < buffArr.indexOf(0, i); i++) { + discordIP += String.fromCharCode(buffArr[i]); + } + discordPort = msg.readUIntLE(msg.length - 2, 2).toString(10); + + var modes = self.vWSData.modes; + var mode = MODE_xsalsa20_poly1305; + if (modes.indexOf(MODE_xsalsa20_poly1305) < 0) { + mode = MODE_plain; + self.client.emit("debug", "Encrypted mode not reported as supported by the server, using 'plain'"); + } + + vWS.send(JSON.stringify({ + "op": 1, + "d": { + "protocol": "udp", + "data": { + "address": discordIP, + "port": Number(discordPort), + "mode": mode + } + } + })); + firstPacket = false; + } + }); + + vWS.on("open", function () { + vWS.send(JSON.stringify({ + op: 0, + d: { + server_id: self.server.id, + user_id: self.client.internal.user.id, + session_id: self.session, + token: self.token + } + })); + }); + + var KAI; + + vWS.on("message", function (msg) { + var data = JSON.parse(msg); + switch (data.op) { + case 2: + self.vWSData = data.d; + + self.KAI = KAI = self.client.internal.intervals.misc["voiceKAI"] = setInterval(function () { + if (vWS && vWS.readyState === _ws2["default"].OPEN) vWS.send(JSON.stringify({ + op: 3, + d: null + })); + }, data.d.heartbeat_interval); + + var udpPacket = new Buffer(70); + udpPacket.writeUIntBE(data.d.ssrc, 0, 4); + udpClient.send(udpPacket, 0, udpPacket.length, data.d.port, self.endpoint, function (err) { + if (err) self.emit("error", err); + }); + break; + case 4: + if (data.d.secret_key && data.d.secret_key.length > 0) { + var buffer = new ArrayBuffer(data.d.secret_key.length); + self.secret = new Uint8Array(buffer); + for (var i = 0; i < _this4.secret.length; i++) { + self.secret[i] = data.d.secret_key[i]; + } + } + + self.ready = true; + self.mode = data.d.mode; + self.emit("ready", self); + + break; + } + }); + }); + }; + + VoiceConnection.prototype.wrapVolume = function wrapVolume(stream) { + stream.pipe(this.volume); + + return this.volume; + }; + + VoiceConnection.prototype.setVolume = function setVolume(volume) { + this.volume.set(volume); + }; + + VoiceConnection.prototype.getVolume = function getVolume() { + return this.volume.get(); + }; + + VoiceConnection.prototype.mute = function mute() { + this.lastVolume = this.volume.get(); + this.setVolume(0); + }; + + VoiceConnection.prototype.unmute = function unmute() { + this.setVolume(this.lastVolume); + this.lastVolume = undefined; + }; + + VoiceConnection.prototype.pause = function pause() { + this.paused = true; + this.setSpeaking(false); + this.playingIntent.emit("pause"); + }; + + VoiceConnection.prototype.resume = function resume() { + this.paused = false; + this.setSpeaking(true); + this.playingIntent.emit("resume"); + }; + + return VoiceConnection; +})(_events2["default"]); + +exports["default"] = VoiceConnection; +module.exports = exports["default"]; diff --git a/lib/Voice/VoicePacket.js b/lib/Voice/VoicePacket.js index f604ad9d4..df10e3c68 100644 --- a/lib/Voice/VoicePacket.js +++ b/lib/Voice/VoicePacket.js @@ -1,3 +1,51 @@ -"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var nacl;try{nacl = require("tweetnacl");}catch(e) { // no tweetnacl! -}var nonce=new Buffer(24);nonce.fill(0);var VoicePacket=function VoicePacket(data,sequence,time,ssrc,secret){_classCallCheck(this,VoicePacket);if(!nacl){throw new Error("tweetnacl not found! Perhaps you didn't install it.");}var mac=secret?16:0;var packetLength=data.length + 12 + mac;var audioBuffer=data;var returnBuffer=new Buffer(packetLength);returnBuffer.fill(0);returnBuffer[0] = 0x80;returnBuffer[1] = 0x78;returnBuffer.writeUIntBE(sequence,2,2);returnBuffer.writeUIntBE(time,4,4);returnBuffer.writeUIntBE(ssrc,8,4);if(secret){ // copy first 12 bytes -returnBuffer.copy(nonce,0,0,12);audioBuffer = nacl.secretbox(data,nonce,secret);}for(var i=0;i < audioBuffer.length;i++) {returnBuffer[i + 12] = audioBuffer[i];}return returnBuffer;};exports["default"] = VoicePacket;module.exports = exports["default"]; +"use strict"; + +exports.__esModule = true; + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var nacl; +try { + nacl = require("tweetnacl"); +} catch (e) { + // no tweetnacl! +} + +var nonce = new Buffer(24); +nonce.fill(0); + +var VoicePacket = function VoicePacket(data, sequence, time, ssrc, secret) { + _classCallCheck(this, VoicePacket); + + if (!nacl) { + throw new Error("tweetnacl not found! Perhaps you didn't install it."); + } + var mac = secret ? 16 : 0; + var packetLength = data.length + 12 + mac; + + var audioBuffer = data; + var returnBuffer = new Buffer(packetLength); + + returnBuffer.fill(0); + returnBuffer[0] = 0x80; + returnBuffer[1] = 0x78; + + returnBuffer.writeUIntBE(sequence, 2, 2); + returnBuffer.writeUIntBE(time, 4, 4); + returnBuffer.writeUIntBE(ssrc, 8, 4); + + if (secret) { + // copy first 12 bytes + returnBuffer.copy(nonce, 0, 0, 12); + audioBuffer = nacl.secretbox(data, nonce, secret); + } + + for (var i = 0; i < audioBuffer.length; i++) { + returnBuffer[i + 12] = audioBuffer[i]; + } + + return returnBuffer; +}; + +exports["default"] = VoicePacket; +module.exports = exports["default"]; diff --git a/lib/Voice/VolumeTransformer.js b/lib/Voice/VolumeTransformer.js index d772fb22c..b0b1f5c48 100644 --- a/lib/Voice/VolumeTransformer.js +++ b/lib/Voice/VolumeTransformer.js @@ -1,13 +1,91 @@ -'use strict';var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if('value' in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}function _inherits(subClass,superClass){if(typeof superClass !== 'function' && superClass !== null){throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Transform=require('stream').Transform; /** +'use strict'; + +var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } + +function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + +var Transform = require('stream').Transform; + +/** * @see https://github.com/reneraab/pcm-volume/blob/master/index.js Inspired by this script - */var Volume=(function(_Transform){_inherits(Volume,_Transform);function Volume(volume){_classCallCheck(this,Volume);_Transform.call(this);this.set(volume);} // Set the volume so that a value of 0.5 is half the perceived volume and -// 2.0 is double the perceived volume. -Volume.prototype.setVolumeLogarithmic = function setVolumeLogarithmic(value){this.volume = Math.pow(value,1.660964);}; // Set the volume to a value specified as decibels. -Volume.prototype.setVolumeDecibels = function setVolumeDecibels(db){this.volume = Math.pow(10,db / 20);};Volume.prototype.get = function get(){return this.volume;};Volume.prototype.set = function set(volume){this.volume = volume === undefined?1:volume;};Volume.prototype._transform = function _transform(buffer,encoding,callback){var out=new Buffer(buffer.length);for(var i=0;i < buffer.length;i += 2) { // Check whether the index is actually in range - sometimes it's possible -// that it skips ahead too far before the end condition of the for can -// kick in. -if(i >= buffer.length - 1){break;} // Read Int16, multiple with multiplier and round down -//console.log(this.volume, this.multiplier, buffer.readInt16LE(i)); -var uint=Math.floor(this.multiplier * buffer.readInt16LE(i)); // Ensure value stays within 16bit -uint = Math.min(32767,uint);uint = Math.max(-32767,uint); // Write 2 new bytes into other buffer; -out.writeInt16LE(uint,i);}this.push(out);callback();};_createClass(Volume,[{key:'volume',get:function get(){return this._volume === undefined?1:this._volume;},set:function set(value){this._volume = value;}},{key:'multiplier',get:function get(){return this.volume;}}]);return Volume;})(Transform);module.exports = Volume; + */ + +var Volume = (function (_Transform) { + _inherits(Volume, _Transform); + + function Volume(volume) { + _classCallCheck(this, Volume); + + _Transform.call(this); + this.set(volume); + } + + // Set the volume so that a value of 0.5 is half the perceived volume and + // 2.0 is double the perceived volume. + + Volume.prototype.setVolumeLogarithmic = function setVolumeLogarithmic(value) { + this.volume = Math.pow(value, 1.660964); + }; + + // Set the volume to a value specified as decibels. + + Volume.prototype.setVolumeDecibels = function setVolumeDecibels(db) { + this.volume = Math.pow(10, db / 20); + }; + + Volume.prototype.get = function get() { + return this.volume; + }; + + Volume.prototype.set = function set(volume) { + this.volume = volume === undefined ? 1 : volume; + }; + + Volume.prototype._transform = function _transform(buffer, encoding, callback) { + var out = new Buffer(buffer.length); + + for (var i = 0; i < buffer.length; i += 2) { + // Check whether the index is actually in range - sometimes it's possible + // that it skips ahead too far before the end condition of the for can + // kick in. + if (i >= buffer.length - 1) { + break; + } + + // Read Int16, multiple with multiplier and round down + //console.log(this.volume, this.multiplier, buffer.readInt16LE(i)); + var uint = Math.floor(this.multiplier * buffer.readInt16LE(i)); + + // Ensure value stays within 16bit + uint = Math.min(32767, uint); + uint = Math.max(-32767, uint); + + // Write 2 new bytes into other buffer; + out.writeInt16LE(uint, i); + } + + this.push(out); + callback(); + }; + + _createClass(Volume, [{ + key: 'volume', + get: function get() { + return this._volume === undefined ? 1 : this._volume; + }, + set: function set(value) { + this._volume = value; + } + }, { + key: 'multiplier', + get: function get() { + return this.volume; + } + }]); + + return Volume; +})(Transform); + +module.exports = Volume; diff --git a/lib/index.js b/lib/index.js index bc003324a..ba2570dce 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,23 +1,114 @@ -"use strict"; /** +"use strict"; + +/** * Object containing user agent data required for API requests. * @typedef {(object)} UserAgent * @property {string} [url=https://github.com/hydrabolt/discord.js] URL to the repository/homepage of the creator. * @property {string} [version=6.0.0] version of your bot. * @property {string} full stringified user-agent that is generate automatically upon changes. Read-only. -*/ /** +*/ + +/** * Object containing properties that can be used to alter the client's functionality. * @typedef {(object)} ClientOptions * @property {boolean} [compress=true] whether or not large packets that are sent over WebSockets should be compressed. * @property {boolean} [revive=false] whether the Client should attempt to automatically reconnect if it is disconnected. * @property {boolean} [rate_limit_as_error=false] whether rejections to API requests due to rate-limiting should be treated as errors. * @property {Number} [large_threshold=250] an integer between 0 and 250. When a server has more users than `options.large_threshold`, only the online/active users are cached. -*/ /** +*/ + +/** * Object containing properties that will be applied when deleting messages * @typedef {(object)} MessageDeletionOptions * @property {Number} [wait] If set, the message will be deleted after `options.wait` milliseconds. - */ /** + */ + +/** * Object containing properties that will be used when fetching channel logs. You cannot specify _both_ `options.before` and `options.after` * @typedef {(object)} ChannelLogsOptions * @property {MessageResolvable} [before] When fetching logs, it will fetch from messages before `options.before` but not including it. * @property {MessageResolvable} [after] When fetching logs, it will fetch from messages after `options.after` but not including it. - */exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}var _ClientClient=require("./Client/Client");var _ClientClient2=_interopRequireDefault(_ClientClient);var _StructuresChannel=require("./Structures/Channel");var _StructuresChannel2=_interopRequireDefault(_StructuresChannel);var _StructuresChannelPermissions=require("./Structures/ChannelPermissions");var _StructuresChannelPermissions2=_interopRequireDefault(_StructuresChannelPermissions);var _StructuresInvite=require("./Structures/Invite");var _StructuresInvite2=_interopRequireDefault(_StructuresInvite);var _StructuresMessage=require("./Structures/Message");var _StructuresMessage2=_interopRequireDefault(_StructuresMessage);var _StructuresPermissionOverwrite=require("./Structures/PermissionOverwrite");var _StructuresPermissionOverwrite2=_interopRequireDefault(_StructuresPermissionOverwrite);var _StructuresPMChannel=require("./Structures/PMChannel");var _StructuresPMChannel2=_interopRequireDefault(_StructuresPMChannel);var _StructuresRole=require("./Structures/Role");var _StructuresRole2=_interopRequireDefault(_StructuresRole);var _StructuresServer=require("./Structures/Server");var _StructuresServer2=_interopRequireDefault(_StructuresServer);var _StructuresServerChannel=require("./Structures/ServerChannel");var _StructuresServerChannel2=_interopRequireDefault(_StructuresServerChannel);var _StructuresTextChannel=require("./Structures/TextChannel");var _StructuresTextChannel2=_interopRequireDefault(_StructuresTextChannel);var _StructuresUser=require("./Structures/User");var _StructuresUser2=_interopRequireDefault(_StructuresUser);var _StructuresVoiceChannel=require("./Structures/VoiceChannel");var _StructuresVoiceChannel2=_interopRequireDefault(_StructuresVoiceChannel);var _Constants=require("./Constants");var _Constants2=_interopRequireDefault(_Constants);var _UtilCacheJs=require("./Util/Cache.js");var _UtilCacheJs2=_interopRequireDefault(_UtilCacheJs);exports["default"] = {Client:_ClientClient2["default"],Channel:_StructuresChannel2["default"],ChannelPermissions:_StructuresChannelPermissions2["default"],Invite:_StructuresInvite2["default"],Message:_StructuresMessage2["default"],PermissionOverwrite:_StructuresPermissionOverwrite2["default"],PMChannel:_StructuresPMChannel2["default"],Role:_StructuresRole2["default"],Server:_StructuresServer2["default"],ServerChannel:_StructuresServerChannel2["default"],TextChannel:_StructuresTextChannel2["default"],User:_StructuresUser2["default"],VoiceChannel:_StructuresVoiceChannel2["default"],Constants:_Constants2["default"],Cache:_UtilCacheJs2["default"]};module.exports = exports["default"]; + */ + +exports.__esModule = true; + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + +var _ClientClient = require("./Client/Client"); + +var _ClientClient2 = _interopRequireDefault(_ClientClient); + +var _StructuresChannel = require("./Structures/Channel"); + +var _StructuresChannel2 = _interopRequireDefault(_StructuresChannel); + +var _StructuresChannelPermissions = require("./Structures/ChannelPermissions"); + +var _StructuresChannelPermissions2 = _interopRequireDefault(_StructuresChannelPermissions); + +var _StructuresInvite = require("./Structures/Invite"); + +var _StructuresInvite2 = _interopRequireDefault(_StructuresInvite); + +var _StructuresMessage = require("./Structures/Message"); + +var _StructuresMessage2 = _interopRequireDefault(_StructuresMessage); + +var _StructuresPermissionOverwrite = require("./Structures/PermissionOverwrite"); + +var _StructuresPermissionOverwrite2 = _interopRequireDefault(_StructuresPermissionOverwrite); + +var _StructuresPMChannel = require("./Structures/PMChannel"); + +var _StructuresPMChannel2 = _interopRequireDefault(_StructuresPMChannel); + +var _StructuresRole = require("./Structures/Role"); + +var _StructuresRole2 = _interopRequireDefault(_StructuresRole); + +var _StructuresServer = require("./Structures/Server"); + +var _StructuresServer2 = _interopRequireDefault(_StructuresServer); + +var _StructuresServerChannel = require("./Structures/ServerChannel"); + +var _StructuresServerChannel2 = _interopRequireDefault(_StructuresServerChannel); + +var _StructuresTextChannel = require("./Structures/TextChannel"); + +var _StructuresTextChannel2 = _interopRequireDefault(_StructuresTextChannel); + +var _StructuresUser = require("./Structures/User"); + +var _StructuresUser2 = _interopRequireDefault(_StructuresUser); + +var _StructuresVoiceChannel = require("./Structures/VoiceChannel"); + +var _StructuresVoiceChannel2 = _interopRequireDefault(_StructuresVoiceChannel); + +var _Constants = require("./Constants"); + +var _Constants2 = _interopRequireDefault(_Constants); + +var _UtilCacheJs = require("./Util/Cache.js"); + +var _UtilCacheJs2 = _interopRequireDefault(_UtilCacheJs); + +exports["default"] = { + Client: _ClientClient2["default"], + Channel: _StructuresChannel2["default"], + ChannelPermissions: _StructuresChannelPermissions2["default"], + Invite: _StructuresInvite2["default"], + Message: _StructuresMessage2["default"], + PermissionOverwrite: _StructuresPermissionOverwrite2["default"], + PMChannel: _StructuresPMChannel2["default"], + Role: _StructuresRole2["default"], + Server: _StructuresServer2["default"], + ServerChannel: _StructuresServerChannel2["default"], + TextChannel: _StructuresTextChannel2["default"], + User: _StructuresUser2["default"], + VoiceChannel: _StructuresVoiceChannel2["default"], + Constants: _Constants2["default"], + Cache: _UtilCacheJs2["default"] +}; +module.exports = exports["default"]; diff --git a/src/Structures/ServerChannel.js b/src/Structures/ServerChannel.js index cf340a0af..eadde0612 100644 --- a/src/Structures/ServerChannel.js +++ b/src/Structures/ServerChannel.js @@ -27,10 +27,10 @@ export default class ServerChannel extends Channel{ if (this.server.ownerID === user.id) { return new ChannelPermissions(4294967295); } - var everyoneRole = this.server.roles.get("name", "@everyone"); + var everyoneRole = this.server.roles.get("id", this.server.id); var userRoles = [everyoneRole].concat(this.server.rolesOf(user) || []); - var userRolesID = userRoles.map((v) => v.id); + var userRolesID = userRoles.filter((v) => !!v).map((v) => v.id); var roleOverwrites = [], memberOverwrites = []; this.permissionOverwrites.forEach((overwrite) => {