@pageproof/sdk-pr 175.0.1561953365596 → 175.0.1563579370431
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/CHANGELOG.md +10 -0
- package/README.md +1 -0
- package/lib/api/Accounts.js +1 -1
- package/lib/api/Files.js +1 -1
- package/lib/api/admin/Admin.js +14 -2
- package/lib/api/admin/Reports.js +63 -0
- package/lib/api/admin/Team.js +18 -6
- package/lib/api/admin/TeamCustomWebhooks.js +51 -0
- package/lib/core/PageProof.js +1 -1
- package/lib/enum/ReportType.js +1 -0
- package/lib/network/Response.js +1 -1
- package/lib/network/endpoints.json +23 -0
- package/lib/pageproof.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.0.0-beta.90
|
|
4
|
+
Released on the 11th of July 2019.
|
|
5
|
+
-[#182](https://github.com/PageProofCom/sdk/pull/182) Support for generating reports by team admins. See [Reports.create](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/admin/Reports.js~Reports.html)
|
|
6
|
+
|
|
7
|
+
## 2.0.0-beta.89
|
|
8
|
+
|
|
9
|
+
Released on the 4th of July 2019.
|
|
10
|
+
|
|
11
|
+
- [[#172](https://github.com/PageProofCom/sdk/pull/172)] Support for setting a user's password for the first time. See [Accounts.setPassword](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Accounts.js~Accounts.html#instance-method-setPassword) and [Accounts.setPasswordRequest](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Accounts.js~Accounts.html#instance-method-setPasswordRequest).
|
|
12
|
+
|
|
3
13
|
## 2.0.0-beta.88
|
|
4
14
|
|
|
5
15
|
Released on the 20th of June 2019.
|
package/README.md
CHANGED
|
@@ -307,6 +307,7 @@ Name | Namespace | Description | Admin-only | Stability
|
|
|
307
307
|
[Proofs Groups Workflows API](./class/src/api/GroupsWorkflows.js~GroupsWorkflows.html) | `proofs.groups.workflows` | Used to add reviewers to proofs in a group. | No | Stable
|
|
308
308
|
[Proofs Reminders API](./class/src/api/Reminders.js~Reminders.html) | `proofs.reminders` | Manage reminders on proof. | No | Experimental
|
|
309
309
|
[Proofs Audit API](./class/src/api/ProofsAudit.js~ProofsAudit.html) | `proofs.audit` | View audit reports/summary/timeline. | No | Experimental
|
|
310
|
+
[Admin Reports API](./class/src/api/Reports.js~Reports.html) | `admin.reports` | Request reports to be emailed to you. | Yes | Stable
|
|
310
311
|
|
|
311
312
|
The "admin-only" APIs are exposed through the
|
|
312
313
|
[PageProof.admin](./class/src/core/PageProof.js~PageProof.html#instance-method-admin) method. These APIs are different
|
package/lib/api/Accounts.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Session=require("../models/Session");var _Session2=_interopRequireDefault(_Session);var _AccountsSSO=require("./AccountsSSO");var _AccountsSSO2=_interopRequireDefault(_AccountsSSO);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Accounts=function(_API){_inherits(Accounts,_API);function Accounts(client){_classCallCheck(this,Accounts);var _this=_possibleConstructorReturn(this,_API.call(this,client));_this.sso=new _AccountsSSO2.default(client);return _this}Accounts.prototype._generateCredentials=function _generateCredentials(password){var _this2=this;return this.client.crypto().generatePasswordHash(password).then(function(passwordHash){return Promise.all([passwordHash,_this2.client.crypto().generateKeyPair()])}).then(function(_ref){var passwordHash=_ref[0],keyPair=_ref[1];return Promise.all([passwordHash,keyPair,_this2.client.crypto().encryptPrivateKey(keyPair.privateKeyPEM,password)])})};Accounts.prototype.register=function register(email,password){var _this3=this;return this._generateCredentials(password).then(function(_ref2){var passwordHash=_ref2[0],keyPair=_ref2[1],privateKeyPEM$=_ref2[2];return Promise.all([keyPair,_this3.client.request("accounts.register",{email:email,password:passwordHash,privateKey:privateKeyPEM$,publicKey:keyPair.publicKeyPEM})])}).then(function(_ref3){var keyPair=_ref3[0];return Promise.all([keyPair,_this3.login(email,password,false)])}).then(function(_ref4){var keyPair=_ref4[0],session=_ref4[1];return Promise.all([keyPair,session,_this3.generateActivationCode()])}).then(function(_ref5){var keyPair=_ref5[0],session=_ref5[1];session.privateKeyPEM=keyPair.privateKeyPEM;return session})};Accounts.prototype.generateActivationCode=function generateActivationCode(){return this.client.request("accounts.generate-activation-code",{userId:this.client.session.userId})};Accounts.prototype.activate=function activate(activationCode){var _this4=this;return this.client.request("accounts.activate",{userId:this.client.session.userId,authCode:activationCode}).then(function(){_this4.client.session.user.hasActivated=true})};Accounts.prototype.login=function login(email,password){var _this5=this;var _decryptPrivateKey=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;return this.client.crypto().generatePasswordHash(password).then(function(passwordHash){return _this5.client.request("accounts.login",{email:email,password:passwordHash})}).then(function(response){var session=(new _Session2.default).fromSession(response.data);session.user.email=email;return session}).then(function(session){if(_decryptPrivateKey){return _this5.client.crypto().decryptPrivateKey(session.privateKeyPEM$,password).then(function(privateKeyPEM){session.privateKeyPEM=privateKeyPEM;return session})}return session}).then(function(session){_this5.client.setSession(session);return session})};Accounts.prototype.resetPassword=function resetPassword(_ref6){var _this6=this;var email=_ref6.email,code=_ref6.code,password=_ref6.password;return this._generateCredentials(password).then(function(_ref7){var passwordHash=_ref7[0],keyPair=_ref7[1],privateKeyPEM$=_ref7[2];return Promise.all([keyPair,_this6.client.request("accounts.reset-password",{email:email,secret:code,newPassword:passwordHash,newPrivateKey:privateKeyPEM$,newPublicKey:keyPair.publicKeyPEM})])}).then(function(_ref8){var keyPair=_ref8[0];return Promise.all([keyPair,_this6.login(email,password,false)])}).then(function(_ref9){var keyPair=_ref9[0],session=_ref9[1];session.privateKeyPEM=keyPair.privateKeyPEM;return session})};Accounts.prototype.forgotPassword=function forgotPassword(email){return this.client.request("accounts.forgot-password",{email:email})};Accounts.prototype.logout=function logout(){var
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Session=require("../models/Session");var _Session2=_interopRequireDefault(_Session);var _AccountsSSO=require("./AccountsSSO");var _AccountsSSO2=_interopRequireDefault(_AccountsSSO);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}var Accounts=function(_API){_inherits(Accounts,_API);function Accounts(client){_classCallCheck(this,Accounts);var _this=_possibleConstructorReturn(this,_API.call(this,client));_this.sso=new _AccountsSSO2.default(client);return _this}Accounts.prototype._generateCredentials=function _generateCredentials(password){var _this2=this;return this.client.crypto().generatePasswordHash(password).then(function(passwordHash){return Promise.all([passwordHash,_this2.client.crypto().generateKeyPair()])}).then(function(_ref){var passwordHash=_ref[0],keyPair=_ref[1];return Promise.all([passwordHash,keyPair,_this2.client.crypto().encryptPrivateKey(keyPair.privateKeyPEM,password)])})};Accounts.prototype.register=function register(email,password){var _this3=this;return this._generateCredentials(password).then(function(_ref2){var passwordHash=_ref2[0],keyPair=_ref2[1],privateKeyPEM$=_ref2[2];return Promise.all([keyPair,_this3.client.request("accounts.register",{email:email,password:passwordHash,privateKey:privateKeyPEM$,publicKey:keyPair.publicKeyPEM})])}).then(function(_ref3){var keyPair=_ref3[0];return Promise.all([keyPair,_this3.login(email,password,false)])}).then(function(_ref4){var keyPair=_ref4[0],session=_ref4[1];return Promise.all([keyPair,session,_this3.generateActivationCode()])}).then(function(_ref5){var keyPair=_ref5[0],session=_ref5[1];session.privateKeyPEM=keyPair.privateKeyPEM;return session})};Accounts.prototype.generateActivationCode=function generateActivationCode(){return this.client.request("accounts.generate-activation-code",{userId:this.client.session.userId})};Accounts.prototype.activate=function activate(activationCode){var _this4=this;return this.client.request("accounts.activate",{userId:this.client.session.userId,authCode:activationCode}).then(function(){_this4.client.session.user.hasActivated=true})};Accounts.prototype.login=function login(email,password){var _this5=this;var _decryptPrivateKey=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;return this.client.crypto().generatePasswordHash(password).then(function(passwordHash){return _this5.client.request("accounts.login",{email:email,password:passwordHash})}).then(function(response){var session=(new _Session2.default).fromSession(response.data);session.user.email=email;return session}).then(function(session){if(_decryptPrivateKey){return _this5.client.crypto().decryptPrivateKey(session.privateKeyPEM$,password).then(function(privateKeyPEM){session.privateKeyPEM=privateKeyPEM;return session})}return session}).then(function(session){_this5.client.setSession(session);return session})};Accounts.prototype.resetPassword=function resetPassword(_ref6){var _this6=this;var email=_ref6.email,code=_ref6.code,password=_ref6.password;return this._generateCredentials(password).then(function(_ref7){var passwordHash=_ref7[0],keyPair=_ref7[1],privateKeyPEM$=_ref7[2];return Promise.all([keyPair,_this6.client.request("accounts.reset-password",{email:email,secret:code,newPassword:passwordHash,newPrivateKey:privateKeyPEM$,newPublicKey:keyPair.publicKeyPEM})])}).then(function(_ref8){var keyPair=_ref8[0];return Promise.all([keyPair,_this6.login(email,password,false)])}).then(function(_ref9){var keyPair=_ref9[0],session=_ref9[1];session.privateKeyPEM=keyPair.privateKeyPEM;return session})};Accounts.prototype.forgotPassword=function forgotPassword(email){return this.client.request("accounts.forgot-password",{email:email})};Accounts.prototype.setPasswordRequest=function setPasswordRequest(email){return this.client.request("accounts.set-password-request",{email:email})};Accounts.prototype.setPassword=function setPassword(_ref10){var _this7=this;var email=_ref10.email,code=_ref10.code,password=_ref10.password;return this._generateCredentials(password).then(function(_ref11){var passwordHash=_ref11[0],keyPair=_ref11[1],privateKeyPEM$=_ref11[2];return Promise.all([keyPair,_this7.client.request("accounts.set-password",{email:email,secret:code,newPassword:passwordHash,newPrivateKey:privateKeyPEM$,newPublicKey:keyPair.publicKeyPEM})])}).then(function(_ref12){var keyPair=_ref12[0];return Promise.all([keyPair,_this7.login(email,password,false)])}).then(function(_ref13){var keyPair=_ref13[0],session=_ref13[1];session.privateKeyPEM=keyPair.privateKeyPEM;return session})};Accounts.prototype.logout=function logout(){var _this8=this;return this.client.request("accounts.logout").catch(function(err){_this8.client.setSession(null);return Promise.reject(err)}).then(function(){_this8.client.setSession(null)})};return Accounts}(_API3.default);exports.default=Accounts;
|
package/lib/api/Files.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _File=require("../models/File");var _File2=_interopRequireDefault(_File);var _FileStatus=require("../enum/FileStatus");var _FileStatus2=_interopRequireDefault(_FileStatus);var _ImportProvider=require("../enum/ImportProvider");var _ImportProvider2=_interopRequireDefault(_ImportProvider);var _streamBlocks=require("../util/streamBlocks");var _streamBlocks2=_interopRequireDefault(_streamBlocks);var _bluffer=require("../bluffer");var _bluffer2=_interopRequireDefault(_bluffer);var _getContentLength=require("../util/getContentLength");var _getContentLength2=_interopRequireDefault(_getContentLength);var _constants=require("../util/constants");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _concurrent=require("../util/concurrent");var _concurrent2=_interopRequireDefault(_concurrent);var _id=require("../util/id");var _parseUrl=require("../util/parseUrl");var _parseUrl2=_interopRequireDefault(_parseUrl);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i]}return target}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}function parseFilename(filename){var extensionIndex=filename.lastIndexOf(".");var name=filename.substring(0,extensionIndex);var extension=filename.substring(extensionIndex+1);return{name:name,extension:extension}}function containPercentage(percent,left,right){var total=1-(left+right);return total*percent+left}var Files=function(_API){_inherits(Files,_API);function Files(){_classCallCheck(this,Files);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Files.prototype.generateToken=function generateToken(assignedTo,assignedType){if(assignedTo&&!assignedType){return Promise.reject(Error('The "assignedType" option is required when specifying the "assignedTo" option.'))}if(!assignedTo&&assignedType){return Promise.reject(Error('The "assignedTo" option is required when specifying the "assignedType" option.'))}return this.client.request("files.legacy.generate-token",{relatedId:assignedTo,fileType:assignedType}).then(function(response){return response.data.Token})};Files.prototype.setCanDownload=function setCanDownload(fileId,canDownload){return this.client.request("files.can-download.update",{fileId:fileId,downloadOriginal:canDownload?1:0})};Files.prototype._waitFileProcessed=function _waitFileProcessed(id){var _this2=this;return new Promise(function(resolve,reject){var checkTimeout=null;var timeoutTimeout=null;var check=function check(){_this2.details(id).then(function(file){checkTimeout=null;switch(file.status){case _FileStatus2.default.OK:{resolve(file);break}case _FileStatus2.default.ERROR:{reject(new Error("File "+id+" encountered a processing error: "+file.message));break}default:{checkTimeout=setTimeout(check,5e3);break}}if(!checkTimeout||file.status===_FileStatus2.default.RIPPING){clearTimeout(timeoutTimeout)}}).catch(reject)};check();timeoutTimeout=setTimeout(function(){clearTimeout(checkTimeout);reject(new Error("File did not finish processing within specified duration."))},3e4)})};Files.prototype.import=function _import(_ref){var _this3=this;var name=_ref.name,url=_ref.url,_ref$provider=_ref.provider,provider=_ref$provider===undefined?_ImportProvider2.default.NONE:_ref$provider,auth=_ref.auth,_ref$download=_ref.download,download=_ref$download===undefined?false:_ref$download,_ref$process=_ref.process,process=_ref$process===undefined?false:_ref$process;var providerSupported=Object.keys(_ImportProvider2.default).some(function(key){return _ImportProvider2.default[key]===provider});if(!providerSupported){return Promise.reject(new Error('Unsupported provider "'+provider+'"'))}var endpoint=provider;if(provider===_ImportProvider2.default.NONE){endpoint="generic"}var _parseFilename=parseFilename(name),filename=_parseFilename.name,extension=_parseFilename.extension;return this._generateKeyIVEnvelope().then(function(_ref2){var envelope=_ref2.envelope;return _this3.client.request("files.import."+endpoint,{extn:extension,filename:filename,url:url,envelope:envelope,accessToken:auth,storeOriginal:download})}).then(function(response){return response.data}).then(function(token){if(process){return _this3._waitFileProcessed(token)}else{var file=new _File2.default;file.id=token;return file}})};Files.prototype._generateKeyIVEnvelope=function _generateKeyIVEnvelope(){var _this4=this;return this.client.crypto().generateKeyIV().then(function(keyIV){return Promise.all([keyIV,_this4.client.crypto().envelopeSeal(keyIV.keyIV,[_this4.client.session.serverPublicKeyPEM,_this4.client.session.publicKeyPEM])])}).then(function(_ref3){var keyIV=_ref3[0],envelope=_ref3[1];return{keyIV:keyIV,envelope:envelope}})};Files.prototype.upload=function upload(){return this.upload__v2.apply(this,arguments)};Files.prototype.upload__v2=function upload__v2(files){var _this5=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var _options$concurrent=options.concurrent,concurrency=_options$concurrent===undefined?6:_options$concurrent,opts=_objectWithoutProperties(options,["concurrent"]);var scheduleChunk=(0,_concurrent2.default)(concurrency);var scheduleDone=(0,_concurrent2.default)(1);var doneFiles=[];var multipleFiles=Array.isArray(files);var filesList=multipleFiles?files:[files];var done=function done(result){doneFiles.push(result);return scheduleDone(function(){if(doneFiles.length){var _doneFiles=doneFiles.slice();doneFiles.length=0;return _this5.client.request("files.v2.upload-complete",{files:_doneFiles})}return null})};return this.client.request("files.v2.generate-credentials",{supports:{providers:["abs","custom"]},files:filesList.map(function(file){var name=void 0;var extension=void 0;if(file.extension){var _ref4=[file.name,file.extension];name=_ref4[0];extension=_ref4[1]}else{var parsed=parseFilename(file.name);var _ref5=[parsed.name,parsed.extension];name=_ref5[0];extension=_ref5[1]}var size=(0,_getContentLength2.default)(file.contents);var chunks=Math.ceil(size/_constants.BYTES_PER_BLOCK);if(file.onProgress){file.onProgress(0)}return{name:name,extension:extension,chunks:chunks,size:size,hash:null,adobeExportData:file.adobeExportData?JSON.stringify(file.adobeExportData):null,assignedTo:file.assignedTo,assignedType:file.assignedType,canDownload:typeof file.download!=="undefined"?!!file.download:true}})}).then(function(response){return Promise.all(filesList.map(function(file,index){var definition=response.data[index];if(file.onProgress){file.onProgress(1)}return _this5._upload__v2(file,definition,opts,scheduleChunk,done).then(function(){var entity=new _File2.default;entity.id=definition.FileId;return entity})}))}).then(function(results){return multipleFiles?results:results[0]})};Files.prototype._upload__v2=function _upload__v2(file,definition,options,schedule,done){var _this6=this;return this._generateKeyIVEnvelope().then(function(_ref6){var keyIV=_ref6.keyIV,envelope=_ref6.envelope;return new Promise(function(resolve){var fileId=definition.FileId,uploadCredentials=definition.UploadCredentials;var bluffer=new _bluffer2.default;var complete=false;var index=0;var blocks=(0,_streamBlocks2.default)(file.contents,function(b){return bluffer.readBase64(b)});var tasks=[];var count=Math.ceil((0,_getContentLength2.default)(file.contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var lastPercent=1;var onUploadProgress=function onUploadProgress(){};var onProgress=file.onProgress;if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);var totalPercent=containPercentage(percent.reduce(function(a,b){return a+(b||0)},0)/count/100,.01,.01)*100;if(typeof options.progressDecimalPlaces!=="undefined"){totalPercent=+totalPercent.toFixed(options.progressDecimalPlaces)}if(lastPercent!==totalPercent){onProgress(totalPercent);lastPercent=totalPercent}}}function handle(block,blockIndex){var task=encryptAndUpload(block,blockIndex);tasks.push(task);return task}var abs=function abs(block,blockIndex){return _this6.client.rawRequest({method:"PUT",host:uploadCredentials.url,path:"/"+fileId+"/"+blockIndex,query:uploadCredentials.sas,body:block,headers:{"x-ms-blob-type":"BlockBlob"}},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var custom=function custom(block,blockIndex){var values={"file.id":fileId,"chunk.index":blockIndex};var interpolate=function interpolate(str){var map=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(a){return a};return str.replace(/\{([\w\.]+)\}/g,function(_,key){return map(values[key])})};var interpolatedHeaders={};Object.keys(uploadCredentials.headers).forEach(function(name){var value=interpolate(uploadCredentials.headers[name]);interpolatedHeaders[interpolate(name)]=value});return _this6.client.rawRequest({method:uploadCredentials.method,host:interpolate(uploadCredentials.host),path:interpolate(uploadCredentials.path,encodeURIComponent),query:interpolate(uploadCredentials.query,encodeURIComponent),body:block,headers:interpolatedHeaders},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var uploadData={abs:abs,custom:custom}[uploadCredentials.type];var encryptAndUpload=function encryptAndUpload(block,blockIndex){return _this6.client.crypto().encryptFileBlock(keyIV,block,true).then(function(block$_){return bluffer.createBase64(block$_)}).then(function(block$){return uploadData(block$,blockIndex)})};var finish=function finish(){return done({fileId:fileId,envelope:envelope}).then(function(){if(onProgress)onProgress(100)})};function next(){if(complete){return}schedule(function(){return blocks().then(function(data){if(data){next();return handle(data,index++)}else if(!complete){complete=true;var final=Promise.all(tasks).then(finish);resolve(final)}})})}next();if(file.async!==false){resolve()}})})};Files.prototype.upload__legacy=function upload__legacy(_ref7){var _this7=this;var name=_ref7.name,contents=_ref7.contents,adobeExportData=_ref7.adobeExportData,assignedTo=_ref7.assignedTo,assignedType=_ref7.assignedType,_ref7$download=_ref7.download,download=_ref7$download===undefined?false:_ref7$download,_ref7$async=_ref7.async,async=_ref7$async===undefined?true:_ref7$async,onProgress=_ref7.onProgress,onError=_ref7.onError;return this.generateToken(assignedTo,assignedType).then(function(token){return Promise.all([token,_this7._generateKeyIVEnvelope()])}).then(function(_ref8){var token=_ref8[0],_ref8$=_ref8[1],keyIV=_ref8$.keyIV,envelope=_ref8$.envelope;var process=_this7._upload__legacy({name:name,contents:contents,adobeExportData:adobeExportData,download:download,token:token,keyIV:keyIV,envelope:envelope,onProgress:onProgress,onError:onError});if(async){process=Promise.resolve()}return process.then(function(){return token})}).then(function(token){var file=new _File2.default;file.id=token;return file})};Files.prototype._upload__legacy=function _upload__legacy(_ref9){var _this8=this;var name=_ref9.name,contents=_ref9.contents,adobeExportData=_ref9.adobeExportData,download=_ref9.download,token=_ref9.token,keyIV=_ref9.keyIV,envelope=_ref9.envelope,onProgress=_ref9.onProgress;return new Promise(function(resolve){var concurrent=4;var _parseFilename2=parseFilename(name),filename=_parseFilename2.name,extension=_parseFilename2.extension;var blocks=(0,_streamBlocks2.default)(contents);var chain=Promise.resolve();var index=0;var end=false;var count=Math.ceil((0,_getContentLength2.default)(contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var onUploadProgress=function onUploadProgress(){};if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(block,blockIndex){return _this8.client.crypto().encryptFileBlock(keyIV,block).then(function(block$){return _this8.client.request("files.legacy.upload-block",{block:blockIndex,part:1,token:token,data:block$},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})})};function next(){blocks().then(function(block){if(end)return;if(block===null){end=true;resolve(chain.then(complete))}else{var handle=process(block,index++);chain=chain.then(function(){return handle});handle.then(next)}})}var complete=function complete(){return _this8.client.request("files.legacy.upload-complete",{block:0,blockCount:index,part:0,token:token,extn:extension,pages:1,filename:filename,storeoriginal:download?1:0,adobeExportData:adobeExportData?JSON.stringify(adobeExportData):null,envelope:envelope}).then(function(){return onProgress&&onProgress(100)})};while(concurrent--){next()}})};Files.prototype.download=function download(_options){var _this9=this;var options=typeof _options==="string"?{fileId:_options}:_options;var fileId=options.fileId,onFileDetails=options.onFileDetails;return this.details(fileId).then(function(file){if(!file.downloadable){throw new Error("File "+fileId+" is not downloadable.")}if(file.status!==_FileStatus2.default.OK){throw new Error("File "+fileId+" cannot be download. The file may still be uploading, processing or has errored.")}if(!file.blocks){throw new Error("File "+fileId+" is empty.")}if(onFileDetails){onFileDetails(file)}return _this9._downloadFile(file,options)})};Files.prototype._downloadFile=function _downloadFile(file,options){var _this10=this;return new Promise(function(resolve){var concurrent=4;var bluffer=new _bluffer2.default;var count=file.blocks;var blocks=new Array(count);var chain=Promise.resolve();var onData=options.onData||function onData(block,index){blocks[index]=block};var onDownloadProgress=function onDownloadProgress(){};if(options.onProgress){var percent=new Array(count);onDownloadProgress=function onDownloadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);options.onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(blockIndex){return _this10.client.request("files.download-block",{proofId:file.assignedTo,fileId:file.id,block:blockIndex+1},{onDownloadProgress:onDownloadProgress.bind(null,blockIndex)}).then(function(response){return _this10.client.crypto().decryptFileBlock(response.data,_this10.client.session.privateKeyPEM).then(function(blockBase64){return bluffer.createBase64(blockBase64)})})};var index=0;var end=false;function next(){if(end)return;if(index<blocks.length){var blockIndex=index++;var block=process(blockIndex);chain=chain.then(function(){return block.then(function(data){return onData(data,blockIndex,count)})});block.then(next)}else{end=true;resolve(chain.then(complete))}}var complete=function complete(){if(options.onProgress){options.onProgress(100)}if(!options.onData){return bluffer.combine.apply(bluffer,blocks)}return null};while(concurrent--){next()}})};Files.prototype.details=function details(fileId){return this.client.request("files.details",{fileId:fileId}).then(function(response){return(new _File2.default).fromFile(response.data)})};Files.prototype.thumbnail=function thumbnail(fileIdOrThumbnailUrl){var _this11=this;var fileId=fileIdOrThumbnailUrl;var thumbnailUrl=null;if(!(0,_id.isFileId)(fileId)){thumbnailUrl=fileId;var thumbnailUrlFileIdRegex=/\/(F[\w]{15})-thumb/;var fileIdMatch=fileIdOrThumbnailUrl.match(thumbnailUrlFileIdRegex);if(fileIdMatch){fileId=fileIdMatch[1]}else{throw new Error("Malformed/unsupported thumbnail URL. Consider this might be related to the SDK version you are using.")}}return this.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(){return _this11._thumbnail(fileId,thumbnailUrl)})};Files.prototype._thumbnail=function _thumbnail(fileId,thumbnailUrl){var _this12=this;var promise=null;if(thumbnailUrl){var parsedUrl=(0,_parseUrl2.default)(thumbnailUrl);promise=this.client.rawRequest({method:"GET",host:parsedUrl.host,path:parsedUrl.pathname,query:parsedUrl.search,body:null,headers:{}}).then(function(response){return response.body})}else{promise=this.client.request("files.thumbnail",{fileId:fileId}).then(function(response){return response.data})}return promise.then(function(data){return _this12.client.crypto().decryptImage(data,_this12.client.session.privateKeyPEM)}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.thumbnails=function thumbnails(fileIds,_ref10){var _this13=this;var _ref10$async=_ref10.async,async=_ref10$async===undefined?false:_ref10$async,onLoadThumbnail=_ref10.onLoadThumbnail,onLoadThumbnails=_ref10.onLoadThumbnails,_ref10$onLoadThumbnai=_ref10.onLoadThumbnailsThrottleMs,onLoadThumbnailsThrottleMs=_ref10$onLoadThumbnai===undefined?1e3:_ref10$onLoadThumbnai,onLoadError=_ref10.onLoadError;var scheduled=[];var pendingBatch={};var scheduleOnLoadThumbnails=onLoadThumbnails?(0,_throttle2.default)(function(){if(Object.keys(pendingBatch).length){onLoadThumbnails(pendingBatch);pendingBatch={}}},onLoadThumbnailsThrottleMs):function(){};return Promise.all(fileIds.map(function(fileId){return _this13.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(resolve){scheduled.push({fileId:fileId,resolve:resolve})}).then(function(thumbnail){var _ref11;return thumbnail&&(_ref11={},_ref11[fileId]=thumbnail,_ref11)})})).then(function(entries){var more=Promise.all(scheduled.map(function(_ref12){var fileId=_ref12.fileId,resolve=_ref12.resolve;return _this13._thumbnail(fileId).then(function(thumbnail){var _ref13;resolve(thumbnail);if(onLoadThumbnail){var _onLoadThumbnail;onLoadThumbnail((_onLoadThumbnail={},_onLoadThumbnail[fileId]=thumbnail,_onLoadThumbnail))}pendingBatch[fileId]=thumbnail;scheduleOnLoadThumbnails();return _ref13={},_ref13[fileId]=thumbnail,_ref13}).catch(function(err){if(onLoadError){onLoadError(err,fileId)}if(!async){return Promise.reject(err)}return{}})}));if(async){return entries}else{return more.then(function(moreEntries){return[].concat(entries,moreEntries)})}}).then(function(entries){return Object.assign.apply(Object,[{}].concat(entries))})};return Files}(_API3.default);exports.default=Files;
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _File=require("../models/File");var _File2=_interopRequireDefault(_File);var _FileStatus=require("../enum/FileStatus");var _FileStatus2=_interopRequireDefault(_FileStatus);var _ImportProvider=require("../enum/ImportProvider");var _ImportProvider2=_interopRequireDefault(_ImportProvider);var _streamBlocks=require("../util/streamBlocks");var _streamBlocks2=_interopRequireDefault(_streamBlocks);var _bluffer=require("../bluffer");var _bluffer2=_interopRequireDefault(_bluffer);var _getContentLength=require("../util/getContentLength");var _getContentLength2=_interopRequireDefault(_getContentLength);var _constants=require("../util/constants");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _concurrent=require("../util/concurrent");var _concurrent2=_interopRequireDefault(_concurrent);var _id=require("../util/id");var _parseUrl=require("../util/parseUrl");var _parseUrl2=_interopRequireDefault(_parseUrl);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _objectWithoutProperties(obj,keys){var target={};for(var i in obj){if(keys.indexOf(i)>=0)continue;if(!Object.prototype.hasOwnProperty.call(obj,i))continue;target[i]=obj[i]}return target}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return call&&(typeof call==="object"||typeof call==="function")?call:self}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass)}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass}function parseFilename(filename){var extensionIndex=filename.lastIndexOf(".");var name=filename.substring(0,extensionIndex);var extension=filename.substring(extensionIndex+1);return{name:name,extension:extension}}function containPercentage(percent,left,right){var total=1-(left+right);return total*percent+left}var Files=function(_API){_inherits(Files,_API);function Files(){_classCallCheck(this,Files);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Files.prototype.generateToken=function generateToken(assignedTo,assignedType){if(assignedTo&&!assignedType){return Promise.reject(Error('The "assignedType" option is required when specifying the "assignedTo" option.'))}if(!assignedTo&&assignedType){return Promise.reject(Error('The "assignedTo" option is required when specifying the "assignedType" option.'))}return this.client.request("files.legacy.generate-token",{relatedId:assignedTo,fileType:assignedType}).then(function(response){return response.data.Token})};Files.prototype.setCanDownload=function setCanDownload(fileId,canDownload){return this.client.request("files.can-download.update",{fileId:fileId,downloadOriginal:canDownload?1:0})};Files.prototype._waitFileProcessed=function _waitFileProcessed(id){var _this2=this;return new Promise(function(resolve,reject){var checkTimeout=null;var timeoutTimeout=null;var check=function check(){_this2.details(id).then(function(file){checkTimeout=null;switch(file.status){case _FileStatus2.default.OK:{resolve(file);break}case _FileStatus2.default.ERROR:{reject(new Error("File "+id+" encountered a processing error: "+file.message));break}default:{checkTimeout=setTimeout(check,5e3);break}}if(!checkTimeout||file.status===_FileStatus2.default.RIPPING){clearTimeout(timeoutTimeout)}}).catch(reject)};check();timeoutTimeout=setTimeout(function(){clearTimeout(checkTimeout);reject(new Error("File did not finish processing within specified duration."))},3e4)})};Files.prototype.import=function _import(_ref){var _this3=this;var name=_ref.name,url=_ref.url,_ref$provider=_ref.provider,provider=_ref$provider===undefined?_ImportProvider2.default.NONE:_ref$provider,auth=_ref.auth,_ref$download=_ref.download,download=_ref$download===undefined?false:_ref$download,_ref$process=_ref.process,process=_ref$process===undefined?false:_ref$process;var providerSupported=Object.keys(_ImportProvider2.default).some(function(key){return _ImportProvider2.default[key]===provider});if(!providerSupported){return Promise.reject(new Error('Unsupported provider "'+provider+'"'))}var endpoint=provider;if(provider===_ImportProvider2.default.NONE){endpoint="generic"}var _parseFilename=parseFilename(name),filename=_parseFilename.name,extension=_parseFilename.extension;return this._generateKeyIVEnvelope().then(function(_ref2){var envelope=_ref2.envelope;return _this3.client.request("files.import."+endpoint,{extn:extension,filename:filename,url:url,envelope:envelope,accessToken:auth,storeOriginal:download})}).then(function(response){return response.data}).then(function(token){if(process){return _this3._waitFileProcessed(token)}else{var file=new _File2.default;file.id=token;return file}})};Files.prototype._generateKeyIVEnvelope=function _generateKeyIVEnvelope(){var _this4=this;return this.client.crypto().generateKeyIV().then(function(keyIV){return Promise.all([keyIV,_this4.client.crypto().envelopeSeal(keyIV.keyIV,[_this4.client.session.serverPublicKeyPEM,_this4.client.session.publicKeyPEM])])}).then(function(_ref3){var keyIV=_ref3[0],envelope=_ref3[1];return{keyIV:keyIV,envelope:envelope}})};Files.prototype.upload=function upload(){return this.upload__v2.apply(this,arguments)};Files.prototype.upload__v2=function upload__v2(files){var _this5=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var _options$concurrent=options.concurrent,concurrency=_options$concurrent===undefined?6:_options$concurrent,opts=_objectWithoutProperties(options,["concurrent"]);var scheduleChunk=(0,_concurrent2.default)(concurrency);var scheduleDone=(0,_concurrent2.default)(1);var doneFiles=[];var multipleFiles=Array.isArray(files);var filesList=multipleFiles?files:[files];var done=function done(result){doneFiles.push(result);return scheduleDone(function(){if(doneFiles.length){var _doneFiles=doneFiles.slice();doneFiles.length=0;return _this5.client.request("files.v2.upload-complete",{files:_doneFiles})}return null})};return this.client.request("files.v2.generate-credentials",{supports:{providers:["abs","custom"]},files:filesList.map(function(file){var name=void 0;var extension=void 0;if(file.extension){var _ref4=[file.name,file.extension];name=_ref4[0];extension=_ref4[1]}else{var parsed=parseFilename(file.name);var _ref5=[parsed.name,parsed.extension];name=_ref5[0];extension=_ref5[1]}var size=(0,_getContentLength2.default)(file.contents);var chunks=Math.ceil(size/_constants.BYTES_PER_BLOCK);if(file.onProgress){file.onProgress(0)}return{name:name,extension:extension,chunks:chunks,size:size,hash:null,adobeExportData:file.adobeExportData?JSON.stringify(file.adobeExportData):null,assignedTo:file.assignedTo,assignedType:file.assignedType,canDownload:typeof file.download!=="undefined"?!!file.download:true}})}).then(function(response){return Promise.all(filesList.map(function(file,index){var definition=response.data[index];if(file.onProgress){file.onProgress(1)}return _this5._upload__v2(file,definition,opts,scheduleChunk,done).then(function(){var entity=new _File2.default;entity.id=definition.FileId;return entity})}))}).then(function(results){return multipleFiles?results:results[0]})};Files.prototype._upload__v2=function _upload__v2(file,definition,options,schedule,done){var _this6=this;return this._generateKeyIVEnvelope().then(function(_ref6){var keyIV=_ref6.keyIV,envelope=_ref6.envelope;return new Promise(function(resolve){var fileId=definition.FileId,uploadCredentials=definition.UploadCredentials;var bluffer=new _bluffer2.default;var complete=false;var index=0;var blocks=(0,_streamBlocks2.default)(file.contents,function(b){return bluffer.readBase64(b)});var tasks=[];var count=Math.ceil((0,_getContentLength2.default)(file.contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var lastPercent=1;var onUploadProgress=function onUploadProgress(){};var onProgress=file.onProgress;if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);var totalPercent=containPercentage(percent.reduce(function(a,b){return a+(b||0)},0)/count/100,.01,.01)*100;if(typeof options.progressDecimalPlaces!=="undefined"){totalPercent=+totalPercent.toFixed(options.progressDecimalPlaces)}if(lastPercent!==totalPercent){onProgress(totalPercent);lastPercent=totalPercent}}}function handle(block,blockIndex){var task=encryptAndUpload(block,blockIndex);tasks.push(task);return task}var abs=function abs(block,blockIndex){return _this6.client.rawRequest({method:"PUT",host:uploadCredentials.url,path:"/"+fileId+"/"+blockIndex,query:uploadCredentials.sas,body:block,headers:{"x-ms-blob-type":"BlockBlob"}},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var custom=function custom(block,blockIndex){var values={"file.id":fileId,"chunk.index":blockIndex};var interpolate=function interpolate(str){var map=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(a){return a};return str.replace(/\{([\w\.]+)\}/g,function(_,key){return map(values[key])})};var interpolatedHeaders={};Object.keys(uploadCredentials.headers).forEach(function(name){var value=interpolate(uploadCredentials.headers[name]);interpolatedHeaders[interpolate(name)]=value});return _this6.client.rawRequest({method:uploadCredentials.method,host:interpolate(uploadCredentials.host),path:interpolate(uploadCredentials.path,encodeURIComponent),query:interpolate(uploadCredentials.query,encodeURIComponent),body:block,headers:interpolatedHeaders},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})};var genericRetry=function genericRetry(maximumAttempts,handler){var attemptCount=0;function attempt(){attemptCount++;return handler().catch(function(err){if(attemptCount>=maximumAttempts){return Promise.reject(err)}return(0,_sleep2.default)(1e3).then(attempt)})}return attempt()};var uploadData={abs:abs,custom:custom}[uploadCredentials.type];var encryptAndUpload=function encryptAndUpload(block,blockIndex){return _this6.client.crypto().encryptFileBlock(keyIV,block,true).then(function(block$_){return bluffer.createBase64(block$_)}).then(function(block$){return genericRetry(5,function(){return uploadData(block$,blockIndex)})})};var finish=function finish(){return done({fileId:fileId,envelope:envelope}).then(function(){if(onProgress)onProgress(100)})};function next(){if(complete){return}schedule(function(){return blocks().then(function(data){if(data){next();return handle(data,index++)}else if(!complete){complete=true;var final=Promise.all(tasks).then(finish);resolve(final)}})})}next();if(file.async!==false){resolve()}})})};Files.prototype.upload__legacy=function upload__legacy(_ref7){var _this7=this;var name=_ref7.name,contents=_ref7.contents,adobeExportData=_ref7.adobeExportData,assignedTo=_ref7.assignedTo,assignedType=_ref7.assignedType,_ref7$download=_ref7.download,download=_ref7$download===undefined?false:_ref7$download,_ref7$async=_ref7.async,async=_ref7$async===undefined?true:_ref7$async,onProgress=_ref7.onProgress,onError=_ref7.onError;return this.generateToken(assignedTo,assignedType).then(function(token){return Promise.all([token,_this7._generateKeyIVEnvelope()])}).then(function(_ref8){var token=_ref8[0],_ref8$=_ref8[1],keyIV=_ref8$.keyIV,envelope=_ref8$.envelope;var process=_this7._upload__legacy({name:name,contents:contents,adobeExportData:adobeExportData,download:download,token:token,keyIV:keyIV,envelope:envelope,onProgress:onProgress,onError:onError});if(async){process=Promise.resolve()}return process.then(function(){return token})}).then(function(token){var file=new _File2.default;file.id=token;return file})};Files.prototype._upload__legacy=function _upload__legacy(_ref9){var _this8=this;var name=_ref9.name,contents=_ref9.contents,adobeExportData=_ref9.adobeExportData,download=_ref9.download,token=_ref9.token,keyIV=_ref9.keyIV,envelope=_ref9.envelope,onProgress=_ref9.onProgress;return new Promise(function(resolve){var concurrent=4;var _parseFilename2=parseFilename(name),filename=_parseFilename2.name,extension=_parseFilename2.extension;var blocks=(0,_streamBlocks2.default)(contents);var chain=Promise.resolve();var index=0;var end=false;var count=Math.ceil((0,_getContentLength2.default)(contents)/_constants.BYTES_PER_BLOCK);var percent=new Array(count);var onUploadProgress=function onUploadProgress(){};if(onProgress){onUploadProgress=function onUploadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(block,blockIndex){return _this8.client.crypto().encryptFileBlock(keyIV,block).then(function(block$){return _this8.client.request("files.legacy.upload-block",{block:blockIndex,part:1,token:token,data:block$},{onUploadProgress:onUploadProgress.bind(null,blockIndex)})})};function next(){blocks().then(function(block){if(end)return;if(block===null){end=true;resolve(chain.then(complete))}else{var handle=process(block,index++);chain=chain.then(function(){return handle});handle.then(next)}})}var complete=function complete(){return _this8.client.request("files.legacy.upload-complete",{block:0,blockCount:index,part:0,token:token,extn:extension,pages:1,filename:filename,storeoriginal:download?1:0,adobeExportData:adobeExportData?JSON.stringify(adobeExportData):null,envelope:envelope}).then(function(){return onProgress&&onProgress(100)})};while(concurrent--){next()}})};Files.prototype.download=function download(_options){var _this9=this;var options=typeof _options==="string"?{fileId:_options}:_options;var fileId=options.fileId,onFileDetails=options.onFileDetails;return this.details(fileId).then(function(file){if(!file.downloadable){throw new Error("File "+fileId+" is not downloadable.")}if(file.status!==_FileStatus2.default.OK){throw new Error("File "+fileId+" cannot be download. The file may still be uploading, processing or has errored.")}if(!file.blocks){throw new Error("File "+fileId+" is empty.")}if(onFileDetails){onFileDetails(file)}return _this9._downloadFile(file,options)})};Files.prototype._downloadFile=function _downloadFile(file,options){var _this10=this;return new Promise(function(resolve){var concurrent=4;var bluffer=new _bluffer2.default;var count=file.blocks;var blocks=new Array(count);var chain=Promise.resolve();var onData=options.onData||function onData(block,index){blocks[index]=block};var onDownloadProgress=function onDownloadProgress(){};if(options.onProgress){var percent=new Array(count);onDownloadProgress=function onDownloadProgress(blockIndex,progress){percent[blockIndex]=Math.max(progress,percent[blockIndex]||0);options.onProgress(percent.reduce(function(a,b){return a+(b||0)},0)/count*.99)}}var process=function process(blockIndex){return _this10.client.request("files.download-block",{proofId:file.assignedTo,fileId:file.id,block:blockIndex+1},{onDownloadProgress:onDownloadProgress.bind(null,blockIndex)}).then(function(response){return _this10.client.crypto().decryptFileBlock(response.data,_this10.client.session.privateKeyPEM).then(function(blockBase64){return bluffer.createBase64(blockBase64)})})};var index=0;var end=false;function next(){if(end)return;if(index<blocks.length){var blockIndex=index++;var block=process(blockIndex);chain=chain.then(function(){return block.then(function(data){return onData(data,blockIndex,count)})});block.then(next)}else{end=true;resolve(chain.then(complete))}}var complete=function complete(){if(options.onProgress){options.onProgress(100)}if(!options.onData){return bluffer.combine.apply(bluffer,blocks)}return null};while(concurrent--){next()}})};Files.prototype.details=function details(fileId){return this.client.request("files.details",{fileId:fileId}).then(function(response){return(new _File2.default).fromFile(response.data)})};Files.prototype.thumbnail=function thumbnail(fileIdOrThumbnailUrl){var _this11=this;var fileId=fileIdOrThumbnailUrl;var thumbnailUrl=null;if(!(0,_id.isFileId)(fileId)){thumbnailUrl=fileId;var thumbnailUrlFileIdRegex=/\/(F[\w]{15})-thumb/;var fileIdMatch=fileIdOrThumbnailUrl.match(thumbnailUrlFileIdRegex);if(fileIdMatch){fileId=fileIdMatch[1]}else{throw new Error("Malformed/unsupported thumbnail URL. Consider this might be related to the SDK version you are using.")}}return this.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(){return _this11._thumbnail(fileId,thumbnailUrl)})};Files.prototype._thumbnail=function _thumbnail(fileId,thumbnailUrl){var _this12=this;var promise=null;if(thumbnailUrl){var parsedUrl=(0,_parseUrl2.default)(thumbnailUrl);promise=this.client.rawRequest({method:"GET",host:parsedUrl.protocol+"//"+parsedUrl.host,path:parsedUrl.pathname,query:parsedUrl.search,body:null,headers:{}}).then(function(response){return response.body})}else{promise=this.client.request("files.thumbnail",{fileId:fileId}).then(function(response){return response.data})}return promise.then(function(data){return _this12.client.crypto().decryptImage(data,_this12.client.session.privateKeyPEM)}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.thumbnails=function thumbnails(fileIds,_ref10){var _this13=this;var _ref10$async=_ref10.async,async=_ref10$async===undefined?false:_ref10$async,onLoadThumbnail=_ref10.onLoadThumbnail,onLoadThumbnails=_ref10.onLoadThumbnails,_ref10$onLoadThumbnai=_ref10.onLoadThumbnailsThrottleMs,onLoadThumbnailsThrottleMs=_ref10$onLoadThumbnai===undefined?1e3:_ref10$onLoadThumbnai,onLoadError=_ref10.onLoadError;var scheduled=[];var pendingBatch={};var scheduleOnLoadThumbnails=onLoadThumbnails?(0,_throttle2.default)(function(){if(Object.keys(pendingBatch).length){onLoadThumbnails(pendingBatch);pendingBatch={}}},onLoadThumbnailsThrottleMs):function(){};return Promise.all(fileIds.map(function(fileId){return _this13.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(resolve){scheduled.push({fileId:fileId,resolve:resolve})}).then(function(thumbnail){var _ref11;return thumbnail&&(_ref11={},_ref11[fileId]=thumbnail,_ref11)})})).then(function(entries){var more=Promise.all(scheduled.map(function(_ref12){var fileId=_ref12.fileId,resolve=_ref12.resolve;return _this13._thumbnail(fileId).then(function(thumbnail){var _ref13;resolve(thumbnail);if(onLoadThumbnail){var _onLoadThumbnail;onLoadThumbnail((_onLoadThumbnail={},_onLoadThumbnail[fileId]=thumbnail,_onLoadThumbnail))}pendingBatch[fileId]=thumbnail;scheduleOnLoadThumbnails();return _ref13={},_ref13[fileId]=thumbnail,_ref13}).catch(function(err){if(onLoadError){onLoadError(err,fileId)}if(!async){return Promise.reject(err)}return{}})}));if(async){return entries}else{return more.then(function(moreEntries){return[].concat(entries,moreEntries)})}}).then(function(entries){return Object.assign.apply(Object,[{}].concat(entries))})};return Files}(_API3.default);exports.default=Files;
|
package/lib/api/admin/Admin.js
CHANGED
|
@@ -10,6 +10,10 @@ var _Team = require('./Team');
|
|
|
10
10
|
|
|
11
11
|
var _Team2 = _interopRequireDefault(_Team);
|
|
12
12
|
|
|
13
|
+
var _Reports = require('./Reports');
|
|
14
|
+
|
|
15
|
+
var _Reports2 = _interopRequireDefault(_Reports);
|
|
16
|
+
|
|
13
17
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
14
18
|
|
|
15
19
|
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
@@ -26,6 +30,12 @@ var Admin = function (_API) {
|
|
|
26
30
|
_inherits(Admin, _API);
|
|
27
31
|
|
|
28
32
|
/** @private */
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The Admin Team API.
|
|
36
|
+
*
|
|
37
|
+
* @type {Team}
|
|
38
|
+
*/
|
|
29
39
|
function Admin(client) {
|
|
30
40
|
_classCallCheck(this, Admin);
|
|
31
41
|
|
|
@@ -33,12 +43,14 @@ var Admin = function (_API) {
|
|
|
33
43
|
var _this = _possibleConstructorReturn(this, _API.call(this, client));
|
|
34
44
|
|
|
35
45
|
_this.team = new _Team2.default(client);
|
|
46
|
+
_this.reports = new _Reports2.default(client);
|
|
36
47
|
return _this;
|
|
37
48
|
}
|
|
49
|
+
|
|
38
50
|
/**
|
|
39
|
-
* The Admin
|
|
51
|
+
* The Admin Reports API.
|
|
40
52
|
*
|
|
41
|
-
* @type {
|
|
53
|
+
* @type {Reports}
|
|
42
54
|
*/
|
|
43
55
|
|
|
44
56
|
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
exports.__esModule = true;
|
|
4
|
+
|
|
5
|
+
var _API2 = require('../API');
|
|
6
|
+
|
|
7
|
+
var _API3 = _interopRequireDefault(_API2);
|
|
8
|
+
|
|
9
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
10
|
+
|
|
11
|
+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
12
|
+
|
|
13
|
+
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
|
14
|
+
|
|
15
|
+
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* Copyright (C) 2018 PageProof Holdings Limited - All Rights Reserved.
|
|
16
|
+
* Unauthorized copying of this file, via any medium is strictly prohibited.
|
|
17
|
+
* Proprietary and confidential.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
var Reports = function (_API) {
|
|
22
|
+
_inherits(Reports, _API);
|
|
23
|
+
|
|
24
|
+
function Reports() {
|
|
25
|
+
_classCallCheck(this, Reports);
|
|
26
|
+
|
|
27
|
+
return _possibleConstructorReturn(this, _API.apply(this, arguments));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Enqueues a report for creation. Emailed to team admin.
|
|
32
|
+
* @example <caption> Be emailed with proofs approved in the last two weeks.</caption>
|
|
33
|
+
* const admin = await client.admin();
|
|
34
|
+
* const today = new Date();
|
|
35
|
+
* const twoWeeksAgo = new Date().setDate(today.getDate() - 14)
|
|
36
|
+
* const features = admin.reports.create(ReportType.APPROVED_PROOFS, {fromDate: twoWeeksAgo, toDate: today});
|
|
37
|
+
*
|
|
38
|
+
* @since 2.0.0-beta.90
|
|
39
|
+
* @param {ReportType} page The page number
|
|
40
|
+
* @param {object} [options] Any report specific options.
|
|
41
|
+
* @param {Date} options.fromDate The start date (earliest) for the report range. Not required for ReportType.PROOFS_OUT_IN_REVIEW_OVERDUE.
|
|
42
|
+
* @param {Date} options.toDate The start date (earliest) for the report range. Not required for ReportType.PROOFS_OUT_IN_REVIEW_OVERDUE.
|
|
43
|
+
* @returns {Promise}
|
|
44
|
+
*/
|
|
45
|
+
Reports.prototype.create = function create(reportType) {
|
|
46
|
+
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
|
|
47
|
+
_ref$fromDate = _ref.fromDate,
|
|
48
|
+
fromDate = _ref$fromDate === undefined ? null : _ref$fromDate,
|
|
49
|
+
_ref$toDate = _ref.toDate,
|
|
50
|
+
toDate = _ref$toDate === undefined ? null : _ref$toDate;
|
|
51
|
+
|
|
52
|
+
return this.client.request('admin.reports.create', {
|
|
53
|
+
report: reportType,
|
|
54
|
+
fromDate: fromDate && fromDate.toISOString(),
|
|
55
|
+
toDate: fromDate && toDate.toISOString()
|
|
56
|
+
});
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
return Reports;
|
|
60
|
+
}(_API3.default);
|
|
61
|
+
|
|
62
|
+
exports.default = Reports;
|
|
63
|
+
//# sourceMappingURL=Reports.js.map
|
package/lib/api/admin/Team.js
CHANGED
|
@@ -18,6 +18,10 @@ var _TeamFeatures = require('./TeamFeatures');
|
|
|
18
18
|
|
|
19
19
|
var _TeamFeatures2 = _interopRequireDefault(_TeamFeatures);
|
|
20
20
|
|
|
21
|
+
var _TeamCustomWebhooks = require('./TeamCustomWebhooks');
|
|
22
|
+
|
|
23
|
+
var _TeamCustomWebhooks2 = _interopRequireDefault(_TeamCustomWebhooks);
|
|
24
|
+
|
|
21
25
|
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
22
26
|
|
|
23
27
|
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
@@ -37,9 +41,15 @@ var Team = function (_API) {
|
|
|
37
41
|
|
|
38
42
|
|
|
39
43
|
/**
|
|
40
|
-
* The Admin Team
|
|
44
|
+
* The Admin Team Features API.
|
|
41
45
|
*
|
|
42
|
-
* @type {
|
|
46
|
+
* @type {TeamFeatures}
|
|
47
|
+
*/
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* The Admin Team Users API.
|
|
51
|
+
*
|
|
52
|
+
* @type {TeamUsers}
|
|
43
53
|
*/
|
|
44
54
|
function Team(client) {
|
|
45
55
|
_classCallCheck(this, Team);
|
|
@@ -50,19 +60,21 @@ var Team = function (_API) {
|
|
|
50
60
|
_this.users = new _TeamUsers2.default(client);
|
|
51
61
|
_this.dashboard = new _TeamDashboard2.default(client);
|
|
52
62
|
_this.features = new _TeamFeatures2.default(client);
|
|
63
|
+
_this.customWebhooks = new _TeamCustomWebhooks2.default(client);
|
|
53
64
|
return _this;
|
|
54
65
|
}
|
|
55
66
|
|
|
56
67
|
/**
|
|
57
|
-
* The Admin
|
|
68
|
+
* The Admin Custom Webhooks API.
|
|
58
69
|
*
|
|
59
|
-
* @type {
|
|
70
|
+
* @type {TeamCustomWebhooks}
|
|
60
71
|
*/
|
|
61
72
|
|
|
73
|
+
|
|
62
74
|
/**
|
|
63
|
-
* The Admin Team
|
|
75
|
+
* The Admin Team Dashboard API.
|
|
64
76
|
*
|
|
65
|
-
* @type {
|
|
77
|
+
* @type {TeamDashboard}
|
|
66
78
|
*/
|
|
67
79
|
|
|
68
80
|
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
exports.__esModule = true;
|
|
4
|
+
|
|
5
|
+
var _API2 = require('../API');
|
|
6
|
+
|
|
7
|
+
var _API3 = _interopRequireDefault(_API2);
|
|
8
|
+
|
|
9
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
10
|
+
|
|
11
|
+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
12
|
+
|
|
13
|
+
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
|
|
14
|
+
|
|
15
|
+
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* Copyright (C) 2018 PageProof Holdings Limited - All Rights Reserved.
|
|
16
|
+
* Unauthorized copying of this file, via any medium is strictly prohibited.
|
|
17
|
+
* Proprietary and confidential.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
var TeamCustomWebhooks = function (_API) {
|
|
22
|
+
_inherits(TeamCustomWebhooks, _API);
|
|
23
|
+
|
|
24
|
+
function TeamCustomWebhooks() {
|
|
25
|
+
_classCallCheck(this, TeamCustomWebhooks);
|
|
26
|
+
|
|
27
|
+
return _possibleConstructorReturn(this, _API.apply(this, arguments));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Creates/registers a new custom webhook.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* const admin = await client.admin();
|
|
35
|
+
* await admin.team.customWebhooks.create('proof_started', 'https://example.com/webhook');
|
|
36
|
+
*
|
|
37
|
+
* @since v2.0.0-beta.90
|
|
38
|
+
* @returns {Promise<TeamFeatures>}
|
|
39
|
+
*/
|
|
40
|
+
TeamCustomWebhooks.prototype.create = function create(eventName, webhookUrl) {
|
|
41
|
+
return this.client.request('admin.team.custom-webhooks.create', {
|
|
42
|
+
event: eventName,
|
|
43
|
+
url: webhookUrl
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
return TeamCustomWebhooks;
|
|
48
|
+
}(_API3.default);
|
|
49
|
+
|
|
50
|
+
exports.default = TeamCustomWebhooks;
|
|
51
|
+
//# sourceMappingURL=TeamCustomWebhooks.js.map
|
package/lib/core/PageProof.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _AdapterRepository=require("./AdapterRepository");var _AdapterRepository2=_interopRequireDefault(_AdapterRepository);var _Cache=require("./Cache");var _Cache2=_interopRequireDefault(_Cache);var _Request=require("../network/Request");var _Request2=_interopRequireDefault(_Request);var _Response=require("../network/Response");var _Response2=_interopRequireDefault(_Response);var _Accounts=require("../api/Accounts");var _Accounts2=_interopRequireDefault(_Accounts);var _Dashboard=require("../api/Dashboard");var _Dashboard2=_interopRequireDefault(_Dashboard);var _Users=require("../api/Users");var _Users2=_interopRequireDefault(_Users);var _Proofs=require("../api/Proofs");var _Proofs2=_interopRequireDefault(_Proofs);var _Briefs=require("../api/Briefs");var _Briefs2=_interopRequireDefault(_Briefs);var _Files=require("../api/Files");var _Files2=_interopRequireDefault(_Files);var _Admin=require("../api/admin/Admin");var _Admin2=_interopRequireDefault(_Admin);var _Workflows=require("../api/Workflows");var _Workflows2=_interopRequireDefault(_Workflows);var _Preferences=require("../api/Preferences");var _Preferences2=_interopRequireDefault(_Preferences);var _Comments=require("../api/Comments");var _Comments2=_interopRequireDefault(_Comments);var _Profile=require("../api/Profile");var _Profile2=_interopRequireDefault(_Profile);var _Sessions=require("../api/Sessions");var _Sessions2=_interopRequireDefault(_Sessions);var _Encryption=require("../api/Encryption");var _Encryption2=_interopRequireDefault(_Encryption);var _Live=require("../api/Live");var _Live2=_interopRequireDefault(_Live);var _Brian=require("../api/brian/Brian");var _Brian2=_interopRequireDefault(_Brian);var _Session=require("../models/Session");var _Session2=_interopRequireDefault(_Session);var _EventEmitter=require("../events/EventEmitter");var _EventEmitter2=_interopRequireDefault(_EventEmitter);var _ResponseStatus=require("../enum/ResponseStatus");var _ResponseStatus2=_interopRequireDefault(_ResponseStatus);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);var _constants=require("../util/constants");var _getTimezone=require("../util/getTimezone");var _getTimezone2=_interopRequireDefault(_getTimezone);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var debug=require("debug")("PageProof");var PageProof=function(){function PageProof(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref$options=_ref.options,options=_ref$options===undefined?{}:_ref$options,_ref$adapters=_ref.adapters,adapters=_ref$adapters===undefined?[]:_ref$adapters;_classCallCheck(this,PageProof);this.options=options;this.events=new _EventEmitter2.default;this.adapters=new _AdapterRepository2.default(adapters);this.cache=new _Cache2.default(this);this.accounts=new _Accounts2.default(this);this.comments=new _Comments2.default(this);this.dashboard=new _Dashboard2.default(this);this.files=new _Files2.default(this);this.profile=new _Profile2.default(this);this.proofs=new _Proofs2.default(this);this.briefs=new _Briefs2.default(this);this.users=new _Users2.default(this);this.workflows=new _Workflows2.default(this);this.preferences=new _Preferences2.default(this);this.sessions=new _Sessions2.default(this);this.encryption=new _Encryption2.default(this);this.live=new _Live2.default(this);this._init();this._registerCoreHooks();this._enhance()}PageProof.prototype._init=function _init(){var requestAdapter=this.adapters.getRequestAdapter();if(!this.options.endpoint){this.options.endpoint=requestAdapter.options.endpoint}if(!this.options.applicationId){this.options.applicationId=requestAdapter.options.applicationId}if(!this.options.subscriptionKey){this.options.subscriptionKey=requestAdapter.options.key||this.options.key}if(this.options.subscriptionKey&&!this.options.applicationId){throw new Error("You must provide an applicationId.")}};PageProof.prototype._registerCoreHooks=function _registerCoreHooks(){this.on("error.throttled",function(event){var ms=event.data.response.data.timeout;debug("Sleeping "+ms+"ms until rate limit resets");return(0,_sleep2.default)(ms)})};PageProof.prototype._enhance=function _enhance(){var _this=this;var adapters=this.adapters.getEnhancementAdapters();adapters.forEach(function(adapter){return adapter.onClientReady(_this)})};PageProof.prototype.setSession=function setSession(session){if(session&&!(session instanceof _Session2.default)){this.session=(new _Session2.default).fromJSON(session)}else{this.session=session||null}return this.session};PageProof.prototype.rawRequest=function rawRequest(_ref2,options){var method=_ref2.method,host=_ref2.host,path=_ref2.path,query=_ref2.query,body=_ref2.body,headers=_ref2.headers;var adapter=this.adapters.getRequestAdapter();return adapter.send({host:host,method:method,path:path,query:query,body:body,headers:headers,credentials:false},options)};PageProof.prototype.getRequestLocalEncodedMetadata=function getRequestLocalEncodedMetadata(){return[(0,_getTimezone2.default)()].map(function(value){return value!==null&&value!==undefined?encodeURIComponent(value):"#"}).join(":")};PageProof.prototype.request=function request(name,params,options){var _this2=this;var request=new _Request2.default(this.options.endpoint,name,params);var adapter=this.adapters.getRequestAdapter();var start=Promise.resolve();if(!request.endpoint.anonymous){if(!this.session){return Promise.reject(new Error("Cannot make call to endpoint ("+name+") when unauthorized."))}var crypto=this.adapters.getCryptoAdapter();start=crypto.generateAuthorizationHeaders(request.getMethod(),request.getPath(),this.session).then(function(headers){return request.addHeaders(headers)})}if(this.options.applicationId){request.addHeader(_constants.DEVICE_ID_HEADER,this.options.applicationId)}if(this.options.subscriptionKey){request.addHeader(_constants.SUBSCRIPTION_KEY_HEADER,this.options.subscriptionKey)}var localEncodedMetadata=this.getRequestLocalEncodedMetadata();if(localEncodedMetadata){request.addHeader(_constants.LOCAL_ENCODED_METADATA_HEADER,localEncodedMetadata)}var meta={request:request};return start.then(function(){var data=request.build();return _this2.events.emit("experimental.request.before",meta,true).then(function(){return data})}).then(function(data){return adapter.send(data,options)}).then(_Response2.default.parse).then(function(response){meta.response=response;_this2.events.emit("experimental.request.after",meta);if(response.code===_ResponseStatus2.default.ERROR_THROTTLED){var handlers=_this2.events.emit("error.throttled",meta);if(handlers.some(Boolean)){return Promise.all(handlers).then(function(){_this2.events.emit("experimental.request.retry",meta);return _this2.request(name,params,options)})}}if(response.code===_ResponseStatus2.default.ERROR_UNAUTHORISED){var sessionToken=_this2.session?_this2.session.token:null;return _this2.events.emit("error.unauthorized",meta,true).then(function(){if(_this2.session&&_this2.session.token!==sessionToken){return _this2.request(name,params,options)}return response})}if(response.deprecated){var message="The "+name+" API has been deprecated. "+(response.deprecated||"");_this2.events.emit("error.deprecated",{name:name,message:message})}return response}).then(function(response){try{if(response.error){_this2.events.emit("error.response",meta);var err=new Error(
|
|
1
|
+
"use strict";exports.__esModule=true;var _AdapterRepository=require("./AdapterRepository");var _AdapterRepository2=_interopRequireDefault(_AdapterRepository);var _Cache=require("./Cache");var _Cache2=_interopRequireDefault(_Cache);var _Request=require("../network/Request");var _Request2=_interopRequireDefault(_Request);var _Response=require("../network/Response");var _Response2=_interopRequireDefault(_Response);var _Accounts=require("../api/Accounts");var _Accounts2=_interopRequireDefault(_Accounts);var _Dashboard=require("../api/Dashboard");var _Dashboard2=_interopRequireDefault(_Dashboard);var _Users=require("../api/Users");var _Users2=_interopRequireDefault(_Users);var _Proofs=require("../api/Proofs");var _Proofs2=_interopRequireDefault(_Proofs);var _Briefs=require("../api/Briefs");var _Briefs2=_interopRequireDefault(_Briefs);var _Files=require("../api/Files");var _Files2=_interopRequireDefault(_Files);var _Admin=require("../api/admin/Admin");var _Admin2=_interopRequireDefault(_Admin);var _Workflows=require("../api/Workflows");var _Workflows2=_interopRequireDefault(_Workflows);var _Preferences=require("../api/Preferences");var _Preferences2=_interopRequireDefault(_Preferences);var _Comments=require("../api/Comments");var _Comments2=_interopRequireDefault(_Comments);var _Profile=require("../api/Profile");var _Profile2=_interopRequireDefault(_Profile);var _Sessions=require("../api/Sessions");var _Sessions2=_interopRequireDefault(_Sessions);var _Encryption=require("../api/Encryption");var _Encryption2=_interopRequireDefault(_Encryption);var _Live=require("../api/Live");var _Live2=_interopRequireDefault(_Live);var _Brian=require("../api/brian/Brian");var _Brian2=_interopRequireDefault(_Brian);var _Session=require("../models/Session");var _Session2=_interopRequireDefault(_Session);var _EventEmitter=require("../events/EventEmitter");var _EventEmitter2=_interopRequireDefault(_EventEmitter);var _ResponseStatus=require("../enum/ResponseStatus");var _ResponseStatus2=_interopRequireDefault(_ResponseStatus);var _sleep=require("../util/sleep");var _sleep2=_interopRequireDefault(_sleep);var _constants=require("../util/constants");var _getTimezone=require("../util/getTimezone");var _getTimezone2=_interopRequireDefault(_getTimezone);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var debug=require("debug")("PageProof");var PageProof=function(){function PageProof(){var _ref=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{},_ref$options=_ref.options,options=_ref$options===undefined?{}:_ref$options,_ref$adapters=_ref.adapters,adapters=_ref$adapters===undefined?[]:_ref$adapters;_classCallCheck(this,PageProof);this.options=options;this.events=new _EventEmitter2.default;this.adapters=new _AdapterRepository2.default(adapters);this.cache=new _Cache2.default(this);this.accounts=new _Accounts2.default(this);this.comments=new _Comments2.default(this);this.dashboard=new _Dashboard2.default(this);this.files=new _Files2.default(this);this.profile=new _Profile2.default(this);this.proofs=new _Proofs2.default(this);this.briefs=new _Briefs2.default(this);this.users=new _Users2.default(this);this.workflows=new _Workflows2.default(this);this.preferences=new _Preferences2.default(this);this.sessions=new _Sessions2.default(this);this.encryption=new _Encryption2.default(this);this.live=new _Live2.default(this);this._init();this._registerCoreHooks();this._enhance()}PageProof.prototype._init=function _init(){var requestAdapter=this.adapters.getRequestAdapter();if(!this.options.endpoint){this.options.endpoint=requestAdapter.options.endpoint}if(!this.options.applicationId){this.options.applicationId=requestAdapter.options.applicationId}if(!this.options.subscriptionKey){this.options.subscriptionKey=requestAdapter.options.key||this.options.key}if(this.options.subscriptionKey&&!this.options.applicationId){throw new Error("You must provide an applicationId.")}};PageProof.prototype._registerCoreHooks=function _registerCoreHooks(){this.on("error.throttled",function(event){var ms=event.data.response.data.timeout;debug("Sleeping "+ms+"ms until rate limit resets");return(0,_sleep2.default)(ms)})};PageProof.prototype._enhance=function _enhance(){var _this=this;var adapters=this.adapters.getEnhancementAdapters();adapters.forEach(function(adapter){return adapter.onClientReady(_this)})};PageProof.prototype.setSession=function setSession(session){if(session&&!(session instanceof _Session2.default)){this.session=(new _Session2.default).fromJSON(session)}else{this.session=session||null}return this.session};PageProof.prototype.rawRequest=function rawRequest(_ref2,options){var method=_ref2.method,host=_ref2.host,path=_ref2.path,query=_ref2.query,body=_ref2.body,headers=_ref2.headers;var adapter=this.adapters.getRequestAdapter();return adapter.send({host:host,method:method,path:path,query:query,body:body,headers:headers,credentials:false},options)};PageProof.prototype.getRequestLocalEncodedMetadata=function getRequestLocalEncodedMetadata(){return[(0,_getTimezone2.default)()].map(function(value){return value!==null&&value!==undefined?encodeURIComponent(value):"#"}).join(":")};PageProof.prototype.request=function request(name,params,options){var _this2=this;var request=new _Request2.default(this.options.endpoint,name,params);var adapter=this.adapters.getRequestAdapter();var start=Promise.resolve();if(!request.endpoint.anonymous){if(!this.session){return Promise.reject(new Error("Cannot make call to endpoint ("+name+") when unauthorized."))}var crypto=this.adapters.getCryptoAdapter();start=crypto.generateAuthorizationHeaders(request.getMethod(),request.getPath(),this.session).then(function(headers){return request.addHeaders(headers)})}if(this.options.applicationId){request.addHeader(_constants.DEVICE_ID_HEADER,this.options.applicationId)}if(this.options.subscriptionKey){request.addHeader(_constants.SUBSCRIPTION_KEY_HEADER,this.options.subscriptionKey)}var localEncodedMetadata=this.getRequestLocalEncodedMetadata();if(localEncodedMetadata){request.addHeader(_constants.LOCAL_ENCODED_METADATA_HEADER,localEncodedMetadata)}var meta={request:request};return start.then(function(){var data=request.build();return _this2.events.emit("experimental.request.before",meta,true).then(function(){return data})}).then(function(data){return adapter.send(data,options)}).then(_Response2.default.parse).then(function(response){meta.response=response;_this2.events.emit("experimental.request.after",meta);if(response.code===_ResponseStatus2.default.ERROR_THROTTLED){var handlers=_this2.events.emit("error.throttled",meta);if(handlers.some(Boolean)){return Promise.all(handlers).then(function(){_this2.events.emit("experimental.request.retry",meta);return _this2.request(name,params,options)})}}if(response.code===_ResponseStatus2.default.ERROR_UNAUTHORISED){var sessionToken=_this2.session?_this2.session.token:null;return _this2.events.emit("error.unauthorized",meta,true).then(function(){if(_this2.session&&_this2.session.token!==sessionToken){return _this2.request(name,params,options)}return response})}if(response.deprecated){var message="The "+name+" API has been deprecated. "+(response.deprecated||"");_this2.events.emit("error.deprecated",{name:name,message:message})}return response}).then(function(response){try{if(response.error){_this2.events.emit("error.response",meta);var err=new Error(response.message+" ["+name+"]");err.response=response;err.request=request;return Promise.reject(err)}else{_this2.events.emit("experimental.request.resolve",meta);return Promise.resolve(response)}}finally{_this2.events.emit("experimental.request.finally",meta)}})};PageProof.prototype.admin=function admin(){if(!this.session){return Promise.reject(new Error("You must be logged in to use the Admin API."))}if(!this.session.user.isAdmin){return Promise.reject(new Error("The current user must be an administrator of a team or enterprise account."))}if(!this._admin){this._admin=Promise.resolve(new _Admin2.default(this))}return this._admin};PageProof.prototype.brian=function brian(){if(!this.session||this.session.userId!==_constants.BRIAN_USER_ID){return Promise.reject(new Error("You do not have permission to use this API."))}if(!this._brian){this._brian=Promise.resolve(new _Brian2.default(this))}return this._brian};PageProof.prototype.crypto=function crypto(){return this.adapters.getCryptoAdapter()};PageProof.prototype.on=function on(event,handler){return this.events.on(event,handler)};return PageProof}();exports.default=PageProof;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.__esModule=true;var ReportType={APPROVED_PROOFS:"ApprovedProofs",PROOFS_OUT_IN_REVIEW:"ProofsOutInReview",PROOFS_OUT_IN_REVIEW_OVERDUE:"ProofsOutInReviewOverdue"};exports.default=ReportType;
|
package/lib/network/Response.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _ResponseStatus=require("../enum/ResponseStatus");var _ResponseStatus2=_interopRequireDefault(_ResponseStatus);var _statusCodes=require("../util/statusCodes");var _constants=require("../util/constants");var _hasOwnProperty=require("../util/hasOwnProperty");var _hasOwnProperty2=_interopRequireDefault(_hasOwnProperty);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Response=function(){function Response(){_classCallCheck(this,Response);this.error=false;this.code=-1;this.data=null;this.message=null;this.deprecated=null}Response.parse=function parse(_ref){var status=_ref.status,_ref$headers=_ref.headers,headers=_ref$headers===undefined?{}:_ref$headers,body=_ref.body;var response=new Response;if(status===_statusCodes.TOO_MANY_REQUESTS_STATUS){response.error=true;response.message="
|
|
1
|
+
"use strict";exports.__esModule=true;var _ResponseStatus=require("../enum/ResponseStatus");var _ResponseStatus2=_interopRequireDefault(_ResponseStatus);var _statusCodes=require("../util/statusCodes");var _constants=require("../util/constants");var _hasOwnProperty=require("../util/hasOwnProperty");var _hasOwnProperty2=_interopRequireDefault(_hasOwnProperty);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function")}}var Response=function(){function Response(){_classCallCheck(this,Response);this.error=false;this.code=-1;this.data=null;this.message=null;this.deprecated=null}Response.parse=function parse(_ref){var status=_ref.status,_ref$headers=_ref.headers,headers=_ref$headers===undefined?{}:_ref$headers,body=_ref.body;var response=new Response;if(status===_statusCodes.TOO_MANY_REQUESTS_STATUS){response.error=true;response.message="Too many requests. Unable to process request due to high volume of requests from your application.";response.code=_ResponseStatus2.default.ERROR_THROTTLED;response.data={timeout:(parseFloat(headers[_constants.RETRY_AFTER_HEADER])||60)*1e3};return response}if((0,_hasOwnProperty2.default)(headers,"deprecated")){response.deprecated=headers.deprecated}if(status===_statusCodes.OK_STATUS&&!body){response.code=_ResponseStatus2.default.OK;return response}try{var json=JSON.parse(body);if(typeof json==="string"){}else if(json&&"ResponseCode"in json){response.code=json.ResponseCode;if(response.code!==_ResponseStatus2.default.OK){response.error=true}}else if(json.Message&&Object.keys(json).length===1){response.error=true;response.code=_ResponseStatus2.default.ERROR_CRITICAL}else if(typeof json.success==="boolean"&&json.message){response.error=json.success===false;response.code=status;response.message=json.message}if(response.error){response.message=response.message||"Response returned with the response code: "+response.code+". Please check SDK error documentation for details."}response.data=json}catch(err){response.error=true}return response};return Response}();exports.default=Response;
|
|
@@ -29,12 +29,24 @@
|
|
|
29
29
|
"body": ["email"],
|
|
30
30
|
"anonymous": true
|
|
31
31
|
},
|
|
32
|
+
"accounts.set-password-request": {
|
|
33
|
+
"method": "POST",
|
|
34
|
+
"path": "/api/users/setpasswordrequest",
|
|
35
|
+
"body": ["email"],
|
|
36
|
+
"anonymous": true
|
|
37
|
+
},
|
|
32
38
|
"accounts.reset-password": {
|
|
33
39
|
"method": "POST",
|
|
34
40
|
"path": "/api/users/resetpassword",
|
|
35
41
|
"body": ["email", "secret", "newPassword", "newPrivateKey", "newPublicKey"],
|
|
36
42
|
"anonymous": true
|
|
37
43
|
},
|
|
44
|
+
"accounts.set-password": {
|
|
45
|
+
"method": "POST",
|
|
46
|
+
"path": "/api/users/setpassword",
|
|
47
|
+
"body": ["email", "secret", "newPassword", "newPrivateKey", "newPublicKey"],
|
|
48
|
+
"anonymous": true
|
|
49
|
+
},
|
|
38
50
|
"accounts.logout": {
|
|
39
51
|
"method": "GET",
|
|
40
52
|
"path": "/api/users/logout"
|
|
@@ -137,6 +149,11 @@
|
|
|
137
149
|
"path": "/api/admin/search",
|
|
138
150
|
"body": ["query", "all", "filterBy", "page"]
|
|
139
151
|
},
|
|
152
|
+
"admin.team.custom-webhooks.create": {
|
|
153
|
+
"method": "POST",
|
|
154
|
+
"path": "/api/admin/teams/custom-webhooks/create",
|
|
155
|
+
"body": ["event", "url"]
|
|
156
|
+
},
|
|
140
157
|
"users.by-id": {
|
|
141
158
|
"method": "GET",
|
|
142
159
|
"path": "/api/users",
|
|
@@ -640,5 +657,11 @@
|
|
|
640
657
|
"version": 2,
|
|
641
658
|
"method": "GET",
|
|
642
659
|
"path": "/api/users/live/token"
|
|
660
|
+
},
|
|
661
|
+
"admin.reports.create": {
|
|
662
|
+
"version": 2,
|
|
663
|
+
"method": "POST",
|
|
664
|
+
"path": "/api/reports",
|
|
665
|
+
"body": ["report", "fromDate", "toDate"]
|
|
643
666
|
}
|
|
644
667
|
}
|