@vidispine/vdt-api 23.1.0 → 23.2.0-pre.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +11 -8
- package/dist/index.es.js.map +1 -1
- package/dist/index.js +12 -8
- package/dist/index.js.map +1 -1
- package/package.json +8 -6
package/dist/index.js
CHANGED
|
@@ -9,6 +9,7 @@ var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProp
|
|
|
9
9
|
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
|
|
10
10
|
var buffer = require('buffer');
|
|
11
11
|
var axios = require('axios');
|
|
12
|
+
var axiosRetry = require('axios-retry');
|
|
12
13
|
var _typeof = require('@babel/runtime/helpers/typeof');
|
|
13
14
|
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
|
|
14
15
|
var _createClass = require('@babel/runtime/helpers/createClass');
|
|
@@ -21,11 +22,12 @@ var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_definePropert
|
|
|
21
22
|
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefaultLegacy(_objectWithoutProperties);
|
|
22
23
|
var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
|
|
23
24
|
var axios__default = /*#__PURE__*/_interopDefaultLegacy(axios);
|
|
25
|
+
var axiosRetry__default = /*#__PURE__*/_interopDefaultLegacy(axiosRetry);
|
|
24
26
|
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
|
|
25
27
|
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
|
|
26
28
|
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
|
|
27
29
|
|
|
28
|
-
var _excluded$Y=["username","password","token","contentType","accept"],_excluded2$S=["path","method","body","headers","queryParams","matrixParams","costEstimate"];function ownKeys$10(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable;})),keys.push.apply(keys,symbols);}return keys;}function _objectSpread$10(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys$10(Object(source),!0).forEach(function(key){_defineProperty__default["default"](target,key,source[key]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys$10(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}return target;}var defaultClient=axios__default["default"].create();var CancelToken=axios__default["default"].CancelToken;function login(_ref){var baseURL=_ref.baseURL,token=_ref.token,username=_ref.username,password=_ref.password,bearerToken=_ref.bearerToken;if(baseURL){defaultClient.defaults.baseURL=baseURL;}if(token){defaultClient.defaults.headers.Authorization="token ".concat(token);}if(bearerToken){defaultClient.defaults.headers.Authorization="Bearer ".concat(bearerToken);}if(username||password)defaultClient.defaults.auth={username:username,password:password};}function logout(){delete defaultClient.defaults.headers.Authorization;delete defaultClient.defaults.auth;}function btoa(str){var buffer$1=str instanceof buffer.Buffer?str:buffer.Buffer.from(str.toString(),'binary');return buffer$1.toString('base64');}function debounce(func,wait,immediate){var _this=this;var timeout;return function(args){var context=_this;var later=function later(){timeout=null;if(!immediate)func.apply(context,args);};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)func.apply(context,args);};}function uuidv4(){return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,function(c){return(// eslint-disable-next-line
|
|
30
|
+
var _excluded$Y=["username","password","token","contentType","accept"],_excluded2$S=["path","method","body","headers","queryParams","matrixParams","costEstimate"];function ownKeys$10(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable;})),keys.push.apply(keys,symbols);}return keys;}function _objectSpread$10(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys$10(Object(source),!0).forEach(function(key){_defineProperty__default["default"](target,key,source[key]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys$10(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}return target;}var defaultClient=axios__default["default"].create();axiosRetry__default["default"](defaultClient,{retries:24,retryDelay:function retryDelay(retryCount){return retryCount*5000;},retryCondition:function retryCondition(){return navigator.onLine===false;}});var CancelToken=axios__default["default"].CancelToken;function login(_ref){var baseURL=_ref.baseURL,token=_ref.token,username=_ref.username,password=_ref.password,bearerToken=_ref.bearerToken;if(baseURL){defaultClient.defaults.baseURL=baseURL;}if(token){defaultClient.defaults.headers.Authorization="token ".concat(token);}if(bearerToken){defaultClient.defaults.headers.Authorization="Bearer ".concat(bearerToken);}if(username||password)defaultClient.defaults.auth={username:username,password:password};}function logout(){delete defaultClient.defaults.headers.Authorization;delete defaultClient.defaults.auth;}function btoa(str){var buffer$1=str instanceof buffer.Buffer?str:buffer.Buffer.from(str.toString(),'binary');return buffer$1.toString('base64');}function debounce(func,wait,immediate){var _this=this;var timeout;return function(args){var context=_this;var later=function later(){timeout=null;if(!immediate)func.apply(context,args);};var callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow)func.apply(context,args);};}function uuidv4(){return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,function(c){return(// eslint-disable-next-line
|
|
29
31
|
(c^crypto.getRandomValues(new Uint8Array(1))[0]&15>>c/4).toString(16));});}function setDefaultHeaders(){var _ref2=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref2$username=_ref2.username,username=_ref2$username===void 0?false:_ref2$username,_ref2$password=_ref2.password,password=_ref2$password===void 0?false:_ref2$password,token=_ref2.token,_ref2$contentType=_ref2.contentType,contentType=_ref2$contentType===void 0?'application/json':_ref2$contentType,_ref2$accept=_ref2.accept,accept=_ref2$accept===void 0?'application/json':_ref2$accept,props=_objectWithoutProperties__default["default"](_ref2,_excluded$Y);var headers={'content-type':contentType,Accept:accept};if(username){var encodedAuth=btoa("".concat(username,":").concat(password));headers.Authorization="Basic ".concat(encodedAuth);}else if(token){headers.Authorization="token ".concat(token);}return _objectSpread$10(_objectSpread$10({},props),headers);}var KV_PARAMS=['jobmetadata','jobMetadata','notificationdata','notificationData','methodMetadata'];function setQueryParams(queryParams){var paramKeys=Object.keys(queryParams);if(paramKeys.length===0)return '';var reducer=function reducer(accumulator,currentKey,currentIndex){if(typeof queryParams[currentKey]==='undefined'){return accumulator;}var currentValue=queryParams[currentKey];var separator=currentIndex>0?'&':'';if(KV_PARAMS.includes(currentKey)){var kvReducer=function kvReducer(a,c,i){return "".concat(a).concat(i>0?'&':'').concat(currentKey,"=").concat(c.key,"%3D").concat(c.value);};var kvString=currentValue.reduce(kvReducer,'');return "".concat(accumulator).concat(separator).concat(kvString);}if(Array.isArray(currentValue)){return "".concat(accumulator).concat(separator).concat(currentKey,"=").concat(currentValue.join(','));}return "".concat(accumulator).concat(separator).concat(currentKey,"=").concat(currentValue);};var paramStr=paramKeys.reduce(reducer,'?');return paramStr;}function setMatrix(matrix){var matrixList=matrix;if(!Array.isArray(matrix)){matrixList=Object.entries(matrix);}if(matrixList.length===0)return '';var reducer=function reducer(a,c){var matrixKey;var matrixValue;if(Array.isArray(c)){var _c=_slicedToArray__default["default"](c,2);matrixKey=_c[0];matrixValue=_c[1];}else {var _Object$keys=Object.keys(c);var _Object$keys2=_slicedToArray__default["default"](_Object$keys,1);matrixKey=_Object$keys2[0];var _Object$values=Object.values(c);var _Object$values2=_slicedToArray__default["default"](_Object$values,1);matrixValue=_Object$values2[0];}if(matrixValue===''||matrixValue===undefined){return a;}return "".concat(a,";").concat(matrixKey,"=").concat(encodeURIComponent(matrixValue));};var matrixStr=matrixList.reduce(reducer,'');return matrixStr;}function isRequired(){throw new Error('Missing property');}function vFetch(){var _ref3=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},path=_ref3.path,_ref3$method=_ref3.method,method=_ref3$method===void 0?'GET':_ref3$method,data=_ref3.body,_ref3$headers=_ref3.headers,extraHeaders=_ref3$headers===void 0?{}:_ref3$headers,_ref3$queryParams=_ref3.queryParams,queryParams=_ref3$queryParams===void 0?{}:_ref3$queryParams,_ref3$matrixParams=_ref3.matrixParams,matrixParams=_ref3$matrixParams===void 0?[]:_ref3$matrixParams,_ref3$costEstimate=_ref3.costEstimate,costEstimate=_ref3$costEstimate===void 0?false:_ref3$costEstimate,props=_objectWithoutProperties__default["default"](_ref3,_excluded2$S);var params=setQueryParams(queryParams);var matrix=setMatrix(matrixParams);var headers=setDefaultHeaders(extraHeaders);var url="".concat(path).concat(matrix).concat(params);if(costEstimate){url=url.replace('/API/','/API/cost/');}var request=_objectSpread$10({method:method,url:url,headers:headers,data:data},props);return new Promise(function(resolve,reject){defaultClient(request).then(function(response){response.ok=response.status>=100&&response.status<=399;response.json=function(){return response.data;};response.text=function(){return response.data;};resolve(response);})["catch"](function(error){return reject(error);});});}
|
|
30
32
|
|
|
31
33
|
var utils = /*#__PURE__*/Object.freeze({
|
|
@@ -564,7 +566,7 @@ var _excluded$T=["itemId"],_excluded2$O=["itemId","shapeId"],_excluded3$G=["item
|
|
|
564
566
|
* @returns {Promise<Object>}
|
|
565
567
|
*/function removeComponentBulkyMetadata(_ref18){var _ref18$itemId=_ref18.itemId,itemId=_ref18$itemId===void 0?isRequired():_ref18$itemId,_ref18$shapeId=_ref18.shapeId,shapeId=_ref18$shapeId===void 0?isRequired():_ref18$shapeId,_ref18$componentId=_ref18.componentId,componentId=_ref18$componentId===void 0?isRequired():_ref18$componentId,_ref18$key=_ref18.key,key=_ref18$key===void 0?isRequired():_ref18$key,props=_objectWithoutProperties__default["default"](_ref18,_excluded18$6);var path="/API/item/".concat(itemId,"/shape/").concat(shapeId,"/component/").concat(componentId,"/metadata/bulky/").concat(key);return vFetch(_objectSpread$W({path:path,method:'DELETE'},props));}var bulkymetadata = {listItemBulkyMetadata:listItemBulkyMetadata,listShapeBulkyMetadata:listShapeBulkyMetadata,listComponentBulkyMetadata:listComponentBulkyMetadata,updateAllItemBulkyMetadata:updateAllItemBulkyMetadata,updateAllShapeBulkyMetadata:updateAllShapeBulkyMetadata,updateAllComponentBulkyMetadata:updateAllComponentBulkyMetadata,removeAllItemBulkyMetadata:removeAllItemBulkyMetadata,removeAllShapeBulkyMetadata:removeAllShapeBulkyMetadata,removeAllComponentBulkyMetadata:removeAllComponentBulkyMetadata,getItemBulkyMetadata:getItemBulkyMetadata,getShapeBulkyMetadata:getShapeBulkyMetadata,getComponentBulkyMetadata:getComponentBulkyMetadata,updateItemBulkyMetadata:updateItemBulkyMetadata,updateShapeBulkyMetadata:updateShapeBulkyMetadata,updateComponentBulkyMetadata:updateComponentBulkyMetadata,removeItemBulkyMetadata:removeItemBulkyMetadata,removeShapeBulkyMetadata:removeShapeBulkyMetadata,removeComponentBulkyMetadata:removeComponentBulkyMetadata};
|
|
566
568
|
|
|
567
|
-
function ownKeys$V(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable;})),keys.push.apply(keys,symbols);}return keys;}function _objectSpread$V(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys$V(Object(source),!0).forEach(function(key){_defineProperty__default["default"](target,key,source[key]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys$V(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}return target;}function toPercent(numerator,denominator){if(numerator===0||denominator===0){return 0;}return Math.floor(numerator/denominator*100);}var constants=Object.freeze({statuses:{transfering:1,paused:2,complete:3,failed:4,unstarted:5,canceled:6},events:{progress:'progress',update:'update',complete:'complete',error:'error',added:'upload-added',removed:'upload-removed',retry:'retry',pausing:'pausing',paused:'paused',resuming:'resuming',offline:'offline',// <-- don't change this one, www spec match
|
|
569
|
+
function ownKeys$V(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter(function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable;})),keys.push.apply(keys,symbols);}return keys;}function _objectSpread$V(target){for(var i=1;i<arguments.length;i++){var source=null!=arguments[i]?arguments[i]:{};i%2?ownKeys$V(Object(source),!0).forEach(function(key){_defineProperty__default["default"](target,key,source[key]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(target,Object.getOwnPropertyDescriptors(source)):ownKeys$V(Object(source)).forEach(function(key){Object.defineProperty(target,key,Object.getOwnPropertyDescriptor(source,key));});}return target;}function toPercent(numerator,denominator){if(numerator===0||denominator===0){return 0;}return Math.floor(numerator/denominator*100);}var constants=Object.freeze({statuses:{transfering:1,paused:2,complete:3,failed:4,unstarted:5,canceled:6,offline:7},events:{progress:'progress',update:'update',complete:'complete',error:'error',added:'upload-added',removed:'upload-removed',retry:'retry',pausing:'pausing',paused:'paused',resuming:'resuming',offline:'offline',// <-- don't change this one, www spec match
|
|
568
570
|
online:'online'// <-- don't change this one, www spec match
|
|
569
571
|
},defaults:{targetRate:4000000,// 4mb sec,
|
|
570
572
|
chunkSize:10000000,// 10mb chunks
|
|
@@ -579,10 +581,9 @@ var handlers=this.events[event];if(!handlers||handlers.length<1)return;handlers.
|
|
|
579
581
|
};Object.assign(this,defaultProps,props);this.state={retries:0,status:constants.statuses.unstarted,startTime:null,completeTime:null,response:null,bytesTransfered:null};this.events=new CUEvents();}// try to transfer
|
|
580
582
|
_createClass__default["default"](Chunk,[{key:"try",value:function _try(){var _this=this;this.state.status=constants.statuses.transfering;this.state.startTime=performance.now();return new Promise(function(resolve,reject){var tryTransfer=function tryTransfer(){_this.transfer().then(function(response){_this.state.response=response;_this.onComplete();resolve();})["catch"](function(){if(_this.state.retries>3){_this.state.status=constants.statuses.failed;reject(new Error("Chunk ".concat(_this.start,"-").concat(_this.end," failed")));}else if(_this.state.status!==constants.statuses.paused){_this.state.retries+=1;// wait a sec and call again
|
|
581
583
|
_this.tryTimeout=setTimeout(function(){tryTransfer();// retry
|
|
582
|
-
},1000);}else {clearTimeout(_this.tryTimeout);}});};tryTransfer()
|
|
583
|
-
});}},{key:"transfer",value:function transfer(){var _this2=this;var options={file:this.blobSlice,onUploadProgress:function onUploadProgress(progressEvent){if(_this2.state.status!==constants.statuses.complete){_this2.state.bytesTransfered=progressEvent.loaded;_this2.events.trigger(constants.events.progress,_this2.state);}}};if(this.end-this.start!==this.fileSize){// only add headers if chunk !== whole file
|
|
584
|
+
},1000);}else {clearTimeout(_this.tryTimeout);}});};tryTransfer();window.addEventListener(constants.events.online,function(){_this.resume();});window.addEventListener(constants.events.offline,function(){_this.pause();});});}},{key:"transfer",value:function transfer(){var _this2=this;var options={file:this.blobSlice,onUploadProgress:function onUploadProgress(progressEvent){if(_this2.state.status!==constants.statuses.complete||_this2.state.status!==constants.statuses.offline){_this2.state.bytesTransfered=progressEvent.loaded;_this2.events.trigger(constants.events.progress,_this2.state);}}};if(this.end-this.start!==this.fileSize){// only add headers if chunk !== whole file
|
|
584
585
|
options.headers={index:this.start,size:this.fileSize};}options=_objectSpread$V(_objectSpread$V({},options),this.api.props);this.transferPromise=this.api.method(options);// TODO implement axios onUploadProgress
|
|
585
|
-
this.state.status=constants.statuses.transfering;return this.transferPromise;}},{key:"onComplete",value:function onComplete(){this.state.status=constants.statuses.complete;this.state.bytesTransfered=this.end-this.start;this.state.completeTime=performance.now();this.events.trigger(constants.events.complete);}},{key:"pause",value:function pause(){if(this.state.status!==constants.statuses.complete){this.state.status=constants.statuses.paused;}}},{key:"cancel",value:function cancel(){if(this.state.status!==constants.statuses.complete){this.state.status=constants.statuses.canceled;// reject promise
|
|
586
|
+
this.state.status=constants.statuses.transfering;return this.transferPromise;}},{key:"onComplete",value:function onComplete(){this.state.status=constants.statuses.complete;this.state.bytesTransfered=this.end-this.start;this.state.completeTime=performance.now();this.events.trigger(constants.events.complete);}},{key:"pause",value:function pause(){if(this.state.status!==constants.statuses.complete){this.state.status=constants.statuses.paused;}}},{key:"resume",value:function resume(){if(this.state.status!==constants.statuses.complete){this.state.status=constants.statuses.transfering;}}},{key:"cancel",value:function cancel(){if(this.state.status!==constants.statuses.complete){this.state.status=constants.statuses.canceled;// reject promise
|
|
586
587
|
// this.transferPromise && this.transferPromise.reject(new Error(`Chunk ${this.start}-${this.end} canceled.`))
|
|
587
588
|
}}},{key:"transferRate",get:function get(){if(this.state.bytesTransfered){var secondsTaken=(this.state.completeTime-this.state.startTime)/1000;var bytesPerSecond=this.state.bytesTransfered/secondsTaken;return bytesPerSecond;}return 0;}}]);return Chunk;}();var ChunkedUpload=/*#__PURE__*/function(){function ChunkedUpload(param,options){_classCallCheck__default["default"](this,ChunkedUpload);this.events=new CUEvents();// can be blob or transfer if for download (?)
|
|
588
589
|
if(!options.api.method)throw new Error('No api method specified');this.defaultOptions=_objectSpread$V(_objectSpread$V({},constants.defaults),{},{targetRate:4000000,// bytes / second
|
|
@@ -599,7 +600,9 @@ this.state.chunks.forEach(function(chunk){var isChunkAvailable=chunk.state.statu
|
|
|
599
600
|
_this3.state.transferPromises.push(chunk["try"]());}// TODO - forEach looks pretty but is not the fastest, consider if perf is optimal
|
|
600
601
|
});// reinvoke this method for next chunk batch
|
|
601
602
|
if(this.state.transferPromises.length>0){// there is more work to do
|
|
602
|
-
Promise.all(this.state.transferPromises).then(function(){_this3.upload();})["catch"](function(error){console.log('Failed on this upload() cycle, check connectivity and try to resume :(');_this3.state.status=constants.statuses.failed;_this3.events.trigger(constants.events.failed,{error:error,transfer:_this3})
|
|
603
|
+
Promise.all(this.state.transferPromises).then(function(){_this3.upload();})["catch"](function(error){console.log('Failed on this upload() cycle, check connectivity and try to resume :(',error);if(_this3.state.status!==constants.statuses.offline){_this3.state.status=constants.statuses.failed;_this3.events.trigger(constants.events.failed,{error:error,transfer:_this3});// if (this.options.onFail) this.options.onFail(error);
|
|
604
|
+
}else {setTimeout(function(){return _this3.retry();},5000);}});}}}else {// Operation unavailable, try .resume() instead.
|
|
605
|
+
this.retry();}}// get all byte ranges for splitting in chunks
|
|
603
606
|
},{key:"getByteRangesForChunks",value:function getByteRangesForChunks(blob){var chunkSize=arguments.length>1&&arguments[1]!==undefined?arguments[1]:this.options.chunkSize;var byteRanges=[];// output
|
|
604
607
|
var minChunkSize=this.options.minChunkSize;var targetChunkSize=chunkSize>=minChunkSize?chunkSize:minChunkSize;var finalChunkSize=targetChunkSize;// determine the number of chunks
|
|
605
608
|
var times=Math.floor(blob.size/finalChunkSize);// if last chunk happens to bee too small, reduce the denominator
|
|
@@ -608,7 +611,7 @@ times-=1;finalChunkSize=Math.floor(blob.size/times);// adjust final chunk size
|
|
|
608
611
|
}if(times<2||blob.size<this.options.minFileSize){// single chunk it is
|
|
609
612
|
byteRanges.push({start:0,end:blob.size});}else {for(var i=0;i<=times;i+=1){var start=finalChunkSize*i;var end=finalChunkSize*i+finalChunkSize;// if the remainig bytes to be transfered is less than minChunkSize
|
|
610
613
|
var remainder=blob.size-finalChunkSize*i;if(remainder<=minChunkSize){end=blob.size;}var range={start:start,end:end};byteRanges.push(range);if(end===blob.size){break;// all byteranges till the end are covered, no more chunks
|
|
611
|
-
}}}return byteRanges;}},{key:"addChunksFromBlob",value:function addChunksFromBlob(blob){var _this4=this;var byteranges=this.getByteRangesForChunks(blob);byteranges.forEach(function(byterange){var chunk=new Chunk({start:byterange.start,end:byterange.end,blobSlice:blob.slice(byterange.start,byterange.end),fileSize:blob.size,api:_this4.options.api});chunk.events.on(constants.events.progress,function(){_this4.onProgress();});chunk.events.on(constants.events.complete,function(){_this4.onProgress();});_this4.state.chunks.push(chunk);});}},{key:"retry",value:function retry(){if(this.state.status===constants.statuses.failed){this.resume();this.events.trigger(constants.events.retry);}}},{key:"resume",value:function resume(){this.state.status=constants.statuses.transfering;this.
|
|
614
|
+
}}}return byteRanges;}},{key:"addChunksFromBlob",value:function addChunksFromBlob(blob){var _this4=this;var byteranges=this.getByteRangesForChunks(blob);byteranges.forEach(function(byterange){var chunk=new Chunk({start:byterange.start,end:byterange.end,blobSlice:blob.slice(byterange.start,byterange.end),fileSize:blob.size,api:_this4.options.api});chunk.events.on(constants.events.progress,function(){_this4.onProgress();});chunk.events.on(constants.events.complete,function(){_this4.onProgress();});_this4.state.chunks.push(chunk);});}},{key:"retry",value:function retry(){if(this.state.status===constants.statuses.failed){this.resume();this.events.trigger(constants.events.retry);}}},{key:"resume",value:function resume(){this.state.status=constants.statuses.transfering;this.events.trigger(constants.events.resuming);if(this.state.chunks.length>0){this.state.chunks.forEach(function(chunkInstance){chunkInstance.resume();});}}},{key:"pause",value:function pause(){var _this5=this;this.state.status=constants.statuses.paused;// run a loop that pauses all Chunk instances (cancel network request / promise?)
|
|
612
615
|
if(this.state.chunks.length>0){this.state.chunks.forEach(function(chunkInstance){chunkInstance.pause();});}// wait for the rest of chunks to complete
|
|
613
616
|
var pausedPromise=Promise.all(this.state.transferPromises);this.events.trigger(constants.events.pausing);pausedPromise.then(function(){_this5.events.trigger(constants.events.paused);});return Promise.all(this.state.transferPromises);}},{key:"cancel",value:function cancel(){var _this6=this;// TODO - check what to destruct
|
|
614
617
|
this.state.status=constants.statuses.canceled;if(this.state.chunks.length>0){this.state.chunks.forEach(function(chunkInstance){chunkInstance.cancel();});}this.upload=function(){};var transfersFinishedPromise=Promise.all(this.state.transferPromises);transfersFinishedPromise.then(function(){_this6.events.trigger(constants.events.removed,_this6);});// remaining transfers finishing, this can take a long time
|
|
@@ -627,7 +630,8 @@ this.state.rate=stats.avgTransferRate;return stats;}// if a setter is used, stop
|
|
|
627
630
|
return this.state.rate;},set:function set(_int2){// sets target rate
|
|
628
631
|
this.state.targetRate=_int2;}},{key:"finalResponse",get:function get(){var times=this.state.chunks.length-1;var response=false;for(var i=times;i>=0;i-=1){var chunk=this.state.chunks[i];if(_typeof__default["default"](chunk.state.response.data)==='object'){return chunk.state.response;}}return response;}},{key:"transferId",get:function get(){return this.state.transferId;}}]);return ChunkedUpload;}();var ChunkedTransferManager=/*#__PURE__*/function(){function ChunkedTransferManager(options){_classCallCheck__default["default"](this,ChunkedTransferManager);this.initialState=Object.freeze({status:constants.statuses.unstarted,transfers:{},bytesDone:0,bytesTotal:0,lastStats:{// helps evaluate progress change
|
|
629
632
|
bytesDone:0,bytesTotal:0}});this.state=_objectSpread$V({},this.initialState);this.options=_objectSpread$V({maxConcurrentFileTransfers:constants.defaults.maxConcurrentFileTransfers,autoResume:constants.defaults.autoResume},options);this.events=new CUEvents();this.bindNetworkEvents();}_createClass__default["default"](ChunkedTransferManager,[{key:"bindNetworkEvents",value:function bindNetworkEvents(){var _this8=this;if(!(typeof window==='undefined')){// check if on browser
|
|
630
|
-
window.addEventListener(constants.events.online,function(){_this8.events.trigger(constants.events.online,_this8.state);if(_this8.options.autoResume){setTimeout(function(){_this8.retry();},1500);}});window.addEventListener(constants.events.offline,function(){_this8.events.trigger(constants.events.offline,_this8.state);
|
|
633
|
+
window.addEventListener(constants.events.online,function(){_this8.events.trigger(constants.events.online,_this8.state);_this8.state.status=constants.statuses.transfering;if(_this8.options.autoResume){setTimeout(function(){_this8.retry();},1500);}});window.addEventListener(constants.events.offline,function(){_this8.events.trigger(constants.events.offline,_this8.state);_this8.state.status=constants.statuses.offline;// if (this.options.autoResume) this.pause();
|
|
634
|
+
});}}},{key:"addChunkedUpload",value:function addChunkedUpload(cuInstance){var _this9=this;// for chunked uploads
|
|
631
635
|
if(cuInstance.transferId!==null){this.state.transfers[cuInstance.transferId]=cuInstance;// bind to ChunkedUpload events
|
|
632
636
|
cuInstance.events.on(constants.events.progress,function(){// a chunk is finished
|
|
633
637
|
_this9.onProgress();});cuInstance.events.on(constants.events.complete,function(){// a transfer is finished
|