nile.js
Version:
A tool for scalable peer-to-peer video streaming using WebTorrent
1 lines • 411 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("Viewer",[],t):"object"==typeof exports?exports.Viewer=t():e.Viewer=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="dist",t(t.s=35)}([function(e,t,n){"use strict";var r,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(e){"object"===("undefined"==typeof window?"undefined":o(window))&&(r=window)}e.exports=r},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},o=!0,i={disableLog:function(e){return"boolean"!=typeof e?new Error("Argument type: "+(void 0===e?"undefined":r(e))+". Please use a boolean."):(o=e,e?"adapter.js logging disabled":"adapter.js logging enabled")},log:function(){if("object"===("undefined"==typeof window?"undefined":r(window))){if(o)return;"undefined"!=typeof console&&"function"==typeof console.log&&console.log.apply(console,arguments)}},extractVersion:function(e,t,n){var r=e.match(t);return r&&r.length>=n&&parseInt(r[n],10)},detectBrowser:function(){var e={};if(e.browser=null,e.version=null,"undefined"==typeof window||!window.navigator)return e.browser="Not a browser.",e;if(navigator.mozGetUserMedia)e.browser="firefox",e.version=this.extractVersion(navigator.userAgent,/Firefox\/(\d+)\./,1);else if(navigator.webkitGetUserMedia)if(window.webkitRTCPeerConnection)e.browser="chrome",e.version=this.extractVersion(navigator.userAgent,/Chrom(e|ium)\/(\d+)\./,2);else{if(!navigator.userAgent.match(/Version\/(\d+).(\d+)/))return e.browser="Unsupported webkit-based browser with GUM support but no WebRTC support.",e;e.browser="safari",e.version=this.extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1)}else if(navigator.mediaDevices&&navigator.userAgent.match(/Edge\/(\d+).(\d+)$/))e.browser="edge",e.version=this.extractVersion(navigator.userAgent,/Edge\/(\d+).(\d+)$/,2);else{if(!navigator.mediaDevices||!navigator.userAgent.match(/AppleWebKit\/(\d+)\./))return e.browser="Not a supported browser.",e;e.browser="safari",e.version=this.extractVersion(navigator.userAgent,/AppleWebKit\/(\d+)\./,1)}return e},shimCreateObjectURL:function(){if("object"===("undefined"==typeof window?"undefined":r(window))&&window.HTMLMediaElement&&"srcObject"in window.HTMLMediaElement.prototype){var e=URL.createObjectURL.bind(URL),t=URL.revokeObjectURL.bind(URL),n=new Map,o=0;URL.createObjectURL=function(t){if("getTracks"in t){var r="polyblob:"+ ++o;return n.set(r,t),console.log("URL.createObjectURL(stream) is deprecated! Use elem.srcObject = stream instead!"),r}return e(t)},URL.revokeObjectURL=function(e){t(e),n.delete(e)};var i=Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype,"src");Object.defineProperty(window.HTMLMediaElement.prototype,"src",{get:function(){return i.get.apply(this)},set:function(e){return this.srcObject=n.get(e)||null,i.set.apply(this,[e])}});var s=HTMLMediaElement.prototype.setAttribute;HTMLMediaElement.prototype.setAttribute=function(){return 2===arguments.length&&"src"===(""+arguments[0]).toLowerCase()&&(this.srcObject=n.get(arguments[1])||null),s.apply(this,arguments)}}}};e.exports={log:i.log,disableLog:i.disableLog,browserDetails:i.detectBrowser(),extractVersion:i.extractVersion,shimCreateObjectURL:i.shimCreateObjectURL,detectBrowser:i.detectBrowser.bind(i)}},function(e,t,n){"use strict";(function(e){function r(e,n){return n("b"+t.packets[e.type]+e.data.data)}function o(e,n,r){if(!n)return t.encodeBase64Packet(e,r);var o=e.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=v[e.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return r(s.buffer)}function i(e,n,r){if(!n)return t.encodeBase64Packet(e,r);var o=new FileReader;return o.onload=function(){e.data=o.result,t.encodePacket(e,n,!0,r)},o.readAsArrayBuffer(e.data)}function s(e,n,r){if(!n)return t.encodeBase64Packet(e,r);if(y)return i(e,n,r);var o=new Uint8Array(1);return o[0]=v[e.type],r(new w([o.buffer,e.data]))}function a(e){try{e=p.decode(e)}catch(e){return!1}return e}function c(e,t,n){for(var r=new Array(e.length),o=h(e.length,n),i=0;i<e.length;i++)!function(e,n,o){t(n,function(t,n){r[e]=n,o(t,r)})}(i,e[i],o)}var u,f=n(48),d=n(19),l=n(37),h=n(36),p=n(71);e&&e.ArrayBuffer&&(u=n(39));var m="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),g="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),y=m||g;t.protocol=3;var v=t.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},b=f(v),_={type:"error",data:"parser error"},w=n(40);t.encodePacket=function(t,n,i,a){"function"==typeof n&&(a=n,n=!1),"function"==typeof i&&(a=i,i=null);var c=void 0===t.data?void 0:t.data.buffer||t.data;if(e.ArrayBuffer&&c instanceof ArrayBuffer)return o(t,n,a);if(w&&c instanceof e.Blob)return s(t,n,a);if(c&&c.base64)return r(t,a);var u=v[t.type];return void 0!==t.data&&(u+=i?p.encode(String(t.data)):String(t.data)),a(""+u)},t.encodeBase64Packet=function(n,r){var o="b"+t.packets[n.type];if(w&&n.data instanceof e.Blob){var i=new FileReader;return i.onload=function(){var e=i.result.split(",")[1];r(o+e)},i.readAsDataURL(n.data)}var s;try{s=String.fromCharCode.apply(null,new Uint8Array(n.data))}catch(e){for(var a=new Uint8Array(n.data),c=new Array(a.length),u=0;u<a.length;u++)c[u]=a[u];s=String.fromCharCode.apply(null,c)}return o+=e.btoa(s),r(o)},t.decodePacket=function(e,n,r){if(void 0===e)return _;if("string"==typeof e){if("b"==e.charAt(0))return t.decodeBase64Packet(e.substr(1),n);if(r&&!1===(e=a(e)))return _;var o=e.charAt(0);return Number(o)==o&&b[o]?e.length>1?{type:b[o],data:e.substring(1)}:{type:b[o]}:_}var i=new Uint8Array(e),o=i[0],s=l(e,1);return w&&"blob"===n&&(s=new w([s])),{type:b[o],data:s}},t.decodeBase64Packet=function(e,t){var n=b[e.charAt(0)];if(!u)return{type:n,data:{base64:!0,data:e.substr(1)}};var r=u.decode(e.substr(1));return"blob"===t&&w&&(r=new w([r])),{type:n,data:r}},t.encodePayload=function(e,n,r){function o(e){return e.length+":"+e}function i(e,r){t.encodePacket(e,!!s&&n,!0,function(e){r(null,o(e))})}"function"==typeof n&&(r=n,n=null);var s=d(e);return n&&s?w&&!y?t.encodePayloadAsBlob(e,r):t.encodePayloadAsArrayBuffer(e,r):e.length?void c(e,i,function(e,t){return r(t.join(""))}):r("0:")},t.decodePayload=function(e,n,r){if("string"!=typeof e)return t.decodePayloadAsBinary(e,n,r);"function"==typeof n&&(r=n,n=null);var o;if(""==e)return r(_,0,1);for(var i,s,a="",c=0,u=e.length;c<u;c++){var f=e.charAt(c);if(":"!=f)a+=f;else{if(""==a||a!=(i=Number(a)))return r(_,0,1);if(s=e.substr(c+1,i),a!=s.length)return r(_,0,1);if(s.length){if(o=t.decodePacket(s,n,!0),_.type==o.type&&_.data==o.data)return r(_,0,1);if(!1===r(o,c+i,u))return}c+=i,a=""}}return""!=a?r(_,0,1):void 0},t.encodePayloadAsArrayBuffer=function(e,n){function r(e,n){t.encodePacket(e,!0,!0,function(e){return n(null,e)})}if(!e.length)return n(new ArrayBuffer(0));c(e,r,function(e,t){var r=t.reduce(function(e,t){var n;return n="string"==typeof t?t.length:t.byteLength,e+n.toString().length+n+2},0),o=new Uint8Array(r),i=0;return t.forEach(function(e){var t="string"==typeof e,n=e;if(t){for(var r=new Uint8Array(e.length),s=0;s<e.length;s++)r[s]=e.charCodeAt(s);n=r.buffer}o[i++]=t?0:1;for(var a=n.byteLength.toString(),s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(var r=new Uint8Array(n),s=0;s<r.length;s++)o[i++]=r[s]}),n(o.buffer)})},t.encodePayloadAsBlob=function(e,n){function r(e,n){t.encodePacket(e,!0,!0,function(e){var t=new Uint8Array(1);if(t[0]=1,"string"==typeof e){for(var r=new Uint8Array(e.length),o=0;o<e.length;o++)r[o]=e.charCodeAt(o);e=r.buffer,t[0]=0}for(var i=e instanceof ArrayBuffer?e.byteLength:e.size,s=i.toString(),a=new Uint8Array(s.length+1),o=0;o<s.length;o++)a[o]=parseInt(s[o]);if(a[s.length]=255,w){var c=new w([t.buffer,a.buffer,e]);n(null,c)}})}c(e,r,function(e,t){return n(new w(t))})},t.decodePayloadAsBinary=function(e,n,r){"function"==typeof n&&(r=n,n=null);for(var o=e,i=[],s=!1;o.byteLength>0;){for(var a=new Uint8Array(o),c=0===a[0],u="",f=1;255!=a[f];f++){if(u.length>310){s=!0;break}u+=a[f]}if(s)return r(_,0,1);o=l(o,2+u.length),u=parseInt(u);var d=l(o,0,u);if(c)try{d=String.fromCharCode.apply(null,new Uint8Array(d))}catch(e){var h=new Uint8Array(d);d="";for(var f=0;f<h.length;f++)d+=String.fromCharCode(h[f])}i.push(d),o=l(o,u)}var p=i.length;i.forEach(function(e,o){r(t.decodePacket(e,n,!0),o,p)})}}).call(t,n(0))},function(e,t,n){"use strict";function r(e){if(e)return o(e)}function o(e){for(var t in r.prototype)e[t]=r.prototype[t];return e}e.exports=r,r.prototype.on=r.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},r.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r,o=0;o<n.length;o++)if((r=n[o])===t||r.fn===t){n.splice(o,1);break}return this},r.prototype.emit=function(e){this._callbacks=this._callbacks||{};var t=[].slice.call(arguments,1),n=this._callbacks["$"+e];if(n){n=n.slice(0);for(var r=0,o=n.length;r<o;++r)n[r].apply(this,t)}return this},r.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},r.prototype.hasListeners=function(e){return!!this.listeners(e).length}},function(e,t,n){"use strict";function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(d===setTimeout)return setTimeout(e,0);if((d===r||!d)&&setTimeout)return d=setTimeout,setTimeout(e,0);try{return d(e,0)}catch(t){try{return d.call(null,e,0)}catch(t){return d.call(this,e,0)}}}function s(e){if(l===clearTimeout)return clearTimeout(e);if((l===o||!l)&&clearTimeout)return l=clearTimeout,clearTimeout(e);try{return l(e)}catch(t){try{return l.call(null,e)}catch(t){return l.call(this,e)}}}function a(){g&&p&&(g=!1,p.length?m=p.concat(m):y=-1,m.length&&c())}function c(){if(!g){var e=i(a);g=!0;for(var t=m.length;t;){for(p=m,m=[];++y<t;)p&&p[y].run();y=-1,t=m.length}p=null,g=!1,s(e)}}function u(e,t){this.fun=e,this.array=t}function f(){}var d,l,h=e.exports={};!function(){try{d="function"==typeof setTimeout?setTimeout:r}catch(e){d=r}try{l="function"==typeof clearTimeout?clearTimeout:o}catch(e){l=o}}();var p,m=[],g=!1,y=-1;h.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];m.push(new u(e,t)),1!==m.length||g||i(c)},u.prototype.run=function(){this.fun.apply(null,this.array)},h.title="browser",h.browser=!0,h.env={},h.argv=[],h.version="",h.versions={},h.on=f,h.addListener=f,h.once=f,h.off=f,h.removeListener=f,h.removeAllListeners=f,h.emit=f,h.prependListener=f,h.prependOnceListener=f,h.listeners=function(e){return[]},h.binding=function(e){throw new Error("process.binding is not supported")},h.cwd=function(){return"/"},h.chdir=function(e){throw new Error("process.chdir is not supported")},h.umask=function(){return 0}},function(e,t,n){"use strict";(function(n,r){var o,i,s,a,a,c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};!function(n){if("object"==c(t)&&void 0!==e)e.exports=n();else{i=[],o=n,void 0!==(s="function"==typeof o?o.apply(t,i):o)&&(e.exports=s)}}(function(){var e;return function e(t,n,r){function o(s,c){if(!n[s]){if(!t[s]){var u="function"==typeof a&&a;if(!c&&u)return a(s,!0);if(i)return a(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var d=n[s]={exports:{}};t[s][0].call(d.exports,function(e){return o(t[s][1][e]||e)},d,d.exports,e,t,n,r)}return n[s].exports}for(var i="function"==typeof a&&a,s=0;s<r.length;s++)o(r[s]);return o}({1:[function(e,t,n){function r(e,t){s.Readable.call(this,t),this.destroyed=!1,this._torrent=e._torrent;var n=t&&t.start||0,r=t&&t.end&&t.end<e.length?t.end:e.length-1,o=e._torrent.pieceLength;this._startPiece=(n+e.offset)/o|0,this._endPiece=(r+e.offset)/o|0,this._piece=this._startPiece,this._offset=n+e.offset-this._startPiece*o,this._missing=r-n+1,this._reading=!1,this._notifying=!1,this._criticalLength=Math.min(1048576/o|0,2)}t.exports=r;var o=e("debug")("webtorrent:file-stream"),i=e("inherits"),s=e("readable-stream");i(r,s.Readable),r.prototype._read=function(){this._reading||(this._reading=!0,this._notify())},r.prototype._notify=function(){var e=this;if(e._reading&&0!==e._missing){if(!e._torrent.bitfield.get(e._piece))return e._torrent.critical(e._piece,e._piece+e._criticalLength);if(!e._notifying){e._notifying=!0;var t=e._piece;e._torrent.store.get(t,function(n,r){if(e._notifying=!1,!e.destroyed){if(n)return e._destroy(n);o("read %s (length %s) (err %s)",t,r.length,n&&n.message),e._offset&&(r=r.slice(e._offset),e._offset=0),e._missing<r.length&&(r=r.slice(0,e._missing)),e._missing-=r.length,o("pushing buffer of length %s",r.length),e._reading=!1,e.push(r),0===e._missing&&e.push(null)}}),e._piece+=1}}},r.prototype.destroy=function(e){this._destroy(null,e)},r.prototype._destroy=function(e,t){this.destroyed||(this.destroyed=!0,this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),e&&this.emit("error",e),this.emit("close"),t&&t())}},{debug:30,inherits:41,"readable-stream":82}],2:[function(e,t,n){(function(n){function r(e,t){i.call(this),this._torrent=e,this._destroyed=!1,this.name=t.name,this.path=t.path,this.length=t.length,this.offset=t.offset,this.done=!1;var n=t.offset,r=n+t.length-1;this._startPiece=n/this._torrent.pieceLength|0,this._endPiece=r/this._torrent.pieceLength|0,0===this.length&&(this.done=!0,this.emit("done"))}t.exports=r;var o=e("end-of-stream"),i=e("events").EventEmitter,s=e("./file-stream"),a=e("inherits"),c=e("path"),u=e("render-media"),f=e("readable-stream"),d=e("stream-to-blob"),l=e("stream-to-blob-url"),h=e("stream-with-known-length-to-buffer");a(r,i),Object.defineProperty(r.prototype,"downloaded",{get:function(){if(!this._torrent.bitfield)return 0;for(var e=0,t=this._startPiece;t<=this._endPiece;++t)if(this._torrent.bitfield.get(t))e+=this._torrent.pieceLength;else{var n=this._torrent.pieces[t];e+=n.length-n.missing}return e}}),r.prototype.select=function(e){0!==this.length&&this._torrent.select(this._startPiece,this._endPiece,e)},r.prototype.deselect=function(){0!==this.length&&this._torrent.deselect(this._startPiece,this._endPiece,!1)},r.prototype.createReadStream=function(e){var t=this;if(0===this.length){var r=new f.PassThrough;return n.nextTick(function(){r.end()}),r}var i=new s(t,e);return t._torrent.select(i._startPiece,i._endPiece,!0,function(){i._notify()}),o(i,function(){t._destroyed||t._torrent.destroyed||t._torrent.deselect(i._startPiece,i._endPiece,!0)}),i},r.prototype.getBuffer=function(e){h(this.createReadStream(),this.length,e)},r.prototype.getBlob=function(e){if("undefined"==typeof window)throw new Error("browser-only method");d(this.createReadStream(),this._getMimeType(),e)},r.prototype.getBlobURL=function(e){if("undefined"==typeof window)throw new Error("browser-only method");l(this.createReadStream(),this._getMimeType(),e)},r.prototype.appendTo=function(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");u.append(this,e,t,n)},r.prototype.renderTo=function(e,t,n){if("undefined"==typeof window)throw new Error("browser-only method");u.render(this,e,t,n)},r.prototype._getMimeType=function(){return u.mime[c.extname(this.name).toLowerCase()]},r.prototype._destroy=function(){this._destroyed=!0,this._torrent=null}}).call(this,e("_process"))},{"./file-stream":1,_process:66,"end-of-stream":33,events:34,inherits:41,path:63,"readable-stream":82,"render-media":83,"stream-to-blob":100,"stream-to-blob-url":99,"stream-with-known-length-to-buffer":101}],3:[function(e,t,n){function r(e,t){var n=this;n.id=e,n.type=t,s("new Peer %s",e),n.addr=null,n.conn=null,n.swarm=null,n.wire=null,n.connected=!1,n.destroyed=!1,n.timeout=null,n.retries=0,n.sentHandshake=!1}function o(){}var i=e("unordered-array-remove"),s=e("debug")("webtorrent:peer"),a=e("bittorrent-protocol"),c=e("./webconn");n.createWebRTCPeer=function(e,t){var n=new r(e.id,"webrtc");return n.conn=e,n.swarm=t,n.conn.connected?n.onConnect():(n.conn.once("connect",function(){n.onConnect()}),n.conn.once("error",function(e){n.destroy(e)}),n.startConnectTimeout()),n},n.createTCPIncomingPeer=function(e){var t=e.remoteAddress+":"+e.remotePort,n=new r(t,"tcpIncoming");return n.conn=e,n.addr=t,n.onConnect(),n},n.createTCPOutgoingPeer=function(e,t){var n=new r(e,"tcpOutgoing");return n.addr=e,n.swarm=t,n},n.createWebSeedPeer=function(e,t){var n=new r(e,"webSeed");return n.swarm=t,n.conn=new c(e,t),n.onConnect(),n},r.prototype.onConnect=function(){var e=this;if(!e.destroyed){e.connected=!0,s("Peer %s connected",e.id),clearTimeout(e.connectTimeout);var t=e.conn;t.once("end",function(){e.destroy()}),t.once("close",function(){e.destroy()}),t.once("finish",function(){e.destroy()}),t.once("error",function(t){e.destroy(t)});var n=e.wire=new a;n.type=e.type,n.once("end",function(){e.destroy()}),n.once("close",function(){e.destroy()}),n.once("finish",function(){e.destroy()}),n.once("error",function(t){e.destroy(t)}),n.once("handshake",function(t,n){e.onHandshake(t,n)}),e.startHandshakeTimeout(),t.pipe(n).pipe(t),e.swarm&&!e.sentHandshake&&e.handshake()}},r.prototype.onHandshake=function(e,t){var n=this;if(n.swarm&&!n.destroyed){if(n.swarm.destroyed)return n.destroy(new Error("swarm already destroyed"));if(e!==n.swarm.infoHash)return n.destroy(new Error("unexpected handshake info hash for this swarm"));if(t===n.swarm.peerId)return n.destroy(new Error("refusing to connect to ourselves"));s("Peer %s got handshake %s",n.id,e),clearTimeout(n.handshakeTimeout),n.retries=0;var r=n.addr;!r&&n.conn.remoteAddress&&(r=n.conn.remoteAddress+":"+n.conn.remotePort),n.swarm._onWire(n.wire,r),n.swarm&&!n.swarm.destroyed&&(n.sentHandshake||n.handshake())}},r.prototype.handshake=function(){var e=this,t={dht:!e.swarm.private&&!!e.swarm.client.dht};e.wire.handshake(e.swarm.infoHash,e.swarm.client.peerId,t),e.sentHandshake=!0},r.prototype.startConnectTimeout=function(){var e=this;clearTimeout(e.connectTimeout),e.connectTimeout=setTimeout(function(){e.destroy(new Error("connect timeout"))},"webrtc"===e.type?25e3:5e3),e.connectTimeout.unref&&e.connectTimeout.unref()},r.prototype.startHandshakeTimeout=function(){var e=this;clearTimeout(e.handshakeTimeout),e.handshakeTimeout=setTimeout(function(){e.destroy(new Error("handshake timeout"))},25e3),e.handshakeTimeout.unref&&e.handshakeTimeout.unref()},r.prototype.destroy=function(e){var t=this;if(!t.destroyed){t.destroyed=!0,t.connected=!1,s("destroy %s (error: %s)",t.id,e&&(e.message||e)),clearTimeout(t.connectTimeout),clearTimeout(t.handshakeTimeout);var n=t.swarm,r=t.conn,a=t.wire;t.swarm=null,t.conn=null,t.wire=null,n&&a&&i(n.wires,n.wires.indexOf(a)),r&&(r.on("error",o),r.destroy()),a&&a.destroy(),n&&n.removePeer(t.id)}}},{"./webconn":6,"bittorrent-protocol":14,debug:30,"unordered-array-remove":111}],4:[function(e,t,n){function r(e){var t=this;t._torrent=e,t._numPieces=e.pieces.length,t._pieces=[],t._onWire=function(e){t.recalculate(),t._initWire(e)},t._onWireHave=function(e){t._pieces[e]+=1},t._onWireBitfield=function(){t.recalculate()},t._torrent.wires.forEach(function(e){t._initWire(e)}),t._torrent.on("wire",t._onWire),t.recalculate()}function o(){return!0}t.exports=r,r.prototype.getRarestPiece=function(e){e||(e=o);for(var t=[],n=1/0,r=0;r<this._numPieces;++r)if(e(r)){var i=this._pieces[r];i===n?t.push(r):i<n&&(t=[r],n=i)}return t.length>0?t[Math.random()*t.length|0]:-1},r.prototype.destroy=function(){var e=this;e._torrent.removeListener("wire",e._onWire),e._torrent.wires.forEach(function(t){e._cleanupWireEvents(t)}),e._torrent=null,e._pieces=null,e._onWire=null,e._onWireHave=null,e._onWireBitfield=null},r.prototype._initWire=function(e){var t=this;e._onClose=function(){t._cleanupWireEvents(e);for(var n=0;n<this._numPieces;++n)t._pieces[n]-=e.peerPieces.get(n)},e.on("have",t._onWireHave),e.on("bitfield",t._onWireBitfield),e.once("close",e._onClose)},r.prototype.recalculate=function(){var e;for(e=0;e<this._numPieces;++e)this._pieces[e]=0;var t=this._torrent.wires.length;for(e=0;e<t;++e)for(var n=this._torrent.wires[e],r=0;r<this._numPieces;++r)this._pieces[r]+=n.peerPieces.get(r)},r.prototype._cleanupWireEvents=function(e){e.removeListener("have",this._onWireHave),e.removeListener("bitfield",this._onWireBitfield),e._onClose&&e.removeListener("close",e._onClose),e._onClose=null}},{}],5:[function(e,t,r){(function(n,r){function o(e,t,n){m.call(this),this._debugId="unknown infohash",this.client=t,this.announce=n.announce,this.urlList=n.urlList,this.path=n.path,this._store=n.store||b,this._getAnnounceOpts=n.getAnnounceOpts,this.strategy=n.strategy||"sequential",this.maxWebConns=n.maxWebConns||4,this._rechokeNumSlots=!1===n.uploads||0===n.uploads?0:+n.uploads||10,this._rechokeOptimisticWire=null,this._rechokeOptimisticTime=0,this._rechokeIntervalId=null,this.ready=!1,this.destroyed=!1,this.paused=!1,this.done=!1,this.metadata=null,this.store=null,this.files=[],this.pieces=[],this._amInterested=!1,this._selections=[],this._critical=[],this.wires=[],this._queue=[],this._peers={},this._peersLength=0,this.received=0,this.uploaded=0,this._downloadSpeed=O(),this._uploadSpeed=O(),this._servers=[],this._xsRequests=[],this._fileModtimes=n.fileModtimes,null!==e&&this._onTorrentId(e),this._debug("new torrent")}function i(e,t){return 2+Math.ceil(t*e.downloadSpeed()/R.BLOCK_LENGTH)}function s(e,t,n){return 1+Math.ceil(t*e.downloadSpeed()/n)}function a(e){return Math.random()*e|0}function c(){}t.exports=o;var u,f=e("addr-to-ip-port"),d=e("bitfield"),l=e("chunk-store-stream/write"),h=e("debug")("webtorrent:torrent"),p=e("torrent-discovery"),m=e("events").EventEmitter,g=e("xtend"),y=e("xtend/mutable"),v=e("fs"),b=e("fs-chunk-store"),_=e("simple-get"),w=e("immediate-chunk-store"),k=e("inherits"),E=e("multistream"),S=e("net"),x=e("os"),C=e("run-parallel"),T=e("run-parallel-limit"),A=e("parse-torrent"),I=e("path"),R=e("torrent-piece"),B=e("pump"),P=e("random-iterate"),L=e("simple-sha1"),O=e("speedometer"),U=e("uniq"),M=e("ut_metadata"),j=e("ut_pex"),D=e("./file"),N=e("./peer"),H=e("./rarity-map"),q=e("./server"),F=5e3,z=3*R.BLOCK_LENGTH,W=[1e3,5e3,15e3],G=e("../package.json").version,V="WebTorrent/"+G+" (https://webtorrent.io)";try{u=I.join(v.statSync("/tmp")&&"/tmp","webtorrent")}catch(e){u=I.join("function"==typeof x.tmpdir?x.tmpdir():"/","webtorrent")}k(o,m),Object.defineProperty(o.prototype,"timeRemaining",{get:function(){return this.done?0:0===this.downloadSpeed?1/0:(this.length-this.downloaded)/this.downloadSpeed*1e3}}),Object.defineProperty(o.prototype,"downloaded",{get:function(){if(!this.bitfield)return 0;for(var e=0,t=0,n=this.pieces.length;t<n;++t)if(this.bitfield.get(t))e+=t===n-1?this.lastPieceLength:this.pieceLength;else{var r=this.pieces[t];e+=r.length-r.missing}return e}}),Object.defineProperty(o.prototype,"downloadSpeed",{get:function(){return this._downloadSpeed()}}),Object.defineProperty(o.prototype,"uploadSpeed",{get:function(){return this._uploadSpeed()}}),Object.defineProperty(o.prototype,"progress",{get:function(){return this.length?this.downloaded/this.length:0}}),Object.defineProperty(o.prototype,"ratio",{get:function(){return this.uploaded/(this.received||1)}}),Object.defineProperty(o.prototype,"numPeers",{get:function(){return this.wires.length}}),Object.defineProperty(o.prototype,"torrentFileBlobURL",{get:function(){if("undefined"==typeof window)throw new Error("browser-only property");return this.torrentFile?URL.createObjectURL(new Blob([this.torrentFile],{type:"application/x-bittorrent"})):null}}),Object.defineProperty(o.prototype,"_numQueued",{get:function(){return this._queue.length+(this._peersLength-this._numConns)}}),Object.defineProperty(o.prototype,"_numConns",{get:function(){var e=this,t=0;for(var n in e._peers)e._peers[n].connected&&(t+=1);return t}}),Object.defineProperty(o.prototype,"swarm",{get:function(){return console.warn("WebTorrent: `torrent.swarm` is deprecated. Use `torrent` directly instead."),this}}),o.prototype._onTorrentId=function(e){var t=this;if(!t.destroyed){var r;try{r=A(e)}catch(e){}r?(t.infoHash=r.infoHash,t._debugId=r.infoHash.toString("hex").substring(0,7),n.nextTick(function(){t.destroyed||t._onParsedTorrent(r)})):A.remote(e,function(e,n){if(!t.destroyed)return e?t._destroy(e):void t._onParsedTorrent(n)})}},o.prototype._onParsedTorrent=function(e){var t=this;if(!t.destroyed){if(t._processParsedTorrent(e),!t.infoHash)return t._destroy(new Error("Malformed torrent data: No info hash"));t.path||(t.path=I.join(u,t.infoHash)),t._rechokeIntervalId=setInterval(function(){t._rechoke()},1e4),t._rechokeIntervalId.unref&&t._rechokeIntervalId.unref(),t.emit("_infoHash",t.infoHash),t.destroyed||(t.emit("infoHash",t.infoHash),t.destroyed||(t.client.listening?t._onListening():t.client.once("listening",function(){t._onListening()})))}},o.prototype._processParsedTorrent=function(e){this._debugId=e.infoHash.toString("hex").substring(0,7),this.announce&&(e.announce=e.announce.concat(this.announce)),this.client.tracker&&r.WEBTORRENT_ANNOUNCE&&!this.private&&(e.announce=e.announce.concat(r.WEBTORRENT_ANNOUNCE)),this.urlList&&(e.urlList=e.urlList.concat(this.urlList)),U(e.announce),U(e.urlList),y(this,e),this.magnetURI=A.toMagnetURI(e),this.torrentFile=A.toTorrentFile(e)},o.prototype._onListening=function(){function e(e){i._destroy(e)}function t(e){"string"==typeof e&&i.done||i.addPeer(e)}function n(){i.emit("trackerAnnounce"),0===i.numPeers&&i.emit("noPeers","tracker")}function r(){i.emit("dhtAnnounce"),0===i.numPeers&&i.emit("noPeers","dht")}function o(e){i.emit("warning",e)}var i=this;if(!i.discovery&&!i.destroyed){var s=i.client.tracker;s&&(s=g(i.client.tracker,{getAnnounceOpts:function(){var e={uploaded:i.uploaded,downloaded:i.downloaded,left:Math.max(i.length-i.downloaded,0)};return i.client.tracker.getAnnounceOpts&&y(e,i.client.tracker.getAnnounceOpts()),i._getAnnounceOpts&&y(e,i._getAnnounceOpts()),e}})),i.discovery=new p({infoHash:i.infoHash,announce:i.announce,peerId:i.client.peerId,dht:!i.private&&i.client.dht,tracker:s,port:i.client.torrentPort,userAgent:V}),i.discovery.on("error",e),i.discovery.on("peer",t),i.discovery.on("trackerAnnounce",n),i.discovery.on("dhtAnnounce",r),i.discovery.on("warning",o),i.info?i._onMetadata(i):i.xs&&i._getMetadataFromServer()}},o.prototype._getMetadataFromServer=function(){function e(e,n){function r(r,o,i){if(t.destroyed)return n(null);if(t.metadata)return n(null);if(r)return t.emit("warning",new Error("http error from xs param: "+e)),n(null);if(200!==o.statusCode)return t.emit("warning",new Error("non-200 status code "+o.statusCode+" from xs param: "+e)),n(null);var s;try{s=A(i)}catch(r){}return s?s.infoHash!==t.infoHash?(t.emit("warning",new Error("got torrent file with incorrect info hash from xs param: "+e)),n(null)):(t._onMetadata(s),void n(null)):(t.emit("warning",new Error("got invalid torrent file from xs param: "+e)),n(null))}if(0!==e.indexOf("http://")&&0!==e.indexOf("https://"))return t.emit("warning",new Error("skipping non-http xs param: "+e)),n(null);var o,i={url:e,method:"GET",headers:{"user-agent":V}};try{o=_.concat(i,r)}catch(r){return t.emit("warning",new Error("skipping invalid url xs param: "+e)),n(null)}t._xsRequests.push(o)}var t=this,n=Array.isArray(t.xs)?t.xs:[t.xs],r=n.map(function(t){return function(n){e(t,n)}});C(r)},o.prototype._onMetadata=function(e){var t=this;if(!t.metadata&&!t.destroyed){t._debug("got metadata"),t._xsRequests.forEach(function(e){e.abort()}),t._xsRequests=[];var n;if(e&&e.infoHash)n=e;else try{n=A(e)}catch(e){return t._destroy(e)}t._processParsedTorrent(n),t.metadata=t.torrentFile,t.client.enableWebSeeds&&t.urlList.forEach(function(e){t.addWebSeed(e)}),0!==t.pieces.length&&t.select(0,t.pieces.length-1,!1),t._rarityMap=new H(t),t.store=new w(new t._store(t.pieceLength,{torrent:{infoHash:t.infoHash},files:t.files.map(function(e){return{path:I.join(t.path,e.path),length:e.length,offset:e.offset}}),length:t.length})),t.files=t.files.map(function(e){return new D(t,e)}),t._hashes=t.pieces,t.pieces=t.pieces.map(function(e,n){var r=n===t.pieces.length-1?t.lastPieceLength:t.pieceLength;return new R(r)}),t._reservations=t.pieces.map(function(){return[]}),t.bitfield=new d(t.pieces.length),t.wires.forEach(function(e){e.ut_metadata&&e.ut_metadata.setMetadata(t.metadata),t._onWireWithMetadata(e)}),t._debug("verifying existing torrent data"),t._fileModtimes&&t._store===b?t.getFileModtimes(function(e,n){if(e)return t._destroy(e);if(t.files.map(function(e,r){return n[r]===t._fileModtimes[r]}).every(function(e){return e})){for(var r=0;r<t.pieces.length;r++)t._markVerified(r);t._onStore()}else t._verifyPieces()}):t._verifyPieces(),t.emit("metadata")}},o.prototype.getFileModtimes=function(e){var t=this,n=[];T(t.files.map(function(e,r){return function(o){v.stat(I.join(t.path,e.path),function(e,t){if(e&&"ENOENT"!==e.code)return o(e);n[r]=t&&t.mtime.getTime(),o(null)})}}),2,function(r){t._debug("done getting file modtimes"),e(r,n)})},o.prototype._verifyPieces=function(){var e=this;T(e.pieces.map(function(t,r){return function(t){if(e.destroyed)return t(new Error("torrent is destroyed"));e.store.get(r,function(o,i){return e.destroyed?t(new Error("torrent is destroyed")):o?n.nextTick(t,null):void L(i,function(n){if(e.destroyed)return t(new Error("torrent is destroyed"));if(n===e._hashes[r]){if(!e.pieces[r])return;e._debug("piece verified %s",r),e._markVerified(r)}else e._debug("piece invalid %s",r);t(null)})})}}),2,function(t){if(t)return e._destroy(t);e._debug("done verifying"),e._onStore()})},o.prototype._markVerified=function(e){this.pieces[e]=null,this._reservations[e]=null,this.bitfield.set(e,!0)},o.prototype._onStore=function(){var e=this;e.destroyed||(e._debug("on store"),e.ready=!0,e.emit("ready"),e._checkDone(),e._updateSelections())},o.prototype.destroy=function(e){this._destroy(null,e)},o.prototype._destroy=function(e,t){var n=this;if(!n.destroyed){n.destroyed=!0,n._debug("destroy"),n.client._remove(n),clearInterval(n._rechokeIntervalId),n._xsRequests.forEach(function(e){e.abort()}),n._rarityMap&&n._rarityMap.destroy();for(var r in n._peers)n.removePeer(r);n.files.forEach(function(e){e instanceof D&&e._destroy()});var o=n._servers.map(function(e){return function(t){e.destroy(t)}});n.discovery&&o.push(function(e){n.discovery.destroy(e)}),n.store&&o.push(function(e){n.store.close(e)}),C(o,t),e&&(0===n.listenerCount("error")?n.client.emit("error",e):n.emit("error",e)),n.emit("close"),n.client=null,n.files=[],n.discovery=null,n.store=null,n._rarityMap=null,n._peers=null,n._servers=null,n._xsRequests=null}},o.prototype.addPeer=function(e){var t=this;if(t.destroyed)throw new Error("torrent is destroyed");if(!t.infoHash)throw new Error("addPeer() must not be called before the `infoHash` event");if(t.client.blocked){var n;if("string"==typeof e){var r;try{r=f(e)}catch(n){return t._debug("ignoring peer: invalid %s",e),t.emit("invalidPeer",e),!1}n=r[0]}else"string"==typeof e.remoteAddress&&(n=e.remoteAddress);if(n&&t.client.blocked.contains(n))return t._debug("ignoring peer: blocked %s",e),"string"!=typeof e&&e.destroy(),t.emit("blockedPeer",e),!1}var o=!!t._addPeer(e);return o?t.emit("peer",e):t.emit("invalidPeer",e),o},o.prototype._addPeer=function(e){var t=this;if(t.destroyed)return"string"!=typeof e&&e.destroy(),null;if("string"==typeof e&&!t._validAddr(e))return t._debug("ignoring peer: invalid %s",e),null;var n=e&&e.id||e;if(t._peers[n])return t._debug("ignoring peer: duplicate (%s)",n),"string"!=typeof e&&e.destroy(),null;if(t.paused)return t._debug("ignoring peer: torrent is paused"),"string"!=typeof e&&e.destroy(),null;t._debug("add peer %s",n);var r;return r="string"==typeof e?N.createTCPOutgoingPeer(e,t):N.createWebRTCPeer(e,t),t._peers[r.id]=r,t._peersLength+=1,"string"==typeof e&&(t._queue.push(r),t._drain()),r},o.prototype.addWebSeed=function(e){if(this.destroyed)throw new Error("torrent is destroyed");if(!/^https?:\/\/.+/.test(e))return this.emit("warning",new Error("ignoring invalid web seed: "+e)),void this.emit("invalidPeer",e);if(this._peers[e])return this.emit("warning",new Error("ignoring duplicate web seed: "+e)),void this.emit("invalidPeer",e);this._debug("add web seed %s",e);var t=N.createWebSeedPeer(e,this);this._peers[t.id]=t,this._peersLength+=1,this.emit("peer",e)},o.prototype._addIncomingPeer=function(e){var t=this;return t.destroyed?e.destroy(new Error("torrent is destroyed")):t.paused?e.destroy(new Error("torrent is paused")):(this._debug("add incoming peer %s",e.id),t._peers[e.id]=e,void(t._peersLength+=1))},o.prototype.removePeer=function(e){var t=this,n=e&&e.id||e;(e=t._peers[n])&&(this._debug("removePeer %s",n),delete t._peers[n],t._peersLength-=1,e.destroy(),t._drain())},o.prototype.select=function(e,t,n,r){var o=this;if(o.destroyed)throw new Error("torrent is destroyed");if(e<0||t<e||o.pieces.length<=t)throw new Error("invalid selection ",e,":",t);n=Number(n)||0,o._debug("select %s-%s (priority %s)",e,t,n),o._selections.push({from:e,to:t,offset:0,priority:n,notify:r||c}),o._selections.sort(function(e,t){return t.priority-e.priority}),o._updateSelections()},o.prototype.deselect=function(e,t,n){var r=this;if(r.destroyed)throw new Error("torrent is destroyed");n=Number(n)||0,r._debug("deselect %s-%s (priority %s)",e,t,n);for(var o=0;o<r._selections.length;++o){var i=r._selections[o];if(i.from===e&&i.to===t&&i.priority===n){r._selections.splice(o,1);break}}r._updateSelections()},o.prototype.critical=function(e,t){var n=this;if(n.destroyed)throw new Error("torrent is destroyed");n._debug("critical %s-%s",e,t);for(var r=e;r<=t;++r)n._critical[r]=!0;n._updateSelections()},o.prototype._onWire=function(e,t){var r=this;if(r._debug("got wire %s (%s)",e._debugId,t||"Unknown"),e.on("download",function(e){r.destroyed||(r.received+=e,r._downloadSpeed(e),r.client._downloadSpeed(e),r.emit("download",e),r.client.emit("download",e))}),e.on("upload",function(e){r.destroyed||(r.uploaded+=e,r._uploadSpeed(e),r.client._uploadSpeed(e),r.emit("upload",e),r.client.emit("upload",e))}),r.wires.push(e),t){var o=f(t);e.remoteAddress=o[0],e.remotePort=o[1]}r.client.dht&&r.client.dht.listening&&e.on("port",function(n){if(!r.destroyed&&!r.client.dht.destroyed){if(!e.remoteAddress)return r._debug("ignoring PORT from peer with no address");if(0===n||n>65536)return r._debug("ignoring invalid PORT from peer");r._debug("port: %s (from %s)",n,t),r.client.dht.addNode({host:e.remoteAddress,port:n})}}),e.on("timeout",function(){r._debug("wire timeout (%s)",t),e.destroy()}),e.setTimeout(3e4,!0),e.setKeepAlive(!0),e.use(M(r.metadata)),e.ut_metadata.on("warning",function(e){r._debug("ut_metadata warning: %s",e.message)}),r.metadata||(e.ut_metadata.on("metadata",function(e){r._debug("got metadata via ut_metadata"),r._onMetadata(e)}),e.ut_metadata.fetch()),"function"!=typeof j||r.private||(e.use(j()),e.ut_pex.on("peer",function(e){r.done||(r._debug("ut_pex: got peer: %s (from %s)",e,t),r.addPeer(e))}),e.ut_pex.on("dropped",function(e){var n=r._peers[e];n&&!n.connected&&(r._debug("ut_pex: dropped peer: %s (from %s)",e,t),r.removePeer(e))}),e.once("close",function(){e.ut_pex.reset()})),r.emit("wire",e,t),r.metadata&&n.nextTick(function(){r._onWireWithMetadata(e)})},o.prototype._onWireWithMetadata=function(e){function t(){o.destroyed||e.destroyed||(o._numQueued>2*(o._numConns-o.numPeers)&&e.amInterested?e.destroy():(i=setTimeout(t,F),i.unref&&i.unref()))}function n(){if(e.peerPieces.buffer.length===o.bitfield.buffer.length){for(r=0;r<o.pieces.length;++r)if(!e.peerPieces.get(r))return;e.isSeeder=!0,e.choke()}}var r,o=this,i=null;e.on("bitfield",function(){n(),o._update()}),e.on("have",function(){n(),o._update()}),e.once("interested",function(){e.unchoke()}),e.once("close",function(){clearTimeout(i)}),e.on("choke",function(){clearTimeout(i),i=setTimeout(t,F),i.unref&&i.unref()}),e.on("unchoke",function(){clearTimeout(i),o._update()}),e.on("request",function(t,n,r,i){if(r>131072)return e.destroy();o.pieces[t]||o.store.get(t,{offset:n,length:r},i)}),e.bitfield(o.bitfield),e.interested(),e.peerExtensions.dht&&o.client.dht&&o.client.dht.listening&&e.port(o.client.dht.address().port),"webSeed"!==e.type&&(i=setTimeout(t,F),i.unref&&i.unref()),e.isSeeder=!1,n()},o.prototype._updateSelections=function(){var e=this;e.ready&&!e.destroyed&&(n.nextTick(function(){e._gcSelections()}),e._updateInterest(),e._update())},o.prototype._gcSelections=function(){for(var e=this,t=0;t<e._selections.length;++t){for(var n=e._selections[t],r=n.offset;e.bitfield.get(n.from+n.offset)&&n.from+n.offset<n.to;)n.offset+=1;r!==n.offset&&n.notify(),n.to===n.from+n.offset&&e.bitfield.get(n.from+n.offset)&&(e._selections.splice(t,1),t-=1,n.notify(),e._updateInterest())}e._selections.length||e.emit("idle")},o.prototype._updateInterest=function(){var e=this,t=e._amInterested;e._amInterested=!!e._selections.length,e.wires.forEach(function(t){e._amInterested?t.interested():t.uninterested()}),t!==e._amInterested&&(e._amInterested?e.emit("interested"):e.emit("uninterested"))},o.prototype._update=function(){var e=this;if(!e.destroyed)for(var t,n=P(e.wires);t=n();)e._updateWire(t)},o.prototype._updateWire=function(e){function t(t,n,r,o){return function(i){return i>=t&&i<=n&&!(i in r)&&e.peerPieces.get(i)&&(!o||o(i))}}function n(){var t=e.downloadSpeed()||1;if(t>z)return function(){return!0};var n=Math.max(1,e.requests.length)*R.BLOCK_LENGTH/t,r=10,o=0;return function(e){if(!r||s.bitfield.get(e))return!0;for(var i=s.pieces[e].missing;o<s.wires.length;o++){var a=s.wires[o],c=a.downloadSpeed();if(!(c<z)&&!(c<=t)&&a.peerPieces.get(e)&&!((i-=c*n)>0))return r--,!1}return!0}}function r(e){for(var t=e,n=e;n<s._selections.length&&s._selections[n].priority;n++)t=n;var r=s._selections[e];s._selections[e]=s._selections[t],s._selections[t]=r}function o(o){if(e.requests.length>=c)return!0;for(var i=n(),a=0;a<s._selections.length;a++){var u,f=s._selections[a];if("rarest"===s.strategy)for(var d=f.from+f.offset,l=f.to,h=l-d+1,p={},m=0,g=t(d,l,p,i);m<h&&!((u=s._rarityMap.getRarestPiece(g))<0);){for(;s._request(e,u,s._critical[u]||o););if(!(e.requests.length<c))return f.priority&&r(a),!0;p[u]=!0,m++}else for(u=f.from+f.offset;u<=f.to;u++)if(e.peerPieces.get(u)&&i(u)){for(;s._request(e,u,s._critical[u]||o););if(!(e.requests.length<c))return f.priority&&r(a),!0}}return!1}var s=this;if(!e.peerChoking){if(!e.downloaded)return function(){if(!e.requests.length)for(var n=s._selections.length;n--;){var r,o=s._selections[n];if("rarest"===s.strategy)for(var i=o.from+o.offset,a=o.to,c=a-i+1,u={},f=0,d=t(i,a,u);f<c&&!((r=s._rarityMap.getRarestPiece(d))<0);){if(s._request(e,r,!1))return;u[r]=!0,f+=1}else for(r=o.to;r>=o.from+o.offset;--r)if(e.peerPieces.get(r)&&s._request(e,r,!1))return}}();var a=i(e,.5);if(!(e.requests.length>=a)){var c=i(e,1);o(!1)||o(!0)}}},o.prototype._rechoke=function(){function e(e,t){return e.downloadSpeed!==t.downloadSpeed?t.downloadSpeed-e.downloadSpeed:e.uploadSpeed!==t.uploadSpeed?t.uploadSpeed-e.uploadSpeed:e.wire.amChoking!==t.wire.amChoking?e.wire.amChoking?1:-1:e.salt-t.salt}var t=this;if(t.ready){t._rechokeOptimisticTime>0?t._rechokeOptimisticTime-=1:t._rechokeOptimisticWire=null;var n=[];t.wires.forEach(function(e){e.isSeeder||e===t._rechokeOptimisticWire||n.push({wire:e,downloadSpeed:e.downloadSpeed(),uploadSpeed:e.uploadSpeed(),salt:Math.random(),isChoked:!0})}),n.sort(e);for(var r=0,o=0;o<n.length&&r<t._rechokeNumSlots;++o)n[o].isChoked=!1,n[o].wire.peerInterested&&(r+=1);if(!t._rechokeOptimisticWire&&o<n.length&&t._rechokeNumSlots){var i=n.slice(o).filter(function(e){return e.wire.peerInterested}),s=i[a(i.length)];s&&(s.isChoked=!1,t._rechokeOptimisticWire=s.wire,t._rechokeOptimisticTime=2)}n.forEach(function(e){e.wire.amChoking!==e.isChoked&&(e.isChoked?e.wire.choke():e.wire.unchoke())})}},o.prototype._hotswap=function(e,t){var n=this,r=e.downloadSpeed();if(r<R.BLOCK_LENGTH)return!1;if(!n._reservations[t])return!1;var o=n._reservations[t];if(!o)return!1;var i,s,a=1/0;for(s=0;s<o.length;s++){var c=o[s];if(c&&c!==e){var u=c.downloadSpeed();u>=z||2*u>r||u>a||(i=c,a=u)}}if(!i)return!1;for(s=0;s<o.length;s++)o[s]===i&&(o[s]=null);for(s=0;s<i.requests.length;s++){var f=i.requests[s];f.piece===t&&n.pieces[t].cancel(f.offset/R.BLOCK_LENGTH|0)}return n.emit("hotswap",i,e,t),!0},o.prototype._request=function(e,t,r){function o(){n.nextTick(function(){a._update()})}var a=this,c=e.requests.length,u="webSeed"===e.type;if(a.bitfield.get(t))return!1;if(c>=(u?Math.min(s(e,1,a.pieceLength),a.maxWebConns):i(e,1)))return!1;var f=a.pieces[t],d=u?f.reserveRemaining():f.reserve();if(-1===d&&r&&a._hotswap(e,t)&&(d=u?f.reserveRemaining():f.reserve()),-1===d)return!1;var l=a._reservations[t];l||(l=a._reservations[t]=[]);var h=l.indexOf(null);-1===h&&(h=l.length),l[h]=e;var p=f.chunkOffset(d),m=u?f.chunkLengthRemaining(d):f.chunkLength(d);return e.request(t,p,m,function n(r,i){if(!a.destroyed){if(!a.ready)return a.once("ready",function(){n(r,i)});if(l[h]===e&&(l[h]=null),f!==a.pieces[t])return o();if(r)return a._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,p,m,e.remoteAddress+":"+e.remotePort,r.message),u?f.cancelRemaining(d):f.cancel(d),void o();if(a._debug("got piece %s (offset: %s length: %s) from %s",t,p,m,e.remoteAddress+":"+e.remotePort),!f.set(d,i,e))return o();var s=f.flush();L(s,function(e){if(!a.destroyed){if(e===a._hashes[t]){if(!a.pieces[t])return;a._debug("piece verified %s",t),a.pieces[t]=null,a._reservations[t]=null,a.bitfield.set(t,!0),a.store.put(t,s),a.wires.forEach(function(e){e.have(t)}),a._checkDone()&&!a.destroyed&&a.discovery.complete()}else a.pieces[t]=new R(f.length),a.emit("warning",new Error("Piece "+t+" failed verification"));o()}})}}),!0},o.prototype._checkDone=function(){var e=this;if(!e.destroyed){e.files.forEach(function(t){if(!t.done){for(var n=t._startPiece;n<=t._endPiece;++n)if(!e.bitfield.get(n))return;t.done=!0,t.emit("done"),e._debug("file done: "+t.name)}});for(var t=!0,n=0;n<e._selections.length;n++){for(var r=e._selections[n],o=r.from;o<=r.to;o++)if(!e.bitfield.get(o)){t=!1;break}if(!t)break}return!e.done&&t&&(e.done=!0,e._debug("torrent done: "+e.infoHash),e.emit("done")),e._gcSelections(),t}},o.prototype.load=function(e,t){var n=this;if(n.destroyed)throw new Error("torrent is destroyed");if(!n.ready)return n.once("ready",function(){n.load(e,t)});Array.isArray(e)||(e=[e]),t||(t=c);var r=new E(e),o=new l(n.store,n.pieceLength);B(r,o,function(e){if(e)return t(e);n.pieces.forEach(function(e,t){n.pieces[t]=null,n._reservations[t]=null,n.bitfield.set(t,!0)}),n._checkDone(),t(null)})},o.prototype.createServer=function(e){if("function"!=typeof q)throw new Error("node.js-only method");if(this.destroyed)throw new Error("torrent is destroyed");var t=new q(this,e);return this._servers.push(t),t},o.prototype.pause=function(){this.destroyed||(this._debug("pause"),this.paused=!0)},o.prototype.resume=function(){this.destroyed||(this._debug("resume"),this.paused=!1,this._drain())},o.prototype._debug=function(){var e=[].slice.call(arguments);e[0]="["+this.client._debugId+"] ["+this._debugId+"] "+e[0],h.apply(null,e)},o.prototype._drain=function(){var e=this;if(this._debug("_drain numConns %s maxConns %s",e._numConns,e.client.maxConns),!("function"!=typeof S.connect||e.destroyed||e.paused||e._numConns>=e.client.maxConns)){this._debug("drain (%s queued, %s/%s peers)",e._numQueued,e.numPeers,e.client.maxConns);var t=e._queue.shift();if(t){this._debug("tcp connect attempt to %s",t.addr);var n=f(t.addr),r={host:n[0],port:n[1]},o=t.conn=S.connect(r);o.once("connect",function(){t.onConnect()}),o.once("error",function(e){t.destroy(e)}),t.startConnectTimeout(),o.on("close",function(){if(!e.destroyed){if(t.retries>=W.length)return void e._debug("conn %s closed: will not re-add (max %s attempts)",t.addr,W.length);var n=W[t.retries];e._debug("conn %s closed: will re-add to queue in %sms (attempt %s)",t.addr,n,t.retries+1);var r=setTimeout(function(){var n=e._addPeer(t.addr);n&&(n.retries=t.retries+1)},n);r.unref&&r.unref()}})}}},o.prototype._validAddr=function(e){var t;try{t=f(e)}catch(e){return!1}var n=t[0],r=t[1];return r>0&&r<65535&&!("127.0.0.1"===n&&r===this.client.torrentPort)}}).call(this,e("_process"),void 0!==n?n:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../package.json":122,"./file":2,"./peer":3,"./rarity-map":4,"./server":21,_process:66,"addr-to-ip-port":7,bitfield:13,"chunk-store-stream/write":26,debug:30,events:34,fs:22,"fs-chunk-store":50,"immediate-chunk-store":40,inherits:41,multistream:58,net:21,os:21,"parse-torrent":62,path:63,pump:67,"random-iterate":72,"run-parallel":86,"run-parallel-limit":85,"simple-get":90,"simple-sha1":92,speedometer:94,"torrent-discovery":106,"torrent-piece":107,uniq:110,ut_metadata:114,ut_pex:21,xtend:119,"xtend/mutable":120}],6:[function(e,t,n){function r(e,t){f.call(this),this.url=e,this.webPeerId=u.sync(e),this._torrent=t,this._init()}t.exports=r;var o=e("bitfield"),i=e("safe-buffer").Buffer,s=e("debug")("webtorrent:webconn"),a=e("simple-get"),c=e("inherits"),u=e("simple-sha1"),f=e("bittorrent-protocol"),d=e("../package.json").version;c(r,f),r.prototype._init=function(){var e=this;e.setKeepAlive(!0),e.once("handshake",function(t,n){if(!e.destroyed){e.handshake(t,e.webPeerId);for(var r=e._torrent.pieces.length,i=new o(r),s=0;s<=r;s++)i.set(s,!0);e.bitfield(i)}}),e.once("interested",function(){s("interested"),e.unchoke()}),e.on("uninterested",function(){s("uninterested")}),e.on("choke",function(){s("choke")}),e.on("unchoke",function(){s("unchoke")}),e.on("bitfield",function(){s("bitfield")}),e.on("request",function(t,n,r,o){s("request pieceIndex=%d offset=%d length=%d",t,n,r),e.httpRequest(t,n,r,o)})},r.prototype.httpRequest=function(e,t,n,r){var o,c=this,u=e*c._torrent.pieceLength,f=u+t,l=f+n-1,h=c._torrent.files;if(h.length<=1)o=[{url:c.url,start:f,end:l}];else{var p=h.filter(function(e){return e.offset<=l&&e.offset+e.length>f});if(p.length<1)return r(new Error("Could not find file corresponnding to web seed range request"));o=p.map(function(e){var t=e.offset+e.length-1;return{url:c.url+("/"===c.url[c.url.length-1]?"":"/")+e.path,fileOffsetInRange:Math.max(e.offset-f,0),start:Math.max(f-e.offset,0),end:Math.min(t,l-e.offset)}})}var m,g=0,y=!1;o.length>1&&(m=i.alloc(n)),o.forEach(function(i){function c(e,t){if(e.statusCode<200||e.statusCode>=300)return y=!0,r(new Error("Unexpected HTTP status code "+e.statusCode));s("Got data of length %d",t.length),1===o.length?r(null,t):(t.copy(m,i.fileOffsetInRange),++g===o.length&&r(null,m))}var u=i.url,f=i.start,l=i.end;s("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",u,e,t,n,f,l);var h={url:u,method:"GET",headers:{"user-agent":"WebTorrent/"+d+" (https://webtorrent.io)",range:"bytes="+f+"-"+l}};a.concat(h,function(e,t,n){if(!y)return e?"undefined"==typeof window||u.startsWith(window.location.origin+"/")?(y=!0,r(e)):a.head(u,function(t,n){if(!y){if(t)return y=!0,r(t);if(n.statusCode<200||n.statusCode>=300)return y=!0,r(new Error("Unexpected HTTP status code "+n.statusCode));if(n.url===u)return y=!0,r(e);h.url=n.url,a.concat(h,function(e,t,n){if(!y)return e?(y=!0,r(e)):void c(t,n)})}}):void c(t,n)})})},r.prototype.destroy=function(){f.prototype.destroy.call(this),this._torrent=null}},{"../package.json":122,bitfield:13,"bittorrent-protocol":14,debug:30,inherits:41,"safe-buffer":88,"simple-get":90,"simple-sha1":92}],7:[function(e,t,n){var r=/^\[?([^\]]+)\]?:(\d+)$/,o={},i=0;t.exports=function(e){if(1e5===i&&t.exports.reset(),!o[e]){var n=r.exec(e);if(!n)throw new Error("invalid addr: "+e);o[e]=[n[1],Number(n[2])],i+=1}return o[e]},t.exports.reset=function(){o={},i=0}},{}],8:[function(e,t,n){function r(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===e[t-2]?2:"="===e[t-1]?1:0}function o(e){return 3*e.length/4-r(e)}function i(e){var t,n,o,i,s,a,c=e.length;s=r(e),a=new d(3*c/4-s),o=s>0?c-4:c;var u=0;for(t=0,n=0;t<o;t+=4,n+=3)i=f[e.charCodeAt(t)]<<18|f[e.charCodeAt(t+1)]<<12|f[e.charCodeAt(t+2)]<<6|f[e.charCodeAt(t+3)],a[u++]=i>>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===s?(i=f[e.charCodeAt(t)]<<2|f[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===s&&(i=f[e.charCodeAt(t)]<<10|f[e.charCodeAt(t+1)]<<4|f[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}function s(e){return u[e>>18&63]+u[e>>12&63]+u[e>>6&63]+u[63&e]}function a(e,t,n){for(var r,o=[],i=t;i<n;i+=3)r=(e[i]<<16)+(e[i+1]<<8)+e[i+2],o.push(s(r));return o.join("")}function c(e){for(var t,n=e.length,r=n%3,o="",i=[],s=0,c=n-r;s<c;s+=16383)i.push(a(e,s,s+16383>c?c:s+16383));return 1===r?(t=e[n-1],o+=u[t>>2],o+=u[t<<4&63],o+="=="):