Ratelimiter inconsistency fix

This commit is contained in:
abalabahaha
2016-04-13 02:06:18 -07:00
parent fc74912a8f
commit ecc35eecda
29 changed files with 6795 additions and 747 deletions

View File

@@ -1,3 +1,207 @@
"use strict";exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var _child_process=require("child_process");var _child_process2=_interopRequireDefault(_child_process); // no opus!
var _VolumeTransformer=require("./VolumeTransformer");var _VolumeTransformer2=_interopRequireDefault(_VolumeTransformer);var opus;try{opus = require("node-opus");}catch(e) {}var AudioEncoder=(function(){function AudioEncoder(){_classCallCheck(this,AudioEncoder);if(opus){this.opus = new opus.OpusEncoder(48000,2);}this.choice = false;this.sanityCheckPassed = undefined;}AudioEncoder.prototype.sanityCheck = function sanityCheck(){var _opus=this.opus;var encodeZeroes=function encodeZeroes(){try{var zeroes=new Buffer(1920);zeroes.fill(0);return _opus.encode(zeroes,1920).readUIntBE(0,3);}catch(err) {return false;}};if(this.sanityCheckPassed === undefined)this.sanityCheckPassed = encodeZeroes() === 16056318;return this.sanityCheckPassed;};AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer){return this.opus.encode(buffer,1920);};AudioEncoder.prototype.getCommand = function getCommand(force){if(this.choice && force)return choice;var choices=["avconv","ffmpeg"];for(var _iterator=choices,_isArray=Array.isArray(_iterator),_i=0,_iterator=_isArray?_iterator:_iterator[Symbol.iterator]();;) {var _ref;if(_isArray){if(_i >= _iterator.length)break;_ref = _iterator[_i++];}else {_i = _iterator.next();if(_i.done)break;_ref = _i.value;}var choice=_ref;var p=_child_process2["default"].spawnSync(choice);if(!p.error){this.choice = choice;return choice;}}return "help";};AudioEncoder.prototype.encodeStream = function encodeStream(stream,options){var _this=this;return new Promise(function(resolve,reject){_this.volume = new _VolumeTransformer2["default"](options.volume);var enc=_child_process2["default"].spawn(_this.getCommand(),['-i','-','-f','s16le','-ar','48000','-ss',options.seek || 0,'-ac',2,'pipe:1']);stream.pipe(enc.stdin);var ffmpegErrors="";enc.stdout.pipe(_this.volume);enc.stderr.on("data",function(data){ffmpegErrors += "\n" + new Buffer(data).toString().trim();});enc.once("exit",function(code,signal){if(code){reject(new Error("FFMPEG: " + ffmpegErrors));}});_this.volume.once("readable",function(){resolve({proc:enc,stream:_this.volume,instream:stream,channels:2});});_this.volume.on("end",function(){reject("end");});_this.volume.on("close",function(){reject("close");});});};AudioEncoder.prototype.encodeFile = function encodeFile(file,options){var _this2=this;return new Promise(function(resolve,reject){_this2.volume = new _VolumeTransformer2["default"](options.volume);var enc=_child_process2["default"].spawn(_this2.getCommand(),['-i',file,'-f','s16le','-ar','48000','-ss',options.seek || 0,'-ac',2,'pipe:1']);var ffmpegErrors="";enc.stdout.pipe(_this2.volume);enc.stderr.on("data",function(data){ffmpegErrors += "\n" + new Buffer(data).toString().trim();});enc.once("exit",function(code,signal){if(code){reject(new Error("FFMPEG: " + ffmpegErrors));}});_this2.volume.once("readable",function(){resolve({proc:enc,stream:_this2.volume,channels:2});});_this2.volume.on("end",function(){reject("end");});_this2.volume.on("close",function(){reject("close");});});};AudioEncoder.prototype.encodeArbitraryFFmpeg = function encodeArbitraryFFmpeg(ffmpegOptions){var _this3=this;return new Promise(function(resolve,reject){_this3.volume = new _VolumeTransformer2["default"](1); // add options discord.js needs
var options=ffmpegOptions.concat(['-f','s16le','-ar','48000','-ac',2,'pipe:1']);var enc=_child_process2["default"].spawn(_this3.getCommand(),options);var ffmpegErrors="";enc.stdout.pipe(_this3.volume);enc.stderr.on("data",function(data){ffmpegErrors += "\n" + new Buffer(data).toString().trim();});enc.once("exit",function(code,signal){if(code){reject(new Error("FFMPEG: " + ffmpegErrors));}});_this3.volume.once("readable",function(){resolve({proc:enc,stream:_this3.volume,channels:2});});_this3.volume.on("end",function(){reject("end");});_this3.volume.on("close",function(){reject("close");});});};return AudioEncoder;})();exports["default"] = AudioEncoder;module.exports = exports["default"];
"use strict";
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _child_process = require("child_process");
var _child_process2 = _interopRequireDefault(_child_process);
// no opus!
var _VolumeTransformer = require("./VolumeTransformer");
var _VolumeTransformer2 = _interopRequireDefault(_VolumeTransformer);
var opus;
try {
opus = require("node-opus");
} catch (e) {}
var AudioEncoder = (function () {
function AudioEncoder() {
_classCallCheck(this, AudioEncoder);
if (opus) {
this.opus = new opus.OpusEncoder(48000, 2);
}
this.choice = false;
this.sanityCheckPassed = undefined;
}
AudioEncoder.prototype.sanityCheck = function sanityCheck() {
var _opus = this.opus;
var encodeZeroes = function encodeZeroes() {
try {
var zeroes = new Buffer(1920);
zeroes.fill(0);
return _opus.encode(zeroes, 1920).readUIntBE(0, 3);
} catch (err) {
return false;
}
};
if (this.sanityCheckPassed === undefined) this.sanityCheckPassed = encodeZeroes() === 16056318;
return this.sanityCheckPassed;
};
AudioEncoder.prototype.opusBuffer = function opusBuffer(buffer) {
return this.opus.encode(buffer, 1920);
};
AudioEncoder.prototype.getCommand = function getCommand(force) {
if (this.choice && force) return choice;
var choices = ["avconv", "ffmpeg"];
for (var _iterator = choices, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var choice = _ref;
var p = _child_process2["default"].spawnSync(choice);
if (!p.error) {
this.choice = choice;
return choice;
}
}
return "help";
};
AudioEncoder.prototype.encodeStream = function encodeStream(stream, options) {
var _this = this;
return new Promise(function (resolve, reject) {
_this.volume = new _VolumeTransformer2["default"](options.volume);
var enc = _child_process2["default"].spawn(_this.getCommand(), ['-i', '-', '-f', 's16le', '-ar', '48000', '-ss', options.seek || 0, '-ac', 2, 'pipe:1']);
stream.pipe(enc.stdin);
var ffmpegErrors = "";
enc.stdout.pipe(_this.volume);
enc.stderr.on("data", function (data) {
ffmpegErrors += "\n" + new Buffer(data).toString().trim();
});
enc.once("exit", function (code, signal) {
if (code) {
reject(new Error("FFMPEG: " + ffmpegErrors));
}
});
_this.volume.once("readable", function () {
resolve({
proc: enc,
stream: _this.volume,
instream: stream,
channels: 2
});
});
_this.volume.on("end", function () {
reject("end");
});
_this.volume.on("close", function () {
reject("close");
});
});
};
AudioEncoder.prototype.encodeFile = function encodeFile(file, options) {
var _this2 = this;
return new Promise(function (resolve, reject) {
_this2.volume = new _VolumeTransformer2["default"](options.volume);
var enc = _child_process2["default"].spawn(_this2.getCommand(), ['-i', file, '-f', 's16le', '-ar', '48000', '-ss', options.seek || 0, '-ac', 2, 'pipe:1']);
var ffmpegErrors = "";
enc.stdout.pipe(_this2.volume);
enc.stderr.on("data", function (data) {
ffmpegErrors += "\n" + new Buffer(data).toString().trim();
});
enc.once("exit", function (code, signal) {
if (code) {
reject(new Error("FFMPEG: " + ffmpegErrors));
}
});
_this2.volume.once("readable", function () {
resolve({
proc: enc,
stream: _this2.volume,
channels: 2
});
});
_this2.volume.on("end", function () {
reject("end");
});
_this2.volume.on("close", function () {
reject("close");
});
});
};
AudioEncoder.prototype.encodeArbitraryFFmpeg = function encodeArbitraryFFmpeg(ffmpegOptions) {
var _this3 = this;
return new Promise(function (resolve, reject) {
_this3.volume = new _VolumeTransformer2["default"](1);
// add options discord.js needs
var options = ffmpegOptions.concat(['-f', 's16le', '-ar', '48000', '-ac', 2, 'pipe:1']);
var enc = _child_process2["default"].spawn(_this3.getCommand(), options);
var ffmpegErrors = "";
enc.stdout.pipe(_this3.volume);
enc.stderr.on("data", function (data) {
ffmpegErrors += "\n" + new Buffer(data).toString().trim();
});
enc.once("exit", function (code, signal) {
if (code) {
reject(new Error("FFMPEG: " + ffmpegErrors));
}
});
_this3.volume.once("readable", function () {
resolve({
proc: enc,
stream: _this3.volume,
channels: 2
});
});
_this3.volume.on("end", function () {
reject("end");
});
_this3.volume.on("close", function () {
reject("close");
});
});
};
return AudioEncoder;
})();
exports["default"] = AudioEncoder;
module.exports = exports["default"];

