| 1 | "use strict"; |
| 2 | (function discordio(Discord){ |
| 3 | var isNode = typeof(window) === "undefined" && typeof(navigator) === "undefined"; |
| 4 | var CURRENT_VERSION = "2.x.x", |
| 5 | GATEWAY_VERSION = 6, |
| 6 | LARGE_THRESHOLD = 250, |
| 7 | CONNECT_WHEN = null, |
| 8 | Endpoints, Payloads; |
| 9 | |
| 10 | if (isNode) { |
| 11 | var Util = require('util'), |
| 12 | FS = require('fs'), |
| 13 | UDP = require('dgram'), |
| 14 | Zlib = require('zlib'), |
| 15 | DNS = require('dns'), |
| 16 | Stream = require('stream'), |
| 17 | BN = require('path').basename, |
| 18 | EE = require('events').EventEmitter, |
| 19 | requesters = { |
| 20 | http: require('http'), |
| 21 | https: require('https') |
| 22 | }, |
| 23 | ChildProc = require('child_process'), |
| 24 | URL = require('url'), |
| 25 | //NPM Modules |
| 26 | NACL = require('tweetnacl'), |
| 27 | Opus = null; |
| 28 | } |
| 29 | |
| 30 | /* --- Version Check --- */ |
| 31 | try { |
| 32 | CURRENT_VERSION = require('../package.json').version; |
| 33 | } catch(e) {} |
| 34 | if (!isNode) CURRENT_VERSION = CURRENT_VERSION + "-browser"; |
| 35 | |
| 36 | /** |
| 37 | * Discord Client constructor |
| 38 | * @class |
| 39 | * @arg {Object} options |
| 40 | * @arg {String} options.token - The token of the account you wish to log in with. |
| 41 | * @arg {Boolean} [options.autorun] - If true, the client runs when constructed without calling `.connect()`. |
| 42 | * @arg {Number} [options.messageCacheLimit] - The amount of messages to cache in memory, per channel. Used for information on deleted/updated messages. The default is 50. |
| 43 | * @arg {Array<Number>} [options.shard] - The shard array. The first index is the current shard ID, the second is the amount of shards that should be running. |
| 44 | */ |
| 45 | Discord.Client = function DiscordClient(options) { |
| 46 | if (!isNode) Emitter.call(this); |
| 47 | if (!options || options.constructor.name !== 'Object') return console.error("An Object is required to create the discord.io client."); |
| 48 | |
| 49 | applyProperties(this, [ |
| 50 | ["_ws", null], |
| 51 | ["_uIDToDM", {}], |
| 52 | ["_ready", false], |
| 53 | ["_vChannels", {}], |
| 54 | ["_messageCache", {}], |
| 55 | ["_connecting", false], |
| 56 | ["_mainKeepAlive", null], |
| 57 | ["_req", APIRequest.bind(this)], |
| 58 | ["_shard", validateShard(options.shard)], |
| 59 | ["_messageCacheLimit", typeof(options.messageCacheLimit) === 'number' ? options.messageCacheLimit : 50], |
| 60 | ]); |
| 61 | |
| 62 | this.connected = false; |
| 63 | this.inviteURL = null; |
| 64 | this.connect = this.connect.bind(this, options); |
| 65 | |
| 66 | if (options.autorun === true) this.connect(); |
| 67 | }; |
| 68 | if (isNode) Emitter.call(Discord.Client); |
| 69 | |
| 70 | /* - DiscordClient - Methods - */ |
| 71 | var DCP = Discord.Client.prototype; |
| 72 | /** |
| 73 | * Manually initiate the WebSocket connection to Discord. |
| 74 | */ |
| 75 | DCP.connect = function () { |
| 76 | var opts = arguments[0]; |
| 77 | if (!this.connected && !this._connecting) return setTimeout(function() { |
| 78 | init(this, opts); |
| 79 | CONNECT_WHEN = Math.max(CONNECT_WHEN, Date.now()) + 6000; |
| 80 | }.bind(this), Math.max( 0, CONNECT_WHEN - Date.now() )); |
| 81 | }; |
| 82 | |
| 83 | /** |
| 84 | * Disconnect the WebSocket connection to Discord. |
| 85 | */ |
| 86 | DCP.disconnect = function () { |
| 87 | if (this._ws) return this._ws.close(1000, "Manual disconnect"), log(this, "Manual disconnect called, websocket closed"); |
| 88 | return log(this, Discord.LogLevels.Warn, "Manual disconnect called with no WebSocket active, ignored"); |
| 89 | }; |
| 90 | |
| 91 | /** |
| 92 | * Retrieve a user object from Discord, Bot only endpoint. You don't have to share a server with this user. |
| 93 | * @arg {Object} input |
| 94 | * @arg {Snowflake} input.userID |
| 95 | */ |
| 96 | DCP.getUser = function(input, callback) { |
| 97 | if (!this.bot) return handleErrCB("[getUser] This account is a 'user' type account, and cannot use 'getUser'. Only bots can use this endpoint.", callback); |
| 98 | this._req('get', Endpoints.USER(input.userID), function(err, res) { |
| 99 | handleResCB("Could not get user", err, res, callback); |
| 100 | }); |
| 101 | }; |
| 102 | |
| 103 | /** |
| 104 | * Edit the client's user information. |
| 105 | * @arg {Object} input |
| 106 | * @arg {String<Base64>} input.avatar - The last part of a Base64 Data URI. `fs.readFileSync('image.jpg', 'base64')` is enough. |
| 107 | * @arg {String} input.username - A username. |
| 108 | * @arg {String} input.email - [User only] An email. |
| 109 | * @arg {String} input.password - [User only] Your current password. |
| 110 | * @arg {String} input.new_password - [User only] A new password. |
| 111 | */ |
| 112 | DCP.editUserInfo = function(input, callback) { |
| 113 | var payload = { |
| 114 | avatar: this.avatar, |
| 115 | email: this.email, |
| 116 | new_password: null, |
| 117 | password: null, |
| 118 | username: this.username |
| 119 | }, |
| 120 | plArr = Object.keys(payload); |
| 121 | |
| 122 | for (var key in input) { |
| 123 | if (plArr.indexOf(key) < 0) return handleErrCB(("[editUserInfo] '" + key + "' is not a valid key. Valid keys are: " + plArr.join(", ")), callback); |
| 124 | payload[key] = input[key]; |
| 125 | } |
| 126 | if (input.avatar) payload.avatar = "data:image/jpg;base64," + input.avatar; |
| 127 | |
| 128 | this._req('patch', Endpoints.ME, payload, function(err, res) { |
| 129 | handleResCB("Unable to edit user information", err, res, callback); |
| 130 | }); |
| 131 | }; |
| 132 | |
| 133 | /** |
| 134 | * Change the client's presence. |
| 135 | * @arg {Object} input |
| 136 | * @arg {String|null} input.status - Used to set the status. online, idle, dnd, invisible, and offline are the possible states. |
| 137 | * @arg {Number|null} input.since - Optional, use a Number before the current point in time. |
| 138 | * @arg {Boolean|null} input.afk - Optional, changes how Discord handles push notifications. |
| 139 | * @arg {Object|null} input.game - Used to set game information. |
| 140 | * @arg {String|null} input.game.name - The name of the game. |
| 141 | * @arg {Number|null} input.game.type - Activity type, 0 for game, 1 for Twitch. |
| 142 | * @arg {String|null} input.game.url - A URL matching the streaming service you've selected. |
| 143 | */ |
| 144 | DCP.setPresence = function(input) { |
| 145 | var payload = Payloads.STATUS(input); |
| 146 | send(this._ws, payload); |
| 147 | |
| 148 | this.presence = payload.d; |
| 149 | }; |
| 150 | |
| 151 | /** |
| 152 | * Receive OAuth information for the current client. |
| 153 | */ |
| 154 | DCP.getOauthInfo = function(callback) { |
| 155 | this._req('get', Endpoints.OAUTH, function(err, res) { |
| 156 | handleResCB("Error GETing OAuth information", err, res, callback); |
| 157 | }); |
| 158 | }; |
| 159 | |
| 160 | /** |
| 161 | * Receive account settings information for the current client. |
| 162 | */ |
| 163 | DCP.getAccountSettings = function(callback) { |
| 164 | this._req('get', Endpoints.SETTINGS, function(err, res) { |
| 165 | handleResCB("Error GETing client settings", err, res, callback); |
| 166 | }); |
| 167 | }; |
| 168 | |
| 169 | /* - DiscordClient - Methods - Content - */ |
| 170 | |
| 171 | /** |
| 172 | * Upload a file to a channel. |
| 173 | * @arg {Object} input |
| 174 | * @arg {Snowflake} input.to - The target Channel or User ID. |
| 175 | * @arg {Buffer|String} input.file - A Buffer containing the file data, or a String that's a path to the file. |
| 176 | * @arg {String|null} input.filename - A filename for the uploaded file, required if you provide a Buffer. |
| 177 | * @arg {String|null} input.message - An optional message to provide. |
| 178 | */ |
| 179 | DCP.uploadFile = function(input, callback) { |
| 180 | /* After like 15 minutes of fighting with Request, turns out Discord doesn't allow multiple files in one message... |
| 181 | despite having an attachments array.*/ |
| 182 | var file, client, multi, message, isBuffer, isString; |
| 183 | |
| 184 | client = this; |
| 185 | multi = new Multipart(); |
| 186 | message = generateMessage(input.message || ""); |
| 187 | isBuffer = (input.file instanceof Buffer); |
| 188 | isString = (type(input.file) === 'string'); |
| 189 | |
| 190 | if (!isBuffer && !isString) return handleErrCB("uploadFile requires a String or Buffer as the 'file' value", callback); |
| 191 | if (isBuffer) { |
| 192 | if (!input.filename) return handleErrCB("uploadFile requires a 'filename' value to be set if using a Buffer", callback); |
| 193 | file = input.file; |
| 194 | } |
| 195 | if (isString) try { file = FS.readFileSync(input.file); } catch(e) { return handleErrCB("File does not exist: " + input.file, callback); } |
| 196 | |
| 197 | [ |
| 198 | ["content", message.content], |
| 199 | ["mentions", ""], |
| 200 | ["tts", false], |
| 201 | ["nonce", message.nonce], |
| 202 | ["file", file, input.filename || BN(input.file)] |
| 203 | ].forEach(multi.append, multi); |
| 204 | multi.finalize(); |
| 205 | |
| 206 | resolveID(client, input.to, function(channelID) { |
| 207 | client._req('post', Endpoints.MESSAGES(channelID), multi, function(err, res) { |
| 208 | handleResCB("Unable to upload file", err, res, callback); |
| 209 | }); |
| 210 | }); |
| 211 | }; |
| 212 | |
| 213 | /** |
| 214 | * Send a message to a channel. |
| 215 | * @arg {Object} input |
| 216 | * @arg {Snowflake} input.to - The target Channel or User ID. |
| 217 | * @arg {String} input.message - The message content. |
| 218 | * @arg {Object} [input.embed] - An embed object to include |
| 219 | * @arg {Boolean} [input.tts] - Enable Text-to-Speech for this message. |
| 220 | * @arg {Number} [input.nonce] - Number-used-only-ONCE. The Discord client uses this to change the message color from grey to white. |
| 221 | * @arg {Boolean} [input.typing] - Indicates whether the message should be sent with simulated typing. Based on message length. |
| 222 | */ |
| 223 | DCP.sendMessage = function(input, callback) { |
| 224 | var message = generateMessage(input.message || '', input.embed); |
| 225 | message.tts = (input.tts === true); |
| 226 | message.nonce = input.nonce || message.nonce; |
| 227 | |
| 228 | if (input.typing === true) { |
| 229 | return simulateTyping( |
| 230 | this, |
| 231 | input.to, |
| 232 | message, |
| 233 | ( (message.content.length * 0.12) * 1000 ), |
| 234 | callback |
| 235 | ); |
| 236 | } |
| 237 | |
| 238 | sendMessage(this, input.to, message, callback); |
| 239 | }; |
| 240 | |
| 241 | /** |
| 242 | * Pull a message object from Discord. |
| 243 | * @arg {Object} input |
| 244 | * @arg {Snowflake} input.channelID - The channel ID that the message is from. |
| 245 | * @arg {Snowflake} input.messageID - The ID of the message. |
| 246 | */ |
| 247 | DCP.getMessage = function(input, callback) { |
| 248 | this._req('get', Endpoints.MESSAGES(input.channelID, input.messageID), function(err, res) { |
| 249 | handleResCB("Unable to get message", err, res, callback); |
| 250 | }); |
| 251 | }; |
| 252 | |
| 253 | /** |
| 254 | * Pull an array of message objects from Discord. |
| 255 | * @arg {Object} input |
| 256 | * @arg {Snowflake} input.channelID - The channel ID to pull the messages from. |
| 257 | * @arg {Number} [input.limit] - How many messages to pull, defaults to 50. |
| 258 | * @arg {Snowflake} [input.before] - Pull messages before this message ID. |
| 259 | * @arg {Snowflake} [input.after] - Pull messages after this message ID. |
| 260 | */ |
| 261 | DCP.getMessages = function(input, callback) { |
| 262 | var client = this, qs = {}, messages = [], lastMessageID = ""; |
| 263 | var total = typeof(input.limit) !== 'number' ? 50 : input.limit; |
| 264 | |
| 265 | if (input.before) qs.before = input.before; |
| 266 | if (input.after) qs.after = input.after; |
| 267 | |
| 268 | (function getMessages() { |
| 269 | if (total > 100) { |
| 270 | qs.limit = 100; |
| 271 | total = total - 100; |
| 272 | } else { |
| 273 | qs.limit = total; |
| 274 | } |
| 275 | |
| 276 | if (messages.length >= input.limit) return call(callback, [null, messages]); |
| 277 | |
| 278 | client._req('get', Endpoints.MESSAGES(input.channelID) + qstringify(qs), function(err, res) { |
| 279 | if (err) return handleErrCB("Unable to get messages", callback); |
| 280 | messages = messages.concat(res.body); |
| 281 | lastMessageID = messages[messages.length - 1] && messages[messages.length - 1].id; |
| 282 | if (lastMessageID) qs.before = lastMessageID; |
| 283 | if (!res.body.length < qs.limit) return call(callback, [null, messages]); |
| 284 | return setTimeout(getMessages, 1000); |
| 285 | }); |
| 286 | })(); |
| 287 | }; |
| 288 | |
| 289 | /** |
| 290 | * Edit a previously sent message. |
| 291 | * @arg {Object} input |
| 292 | * @arg {Snowflake} input.channelID |
| 293 | * @arg {Snowflake} input.messageID |
| 294 | * @arg {String} input.message - The new message content |
| 295 | * @arg {Object} [input.embed] - The new Discord Embed object |
| 296 | */ |
| 297 | DCP.editMessage = function(input, callback) { |
| 298 | this._req('patch', Endpoints.MESSAGES(input.channelID, input.messageID), generateMessage(input.message || '', input.embed), function(err, res) { |
| 299 | handleResCB("Unable to edit message", err, res, callback); |
| 300 | }); |
| 301 | }; |
| 302 | |
| 303 | /** |
| 304 | * Delete a posted message. |
| 305 | * @arg {Object} input |
| 306 | * @arg {Snowflake} input.channelID |
| 307 | * @arg {Snowflake} input.messageID |
| 308 | */ |
| 309 | DCP.deleteMessage = function(input, callback) { |
| 310 | this._req('delete', Endpoints.MESSAGES(input.channelID, input.messageID), function(err, res) { |
| 311 | handleResCB("Unable to delete message", err, res, callback); |
| 312 | }); |
| 313 | }; |
| 314 | |
| 315 | /** |
| 316 | * Delete a batch of messages. |
| 317 | * @arg {Object} input |
| 318 | * @arg {Snowflake} input.channelID |
| 319 | * @arg {Array<Snowflake>} input.messageIDs - An Array of message IDs, with a maximum of 100 indexes. |
| 320 | */ |
| 321 | DCP.deleteMessages = function(input, callback) { |
| 322 | this._req('post', Endpoints.BULK_DELETE(input.channelID), {messages: input.messageIDs.slice(0, 100)}, function(err, res) { |
| 323 | handleResCB("Unable to delete messages", err, res, callback); |
| 324 | }); |
| 325 | }; |
| 326 | |
| 327 | /** |
| 328 | * Pin a message to the channel. |
| 329 | * @arg {Object} input |
| 330 | * @arg {Snowflake} input.channelID |
| 331 | * @arg {Snowflake} input.messageID |
| 332 | */ |
| 333 | DCP.pinMessage = function(input, callback) { |
| 334 | this._req('put', Endpoints.PINNED_MESSAGES(input.channelID, input.messageID), function(err, res) { |
| 335 | handleResCB("Unable to pin message", err, res, callback); |
| 336 | }); |
| 337 | }; |
| 338 | |
| 339 | /** |
| 340 | * Get an array of pinned messages from a channel. |
| 341 | * @arg {Object} input |
| 342 | * @arg {Snowflake} input.channelID |
| 343 | */ |
| 344 | DCP.getPinnedMessages = function(input, callback) { |
| 345 | this._req('get', Endpoints.PINNED_MESSAGES(input.channelID), function(err, res) { |
| 346 | handleResCB("Unable to get pinned messages", err, res, callback); |
| 347 | }); |
| 348 | }; |
| 349 | |
| 350 | /** |
| 351 | * Delete a pinned message from a channel. |
| 352 | * @arg {Object} input |
| 353 | * @arg {Snowflake} input.channelID |
| 354 | * @arg {Snowflake} input.messageID |
| 355 | */ |
| 356 | DCP.deletePinnedMessage = function(input, callback) { |
| 357 | this._req('delete', Endpoints.PINNED_MESSAGES(input.channelID, input.messageID), function(err, res) { |
| 358 | handleResCB("Unable to delete pinned message", err, res, callback); |
| 359 | }); |
| 360 | }; |
| 361 | |
| 362 | /** |
| 363 | * Send 'typing...' status to a channel |
| 364 | * @arg {Snowflake} channelID |
| 365 | */ |
| 366 | DCP.simulateTyping = function(channelID, callback) { |
| 367 | this._req('post', Endpoints.TYPING(channelID), function(err, res) { |
| 368 | handleResCB("Unable to simulate typing", err, res, callback); |
| 369 | }); |
| 370 | }; |
| 371 | |
| 372 | /** |
| 373 | * Replace Snowflakes with the names if applicable. |
| 374 | * @arg {String} message - The message to fix. |
| 375 | * @arg {Snowflake|null} serverID - Optional, the ID of the message's server of origin, used for nickname lookup |
| 376 | */ |
| 377 | DCP.fixMessage = function(message, serverID) { |
| 378 | var client = this; |
| 379 | return message.replace(/<@&(\d*)>|<@!(\d*)>|<@(\d*)>|<#(\d*)>/g, function(match, RID, NID, UID, CID) { |
| 380 | var k, i; |
| 381 | if (UID || CID) { |
| 382 | if (client.users[UID]) return "@" + client.users[UID].username; |
| 383 | if (client.channels[CID]) return "#" + client.channels[CID].name; |
| 384 | } |
| 385 | if (RID || NID) { |
| 386 | if (NID && client.servers[serverID]) return "@" + client.servers[serverID].members[NID].nick; |
| 387 | k = Object.keys(client.servers); |
| 388 | for (i=0; i<k.length; i++) { |
| 389 | if (client.servers[k[i]].roles[RID]) return "@" + client.servers[k[i]].roles[RID].name; |
| 390 | if (client.servers[k[i]].members[NID] && client.servers[k[i]].members[NID].nick) return "@" + client.servers[k[i]].members[NID].nick; |
| 391 | } |
| 392 | } |
| 393 | }); |
| 394 | }; |
| 395 | |
| 396 | /** |
| 397 | * Add an emoji reaction to a message. |
| 398 | * @arg {Object} input |
| 399 | * @arg {Snowflake} input.channelID |
| 400 | * @arg {Snowflake} input.messageID |
| 401 | * @arg {String} input.reaction - Either the emoji unicode or the emoji name:id/object. |
| 402 | */ |
| 403 | DCP.addReaction = function(input, callback) { |
| 404 | var client = this; |
| 405 | resolveID(client, input.channelID, function(channelID) { |
| 406 | client._req('put', Endpoints.USER_REACTIONS(channelID, input.messageID, stringifyEmoji(input.reaction)), function(err, res) { |
| 407 | handleResCB("Unable to add reaction", err, res, callback); |
| 408 | }); |
| 409 | }); |
| 410 | }; |
| 411 | |
| 412 | /** |
| 413 | * Get an emoji reaction of a message. |
| 414 | * @arg {Object} input |
| 415 | * @arg {Snowflake} input.channelID |
| 416 | * @arg {Snowflake} input.messageID |
| 417 | * @arg {String} input.reaction - Either the emoji unicode or the emoji name:id/object. |
| 418 | * @arg {String} [input.limit] |
| 419 | */ |
| 420 | DCP.getReaction = function(input, callback) { |
| 421 | var qs = { limit: (typeof(input.limit) !== 'number' ? 100 : input.limit) }; |
| 422 | var client = this; |
| 423 | resolveID(client, input.channelID, function(channelID) { |
| 424 | client._req('get', Endpoints.MESSAGE_REACTIONS(channelID, input.messageID, stringifyEmoji(input.reaction)) + qstringify(qs), function(err, res) { |
| 425 | handleResCB("Unable to get reaction", err, res, callback); |
| 426 | }); |
| 427 | }); |
| 428 | }; |
| 429 | |
| 430 | /** |
| 431 | * Remove an emoji reaction from a message. |
| 432 | * @arg {Object} input |
| 433 | * @arg {Snowflake} input.channelID |
| 434 | * @arg {Snowflake} input.messageID |
| 435 | * @arg {Snowflake} [input.userID] |
| 436 | * @arg {String} input.reaction - Either the emoji unicode or the emoji name:id/object. |
| 437 | */ |
| 438 | DCP.removeReaction = function(input, callback) { |
| 439 | var client = this; |
| 440 | resolveID(client, input.channelID, function(channelID) { |
| 441 | client._req('delete', Endpoints.USER_REACTIONS(channelID, input.messageID, stringifyEmoji(input.reaction), input.userID), function(err, res) { |
| 442 | handleResCB("Unable to remove reaction", err, res, callback); |
| 443 | }); |
| 444 | }); |
| 445 | }; |
| 446 | |
| 447 | /** |
| 448 | * Remove all emoji reactions from a message. |
| 449 | * @arg {Object} input |
| 450 | * @arg {Snowflake} input.channelID |
| 451 | * @arg {Snowflake} input.messageID |
| 452 | */ |
| 453 | DCP.removeAllReactions = function(input, callback) { |
| 454 | var client = this; |
| 455 | resolveID(client, input.channelID, function(channelID) { |
| 456 | client._req('delete', Endpoints.MESSAGE_REACTIONS(channelID, input.messageID), function(err, res) { |
| 457 | handleResCB("Unable to remove reactions", err, res, callback); |
| 458 | }); |
| 459 | }); |
| 460 | }; |
| 461 | |
| 462 | /* - DiscordClient - Methods - Server Management - */ |
| 463 | |
| 464 | /** |
| 465 | * Remove a user from a server. |
| 466 | * @arg {Object} input |
| 467 | * @arg {Snowflake} input.serverID |
| 468 | * @arg {Snowflake} input.userID |
| 469 | */ |
| 470 | DCP.kick = function(input, callback) { |
| 471 | this._req('delete', Endpoints.MEMBERS(input.serverID, input.userID), function(err, res) { |
| 472 | handleResCB("Could not kick user", err, res, callback); |
| 473 | }); |
| 474 | }; |
| 475 | |
| 476 | /** |
| 477 | * Remove and ban a user from a server. |
| 478 | * @arg {Object} input |
| 479 | * @arg {Snowflake} input.serverID |
| 480 | * @arg {Snowflake} input.userID |
| 481 | * @arg {String} input.reason |
| 482 | * @arg {Number} [input.lastDays] - Removes their messages up until this point, either 1 or 7 days. |
| 483 | */ |
| 484 | DCP.ban = function(input, callback) { |
| 485 | var url = Endpoints.BANS(input.serverID, input.userID); |
| 486 | var opts = {}; |
| 487 | |
| 488 | if (input.lastDays) { |
| 489 | input.lastDays = Number(input.lastDays); |
| 490 | input.lastDays = Math.min(input.lastDays, 7); |
| 491 | input.lastDays = Math.max(input.lastDays, 1); |
| 492 | opts["delete-message-days"] = input.lastDays; |
| 493 | } |
| 494 | |
| 495 | if (input.reason) opts.reason = input.reason; |
| 496 | |
| 497 | url += qstringify(opts); |
| 498 | |
| 499 | this._req('put', url, function(err, res) { |
| 500 | handleResCB("Could not ban user", err, res, callback); |
| 501 | }); |
| 502 | } |
| 503 | |
| 504 | /** |
| 505 | * Unban a user from a server. |
| 506 | * @arg {Object} input |
| 507 | * @arg {Snowflake} input.serverID |
| 508 | * @arg {Snowflake} input.userID |
| 509 | */ |
| 510 | DCP.unban = function(input, callback) { |
| 511 | this._req('delete', Endpoints.BANS(input.serverID, input.userID), function(err, res) { |
| 512 | handleResCB("Could not unban user", err, res, callback); |
| 513 | }); |
| 514 | }; |
| 515 | |
| 516 | /** |
| 517 | * Move a user between voice channels. |
| 518 | * @arg {Object} input |
| 519 | * @arg {Snowflake} input.serverID |
| 520 | * @arg {Snowflake} input.userID |
| 521 | * @arg {Snowflake} input.channelID |
| 522 | */ |
| 523 | DCP.moveUserTo = function(input, callback) { |
| 524 | this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {channel_id: input.channelID}, function(err, res) { |
| 525 | handleResCB("Could not move the user", err, res, callback); |
| 526 | }); |
| 527 | }; |
| 528 | |
| 529 | /** |
| 530 | * Server-mute the user from speaking in all voice channels. |
| 531 | * @arg {Object} input |
| 532 | * @arg {Snowflake} input.serverID |
| 533 | * @arg {Snowflake} input.userID |
| 534 | */ |
| 535 | DCP.mute = function(input, callback) { |
| 536 | this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {mute: true}, function(err, res) { |
| 537 | handleResCB("Could not mute user", err, res, callback); |
| 538 | }); |
| 539 | }; |
| 540 | |
| 541 | /** |
| 542 | * Remove the server-mute from a user. |
| 543 | * @arg {Object} input |
| 544 | * @arg {Snowflake} input.serverID |
| 545 | * @arg {Snowflake} input.userID |
| 546 | */ |
| 547 | DCP.unmute = function(input, callback) { |
| 548 | this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {mute: false}, function(err, res) { |
| 549 | handleResCB("Could not unmute user", err, res, callback); |
| 550 | }); |
| 551 | }; |
| 552 | |
| 553 | /** |
| 554 | * Server-deafen a user. |
| 555 | * @arg {Object} input |
| 556 | * @arg {Snowflake} input.serverID |
| 557 | * @arg {Snowflake} input.userID |
| 558 | */ |
| 559 | DCP.deafen = function(input, callback) { |
| 560 | this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {deaf: true}, function(err, res) { |
| 561 | handleResCB("Could not deafen user", err, res, callback); |
| 562 | }); |
| 563 | }; |
| 564 | |
| 565 | /** |
| 566 | * Remove the server-deafen from a user. |
| 567 | * @arg {Object} input |
| 568 | * @arg {Snowflake} input.serverID |
| 569 | * @arg {Snowflake} input.userID |
| 570 | */ |
| 571 | DCP.undeafen = function(input, callback) { |
| 572 | this._req('patch', Endpoints.MEMBERS(input.serverID, input.userID), {deaf: false}, function(err, res) { |
| 573 | handleResCB("Could not undeafen user", err, res, callback); |
| 574 | }); |
| 575 | }; |
| 576 | |
| 577 | /** |
| 578 | * Self-mute the client from speaking in all voice channels. |
| 579 | * @arg {Snowflake} serverID |
| 580 | */ |
| 581 | DCP.muteSelf = function(serverID, callback) { |
| 582 | var server = this.servers[serverID], channelID, voiceSession; |
| 583 | if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); |
| 584 | |
| 585 | server.self_mute = true; |
| 586 | |
| 587 | if (!server.voiceSession) return call(callback, [null]); |
| 588 | |
| 589 | voiceSession = server.voiceSession; |
| 590 | voiceSession.self_mute = true; |
| 591 | channelID = voiceSession.channelID; |
| 592 | if (!channelID) return call(callback, [null]); |
| 593 | return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, true, server.self_deaf))]); |
| 594 | }; |
| 595 | |
| 596 | /** |
| 597 | * Remove the self-mute from the client. |
| 598 | * @arg {Snowflake} serverID |
| 599 | */ |
| 600 | DCP.unmuteSelf = function(serverID, callback) { |
| 601 | var server = this.servers[serverID], channelID, voiceSession; |
| 602 | if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); |
| 603 | |
| 604 | server.self_mute = false; |
| 605 | |
| 606 | if (!server.voiceSession) return call(callback, [null]); |
| 607 | |
| 608 | voiceSession = server.voiceSession; |
| 609 | voiceSession.self_mute = false; |
| 610 | channelID = voiceSession.channelID; |
| 611 | if (!channelID) return call(callback, [null]); |
| 612 | return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, false, server.self_deaf))]); |
| 613 | }; |
| 614 | |
| 615 | /** |
| 616 | * Self-deafen the client. |
| 617 | * @arg {Snowflake} serverID |
| 618 | */ |
| 619 | DCP.deafenSelf = function(serverID, callback) { |
| 620 | var server = this.servers[serverID], channelID, voiceSession; |
| 621 | if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); |
| 622 | |
| 623 | server.self_deaf = true; |
| 624 | |
| 625 | if (!server.voiceSession) return call(callback, [null]); |
| 626 | |
| 627 | voiceSession = server.voiceSession; |
| 628 | voiceSession.self_deaf = true; |
| 629 | channelID = voiceSession.channelID; |
| 630 | if (!channelID) return call(callback, [null]); |
| 631 | return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, server.self_mute, true))]); |
| 632 | }; |
| 633 | |
| 634 | /** |
| 635 | * Remove the self-deafen from the client. |
| 636 | * @arg {Snowflake} serverID |
| 637 | */ |
| 638 | DCP.undeafenSelf = function(serverID, callback) { |
| 639 | var server = this.servers[serverID], channelID, voiceSession; |
| 640 | if (!server) return handleErrCB(("Cannot find the server provided: " + serverID), callback); |
| 641 | |
| 642 | server.self_deaf = false; |
| 643 | |
| 644 | if (!server.voiceSession) return call(callback, [null]); |
| 645 | |
| 646 | voiceSession = server.voiceSession; |
| 647 | voiceSession.self_deaf = false; |
| 648 | channelID = voiceSession.channelID; |
| 649 | if (!channelID) return call(callback, [null]); |
| 650 | return call(callback, [send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, server.self_mute, false))]); |
| 651 | }; |
| 652 | |
| 653 | /*Bot server management actions*/ |
| 654 | |
| 655 | /** |
| 656 | * Create a server [User only]. |
| 657 | * @arg {Object} input |
| 658 | * @arg {String} input.name - The server's name |
| 659 | * @arg {String} [input.region] - The server's region code, check the Gitbook documentation for all of them. |
| 660 | * @arg {String<Base64>} [input.icon] - The last part of a Base64 Data URI. `fs.readFileSync('image.jpg', 'base64')` is enough. |
| 661 | */ |
| 662 | DCP.createServer = function(input, callback) { |
| 663 | var payload, client = this; |
| 664 | payload = {icon: null, name: null, region: null}; |
| 665 | for (var key in input) { |
| 666 | if (Object.keys(payload).indexOf(key) < 0) continue; |
| 667 | payload[key] = input[key]; |
| 668 | } |
| 669 | if (input.icon) payload.icon = "data:image/jpg;base64," + input.icon; |
| 670 | |
| 671 | client._req('post', Endpoints.SERVERS(), payload, function(err, res) { |
| 672 | try { |
| 673 | client.servers[res.body.id] = {}; |
| 674 | copyKeys(res.body, client.servers[res.body.id]); |
| 675 | } catch(e) {} |
| 676 | handleResCB("Could not create server", err, res, callback); |
| 677 | }); |
| 678 | }; |
| 679 | |
| 680 | /** |
| 681 | * Edit server information. |
| 682 | * @arg {Object} input |
| 683 | * @arg {Snowflake} input.serverID |
| 684 | * @arg {String} [input.name] |
| 685 | * @arg {String} [input.icon] |
| 686 | * @arg {String} [input.region] |
| 687 | * @arg {Snowflake} [input.afk_channel_id] - The ID of the voice channel to move a user to after the afk period. |
| 688 | * @arg {Number} [input.afk_timeout] - Time in seconds until a user is moved to the afk channel. 60, 300, 900, 1800, or 3600. |
| 689 | */ |
| 690 | DCP.editServer = function(input, callback) { |
| 691 | var payload, serverID = input.serverID, server, client = this; |
| 692 | if (!client.servers[serverID]) return handleErrCB(("[editServer] Server " + serverID + " not found."), callback); |
| 693 | |
| 694 | server = client.servers[serverID]; |
| 695 | payload = { |
| 696 | name: server.name, |
| 697 | icon: server.icon, |
| 698 | region: server.region, |
| 699 | afk_channel_id: server.afk_channel_id, |
| 700 | afk_timeout: server.afk_timeout |
| 701 | }; |
| 702 | |
| 703 | for (var key in input) { |
| 704 | if (Object.keys(payload).indexOf(key) < 0) continue; |
| 705 | if (key === 'afk_channel_id') { |
| 706 | if (server.channels[input[key]] && server.channels[input[key]].type === 'voice') payload[key] = input[key]; |
| 707 | continue; |
| 708 | } |
| 709 | if (key === 'afk_timeout') { |
| 710 | if ([60, 300, 900, 1800, 3600].indexOf(Number(input[key])) > -1) payload[key] = input[key]; |
| 711 | continue; |
| 712 | } |
| 713 | payload[key] = input[key]; |
| 714 | } |
| 715 | if (input.icon) payload.icon = "data:image/jpg;base64," + input.icon; |
| 716 | |
| 717 | client._req('patch', Endpoints.SERVERS(input.serverID), payload, function(err, res) { |
| 718 | handleResCB("Unable to edit server", err, res, callback); |
| 719 | }); |
| 720 | }; |
| 721 | |
| 722 | /** |
| 723 | * Edit the widget information for a server. |
| 724 | * @arg {Object} input |
| 725 | * @arg {Snowflake} input.serverID - The ID of the server whose widget you want to edit. |
| 726 | * @arg {Boolean} [input.enabled] - Whether or not you want the widget to be enabled. |
| 727 | * @arg {Snowflake} [input.channelID] - [Important] The ID of the channel you want the instant invite to point to. |
| 728 | */ |
| 729 | DCP.editServerWidget = function(input, callback) { |
| 730 | var client = this, payload, url = Endpoints.SERVERS(input.serverID) + "/embed"; |
| 731 | |
| 732 | client._req('get', url, function(err, res) { |
| 733 | if (err) return handleResCB("Unable to GET server widget settings. Can not edit without retrieving first.", err, res, callback); |
| 734 | payload = { |
| 735 | enabled: ('enabled' in input ? input.enabled : res.body.enabled), |
| 736 | channel_id: ('channelID' in input ? input.channelID : res.body.channel_id) |
| 737 | }; |
| 738 | client._req('patch', url, payload, function(err, res) { |
| 739 | handleResCB("Unable to edit server widget", err, res, callback); |
| 740 | }); |
| 741 | }); |
| 742 | }; |
| 743 | |
| 744 | /** |
| 745 | * [User Account] Add an emoji to a server |
| 746 | * @arg {Object} input |
| 747 | * @arg {Snowflake} input.serverID |
| 748 | * @arg {String} input.name - The emoji's name |
| 749 | * @arg {String<Base64>} input.image - The emoji's image data in Base64 |
| 750 | */ |
| 751 | DCP.addServerEmoji = function(input, callback) { |
| 752 | var payload = { |
| 753 | name: input.name, |
| 754 | image: "data:image/png;base64," + input.image |
| 755 | }; |
| 756 | this._req('post', Endpoints.SERVER_EMOJIS(input.serverID), payload, function(err, res) { |
| 757 | handleResCB("Unable to add emoji to the server", err, res, callback); |
| 758 | }); |
| 759 | } |
| 760 | |
| 761 | /** |
| 762 | * [User Account] Edit a server emoji data (name only, currently) |
| 763 | * @arg {Object} input |
| 764 | * @arg {Snowflake} input.serverID |
| 765 | * @arg {Snowflake} input.emojiID - The emoji's ID |
| 766 | * @arg {String} [input.name] |
| 767 | * @arg {Array<Snowflake>} [input.roles] - An array of role IDs you want to limit the emoji's usage to |
| 768 | */ |
| 769 | DCP.editServerEmoji = function(input, callback) { |
| 770 | var emoji, payload = {}; |
| 771 | if ( !this.servers[input.serverID] ) return handleErrCB(("[editServerEmoji] Server not available: " + input.serverID), callback); |
| 772 | if ( !this.servers[input.serverID].emojis[input.emojiID]) return handleErrCB(("[editServerEmoji] Emoji not available: " + input.emojiID), callback); |
| 773 | |
| 774 | emoji = this.servers[input.serverID].emojis[input.emojiID]; |
| 775 | payload.name = input.name || emoji.name; |
| 776 | payload.roles = input.roles || emoji.roles; |
| 777 | |
| 778 | this._req('patch', Endpoints.SERVER_EMOJIS(input.serverID, input.emojiID), payload, function(err, res) { |
| 779 | handleResCB("[editServerEmoji] Could not edit server emoji", err, res, callback); |
| 780 | }); |
| 781 | }; |
| 782 | |
| 783 | /** |
| 784 | * [User Account] Remove an emoji from a server |
| 785 | * @arg {Object} input |
| 786 | * @arg {Snowflake} input.serverID |
| 787 | * @arg {Snowflake} input.emojiID |
| 788 | */ |
| 789 | DCP.deleteServerEmoji = function(input, callback) { |
| 790 | this._req('delete', Endpoints.SERVER_EMOJIS(input.serverID, input.emojiID), function(err, res) { |
| 791 | handleResCB("[deleteServerEmoji] Could not delete server emoji", err, res, callback); |
| 792 | }); |
| 793 | }; |
| 794 | |
| 795 | /** |
| 796 | * Leave a server. |
| 797 | * @arg {Snowflake} serverID |
| 798 | */ |
| 799 | DCP.leaveServer = function(serverID, callback) { |
| 800 | this._req('delete', Endpoints.SERVERS_PERSONAL(serverID), function(err, res) { |
| 801 | handleResCB("Could not leave server", err, res, callback); |
| 802 | }); |
| 803 | }; |
| 804 | |
| 805 | /** |
| 806 | * Delete a server owned by the client. |
| 807 | * @arg {Snowflake} serverID |
| 808 | */ |
| 809 | DCP.deleteServer = function(serverID, callback) { |
| 810 | this._req('delete', Endpoints.SERVERS(serverID), function(err, res) { |
| 811 | handleResCB("Could not delete server", err, res, callback); |
| 812 | }); |
| 813 | }; |
| 814 | |
| 815 | /** |
| 816 | * Transfer ownership of a server to another user. |
| 817 | * @arg {Object} input |
| 818 | * @arg {Snowflake} input.serverID |
| 819 | * @arg {Snowflake} input.userID |
| 820 | */ |
| 821 | DCP.transferOwnership = function(input, callback) { |
| 822 | this._req('patch', Endpoints.SERVERS(input.serverID), {owner_id: input.userID}, function(err, res) { |
| 823 | handleResCB("Could not transfer server ownership", err, res, callback); |
| 824 | }); |
| 825 | }; |
| 826 | |
| 827 | /** |
| 828 | * (Used to) Accept an invite to a server [User Only]. Can no longer be used. |
| 829 | * @deprecated |
| 830 | */ |
| 831 | DCP.acceptInvite = function(NUL, callback) { |
| 832 | return handleErrCB("acceptInvite can no longer be used", callback); |
| 833 | }; |
| 834 | |
| 835 | /** |
| 836 | * Generate an invite URL for a channel. |
| 837 | * @arg {Object} input |
| 838 | * @arg {Snowflake} input.channelID |
| 839 | * @arg {Number} input.max_age |
| 840 | * @arg {Number} input.max_uses |
| 841 | * @arg {Boolean} input.temporary |
| 842 | * @arg {Boolean} input.unique |
| 843 | */ |
| 844 | DCP.createInvite = function(input, callback) { |
| 845 | var allowed = ["channelID", "max_age", "max_uses", "temporary", "unique"]; |
| 846 | var payload = {}; |
| 847 | |
| 848 | allowed.forEach(function(name) { |
| 849 | if (input[name]) payload[name] = input[name]; |
| 850 | }); |
| 851 | |
| 852 | this._req('post', Endpoints.CHANNEL(payload.channelID) + "/invites", payload, function(err, res) { |
| 853 | handleResCB('Unable to create invite', err, res, callback); |
| 854 | }); |
| 855 | }; |
| 856 | |
| 857 | /** |
| 858 | * Delete an invite code. |
| 859 | * @arg {String} inviteCode |
| 860 | */ |
| 861 | DCP.deleteInvite = function(inviteCode, callback) { |
| 862 | this._req('delete', Endpoints.INVITES(inviteCode), function(err, res) { |
| 863 | handleResCB('Unable to delete invite', err, res, callback); |
| 864 | }); |
| 865 | }; |
| 866 | |
| 867 | /** |
| 868 | * Get information on an invite. |
| 869 | * @arg {String} inviteCode |
| 870 | */ |
| 871 | DCP.queryInvite = function(inviteCode, callback) { |
| 872 | this._req('get', Endpoints.INVITES(inviteCode), function(err, res) { |
| 873 | handleResCB('Unable to get information about invite', err, res, callback); |
| 874 | }); |
| 875 | }; |
| 876 | |
| 877 | /** |
| 878 | * Get all invites for a server. |
| 879 | * @arg {Snowflake} serverID |
| 880 | */ |
| 881 | DCP.getServerInvites = function(serverID, callback) { |
| 882 | this._req('get', Endpoints.SERVERS(serverID) + "/invites", function(err, res) { |
| 883 | handleResCB('Unable to get invite list for server' + serverID, err, res, callback); |
| 884 | }); |
| 885 | }; |
| 886 | |
| 887 | /** |
| 888 | * Get all invites for a channel. |
| 889 | * @arg {Snowflake} channelID |
| 890 | */ |
| 891 | DCP.getChannelInvites = function(channelID, callback) { |
| 892 | this._req('get', Endpoints.CHANNEL(channelID) + "/invites", function(err, res) { |
| 893 | handleResCB('Unable to get invite list for channel' + channelID, err, res, callback); |
| 894 | }); |
| 895 | }; |
| 896 | |
| 897 | /** |
| 898 | * Create a channel. |
| 899 | * @arg {Object} input |
| 900 | * @arg {Snowflake} input.serverID |
| 901 | * @arg {String} input.name |
| 902 | * @arg {String} [input.type] - 'text' or 'voice', defaults to 'text. |
| 903 | * @arg {Snowflake} [input.parentID] |
| 904 | */ |
| 905 | DCP.createChannel = function(input, callback) { |
| 906 | var client = this, payload = { |
| 907 | name: input.name, |
| 908 | type: (['text', 'voice'].indexOf(input.type) < 0) ? 'text' : input.type, |
| 909 | parent_id: input.parentID |
| 910 | }; |
| 911 | |
| 912 | this._req('post', Endpoints.SERVERS(input.serverID) + "/channels", payload, function(err, res) { |
| 913 | try { |
| 914 | var serverID = res.body.guild_id; |
| 915 | var channelID = res.body.id; |
| 916 | |
| 917 | client.channels[channelID] = new Channel( client, client.servers[serverID], res.body ); |
| 918 | } catch(e) {} |
| 919 | handleResCB('Unable to create channel', err, res, callback); |
| 920 | }); |
| 921 | }; |
| 922 | |
| 923 | /** |
| 924 | * Create a Direct Message channel. |
| 925 | * @arg {Snowflake} userID |
| 926 | */ |
| 927 | DCP.createDMChannel = function(userID, callback) { |
| 928 | var client = this; |
| 929 | this._req('post', Endpoints.USER(client.id) + "/channels", {recipient_id: userID}, function(err, res) { |
| 930 | if (!err && goodResponse(res)) client._uIDToDM[res.body.recipients[0].id] = res.body.id; |
| 931 | handleResCB("Unable to create DM Channel", err, res, callback); |
| 932 | }); |
| 933 | }; |
| 934 | |
| 935 | /** |
| 936 | * Delete a channel. |
| 937 | * @arg {Snowflake} channelID |
| 938 | */ |
| 939 | DCP.deleteChannel = function(channelID, callback) { |
| 940 | this._req('delete', Endpoints.CHANNEL(channelID), function(err, res) { |
| 941 | handleResCB("Unable to delete channel", err, res, callback); |
| 942 | }); |
| 943 | }; |
| 944 | |
| 945 | /** |
| 946 | * Edit a channel's information. |
| 947 | * @arg {Object} input |
| 948 | * @arg {Snowflake} input.channelID |
| 949 | * @arg {String} [input.name] |
| 950 | * @arg {String} [input.topic] - The topic of the channel. |
| 951 | * @arg {Number} [input.bitrate] - [Voice Only] The bitrate for the channel. |
| 952 | * @arg {Number} [input.position] - The channel's position on the list. |
| 953 | * @arg {Number} [input.user_limit] - [Voice Only] Imposes a user limit on a voice channel. |
| 954 | */ |
| 955 | DCP.editChannelInfo = function(input, callback) { |
| 956 | var channel, payload; |
| 957 | |
| 958 | try { |
| 959 | channel = this.channels[input.channelID]; |
| 960 | payload = { |
| 961 | name: channel.name, |
| 962 | topic: channel.topic, |
| 963 | bitrate: channel.bitrate, |
| 964 | position: channel.position, |
| 965 | user_limit: channel.user_limit, |
| 966 | nsfw: channel.nsfw, |
| 967 | parent_id: (input.parentID === undefined ? channel.parent_id : input.parentID) |
| 968 | }; |
| 969 | |
| 970 | for (var key in input) { |
| 971 | if (Object.keys(payload).indexOf(key) < 0) continue; |
| 972 | if (+input[key]) { |
| 973 | if (key === 'bitrate') { |
| 974 | payload.bitrate = Math.min( Math.max( input.bitrate, 8000), 96000); |
| 975 | continue; |
| 976 | } |
| 977 | if (key === 'user_limit') { |
| 978 | payload.user_limit = Math.min( Math.max( input.user_limit, 0), 99); |
| 979 | continue; |
| 980 | } |
| 981 | } |
| 982 | payload[key] = input[key]; |
| 983 | } |
| 984 | |
| 985 | this._req('patch', Endpoints.CHANNEL(input.channelID), payload, function(err, res) { |
| 986 | handleResCB("Unable to edit channel", err, res, callback); |
| 987 | }); |
| 988 | } catch(e) {return handleErrCB(e, callback);} |
| 989 | }; |
| 990 | |
| 991 | /** |
| 992 | * Edit (or creates) a permission override for a channel. |
| 993 | * @arg {Object} input |
| 994 | * @arg {Snowflake} input.channelID |
| 995 | * @arg {Snowflake} [input.userID] |
| 996 | * @arg {Snowflake} [input.roleID] |
| 997 | * @arg {Array<Number>} input.allow - An array of permissions to allow. Discord.Permissions.XXXXXX. |
| 998 | * @arg {Array<Number>} input.deny - An array of permissions to deny, same as above. |
| 999 | * @arg {Array<Number>} input.default - An array of permissions that cancels out allowed and denied permissions. |
| 1000 | */ |
| 1001 | DCP.editChannelPermissions = function(input, callback) { //Will shrink this up later |
| 1002 | var payload, pType, ID, channel, permissions, allowed_values; |
| 1003 | if (!input.userID && !input.roleID) return handleErrCB("[editChannelPermissions] No userID or roleID provided", callback); |
| 1004 | if (!this.channels[input.channelID]) return handleErrCB(("[editChannelPermissions] No channel found for ID: " + input.channelID), callback); |
| 1005 | if (!input.allow && !input.deny && !input.default) return handleErrCB("[editChannelPermissions] No allow, deny or default array provided.", callback); |
| 1006 | |
| 1007 | pType = input.userID ? 'user' : 'role'; |
| 1008 | ID = input[pType + "ID"]; |
| 1009 | channel = this.channels[ input.channelID ]; |
| 1010 | permissions = channel.permissions[pType][ID] || { allow: 0, deny: 0 }; |
| 1011 | allowed_values = [0, 4, 28].concat(((channel.type === 'text' || channel.type === 0) ? |
| 1012 | [10, 11, 12, 13, 14, 15, 16, 17, 18] : |
| 1013 | [20, 21, 22, 23, 24, 25] )); |
| 1014 | |
| 1015 | //Take care of allow first |
| 1016 | if (type(input.allow) === 'array') { |
| 1017 | input.allow.forEach(function(perm) { |
| 1018 | if (allowed_values.indexOf(perm) < 0) return; |
| 1019 | if (hasPermission(perm, permissions.deny)) { |
| 1020 | permissions.deny = removePermission(perm, permissions.deny); |
| 1021 | } |
| 1022 | permissions.allow = givePermission(perm, permissions.allow); |
| 1023 | }); |
| 1024 | }else if(typeof input.allow === 'number'){ //If people want to be a smartass and calculate their permission number themselves. |
| 1025 | permissions.allow = input.allow |
| 1026 | } |
| 1027 | //Take care of deny second |
| 1028 | if (type(input.deny) === 'array') { |
| 1029 | input.deny.forEach(function(perm) { |
| 1030 | if (allowed_values.indexOf(perm) < 0) return; |
| 1031 | if (hasPermission(perm, permissions.allow)) { |
| 1032 | permissions.allow = removePermission(perm, permissions.allow); |
| 1033 | } |
| 1034 | permissions.deny = givePermission(perm, permissions.deny); |
| 1035 | }); |
| 1036 | }else if(typeof input.deny === 'number'){ |
| 1037 | permissions.deny = input.deny |
| 1038 | } |
| 1039 | //Take care of defaulting last |
| 1040 | if (type(input.default) === 'array') { |
| 1041 | input.default.forEach(function(perm) { |
| 1042 | if (allowed_values.indexOf(perm) < 0) return; |
| 1043 | permissions.allow = removePermission(perm, permissions.allow); |
| 1044 | permissions.deny = removePermission(perm, permissions.deny); |
| 1045 | }); |
| 1046 | }else if(typeof input.default === 'number'){ |
| 1047 | permissions.default = input.default |
| 1048 | } |
| 1049 | |
| 1050 | payload = { |
| 1051 | type: (pType === 'user' ? 'member' : 'role'), |
| 1052 | id: ID, |
| 1053 | deny: permissions.deny, |
| 1054 | allow: permissions.allow |
| 1055 | }; |
| 1056 | |
| 1057 | this._req('put', Endpoints.CHANNEL(input.channelID) + "/permissions/" + ID, payload, function(err, res) { |
| 1058 | handleResCB('Unable to edit permission', err, res, callback); |
| 1059 | }); |
| 1060 | }; |
| 1061 | |
| 1062 | /** |
| 1063 | * Delete a permission override for a channel. |
| 1064 | * @arg {Object} input |
| 1065 | * @arg {Snowflake} input.channelID |
| 1066 | * @arg {Snowflake} [input.userID] |
| 1067 | * @arg {Snowflake} [input.roleID] |
| 1068 | */ |
| 1069 | DCP.deleteChannelPermission = function(input, callback) { |
| 1070 | var payload, pType, ID; |
| 1071 | if (!input.userID && !input.roleID) return handleErrCB("[deleteChannelPermission] No userID or roleID provided", callback); |
| 1072 | if (!this.channels[input.channelID]) return handleErrCB(("[deleteChannelPermission] No channel found for ID: " + input.channelID), callback); |
| 1073 | |
| 1074 | pType = input.userID ? 'user' : 'role'; |
| 1075 | ID = input[pType + "ID"]; |
| 1076 | |
| 1077 | payload = { |
| 1078 | type: (pType === 'user' ? 'member' : 'role'), |
| 1079 | id: ID |
| 1080 | }; |
| 1081 | |
| 1082 | this._req('delete', Endpoints.CHANNEL(input.channelID) + "/permissions/" + ID, payload, function(err, res) { |
| 1083 | handleResCB('Unable to delete permission', err, res, callback); |
| 1084 | }); |
| 1085 | }; |
| 1086 | |
| 1087 | /** |
| 1088 | * Create a role for a server. |
| 1089 | * @arg {Snowflake} serverID |
| 1090 | */ |
| 1091 | DCP.createRole = function(serverID, callback) { |
| 1092 | var client = this; |
| 1093 | this._req('post', Endpoints.ROLES(serverID), function(err, res) { |
| 1094 | try { |
| 1095 | client.servers[serverID].roles[res.body.id] = new Role(res.body); |
| 1096 | } catch(e) {} |
| 1097 | handleResCB("Unable to create role", err, res, callback); |
| 1098 | }); |
| 1099 | }; |
| 1100 | |
| 1101 | /** |
| 1102 | * Edit a role. |
| 1103 | * @arg {Object} input |
| 1104 | * @arg {Snowflake} input.serverID |
| 1105 | * @arg {Snowflake} input.roleID - The ID of the role. |
| 1106 | * @arg {String} [input.name] |
| 1107 | * @arg {String} [input.color] - A color value as a number. Recommend using Hex numbers, as they can map to HTML colors (0xF35353 === #F35353). |
| 1108 | * @arg {Boolean} [input.hoist] - Separates the users in this role from the normal online users. |
| 1109 | * @arg {Object} [input.permissions] - An Object containing the permission as a key, and `true` or `false` as its value. Read the Permissions doc. |
| 1110 | * @arg {Boolean} [input.mentionable] - Toggles if users can @Mention this role. |
| 1111 | */ |
| 1112 | DCP.editRole = function(input, callback) { |
| 1113 | var role, payload; |
| 1114 | try { |
| 1115 | role = new Role(this.servers[input.serverID].roles[input.roleID]); |
| 1116 | payload = { |
| 1117 | name: role.name, |
| 1118 | color: role.color, |
| 1119 | hoist: role.hoist, |
| 1120 | permissions: role._permissions, |
| 1121 | mentionable: role.mentionable, |
| 1122 | position: role.position |
| 1123 | }; |
| 1124 | |
| 1125 | for (var key in input) { |
| 1126 | if (Object.keys(payload).indexOf(key) < 0) continue; |
| 1127 | if (key === 'permissions') { |
| 1128 | for (var perm in input[key]) { |
| 1129 | role[perm] = input[key][perm]; |
| 1130 | payload.permissions = role._permissions; |
| 1131 | } |
| 1132 | continue; |
| 1133 | } |
| 1134 | if (key === 'color') { |
| 1135 | if (String(input[key])[0] === '#') payload.color = parseInt(String(input[key]).replace('#', '0x'), 16); |
| 1136 | if (Discord.Colors[input[key]]) payload.color = Discord.Colors[input[key]]; |
| 1137 | if (type(input[key]) === 'number') payload.color = input[key]; |
| 1138 | continue; |
| 1139 | } |
| 1140 | payload[key] = input[key]; |
| 1141 | } |
| 1142 | this._req('patch', Endpoints.ROLES(input.serverID, input.roleID), payload, function(err, res) { |
| 1143 | handleResCB("Unable to edit role", err, res, callback); |
| 1144 | }); |
| 1145 | } catch(e) {return handleErrCB(('[editRole] ' + e), callback);} |
| 1146 | }; |
| 1147 | |
| 1148 | /** |
| 1149 | * Delete a role. |
| 1150 | * @arg {Object} input |
| 1151 | * @arg {Snowflake} input.serverID |
| 1152 | * @arg {Snowflake} input.roleID |
| 1153 | */ |
| 1154 | DCP.deleteRole = function(input, callback) { |
| 1155 | this._req('delete', Endpoints.ROLES(input.serverID, input.roleID), function(err, res) { |
| 1156 | handleResCB("Could not remove role", err, res, callback); |
| 1157 | }); |
| 1158 | }; |
| 1159 | |
| 1160 | /** |
| 1161 | * Add a user to a role. |
| 1162 | * @arg {Object} input |
| 1163 | * @arg {Snowflake} input.serverID |
| 1164 | * @arg {Snowflake} input.roleID |
| 1165 | * @arg {Snowflake} input.userID |
| 1166 | */ |
| 1167 | DCP.addToRole = function(input, callback) { |
| 1168 | this._req('put', Endpoints.MEMBER_ROLES(input.serverID, input.userID, input.roleID), function(err, res) { |
| 1169 | handleResCB("Could not add role", err, res, callback); |
| 1170 | }); |
| 1171 | }; |
| 1172 | |
| 1173 | /** |
| 1174 | * Remove a user from a role. |
| 1175 | * @arg {Object} input |
| 1176 | * @arg {Snowflake} input.serverID |
| 1177 | * @arg {Snowflake} input.roleID |
| 1178 | * @arg {Snowflake} input.userID |
| 1179 | */ |
| 1180 | DCP.removeFromRole = function(input, callback) { |
| 1181 | this._req('delete', Endpoints.MEMBER_ROLES(input.serverID, input.userID, input.roleID), function(err, res) { |
| 1182 | handleResCB("Could not remove role", err, res, callback); |
| 1183 | }); |
| 1184 | }; |
| 1185 | |
| 1186 | /** |
| 1187 | * Edit a user's nickname. |
| 1188 | * @arg {Object} input |
| 1189 | * @arg {Snowflake} input.serverID |
| 1190 | * @arg {Snowflake} input.userID |
| 1191 | * @arg {String} input.nick - The nickname you'd like displayed. |
| 1192 | */ |
| 1193 | DCP.editNickname = function(input, callback) { |
| 1194 | var payload = {nick: String( input.nick ? input.nick : "" )}; |
| 1195 | var url = input.userID === this.id ? |
| 1196 | Endpoints.MEMBERS(input.serverID) + "/@me/nick" : |
| 1197 | Endpoints.MEMBERS(input.serverID, input.userID); |
| 1198 | |
| 1199 | this._req('patch', url, payload, function(err, res) { |
| 1200 | handleResCB("Could not change nickname", err, res, callback); |
| 1201 | }); |
| 1202 | }; |
| 1203 | |
| 1204 | /** |
| 1205 | * Edit a user's note. |
| 1206 | * @arg {Object} input |
| 1207 | * @arg {Snowflake} input.userID |
| 1208 | * @arg {String} input.note - The note content that you want to use. |
| 1209 | */ |
| 1210 | DCP.editNote = function(input, callback) { |
| 1211 | this._req('put', Endpoints.NOTE(input.userID), {note: input.note}, function(err, res) { |
| 1212 | handleResCB("Could not edit note", err, res, callback); |
| 1213 | }); |
| 1214 | }; |
| 1215 | |
| 1216 | /** |
| 1217 | * Retrieve a user object from Discord, the library already caches users, however. |
| 1218 | * @arg {Object} input |
| 1219 | * @arg {Snowflake} input.serverID |
| 1220 | * @arg {Snowflake} input.userID |
| 1221 | */ |
| 1222 | DCP.getMember = function(input, callback) { |
| 1223 | this._req('get', Endpoints.MEMBERS(input.serverID, input.userID), function(err, res) { |
| 1224 | handleResCB("Could not get member", err, res, callback); |
| 1225 | }); |
| 1226 | }; |
| 1227 | |
| 1228 | /** |
| 1229 | * Retrieve a group of user objects from Discord. |
| 1230 | * @arg {Object} input |
| 1231 | * @arg {Number} [input.limit] - The amount of users to pull, defaults to 50. |
| 1232 | * @arg {Snowflake} [input.after] - The offset using a user ID. |
| 1233 | */ |
| 1234 | DCP.getMembers = function(input, callback) { |
| 1235 | var qs = {}; |
| 1236 | qs.limit = (typeof(input.limit) !== 'number' ? 50 : input.limit); |
| 1237 | if (input.after) qs.after = input.after; |
| 1238 | |
| 1239 | this._req('get', Endpoints.MEMBERS(input.serverID) + qstringify(qs), function(err, res) { |
| 1240 | handleResCB("Could not get members", err, res, callback); |
| 1241 | }); |
| 1242 | }; |
| 1243 | |
| 1244 | /** |
| 1245 | * Get the ban list from a server |
| 1246 | * @arg {Snowflake} serverID |
| 1247 | */ |
| 1248 | DCP.getBans = function(serverID, callback) { |
| 1249 | this._req('get', Endpoints.BANS(serverID), function(err, res) { |
| 1250 | handleResCB("Could not get ban list", err, res, callback); |
| 1251 | }); |
| 1252 | }; |
| 1253 | |
| 1254 | /** |
| 1255 | * Get all webhooks for a server |
| 1256 | * @arg {Snowflake} serverID |
| 1257 | */ |
| 1258 | DCP.getServerWebhooks = function(serverID, callback) { |
| 1259 | this._req('get', Endpoints.SERVER_WEBHOOKS(serverID), function(err, res) { |
| 1260 | handleResCB("Could not get server Webhooks", err, res, callback); |
| 1261 | }); |
| 1262 | }; |
| 1263 | |
| 1264 | /** |
| 1265 | * Get webhooks from a channel |
| 1266 | * @arg {Snowflake} channelID |
| 1267 | */ |
| 1268 | DCP.getChannelWebhooks = function(channelID, callback) { |
| 1269 | this._req('get', Endpoints.CHANNEL_WEBHOOKS(channelID), function(err, res) { |
| 1270 | handleResCB("Could not get channel Webhooks", err, res, callback); |
| 1271 | }); |
| 1272 | }; |
| 1273 | |
| 1274 | /** |
| 1275 | * Create a webhook for a server |
| 1276 | * @arg {Snowflake} serverID |
| 1277 | */ |
| 1278 | DCP.createWebhook = function(serverID, callback) { |
| 1279 | this._req('post', Endpoints.SERVER_WEBHOOKS(serverID), function(err, res) { |
| 1280 | handleResCB("Could not create a Webhook", err, res, callback); |
| 1281 | }); |
| 1282 | }; |
| 1283 | |
| 1284 | /** |
| 1285 | * Edit a webhook |
| 1286 | * @arg {Object} input |
| 1287 | * @arg {Snowflake} input.webhookID - The Webhook's ID |
| 1288 | * @arg {String} [input.name] |
| 1289 | * @arg {String<Base64>} [input.avatar] |
| 1290 | * @arg {String} [input.channelID] |
| 1291 | */ |
| 1292 | DCP.editWebhook = function(input, callback) { |
| 1293 | var client = this, payload = {}, allowed = ['avatar', 'name']; |
| 1294 | this._req('get', Endpoints.WEBHOOKS(input.webhookID), function(err, res) { |
| 1295 | if (err || !goodResponse(res)) return handleResCB("Couldn't get webhook, do you have permissions to access it?", err, res, callback); |
| 1296 | allowed.forEach(function(key) { |
| 1297 | payload[key] = (key in input ? input[key] : res.body[key]); |
| 1298 | }); |
| 1299 | payload.channel_id = input.channelID || res.body.channel_id; |
| 1300 | |
| 1301 | client._req('patch', Endpoints.WEBHOOKS(input.webhookID), payload, function(err, res) { |
| 1302 | return handleResCB("Couldn't update webhook", err, res, callback); |
| 1303 | }); |
| 1304 | }); |
| 1305 | }; |
| 1306 | |
| 1307 | /* --- Voice --- */ |
| 1308 | |
| 1309 | /** |
| 1310 | * Join a voice channel. |
| 1311 | * @arg {Snowflake} channelID |
| 1312 | */ |
| 1313 | DCP.joinVoiceChannel = function(channelID, callback) { |
| 1314 | var serverID, server, channel, voiceSession; |
| 1315 | try { |
| 1316 | serverID = this.channels[channelID].guild_id; |
| 1317 | server = this.servers[serverID]; |
| 1318 | channel = server.channels[channelID]; |
| 1319 | } catch(e) {} |
| 1320 | if (!serverID) return handleErrCB(("Cannot find the server related to the channel provided: " + channelID), callback); |
| 1321 | if (channel.type !== 'voice' && channel.type !== 2) return handleErrCB(("Selected channel is not a voice channel: " + channelID), callback); |
| 1322 | if (this._vChannels[channelID]) return handleErrCB(("Voice channel already active: " + channelID), callback); |
| 1323 | |
| 1324 | voiceSession = getVoiceSession(this, channelID, server); |
| 1325 | voiceSession.self_mute = server.self_mute; |
| 1326 | voiceSession.self_deaf = server.self_deaf; |
| 1327 | checkVoiceReady(voiceSession, callback); |
| 1328 | return send(this._ws, Payloads.UPDATE_VOICE(serverID, channelID, server.self_mute, server.self_deaf)); |
| 1329 | }; |
| 1330 | |
| 1331 | /** |
| 1332 | * Leave a voice channel. |
| 1333 | * @arg {Snowflake} channelID |
| 1334 | */ |
| 1335 | DCP.leaveVoiceChannel = function(channelID, callback) { |
| 1336 | if (!this._vChannels[channelID]) return handleErrCB(("Not in the voice channel: " + channelID), callback); |
| 1337 | return leaveVoiceChannel(this, channelID, callback); |
| 1338 | }; |
| 1339 | |
| 1340 | /** |
| 1341 | * Prepare the client for sending/receiving audio. |
| 1342 | * @arg {Snowflake|Object} channelObj - Either the channel ID, or an Object with `channelID` as a key and the ID as the value. |
| 1343 | * @arg {Number} [channelObj.maxStreamSize] - The size in KB that you wish to receive before pushing out earlier data. Required if you want to store or receive incoming audio. |
| 1344 | * @arg {Boolean} [channelObj.stereo] - Sets the audio to be either stereo or mono. Defaults to true. |
| 1345 | */ |
| 1346 | DCP.getAudioContext = function(channelObj, callback) { |
| 1347 | // #q/qeled gave a proper timing solution. Credit where it's due. |
| 1348 | if (!isNode) return handleErrCB("Using audio in the browser is currently not supported.", callback); |
| 1349 | var channelID = channelObj.channelID || channelObj, voiceSession = this._vChannels[channelID], encoder = chooseAudioEncoder(['ffmpeg', 'avconv']); |
| 1350 | |
| 1351 | if (!voiceSession) return handleErrCB(("You have not joined the voice channel: " + channelID), callback); |
| 1352 | if (voiceSession.ready !== true) return handleErrCB(("The connection to the voice channel " + channelID + " has not been initialized yet."), callback); |
| 1353 | if (!encoder) return handleErrCB("You need either 'ffmpeg' or 'avconv' and they need to be added to PATH", callback); |
| 1354 | |
| 1355 | voiceSession.audio = voiceSession.audio || new AudioCB( |
| 1356 | voiceSession, |
| 1357 | channelObj.stereo === false ? 1 : 2, |
| 1358 | encoder, |
| 1359 | Math.abs(Number(channelObj.maxStreamSize))); |
| 1360 | |
| 1361 | return call(callback, [null, voiceSession.audio]); |
| 1362 | }; |
| 1363 | |
| 1364 | /* --- Misc --- */ |
| 1365 | |
| 1366 | /** |
| 1367 | * Retrieves all offline (and online, if using a user account) users, fires the `allUsers` event when done. |
| 1368 | */ |
| 1369 | DCP.getAllUsers = function(callback) { |
| 1370 | var servers = Object.keys(this.servers).filter(function(s) { |
| 1371 | s = this.servers[s]; |
| 1372 | if (s.members) return s.member_count !== Object.keys(s.members).length && (this.bot ? s.large : true); |
| 1373 | }, this); |
| 1374 | |
| 1375 | if (!servers[0]) { |
| 1376 | this.emit('allUsers'); |
| 1377 | return handleErrCB("There are no users to be collected", callback); |
| 1378 | } |
| 1379 | if (!this.bot) send(this._ws, Payloads.ALL_USERS(this)); |
| 1380 | |
| 1381 | return getOfflineUsers(this, servers, callback); |
| 1382 | }; |
| 1383 | |
| 1384 | /* --- Functions --- */ |
| 1385 | function handleErrCB(err, callback) { |
| 1386 | if (!err) return false; |
| 1387 | return call(callback, [new Error(err)]); |
| 1388 | } |
| 1389 | function handleResCB(errMessage, err, res, callback) { |
| 1390 | if (typeof(callback) !== 'function') return; |
| 1391 | res = res || {}; |
| 1392 | if (!err && goodResponse(res)) return (callback(null, res.body), true); |
| 1393 | |
| 1394 | var e = new Error( err || errMessage ); |
| 1395 | e.name = "ResponseError"; |
| 1396 | e.statusCode = res.statusCode; |
| 1397 | e.statusMessage = res.statusMessage; |
| 1398 | e.response = res.body; |
| 1399 | return (callback(e), false); |
| 1400 | } |
| 1401 | function goodResponse(response) { |
| 1402 | return (response.statusCode / 100 | 0) === 2; |
| 1403 | } |
| 1404 | function stringifyError(response) { |
| 1405 | if (!response) return null; |
| 1406 | return response.statusCode + " " + response.statusMessage + "\n" + JSON.stringify(response.body); |
| 1407 | } |
| 1408 | |
| 1409 | /* - Functions - Messages - */ |
| 1410 | function sendMessage(client, to, message, callback) { |
| 1411 | resolveID(client, to, function(channelID) { |
| 1412 | client._req('post', Endpoints.MESSAGES(channelID), message, function(err, res) { |
| 1413 | handleResCB("Unable to send messages", err, res, callback); |
| 1414 | }); |
| 1415 | }); |
| 1416 | } |
| 1417 | function cacheMessage(cache, limit, channelID, message) { |
| 1418 | if (!cache[channelID]) cache[channelID] = {}; |
| 1419 | if (limit === -1) return void(cache[channelID][message.id] = message); |
| 1420 | var k = Object.keys(cache[channelID]); |
| 1421 | if (k.length > limit) delete(cache[channelID][k[0]]); |
| 1422 | cache[channelID][message.id] = message; |
| 1423 | } |
| 1424 | function generateMessage(message, embed) { |
| 1425 | return { |
| 1426 | type: 0, |
| 1427 | content: String(message), |
| 1428 | nonce: Math.floor(Math.random() * Number.MAX_SAFE_INTEGER), |
| 1429 | embed: embed || {} |
| 1430 | }; |
| 1431 | } |
| 1432 | function messageHeaders(client) { |
| 1433 | var r = { |
| 1434 | "accept": "*/*", |
| 1435 | "accept-language": "en-US;q=0.8", |
| 1436 | }; |
| 1437 | if (isNode) { |
| 1438 | r["accept-encoding"] = "gzip, deflate"; |
| 1439 | r.user_agent = "DiscordBot (https://github.com/izy521/discord.io, " + CURRENT_VERSION + ")"; |
| 1440 | r.dnt = 1; |
| 1441 | } |
| 1442 | try { |
| 1443 | r.authorization = (client.bot ? "Bot " : "") + client.internals.token; |
| 1444 | } catch(e) {} |
| 1445 | return r; |
| 1446 | } |
| 1447 | function simulateTyping(client, to, message, time, callback) { |
| 1448 | if (time <= 0) return sendMessage(client, to, message, callback); |
| 1449 | |
| 1450 | client.simulateTyping(to, function() { |
| 1451 | setTimeout(simulateTyping, Math.min(time, 5000), client, to, message, time - 5000, callback); |
| 1452 | }); |
| 1453 | } |
| 1454 | function stringifyEmoji(emoji) { |
| 1455 | if (typeof emoji === 'object') // if (emoji.name && emoji.id) |
| 1456 | return emoji.name + ':' + emoji.id; |
| 1457 | if (emoji.indexOf(':') > -1) |
| 1458 | return emoji; |
| 1459 | return encodeURIComponent(decodeURIComponent(emoji)); |
| 1460 | } |
| 1461 | |
| 1462 | /* - Functions - Utils */ |
| 1463 | function APIRequest(method, url) { |
| 1464 | var data, callback, opts, req, headers = messageHeaders(this); |
| 1465 | callback = ( typeof(arguments[2]) === 'function' ? arguments[2] : (data = arguments[2], arguments[3]) ); |
| 1466 | |
| 1467 | if (isNode) { |
| 1468 | opts = URL.parse(url); |
| 1469 | opts.method = method; |
| 1470 | opts.headers = headers; |
| 1471 | |
| 1472 | req = requesters[opts.protocol.slice(0, -1)].request(opts, function(res) { |
| 1473 | var chunks = []; |
| 1474 | res.on('data', function(c) { chunks[chunks.length] = c; }); |
| 1475 | res.once('end', function() { |
| 1476 | chunks = Buffer.concat(chunks); |
| 1477 | Zlib.gunzip(chunks, function(err, uc) { |
| 1478 | if (!err) uc = uc.toString(); |
| 1479 | try { res.body = JSON.parse(uc || chunks); } catch(e) {} |
| 1480 | return callback(null, res); |
| 1481 | }); |
| 1482 | }); |
| 1483 | }); |
| 1484 | if (type(data) === 'object' || method.toLowerCase() === 'get') req.setHeader("Content-Type", "application/json; charset=utf-8"); |
| 1485 | if (data instanceof Multipart) req.setHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary); |
| 1486 | if (data) req.write( data.result || JSON.stringify(data), data.result ? 'binary' : 'utf-8' ); |
| 1487 | req.end(); |
| 1488 | |
| 1489 | return req.once('error', function(e) { return callback(e.message); }); |
| 1490 | } |
| 1491 | |
| 1492 | req = new XMLHttpRequest(); |
| 1493 | req.open(method.toUpperCase(), url, true); |
| 1494 | for (var key in headers) { |
| 1495 | req.setRequestHeader(key, headers[key]); |
| 1496 | } |
| 1497 | req.onreadystatechange = function() { |
| 1498 | if (req.readyState == 4) { |
| 1499 | req.statusCode = req.status; |
| 1500 | req.statusMessage = req.statusText; |
| 1501 | try {req.body = JSON.parse(req.responseText);} catch (e) { return handleErrCB(e, callback); } |
| 1502 | callback(null, req); |
| 1503 | } |
| 1504 | }; |
| 1505 | if (type(data) === 'object' || method.toLowerCase() === 'get') req.setRequestHeader("Content-Type", "application/json; charset=utf-8"); |
| 1506 | if (data instanceof Multipart) req.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.boundary); |
| 1507 | if (data) return req.send( data.result ? data.result : JSON.stringify(data) ); |
| 1508 | req.send(null); |
| 1509 | } |
| 1510 | function send(ws, data) { |
| 1511 | if (ws && ws.readyState == 1) ws.send(JSON.stringify(data)); |
| 1512 | } |
| 1513 | function copy(obj) { |
| 1514 | try { |
| 1515 | return JSON.parse( JSON.stringify( obj ) ); |
| 1516 | } catch(e) {} |
| 1517 | } |
| 1518 | function copyKeys(from, to, omit) { |
| 1519 | if (!omit) omit = []; |
| 1520 | for (var key in from) { |
| 1521 | if (omit.indexOf(key) > -1) continue; |
| 1522 | to[key] = from[key]; |
| 1523 | } |
| 1524 | } |
| 1525 | function applyProperties(object, properties) { |
| 1526 | properties.forEach(function(t) { |
| 1527 | Object.defineProperty(object, t[0], { |
| 1528 | configurable: true, |
| 1529 | writable: true, |
| 1530 | value: t[1] |
| 1531 | }); |
| 1532 | }, object); |
| 1533 | } |
| 1534 | function type(v) { |
| 1535 | return Object.prototype.toString.call(v).match(/ (.*)]/)[1].toLowerCase(); |
| 1536 | } |
| 1537 | function call(f, a) { |
| 1538 | if (typeof(f) != 'function') return; |
| 1539 | return f.apply(null, a); |
| 1540 | } |
| 1541 | function qstringify(obj) { |
| 1542 | //.map + .join is 7x slower! |
| 1543 | var i=0, s = "", k = Object.keys(obj); |
| 1544 | for (i;i<k.length;i++) { |
| 1545 | s += k[i] + "=" + obj[k[i]] + "&"; |
| 1546 | } |
| 1547 | return "?" + s.slice(0, -1); |
| 1548 | } |
| 1549 | function emit(client, message) { |
| 1550 | if (!message.t) return; |
| 1551 | var t = message.t.split("_"), i = 1, args = [t[0].toLowerCase()]; |
| 1552 | |
| 1553 | for (i; i<t.length; i++) { |
| 1554 | args[0] += t[i][0] + t[i].slice(1).toLowerCase(); |
| 1555 | } |
| 1556 | for (i=2; i<arguments.length; i++) { |
| 1557 | args.push(arguments[i]); |
| 1558 | } |
| 1559 | args.push(message); |
| 1560 | client.emit.apply(client, args); |
| 1561 | } |
| 1562 | function decompressWSMessage(m, f) { |
| 1563 | f = f || {}; |
| 1564 | return f.binary ? JSON.parse(Zlib.inflateSync(m).toString()) : JSON.parse(m); |
| 1565 | } |
| 1566 | function removeAllListeners(emitter, type) { |
| 1567 | if (!emitter) return; |
| 1568 | var e = emitter._evts, i, k, o, s, z; |
| 1569 | if (isNode) return type ? emitter.removeAllListeners(type) : emitter.removeAllListeners(); |
| 1570 | |
| 1571 | if (type && e[type]) { |
| 1572 | for (i=0; i<e[type].length; i++) { |
| 1573 | emitter.removeListener(type, e[type][i]); |
| 1574 | } |
| 1575 | } |
| 1576 | |
| 1577 | if (!type) { |
| 1578 | k = Object.keys(e); |
| 1579 | for (o=0; o<k.length; o++) { |
| 1580 | s = e[ k[o] ]; |
| 1581 | for (z=0; z<s.length; z++) { |
| 1582 | emitter.removeListener(k[o], s[z]); |
| 1583 | } |
| 1584 | } |
| 1585 | } |
| 1586 | } |
| 1587 | function colorFromRole(server, member) { |
| 1588 | return member.roles.reduce(function(array, ID) { |
| 1589 | var role = server.roles[ID]; |
| 1590 | if (!role) return array; |
| 1591 | return role.position > array[0] && role.color ? [role.position, role.color] : array; |
| 1592 | }, [-1, null])[1]; |
| 1593 | } |
| 1594 | function log(client, level_message) { |
| 1595 | var level, message; |
| 1596 | if (arguments.length === 2) { |
| 1597 | level = Discord.LogLevels.Info; |
| 1598 | message = level_message; |
| 1599 | } else { |
| 1600 | level = level_message; |
| 1601 | message = arguments[2]; |
| 1602 | } |
| 1603 | return client.emit('log', level, message); |
| 1604 | } |
| 1605 | |
| 1606 | function givePermission(bit, permissions) { |
| 1607 | return permissions | (1 << bit); |
| 1608 | } |
| 1609 | function removePermission(bit, permissions) { |
| 1610 | return permissions & ~(1 << bit); |
| 1611 | } |
| 1612 | function hasPermission(bit, permissions) { |
| 1613 | return ((permissions >> bit) & 1) == 1; |
| 1614 | } |
| 1615 | //For the Getters and Setters |
| 1616 | function getPerm(bit) { |
| 1617 | return function() { |
| 1618 | return ((this._permissions >> bit) & 1) == 1; |
| 1619 | }; |
| 1620 | } |
| 1621 | function setPerm(bit) { |
| 1622 | return function(v) { |
| 1623 | if (v === true) return this._permissions |= (1 << (bit)); |
| 1624 | if (v === false) return this._permissions &= ~(1 << bit); |
| 1625 | }; |
| 1626 | } |
| 1627 | |
| 1628 | function getServerInfo(client, servArr) { |
| 1629 | for (var server=0; server<servArr.length; server++) { |
| 1630 | client.servers[servArr[server].id] = new Server(client, servArr[server]); |
| 1631 | } |
| 1632 | } |
| 1633 | function getDirectMessages(client, DMArray) { |
| 1634 | for (var DM=0; DM<DMArray.length; DM++) { |
| 1635 | client.directMessages[DMArray[DM].id] = new DMChannel(client._uIDToDM, DMArray[DM]); |
| 1636 | } |
| 1637 | } |
| 1638 | function resolveID(client, ID, callback) { |
| 1639 | /*Get channel from ServerID, ChannelID or UserID. |
| 1640 | Only really used for sendMessage and uploadFile.*/ |
| 1641 | //Callback used instead of return because requesting seems necessary. |
| 1642 | |
| 1643 | if (client._uIDToDM[ID]) return callback(client._uIDToDM[ID]); |
| 1644 | //If it's a UserID, and it's in the UserID : ChannelID cache, use the found ChannelID |
| 1645 | |
| 1646 | //If the ID isn't in the UserID : ChannelID cache, let's try seeing if it belongs to a user. |
| 1647 | if (client.users[ID]) return client.createDMChannel(ID, function(err, res) { |
| 1648 | if (err) return console.log("Internal ID resolver error: " + JSON.stringify(err)); |
| 1649 | callback(res.id); |
| 1650 | }); |
| 1651 | |
| 1652 | return callback(ID); //Finally, the ID must not belong to a User, so send the message directly to it, as it must be a Channel's. |
| 1653 | } |
| 1654 | function resolveEvent(e) { |
| 1655 | return e.detail || ([e.data][0] ? [e.data] : [e.code]); |
| 1656 | } |
| 1657 | |
| 1658 | /* --- Initializing --- */ |
| 1659 | function init(client, opts) { |
| 1660 | client.servers = {}; |
| 1661 | client.channels = {}; |
| 1662 | client.users = {}; |
| 1663 | client.directMessages = {}; |
| 1664 | client.internals = { |
| 1665 | oauth: {}, |
| 1666 | version: CURRENT_VERSION, |
| 1667 | settings: {} |
| 1668 | }; |
| 1669 | client._connecting = true; |
| 1670 | |
| 1671 | setupPing(client.internals); |
| 1672 | return getToken(client, opts); |
| 1673 | } |
| 1674 | function getToken(client, opts) { |
| 1675 | if (opts.token) return getGateway(client, opts.token); |
| 1676 | if (!isNode) { |
| 1677 | //Read from localStorage? Sounds like a bad idea, but I'll leave this here. |
| 1678 | } |
| 1679 | } |
| 1680 | function getGateway(client, token) { |
| 1681 | client.internals.token = token; |
| 1682 | |
| 1683 | return APIRequest('get', Endpoints.GATEWAY, function (err, res) { |
| 1684 | if (err || !goodResponse(res)) { |
| 1685 | client._connecting = false; |
| 1686 | return client.emit("disconnect", "Error GETing gateway:\n" + stringifyError(res), 0); |
| 1687 | } |
| 1688 | return startConnection(client, (res.body.url + "/?encoding=json&v=" + GATEWAY_VERSION)); |
| 1689 | }); |
| 1690 | } |
| 1691 | function startConnection(client, gateway) { |
| 1692 | client._ws = new Websocket(gateway); |
| 1693 | client.internals.gatewayUrl = gateway; |
| 1694 | |
| 1695 | client._ws.once('close', handleWSClose.bind(client)); |
| 1696 | client._ws.once('error', handleWSClose.bind(client)); |
| 1697 | client._ws.on('message', handleWSMessage.bind(client)); |
| 1698 | } |
| 1699 | function getOfflineUsers(client, servArr, callback) { |
| 1700 | if (!servArr[0]) return call(callback); |
| 1701 | |
| 1702 | send(client._ws, Payloads.OFFLINE_USERS(servArr)); |
| 1703 | return setTimeout( getOfflineUsers, 0, client, servArr, callback ); |
| 1704 | } |
| 1705 | function checkForAllServers(client, ready, message) { |
| 1706 | var all = Object.keys(client.servers).every(function(s) { |
| 1707 | return !client.servers[s].unavailable; |
| 1708 | }); |
| 1709 | if (all || ready[0]) return void(client._ready = true && client.emit('ready', message)); |
| 1710 | return setTimeout(checkForAllServers, 0, client, ready, message); |
| 1711 | } |
| 1712 | function setupPing(obj) { |
| 1713 | applyProperties(obj, [ |
| 1714 | ["_pings", []], |
| 1715 | ["_lastHB", 0] |
| 1716 | ]); |
| 1717 | Object.defineProperty(obj, 'ping', { |
| 1718 | get: function() { |
| 1719 | return ((obj._pings.reduce(function(p, c) { return p + c; }, 0) / obj._pings.length) || 0) | 0; |
| 1720 | }, |
| 1721 | set: function() {} |
| 1722 | }); |
| 1723 | } |
| 1724 | function validateShard(shard) { |
| 1725 | return ( |
| 1726 | type(shard) === 'array' && |
| 1727 | shard.length === 2 && |
| 1728 | shard[0] <= shard[1] && |
| 1729 | shard[1] > 1 |
| 1730 | ) ? shard : null; |
| 1731 | } |
| 1732 | function identifyOrResume(client) { |
| 1733 | var payload, internals = client.internals; |
| 1734 | |
| 1735 | if (internals.sequence && internals.token && internals.sessionID) { |
| 1736 | payload = Payloads.RESUME(client); |
| 1737 | } else { |
| 1738 | payload = Payloads.IDENTIFY(client); |
| 1739 | if (client._shard) payload.d.shard = client._shard; |
| 1740 | } |
| 1741 | client._connecting = false; |
| 1742 | |
| 1743 | return send(client._ws, payload); |
| 1744 | } |
| 1745 | |
| 1746 | /* - Functions - Websocket Handling - */ |
| 1747 | function handleWSMessage(data, flags) { |
| 1748 | var message = decompressWSMessage(data, flags); |
| 1749 | var _data = message.d; |
| 1750 | var client = this, user, server, member, old, |
| 1751 | userID, serverID, channelID, currentVCID, |
| 1752 | mute, deaf, self_mute, self_deaf; |
| 1753 | |
| 1754 | switch (message.op) { |
| 1755 | case 0: |
| 1756 | //Event dispatched - update our sequence number |
| 1757 | client.internals.sequence = message.s; |
| 1758 | break; |
| 1759 | case 1: |
| 1760 | //Heartbeat requested by Discord - send one immediately |
| 1761 | send(client._ws, Payloads.HEARTBEAT(client)); |
| 1762 | break; |
| 1763 | case 7: |
| 1764 | //Reconnect requested by discord |
| 1765 | clearTimeout(client.internals.heartbeat); |
| 1766 | client._ws.close(1000, 'Reconnect requested by Discord'); |
| 1767 | break; |
| 1768 | case 9: |
| 1769 | //Disconnect after an Invalid Session |
| 1770 | //Disconnect the client if the client has received an invalid session id |
| 1771 | if(!message.d) { |
| 1772 | delete(client.internals.sequence); |
| 1773 | delete(client.internals.sessionID); |
| 1774 | //Send new identify after 1-5 seconds, chosen randomly (per Gateway docs) |
| 1775 | setTimeout(function() { |
| 1776 | identifyOrResume(client); |
| 1777 | }, Math.random()*4000+1000); |
| 1778 | } else identifyOrResume(client); |
| 1779 | |
| 1780 | |
| 1781 | break; |
| 1782 | case 10: |
| 1783 | //Start keep-alive interval |
| 1784 | //Disconnect the client if no ping has been received |
| 1785 | //Since v3 you send the IDENTIFY/RESUME payload here. |
| 1786 | identifyOrResume(client); |
| 1787 | if(!client.presence) client.presence = { status: "online", since: Date.now() }; |
| 1788 | client.connected = true; |
| 1789 | |
| 1790 | client._mainKeepAlive = setInterval(function() { |
| 1791 | client.internals.heartbeat = setTimeout(function() { |
| 1792 | client._ws && client._ws.close(1001, "No heartbeat received"); |
| 1793 | }, _data.heartbeat_interval); |
| 1794 | client.internals._lastHB = Date.now(); |
| 1795 | send(client._ws, Payloads.HEARTBEAT(client)); |
| 1796 | }, _data.heartbeat_interval); |
| 1797 | break; |
| 1798 | case 11: |
| 1799 | clearTimeout(client.internals.heartbeat); |
| 1800 | client.internals._pings.unshift(Date.now() - client.internals._lastHB); |
| 1801 | client.internals._pings = client.internals._pings.slice(0, 10); |
| 1802 | break; |
| 1803 | } |
| 1804 | |
| 1805 | //Events |
| 1806 | client.emit('any', message); |
| 1807 | //TODO: Remove in v3 |
| 1808 | client.emit('debug', message); |
| 1809 | switch (message.t) { |
| 1810 | case "READY": |
| 1811 | copyKeys(_data.user, client); |
| 1812 | client.internals.sessionID = _data.session_id; |
| 1813 | |
| 1814 | getServerInfo(client, _data.guilds); |
| 1815 | getDirectMessages(client, _data.private_channels); |
| 1816 | |
| 1817 | if (client.bot) client.getOauthInfo(function(err, res) { |
| 1818 | if (err) return console.log(err); |
| 1819 | client.internals.oauth = res; |
| 1820 | client.inviteURL = "https://discordapp.com/oauth2/authorize?client_id=" + res.id + "&scope=bot"; |
| 1821 | }); |
| 1822 | if (!client.bot) client.getAccountSettings(function(err, res) { |
| 1823 | if (err) return console.log(err); |
| 1824 | client.internals.settings = res; |
| 1825 | }); |
| 1826 | |
| 1827 | return (function() { |
| 1828 | if (client._ready) return; |
| 1829 | var ready = [false]; |
| 1830 | setTimeout(function() { ready[0] = true; }, 3500); |
| 1831 | checkForAllServers(client, ready, message); |
| 1832 | })(); |
| 1833 | case "MESSAGE_CREATE": |
| 1834 | client.emit('message', _data.author.username, _data.author.id, _data.channel_id, _data.content, message); |
| 1835 | emit(client, message, _data.author.username, _data.author.id, _data.channel_id, _data.content); |
| 1836 | return cacheMessage(client._messageCache, client._messageCacheLimit, _data.channel_id, _data); |
| 1837 | case "MESSAGE_UPDATE": |
| 1838 | try { |
| 1839 | emit(client, message, client._messageCache[_data.channel_id][_data.id], _data); |
| 1840 | } catch (e) { emit(client, message, undefined, _data); } |
| 1841 | return cacheMessage(client._messageCache, client._messageCacheLimit, _data.channel_id, _data); |
| 1842 | case "PRESENCE_UPDATE": |
| 1843 | if (!_data.guild_id) break; |
| 1844 | |
| 1845 | serverID = _data.guild_id; |
| 1846 | userID = _data.user.id; |
| 1847 | |
| 1848 | if (!client.users[userID]) client.users[userID] = new User(_data.user); |
| 1849 | |
| 1850 | user = client.users[userID]; |
| 1851 | member = client.servers[serverID].members[userID] || {}; |
| 1852 | |
| 1853 | copyKeys(_data.user, user); |
| 1854 | user.game = _data.game; |
| 1855 | |
| 1856 | copyKeys(_data, member, ['user', 'guild_id', 'game']); |
| 1857 | client.emit('presence', user.username, user.id, member.status, user.game, message); |
| 1858 | break; |
| 1859 | case "USER_UPDATE": |
| 1860 | copyKeys(_data, client); |
| 1861 | break; |
| 1862 | case "USER_SETTINGS_UPDATE": |
| 1863 | copyKeys(_data, client.internals); |
| 1864 | break; |
| 1865 | case "GUILD_CREATE": |
| 1866 | /*The lib will attempt to create the server using the response from the |
| 1867 | REST API, if the user using the lib creates the server. There are missing keys, however. |
| 1868 | So we still need this GUILD_CREATE event to fill in the blanks. |
| 1869 | If It's not our created server, then there will be no server with that ID in the cache, |
| 1870 | So go ahead and create one.*/ |
| 1871 | client.servers[_data.id] = new Server(client, _data); |
| 1872 | return emit(client, message, client.servers[_data.id]); |
| 1873 | case "GUILD_UPDATE": |
| 1874 | old = copy(client.servers[_data.id]); |
| 1875 | Server.update(client, _data); |
| 1876 | return emit(client, message, old, client.servers[_data.id]); |
| 1877 | case "GUILD_DELETE": |
| 1878 | emit(client, message, client.servers[_data.id]); |
| 1879 | return delete(client.servers[_data.id]); |
| 1880 | case "GUILD_MEMBER_ADD": |
| 1881 | client.users[_data.user.id] = new User(_data.user); |
| 1882 | client.servers[_data.guild_id].members[_data.user.id] = new Member(client, client.servers[_data.guild_id], _data); |
| 1883 | client.servers[_data.guild_id].member_count += 1; |
| 1884 | return emit(client, message, client.servers[_data.guild_id].members[_data.user.id]); |
| 1885 | case "GUILD_MEMBER_UPDATE": |
| 1886 | old = copy(client.servers[_data.guild_id].members[_data.user.id]); |
| 1887 | Member.update(client, client.servers[_data.guild_id], _data); |
| 1888 | return emit(client, message, old, client.servers[_data.guild_id].members[_data.user.id]); |
| 1889 | case "GUILD_MEMBER_REMOVE": |
| 1890 | if (_data.user && _data.user.id === client.id) return; |
| 1891 | client.servers[_data.guild_id].member_count -= 1; |
| 1892 | emit(client, message, client.servers[_data.guild_id].members[_data.user.id]); |
| 1893 | return delete(client.servers[_data.guild_id].members[_data.user.id]); |
| 1894 | case "GUILD_ROLE_CREATE": |
| 1895 | client.servers[_data.guild_id].roles[_data.role.id] = new Role(_data.role); |
| 1896 | return emit(client, message, client.servers[_data.guild_id].roles[_data.role.id]); |
| 1897 | case "GUILD_ROLE_UPDATE": |
| 1898 | server = client.servers[_data.guild_id]; |
| 1899 | old = copy(server.roles[_data.role.id]); |
| 1900 | Role.update(server, _data); |
| 1901 | Object.keys(server.members).forEach(function(memberID) { |
| 1902 | var member = server.members[memberID]; |
| 1903 | if ( member.roles.indexOf(_data.role.id) < 0 ) return; |
| 1904 | member.color = colorFromRole(server, member); |
| 1905 | }); |
| 1906 | return emit(client, message, old, server.roles[_data.role.id]); |
| 1907 | case "GUILD_ROLE_DELETE": |
| 1908 | if (client.servers[_data.guild_id]){ |
| 1909 | emit(client, message, client.servers[_data.guild_id].roles[_data.role_id]); |
| 1910 | return delete(client.servers[_data.guild_id].roles[_data.role_id]); |
| 1911 | } |
| 1912 | break; |
| 1913 | case "CHANNEL_CREATE": |
| 1914 | channelID = _data.id; |
| 1915 | |
| 1916 | if (_data.type == 1) { |
| 1917 | if (client.directMessages[channelID]) return; |
| 1918 | client.directMessages[channelID] = new DMChannel(client._uIDToDM, _data); |
| 1919 | return emit(client, message, client.directMessages[channelID]); |
| 1920 | } |
| 1921 | |
| 1922 | if (client.channels[channelID]) return; |
| 1923 | client.channels[channelID] = new Channel(client, client.servers[_data.guild_id], _data); |
| 1924 | return emit(client, message, client.channels[channelID]); |
| 1925 | case "CHANNEL_UPDATE": |
| 1926 | old = copy(client.channels[_data.id]); |
| 1927 | Channel.update(client, _data); |
| 1928 | return emit(client, message, old, client.channels[_data.id]); |
| 1929 | case "CHANNEL_DELETE": |
| 1930 | if (_data.type == 1) { |
| 1931 | emit(client, message, client.directMessages[_data.id]); |
| 1932 | delete(client.directMessages[_data.id]); |
| 1933 | return delete(client._uIDToDM[_data.recipients[0].id]); |
| 1934 | } |
| 1935 | Object.keys(client.servers[_data.guild_id].members).forEach(function(m) { |
| 1936 | if (client.servers[_data.guild_id].members[m].voice_channel_id == _data.id) { |
| 1937 | client.servers[_data.guild_id].members[m].voice_channel_id = null; |
| 1938 | } |
| 1939 | }); |
| 1940 | emit(client, message, client.servers[_data.guild_id].channels[_data.id]); |
| 1941 | delete(client.servers[_data.guild_id].channels[_data.id]); |
| 1942 | return delete(client.channels[_data.id]); |
| 1943 | case "GUILD_EMOJIS_UPDATE": |
| 1944 | old = copy(client.servers[_data.guild_id].emojis); |
| 1945 | Emoji.update(client.servers[_data.guild_id], _data.emojis); |
| 1946 | return emit(client, message, old, client.servers[_data.guild_id].emojis); |
| 1947 | case "VOICE_STATE_UPDATE": |
| 1948 | serverID = _data.guild_id; |
| 1949 | channelID = _data.channel_id; |
| 1950 | userID = _data.user_id; |
| 1951 | server = client.servers[serverID]; |
| 1952 | mute = !!_data.mute; |
| 1953 | self_mute = !!_data.self_mute; |
| 1954 | deaf = !!_data.deaf; |
| 1955 | self_deaf = !!_data.self_deaf; |
| 1956 | |
| 1957 | try { |
| 1958 | currentVCID = server.members[userID].voice_channel_id; |
| 1959 | if (currentVCID) delete( server.channels[currentVCID].members[userID] ); |
| 1960 | if (channelID) server.channels[channelID].members[userID] = _data; |
| 1961 | server.members[userID].mute = (mute || self_mute); |
| 1962 | server.members[userID].deaf = (deaf || self_deaf); |
| 1963 | server.members[userID].voice_channel_id = channelID; |
| 1964 | } catch(e) {} |
| 1965 | |
| 1966 | if (userID === client.id) { |
| 1967 | server.self_mute = self_mute; |
| 1968 | server.self_deaf = self_deaf; |
| 1969 | if (channelID === null) { |
| 1970 | if (server.voiceSession) leaveVoiceChannel(client, server.voiceSession.channelID); |
| 1971 | server.voiceSession = null; |
| 1972 | } else { |
| 1973 | if (!server.voiceSession) { |
| 1974 | server.voiceSession = getVoiceSession(client, channelID, server); |
| 1975 | } |
| 1976 | if (channelID !== server.voiceSession.channelID) { |
| 1977 | delete( client._vChannels[server.voiceSession.channelID] ); |
| 1978 | getVoiceSession(client, channelID, server).channelID = channelID; |
| 1979 | } |
| 1980 | |
| 1981 | server.voiceSession.session = _data.session_id; |
| 1982 | server.voiceSession.self_mute = self_mute; |
| 1983 | server.voiceSession.self_deaf = self_deaf; |
| 1984 | } |
| 1985 | } |
| 1986 | break; |
| 1987 | case "VOICE_SERVER_UPDATE": |
| 1988 | serverID = _data.guild_id; |
| 1989 | server = client.servers[serverID]; |
| 1990 | server.voiceSession.token = _data.token; |
| 1991 | server.voiceSession.severID = serverID; |
| 1992 | server.voiceSession.endpoint = _data.endpoint; |
| 1993 | joinVoiceChannel(client, server.voiceSession); |
| 1994 | break; |
| 1995 | case "GUILD_MEMBERS_CHUNK": |
| 1996 | serverID = _data.guild_id; |
| 1997 | if (!client.servers[serverID].members) client.servers[serverID].members = {}; |
| 1998 | |
| 1999 | _data.members.forEach(function(member) { |
| 2000 | var uID = member.user.id; |
| 2001 | var members = client.servers[serverID].members; |
| 2002 | if (members[uID]) return; |
| 2003 | if (!client.users[uID]) client.users[uID] = new User(member.user); |
| 2004 | members[uID] = new Member(client, client.servers[serverID], member); |
| 2005 | }); |
| 2006 | var all = Object.keys(client.servers).every(function(server) { |
| 2007 | server = client.servers[server]; |
| 2008 | return server.member_count === Object.keys(server.members).length; |
| 2009 | }); |
| 2010 | |
| 2011 | if (all) return client.emit("allUsers"); |
| 2012 | break; |
| 2013 | case "GUILD_SYNC": |
| 2014 | _data.members.forEach(function(member) { |
| 2015 | var uID = member.user.id; |
| 2016 | if (!client.users[uID]) client.users[uID] = new User(member.user); |
| 2017 | client.servers[_data.id].members[uID] = new Member(client, client.servers[_data.id], member); |
| 2018 | }); |
| 2019 | |
| 2020 | _data.presences.forEach(function(presence) { |
| 2021 | var uID = presence.user.id; |
| 2022 | var members = client.servers[_data.id].members; |
| 2023 | if (!members[uID]) return void(new User(presence.user)); |
| 2024 | delete(presence.user); |
| 2025 | copyKeys(presence, members[uID]); |
| 2026 | }); |
| 2027 | client.servers[_data.id].large = _data.large; |
| 2028 | break; |
| 2029 | } |
| 2030 | return emit(client, message); |
| 2031 | } |
| 2032 | function handleWSClose(code, data) { |
| 2033 | var client = this; |
| 2034 | var eMsg = Discord.Codes.WebSocket[code] || data; |
| 2035 | |
| 2036 | clearInterval(client._mainKeepAlive); |
| 2037 | client.connected = false; |
| 2038 | removeAllListeners(client._ws, 'message'); |
| 2039 | |
| 2040 | if ([1001, 1006].indexOf(code) > -1) return getGateway(client, client.internals.token); |
| 2041 | |
| 2042 | client._ready = false; |
| 2043 | client._ws = null; |
| 2044 | |
| 2045 | client.emit("disconnect", eMsg, code); |
| 2046 | } |
| 2047 | |
| 2048 | /* - Functions - Voice - */ |
| 2049 | function joinVoiceChannel(client, voiceSession) { |
| 2050 | var vWS, vUDP, endpoint = voiceSession.endpoint.split(":")[0]; |
| 2051 | //handleVoiceChannelChange(client, voiceSession); |
| 2052 | |
| 2053 | voiceSession.ws = {}; |
| 2054 | voiceSession.udp = {}; |
| 2055 | voiceSession.members = {}; |
| 2056 | voiceSession.error = null; |
| 2057 | voiceSession.ready = false; |
| 2058 | voiceSession.joined = false; |
| 2059 | voiceSession.translator = {}; |
| 2060 | voiceSession.wsKeepAlive = null; |
| 2061 | voiceSession.udpKeepAlive = null; |
| 2062 | voiceSession.keepAlivePackets = 0; |
| 2063 | voiceSession.emitter = new Emitter(); |
| 2064 | if (isNode) voiceSession.keepAliveBuffer = new Buffer(8).fill(0); |
| 2065 | vWS = voiceSession.ws.connection = new Websocket("wss://" + endpoint); |
| 2066 | |
| 2067 | if (isNode) return DNS.lookup(endpoint, function(err, address) { |
| 2068 | if (err) return void(voiceSession.error = err); |
| 2069 | |
| 2070 | voiceSession.address = address; |
| 2071 | vUDP = voiceSession.udp.connection = UDP.createSocket("udp4"); |
| 2072 | |
| 2073 | vUDP.bind({exclusive: true}); |
| 2074 | vUDP.once('message', handleUDPMessage.bind(client, voiceSession)); |
| 2075 | |
| 2076 | vWS.once('open', handlevWSOpen.bind(client, voiceSession)); |
| 2077 | vWS.on('message', handlevWSMessage.bind(client, voiceSession)); |
| 2078 | vWS.once('close', handlevWSClose.bind(client, voiceSession)); |
| 2079 | }); |
| 2080 | |
| 2081 | vWS.once('open', handlevWSOpen.bind(client, voiceSession)); |
| 2082 | vWS.on('message', handlevWSMessage.bind(client, voiceSession)); |
| 2083 | vWS.once('close', handlevWSClose.bind(client, voiceSession)); |
| 2084 | return void(voiceSession.joined = true); |
| 2085 | } |
| 2086 | |
| 2087 | function leaveVoiceChannel(client, channelID, callback) { |
| 2088 | if (!client._vChannels[channelID]) return; |
| 2089 | |
| 2090 | try { |
| 2091 | client._vChannels[channelID].ws.connection.close(); |
| 2092 | client._vChannels[channelID].udp.connection.close(); |
| 2093 | } catch(e) {} |
| 2094 | |
| 2095 | send(client._ws, Payloads.UPDATE_VOICE(client.channels[channelID].guild_id, null, false, false)); |
| 2096 | |
| 2097 | return call(callback, [null]); |
| 2098 | } |
| 2099 | |
| 2100 | function keepUDPAlive(VS) { |
| 2101 | if (!VS.keepAliveBuffer) return; |
| 2102 | |
| 2103 | if (VS.keepAlivePackets > 4294967294) { |
| 2104 | VS.keepAlivePackets = 0; |
| 2105 | VS.keepAliveBuffer.fill(0); |
| 2106 | } |
| 2107 | VS.keepAliveBuffer.writeUIntLE(++VS.keepAlivePackets, 0, 6); |
| 2108 | try { |
| 2109 | return VS.udp.connection.send(VS.keepAliveBuffer, 0, VS.keepAliveBuffer.length, VS.ws.port, VS.address); |
| 2110 | } catch(e) {} |
| 2111 | } |
| 2112 | |
| 2113 | function getVoiceSession(client, channelID, server) { |
| 2114 | if (!channelID) return null; |
| 2115 | return client._vChannels[channelID] ? |
| 2116 | client._vChannels[channelID] : |
| 2117 | client._vChannels[channelID] = (server && server.voiceSession) || { |
| 2118 | serverID: (server && server.id) || null, |
| 2119 | channelID: channelID, |
| 2120 | token: null, |
| 2121 | session: null, |
| 2122 | endpoint: null, |
| 2123 | self_mute: false, |
| 2124 | self_deaf: false |
| 2125 | }; |
| 2126 | } |
| 2127 | |
| 2128 | function checkVoiceReady(voiceSession, callback) { |
| 2129 | return setTimeout(function() { |
| 2130 | if (voiceSession.error) return call(callback, [voiceSession.error]); |
| 2131 | if (voiceSession.joined) return call(callback, [null, voiceSession.emitter]); |
| 2132 | return checkVoiceReady(voiceSession, callback); |
| 2133 | }, 1); |
| 2134 | } |
| 2135 | |
| 2136 | /* - Functions - Voice - Handling - */ |
| 2137 | |
| 2138 | function handlevWSOpen(voiceSession) { |
| 2139 | return send(voiceSession.ws.connection, Payloads.VOICE_IDENTIFY(this.id, voiceSession)); |
| 2140 | } |
| 2141 | function handlevWSMessage(voiceSession, vMessage, vFlags) { |
| 2142 | var client = this, vData = decompressWSMessage(vMessage, vFlags); |
| 2143 | switch (vData.op) { |
| 2144 | case 2: //Ready (Actually means you're READY to initiate the UDP connection) |
| 2145 | copyKeys(vData.d, voiceSession.ws); |
| 2146 | voiceSession.wsKeepAlive = setInterval(send, vData.d.heartbeat_interval, voiceSession.ws.connection, { "op": 3, "d": null }); |
| 2147 | |
| 2148 | if (!isNode) return; |
| 2149 | |
| 2150 | var udpDiscPacket = new Buffer(70); |
| 2151 | udpDiscPacket.writeUIntBE(vData.d.ssrc, 0, 4); |
| 2152 | voiceSession.udp.connection.send( |
| 2153 | udpDiscPacket, 0, udpDiscPacket.length, vData.d.port, voiceSession.address, |
| 2154 | function(err) { if (err) {leaveVoiceChannel(client, voiceSession.channelID); handleErrCB("UDP discovery error", callback); } } |
| 2155 | ); |
| 2156 | |
| 2157 | voiceSession.udpKeepAlive = setInterval(keepUDPAlive, 5000, voiceSession); |
| 2158 | break; |
| 2159 | case 4: //Session Discription (Actually means you're ready to send audio... stupid Discord Devs :I) |
| 2160 | voiceSession.selectedMode = vData.d.mode; |
| 2161 | voiceSession.secretKey = vData.d.secret_key; |
| 2162 | voiceSession.joined = true; |
| 2163 | voiceSession.ready = true; |
| 2164 | break; |
| 2165 | case 5: //Speaking (At least this isn't confusing!) |
| 2166 | voiceSession.emitter.emit('speaking', vData.d.user_id, vData.d.ssrc, vData.d.speaking); |
| 2167 | break; |
| 2168 | } |
| 2169 | } |
| 2170 | function handlevWSClose(voiceSession) { |
| 2171 | //Emit the disconnect event first |
| 2172 | voiceSession.emitter.emit("disconnect", voiceSession.channelID); |
| 2173 | voiceSession.emitter = null |
| 2174 | //Kill encoder and decoders |
| 2175 | var audio = voiceSession.audio, members = voiceSession.members; |
| 2176 | if (audio) { |
| 2177 | if (audio._systemEncoder) audio._systemEncoder.kill(); |
| 2178 | if (audio._mixedDecoder) audio._mixedDecoder.destroy(); |
| 2179 | } |
| 2180 | |
| 2181 | Object.keys(members).forEach(function(ID) { |
| 2182 | var member = members[ID]; |
| 2183 | if (member.decoder) member.decoder.destroy(); |
| 2184 | }); |
| 2185 | |
| 2186 | //Clear intervals and remove listeners |
| 2187 | clearInterval(voiceSession.wsKeepAlive); |
| 2188 | clearInterval(voiceSession.udpKeepAlive); |
| 2189 | removeAllListeners(voiceSession.emitter); |
| 2190 | removeAllListeners(voiceSession.udp.connection, 'message'); |
| 2191 | removeAllListeners(voiceSession.ws.connection, 'message'); |
| 2192 | |
| 2193 | return delete(this._vChannels[voiceSession.channelID]); |
| 2194 | } |
| 2195 | |
| 2196 | function handleUDPMessage(voiceSession, msg, rinfo) { |
| 2197 | var buffArr = JSON.parse(JSON.stringify(msg)).data, client = this, vDiscIP = "", vDiscPort; |
| 2198 | for (var i=4; i<buffArr.indexOf(0, i); i++) { |
| 2199 | vDiscIP += String.fromCharCode(buffArr[i]); |
| 2200 | } |
| 2201 | vDiscPort = msg.readUIntLE(msg.length - 2, 2).toString(10); |
| 2202 | return send(voiceSession.ws.connection, Payloads.VOICE_DISCOVERY(vDiscIP, vDiscPort, 'xsalsa20_poly1305')); |
| 2203 | } |
| 2204 | |
| 2205 | /* - Functions - Voice - AudioCallback - */ |
| 2206 | function AudioCB(voiceSession, audioChannels, encoder, maxStreamSize) { |
| 2207 | //With the addition of the new Stream API, `playAudioFile`, `stopAudioFile` and `send` |
| 2208 | //will be removed. However they're deprecated for now, hence the code repetition. |
| 2209 | if (maxStreamSize && !Opus) Opus = require('cjopus'); |
| 2210 | Stream.Duplex.call(this); |
| 2211 | var ACBI = this; |
| 2212 | |
| 2213 | this.audioChannels = audioChannels; |
| 2214 | this.members = voiceSession.members; |
| 2215 | |
| 2216 | applyProperties(this, [ |
| 2217 | ["_sequence", 0], |
| 2218 | ["_timestamp", 0], |
| 2219 | ["_readable", false], |
| 2220 | ["_streamRef", null], |
| 2221 | ["_startTime", null], |
| 2222 | ["_systemEncoder", null], |
| 2223 | ["_playingAudioFile", false], |
| 2224 | ["_voiceSession", voiceSession], |
| 2225 | ["_port", voiceSession.ws.port], |
| 2226 | ["_address", voiceSession.address], |
| 2227 | ["_decodeNonce", new Uint8Array(24)], |
| 2228 | ["_vUDP", voiceSession.udp.connection], |
| 2229 | ["_secretKey", new Uint8Array(voiceSession.secretKey)], |
| 2230 | ["_mixedDecoder", Opus && new Opus.OpusEncoder( 48000, audioChannels ) || null] |
| 2231 | ]); |
| 2232 | |
| 2233 | createAudioEncoder(this, encoder); |
| 2234 | |
| 2235 | this._write = function _write(chunk, encoding, callback) { |
| 2236 | ACBI._systemEncoder.stdin.write(chunk); |
| 2237 | return callback(); |
| 2238 | }; |
| 2239 | this._read = function _read() {}; |
| 2240 | this.stop = function stop() { |
| 2241 | return this._systemEncoder.stdout.read = function() { return null }; |
| 2242 | }; |
| 2243 | |
| 2244 | if (maxStreamSize) { |
| 2245 | voiceSession.ws.connection.on('message', function(data, flags) { |
| 2246 | data = decompressWSMessage(data, flags); |
| 2247 | |
| 2248 | if (data.op !== 5) return; |
| 2249 | if (!voiceSession.members[data.d.user_id]) { |
| 2250 | voiceSession.members[data.d.user_id] = new Stream.Readable({ |
| 2251 | highWaterMark: maxStreamSize, |
| 2252 | read: function(s) {} |
| 2253 | }); |
| 2254 | voiceSession.members[data.d.user_id].decoder = new Opus.OpusEncoder( 48000, ACBI.audioChannels ); |
| 2255 | ACBI.emit('newMemberStream', data.d.user_id, voiceSession.members[data.d.user_id]); |
| 2256 | } |
| 2257 | |
| 2258 | voiceSession.members[data.d.user_id].ssrc = data.d.ssrc; |
| 2259 | voiceSession.translator[data.d.ssrc] = voiceSession.members[data.d.user_id]; |
| 2260 | }); |
| 2261 | this._vUDP.on('message', handleIncomingAudio.bind(this)); |
| 2262 | } |
| 2263 | } |
| 2264 | if (isNode) Util.inherits(AudioCB, Stream.Duplex); |
| 2265 | AudioCB.VoicePacket = (function() { |
| 2266 | if (!isNode) return; |
| 2267 | var header = new Buffer(12), nonce = new Uint8Array(24), output = new Buffer(2048); |
| 2268 | |
| 2269 | header[0] = 0x80; |
| 2270 | header[1] = 0x78; |
| 2271 | |
| 2272 | return function(packet, ssrc, sequence, timestamp, key) { |
| 2273 | header.writeUIntBE(sequence, 2, 2); |
| 2274 | header.writeUIntBE(timestamp, 4, 4); |
| 2275 | header.writeUIntBE(ssrc, 8, 4); |
| 2276 | //<Buffer 80 78 00 01 00 00 03 c0 00 00 00 01> |
| 2277 | nonce.set(header); |
| 2278 | //<Buffer 80 78 00 01 00 00 03 c0 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00> |
| 2279 | |
| 2280 | var encrypted = new Buffer( |
| 2281 | NACL.secretbox( |
| 2282 | new Uint8Array(packet), |
| 2283 | nonce, |
| 2284 | key |
| 2285 | ) |
| 2286 | ); |
| 2287 | |
| 2288 | header.copy(output); |
| 2289 | encrypted.copy(output, 12); |
| 2290 | |
| 2291 | return output.slice(0, header.length + encrypted.length); |
| 2292 | }; |
| 2293 | })(); |
| 2294 | var ACBP = AudioCB.prototype; |
| 2295 | //TODO: Remove in v3 |
| 2296 | ACBP.playAudioFile = function(location, callback) { |
| 2297 | if (!this._mixedDecoder) { |
| 2298 | if (!Opus) Opus = require('cjopus'); |
| 2299 | this._mixedDecoder = new Opus.OpusEncoder( 48000, this.audioChannels ); |
| 2300 | } |
| 2301 | |
| 2302 | if (this._playingAudioFile) return handleErrCB("There is already a file being played.", callback); |
| 2303 | var encs = ['ffmpeg', 'avconv'], selection, enc, ACBI = this; |
| 2304 | |
| 2305 | this._playingAudioFile = true; |
| 2306 | selection = chooseAudioEncoder(encs); |
| 2307 | |
| 2308 | if (!selection) return console.log("You need either 'ffmpeg' or 'avconv' and they need to be added to PATH"); |
| 2309 | |
| 2310 | enc = ChildProc.spawn(selection , [ |
| 2311 | '-i', location, |
| 2312 | '-f', 's16le', |
| 2313 | '-ar', '48000', |
| 2314 | '-ac', ACBI.audioChannels, |
| 2315 | 'pipe:1' |
| 2316 | ], {stdio: ['pipe', 'pipe', 'ignore']}); |
| 2317 | enc.stdout.once('end', function() { |
| 2318 | enc.kill(); |
| 2319 | send(ACBI._voiceSession.ws.connection, Payloads.VOICE_SPEAK(0)); |
| 2320 | ACBI._playingAudioFile = false; |
| 2321 | ACBI.emit('fileEnd'); |
| 2322 | }); |
| 2323 | enc.stdout.once('error', function(e) { |
| 2324 | enc.stdout.emit('end'); |
| 2325 | }); |
| 2326 | enc.stdout.once('readable', function() { |
| 2327 | send(ACBI._voiceSession.ws.connection, Payloads.VOICE_SPEAK(1)); |
| 2328 | ACBI._startTime = new Date().getTime(); |
| 2329 | prepareAudioOld(ACBI, enc.stdout, 1); |
| 2330 | }); |
| 2331 | this._streamRef = enc; |
| 2332 | }; |
| 2333 | //TODO: Remove in v3 |
| 2334 | ACBP.stopAudioFile = function(callback) { |
| 2335 | if (!this._playingAudioFile) return handleErrCB("There is no file being played", callback); |
| 2336 | |
| 2337 | this._streamRef.stdout.end(); |
| 2338 | this._streamRef.kill(); |
| 2339 | this._playingAudioFile = false; |
| 2340 | |
| 2341 | call(callback); |
| 2342 | }; |
| 2343 | //TODO: Remove in v3 |
| 2344 | ACBP.send = function(stream) { |
| 2345 | if (!this._mixedDecoder) { |
| 2346 | if (!Opus) Opus = require('cjopus'); |
| 2347 | this._mixedDecoder = new Opus.OpusEncoder( 48000, this.audioChannels ); |
| 2348 | } |
| 2349 | send(this._voiceSession.ws.connection, Payloads.VOICE_SPEAK(1)); |
| 2350 | this._startTime = new Date().getTime(); |
| 2351 | prepareAudioOld(this, stream, 1); |
| 2352 | }; |
| 2353 | |
| 2354 | function prepareAudio(ACBI, readableStream, cnt) { |
| 2355 | var data = readableStream.read( 320 ) || readableStream.read(); //(128 [kb] * 20 [frame_size]) / 8 == 320 |
| 2356 | |
| 2357 | if (!data) { |
| 2358 | send(ACBI._voiceSession.ws.connection, Payloads.VOICE_SPEAK(0)); |
| 2359 | ACBI._readable = false; |
| 2360 | return readableStream.emit('end'); |
| 2361 | } |
| 2362 | |
| 2363 | return setTimeout(function() { |
| 2364 | sendAudio(ACBI, data); |
| 2365 | prepareAudio(ACBI, readableStream, cnt + 1); |
| 2366 | }, 20 + ( (ACBI._startTime + cnt * 20) - Date.now() )); |
| 2367 | } |
| 2368 | |
| 2369 | //TODO: Remove in v3 |
| 2370 | function prepareAudioOld(ACBI, readableStream) { |
| 2371 | var done = false; |
| 2372 | |
| 2373 | readableStream.on('end', function() { |
| 2374 | done = true; |
| 2375 | send(ACBI._voiceSession.ws.connection, Payloads.VOICE_SPEAK(0)); |
| 2376 | }); |
| 2377 | |
| 2378 | _prepareAudio(ACBI, readableStream, 1); |
| 2379 | |
| 2380 | function _prepareAudio(ACBI, readableStream, cnt) { |
| 2381 | if (done) return; |
| 2382 | var buffer, encoded; |
| 2383 | |
| 2384 | buffer = readableStream.read( 1920 * ACBI.audioChannels ); |
| 2385 | encoded = [0xF8, 0xFF, 0xFE]; |
| 2386 | |
| 2387 | if ((buffer && buffer.length === 1920 * ACBI.audioChannels) && !ACBI._mixedDecoder.destroyed) { |
| 2388 | encoded = ACBI._mixedDecoder.encode(buffer); |
| 2389 | } |
| 2390 | |
| 2391 | return setTimeout(function() { |
| 2392 | sendAudio(ACBI, encoded); |
| 2393 | _prepareAudio(ACBI, readableStream, cnt + 1); |
| 2394 | }, 20 + ( (ACBI._startTime + cnt * 20) - Date.now() )); |
| 2395 | } |
| 2396 | } |
| 2397 | |
| 2398 | function sendAudio(ACBI, buffer) { |
| 2399 | ACBI._sequence = (ACBI._sequence + 1 ) < 0xFFFF ? ACBI._sequence + 1 : 0; |
| 2400 | ACBI._timestamp = (ACBI._timestamp + 960) < 0xFFFFFFFF ? ACBI._timestamp + 960 : 0; |
| 2401 | if (ACBI._voiceSession.self_mute) return; |
| 2402 | var audioPacket = AudioCB.VoicePacket(buffer, ACBI._voiceSession.ws.ssrc, ACBI._sequence, ACBI._timestamp, ACBI._secretKey); |
| 2403 | |
| 2404 | try { |
| 2405 | //It throws a synchronous error if it fails (someone leaves the audio channel while playing audio) |
| 2406 | ACBI._vUDP.send(audioPacket, 0, audioPacket.length, ACBI._port, ACBI._address); |
| 2407 | } catch(e) { return; } |
| 2408 | } |
| 2409 | |
| 2410 | function handleIncomingAudio(msg) { |
| 2411 | //The response from the UDP keep alive ping |
| 2412 | if (msg.length === 8 || this._voiceSession.self_deaf) return; |
| 2413 | |
| 2414 | var header = msg.slice(0, 12), |
| 2415 | audio = msg.slice(12), |
| 2416 | ssrc = header.readUIntBE(8, 4), |
| 2417 | member = this._voiceSession.translator[ssrc], |
| 2418 | decrypted, decoded; |
| 2419 | |
| 2420 | this._decodeNonce.set(header); |
| 2421 | |
| 2422 | try { |
| 2423 | decrypted = new Buffer( |
| 2424 | NACL.secretbox.open( |
| 2425 | new Uint8Array(audio), |
| 2426 | this._decodeNonce, |
| 2427 | this._secretKey |
| 2428 | ) |
| 2429 | ); |
| 2430 | |
| 2431 | if (member) { |
| 2432 | decoded = member.decoder.decode(decrypted); |
| 2433 | addToStreamBuffer(member, decoded); |
| 2434 | } else { |
| 2435 | decoded = this._mixedDecoder.decode(decrypted); |
| 2436 | } |
| 2437 | |
| 2438 | addToStreamBuffer(this, decoded); |
| 2439 | this.emit('incoming', ssrc, decoded ); |
| 2440 | } catch(e) {} |
| 2441 | } |
| 2442 | function addToStreamBuffer(RStream, data) { |
| 2443 | return RStream.push(new Buffer(data)) || !!RStream.read(data.length); |
| 2444 | } |
| 2445 | |
| 2446 | function chooseAudioEncoder(players) { |
| 2447 | if (!players[0]) return null; |
| 2448 | var file = players.shift(); |
| 2449 | var s = ChildProc.spawnSync(file); |
| 2450 | return s.error ? chooseAudioEncoder(players) : file; |
| 2451 | } |
| 2452 | function createAudioEncoder(ACBI, encoder) { |
| 2453 | var enc = ACBI._systemEncoder; |
| 2454 | if (enc) { |
| 2455 | enc.stdout.emit('end'); |
| 2456 | enc.kill(); |
| 2457 | ACBI._systemEncoder = null; |
| 2458 | } |
| 2459 | |
| 2460 | enc = ACBI._systemEncoder = ChildProc.spawn(encoder, [ |
| 2461 | '-hide_banner', |
| 2462 | '-loglevel', 'error', |
| 2463 | '-i', 'pipe:0', |
| 2464 | '-map', '0:a', |
| 2465 | '-acodec', 'libopus', |
| 2466 | '-f', 'data', |
| 2467 | '-sample_fmt', 's16', |
| 2468 | '-vbr', 'off', |
| 2469 | '-compression_level', '10', |
| 2470 | '-ar', '48000', |
| 2471 | '-ac', ACBI.audioChannels, |
| 2472 | '-b:a', '128000', |
| 2473 | 'pipe:1' |
| 2474 | ], {stdio: ['pipe', 'pipe', 'pipe']}); |
| 2475 | |
| 2476 | enc.stderr.once('data', function(d) { |
| 2477 | if (ACBI.listeners('error').length > 0) ACBI.emit('error', d.toString()); |
| 2478 | }); |
| 2479 | |
| 2480 | enc.stdin.once('error', function(e) { |
| 2481 | enc.stdout.emit('end'); |
| 2482 | enc.kill(); |
| 2483 | }); |
| 2484 | |
| 2485 | enc.stdout.once('error', function(e) { |
| 2486 | enc.stdout.emit('end'); |
| 2487 | enc.kill(); |
| 2488 | }); |
| 2489 | enc.stdout.once('end', function() { |
| 2490 | createAudioEncoder(ACBI, encoder); |
| 2491 | ACBI.emit('done'); |
| 2492 | }); |
| 2493 | enc.stdout.on('readable', function() { |
| 2494 | if (ACBI._readable) return; |
| 2495 | |
| 2496 | ACBI._readable = true; |
| 2497 | send(ACBI._voiceSession.ws.connection, Payloads.VOICE_SPEAK(1)); |
| 2498 | ACBI._startTime = new Date().getTime(); |
| 2499 | prepareAudio(ACBI, enc.stdout, 1); |
| 2500 | }); |
| 2501 | } |
| 2502 | |
| 2503 | /* - DiscordClient - Classes - */ |
| 2504 | function Resource() {} |
| 2505 | Object.defineProperty(Resource.prototype, "creationTime", { |
| 2506 | get: function() { return (+this.id / 4194304) + 1420070400000; }, |
| 2507 | set: function() {} |
| 2508 | }); |
| 2509 | [Server, Channel, DMChannel, User, Member, Role].forEach(function(p) { |
| 2510 | p.prototype = Object.create(Resource.prototype); |
| 2511 | Object.defineProperty(p.prototype, 'constructor', {value: p, enumerable: false}); |
| 2512 | }); |
| 2513 | |
| 2514 | function Server(client, data) { |
| 2515 | var server = this; |
| 2516 | //Accept everything now and trim what we don't need, manually. Any data left in is fine, any data left out could lead to a broken lib. |
| 2517 | copyKeys(data, this); |
| 2518 | this.large = this.large || this.member_count > LARGE_THRESHOLD; |
| 2519 | this.voiceSession = null; |
| 2520 | this.self_mute = !!this.self_mute; |
| 2521 | this.self_deaf = !!this.self_deaf; |
| 2522 | if (data.unavailable) return; |
| 2523 | |
| 2524 | //Objects so we can use direct property accessing without for loops |
| 2525 | this.channels = {}; |
| 2526 | this.members = {}; |
| 2527 | this.roles = {}; |
| 2528 | this.emojis = {}; |
| 2529 | |
| 2530 | //Copy the data into the objects using IDs as keys |
| 2531 | data.channels.forEach(function(channel) { |
| 2532 | client.channels[channel.id] = new Channel(client, server, channel); |
| 2533 | }); |
| 2534 | data.roles.forEach(function(role) { |
| 2535 | server.roles[role.id] = new Role(role); |
| 2536 | }); |
| 2537 | data.members.forEach(function(member) { |
| 2538 | client.users[member.user.id] = new User(member.user); |
| 2539 | server.members[member.user.id] = new Member(client, server, member); |
| 2540 | }); |
| 2541 | data.presences.forEach(function(presence) { |
| 2542 | var id = presence.user.id; |
| 2543 | if (!client.users[id] || !server.members[id]) return; |
| 2544 | delete(presence.user); |
| 2545 | |
| 2546 | client.users[id].game = presence.game; |
| 2547 | server.members[id].status = presence.status; |
| 2548 | }); |
| 2549 | data.emojis.forEach(function(emoji) { |
| 2550 | server.emojis[emoji.id] = new Emoji(emoji); |
| 2551 | }); |
| 2552 | data.voice_states.forEach(function(vs) { |
| 2553 | var cID = vs.channel_id; |
| 2554 | var uID = vs.user_id; |
| 2555 | if (!server.channels[cID] || !server.members[uID]) return; |
| 2556 | server.channels[cID].members[uID] = vs; |
| 2557 | server.members[uID].voice_channel_id = cID; |
| 2558 | }); |
| 2559 | |
| 2560 | //Now we can get rid of any of the things we don't need anymore |
| 2561 | delete(this.voice_states); |
| 2562 | delete(this.presences); |
| 2563 | } |
| 2564 | function Channel(client, server, data) { |
| 2565 | var channel = this; |
| 2566 | this.members = {}; |
| 2567 | this.permissions = { user: {}, role: {} }; |
| 2568 | this.guild_id = server.id; |
| 2569 | copyKeys(data, this, ['permission_overwrites', 'emojis']); |
| 2570 | Object.defineProperty(server.channels, channel.id, { |
| 2571 | get: function() { return client.channels[channel.id]; }, |
| 2572 | set: function(v) { client.channels[channel.id] = v; }, |
| 2573 | enumerable: true, |
| 2574 | configurable: true |
| 2575 | }); |
| 2576 | data.permission_overwrites.forEach(function(p) { |
| 2577 | var type = (p.type === 'member' ? 'user' : 'role'); |
| 2578 | this.permissions[type][p.id] = {allow: p.allow, deny: p.deny}; |
| 2579 | }, this); |
| 2580 | } |
| 2581 | function DMChannel(translator, data) { |
| 2582 | copyKeys(data, this); |
| 2583 | this.recipient = data.recipients[0]; |
| 2584 | data.recipients.forEach(function(recipient) { |
| 2585 | translator[recipient.id] = data.id; |
| 2586 | }); |
| 2587 | } |
| 2588 | function User(data) { |
| 2589 | copyKeys(data, this); |
| 2590 | this.bot = this.bot || false; |
| 2591 | } |
| 2592 | function Member(client, server, data) { |
| 2593 | copyKeys(data, this, ['user', 'joined_at',]); |
| 2594 | this.id = data.user.id; |
| 2595 | this.joined_at = Date.parse(data.joined_at); |
| 2596 | this.color = colorFromRole(server, this); |
| 2597 | ['username', 'discriminator', 'bot', 'avatar', 'game'].forEach(function(k) { |
| 2598 | if (k in Member.prototype) return; |
| 2599 | |
| 2600 | Object.defineProperty(Member.prototype, k, { |
| 2601 | get: function() { return client.users[this.id][k]; }, |
| 2602 | set: function(v) { client.users[this.id][k] = v; }, |
| 2603 | enumerable: true, |
| 2604 | }); |
| 2605 | }); |
| 2606 | } |
| 2607 | function Role(data) { |
| 2608 | copyKeys(data, this, ['permissions']); |
| 2609 | //Use `permissions` from Discord, or `_permissions` if we're making it out of a cache. |
| 2610 | this._permissions = data._permissions || data.permissions; |
| 2611 | } |
| 2612 | function Emoji(data) { |
| 2613 | copyKeys(data, this); |
| 2614 | } |
| 2615 | |
| 2616 | function Multipart() { |
| 2617 | this.boundary = |
| 2618 | "NodeDiscordIO" + "-" + CURRENT_VERSION; |
| 2619 | this.result = ""; |
| 2620 | } |
| 2621 | Multipart.prototype.append = function(data) { |
| 2622 | /* Header */ |
| 2623 | var str = "\r\n--"; |
| 2624 | str += this.boundary + "\r\n"; |
| 2625 | str += 'Content-Disposition: form-data; name="' + data[0] + '"'; |
| 2626 | if (data[2]) { |
| 2627 | str += '; filename="' + data[2] + '"\r\n'; |
| 2628 | str += 'Content-Type: application/octet-stream'; |
| 2629 | } |
| 2630 | /* Body */ |
| 2631 | str += "\r\n\r\n" + ( data[1] instanceof Buffer ? data[1] : new Buffer(String(data[1]), 'utf-8') ).toString('binary'); |
| 2632 | this.result += str; |
| 2633 | }; |
| 2634 | Multipart.prototype.finalize = function() { |
| 2635 | this.result += "\r\n--" + this.boundary + "--"; |
| 2636 | }; |
| 2637 | |
| 2638 | Server.update = function(client, data) { |
| 2639 | if (!client.servers[data.id]) client.servers[data.id] = {}; // new Server(client, data)? |
| 2640 | for (var key in data) { |
| 2641 | if (key === 'roles') { |
| 2642 | data[key].forEach(function(r) { |
| 2643 | client.servers[data.id].roles[r.id] = new Role(r); |
| 2644 | }); |
| 2645 | continue; |
| 2646 | } |
| 2647 | if (key === 'emojis') continue; |
| 2648 | client.servers[data.id][key] = data[key]; |
| 2649 | } |
| 2650 | }; |
| 2651 | Channel.update = function(client, data) { |
| 2652 | if (!client.channels[data.id]) client.channels[data.id] = {}; // new Channel(client, data)? |
| 2653 | for (var key in data) { |
| 2654 | if (key === 'permission_overwrites') { |
| 2655 | data[key].forEach(function(p) { |
| 2656 | var type = (p.type === 'member' ? 'user' : 'role'); |
| 2657 | client.channels[data.id].permissions[type][p.id] = { |
| 2658 | allow: p.allow, |
| 2659 | deny: p.deny |
| 2660 | }; |
| 2661 | }); |
| 2662 | continue; |
| 2663 | } |
| 2664 | client.channels[data.id][key] = data[key]; |
| 2665 | } |
| 2666 | }; |
| 2667 | Member.update = function(client, server, data) { |
| 2668 | if (!server.members[data.user.id]) return server.members[data.user.id] = new Member(client, server, data); |
| 2669 | var member = server.members[data.user.id]; |
| 2670 | copyKeys(data, member, ['user']); |
| 2671 | member.color = colorFromRole(server, member); |
| 2672 | }; |
| 2673 | Role.update = function(server, data) { |
| 2674 | if (!server.roles[data.role.id]) server.roles[data.role.id] = {}; // new Role(data)? |
| 2675 | server.roles[data.role.id]._permissions = data.role.permissions; |
| 2676 | copyKeys(data.role, server.roles[data.role.id], ['permissions']); |
| 2677 | }; |
| 2678 | Emoji.update = function(server, data) { |
| 2679 | server.emojis = {}; |
| 2680 | data.forEach(function(emoji) { |
| 2681 | server.emojis[emoji.id] = new Emoji(emoji); |
| 2682 | }); |
| 2683 | } |
| 2684 | |
| 2685 | Object.defineProperty(Role.prototype, "permission_values", { |
| 2686 | get: function() { return this; }, |
| 2687 | set: function() {}, |
| 2688 | enumerable: true |
| 2689 | }); |
| 2690 | Object.defineProperty(User.prototype, 'avatarURL', { |
| 2691 | get: function() { |
| 2692 | if (!this.avatar) return null; |
| 2693 | var animated = this.avatar.indexOf("a_") > -1; |
| 2694 | return Discord.Endpoints.CDN + "/avatars/" + this.id + "/" + this.avatar + (animated ? ".gif" : ".webp"); |
| 2695 | }, |
| 2696 | set: function() {} |
| 2697 | }); |
| 2698 | |
| 2699 | //Discord.OAuth; |
| 2700 | Discord.version = CURRENT_VERSION; |
| 2701 | Discord.Emitter = Emitter; |
| 2702 | Discord.Codes = {}; |
| 2703 | Discord.Codes.WebSocket = { |
| 2704 | "0" : "Gateway Error", |
| 2705 | "4000": "Unknown Error", |
| 2706 | "4001": "Unknown Opcode", |
| 2707 | "4002": "Decode Error", |
| 2708 | "4003": "Not Authenticated", |
| 2709 | "4004": "Authentication Failed", |
| 2710 | "4005": "Already Authenticated", |
| 2711 | "4006": "Session Not Valid", |
| 2712 | "4007": "Invalid Sequence Number", |
| 2713 | "4008": "Rate Limited", |
| 2714 | "4009": "Session Timeout", |
| 2715 | "4010": "Invalid Shard", |
| 2716 | "4011": "Sharding Required", |
| 2717 | "4012": "Invalid Gateway Version" |
| 2718 | }; |
| 2719 | Discord.Colors = { |
| 2720 | DEFAULT: 0, |
| 2721 | AQUA: 1752220, |
| 2722 | GREEN: 3066993, |
| 2723 | BLUE: 3447003, |
| 2724 | PURPLE: 10181046, |
| 2725 | GOLD: 15844367, |
| 2726 | ORANGE: 15105570, |
| 2727 | RED: 15158332, |
| 2728 | GREY: 9807270, |
| 2729 | DARKER_GREY: 8359053, |
| 2730 | NAVY: 3426654, |
| 2731 | DARK_AQUA: 1146986, |
| 2732 | DARK_GREEN: 2067276, |
| 2733 | DARK_BLUE: 2123412, |
| 2734 | DARK_PURPLE: 7419530, |
| 2735 | DARK_GOLD: 12745742, |
| 2736 | DARK_ORANGE: 11027200, |
| 2737 | DARK_RED: 10038562, |
| 2738 | DARK_GREY: 9936031, |
| 2739 | LIGHT_GREY: 12370112, |
| 2740 | DARK_NAVY: 2899536 |
| 2741 | }; |
| 2742 | Discord.Permissions = { |
| 2743 | GENERAL_CREATE_INSTANT_INVITE: 0, |
| 2744 | GENERAL_KICK_MEMBERS: 1, |
| 2745 | GENERAL_BAN_MEMBERS: 2, |
| 2746 | GENERAL_ADMINISTRATOR: 3, |
| 2747 | GENERAL_MANAGE_CHANNELS: 4, |
| 2748 | GENERAL_MANAGE_GUILD: 5, |
| 2749 | GENERAL_AUDIT_LOG: 7, |
| 2750 | GENERAL_MANAGE_ROLES: 28, |
| 2751 | GENERAL_MANAGE_NICKNAMES: 27, |
| 2752 | GENERAL_CHANGE_NICKNAME: 26, |
| 2753 | GENERAL_MANAGE_WEBHOOKS: 29, |
| 2754 | GENERAL_MANAGE_EMOJIS: 30, |
| 2755 | |
| 2756 | TEXT_ADD_REACTIONS: 6, |
| 2757 | TEXT_READ_MESSAGES: 10, |
| 2758 | TEXT_SEND_MESSAGES: 11, |
| 2759 | TEXT_SEND_TTS_MESSAGE: 12, |
| 2760 | TEXT_MANAGE_MESSAGES: 13, |
| 2761 | TEXT_EMBED_LINKS: 14, |
| 2762 | TEXT_ATTACH_FILES: 15, |
| 2763 | TEXT_READ_MESSAGE_HISTORY: 16, |
| 2764 | TEXT_MENTION_EVERYONE: 17, |
| 2765 | TEXT_EXTERNAL_EMOJIS: 18, |
| 2766 | |
| 2767 | VOICE_CONNECT: 20, |
| 2768 | VOICE_SPEAK: 21, |
| 2769 | VOICE_MUTE_MEMBERS: 22, |
| 2770 | VOICE_DEAFEN_MEMBERS: 23, |
| 2771 | VOICE_MOVE_MEMBERS: 24, |
| 2772 | VOICE_USE_VAD: 25, |
| 2773 | }; |
| 2774 | Discord.LogLevels = { |
| 2775 | Verbose: 0, |
| 2776 | Info: 1, |
| 2777 | Warn: 2, |
| 2778 | Error: 3 |
| 2779 | }; |
| 2780 | |
| 2781 | Object.keys(Discord.Permissions).forEach(function(pn) { |
| 2782 | Object.defineProperty(Role.prototype, pn, { |
| 2783 | get: getPerm( Discord.Permissions[pn] ), |
| 2784 | set: setPerm( Discord.Permissions[pn] ), |
| 2785 | enumerable: true |
| 2786 | }); |
| 2787 | }); |
| 2788 | |
| 2789 | /* Wrappers */ |
| 2790 | function Emitter() { |
| 2791 | var emt = this; |
| 2792 | if (isNode) { |
| 2793 | EE.call(this); |
| 2794 | if (this.prototype) return Util.inherits(this, EE); |
| 2795 | return new EE(); |
| 2796 | } |
| 2797 | //Thank you, http://stackoverflow.com/a/24216547 |
| 2798 | function _Emitter() { |
| 2799 | var eventTarget = document.createDocumentFragment(); |
| 2800 | ["addEventListener", "dispatchEvent", "removeEventListener"].forEach(function(method) { |
| 2801 | if (!this[method]) this[method] = eventTarget[method].bind(eventTarget); |
| 2802 | }, this); |
| 2803 | } |
| 2804 | //But I did the rest myself! D:< |
| 2805 | _Emitter.call(this); |
| 2806 | this._evts = {}; |
| 2807 | this.on = function(eName, eFunc) { |
| 2808 | if (!emt._evts[eName]) emt._evts[eName] = []; |
| 2809 | emt._evts[eName].push(eOn); |
| 2810 | |
| 2811 | return this.addEventListener(eName, eOn); |
| 2812 | |
| 2813 | function eOn(e) { |
| 2814 | return eFunc.apply(null, resolveEvent(e)); |
| 2815 | } |
| 2816 | }; |
| 2817 | this.once = function(eName, eFunc) { |
| 2818 | if (!emt._evts[eName]) emt._evts[eName] = []; |
| 2819 | emt._evts[eName].push(eOnce); |
| 2820 | |
| 2821 | return this.addEventListener(eName, eOnce); |
| 2822 | |
| 2823 | function eOnce(e) { |
| 2824 | eFunc.apply(null, resolveEvent(e)); |
| 2825 | return emt.removeListener(eName, eOnce); |
| 2826 | } |
| 2827 | }; |
| 2828 | this.removeListener = function(eName, eFunc) { |
| 2829 | if (emt._evts[eName]) emt._evts[eName].splice(emt._evts[eName].lastIndexOf(eFunc), 1); |
| 2830 | return this.removeEventListener(eName, eFunc); |
| 2831 | }; |
| 2832 | this.emit = function(eName) { |
| 2833 | return this.dispatchEvent( new CustomEvent(eName, {'detail': Array.prototype.slice.call(arguments, 1) }) ); |
| 2834 | }; |
| 2835 | return this; |
| 2836 | } |
| 2837 | |
| 2838 | function Websocket(url, opts) { |
| 2839 | if (isNode) return new (require('ws'))(url, opts); |
| 2840 | return Emitter.call(new WebSocket(url)); |
| 2841 | } |
| 2842 | |
| 2843 | /* Endpoints */ |
| 2844 | (function () { |
| 2845 | var API = "https://discordapp.com/api"; |
| 2846 | var CDN = "http://cdn.discordapp.com"; |
| 2847 | var ME = API + "/users/@me"; |
| 2848 | Endpoints = Discord.Endpoints = { |
| 2849 | API: API, |
| 2850 | CDN: CDN, |
| 2851 | |
| 2852 | ME: ME, |
| 2853 | NOTE: function(userID) { |
| 2854 | return ME + "/notes/" + userID; |
| 2855 | }, |
| 2856 | LOGIN: API + "/auth/login", |
| 2857 | OAUTH: API + "/oauth2/applications/@me", |
| 2858 | GATEWAY: API + "/gateway", |
| 2859 | SETTINGS: ME + "/settings", |
| 2860 | |
| 2861 | SERVERS: function(serverID) { |
| 2862 | return API + "/guilds" + (serverID ? "/" + serverID : ""); |
| 2863 | }, |
| 2864 | SERVERS_PERSONAL: function(serverID) { |
| 2865 | return this.ME + "/guilds" + (serverID ? "/" + serverID : ""); //Method to list personal servers? |
| 2866 | }, |
| 2867 | SERVER_EMOJIS: function(serverID, emojiID) { |
| 2868 | return this.SERVERS(serverID) + "/emojis" + (emojiID ? "/" + emojiID : ""); |
| 2869 | }, |
| 2870 | |
| 2871 | CHANNEL: function(channelID) { |
| 2872 | return API + "/channels/" + channelID; |
| 2873 | }, |
| 2874 | |
| 2875 | MEMBERS: function(serverID, userID) { |
| 2876 | return this.SERVERS(serverID) + "/members" + (userID ? "/" + userID : ""); |
| 2877 | }, |
| 2878 | MEMBER_ROLES: function(serverID, userID, roleID) { |
| 2879 | return this.MEMBERS(serverID, userID) + "/roles" + (roleID ? "/" + roleID : ""); |
| 2880 | }, |
| 2881 | |
| 2882 | USER: function(userID) { |
| 2883 | return API + "/users/" + userID; |
| 2884 | }, |
| 2885 | |
| 2886 | ROLES: function(serverID, roleID) { |
| 2887 | return this.SERVERS(serverID) + "/roles" + (roleID ? "/" + roleID : ""); |
| 2888 | }, |
| 2889 | |
| 2890 | BANS: function(serverID, userID) { |
| 2891 | return this.SERVERS(serverID) + "/bans" + (userID ? "/" + userID : ""); |
| 2892 | }, |
| 2893 | |
| 2894 | MESSAGES: function(channelID, messageID) { |
| 2895 | return this.CHANNEL(channelID) + "/messages" + (messageID ? "/" + messageID : ""); |
| 2896 | }, |
| 2897 | PINNED_MESSAGES: function(channelID, messageID) { |
| 2898 | return this.CHANNEL(channelID) + "/pins" + (messageID ? "/" + messageID : ""); |
| 2899 | }, |
| 2900 | |
| 2901 | MESSAGE_REACTIONS: function(channelID, messageID, reaction) { |
| 2902 | return this.MESSAGES(channelID, messageID) + "/reactions" + ( reaction ? ("/" + reaction) : "" ); |
| 2903 | }, |
| 2904 | USER_REACTIONS: function(channelID, messageID, reaction, userID) { |
| 2905 | return this.MESSAGE_REACTIONS(channelID, messageID, reaction) + '/' + ( (!userID || userID === this.id) ? '@me' : userID ); |
| 2906 | }, |
| 2907 | |
| 2908 | INVITES: function(inviteCode) { |
| 2909 | return API + "/invite/" + inviteCode; |
| 2910 | }, |
| 2911 | |
| 2912 | SERVER_WEBHOOKS: function(serverID) { |
| 2913 | return this.SERVERS(serverID) + "/webhooks"; |
| 2914 | }, |
| 2915 | CHANNEL_WEBHOOKS: function(channelID) { |
| 2916 | return this.CHANNEL(channelID) +"/webhooks"; |
| 2917 | }, |
| 2918 | |
| 2919 | WEBHOOKS: function(webhookID) { |
| 2920 | return API + "/webhooks/" + webhookID; |
| 2921 | }, |
| 2922 | |
| 2923 | BULK_DELETE: function(channelID) { |
| 2924 | return this.CHANNEL(channelID) + "/messages/bulk-delete"; |
| 2925 | }, |
| 2926 | |
| 2927 | TYPING: function(channelID) { |
| 2928 | return this.CHANNEL(channelID) + "/typing"; |
| 2929 | } |
| 2930 | |
| 2931 | }; |
| 2932 | })(); |
| 2933 | |
| 2934 | /* Payloads */ |
| 2935 | (function() { |
| 2936 | Payloads = { |
| 2937 | IDENTIFY: function(client) { |
| 2938 | return { |
| 2939 | op: 2, |
| 2940 | d: { |
| 2941 | token: client.internals.token, |
| 2942 | compress: isNode && !!Zlib.inflateSync, |
| 2943 | large_threshold: LARGE_THRESHOLD, |
| 2944 | presence: client.presence, |
| 2945 | properties: { |
| 2946 | $os: isNode ? require('os').platform() : navigator.platform, |
| 2947 | $browser:"discord.io", |
| 2948 | $device:"discord.io", |
| 2949 | $referrer:"", |
| 2950 | $referring_domain:"" |
| 2951 | } |
| 2952 | } |
| 2953 | }; |
| 2954 | }, |
| 2955 | RESUME: function(client) { |
| 2956 | return { |
| 2957 | op: 6, |
| 2958 | d: { |
| 2959 | token: client.internals.token, |
| 2960 | session_id: client.internals.sessionID, |
| 2961 | seq: client.internals.sequence |
| 2962 | } |
| 2963 | }; |
| 2964 | }, |
| 2965 | HEARTBEAT: function(client) { |
| 2966 | return {op: 1, d: client.internals.sequence}; |
| 2967 | }, |
| 2968 | ALL_USERS: function(client) { |
| 2969 | return {op: 12, d: Object.keys(client.servers)}; |
| 2970 | }, |
| 2971 | STATUS: function(input) { |
| 2972 | return { |
| 2973 | op: 3, |
| 2974 | d: { |
| 2975 | status: type(input.since) === 'number' ? 'idle' : input.status !== undefined ? input.status : null, |
| 2976 | afk: !!input.afk, |
| 2977 | since: type(input.since) === 'number' || input.status === 'idle' ? Date.now() : null, |
| 2978 | game: type(input.game) === 'object' ? |
| 2979 | { |
| 2980 | name: input.game.name ? String(input.game.name) : null, |
| 2981 | type: input.game.type ? Number(input.game.type) : 0, |
| 2982 | url: input.game.url ? String(input.game.url) : null |
| 2983 | } : |
| 2984 | null |
| 2985 | } |
| 2986 | }; |
| 2987 | }, |
| 2988 | UPDATE_VOICE: function(serverID, channelID, self_mute, self_deaf) { |
| 2989 | return { |
| 2990 | op: 4, |
| 2991 | d: { |
| 2992 | guild_id: serverID, |
| 2993 | channel_id: channelID, |
| 2994 | self_mute: self_mute, |
| 2995 | self_deaf: self_deaf |
| 2996 | } |
| 2997 | }; |
| 2998 | }, |
| 2999 | OFFLINE_USERS: function(array) { |
| 3000 | return { |
| 3001 | op: 8, |
| 3002 | d: { |
| 3003 | guild_id: array.splice(0, 50), |
| 3004 | query: "", |
| 3005 | limit: 0 |
| 3006 | } |
| 3007 | }; |
| 3008 | }, |
| 3009 | VOICE_SPEAK: function(v) { |
| 3010 | return {op:5, d:{ speaking: !!v, delay: 0 }}; |
| 3011 | }, |
| 3012 | VOICE_IDENTIFY: function(clientID, voiceSession) { |
| 3013 | return { |
| 3014 | op: 0, |
| 3015 | d: { |
| 3016 | server_id: voiceSession.serverID, |
| 3017 | user_id: clientID, |
| 3018 | session_id: voiceSession.session, |
| 3019 | token: voiceSession.token |
| 3020 | } |
| 3021 | }; |
| 3022 | }, |
| 3023 | VOICE_DISCOVERY: function(ip, port, mode) { |
| 3024 | return { |
| 3025 | op:1, |
| 3026 | d:{ |
| 3027 | protocol:"udp", |
| 3028 | data:{ |
| 3029 | address: ip, |
| 3030 | port: Number(port), |
| 3031 | mode: mode |
| 3032 | } |
| 3033 | } |
| 3034 | }; |
| 3035 | } |
| 3036 | } |
| 3037 | })(); |
| 3038 | |
| 3039 | })(typeof exports === 'undefined'? this.Discord = {} : exports); |