forked from PrivateCoffee/transfer.coffee
16 lines
875 KiB
JavaScript
16 lines
875 KiB
JavaScript
|
(function(f){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=f();else if("function"==typeof define&&define.amd)define([],f);else{var g;g="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,g.WebTorrent=f()}})(function(){var _MathLN=Math.LN2,_Mathlog2=Math.log,_Mathpow=Math.pow,_Mathabs=Math.abs,_Mathfloor=Math.floor,_Mathround=Math.round,_Mathsin=Math.sin,_Mathcos=Math.cos,_MathPI=Math.PI,_Mathimul=Math.imul,_Mathclz=Math.clz32,_StringfromCharCode=String.fromCharCode,_Mathmax=Math.max,_Mathceil=Math.ceil,_Mathmin=Math.min,define;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module){const{Readable}=require("streamx"),debugFactory=require("debug"),debug=debugFactory("webtorrent:file-stream");module.exports=class extends Readable{constructor(file,opts){super(opts??{}),this._torrent=file._torrent;const start=opts&&opts.start||0,end=opts&&opts.end&&opts.end<file.length?opts.end:file.length-1,pieceLength=file._torrent.pieceLength;this._startPiece=0|(start+file.offset)/pieceLength,this._endPiece=0|(end+file.offset)/pieceLength,this._piece=this._startPiece,this._offset=start+file.offset-this._startPiece*pieceLength,this._missing=end-start+1,this._reading=!1,this._notifying=!1,this._criticalLength=_Mathmin(0|1048576/pieceLength,2),this._torrent.select(this._startPiece,this._endPiece,!0,()=>{this._notify()})}_read(cb){this._reading||(this._reading=!0,this._notify(cb))}_notify(cb=()=>{}){if(!this._reading||0===this._missing)return cb();if(!this._torrent.bitfield.get(this._piece))return cb(),this._torrent.critical(this._piece,this._piece+this._criticalLength);if(this._notifying)return cb();if(this._notifying=!0,this._torrent.destroyed)return this.destroy(new Error("Torrent removed"));const p=this._piece,getOpts={};p===this._torrent.pieces.length-1&&(getOpts.length=this._torrent.lastPieceLength),this._torrent.store.get(p,getOpts,(err,buffer)=>{if(this._notifying=!1,!this.destroyed)return debug("read %s (length %s) (err %s)",p,buffer&&buffer.length,err&&err.message),err?this.destroy(err):void(this._offset&&(buffer=buffer.slice(this._offset),this._offset=0),this._missing<buffer.length&&(buffer=buffer.slice(0,this._missing)),this._missing-=buffer.length,debug("pushing buffer of length %s",buffer.length),this._reading=!1,this.push(buffer),0===this._missing&&this.push(null),cb())}),this._piece+=1}_destroy(cb,err){this._torrent.destroyed||this._torrent.deselect(this._startPiece,this._endPiece,!0),cb(err)}}},{debug:91,streamx:264}],2:[function(require,module){const EventEmitter=require("events"),{PassThrough}=require("streamx"),path=require("path"),render=require("render-media"),{BlobWriteStream}=require("fast-blob-stream"),streamToBuffer=require("stream-with-known-length-to-buffer"),queueMicrotask=require("queue-microtask"),rangeParser=require("range-parser"),mime=require("mime"),eos=require("end-of-stream"),FileStream=require("./file-stream.js");module.exports=class extends EventEmitter{constructor(torrent,file){super(),this._torrent=torrent,this._destroyed=!1,this._fileStreams=new Set,this.name=file.name,this.path=file.path,this.length=file.length,this.offset=file.offset,this.done=!1;const start=file.offset,end=start+file.length-1;this._startPiece=0|start/this._torrent.pieceLength,this._endPiece=0|end/this._torrent.pieceLength,0===this.length&&(this.done=!0,this.emit("done")),this._serviceWorker=torrent.client.serviceWorker}get downloaded(){if(this._destroyed||!this._torrent.bitfield)return 0;const{pieces,bitfield,pieceLength,lastPieceLength}=this._torrent,{_startPiece:start,_endPiece:end}=this,getPieceLength=pieceIndex=>pieceIndex=
|
||
|
* The buffer module from node.js, for the browser.
|
||
|
*
|
||
|
* @author Feross Aboukhadijeh <https://feross.org>
|
||
|
* @license MIT
|
||
|
*/"use strict";function typedArraySupport(){try{var arr=new Uint8Array(1);return arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===arr.foo()}catch(e){return!1}}function createBuffer(length){if(2147483647<length)throw new RangeError("The value \""+length+"\" is invalid for option \"size\"");var buf=new Uint8Array(length);return buf.__proto__=Buffer.prototype,buf}function Buffer(arg,encodingOrOffset,length){if("number"==typeof arg){if("string"==typeof encodingOrOffset)throw new TypeError("The \"string\" argument must be of type string. Received type number");return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}function from(value,encodingOrOffset,length){if("string"==typeof value)return fromString(value,encodingOrOffset);if(ArrayBuffer.isView(value))return fromArrayLike(value);if(null==value)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value);if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer))return fromArrayBuffer(value,encodingOrOffset,length);if("number"==typeof value)throw new TypeError("The \"value\" argument must not be of type number. Received type number");var valueOf=value.valueOf&&value.valueOf();if(null!=valueOf&&valueOf!==value)return Buffer.from(valueOf,encodingOrOffset,length);var b=fromObject(value);if(b)return b;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof value[Symbol.toPrimitive])return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof value)}function assertSize(size){if("number"!=typeof size)throw new TypeError("\"size\" argument must be of type number");else if(0>size)throw new RangeError("The value \""+size+"\" is invalid for option \"size\"")}function alloc(size,fill,encoding){return assertSize(size),0>=size?createBuffer(size):void 0===fill?createBuffer(size):"string"==typeof encoding?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}function allocUnsafe(size){return assertSize(size),createBuffer(0>size?0:0|checked(size))}function fromString(string,encoding){if(("string"!=typeof encoding||""===encoding)&&(encoding="utf8"),!Buffer.isEncoding(encoding))throw new TypeError("Unknown encoding: "+encoding);var length=0|byteLength(string,encoding),buf=createBuffer(length),actual=buf.write(string,encoding);return actual!==length&&(buf=buf.slice(0,actual)),buf}function fromArrayLike(array){for(var length=0>array.length?0:0|checked(array.length),buf=createBuffer(length),i=0;i<length;i+=1)buf[i]=255&array[i];return buf}function fromArrayBuffer(array,byteOffset,length){if(0>byteOffset||array.byteLength<byteOffset)throw new RangeError("\"offset\" is outside of buffer bounds");if(array.byteLength<byteOffset+(length||0))throw new RangeError("\"length\" is outside of buffer bounds");var buf;return buf=void 0===byteOffset&&void 0===length?new Uint8Array(array):void 0===length?new Uint8Array(array,byteOffset):new Uint8Array(array,byteOffset,length),buf.__proto__=Buffer.prototype,buf}function fromObject(obj){if(Buffer.isBuffer(obj)){var len=0|checked(obj.length),buf=createBuffer(len);return 0===buf.length?buf:(obj.copy(buf,0,0,len),buf)}return void 0===obj.length?"Buffer"===obj.type&&Array.isArray(obj.data)?fromArrayLike(obj.data):void 0:"number"!=typeof obj.length||numberIsNaN(obj.length)?createBuffer(0):fromArrayLike(obj)}function checked(length){if(length>=2147483647)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+2147483647 .toString(16)+" bytes");return 0|length}function SlowBuffer(length){return+length!=length&&(length=0),Buffer.alloc(+length)}function byteLength(string,encoding){if(Buffer.isBuffer(string))return string.length;if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer))return string.byteLength;if("string"!=typeof string)throw new TypeError("The \"string\" argument must be one of type string, Buffe
|
||
|
* Determine if an object is a Buffer
|
||
|
*
|
||
|
* @author Feross Aboukhadijeh <https://feross.org>
|
||
|
* @license MIT
|
||
|
*/module.exports=function(obj){return null!=obj&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)}},{}],150:[function(require,module,exports){module.exports=async function*(iterators){for(let iterator of iterators)"function"==typeof iterator&&(iterator=iterator()),yield*iterator}},{}],151:[function(require,module,exports){"use strict";const blacklist=["^npm-debug\\.log$","^\\..*\\.swp$","^\\.DS_Store$","^\\.AppleDouble$","^\\.LSOverride$","^Icon\\r$","^\\._.*","^\\.Spotlight-V100(?:$|\\/)","\\.Trashes","^__MACOSX$","~$","^Thumbs\\.db$","^ehthumbs\\.db$","^Desktop\\.ini$","@eaDir$"];exports.re=()=>{throw new Error("`junk.re` was renamed to `junk.regex`")},exports.regex=new RegExp(blacklist.join("|")),exports.is=filename=>exports.regex.test(filename),exports.not=filename=>!exports.is(filename),exports.default=module.exports},{}],152:[function(require,module,exports){exports.RateLimiter=require("./lib/rateLimiter"),exports.TokenBucket=require("./lib/tokenBucket")},{"./lib/rateLimiter":154,"./lib/tokenBucket":155}],153:[function(require,module,exports){(function(process){(function(){var getMilliseconds=function(){if("undefined"!=typeof process&&process.hrtime){var hrtime=process.hrtime(),seconds=hrtime[0],nanoseconds=hrtime[1];return 1e3*seconds+_Mathfloor(nanoseconds/1e6)}return new Date().getTime()};module.exports=getMilliseconds}).call(this)}).call(this,require("_process"))},{_process:193}],154:[function(require,module,exports){(function(process){(function(){var TokenBucket=require("./tokenBucket"),getMilliseconds=require("./clock"),RateLimiter=function(tokensPerInterval,interval,fireImmediately){this.tokenBucket=new TokenBucket(tokensPerInterval,tokensPerInterval,interval,null),this.tokenBucket.content=tokensPerInterval,this.curIntervalStart=getMilliseconds(),this.tokensThisInterval=0,this.fireImmediately=fireImmediately};RateLimiter.prototype={tokenBucket:null,curIntervalStart:0,tokensThisInterval:0,fireImmediately:!1,removeTokens:function(count,callback){function afterTokensRemoved(err,tokensRemaining){return err?callback(err,null):void(self.tokensThisInterval+=count,callback(null,tokensRemaining))}if(count>this.tokenBucket.bucketSize)return process.nextTick(callback.bind(null,"Requested tokens "+count+" exceeds maximum tokens per interval "+this.tokenBucket.bucketSize,null)),!1;var self=this,now=getMilliseconds();if((now<this.curIntervalStart||now-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=now,this.tokensThisInterval=0),count>this.tokenBucket.tokensPerInterval-this.tokensThisInterval){if(this.fireImmediately)process.nextTick(callback.bind(null,null,-1));else{var waitInterval=_Mathceil(this.curIntervalStart+this.tokenBucket.interval-now);setTimeout(function(){self.tokenBucket.removeTokens(count,afterTokensRemoved)},waitInterval)}return!1}return this.tokenBucket.removeTokens(count,afterTokensRemoved)},tryRemoveTokens:function(count){if(count>this.tokenBucket.bucketSize)return!1;var now=getMilliseconds();if((now<this.curIntervalStart||now-this.curIntervalStart>=this.tokenBucket.interval)&&(this.curIntervalStart=now,this.tokensThisInterval=0),count>this.tokenBucket.tokensPerInterval-this.tokensThisInterval)return!1;var removed=this.tokenBucket.tryRemoveTokens(count);return removed&&(this.tokensThisInterval+=count),removed},getTokensRemaining:function(){return this.tokenBucket.drip(),this.tokenBucket.content}},module.exports=RateLimiter}).call(this)}).call(this,require("_process"))},{"./clock":153,"./tokenBucket":155,_process:193}],155:[function(require,module,exports){(function(process){(function(){var TokenBucket=function(bucketSize,tokensPerInterval,interval,parentBucket){if(this.bucketSize=bucketSize,this.tokensPerInterval=tokensPerInterval,"string"==typeof interval)switch(interval){case"sec":case"second":this.interval=1e3;break;case"min":case"minute":this.interval=60000;break;case"hr":case"hour":this.interval=3600000;break;case"day":this.interval=86400000;break;default:throw new Error("Invaid interval "+interval);}else this.interval=interval;this.parentBucket=parentBucket,this.conte
|
||
|
* range-parser
|
||
|
* Copyright(c) 2012-2014 TJ Holowaychuk
|
||
|
* Copyright(c) 2015-2016 Douglas Christopher Wilson
|
||
|
* MIT Licensed
|
||
|
*/"use strict";function rangeParser(size,str,options){if("string"!=typeof str)throw new TypeError("argument str must be a string");var index=str.indexOf("=");if(-1===index)return-2;var arr=str.slice(index+1).split(","),ranges=[];ranges.type=str.slice(0,index);for(var i=0;i<arr.length;i++){var range=arr[i].split("-"),start=parseInt(range[0],10),end=parseInt(range[1],10);(isNaN(start)?(start=size-end,end=size-1):isNaN(end)&&(end=size-1),end>size-1&&(end=size-1),!(isNaN(start)||isNaN(end)||start>end||0>start))&&ranges.push({start:start,end:end})}return 1>ranges.length?-1:options&&options.combine?combineRanges(ranges):ranges}function combineRanges(ranges){for(var ordered=ranges.map(mapWithIndex).sort(sortByRangeStart),j=0,i=1;i<ordered.length;i++){var range=ordered[i],current=ordered[j];range.start>current.end+1?ordered[++j]=range:range.end>current.end&&(current.end=range.end,current.index=_Mathmin(current.index,range.index))}ordered.length=j+1;var combined=ordered.sort(sortByRangeIndex).map(mapWithoutIndex);return combined.type=ranges.type,combined}function mapWithIndex(range,index){return{start:range.start,end:range.end,index:index}}function mapWithoutIndex(range){return{start:range.start,end:range.end}}function sortByRangeIndex(a,b){return a.index-b.index}function sortByRangeStart(a,b){return a.start-b.start}module.exports=rangeParser},{}],212:[function(require,module,exports){const{Writable,PassThrough}=require("readable-stream");class RangeSliceStream extends Writable{constructor(offset,opts={}){super(opts),this.destroyed=!1,this._queue=[],this._position=offset||0,this._cb=null,this._buffer=null,this._out=null}_write(chunk,encoding,cb){let drained=!0;for(;!0;){if(this.destroyed)return;if(0===this._queue.length)return this._buffer=chunk,void(this._cb=cb);this._buffer=null;var currRange=this._queue[0];const writeStart=_Mathmax(currRange.start-this._position,0),writeEnd=currRange.end-this._position;if(writeStart>=chunk.length)return this._position+=chunk.length,cb(null);let toWrite;if(writeEnd>chunk.length){this._position+=chunk.length,toWrite=0===writeStart?chunk:chunk.slice(writeStart),drained=currRange.stream.write(toWrite)&&drained;break}this._position+=writeEnd,toWrite=0===writeStart&&writeEnd===chunk.length?chunk:chunk.slice(writeStart,writeEnd),drained=currRange.stream.write(toWrite)&&drained,currRange.last&&currRange.stream.end(),chunk=chunk.slice(writeEnd),this._queue.shift()}drained?cb(null):currRange.stream.once("drain",cb.bind(null,null))}slice(ranges){if(this.destroyed)return null;Array.isArray(ranges)||(ranges=[ranges]);const str=new PassThrough;return ranges.forEach((range,i)=>{this._queue.push({start:range.start,end:range.end,stream:str,last:i===ranges.length-1})}),this._buffer&&this._write(this._buffer,null,this._cb),str}destroy(err){this.destroyed||(this.destroyed=!0,err&&this.emit("error",err))}}module.exports=RangeSliceStream},{"readable-stream":228}],213:[function(require,module,exports){"use strict";function isInteger(n){return parseInt(n,10)===n}function createRC4(N){function identityPermutation(){for(var s=Array(N),i=0;i<N;i++)s[i]=i;return s}function seed(key){if(void 0===key){key=Array(N);for(var k=0;k<N;k++)key[k]=_Mathfloor(Math.random()*N)}else if("string"==typeof key)key=""+key,key=key.split("").map(function(c){return c.charCodeAt(0)%N});else if(!Array.isArray(key))throw new TypeError("invalid seed key specified");else if(!key.every(function(v){return"number"==typeof v&&v===(0|v)}))throw new TypeError("invalid seed key specified: not array of integers");for(var keylen=key.length,s=identityPermutation(),j=0,i=0;i<N;i++){j=(j+s[i]+key[i%keylen])%N;var tmp=s[i];s[i]=s[j],s[j]=tmp}return s}function RC4(key){this.s=seed(key),this.i=0,this.j=0}return RC4.prototype.randomNative=function(){this.i=(this.i+1)%N,this.j=(this.j+this.s[this.i])%N;var tmp=this.s[this.i];this.s[this.i]=this.s[this.j],this.s[this.j]=tmp;var k=this.s[(this.s[this.i]+this.s[this.j])%N];return k},RC4.prototype.randomUInt32=function(){var a=this.randomByte(),b=this.randomByte(),c=this.randomByte(),d=this.randomByte();return 256
|