View File

@@ -1,2 +1,28 @@
"use strict"; // represents an intent of streaming music
exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _events=require("events");var _events2=_interopRequireDefault(_events);var StreamIntent=(function(_EventEmitter){_inherits(StreamIntent,_EventEmitter);function StreamIntent(){_classCallCheck(this,StreamIntent);_EventEmitter.call(this);}return StreamIntent;})(_events2["default"]);exports["default"] = StreamIntent;module.exports = exports["default"];
"use strict";
// represents an intent of streaming music
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _events = require("events");
var _events2 = _interopRequireDefault(_events);
var StreamIntent = (function (_EventEmitter) {
_inherits(StreamIntent, _EventEmitter);
function StreamIntent() {
_classCallCheck(this, StreamIntent);
_EventEmitter.call(this);
}
return StreamIntent;
})(_events2["default"]);
exports["default"] = StreamIntent;
module.exports = exports["default"];

View File

@@ -1,14 +1,490 @@
"use strict"; /*
"use strict";
/*
Major credit to izy521 who is the creator of
https://github.com/izy521/discord.io,
without his help voice chat in discord.js would not have
been possible!
*/exports.__esModule = true;function _interopRequireDefault(obj){return obj && obj.__esModule?obj:{"default":obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _inherits(subClass,superClass){if(typeof superClass !== "function" && superClass !== null){throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var _ws=require("ws");var _ws2=_interopRequireDefault(_ws);var _dns=require("dns");var _dns2=_interopRequireDefault(_dns);var _dgram=require("dgram");var _dgram2=_interopRequireDefault(_dgram);var _AudioEncoder=require("./AudioEncoder");var _AudioEncoder2=_interopRequireDefault(_AudioEncoder);var _VoicePacket=require("./VoicePacket");var _VoicePacket2=_interopRequireDefault(_VoicePacket);var _VolumeTransformer=require("./VolumeTransformer");var _VolumeTransformer2=_interopRequireDefault(_VolumeTransformer);var _StreamIntent=require("./StreamIntent");var _StreamIntent2=_interopRequireDefault(_StreamIntent);var _events=require("events");var _events2=_interopRequireDefault(_events);var _unpipe=require("unpipe");var _unpipe2=_interopRequireDefault(_unpipe);var MODE_xsalsa20_poly1305="xsalsa20_poly1305";var MODE_plain="plain";var VoiceConnection=(function(_EventEmitter){_inherits(VoiceConnection,_EventEmitter);function VoiceConnection(channel,client,session,token,server,endpoint){_classCallCheck(this,VoiceConnection);_EventEmitter.call(this);this.id = channel.id;this.voiceChannel = channel;this.client = client;this.session = session;this.token = token;this.server = server;this.endpoint = endpoint.split(":")[0];this.vWS = null; // vWS means voice websocket
this.ready = false;this.vWSData = {};this.encoder = new _AudioEncoder2["default"]();this.udp = null;this.playingIntent = null;this.playing = false;this.streamTime = 0;this.streamProc = null;this.KAI = null;this.timestamp = 0;this.sequence = 0;this.mode = null;this.secret = null;this.volume = new _VolumeTransformer2["default"]();this.paused = false;this.init();}VoiceConnection.prototype.destroy = function destroy(){this.stopPlaying();if(this.KAI){clearInterval(this.KAI);}this.vWS.close();this.udp.close();this.client.internal.sendWS({op:4,d:{guild_id:this.server.id,channel_id:null,self_mute:true,self_deaf:false}});this.client.internal.voiceConnections.remove(this);};VoiceConnection.prototype.stopPlaying = function stopPlaying(){this.playing = false;this.playingIntent = null;if(this.instream){ //not all streams implement these...
//and even file stream don't seem to implement them properly...
_unpipe2["default"](this.instream);if(this.instream.end){this.instream.end();}if(this.instream.destroy){this.instream.destroy();}this.instream = null;}if(this.streamProc){this.streamProc.stdin.pause();this.streamProc.kill("SIGINT");this.streamProc = null;}};VoiceConnection.prototype.playStream = function playStream(stream){var channels=arguments.length <= 1 || arguments[1] === undefined?2:arguments[1];var self=this,startTime=Date.now(),count=0,length=20,retStream=new _StreamIntent2["default"](),onWarning=false;this.volume = stream;this.playing = true;this.playingIntent = retStream;function send(){if(self.paused){startTime += Date.now() - (startTime + count * length);setTimeout(send,length);return;}if(!self.playingIntent || !self.playing){self.setSpeaking(false);retStream.emit("end");return;}try{var buffer=stream.read(1920 * channels);if(!buffer){if(onWarning){self.setSpeaking(false);retStream.emit("end");return;}else {onWarning = true;setTimeout(send,length * 10); // give chance for some data in 200ms to appear
return;}}if(buffer.length !== 1920 * channels){var newBuffer=new Buffer(1920 * channels).fill(0);buffer.copy(newBuffer);buffer = newBuffer;}count++;self.sequence + 1 < 65535?self.sequence += 1:self.sequence = 0;self.timestamp + 960 < 4294967295?self.timestamp += 960:self.timestamp = 0;self.sendBuffer(buffer,self.sequence,self.timestamp,function(e){});var nextTime=startTime + count * length;self.streamTime = count * length;setTimeout(send,length + (nextTime - Date.now()));if(!self.playing)self.setSpeaking(true);retStream.emit("time",self.streamTime);}catch(e) {retStream.emit("error",e);}}self.setSpeaking(true);send();return retStream;};VoiceConnection.prototype.setSpeaking = function setSpeaking(value){this.playing = value;if(this.vWS.readyState === _ws2["default"].OPEN)this.vWS.send(JSON.stringify({op:5,d:{speaking:value,delay:0}}));};VoiceConnection.prototype.sendPacket = function sendPacket(packet){var callback=arguments.length <= 1 || arguments[1] === undefined?function(err){}:arguments[1];var self=this;self.playing = true;try{if(self.vWS.readyState === _ws2["default"].OPEN)self.udp.send(packet,0,packet.length,self.vWSData.port,self.endpoint,callback);}catch(e) {self.playing = false;callback(e);return false;}};VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer,sequence,timestamp,callback){var self=this;self.playing = true;try{if(!self.encoder.opus){self.playing = false;throw new Error("node-opus not found! Perhaps you didn't install it.");return;}if(!self.encoder.sanityCheck()){self.playing = false;throw new Error("node-opus sanity check failed! Try re-installing node-opus.");return;}var buffer=self.encoder.opusBuffer(rawbuffer);var packet=new _VoicePacket2["default"](buffer,sequence,timestamp,self.vWSData.ssrc,self.secret);return self.sendPacket(packet,callback);}catch(e) {self.playing = false;self.emit("error",e);return false;}};VoiceConnection.prototype.playFile = function playFile(stream){var _this=this;var options=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,str){}:arguments[2];var self=this;self.stopPlaying();if(typeof options === "function"){ // options is the callback
callback = options;}if(typeof options !== "object"){options = {};}options.volume = options.volume !== undefined?options.volume:this.getVolume();return new Promise(function(resolve,reject){_this.encoder.encodeFile(stream,options)["catch"](error).then(function(data){self.streamProc = data.proc;var intent=self.playStream(data.stream,2);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playRawStream = function playRawStream(stream){var _this2=this;var options=arguments.length <= 1 || arguments[1] === undefined?false:arguments[1];var callback=arguments.length <= 2 || arguments[2] === undefined?function(err,str){}:arguments[2];var self=this;self.stopPlaying();if(typeof options === "function"){ // options is the callback
callback = options;}if(typeof options !== "object"){options = {};}options.volume = options.volume !== undefined?options.volume:this.getVolume();return new Promise(function(resolve,reject){_this2.encoder.encodeStream(stream,options)["catch"](error).then(function(data){self.streamProc = data.proc;self.instream = data.instream;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.playArbitraryFFmpeg = function playArbitraryFFmpeg(ffmpegOptions){var _this3=this;var callback=arguments.length <= 1 || arguments[1] === undefined?function(err,str){}:arguments[1];var self=this;self.stopPlaying();if(typeof options === "function"){ // options is the callback
callback = options;}if(typeof options !== "object"){options = {};}options.volume = options.volume !== undefined?options.volume:this.getVolume();return new Promise(function(resolve,reject){_this3.encoder.encodeArbitraryFFmpeg(ffmpegOptions)["catch"](error).then(function(data){self.streamProc = data.proc;self.instream = data.instream;var intent=self.playStream(data.stream);resolve(intent);callback(null,intent);});function error(){var e=arguments.length <= 0 || arguments[0] === undefined?true:arguments[0];reject(e);callback(e);}});};VoiceConnection.prototype.init = function init(){var _this4=this;var self=this;_dns2["default"].lookup(this.endpoint,function(err,address,family){var vWS=self.vWS = new _ws2["default"]("wss://" + _this4.endpoint,null,{rejectUnauthorized:false});_this4.endpoint = address;var udpClient=self.udp = _dgram2["default"].createSocket("udp4");var firstPacket=true;var discordIP="",discordPort="";udpClient.bind({exclusive:true});udpClient.on('message',function(msg,rinfo){var buffArr=JSON.parse(JSON.stringify(msg)).data;if(firstPacket === true){for(var i=4;i < buffArr.indexOf(0,i);i++) {discordIP += String.fromCharCode(buffArr[i]);}discordPort = msg.readUIntLE(msg.length - 2,2).toString(10);var modes=self.vWSData.modes;var mode=MODE_xsalsa20_poly1305;if(modes.indexOf(MODE_xsalsa20_poly1305) < 0){mode = MODE_plain;self.client.emit("debug","Encrypted mode not reported as supported by the server, using 'plain'");}vWS.send(JSON.stringify({"op":1,"d":{"protocol":"udp","data":{"address":discordIP,"port":Number(discordPort),"mode":mode}}}));firstPacket = false;}});vWS.on("open",function(){vWS.send(JSON.stringify({op:0,d:{server_id:self.server.id,user_id:self.client.internal.user.id,session_id:self.session,token:self.token}}));});var KAI;vWS.on("message",function(msg){var data=JSON.parse(msg);switch(data.op){case 2:self.vWSData = data.d;self.KAI = KAI = self.client.internal.intervals.misc["voiceKAI"] = setInterval(function(){if(vWS && vWS.readyState === _ws2["default"].OPEN)vWS.send(JSON.stringify({op:3,d:null}));},data.d.heartbeat_interval);var udpPacket=new Buffer(70);udpPacket.writeUIntBE(data.d.ssrc,0,4);udpClient.send(udpPacket,0,udpPacket.length,data.d.port,self.endpoint,function(err){if(err)self.emit("error",err);});break;case 4:if(data.d.secret_key && data.d.secret_key.length > 0){var buffer=new ArrayBuffer(data.d.secret_key.length);self.secret = new Uint8Array(buffer);for(var i=0;i < _this4.secret.length;i++) {self.secret[i] = data.d.secret_key[i];}}self.ready = true;self.mode = data.d.mode;self.emit("ready",self);break;}});});};VoiceConnection.prototype.wrapVolume = function wrapVolume(stream){stream.pipe(this.volume);return this.volume;};VoiceConnection.prototype.setVolume = function setVolume(volume){this.volume.set(volume);};VoiceConnection.prototype.getVolume = function getVolume(){return this.volume.get();};VoiceConnection.prototype.mute = function mute(){this.lastVolume = this.volume.get();this.setVolume(0);};VoiceConnection.prototype.unmute = function unmute(){this.setVolume(this.lastVolume);this.lastVolume = undefined;};VoiceConnection.prototype.pause = function pause(){this.paused = true;this.setSpeaking(false);this.playingIntent.emit("pause");};VoiceConnection.prototype.resume = function resume(){this.paused = false;this.setSpeaking(true);this.playingIntent.emit("resume");};return VoiceConnection;})(_events2["default"]);exports["default"] = VoiceConnection;module.exports = exports["default"];
*/
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _ws = require("ws");
var _ws2 = _interopRequireDefault(_ws);
var _dns = require("dns");
var _dns2 = _interopRequireDefault(_dns);
var _dgram = require("dgram");
var _dgram2 = _interopRequireDefault(_dgram);
var _AudioEncoder = require("./AudioEncoder");
var _AudioEncoder2 = _interopRequireDefault(_AudioEncoder);
var _VoicePacket = require("./VoicePacket");
var _VoicePacket2 = _interopRequireDefault(_VoicePacket);
var _VolumeTransformer = require("./VolumeTransformer");
var _VolumeTransformer2 = _interopRequireDefault(_VolumeTransformer);
var _StreamIntent = require("./StreamIntent");
var _StreamIntent2 = _interopRequireDefault(_StreamIntent);
var _events = require("events");
var _events2 = _interopRequireDefault(_events);
var _unpipe = require("unpipe");
var _unpipe2 = _interopRequireDefault(_unpipe);
var MODE_xsalsa20_poly1305 = "xsalsa20_poly1305";
var MODE_plain = "plain";
var VoiceConnection = (function (_EventEmitter) {
_inherits(VoiceConnection, _EventEmitter);
function VoiceConnection(channel, client, session, token, server, endpoint) {
_classCallCheck(this, VoiceConnection);
_EventEmitter.call(this);
this.id = channel.id;
this.voiceChannel = channel;
this.client = client;
this.session = session;
this.token = token;
this.server = server;
this.endpoint = endpoint.split(":")[0];
this.vWS = null; // vWS means voice websocket
this.ready = false;
this.vWSData = {};
this.encoder = new _AudioEncoder2["default"]();
this.udp = null;
this.playingIntent = null;
this.playing = false;
this.streamTime = 0;
this.streamProc = null;
this.KAI = null;
this.timestamp = 0;
this.sequence = 0;
this.mode = null;
this.secret = null;
this.volume = new _VolumeTransformer2["default"]();
this.paused = false;
this.init();
}
VoiceConnection.prototype.destroy = function destroy() {
this.stopPlaying();
if (this.KAI) {
clearInterval(this.KAI);
}
this.vWS.close();
this.udp.close();
this.client.internal.sendWS({
op: 4,
d: {
guild_id: this.server.id,
channel_id: null,
self_mute: true,
self_deaf: false
}
});
this.client.internal.voiceConnections.remove(this);
};
VoiceConnection.prototype.stopPlaying = function stopPlaying() {
this.playing = false;
this.playingIntent = null;
if (this.instream) {
//not all streams implement these...
//and even file stream don't seem to implement them properly...
_unpipe2["default"](this.instream);
if (this.instream.end) {
this.instream.end();
}
if (this.instream.destroy) {
this.instream.destroy();
}
this.instream = null;
}
if (this.streamProc) {
this.streamProc.stdin.pause();
this.streamProc.kill("SIGINT");
this.streamProc = null;
}
};
VoiceConnection.prototype.playStream = function playStream(stream) {
var channels = arguments.length <= 1 || arguments[1] === undefined ? 2 : arguments[1];
var self = this,
startTime = Date.now(),
count = 0,
length = 20,
retStream = new _StreamIntent2["default"](),
onWarning = false;
this.volume = stream;
this.playing = true;
this.playingIntent = retStream;
function send() {
if (self.paused) {
startTime += Date.now() - (startTime + count * length);
setTimeout(send, length);
return;
}
if (!self.playingIntent || !self.playing) {
self.setSpeaking(false);
retStream.emit("end");
return;
}
try {
var buffer = stream.read(1920 * channels);
if (!buffer) {
if (onWarning) {
self.setSpeaking(false);
retStream.emit("end");
return;
} else {
onWarning = true;
setTimeout(send, length * 10); // give chance for some data in 200ms to appear
return;
}
}
if (buffer.length !== 1920 * channels) {
var newBuffer = new Buffer(1920 * channels).fill(0);
buffer.copy(newBuffer);
buffer = newBuffer;
}
count++;
self.sequence + 1 < 65535 ? self.sequence += 1 : self.sequence = 0;
self.timestamp + 960 < 4294967295 ? self.timestamp += 960 : self.timestamp = 0;
self.sendBuffer(buffer, self.sequence, self.timestamp, function (e) {});
var nextTime = startTime + count * length;
self.streamTime = count * length;
setTimeout(send, length + (nextTime - Date.now()));
if (!self.playing) self.setSpeaking(true);
retStream.emit("time", self.streamTime);
} catch (e) {
retStream.emit("error", e);
}
}
self.setSpeaking(true);
send();
return retStream;
};
VoiceConnection.prototype.setSpeaking = function setSpeaking(value) {
this.playing = value;
if (this.vWS.readyState === _ws2["default"].OPEN) this.vWS.send(JSON.stringify({
op: 5,
d: {
speaking: value,
delay: 0
}
}));
};
VoiceConnection.prototype.sendPacket = function sendPacket(packet) {
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err) {} : arguments[1];
var self = this;
self.playing = true;
try {
if (self.vWS.readyState === _ws2["default"].OPEN) self.udp.send(packet, 0, packet.length, self.vWSData.port, self.endpoint, callback);
} catch (e) {
self.playing = false;
callback(e);
return false;
}
};
VoiceConnection.prototype.sendBuffer = function sendBuffer(rawbuffer, sequence, timestamp, callback) {
var self = this;
self.playing = true;
try {
if (!self.encoder.opus) {
self.playing = false;
throw new Error("node-opus not found! Perhaps you didn't install it.");
return;
}
if (!self.encoder.sanityCheck()) {
self.playing = false;
throw new Error("node-opus sanity check failed! Try re-installing node-opus.");
return;
}
var buffer = self.encoder.opusBuffer(rawbuffer);
var packet = new _VoicePacket2["default"](buffer, sequence, timestamp, self.vWSData.ssrc, self.secret);
return self.sendPacket(packet, callback);
} catch (e) {
self.playing = false;
self.emit("error", e);
return false;
}
};
VoiceConnection.prototype.playFile = function playFile(stream) {
var _this = this;
var options = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, str) {} : arguments[2];
var self = this;
self.stopPlaying();
if (typeof options === "function") {
// options is the callback
callback = options;
}
if (typeof options !== "object") {
options = {};
}
options.volume = options.volume !== undefined ? options.volume : this.getVolume();
return new Promise(function (resolve, reject) {
_this.encoder.encodeFile(stream, options)["catch"](error).then(function (data) {
self.streamProc = data.proc;
var intent = self.playStream(data.stream, 2);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.playRawStream = function playRawStream(stream) {
var _this2 = this;
var options = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var callback = arguments.length <= 2 || arguments[2] === undefined ? function (err, str) {} : arguments[2];
var self = this;
self.stopPlaying();
if (typeof options === "function") {
// options is the callback
callback = options;
}
if (typeof options !== "object") {
options = {};
}
options.volume = options.volume !== undefined ? options.volume : this.getVolume();
return new Promise(function (resolve, reject) {
_this2.encoder.encodeStream(stream, options)["catch"](error).then(function (data) {
self.streamProc = data.proc;
self.instream = data.instream;
var intent = self.playStream(data.stream);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.playArbitraryFFmpeg = function playArbitraryFFmpeg(ffmpegOptions) {
var _this3 = this;
var callback = arguments.length <= 1 || arguments[1] === undefined ? function (err, str) {} : arguments[1];
var self = this;
self.stopPlaying();
if (typeof options === "function") {
// options is the callback
callback = options;
}
if (typeof options !== "object") {
options = {};
}
options.volume = options.volume !== undefined ? options.volume : this.getVolume();
return new Promise(function (resolve, reject) {
_this3.encoder.encodeArbitraryFFmpeg(ffmpegOptions)["catch"](error).then(function (data) {
self.streamProc = data.proc;
self.instream = data.instream;
var intent = self.playStream(data.stream);
resolve(intent);
callback(null, intent);
});
function error() {
var e = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
reject(e);
callback(e);
}
});
};
VoiceConnection.prototype.init = function init() {
var _this4 = this;
var self = this;
_dns2["default"].lookup(this.endpoint, function (err, address, family) {
var vWS = self.vWS = new _ws2["default"]("wss://" + _this4.endpoint, null, { rejectUnauthorized: false });
_this4.endpoint = address;
var udpClient = self.udp = _dgram2["default"].createSocket("udp4");
var firstPacket = true;
var discordIP = "",
discordPort = "";
udpClient.bind({ exclusive: true });
udpClient.on('message', function (msg, rinfo) {
var buffArr = JSON.parse(JSON.stringify(msg)).data;
if (firstPacket === true) {
for (var i = 4; i < buffArr.indexOf(0, i); i++) {
discordIP += String.fromCharCode(buffArr[i]);
}
discordPort = msg.readUIntLE(msg.length - 2, 2).toString(10);
var modes = self.vWSData.modes;
var mode = MODE_xsalsa20_poly1305;
if (modes.indexOf(MODE_xsalsa20_poly1305) < 0) {
mode = MODE_plain;
self.client.emit("debug", "Encrypted mode not reported as supported by the server, using 'plain'");
}
vWS.send(JSON.stringify({
"op": 1,
"d": {
"protocol": "udp",
"data": {
"address": discordIP,
"port": Number(discordPort),
"mode": mode
}
}
}));
firstPacket = false;
}
});
vWS.on("open", function () {
vWS.send(JSON.stringify({
op: 0,
d: {
server_id: self.server.id,
user_id: self.client.internal.user.id,
session_id: self.session,
token: self.token
}
}));
});
var KAI;
vWS.on("message", function (msg) {
var data = JSON.parse(msg);
switch (data.op) {
case 2:
self.vWSData = data.d;
self.KAI = KAI = self.client.internal.intervals.misc["voiceKAI"] = setInterval(function () {
if (vWS && vWS.readyState === _ws2["default"].OPEN) vWS.send(JSON.stringify({
op: 3,
d: null
}));
}, data.d.heartbeat_interval);
var udpPacket = new Buffer(70);
udpPacket.writeUIntBE(data.d.ssrc, 0, 4);
udpClient.send(udpPacket, 0, udpPacket.length, data.d.port, self.endpoint, function (err) {
if (err) self.emit("error", err);
});
break;
case 4:
if (data.d.secret_key && data.d.secret_key.length > 0) {
var buffer = new ArrayBuffer(data.d.secret_key.length);
self.secret = new Uint8Array(buffer);
for (var i = 0; i < _this4.secret.length; i++) {
self.secret[i] = data.d.secret_key[i];
}
}
self.ready = true;
self.mode = data.d.mode;
self.emit("ready", self);
break;
}
});
});
};
VoiceConnection.prototype.wrapVolume = function wrapVolume(stream) {
stream.pipe(this.volume);
return this.volume;
};
VoiceConnection.prototype.setVolume = function setVolume(volume) {
this.volume.set(volume);
};
VoiceConnection.prototype.getVolume = function getVolume() {
return this.volume.get();
};
VoiceConnection.prototype.mute = function mute() {
this.lastVolume = this.volume.get();
this.setVolume(0);
};
VoiceConnection.prototype.unmute = function unmute() {
this.setVolume(this.lastVolume);
this.lastVolume = undefined;
};
VoiceConnection.prototype.pause = function pause() {
this.paused = true;
this.setSpeaking(false);
this.playingIntent.emit("pause");
};
VoiceConnection.prototype.resume = function resume() {
this.paused = false;
this.setSpeaking(true);
this.playingIntent.emit("resume");
};
return VoiceConnection;
})(_events2["default"]);
exports["default"] = VoiceConnection;
module.exports = exports["default"];

View File

@@ -1,3 +1,51 @@
"use strict";exports.__esModule = true;function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}var nacl;try{nacl = require("tweetnacl");}catch(e) { // no tweetnacl!
}var nonce=new Buffer(24);nonce.fill(0);var VoicePacket=function VoicePacket(data,sequence,time,ssrc,secret){_classCallCheck(this,VoicePacket);if(!nacl){throw new Error("tweetnacl not found! Perhaps you didn't install it.");}var mac=secret?16:0;var packetLength=data.length + 12 + mac;var audioBuffer=data;var returnBuffer=new Buffer(packetLength);returnBuffer.fill(0);returnBuffer[0] = 0x80;returnBuffer[1] = 0x78;returnBuffer.writeUIntBE(sequence,2,2);returnBuffer.writeUIntBE(time,4,4);returnBuffer.writeUIntBE(ssrc,8,4);if(secret){ // copy first 12 bytes
returnBuffer.copy(nonce,0,0,12);audioBuffer = nacl.secretbox(data,nonce,secret);}for(var i=0;i < audioBuffer.length;i++) {returnBuffer[i + 12] = audioBuffer[i];}return returnBuffer;};exports["default"] = VoicePacket;module.exports = exports["default"];
"use strict";
exports.__esModule = true;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var nacl;
try {
nacl = require("tweetnacl");
} catch (e) {
// no tweetnacl!
}
var nonce = new Buffer(24);
nonce.fill(0);
var VoicePacket = function VoicePacket(data, sequence, time, ssrc, secret) {
_classCallCheck(this, VoicePacket);
if (!nacl) {
throw new Error("tweetnacl not found! Perhaps you didn't install it.");
}
var mac = secret ? 16 : 0;
var packetLength = data.length + 12 + mac;
var audioBuffer = data;
var returnBuffer = new Buffer(packetLength);
returnBuffer.fill(0);
returnBuffer[0] = 0x80;
returnBuffer[1] = 0x78;
returnBuffer.writeUIntBE(sequence, 2, 2);
returnBuffer.writeUIntBE(time, 4, 4);
returnBuffer.writeUIntBE(ssrc, 8, 4);
if (secret) {
// copy first 12 bytes
returnBuffer.copy(nonce, 0, 0, 12);
audioBuffer = nacl.secretbox(data, nonce, secret);
}
for (var i = 0; i < audioBuffer.length; i++) {
returnBuffer[i + 12] = audioBuffer[i];
}
return returnBuffer;
};
exports["default"] = VoicePacket;
module.exports = exports["default"];

View File

@@ -1,13 +1,91 @@
'use strict';var _createClass=(function(){function defineProperties(target,props){for(var i=0;i < props.length;i++) {var descriptor=props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if('value' in descriptor)descriptor.writable = true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};})();function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError('Cannot call a class as a function');}}function _inherits(subClass,superClass){if(typeof superClass !== 'function' && superClass !== null){throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass);}subClass.prototype = Object.create(superClass && superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__ = superClass;}var Transform=require('stream').Transform; /**
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Transform = require('stream').Transform;
/**
* @see https://github.com/reneraab/pcm-volume/blob/master/index.js Inspired by this script
*/var Volume=(function(_Transform){_inherits(Volume,_Transform);function Volume(volume){_classCallCheck(this,Volume);_Transform.call(this);this.set(volume);} // Set the volume so that a value of 0.5 is half the perceived volume and
// 2.0 is double the perceived volume.
Volume.prototype.setVolumeLogarithmic = function setVolumeLogarithmic(value){this.volume = Math.pow(value,1.660964);}; // Set the volume to a value specified as decibels.
Volume.prototype.setVolumeDecibels = function setVolumeDecibels(db){this.volume = Math.pow(10,db / 20);};Volume.prototype.get = function get(){return this.volume;};Volume.prototype.set = function set(volume){this.volume = volume === undefined?1:volume;};Volume.prototype._transform = function _transform(buffer,encoding,callback){var out=new Buffer(buffer.length);for(var i=0;i < buffer.length;i += 2) { // Check whether the index is actually in range - sometimes it's possible
// that it skips ahead too far before the end condition of the for can
// kick in.
if(i >= buffer.length - 1){break;} // Read Int16, multiple with multiplier and round down
//console.log(this.volume, this.multiplier, buffer.readInt16LE(i));
var uint=Math.floor(this.multiplier * buffer.readInt16LE(i)); // Ensure value stays within 16bit
uint = Math.min(32767,uint);uint = Math.max(-32767,uint); // Write 2 new bytes into other buffer;
out.writeInt16LE(uint,i);}this.push(out);callback();};_createClass(Volume,[{key:'volume',get:function get(){return this._volume === undefined?1:this._volume;},set:function set(value){this._volume = value;}},{key:'multiplier',get:function get(){return this.volume;}}]);return Volume;})(Transform);module.exports = Volume;
*/
var Volume = (function (_Transform) {
_inherits(Volume, _Transform);
function Volume(volume) {
_classCallCheck(this, Volume);
_Transform.call(this);
this.set(volume);
}
// Set the volume so that a value of 0.5 is half the perceived volume and
// 2.0 is double the perceived volume.
Volume.prototype.setVolumeLogarithmic = function setVolumeLogarithmic(value) {
this.volume = Math.pow(value, 1.660964);
};
// Set the volume to a value specified as decibels.
Volume.prototype.setVolumeDecibels = function setVolumeDecibels(db) {
this.volume = Math.pow(10, db / 20);
};
Volume.prototype.get = function get() {
return this.volume;
};
Volume.prototype.set = function set(volume) {
this.volume = volume === undefined ? 1 : volume;
};
Volume.prototype._transform = function _transform(buffer, encoding, callback) {
var out = new Buffer(buffer.length);
for (var i = 0; i < buffer.length; i += 2) {
// Check whether the index is actually in range - sometimes it's possible
// that it skips ahead too far before the end condition of the for can
// kick in.
if (i >= buffer.length - 1) {
break;
}
// Read Int16, multiple with multiplier and round down
//console.log(this.volume, this.multiplier, buffer.readInt16LE(i));
var uint = Math.floor(this.multiplier * buffer.readInt16LE(i));
// Ensure value stays within 16bit
uint = Math.min(32767, uint);
uint = Math.max(-32767, uint);
// Write 2 new bytes into other buffer;
out.writeInt16LE(uint, i);
}
this.push(out);
callback();
};
_createClass(Volume, [{
key: 'volume',
get: function get() {
return this._volume === undefined ? 1 : this._volume;
},
set: function set(value) {
this._volume = value;
}
}, {
key: 'multiplier',
get: function get() {
return this.volume;
}
}]);
return Volume;
})(Transform);
module.exports = Volume;