diff --git a/cachep2p.min.js b/cachep2p.min.js index 734c334..9a740dc 100644 --- a/cachep2p.min.js +++ b/cachep2p.min.js @@ -8,4 +8,4 @@ l=d,d=c,c=a<<30|a>>>2,a=i,i=m,o[r>>2]=g;for(r=e+240|0;(r|0)<(e+320|0);r=r+4|0)g= u(r,s),r.prototype.updatePort=function(e){var t=this;e!==t._port&&(t._port=e,t.dht&&t._dhtAnnounce(),t.tracker&&(t.tracker.stop(),t.tracker.destroy(function(){t.tracker=t._createTracker()})))},r.prototype.complete=function(e){this.tracker&&this.tracker.complete(e)},r.prototype.destroy=function(e){var t=this;if(!t.destroyed){t.destroyed=!0,clearTimeout(t._dhtTimeout);var n=[];t.tracker&&(t.tracker.stop(),t.tracker.removeListener("warning",t._onWarning),t.tracker.removeListener("error",t._onError),t.tracker.removeListener("peer",t._onTrackerPeer),t.tracker.removeListener("update",t._onTrackerAnnounce),n.push(function(e){t.tracker.destroy(e)})),t.dht&&t.dht.removeListener("peer",t._onDHTPeer),t._internalDHT&&(t.dht.removeListener("warning",t._onWarning),t.dht.removeListener("error",t._onError),n.push(function(e){t.dht.destroy(e)})),c(n,e),t.dht=null,t.tracker=null,t._announce=null}},r.prototype._createTracker=function(){var e=a(this._trackerOpts,{infoHash:this.infoHash,announce:this._announce,peerId:this.peerId,port:this._port}),t=new f(e);return t.on("warning",this._onWarning),t.on("error",this._onError),t.on("peer",this._onTrackerPeer),t.on("update",this._onTrackerAnnounce),t.setInterval(this._intervalMs),t.start(),t},r.prototype._dhtAnnounce=function(){function e(){return t._intervalMs+Math.floor(Math.random()*t._intervalMs/5)}var t=this;t._dhtAnnouncing||(o("dht announce"),t._dhtAnnouncing=!0,clearTimeout(t._dhtTimeout),t.dht.announce(t.infoHash,t._port,function(n){t._dhtAnnouncing=!1,o("dht announce complete"),n&&t.emit("warning",n),t.emit("dhtAnnounce"),t.destroyed||(t._dhtTimeout=setTimeout(function(){t._dhtAnnounce()},e()),t._dhtTimeout.unref&&t._dhtTimeout.unref())}))}}).call(this,e("_process"))},{_process:61,"bittorrent-dht/client":15,"bittorrent-tracker/client":9,debug:24,events:29,inherits:36,"run-parallel":80,xtend:121}],101:[function(e,t){(function(e){function n(e){return this instanceof n?(this.length=e,this.missing=e,this.sources=null,this._chunks=Math.ceil(e/r),this._remainder=e%r||r,this._buffered=0,this._buffer=null,this._cancellations=null,this._reservations=0,void(this._flushed=!1)):new n(e)}t.exports=n;var r=16384;n.BLOCK_LENGTH=r,n.prototype.chunkLength=function(e){return e===this._chunks-1?this._remainder:r},n.prototype.chunkLengthRemaining=function(e){return this.length-e*r},n.prototype.chunkOffset=function(e){return e*r},n.prototype.reserve=function(){return this.init()?this._cancellations.length?this._cancellations.pop():this._reservationss;s++)if(!this._buffer[e+s]){var a=s*r,u=t.slice(a,a+r);this._buffered++,this._buffer[e+s]=u,this.missing-=u.length,-1===this.sources.indexOf(n)&&this.sources.push(n)}return this._buffered===this._chunks},n.prototype.flush=function(){if(!this._buffer||this._chunks!==this._buffered)return null;var t=e.concat(this._buffer,this.length);return this._buffer=null,this._cancellations=null,this.sources=null,this._flushed=!0,t},n.prototype.init=function(){return this._flushed?!1:this._buffer?!0:(this._buffer=new Array(this._chunks),this._cancellations=[],this.sources=[],!0)}}).call(this,e("buffer").Buffer)},{buffer:18}],102:[function(e,t){(function(n){var r=e("is-typedarray").strict;t.exports=function(e){if(r(e)){var t=new n(e.buffer);return e.byteLength!==e.buffer.byteLength&&(t=t.slice(e.byteOffset,e.byteOffset+e.byteLength)),t}return new n(e)}}).call(this,e("buffer").Buffer)},{buffer:18,"is-typedarray":40}],103:[function(e,t,n){(function(e){var t=4294967295;n.encodingLength=function(){return 8},n.encode=function(n,r,o){r||(r=new e(8)),o||(o=0);var i=Math.floor(n/t),s=n-i*t;return r.writeUInt32BE(i,o),r.writeUInt32BE(s,o+4),r},n.decode=function(n,r){r||(r=0),n||(n=new e(4)),r||(r=0);var o=n.readUInt32BE(r),i=n.readUInt32BE(r+4);return o*t+i},n.encode.bytes=8,n.decode.bytes=8}).call(this,e("buffer").Buffer)},{buffer:18}],104:[function(e,t){"use strict";function n(e,t){for(var n=1,r=e.length,o=e[0],i=e[0],s=1;r>s;++s)if(i=o,o=e[s],t(o,i)){if(s===n){n++;continue}e[n++]=o}return e.length=n,e}function r(e){for(var t=1,n=e.length,r=e[0],o=e[0],i=1;n>i;++i,o=r)if(o=r,r=e[i],r!==o){if(i===t){t++;continue}e[t++]=r}return e.length=t,e}function o(e,t,o){return 0===e.length?e:t?(o||e.sort(t),n(e,t)):(o||e.sort(),r(e))}t.exports=o},{}],105:[function(e,t){function n(e,t){if(!(t>=e.length||0>t)){var n=e.pop();if(t",'"',"`"," ","\r","\n"," "],p=["{","}","|","\\","^","`"].concat(l),m=["'"].concat(p),g=["%","/","?",";","#"].concat(m),y=["/","?","#"],_=255,v=/^[+a-z0-9A-Z_-]{0,63}$/,b=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,w={javascript:!0,"javascript:":!0},E={javascript:!0,"javascript:":!0},k={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},x=e("querystring");r.prototype.parse=function(e,t,n){if(!c.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var r=e.indexOf("?"),o=-1!==r&&rA)&&(B=A)}var T,C;C=-1===B?a.lastIndexOf("@"):a.lastIndexOf("@",B),-1!==C&&(T=a.slice(0,C),a=a.slice(C+1),this.auth=decodeURIComponent(T)),B=-1;for(var I=0;IA)&&(B=A)}-1===B&&(B=a.length),this.host=a.slice(0,B),a=a.slice(B),this.parseHost(),this.hostname=this.hostname||"";var L="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!L)for(var R=this.hostname.split(/\./),I=0,U=R.length;U>I;I++){var P=R[I];if(P&&!P.match(v)){for(var O="",M=0,j=P.length;j>M;M++)O+=P.charCodeAt(M)>127?"x":P[M];if(!O.match(v)){var H=R.slice(0,I),D=R.slice(I+1),q=P.match(b);q&&(H.push(q[1]),D.unshift(q[2])),D.length&&(a="/"+D.join(".")+a),this.hostname=H.join(".");break}}}this.hostname=this.hostname.length>_?"":this.hostname.toLowerCase(),L||(this.hostname=u.toASCII(this.hostname));var N=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+N,this.href+=this.host,L&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==a[0]&&(a="/"+a))}if(!w[p])for(var I=0,U=m.length;U>I;I++){var W=m[I];if(-1!==a.indexOf(W)){var F=encodeURIComponent(W);F===W&&(F=escape(W)),a=a.split(W).join(F)}}var Y=a.indexOf("#");-1!==Y&&(this.hash=a.substr(Y),a=a.slice(0,Y));var V=a.indexOf("?");if(-1!==V?(this.search=a.substr(V),this.query=a.substr(V+1),t&&(this.query=x.parse(this.query)),a=a.slice(0,V)):t&&(this.search="",this.query={}),a&&(this.pathname=a),k[p]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){var N=this.pathname||"",G=this.search||"";this.path=N+G}return this.href=this.format(),this},r.prototype.format=function(){var e=this.auth||"";e&&(e=encodeURIComponent(e),e=e.replace(/%3A/i,":"),e+="@");var t=this.protocol||"",n=this.pathname||"",r=this.hash||"",o=!1,i="";this.host?o=e+this.host:this.hostname&&(o=e+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(o+=":"+this.port)),this.query&&c.isObject(this.query)&&Object.keys(this.query).length&&(i=x.stringify(this.query));var s=this.search||i&&"?"+i||"";return t&&":"!==t.substr(-1)&&(t+=":"),this.slashes||(!t||k[t])&&o!==!1?(o="//"+(o||""),n&&"/"!==n.charAt(0)&&(n="/"+n)):o||(o=""),r&&"#"!==r.charAt(0)&&(r="#"+r),s&&"?"!==s.charAt(0)&&(s="?"+s),n=n.replace(/[?#]/g,function(e){return encodeURIComponent(e)}),s=s.replace("#","%23"),t+o+n+s+r},r.prototype.resolve=function(e){return this.resolveObject(o(e,!1,!0)).format()},r.prototype.resolveObject=function(e){if(c.isString(e)){var t=new r;t.parse(e,!1,!0),e=t}for(var n=new r,o=Object.keys(this),i=0;i0?n.host.split("@"):!1;S&&(n.auth=S.shift(),n.host=n.hostname=S.shift())}return n.search=e.search,n.query=e.query,c.isNull(n.pathname)&&c.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.href=n.format(),n}if(!w.length)return n.pathname=null,n.path=n.search?"/"+n.search:null,n.href=n.format(),n;for(var B=w.slice(-1)[0],I=(n.host||e.host||w.length>1)&&("."===B||".."===B)||""===B,A=0,T=w.length;T>=0;T--)B=w[T],"."===B?w.splice(T,1):".."===B?(w.splice(T,1),A++):A&&(w.splice(T,1),A--);if(!v&&!b)for(;A--;A)w.unshift("..");!v||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),I&&"/"!==w.join("/").substr(-1)&&w.push("");var C=""===w[0]||w[0]&&"/"===w[0].charAt(0);if(x){n.hostname=n.host=C?"":w.length?w.shift():"";var S=n.host&&n.host.indexOf("@")>0?n.host.split("@"):!1;S&&(n.auth=S.shift(),n.host=n.hostname=S.shift())}return v=v||n.host&&w.length,v&&!C&&w.unshift(""),w.length?n.pathname=w.join("/"):(n.pathname=null,n.path=null),c.isNull(n.pathname)&&c.isNull(n.search)||(n.path=(n.pathname?n.pathname:"")+(n.search?n.search:"")),n.auth=e.auth||n.auth,n.slashes=n.slashes||e.slashes,n.href=n.format(),n},r.prototype.parseHost=function(){var e=this.host,t=d.exec(e);t&&(t=t[0],":"!==t&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":107,punycode:63,querystring:66}],107:[function(e,t){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],108:[function(e,t){var n=e("bencode"),r=e("bitfield"),o=e("safe-buffer").Buffer,i=e("debug")("ut_metadata"),s=e("events").EventEmitter,a=e("inherits"),u=(e("simple-sha1"),1e7),c=1e3,f=16384;t.exports=function(e){function t(t){s.call(this),this._wire=t,this._metadataComplete=!1,this._metadataSize=null,this._remainingRejects=null,this._fetching=!1,this._bitfield=new r(0,{grow:c}),o.isBuffer(e)&&this.setMetadata(e)}return a(t,s),t.prototype.name="ut_metadata",t.prototype.onHandshake=function(e){this._infoHash=e},t.prototype.onExtendedHandshake=function(e){return e.m&&e.m.ut_metadata?e.metadata_size?"number"!=typeof e.metadata_size||uthis._metadataSize&&(n=this._metadataSize);var r=this.metadata.slice(t,n);this._data(e,r,this._metadataSize)},t.prototype._onData=function(e,t){t.length>f||(t.copy(this.metadata,e*f),this._bitfield.set(e),this._checkDone())},t.prototype._onReject=function(e){this._remainingRejects>0&&this._fetching?(this._request(e),this._remainingRejects-=1):this.emit("warning",new Error('Peer sent "reject" too much'))},t.prototype._requestPieces=function(){this.metadata=o.alloc(this._metadataSize);for(var e=0;e0?this._requestPieces():this.emit("warning",new Error("Peer sent invalid metadata"))},t}},{bencode:5,bitfield:7,debug:24,events:29,inherits:36,"safe-buffer":82,"simple-sha1":86}],109:[function(e,t){(function(e){function n(e,t){function n(){if(!o){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),o=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var o=!1;return n}function r(t){try{if(!e.localStorage)return!1}catch(n){return!1}var r=e.localStorage[t];return null==r?!1:"true"===String(r).toLowerCase()}t.exports=n}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],110:[function(e,t){(function(n){function r(e){var t=this;a.call(t),t._tracks=[],t._fragmentSequence=1,t._file=e,t._decoder=null,t._findMoov(0)}function o(e,t){var n=this;n._entries=e,n._countName=t||"count",n._index=0,n._offset=0,n.value=n._entries[0]}function i(){return{version:0,flags:0,entries:[]}}var s=e("binary-search"),a=e("events").EventEmitter,u=e("inherits"),c=e("mp4-stream"),f=e("mp4-box-encoding"),d=e("range-slice-stream");t.exports=r,u(r,a),r.prototype._findMoov=function(e){var t=this;t._decoder&&t._decoder.destroy(),t._decoder=c.decode();var n=t._file.createReadStream({start:e});n.pipe(t._decoder),t._decoder.once("box",function(r){"moov"===r.type?t._decoder.decode(function(e){n.destroy();try{t._processMoov(e)}catch(r){r.message="Cannot parse mp4 file: "+r.message,t.emit("error",r)}}):(n.destroy(),t._findMoov(e+r.length))})},o.prototype.inc=function(){var e=this;e._offset++,e._offset>=e._entries[e._index][e._countName]&&(e._index++,e._offset=0),e.value=e._entries[e._index]},r.prototype._processMoov=function(e){var t=this,r=e.traks;t._tracks=[],t._hasVideo=!1,t._hasAudio=!1;for(var s=0;s=d.stsz.entries.length)break;if(g++,_+=S,g>=x.samplesPerChunk){g=0,_=0,y++;var T=d.stsc.entries[v+1];T&&y+1>=T.firstChunk&&v++}b+=B,w.inc(),E&&E.inc(),A&&k++}c.mdia.mdhd.duration=0,c.tkhd.duration=0;var C=x.sampleDescriptionId,L={type:"moov",mvhd:e.mvhd,traks:[{tkhd:c.tkhd,mdia:{mdhd:c.mdia.mdhd,hdlr:c.mdia.hdlr,elng:c.mdia.elng,minf:{vmhd:c.mdia.minf.vmhd,smhd:c.mdia.minf.smhd,dinf:c.mdia.minf.dinf,stbl:{stsd:d.stsd,stts:i(),ctts:i(),stsc:i(),stsz:i(),stco:i(),stss:i()}}}}],mvex:{mehd:{fragmentDuration:e.mvhd.duration},trexs:[{trackId:c.tkhd.trackId,defaultSampleDescriptionIndex:C,defaultSampleDuration:0,defaultSampleSize:0,defaultSampleFlags:0}]}};t._tracks.push({trackId:c.tkhd.trackId,timeScale:c.mdia.mdhd.timeScale,samples:p,currSample:null,currTime:null,moov:L,mime:u})}if(0===t._tracks.length)return void t.emit("error",new Error("no playable tracks"));e.mvhd.duration=0,t._ftyp={type:"ftyp",brand:"iso5",brandVersion:0,compatibleBrands:["iso5"]};var R=f.encode(t._ftyp),U=t._tracks.map(function(e){var t=f.encode(e.moov);return{mime:e.mime,init:n.concat([R,t])}});t.emit("ready",U)},r.prototype.seek=function(e){var t=this;if(!t._tracks)throw new Error("Not ready yet; wait for 'ready' event");t._fileStream&&(t._fileStream.destroy(),t._fileStream=null);var n=-1;if(t._tracks.map(function(r,o){function i(e){s.destroyed||s.box(e.moof,function(n){if(n)return t.emit("error",n);if(!s.destroyed){var a=r.inStream.slice(e.ranges);a.pipe(s.mediaData(e.length,function(e){if(e)return t.emit("error",e);if(!s.destroyed){var n=t._generateFragment(o);return n?void i(n):s.finalize()}}))}})}r.outStream&&r.outStream.destroy(),r.inStream&&(r.inStream.destroy(),r.inStream=null);var s=r.outStream=c.encode(),a=t._generateFragment(o,e);return a?((-1===n||a.ranges[0].start=0){var r=t._fileStream=t._file.createReadStream({start:n});t._tracks.forEach(function(e){e.inStream=new d(n),r.pipe(e.inStream)})}return t._tracks.map(function(e){return e.outStream})},r.prototype._findSampleBefore=function(e,t){var n=this,r=n._tracks[e],o=Math.floor(r.timeScale*t),i=s(r.samples,o,function(e,t){var n=e.dts+e.presentationOffset;return n-t});for(-1===i?i=0:0>i&&(i=-i-2);!r.samples[i].sync;)i--;return i};var h=1;r.prototype._generateFragment=function(e,t){var n,r=this,o=r._tracks[e];if(n=void 0!==t?r._findSampleBefore(e,t):o.currSample,n>=o.samples.length)return null;for(var i=o.samples[n].dts,s=0,a=[],u=n;u=o.timeScale*h)break;s+=c.size;var f=a.length-1;0>f||a[f].end!==c.offset?a.push({start:c.offset,end:c.offset+c.size}):a[f].end+=c.size}return o.currSample=u,{moof:r._generateMoof(e,n,u),ranges:a,length:s}},r.prototype._generateMoof=function(e,t,n){for(var r=this,o=r._tracks[e],i=[],s=t;n>s;s++){var a=o.samples[s];i.push({sampleDuration:a.duration,sampleSize:a.size,sampleFlags:a.sync?33554432:16842752,sampleCompositionTimeOffset:a.presentationOffset})}var u={type:"moof",mfhd:{sequenceNumber:r._fragmentSequence++},trafs:[{tfhd:{flags:131072,trackId:o.trackId},tfdt:{baseMediaDecodeTime:o.samples[t].dts},trun:{flags:3841,dataOffset:8,entries:i}}]};return u.trafs[0].trun.dataOffset+=f.encodingLength(u),u}}).call(this,e("buffer").Buffer)},{"binary-search":6,buffer:18,events:29,inherits:36,"mp4-box-encoding":48,"mp4-stream":51,"range-slice-stream":69}],111:[function(e,t){function n(e,t,o){var i=this;return this instanceof n?(o=o||{},i.detailedError=null,i._elem=t,i._elemWrapper=new r(t),i._waitingFired=!1,i._trackMeta=null,i._file=e,i._tracks=null,"none"!==i._elem.preload&&i._createMuxer(),i._onError=function(){i.detailedError=i._elemWrapper.detailedError,i.destroy()},i._onWaiting=function(){i._waitingFired=!0,i._muxer?i._tracks&&i._pump():i._createMuxer()},i._elem.addEventListener("waiting",i._onWaiting),void i._elem.addEventListener("error",i._onError)):new n(e,t,o)}var r=e("mediasource"),o=e("pump"),i=e("./mp4-remuxer");t.exports=n,n.prototype._createMuxer=function(){var e=this;e._muxer=new i(e._file),e._muxer.on("ready",function(t){e._tracks=t.map(function(t){var n=e._elemWrapper.createWriteStream(t.mime);n.on("error",function(t){e._elemWrapper.error(t)});var r={muxed:null,mediaSource:n,initFlushed:!1,onInitFlushed:null};return n.write(t.init,function(e){r.initFlushed=!0,r.onInitFlushed&&r.onInitFlushed(e)}),r}),(e._waitingFired||"auto"===e._elem.preload)&&e._pump()}),e._muxer.on("error",function(t){e._elemWrapper.error(t)})},n.prototype._pump=function(){var e=this,t=e._muxer.seek(e._elem.currentTime,!e._tracks);e._tracks.forEach(function(n,r){var i=function(){n.muxed&&(n.muxed.destroy(),n.mediaSource=e._elemWrapper.createWriteStream(n.mediaSource),n.mediaSource.on("error",function(t){e._elemWrapper.error(t)})),n.muxed=t[r],o(n.muxed,n.mediaSource)};n.initFlushed?i():n.onInitFlushed=function(t){return t?void e._elemWrapper.error(t):void i()}})},n.prototype.destroy=function(){var e=this;e.destroyed||(e.destroyed=!0,e._elem.removeEventListener("waiting",e._onWaiting),e._elem.removeEventListener("error",e._onError),e._tracks&&e._tracks.forEach(function(e){e.muxed.destroy()}),e._elem.src="")}},{"./mp4-remuxer":110,mediasource:44,pump:62}],112:[function(e,t){(function(n,r){function o(e){function t(){i.destroyed||(i.ready=!0,i.emit("ready"))}var i=this;return i instanceof o?(h.call(i),e||(e={}),i.peerId="string"==typeof e.peerId?e.peerId:a.isBuffer(e.peerId)?e.peerId.toString("hex"):a.from(I+b(9).toString("base64")).toString("hex"),i.peerIdBuffer=a.from(i.peerId,"hex"),i.nodeId="string"==typeof e.nodeId?e.nodeId:a.isBuffer(e.nodeId)?e.nodeId.toString("hex"):b(20).toString("hex"),i.nodeIdBuffer=a.from(i.nodeId,"hex"),i.destroyed=!1,i.listening=!1,i.torrentPort=e.torrentPort||0,i.dhtPort=e.dhtPort||0,i.tracker=void 0!==e.tracker?e.tracker:{},i.torrents=[],i.maxConns=Number(e.maxConns)||55,f("new webtorrent (peerId %s, nodeId %s, port %s)",i.peerId,i.nodeId,i.torrentPort),i.tracker&&("object"!=typeof i.tracker&&(i.tracker={}),e.rtcConfig&&(console.warn("WebTorrent: opts.rtcConfig is deprecated. Use opts.tracker.rtcConfig instead"),i.tracker.rtcConfig=e.rtcConfig),e.wrtc&&(console.warn("WebTorrent: opts.wrtc is deprecated. Use opts.tracker.wrtc instead"),i.tracker.wrtc=e.wrtc),r.WRTC&&!i.tracker.wrtc&&(i.tracker.wrtc=r.WRTC)),"function"==typeof k?i._tcpPool=new k(i):n.nextTick(function(){i._onListening()}),i._downloadSpeed=w(),i._uploadSpeed=w(),e.dht!==!1&&"function"==typeof d?(i.dht=new d(l({nodeId:i.nodeId},e.dht)),i.dht.once("error",function(e){i._destroy(e)}),i.dht.once("listening",function(){var e=i.dht.address();e&&(i.dhtPort=e.port)}),i.dht.setMaxListeners(0),i.dht.listen(i.dhtPort)):i.dht=!1,i.enableWebSeeds=e.webSeeds!==!1,void("function"==typeof m&&null!=e.blocklist?m(e.blocklist,{headers:{"user-agent":"WebTorrent/"+S+" (https://webtorrent.io)"}},function(e,n){return e?i.error("Failed to load blocklist: "+e.message):(i.blocked=n,void t())}):n.nextTick(t))):new o(e)}function i(e){return"object"==typeof e&&null!=e&&"function"==typeof e.pipe}function s(e){return"undefined"!=typeof FileList&&e instanceof FileList}t.exports=o;var a=e("safe-buffer").Buffer,u=e("simple-concat"),c=e("create-torrent"),f=e("debug")("webtorrent"),d=e("bittorrent-dht/client"),h=e("events").EventEmitter,l=e("xtend"),p=e("inherits"),m=e("load-ip-set"),g=e("run-parallel"),y=e("parse-torrent"),_=e("path"),v=e("simple-peer"),b=e("randombytes"),w=e("speedometer"),E=e("zero-fill"),k=e("./lib/tcp-pool"),x=e("./lib/torrent"),S=e("./package.json").version,B=S.match(/([0-9]+)/g).slice(0,2).map(function(e){return E(2,e)}).join(""),I="-WW"+B+"-";p(o,h),o.WEBRTC_SUPPORT=v.WEBRTC_SUPPORT,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(){var e=this.torrents.filter(function(e){return 1!==e.progress}),t=e.reduce(function(e,t){return e+t.downloaded},0),n=e.reduce(function(e,t){return e+(t.length||0)},0)||1;return t/n}}),Object.defineProperty(o.prototype,"ratio",{get:function(){var e=this.torrents.reduce(function(e,t){return e+t.uploaded},0),t=this.torrents.reduce(function(e,t){return e+t.received},0)||1;return e/t}}),o.prototype.get=function(e){var t,n,r=this,o=r.torrents.length;if(e instanceof x){for(t=0;o>t;t++)if(n=r.torrents[t],n===e)return n}else{var i;try{i=y(e)}catch(s){}if(!i)return null;if(!i.infoHash)throw new Error("Invalid torrent identifier");for(t=0;o>t;t++)if(n=r.torrents[t],n.infoHash===i.infoHash)return n}return null},o.prototype.download=function(e,t,n){return console.warn("WebTorrent: client.download() is deprecated. Use client.add() instead"),this.add(e,t,n)},o.prototype.add=function(e,t,n){function r(){if(!s.destroyed)for(var e=0,t=s.torrents.length;t>e;e++){var n=s.torrents[e];if(n.infoHash===a.infoHash&&n!==a)return void a._destroy(new Error("Cannot add duplicate torrent "+a.infoHash))}}function o(){s.destroyed||("function"==typeof n&&n(a),s.emit("torrent",a))}function i(){a.removeListener("_infoHash",r),a.removeListener("ready",o),a.removeListener("close",i)}var s=this;if(s.destroyed)throw new Error("client is destroyed");if("function"==typeof t)return s.add(e,null,t);f("add"),t=t?l(t):{};var a=new x(e,s,t);return s.torrents.push(a),a.once("_infoHash",r),a.once("ready",o),a.once("close",i),a},o.prototype.seed=function(e,t,n){function r(e){var t=[function(t){e.load(d,t)}];a.dht&&t.push(function(t){e.once("dhtAnnounce",t)}),g(t,function(t){return a.destroyed?void 0:t?e._destroy(t):void o(e)})}function o(e){f("on seed"),"function"==typeof n&&n(e),e.emit("seed"),a.emit("seed",e)}var a=this;if(a.destroyed)throw new Error("client is destroyed");if("function"==typeof t)return a.seed(e,null,t);f("seed"),t=t?l(t):{},"string"==typeof e&&(t.path=_.dirname(e)),t.createdBy||(t.createdBy="WebTorrent/"+B);var d,h=a.add(null,t,r);return s(e)&&(e=Array.prototype.slice.call(e)),Array.isArray(e)||(e=[e]),g(e.map(function(e){return function(t){i(e)?u(e,t):t(null,e)}}),function(e,n){return a.destroyed?void 0:e?h._destroy(e):void c.parseInput(n,t,function(e,r){if(!a.destroyed){if(e)return h._destroy(e);d=r.map(function(e){return e.getStream}),c(n,t,function(e,n){if(!a.destroyed){if(e)return h._destroy(e);var r=a.get(n);r?h._destroy(new Error("Cannot add duplicate torrent "+r.infoHash)):h._onTorrentId(n,t.forced_id)}})}})}),h},o.prototype.remove=function(e,t){f("remove");var n=this.get(e);if(!n)throw new Error("No torrent with id "+e);this._remove(e,t)},o.prototype._remove=function(e,t){var n=this.get(e);n&&(this.torrents.splice(this.torrents.indexOf(n),1),n.destroy(t))},o.prototype.address=function(){return this.listening?this._tcpPool?this._tcpPool.server.address():{address:"0.0.0.0",family:"IPv4",port:0}:null},o.prototype.destroy=function(e){if(this.destroyed)throw new Error("client already destroyed");this._destroy(null,e)},o.prototype._destroy=function(e,t){var n=this;f("client destroy"),n.destroyed=!0;var r=n.torrents.map(function(e){return function(t){e.destroy(t)}});n._tcpPool&&r.push(function(e){n._tcpPool.destroy(e)}),n.dht&&r.push(function(e){n.dht.destroy(e)}),g(r,t),e&&n.emit("error",e),n.torrents=[],n._tcpPool=null,n.dht=null},o.prototype._onListening=function(){if(this.listening=!0,this._tcpPool){var e=this._tcpPool.server.address();e&&(this.torrentPort=e.port)}this.emit("listening")}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/tcp-pool":15,"./lib/torrent":117,"./package.json":119,_process:61,"bittorrent-dht/client":15,"create-torrent":23,debug:24,events:29,inherits:36,"load-ip-set":15,"parse-torrent":57,path:58,randombytes:68,"run-parallel":80,"safe-buffer":82,"simple-concat":83,"simple-peer":85,speedometer:88,xtend:121,"zero-fill":123}],113:[function(e,t){function n(e,t){i.Readable.call(this,t),this.destroyed=!1,this._torrent=e._torrent;var n=t&&t.start||0,r=t&&t.end&&t.endi&&(t=[o],n=i)}return t.length>0?t[Math.random()*t.length|0]:-1},n.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},n.prototype._initWire=function(e){var t=this;e._onClose=function(){t._cleanupWireEvents(e);for(var n=0;ne;++e)for(var n=this._torrent.wires[e],r=0;rt;++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,t){var r=this;if(!r.destroyed){var o;try{o=A(e)}catch(i){}o?(r.infoHash=o.infoHash,n.nextTick(function(){r.destroyed||r._onParsedTorrent(o,t)})):A.remote(e,function(e,n){return r.destroyed?void 0:e?r._destroy(e):void r._onParsedTorrent(n,t)})}},o.prototype._onParsedTorrent=function(e,t){var n=this;if(!n.destroyed){if(n._processParsedTorrent(e),!n.infoHash)return n._destroy(new Error("Malformed torrent data: No info hash"));n.path||(n.path=T.join(c,n.infoHash)),n._rechokeIntervalId=setInterval(function(){n._rechoke()},$),n._rechokeIntervalId.unref&&n._rechokeIntervalId.unref(),t?(n.emit("_infoHash",t),n.emit("infoHash",t),n.infoHash=t):(n.emit("_infoHash",n.infoHash),n.emit("infoHash",n.infoHash)),n.destroyed||(n.client.listening?n._onListening():n.client.once("listening",function(){n._onListening()}))}},o.prototype._processParsedTorrent=function(e){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)),O(e.announce),O(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}),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._debug("http error from xs param: %s",e),n(null);if(200!==o.statusCode)return t._debug("non-200 status code %s from xs param: %s",o.statusCode,e),n(null);var s;try{s=A(i)}catch(r){}return s?s.infoHash!==t.infoHash?(t._debug("got torrent file with incorrect info hash from xs param: %s",e),n(null)):(t._onMetadata(s),void n(null)):(t._debug("got invalid torrent file from xs param: %s",e),n(null))}if(0!==e.indexOf("http://")&&0!==e.indexOf("https://"))return t._debug("skipping non-http xs param: %s",e),n(null);var o,i={url:e,method:"GET",headers:{"user-agent":"WebTorrent/"+Q+" (https://webtorrent.io)"}};try{o=b.concat(i,r)}catch(s){return t._debug("skipping invalid url xs param: %s",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)}});B(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(r){return t._destroy(r)}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 q(t),t.store=new w(new t._store(t.pieceLength,{torrent:{infoHash:t.infoHash},files:t.files.map(function(e){return{path:T.join(t.path,e.path),length:e.length,offset:e.offset}}),length:t.length})),t.files=t.files.map(function(e){return new H(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 C(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===v?t.getFileModtimes(function(e,n){if(e)return t._destroy(e);var r=t.files.map(function(e,r){return n[r]===t._fileModtimes[r]}).every(function(e){return e});if(r){for(var o=0;oe||e>t||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||u}),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;++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(W,!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(){r.destroyed||e.destroyed||(r._numQueued>2*(r._numConns-r.numPeers)&&e.amInterested?e.destroy():(o=setTimeout(t,F),o.unref&&o.unref()))}function n(){if(e.peerPieces.length===r.pieces.length){for(;iz?e.destroy():void(r.pieces[t]||r.store.get(t,{offset:n,length:o},i))}),e.bitfield(r.bitfield),e.interested(),e.peerExtensions.dht&&r.client.dht&&r.client.dht.listening&&e.port(r.client.dht.address().port),o=setTimeout(t,F),o.unref&&o.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=t&&n>=i&&!(i in r)&&e.peerPieces.get(i)&&(!o||o(i))}}function n(){if(!e.requests.length)for(var n=a._selections.length;n--;){var r,o=a._selections[n];if("rarest"===a.strategy)for(var i=o.from+o.offset,s=o.to,u=s-i+1,c={},f=0,d=t(i,s,c);u>f&&(r=a._rarityMap.getRarestPiece(d),!(0>r));){if(a._request(e,r,!1))return;c[r]=!0,f+=1}else for(r=o.to;r>=o.from+o.offset;--r)if(e.peerPieces.get(r)&&a._request(e,r,!1))return}}function r(){var t=e.downloadSpeed()||1;if(t>Y)return function(){return!0};var n=Math.max(1,e.requests.length)*C.BLOCK_LENGTH/t,r=10,o=0;return function(e){if(!r||a.bitfield.get(e))return!0;for(var i=a.pieces[e].missing;ou||t>=u||!s.peerPieces.get(e)||(i-=u*n)>0))return r--,!1}return!0}}function o(e){for(var t=e,n=e;n=c)return!0;for(var i=r(),s=0;sm&&(u=a._rarityMap.getRarestPiece(g),!(0>u));){for(;a._request(e,u,a._critical[u]||n););if(!(e.requests.length=u)){var c=i(e,G);s(!1)||s(!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=Y||2*c>r||c>a||(i=u,a=c)}}if(!i)return!1;for(s=0;s=f)return!1;var d=a.pieces[t],h=c?d.reserveRemaining():d.reserve();if(-1===h&&r&&a._hotswap(e,t)&&(h=c?d.reserveRemaining():d.reserve()),-1===h)return!1;var l=a._reservations[t];l||(l=a._reservations[t]=[]);var p=l.indexOf(null);-1===p&&(p=l.length),l[p]=e;var m=d.chunkOffset(h),g=c?d.chunkLengthRemaining(h):d.chunkLength(h);return e.request(t,m,g,function y(n,r){if(!a.ready)return a.once("ready",function(){y(n,r)});if(l[p]===e&&(l[p]=null),d!==a.pieces[t])return o();if(n)return a._debug("error getting piece %s (offset: %s length: %s) from %s: %s",t,m,g,e.remoteAddress+":"+e.remotePort,n.message),c?d.cancelRemaining(h):d.cancel(h),void o();if(a._debug("got piece %s (offset: %s length: %s) from %s",t,m,g,e.remoteAddress+":"+e.remotePort),!d.set(h,r,e))return o();var i=d.flush();U(i,function(e){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,i),a.wires.forEach(function(e){e.have(t)}),a._checkDone()}else a.pieces[t]=new C(d.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.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=x.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>=J.length)return void e._debug("conn %s closed: will not re-add (max %s attempts)",t.addr,J.length);var n=J[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(n){return!1}var r=t[0],o=t[1];return o>0&&65535>o&&!("127.0.0.1"===r&&o===this.client.torrentPort)}}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../package.json":119,"./file":114,"./peer":115,"./rarity-map":116,"./server":15,_process:61,"addr-to-ip-port":1,bitfield:7,"chunk-store-stream/write":20,debug:24,events:29,fs:16,"fs-chunk-store":45,"immediate-chunk-store":35,inherits:36,multistream:53,net:15,os:15,"parse-torrent":57,path:58,pump:62,"random-iterate":67,"run-parallel":80,"run-parallel-limit":79,"simple-get":84,"simple-sha1":86,speedometer:88,"torrent-discovery":100,"torrent-piece":101,uniq:104,ut_metadata:108,ut_pex:15,xtend:121,"xtend/mutable":122}],118:[function(e,t){function n(e,t){c.call(this),this.url=e,this.webPeerId=u.sync(e),this._torrent=t,this._init()}t.exports=n;var r=e("bitfield"),o=e("safe-buffer").Buffer,i=e("debug")("webtorrent:webconn"),s=e("simple-get"),a=e("inherits"),u=e("simple-sha1"),c=e("bittorrent-protocol"),f=e("../package.json").version;a(n,c),n.prototype._init=function(){var e=this;e.setKeepAlive(!0),e.once("handshake",function(t){if(!e.destroyed){e.handshake(t,e.webPeerId);for(var n=e._torrent.pieces.length,o=new r(n),i=0;n>=i;i++)o.set(i,!0);e.bitfield(o)}}),e.once("interested",function(){i("interested"),e.unchoke()}),e.on("uninterested",function(){i("uninterested")}),e.on("choke",function(){i("choke")}),e.on("unchoke",function(){i("unchoke")}),e.on("bitfield",function(){i("bitfield")}),e.on("request",function(t,n,r,o){i("request pieceIndex=%d offset=%d length=%d",t,n,r),e.httpRequest(t,n,r,o)})},n.prototype.httpRequest=function(e,t,n,r){ -var a,u=this,c=e*u._torrent.pieceLength,d=c+t,h=d+n-1,l=u._torrent.files;if(l.length<=1)a=[{url:u.url,start:d,end:h}];else{var p=l.filter(function(e){return e.offset<=h&&e.offset+e.length>d});if(p.length<1)return r(new Error("Could not find file corresponnding to web seed range request"));a=p.map(function(e){var t=e.offset+e.length-1,n=u.url+("/"===u.url[u.url.length-1]?"":"/")+e.path;return{url:n,fileOffsetInRange:Math.max(e.offset-d,0),start:Math.max(d-e.offset,0),end:Math.min(t,h-e.offset)}})}var m,g=0,y=!1;a.length>1&&(m=o.alloc(n)),a.forEach(function(o){function u(e,t){return e.statusCode<200||e.statusCode>=300?(y=!0,r(new Error("Unexpected HTTP status code "+e.statusCode))):(i("Got data of length %d",t.length),void(1===a.length?r(null,t):(t.copy(m,o.fileOffsetInRange),++g===a.length&&r(null,m))))}var c=o.url,d=o.start,h=o.end;i("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",c,e,t,n,d,h);var l={url:c,method:"GET",headers:{"user-agent":"WebTorrent/"+f+" (https://webtorrent.io)",range:"bytes="+d+"-"+h}};s.concat(l,function(e,t,n){return y?void 0:e?"undefined"==typeof window||c.startsWith(window.location.origin+"/")?(y=!0,r(e)):s.head(c,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===c)return y=!0,r(e);l.url=n.url,s.concat(l,function(e,t,n){return y?void 0:e?(y=!0,r(e)):void u(t,n)})}}):void u(t,n)})})},n.prototype.destroy=function(){c.prototype.destroy.call(this),this._torrent=null}},{"../package.json":119,bitfield:7,"bittorrent-protocol":8,debug:24,inherits:36,"safe-buffer":82,"simple-get":84,"simple-sha1":86}],119:[function(e,t){t.exports={version:"0.97.2"}},{}],120:[function(e,t){function n(e,t){function r(){for(var t=new Array(arguments.length),n=0;n0?new Array(e+(/\./.test(t)?2:1)).join(r)+t:t+"")}},{}],124:[function(e,t){function n(e,t){function r(e){e.files.forEach(function(e){e.getBuffer(function(e,t){if(e)return log(e.message);var n=JSON.parse(t.toString("utf8"));f[n.url]=n,c.update_links(),window.onpopstate=function(e){document.documentElement.innerHTML=e.state.page,document.title=l+" "+e.state.title,window.scrollTo(0,0),c.emit("onpopstate",e);for(var t=document.getElementsByTagName("a"),n=0;n-1?t[n].onclick=function(e){e.preventDefault(),document.documentElement.innerHTML=f[e.target.href].page,document.title=l+" "+f[e.target.href].title,window.history.pushState({page:f[e.target.href].page,title:f[e.target.href].title},"",e.target.href),setTimeout(function(){window.scrollTo(0,0)},10)}:c.fetch(t[n])}})})}var c=this;return"function"==typeof e&&(t=e),document.security_sha1&&(c.security_sha1=document.security_sha1),l=e&&e.cached_mark?e.cached_mark:"* ",c instanceof n?(u.call(c),c.emit("message","Initializing CacheP2P..."),window.onpopstate=function(e){console.log("onpopstate called",e)},c.announceList=[["udp://tracker.openbittorrent.com:80"],["udp://tracker.internetwarriors.net:1337"],["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://exodus.desync.com:6969"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"]],e&&e.announceList&&(c.announceList=e.announceList),c.fetch=function(e){(!document.security_sha1||Object.keys(document.security_sha1).indexOf(e.href)>-1)&&-1===Object.keys(f).indexOf(e.href)&&(c.emit("message","Pre-fetching '"+e.href+"' page from other peers browsing this website..."),c.emit("alert","Please tell a friend to open this site's "+e.text+" to see it in action."),d.push(e.href),o(e.href,function(e){var t="magnet:?xt=urn:btih:"+e+"&dn=Unnamed+Torrent+1476541118022&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.internetwarriors.net%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=wss%3A%2F%2Ftracker.openwebtorrent.com";torrent=i.add(t,r),torrent.on("done",function(){c.emit("webtorrent","Cache received")}),torrent.on("download",function(e){c.emit("webtorrent","Receiving Cache ("+e+" bytes)")}),torrent.on("wire",function(e){c.emit("webtorrent","Peer ("+e.remoteAddress+") connected over "+e.type+" (Connection ID: "+e.peerId.substr(0,10)+").")})}))},c.scan_links=function(){c.emit("message","Pre-fetching uncached links in this page... ");for(var e=document.getElementsByTagName("a"),t=0;t-1&&(!document.security_sha1||Object.keys(document.security_sha1).indexOf(e[t].href)>-1)&&-1===Object.keys(f).indexOf(e[t].href)&&c.fetch(e[t]);c.update_links()},c.update_links=function(){var e=document.getElementsByTagName("a");Object.keys(f).forEach(function(t){for(var n=f[t],r=0;rd});if(p.length<1)return r(new Error("Could not find file corresponnding to web seed range request"));a=p.map(function(e){var t=e.offset+e.length-1,n=u.url+("/"===u.url[u.url.length-1]?"":"/")+e.path;return{url:n,fileOffsetInRange:Math.max(e.offset-d,0),start:Math.max(d-e.offset,0),end:Math.min(t,h-e.offset)}})}var m,g=0,y=!1;a.length>1&&(m=o.alloc(n)),a.forEach(function(o){function u(e,t){return e.statusCode<200||e.statusCode>=300?(y=!0,r(new Error("Unexpected HTTP status code "+e.statusCode))):(i("Got data of length %d",t.length),void(1===a.length?r(null,t):(t.copy(m,o.fileOffsetInRange),++g===a.length&&r(null,m))))}var c=o.url,d=o.start,h=o.end;i("Requesting url=%s pieceIndex=%d offset=%d length=%d start=%d end=%d",c,e,t,n,d,h);var l={url:c,method:"GET",headers:{"user-agent":"WebTorrent/"+f+" (https://webtorrent.io)",range:"bytes="+d+"-"+h}};s.concat(l,function(e,t,n){return y?void 0:e?"undefined"==typeof window||c.startsWith(window.location.origin+"/")?(y=!0,r(e)):s.head(c,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===c)return y=!0,r(e);l.url=n.url,s.concat(l,function(e,t,n){return y?void 0:e?(y=!0,r(e)):void u(t,n)})}}):void u(t,n)})})},n.prototype.destroy=function(){c.prototype.destroy.call(this),this._torrent=null}},{"../package.json":119,bitfield:7,"bittorrent-protocol":8,debug:24,inherits:36,"safe-buffer":82,"simple-get":84,"simple-sha1":86}],119:[function(e,t){t.exports={version:"0.97.2"}},{}],120:[function(e,t){function n(e,t){function r(){for(var t=new Array(arguments.length),n=0;n0?new Array(e+(/\./.test(t)?2:1)).join(r)+t:t+"")}},{}],124:[function(e,t){function n(e,t){function r(e){e.files.forEach(function(e){e.getBuffer(function(e,t){if(e)return log(e.message);var n=JSON.parse(t.toString("utf8"));o(n.page,function(e){return e!=c.security_sha1[n.url]?void c.emit("message","Cached version of "+n.url+" has wrong security hash. This is possibly malicious content! Ignoring the version obtained."):(c.emit("message","Cached version of "+n.url+" has a verified security hash! Proceeding by changing links in page."),f[n.url]=n,c.update_links(),void(window.onpopstate=function(e){document.documentElement.innerHTML=e.state.page,document.title=l+" "+e.state.title,window.scrollTo(0,0),c.emit("onpopstate",e);for(var t=document.getElementsByTagName("a"),n=0;n-1?t[n].onclick=function(e){e.preventDefault(),document.documentElement.innerHTML=f[e.target.href].page,document.title=l+" "+f[e.target.href].title,window.history.pushState({page:f[e.target.href].page,title:f[e.target.href].title},"",e.target.href),setTimeout(function(){window.scrollTo(0,0)},10)}:c.fetch(t[n])}))})})})}var c=this;return"function"==typeof e&&(t=e),document.security_sha1&&(c.security_sha1=document.security_sha1),l=e&&e.cached_mark?e.cached_mark:"* ",c instanceof n?(u.call(c),c.emit("message","Initializing CacheP2P..."),window.onpopstate=function(e){console.log("onpopstate called",e)},c.announceList=[["udp://tracker.openbittorrent.com:80"],["udp://tracker.internetwarriors.net:1337"],["udp://tracker.leechers-paradise.org:6969"],["udp://tracker.coppersurfer.tk:6969"],["udp://exodus.desync.com:6969"],["wss://tracker.btorrent.xyz"],["wss://tracker.openwebtorrent.com"]],e&&e.announceList&&(c.announceList=e.announceList),c.fetch=function(e){(!document.security_sha1||Object.keys(document.security_sha1).indexOf(e.href)>-1)&&-1===Object.keys(f).indexOf(e.href)&&(c.emit("message","Pre-fetching '"+e.href+"' page from other peers browsing this website..."),c.emit("alert","Please tell a friend to open this site's "+e.text+" to see it in action."),d.push(e.href),o(e.href,function(e){var t="magnet:?xt=urn:btih:"+e+"&dn=Unnamed+Torrent+1476541118022&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Ftracker.internetwarriors.net%3A1337&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Ftracker.openbittorrent.com%3A80&tr=wss%3A%2F%2Ftracker.openwebtorrent.com";torrent=i.add(t,r),torrent.on("done",function(){c.emit("webtorrent","Cache received")}),torrent.on("download",function(e){c.emit("webtorrent","Receiving Cache ("+e+" bytes)")}),torrent.on("wire",function(e){c.emit("webtorrent","Peer ("+e.remoteAddress+") connected over "+e.type+" (Connection ID: "+e.peerId.substr(0,10)+").")})}))},c.scan_links=function(){c.emit("message","Pre-fetching uncached links in this page... ");for(var e=document.getElementsByTagName("a"),t=0;t-1&&(!document.security_sha1||Object.keys(document.security_sha1).indexOf(e[t].href)>-1)&&-1===Object.keys(f).indexOf(e[t].href)&&c.fetch(e[t]);c.update_links()},c.update_links=function(){var e=document.getElementsByTagName("a");Object.keys(f).forEach(function(t){for(var n=f[t],r=0;r -1){ if(!document.security_sha1 || Object.keys(document.security_sha1).indexOf(this_page_links[i].href) > -1){ if(Object.keys(cached_link_lists).indexOf(this_page_links[i].href) === -1){ self.fetch(this_page_links[i]) } - } + } } } self.update_links() } self.update_links = function(){ - var all_links = document.getElementsByTagName('a') - + var all_links = document.getElementsByTagName('a') + Object.keys(cached_link_lists).forEach(function(each_url){ var got_page = cached_link_lists[each_url] for(var i = 0 ; i < all_links.length ; i++ ){ @@ -99,7 +99,7 @@ function CacheP2P(opts, callback){ self.emit('alert', "Security check of content received: "+sha.sync(got_page.page)+"...") self.emit('success', "Got this site's '" +all_links[i].text+"' in Cache (sha1: "+got_page.page_hash+" ✔)") self.emit('success', "The main server will not be used when '"+link_to_page.text+"' is clicked.") - + link_to_page.onclick = function(event){ event.preventDefault(); if(!history_initialized){ @@ -109,18 +109,18 @@ function CacheP2P(opts, callback){ document.title = cached_mark+' '+cached_link_lists[event.target.href].title // setTimeout(function(){ // window.scrollTo(0, 0); - + // }, 10) self.emit('cache', event) self.emit('ready') self.scan_links() - + window.history.pushState({page: got_page.page, title: got_page.title},"", got_page.url); } } } }) - } + } function onTorrent (torrent) { torrent.files.forEach(function (file) { @@ -129,42 +129,50 @@ function CacheP2P(opts, callback){ // debug(b) // debug(b.toString('utf8')) var got_page = JSON.parse(b.toString('utf8')) - // self.emit('message', "Got cached version of "+got_page.url+" from web peer, modifying link to point to cache.") - - cached_link_lists[got_page.url] = got_page - self.update_links() + // self.emit('message', "Got cached version of "+got_page.url+" from web peer, checking security hash.") - window.onpopstate = function(to) { - document.documentElement.innerHTML = to.state.page - document.title = cached_mark+" "+to.state.title - window.scrollTo(0, 0); - self.emit('onpopstate', to) - - var this_page_links = document.getElementsByTagName('a') - for(var i = 0; i < this_page_links.length ; i++){ - if(Object.keys(cached_link_lists).indexOf(this_page_links[i].href) > -1){ - this_page_links[i].onclick = function(event){ - event.preventDefault(); - document.documentElement.innerHTML = cached_link_lists[event.target.href].page - document.title = cached_mark+' '+cached_link_lists[event.target.href].title - window.history.pushState({page: cached_link_lists[event.target.href].page, title: cached_link_lists[event.target.href].title},"", event.target.href); - setTimeout(function(){ - window.scrollTo(0, 0); - }, 10) + sha(got_page.page, function (page_hash) { + if (page_hash != self.security_sha1[got_page.url]) { + self.emit('message', 'Cached version of ' + got_page.url + ' has wrong security hash. This is possibly malicious content! Ignoring the version obtained.'); + return; + } + + self.emit('message', 'Cached version of ' + got_page.url + ' has a verified security hash! Proceeding by changing links in page.'); + cached_link_lists[got_page.url] = got_page + self.update_links() + + window.onpopstate = function(to) { + document.documentElement.innerHTML = to.state.page + document.title = cached_mark+" "+to.state.title + window.scrollTo(0, 0); + self.emit('onpopstate', to) + + var this_page_links = document.getElementsByTagName('a') + for(var i = 0; i < this_page_links.length ; i++){ + if(Object.keys(cached_link_lists).indexOf(this_page_links[i].href) > -1){ + this_page_links[i].onclick = function(event){ + event.preventDefault(); + document.documentElement.innerHTML = cached_link_lists[event.target.href].page + document.title = cached_mark+' '+cached_link_lists[event.target.href].title + window.history.pushState({page: cached_link_lists[event.target.href].page, title: cached_link_lists[event.target.href].title},"", event.target.href); + setTimeout(function(){ + window.scrollTo(0, 0); + }, 10) + } + } else { + self.fetch(this_page_links[i]) } - } else { - self.fetch(this_page_links[i]) } } - } + }); }) }) } setTimeout(function(){ - + self.emit('message', "Initializing CacheP2P") - + self.scan_links() var message = {