@pageproof/sdk-pr 408.0.1642468607140 → 409.0.1642470099460
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 +119 -1
- package/README.md +1 -0
- package/lib/api/Accounts.d.ts +9 -1
- package/lib/api/Accounts.js +1 -1
- package/lib/api/AccountsMFA.d.ts +28 -0
- package/lib/api/AccountsMFA.js +1 -0
- package/lib/api/Comments.d.ts +73 -24
- package/lib/api/Comments.js +1 -1
- package/lib/api/Files.d.ts +13 -0
- package/lib/api/Files.js +1 -1
- package/lib/api/Workflows.d.ts +20 -0
- package/lib/api/Workflows.js +1 -1
- package/lib/api/admin/TeamFeatures.d.ts +2 -6
- package/lib/api/admin/TeamFeatures.js +2 -8
- package/lib/models/Comment.d.ts +33 -4
- package/lib/models/Comment.js +1 -1
- package/lib/models/User.d.ts +6 -0
- package/lib/models/User.js +1 -1
- package/lib/models/Workflow.d.ts +6 -0
- package/lib/models/Workflow.js +1 -1
- package/lib/models/index.d.ts +1 -2
- package/lib/models/index.js +1 -1
- package/lib/network/endpoints.json +31 -1
- package/lib/pageproof.js +1 -1
- package/lib/types/FileV2.d.ts +62 -0
- package/lib/types/FileV2.js +1 -0
- package/lib/types/Pin.d.ts +33 -0
- package/lib/types/Pin.js +1 -0
- package/lib/util/exports.d.ts +6 -0
- package/lib/util/exports.js +1 -1
- package/lib/util/pins/parsePins.d.ts +1 -0
- package/lib/util/pins/parsePins.js +78 -0
- package/lib/util/pins/serializePins.d.ts +1 -0
- package/lib/util/pins/serializePins.js +51 -0
- package/lib/util/pins/utils.d.ts +3 -0
- package/lib/util/pins/utils.js +18 -0
- package/package.json +1 -1
- package/lib/models/Pin.d.ts +0 -43
- package/lib/models/Pin.js +0 -1
- package/lib/models/PinFill.d.ts +0 -16
- package/lib/models/PinFill.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,17 +1,135 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.0.0-beta.284
|
|
4
|
+
|
|
5
|
+
Released on the 23rd of December 2021.
|
|
6
|
+
|
|
7
|
+
This release introduces support for comments with multiple pins. This means it's now possible to create a comment that has more than one pin (previously the limit). Because of this, we've made some changes that you'll want to know about, to ensure your transition to this version (and subsequent versions) are as seamless as possible.
|
|
8
|
+
|
|
9
|
+
We've removed the following things:
|
|
10
|
+
- The `Pin` and `PinFill` models have been removed. The objects you get by accessing pin fields now return a plain JavaScript object instead of an instance of the `Pin` class. The fields on this object are no different than before - but if you were previously checking the prototype of these objects, these checks will now produce a false-negative.
|
|
11
|
+
|
|
12
|
+
We're pretty confident that this change should have little to no impact on your integration with PageProof. And if you currently use the SDK sidecar, absolutely no impact whatsoever. This is highly edge-case.
|
|
13
|
+
|
|
14
|
+
We've deprecated a few model properties:
|
|
15
|
+
- The `Comment` model
|
|
16
|
+
- The `pin` property has been replaced by the new `pins` property. This property is an array of pins attached to the comment. As mentioned above, the objects you get from this array is a plain JavaScript object - but contains all the same properties. Accessing the deprecated `pin` property will yield the first pin attached to the comment - for backwards compatibility reasons only. The `pin` property will be removed in a later release.
|
|
17
|
+
|
|
18
|
+
> Change any code like `comment.pin` to `comment.pins[0]`. Ideally, also change your code to have support for multiple pins (this change may be more complex than the example).
|
|
19
|
+
- The `mediaTime` property has been replaced by the `time` property on the pin object. This change means it's possible for video and auto proofs to have pins added at different times along the timeline. This is not currently something we support in PageProof, but is making way for that functionality to be implemented in the future. Accessing the deprecated `mediaTime` property will yield the first pin's time - for backwards compatibility reasons only. The `mediaTime` property will be removed in a later release.
|
|
20
|
+
|
|
21
|
+
> Change any code like `comment.mediaTime` to `comment.pins[0].time`. And again, ideally you'd also want to change your code to have support for multiple pins.
|
|
22
|
+
- The `mediaDuration` property has been replaced by the `duration` property on the pin object. This change has been made for the same reasons as the change to the `mediaTime` property (above). Accessing the deprecated `mediaDuration` property will yield the first pin's duration - for backwards compatibility reasons only. The `mediaDuration` property will be removed in a later release.
|
|
23
|
+
|
|
24
|
+
> Change any code like `comment.mediaDuration` to `comment.pins[0].duration`. And again, ideally you'd also want to change your code to have support for multiple pins.
|
|
25
|
+
|
|
26
|
+
We've deprecated a few API options:
|
|
27
|
+
- The `Comments.create()` method
|
|
28
|
+
- The `pin` option has been replaced by the new `pins` option. This property is array of pins to attach to the comment. Providing this option behaves exactly as it did in earlier versions of the SDK, but it is recommended you switch to using the `pins` option, as we plan on removing the `pin` option in the future.
|
|
29
|
+
- The `mediaTime` option has been replaced by the `time` property on the pin object(s). Providing this option automatically assigns the first pin with the `time` property - but we recommend that you switch to manually specifying the `time` property, as we plan on removing the `mediaTime` option in the future.
|
|
30
|
+
- The `mediaDuration` option has been replaced by the `duration` property on the pin object(s). Providing this option automatically assigns the first pin with the `duration` property - but we recommend that you switch to manually specifying the `duration` property, as we plan on removing the `mediaDuration` option in the future.
|
|
31
|
+
|
|
32
|
+
### TL;DR
|
|
33
|
+
|
|
34
|
+
Here are a couple of code snippets of code that you may have in your PageProof integration code. If you're in a rush - here's a quick example of the changes you'll want to make.
|
|
35
|
+
|
|
36
|
+
**Creating comments**
|
|
37
|
+
|
|
38
|
+
Before (deprecated):
|
|
39
|
+
```js
|
|
40
|
+
await client.comments.create({
|
|
41
|
+
proofId: 'PR4G1XDX6W4QC579',
|
|
42
|
+
raw: 'Hello World',
|
|
43
|
+
pin: {
|
|
44
|
+
x: 0.024566473,
|
|
45
|
+
y: 0.756634520,
|
|
46
|
+
},
|
|
47
|
+
mediaTime: 17.3605,
|
|
48
|
+
mediaDuration: 1.5,
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
After (recommended, and the way forward):
|
|
53
|
+
```js
|
|
54
|
+
await client.comments.create({
|
|
55
|
+
proofId: 'PR4G1XDX6W4QC579',
|
|
56
|
+
raw: 'Hello World',
|
|
57
|
+
pins: [
|
|
58
|
+
{
|
|
59
|
+
x: 0.024566473,
|
|
60
|
+
y: 0.756634520,
|
|
61
|
+
time: 17.3605,
|
|
62
|
+
duration: 1.5,
|
|
63
|
+
},
|
|
64
|
+
],
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Loading & accessing comment/pin info**
|
|
69
|
+
|
|
70
|
+
Before (deprecated):
|
|
71
|
+
```js
|
|
72
|
+
const comments = await client.comments.load('PR4G1XDX6W4QC579');
|
|
73
|
+
comments[0].pin.x === 0.024566473;
|
|
74
|
+
comments[0].pin.y === 0.756634520;
|
|
75
|
+
comments[0].mediaTime === 17.3605;
|
|
76
|
+
comments[0].mediaDuration === 1.5;
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
After (recommended, and the way forward):
|
|
80
|
+
```js
|
|
81
|
+
const comments = await client.comments.load('PR4G1XDX6W4QC579');
|
|
82
|
+
comments[0].pins[0].x === 0.024566473;
|
|
83
|
+
comments[0].pins[0].y === 0.756634520;
|
|
84
|
+
comments[0].pins[0].time === 17.3605;
|
|
85
|
+
comments[0].pins[0].duration === 1.5;
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## 2.0.0-beta.283
|
|
89
|
+
|
|
90
|
+
Released on the 21th of December 2021.
|
|
91
|
+
|
|
92
|
+
- [[PP-1689](https://goto.pageproof.dev/PP-1689)] Added support for MFA (multi-factor authenticator). See [Accounts.login](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Accounts.js~Accounts.html#instance-method-login).
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
## 2.0.0-beta.282
|
|
96
|
+
|
|
97
|
+
Released on the 20th of December 2021.
|
|
98
|
+
|
|
99
|
+
- [[PP-1654](https://goto.pageproof.dev/PP-1654)] Added support enterprise teams to specify a custom email address for all of their emails to be sent from (requires SPF verification). See [TeamFeatures.setSenderEmail](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/admin/TeamFeatures.js~TeamFeatures.html#instance-method-setSenderEmail).
|
|
100
|
+
|
|
101
|
+
## 2.0.0-beta.281
|
|
102
|
+
|
|
103
|
+
Released on the 17th of December 2021.
|
|
104
|
+
|
|
105
|
+
- [[PP-1536](https://pageproof.atlassian.net/browse/PP-1536)] Added support for duplicating files. See [Files.duplicate](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Files.js~Files.html#instance-method-duplicate).
|
|
106
|
+
|
|
107
|
+
## 2.0.0-beta.280
|
|
108
|
+
|
|
109
|
+
Released on the 10th of December 2021.
|
|
110
|
+
|
|
111
|
+
- [[PP-1642](https://pageproof.atlassian.net/browse/PP-1642)] Added support for favoriting workflow templates. See [Workflow.isFavorite](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/models/Workflow.js~Workflow.html#instance-member-isFavorite), [Workflows.favorite](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Workflows.js~Workflows.html#instance-method-favorite), and [Workflows.unfavorite](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Workflows.js~Workflows.html#instance-method-unfavorite).
|
|
112
|
+
|
|
113
|
+
## 2.0.0-beta.279
|
|
114
|
+
|
|
115
|
+
Released on the 10th of December 2021.
|
|
116
|
+
|
|
117
|
+
_This version does not contain any new features._
|
|
118
|
+
|
|
3
119
|
## 2.0.0-beta.278
|
|
4
120
|
|
|
5
121
|
Released on the 7th of December 2021.
|
|
6
122
|
|
|
7
123
|
- [[PP-1641](https://pageproof.atlassian.net/browse/PP-1641)] Add the `decisionDate` field to the WorkflowUser model. See [WorkflowUser.decisionDate](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/models/WorkflowUser.js~WorkflowUser.html#instance-member-decisionDate).
|
|
8
124
|
|
|
9
|
-
## 2.0.0-beta.
|
|
125
|
+
## 2.0.0-beta.277
|
|
10
126
|
|
|
11
127
|
Released on the 28th of October 2021.
|
|
12
128
|
|
|
13
129
|
- [[PP-1515](https://pageproof.atlassian.net/browse/PP-1515)] Added support for retrieving multiple comment attachments. See [Comments.load](https://docs.pageproof.tech/@pageproof/sdk/beta/class/src/api/Comments.js~Comments.html#instance-method-load).
|
|
14
130
|
|
|
131
|
+
Note: This version was mistakenly released as `2.0.0-beta.277` instead of `2.0.0-beta.177`.
|
|
132
|
+
|
|
15
133
|
## 2.0.0-beta.176
|
|
16
134
|
|
|
17
135
|
Released on the 27th of September 2021.
|
package/README.md
CHANGED
|
@@ -286,6 +286,7 @@ Name | Namespace | Description | Admin-only | Stability
|
|
|
286
286
|
--- | --- | --- | --- | ---
|
|
287
287
|
[Accounts API](./class/src/api/Accounts.js~Accounts.html) | `accounts` | Used to create accounts, activate and login. | No | Stable
|
|
288
288
|
[Accounts SSO API](./class/src/api/AccountsSSO.js~AccountsSSO.html) | `accounts.sso` | Used to login using a SSO provider. | No | Experimental
|
|
289
|
+
[Accounts MFA API](./class/src/api/AccountsMFA.js~AccountsMFA.html) | `accounts.mfa` | Used to activate, de-activate and enable user mfa login. | No | experimental
|
|
289
290
|
[Comments API](./class/src/api/Comments.js~Comments.html) | `comments` | Used to load comments. | No | Stable
|
|
290
291
|
[Dashboard API](./class/src/api/Dashboard.js~Dashboard.html) | `dashboard` | Used to load the authenticated user's dashboard & search for/filter proofs. | No | Stable
|
|
291
292
|
[Dashboard Groups API](./class/src/api/DashboardGroups.js~DashboardGroups.html) | `dashboard.groups` | Used to load proof groups | No | Experimental
|
package/lib/api/Accounts.d.ts
CHANGED
|
@@ -8,6 +8,12 @@ declare class Accounts extends API {
|
|
|
8
8
|
* @type {AccountsSSO}
|
|
9
9
|
*/
|
|
10
10
|
sso: AccountsSSO;
|
|
11
|
+
/**
|
|
12
|
+
* The Accounts MFA API.
|
|
13
|
+
*
|
|
14
|
+
* @type {AccountsMFA}
|
|
15
|
+
*/
|
|
16
|
+
mfa: AccountsMFA;
|
|
11
17
|
/** @private */
|
|
12
18
|
_generateCredentials(password: any): any;
|
|
13
19
|
/**
|
|
@@ -101,9 +107,10 @@ declare class Accounts extends API {
|
|
|
101
107
|
*
|
|
102
108
|
* @param {string} email The user's email address
|
|
103
109
|
* @param {string} password The user's secure password
|
|
110
|
+
* @param {string} [totp] The user's timed one time passcode produced from their authenticator app
|
|
104
111
|
* @returns {Promise<Session>}
|
|
105
112
|
*/
|
|
106
|
-
login(email: string, password: string, _decryptPrivateKey?: boolean): Promise<Session>;
|
|
113
|
+
login(email: string, password: string, totp?: string, _decryptPrivateKey?: boolean): Promise<Session>;
|
|
107
114
|
/**
|
|
108
115
|
* Resets the password for an account.
|
|
109
116
|
*
|
|
@@ -206,4 +213,5 @@ declare class Accounts extends API {
|
|
|
206
213
|
}
|
|
207
214
|
import API from "./API";
|
|
208
215
|
import AccountsSSO from "./AccountsSSO";
|
|
216
|
+
import AccountsMFA from "./AccountsMFA";
|
|
209
217
|
import Session from "../models/Session";
|
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;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(typeof options==="string"){console.warn("Warning: Passing the user's activation code during account creation has been moved into an options object. For compatibility reasons, the legacy behaviour still functions as expected, but please update your code as this will be changed in a future version.");options={activationCode:options}}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,referrer:options.referrer})])}).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,options.activationCode?_this3.activate(options.activationCode).catch(function(){return _this3.generateActivationCode()}):_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>
|
|
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);var _AccountsMFA=require("./AccountsMFA");var _AccountsMFA2=_interopRequireDefault(_AccountsMFA);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);_this.mfa=new _AccountsMFA2.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;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(typeof options==="string"){console.warn("Warning: Passing the user's activation code during account creation has been moved into an options object. For compatibility reasons, the legacy behaviour still functions as expected, but please update your code as this will be changed in a future version.");options={activationCode:options}}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,referrer:options.referrer})])}).then(function(_ref3){var keyPair=_ref3[0];return Promise.all([keyPair,_this3.login(email,password,undefined,false)])}).then(function(_ref4){var keyPair=_ref4[0],session=_ref4[1];return Promise.all([keyPair,session,options.activationCode?_this3.activate(options.activationCode).catch(function(){return _this3.generateActivationCode()}):_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,totp){var _this5=this;var _decryptPrivateKey=arguments.length>3&&arguments[3]!==undefined?arguments[3]:true;return this.client.crypto().generatePasswordHash(password).then(function(passwordHash){return _this5.client.request("accounts.login",{email:email,password:passwordHash,totp:totp})}).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,undefined,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,undefined,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;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export default AccountsMFA;
|
|
2
|
+
declare class AccountsMFA extends API {
|
|
3
|
+
constructor(client: any);
|
|
4
|
+
/**
|
|
5
|
+
* Begins the setup for MFA (multi-factor authentication).
|
|
6
|
+
*
|
|
7
|
+
* @returns {Promise<{ secret: string, qrCodeImage: string }>}
|
|
8
|
+
*/
|
|
9
|
+
setup(): Promise<{
|
|
10
|
+
secret: string;
|
|
11
|
+
qrCodeImage: string;
|
|
12
|
+
}>;
|
|
13
|
+
/**
|
|
14
|
+
* Enables the pending MFA configuration by providing a TOTP code to verify the authenticator app setup was successful.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} totp The timed one time passcode the user has received from scanning the qr code via their authentication app
|
|
17
|
+
* @returns {Promise}
|
|
18
|
+
*/
|
|
19
|
+
enable(totp: string): Promise<any>;
|
|
20
|
+
/**
|
|
21
|
+
* Disables current user MFA (multi-factor-authentication) once the user has entered their password.
|
|
22
|
+
*
|
|
23
|
+
* @param {string} password The users account password
|
|
24
|
+
* @returns {Promise}
|
|
25
|
+
*/
|
|
26
|
+
remove(password: string): Promise<any>;
|
|
27
|
+
}
|
|
28
|
+
import API from "./API";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);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 AccountsMFA=function(_API){_inherits(AccountsMFA,_API);function AccountsMFA(){_classCallCheck(this,AccountsMFA);return _possibleConstructorReturn(this,_API.apply(this,arguments))}AccountsMFA.prototype.setup=function setup(){return this.client.request("mfa.setup").then(function(response){return{secret:response.data.SetupSecret,qrCodeImage:response.data.SetupQrCode}})};AccountsMFA.prototype.enable=function enable(totp){return this.client.request("mfa.enable",{totp:totp})};AccountsMFA.prototype.remove=function remove(password){var _this2=this;return this.client.crypto().generatePasswordHash(password).then(function(passwordHash){return _this2.client.request("mfa.remove",{password:passwordHash})})};return AccountsMFA}(_API3.default);exports.default=AccountsMFA;
|
package/lib/api/Comments.d.ts
CHANGED
|
@@ -164,6 +164,21 @@ declare class Comments extends API {
|
|
|
164
164
|
* @returns {Promise<Array<Comment>>}
|
|
165
165
|
*/
|
|
166
166
|
load(_options: any): Promise<Comment[]>;
|
|
167
|
+
/**
|
|
168
|
+
* @typedef {object} CreateCommentOptions The options for creating a new comment
|
|
169
|
+
* @property {string} [raw] The comment text (plain text)
|
|
170
|
+
* @property {object} [tokens] The comment tokens (rich text)
|
|
171
|
+
* @property {string} [proofId] The proof ID the comment should be attached to
|
|
172
|
+
* @property {number} [pageNumber=1] For comments (not replies) - the page number the comment was placed on
|
|
173
|
+
* @property {Pin} [pin] For comments (not replies) - the comment's pin coordinates (deprecated: provide an array of pins instead)
|
|
174
|
+
* @property {Pin[]} [pins] For comments (not replies) - the comment's pin(s) coordinates
|
|
175
|
+
* @property {number} [mediaTime] For audio/video proofs - the time (in seconds) that the pin was placed (deprecated: set the time within the pin object)
|
|
176
|
+
* @property {number} [mediaDuration] For audio/video proofs - the duration (in seconds) that the pin spans (deprecated: set the duration within the pin object)
|
|
177
|
+
* @property {string} [parentCommentId] For replies - the parent comment ID
|
|
178
|
+
* @property {object} [metadata] For web proofs - additional metadata relating to the comment snapshot. It is recommended that you do not provide metadata through the SDK currently, as the format for the metadata is not documented (and is subject to change).
|
|
179
|
+
* @property {string} [state] For comments (not replies) - The state of the comment (currently only supports to-dos)
|
|
180
|
+
* @property {string} [creationToken] Only required if you're retrying (token can be extracted from the error object which is resolved (rejected, in this case) from the Promise)
|
|
181
|
+
*/
|
|
167
182
|
/**
|
|
168
183
|
* Creates a new comment (or reply).
|
|
169
184
|
*
|
|
@@ -184,10 +199,12 @@ declare class Comments extends API {
|
|
|
184
199
|
* await client.comments.create({
|
|
185
200
|
* proofId: 'PPTMHIVPYMB2XRTK',
|
|
186
201
|
* raw: 'Hello World!',
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
202
|
+
* pins: [
|
|
203
|
+
* {
|
|
204
|
+
* x: 0, // add the pin to the center of the proof
|
|
205
|
+
* y: 0,
|
|
206
|
+
* },
|
|
207
|
+
* ],
|
|
191
208
|
* });
|
|
192
209
|
*
|
|
193
210
|
* @example <caption>Single retry logic</caption>
|
|
@@ -195,7 +212,7 @@ declare class Comments extends API {
|
|
|
195
212
|
* await client.comments.create({
|
|
196
213
|
* proofId: 'PPTMHIVPYMB2XRTK',
|
|
197
214
|
* raw: 'Hello World!',
|
|
198
|
-
*
|
|
215
|
+
* pins: [{ x: 0, y: 0 }],
|
|
199
216
|
* creationToken: retryCreationToken,
|
|
200
217
|
* });
|
|
201
218
|
* }
|
|
@@ -215,27 +232,59 @@ declare class Comments extends API {
|
|
|
215
232
|
* }
|
|
216
233
|
*
|
|
217
234
|
* @since v2.0.0-beta.46
|
|
218
|
-
* @param {
|
|
219
|
-
* @param {string} [comment.raw] The raw comment text (rich text is not supported)
|
|
220
|
-
* @param {object} [comment.tokens] The comment tokens (with rich-text support). If you are creating legacy-style comments (just plain text) then use the "raw" option. Please note that while PageProof will continue to support plain text comments for the foreseeable future, it's recommended that you use the new "tokenized" comments.
|
|
221
|
-
* @param {string} comment.proofId The proof id the comment should be attached to
|
|
222
|
-
* @param {number} [comment.pageNumber=1] For comments (not replies) - the page number the comment should be attached to
|
|
223
|
-
* @param {Pin} [comment.pin] For comments (not replies) - the comment's pin coordinates
|
|
224
|
-
* @param {number} [comment.pin.x] The pin's x coordinate
|
|
225
|
-
* @param {number} [comment.pin.y] The pin's y coordinate
|
|
226
|
-
* @param {number} [comment.pin.x2] For boxes or lines - the pin's x2 coordinate
|
|
227
|
-
* @param {number} [comment.pin.y2] For boxes or lines - the pin's y2 coordinate
|
|
228
|
-
* @param {string} [comment.pin.fill.image] For pin fill images - the pin's fill image if pin is different then a dot or box type (like draw or text)
|
|
229
|
-
* @param {string} [comment.pin.fill.type] For pin fill images - the pin's fill image type
|
|
230
|
-
* @param {number} [comment.mediaTime] For video & audio - the start time
|
|
231
|
-
* @param {number} [comment.mediaDuration] For video & audio - the duration
|
|
232
|
-
* @param {string} [comment.parentCommentId] For replies - the parent comment id
|
|
233
|
-
* @param {object} [comment.metadata] For web proofs - additional metadata relating to the comment snapshot. It is recommended that you do not provide metadata through the SDK currently, as the format for the metadata is not documented (and is subject to change).
|
|
234
|
-
* @param {CommentState} [comment.state] For comments (not replies) - The state of the comment (currently only supports to-dos)
|
|
235
|
-
* @param {string} [comment.creationToken] Only required if you're retrying (token can be extracted from the error object which is resolved (rejected, in this case) from the Promise)
|
|
235
|
+
* @param {CreateCommentOptions} options The creation options
|
|
236
236
|
* @returns {Promise<Comment>}
|
|
237
237
|
*/
|
|
238
|
-
create({ raw, tokens, proofId, pageNumber, pin, mediaTime, mediaDuration, parentCommentId, metadata, state, creationToken: retryCreationToken, }:
|
|
238
|
+
create({ raw, tokens, proofId, pageNumber, pin, pins, mediaTime, mediaDuration, parentCommentId, metadata, state, creationToken: retryCreationToken, }: {
|
|
239
|
+
/**
|
|
240
|
+
* The comment text (plain text)
|
|
241
|
+
*/
|
|
242
|
+
raw?: string;
|
|
243
|
+
/**
|
|
244
|
+
* The comment tokens (rich text)
|
|
245
|
+
*/
|
|
246
|
+
tokens?: any;
|
|
247
|
+
/**
|
|
248
|
+
* The proof ID the comment should be attached to
|
|
249
|
+
*/
|
|
250
|
+
proofId?: string;
|
|
251
|
+
/**
|
|
252
|
+
* For comments (not replies) - the page number the comment was placed on
|
|
253
|
+
*/
|
|
254
|
+
pageNumber?: number;
|
|
255
|
+
/**
|
|
256
|
+
* For comments (not replies) - the comment's pin coordinates (deprecated: provide an array of pins instead)
|
|
257
|
+
*/
|
|
258
|
+
pin?: Pin;
|
|
259
|
+
/**
|
|
260
|
+
* For comments (not replies) - the comment's pin(s) coordinates
|
|
261
|
+
*/
|
|
262
|
+
pins?: Pin[];
|
|
263
|
+
/**
|
|
264
|
+
* For audio/video proofs - the time (in seconds) that the pin was placed (deprecated: set the time within the pin object)
|
|
265
|
+
*/
|
|
266
|
+
mediaTime?: number;
|
|
267
|
+
/**
|
|
268
|
+
* For audio/video proofs - the duration (in seconds) that the pin spans (deprecated: set the duration within the pin object)
|
|
269
|
+
*/
|
|
270
|
+
mediaDuration?: number;
|
|
271
|
+
/**
|
|
272
|
+
* For replies - the parent comment ID
|
|
273
|
+
*/
|
|
274
|
+
parentCommentId?: string;
|
|
275
|
+
/**
|
|
276
|
+
* For web proofs - additional metadata relating to the comment snapshot. It is recommended that you do not provide metadata through the SDK currently, as the format for the metadata is not documented (and is subject to change).
|
|
277
|
+
*/
|
|
278
|
+
metadata?: any;
|
|
279
|
+
/**
|
|
280
|
+
* For comments (not replies) - The state of the comment (currently only supports to-dos)
|
|
281
|
+
*/
|
|
282
|
+
state?: string;
|
|
283
|
+
/**
|
|
284
|
+
* Only required if you're retrying (token can be extracted from the error object which is resolved (rejected, in this case) from the Promise)
|
|
285
|
+
*/
|
|
286
|
+
creationToken?: string;
|
|
287
|
+
}): Promise<Comment>;
|
|
239
288
|
}
|
|
240
289
|
import API from "./API";
|
|
241
290
|
import Comment from "../models/Comment";
|
package/lib/api/Comments.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Comment=require("../models/Comment");var _Comment2=_interopRequireDefault(_Comment);var _CommentState=require("../enum/CommentState");var _CommentState2=_interopRequireDefault(_CommentState);var _constants=require("../util/constants");var _sort=require("../util/sort");var _v=require("../util/comments/v2");var _extractMentions=require("../util/comments/extractMentions");var _extractMentions2=_interopRequireDefault(_extractMentions);var _parseComment=require("../util/comments/parseComment");var _parseComment2=_interopRequireDefault(_parseComment);var _creationToken=require("../util/creationToken");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _getCommentState=require("../util/comments/getCommentState");var _getCommentState2=_interopRequireDefault(_getCommentState);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}function getCommentDataFromPages(pages){var comments=[];Object.keys(pages).forEach(function(pageNumber){pages[pageNumber].Comments.forEach(function(commentData){comments.push(commentData)})});return comments}var _sortPages=(0,_sort.sortObjectsByKey)("pageNumber");var _sortCreatedDateDESC=(0,_sort.sortObjectsByKey)("createdDate",true);var _sortCreatedDateASC=(0,_sort.sortObjectsByKey)("createdDate",false);var sortComments=(0,_sort.combineSort)(_sortPages,_sortCreatedDateDESC);var sortReplies=(0,_sort.combineSort)(_sortPages,_sortCreatedDateASC);function mapComments(commentsData){var comments=[];var replies=[];commentsData.forEach(function(commentData){var entity=(new _Comment2.default).fromComment(commentData);if(entity.parentCommentId){replies.push(entity)}else{comments.push(entity)}});comments.sort(sortComments);var commentIds=comments.map(function(c){return c.id});var sortByParentCommentIndex=(0,_sort.sortObjectsBy)(function(r){return commentIds.indexOf(r.parentCommentId)},true);replies.sort((0,_sort.combineSort)(sortReplies,sortByParentCommentIndex));return comments.concat(replies)}var Comments=function(_API){_inherits(Comments,_API);function Comments(){_classCallCheck(this,Comments);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Comments.prototype._mark=function _mark(commentId,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={commentId:commentId};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.update",data).then(function(response){return(0,_getCommentState2.default)(response.data)})};Comments.prototype._markAll=function _markAll(proofId,commentIds,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={proofId:proofId,commentIds:commentIds};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.multiple-update",data).then(function(response){return response.data.map(function(comment){return{commentId:comment.CommentId,commentState:(0,_getCommentState2.default)(comment)}})})};Comments.prototype.mark=function mark(commentId,state){return this._mark(commentId,state,true)};Comments.prototype.unmark=function unmark(commentId,state){return this._mark(commentId,state,false)};Comments.prototype.markAll=function markAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,true)};Comments.prototype.unmarkAll=function unmarkAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,false)};Comments.prototype.delete=function _delete(commentId){return this.client.request("comments.delete",{commentId:commentId})};Comments.prototype.load=function load(_options){var _this2=this;var options=typeof _options==="string"?{proofId:_options}:_options;var proofId=options.proofId,_options$pageNumber=options.pageNumber,pageNumber=_options$pageNumber===undefined?null:_options$pageNumber,_options$sinceDate=options.sinceDate,sinceDate=_options$sinceDate===undefined?null:_options$sinceDate,_options$async=options.async,async=_options$async===undefined?false:_options$async,_options$decrypt=options.decrypt,decrypt=_options$decrypt===undefined?true:_options$decrypt,onDecryptComment=options.onDecryptComment,onDecryptComments=options.onDecryptComments,_options$onDecryptCom=options.onDecryptCommentsThrottleMs,onDecryptCommentsThrottleMs=_options$onDecryptCom===undefined?1e3:_options$onDecryptCom,onDecryptError=options.onDecryptError;var sinceDateISO=sinceDate?sinceDate.toISOString().match(_constants.ISO_REGEX)[0]:_constants.DEFAULT_ISO_DATE;var payload={proofId:proofId,page:pageNumber,timestamp:sinceDateISO};return this.client.request(pageNumber!==null?"comments.load-page":"comments.load-all",payload).then(function(response){var comments=mapComments(response.data.Pages?getCommentDataFromPages(response.data.Pages):response.data);var wait=Promise.resolve();if(decrypt){var scheduled=[];var pendingBatch=[];var scheduleOnDecryptComments=onDecryptComments?(0,_throttle2.default)(function(){if(pendingBatch.length){onDecryptComments(pendingBatch);pendingBatch=[]}},onDecryptCommentsThrottleMs):function(){};var cached=Promise.all(comments.map(function(comment){return _this2.client.cache.auto(_constants.COMMENT_CACHE_PREFIX+comment.comment$,function(resolve){scheduled.push({comment:comment,resolve:resolve})}).then(function(rawComment){if(rawComment){comment.fromRawComment(rawComment)}return comment})}));wait=wait.then(function(){return cached});wait=wait.then(function(){var decrypted=scheduled.map(function(_ref){var comment=_ref.comment,resolve=_ref.resolve;return _this2.client.crypto().decryptComment(comment.comment$,comment.envelope,_this2.client.keyPairs.getPrivateKeyPEMs()).then(function(rawComment){comment.fromRawComment(rawComment);resolve(rawComment);if(onDecryptComment){onDecryptComment(comment)}pendingBatch.push(comment);scheduleOnDecryptComments()}).catch(function(err){if(onDecryptError){onDecryptError(err,comment)}if(!async){return Promise.reject(err)}return undefined})});if(!async){return Promise.all(decrypted)}return null})}return wait.then(function(){return comments})})};Comments.prototype.create=function create(_ref2){var _this3=this;var raw=_ref2.raw,tokens=_ref2.tokens,proofId=_ref2.proofId,_ref2$pageNumber=_ref2.pageNumber,pageNumber=_ref2$pageNumber===undefined?1:_ref2$pageNumber,pin=_ref2.pin,mediaTime=_ref2.mediaTime,mediaDuration=_ref2.mediaDuration,parentCommentId=_ref2.parentCommentId,metadata=_ref2.metadata,state=_ref2.state,retryCreationToken=_ref2.creationToken;var mentions=[];var serialized=raw||(0,_v.serialize)(tokens);{var parsed=tokens||(0,_parseComment2.default)(raw);mentions.push.apply(mentions,(0,_extractMentions2.default)(parsed))}var creationToken=retryCreationToken||(0,_creationToken.generateCreationToken)();return this.client.crypto().encryptComment(serialized,this.client.keyPairs.getPublicKeyPEMs()).then(function(_ref3){var envelope=_ref3.envelope,comment$=_ref3.comment$;return{proofId:proofId,page:parentCommentId?undefined:pageNumber,envelope:envelope,encryptedComment:comment$,xy:
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Comment=require("../models/Comment");var _Comment2=_interopRequireDefault(_Comment);var _CommentState=require("../enum/CommentState");var _CommentState2=_interopRequireDefault(_CommentState);var _constants=require("../util/constants");var _sort=require("../util/sort");var _v=require("../util/comments/v2");var _extractMentions=require("../util/comments/extractMentions");var _extractMentions2=_interopRequireDefault(_extractMentions);var _parseComment=require("../util/comments/parseComment");var _parseComment2=_interopRequireDefault(_parseComment);var _creationToken=require("../util/creationToken");var _throttle=require("../util/throttle");var _throttle2=_interopRequireDefault(_throttle);var _getCommentState=require("../util/comments/getCommentState");var _getCommentState2=_interopRequireDefault(_getCommentState);var _serializePins=require("../util/pins/serializePins");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}function getCommentDataFromPages(pages){var comments=[];Object.keys(pages).forEach(function(pageNumber){pages[pageNumber].Comments.forEach(function(commentData){comments.push(commentData)})});return comments}var _sortPages=(0,_sort.sortObjectsByKey)("pageNumber");var _sortCreatedDateDESC=(0,_sort.sortObjectsByKey)("createdDate",true);var _sortCreatedDateASC=(0,_sort.sortObjectsByKey)("createdDate",false);var sortComments=(0,_sort.combineSort)(_sortPages,_sortCreatedDateDESC);var sortReplies=(0,_sort.combineSort)(_sortPages,_sortCreatedDateASC);function mapComments(commentsData){var comments=[];var replies=[];commentsData.forEach(function(commentData){var entity=(new _Comment2.default).fromComment(commentData);if(entity.parentCommentId){replies.push(entity)}else{comments.push(entity)}});comments.sort(sortComments);var commentIds=comments.map(function(c){return c.id});var sortByParentCommentIndex=(0,_sort.sortObjectsBy)(function(r){return commentIds.indexOf(r.parentCommentId)},true);replies.sort((0,_sort.combineSort)(sortReplies,sortByParentCommentIndex));return comments.concat(replies)}var Comments=function(_API){_inherits(Comments,_API);function Comments(){_classCallCheck(this,Comments);return _possibleConstructorReturn(this,_API.apply(this,arguments))}Comments.prototype._mark=function _mark(commentId,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={commentId:commentId};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.update",data).then(function(response){return(0,_getCommentState2.default)(response.data)})};Comments.prototype._markAll=function _markAll(proofId,commentIds,state,value){if(Object.keys(_CommentState2.default).map(function(key){return _CommentState2.default[key]}).indexOf(state)===-1){throw new Error('Cannot mark comment state "'+state+'".')}var TODO=_CommentState2.default.TODO,DONE=_CommentState2.default.DONE,UNMARKED=_CommentState2.default.UNMARKED;var data={proofId:proofId,commentIds:commentIds};switch(state){case UNMARKED:{data.change=0;data.done=0;break}case TODO:{data.change=value?1:0;data.done=0;break}case DONE:{data.done=value?1:0;break}}return this.client.request("comments.state.multiple-update",data).then(function(response){return response.data.map(function(comment){return{commentId:comment.CommentId,commentState:(0,_getCommentState2.default)(comment)}})})};Comments.prototype.mark=function mark(commentId,state){return this._mark(commentId,state,true)};Comments.prototype.unmark=function unmark(commentId,state){return this._mark(commentId,state,false)};Comments.prototype.markAll=function markAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,true)};Comments.prototype.unmarkAll=function unmarkAll(proofId,commentIds,state){return this._markAll(proofId,commentIds,state,false)};Comments.prototype.delete=function _delete(commentId){return this.client.request("comments.delete",{commentId:commentId})};Comments.prototype.load=function load(_options){var _this2=this;var options=typeof _options==="string"?{proofId:_options}:_options;var proofId=options.proofId,_options$pageNumber=options.pageNumber,pageNumber=_options$pageNumber===undefined?null:_options$pageNumber,_options$sinceDate=options.sinceDate,sinceDate=_options$sinceDate===undefined?null:_options$sinceDate,_options$async=options.async,async=_options$async===undefined?false:_options$async,_options$decrypt=options.decrypt,decrypt=_options$decrypt===undefined?true:_options$decrypt,onDecryptComment=options.onDecryptComment,onDecryptComments=options.onDecryptComments,_options$onDecryptCom=options.onDecryptCommentsThrottleMs,onDecryptCommentsThrottleMs=_options$onDecryptCom===undefined?1e3:_options$onDecryptCom,onDecryptError=options.onDecryptError;var sinceDateISO=sinceDate?sinceDate.toISOString().match(_constants.ISO_REGEX)[0]:_constants.DEFAULT_ISO_DATE;var payload={proofId:proofId,page:pageNumber,timestamp:sinceDateISO};return this.client.request(pageNumber!==null?"comments.load-page":"comments.load-all",payload).then(function(response){var comments=mapComments(response.data.Pages?getCommentDataFromPages(response.data.Pages):response.data);var wait=Promise.resolve();if(decrypt){var scheduled=[];var pendingBatch=[];var scheduleOnDecryptComments=onDecryptComments?(0,_throttle2.default)(function(){if(pendingBatch.length){onDecryptComments(pendingBatch);pendingBatch=[]}},onDecryptCommentsThrottleMs):function(){};var cached=Promise.all(comments.map(function(comment){return _this2.client.cache.auto(_constants.COMMENT_CACHE_PREFIX+comment.comment$,function(resolve){scheduled.push({comment:comment,resolve:resolve})}).then(function(rawComment){if(rawComment){comment.fromRawComment(rawComment)}return comment})}));wait=wait.then(function(){return cached});wait=wait.then(function(){var decrypted=scheduled.map(function(_ref){var comment=_ref.comment,resolve=_ref.resolve;return _this2.client.crypto().decryptComment(comment.comment$,comment.envelope,_this2.client.keyPairs.getPrivateKeyPEMs()).then(function(rawComment){comment.fromRawComment(rawComment);resolve(rawComment);if(onDecryptComment){onDecryptComment(comment)}pendingBatch.push(comment);scheduleOnDecryptComments()}).catch(function(err){if(onDecryptError){onDecryptError(err,comment)}if(!async){return Promise.reject(err)}return undefined})});if(!async){return Promise.all(decrypted)}return null})}return wait.then(function(){return comments})})};Comments.prototype.create=function create(_ref2){var _this3=this;var raw=_ref2.raw,tokens=_ref2.tokens,proofId=_ref2.proofId,_ref2$pageNumber=_ref2.pageNumber,pageNumber=_ref2$pageNumber===undefined?1:_ref2$pageNumber,pin=_ref2.pin,pins=_ref2.pins,mediaTime=_ref2.mediaTime,mediaDuration=_ref2.mediaDuration,parentCommentId=_ref2.parentCommentId,metadata=_ref2.metadata,state=_ref2.state,retryCreationToken=_ref2.creationToken;var mentions=[];var serialized=raw||(0,_v.serialize)(tokens);{var parsed=tokens||(0,_parseComment2.default)(raw);mentions.push.apply(mentions,(0,_extractMentions2.default)(parsed))}var pinList=[];var boxFill=void 0;if(pins){pinList=pinList.concat(pins)}else if(pin){pinList.push(pin)}var primaryPin=pinList[0];if(primaryPin){if(primaryPin.fill)boxFill=primaryPin.fill;if(mediaTime)primaryPin.time=mediaTime;if(mediaDuration)primaryPin.duration=mediaDuration}var creationToken=retryCreationToken||(0,_creationToken.generateCreationToken)();return this.client.crypto().encryptComment(serialized,this.client.keyPairs.getPublicKeyPEMs()).then(function(_ref3){var envelope=_ref3.envelope,comment$=_ref3.comment$;return{proofId:proofId,page:parentCommentId?undefined:pageNumber,envelope:envelope,encryptedComment:comment$,xy:(0,_serializePins.serializePins)(pinList),boxFillImage:boxFill?boxFill.image:undefined,boxFillType:boxFill?boxFill.type:undefined,parent:parentCommentId||undefined,mentions:mentions,metadata:metadata?JSON.stringify(metadata):"{}",creationToken:creationToken,change:state===_CommentState2.default.TODO?"1":undefined,done:state===_CommentState2.default.DONE?"1":undefined}}).then(function(requestData){return _this3.client.request("comments.create",requestData).then(function(response){return(new _Comment2.default).fromComment(response.data).fromRawComment(serialized)})}).catch(function(err){if(err){err.creationToken=creationToken}return Promise.reject(err)})};return Comments}(_API3.default);exports.default=Comments;
|
package/lib/api/Files.d.ts
CHANGED
|
@@ -378,6 +378,19 @@ declare class Files extends API {
|
|
|
378
378
|
onLoadThumbnailsThrottleMs?: number;
|
|
379
379
|
onLoadError?: Function;
|
|
380
380
|
}): Promise<any>;
|
|
381
|
+
/**
|
|
382
|
+
* Duplicates a file.
|
|
383
|
+
*
|
|
384
|
+
* The file is asynchronously copied server-side but this method resolves as soon as the record is allocated for the duplicated file.
|
|
385
|
+
*
|
|
386
|
+
* @example <caption>Duplicate a file</caption>
|
|
387
|
+
* await client.files.duplicate('FTRIWJJDYNE8DFFF');
|
|
388
|
+
*
|
|
389
|
+
* @since v2.0.0-beta.281
|
|
390
|
+
* @param {string} id The file id
|
|
391
|
+
* @returns {Promise<FileV2>}
|
|
392
|
+
*/
|
|
393
|
+
duplicate(id: string): Promise<FileV2>;
|
|
381
394
|
}
|
|
382
395
|
import API from "./API";
|
|
383
396
|
import File from "../models/File";
|
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 _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._createWebsiteFile=function _createWebsiteFile(url){var _this3=this;return this._generateKeyIVEnvelope().then(function(_ref){var envelope=_ref.envelope;return _this3.client.request("files.import.web",{url:url,envelope:envelope})}).then(function(response){return response.data})};Files.prototype._importFileFromUrl=function _importFileFromUrl(_ref2){var _this4=this;var name=_ref2.name,url=_ref2.url,provider=_ref2.provider,auth=_ref2.auth,download=_ref2.download;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(_ref3){var envelope=_ref3.envelope;return _this4.client.request("files.import."+endpoint,{extn:extension,filename:filename,url:url,envelope:envelope,accessToken:auth,storeOriginal:download})}).then(function(response){return response.data})};Files.prototype.import=function _import(_ref4){var _this5=this;var name=_ref4.name,url=_ref4.url,_ref4$provider=_ref4.provider,provider=_ref4$provider===undefined?_ImportProvider2.default.NONE:_ref4$provider,auth=_ref4.auth,_ref4$download=_ref4.download,download=_ref4$download===undefined?false:_ref4$download,_ref4$process=_ref4.process,process=_ref4$process===undefined?false:_ref4$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+'"'))}return(provider===_ImportProvider2.default.WEBSITE?this._createWebsiteFile(url):this._importFileFromUrl({name:name,url:url,provider:provider,auth:auth,download:download})).then(function(token){if(process){return _this5._waitFileProcessed(token)}else{var file=new _File2.default;file.id=token;return file}})};Files.prototype.email=function email(){return this.client.request("files.create-email").then(function(response){return response.data})};Files.prototype._generateKeyIVEnvelope=function _generateKeyIVEnvelope(){var _this6=this;return this.client.crypto().generateKeyIV().then(function(keyIV){return Promise.all([keyIV,_this6.client.crypto().envelopeSeal(keyIV.keyIV,_this6.client.keyPairs.getPublicKeyPEMs())])}).then(function(_ref5){var keyIV=_ref5[0],envelope=_ref5[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 _this7=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 _this7.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 _ref6=[file.name,file.extension];name=_ref6[0];extension=_ref6[1]}else{var parsed=parseFilename(file.name);var _ref7=[parsed.name,parsed.extension];name=_ref7[0];extension=_ref7[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)}var entity=new _File2.default;entity.id=definition.FileId;if(file.onFileDetails){file.onFileDetails(entity)}return _this7._upload__v2(file,definition,opts,scheduleChunk,done).then(function(){return entity})}))}).then(function(results){return multipleFiles?results:results[0]})};Files.prototype._upload__v2=function _upload__v2(file,definition,options,schedule,done){var _this8=this;return this._generateKeyIVEnvelope().then(function(_ref8){var keyIV=_ref8.keyIV,envelope=_ref8.envelope;return new Promise(function(resolve,reject){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 _this8.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 _this8.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 _this8.client.crypto().encryptFileBlock(keyIV,block,true).then(function(block$_){return bluffer.createBase64(block$_)}).then(function(block$){var retries=0;var chunkRetryLimit=typeof options.chunkRetryLimit!=="undefined"?options.chunkRetryLimit:3;function attemptUploadData(){return uploadData(block$,blockIndex).then(function(response){if([200,201].indexOf(response.status)===-1){if(retries<chunkRetryLimit){retries++;if(options.chunkRetryDelay){return(0,_sleep2.default)(options.chunkRetryDelay).then(attemptUploadData)}return attemptUploadData()}else{var err=new Error("Failed to upload block #"+blockIndex+" (retried "+retries+" times).");reject(err);complete=true;throw err}}return response})}return attemptUploadData()})};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(_ref9){var _this9=this;var name=_ref9.name,contents=_ref9.contents,adobeExportData=_ref9.adobeExportData,assignedTo=_ref9.assignedTo,assignedType=_ref9.assignedType,_ref9$download=_ref9.download,download=_ref9$download===undefined?false:_ref9$download,_ref9$async=_ref9.async,async=_ref9$async===undefined?true:_ref9$async,onProgress=_ref9.onProgress,onError=_ref9.onError;return this.generateToken(assignedTo,assignedType).then(function(token){return Promise.all([token,_this9._generateKeyIVEnvelope()])}).then(function(_ref10){var token=_ref10[0],_ref10$=_ref10[1],keyIV=_ref10$.keyIV,envelope=_ref10$.envelope;var process=_this9._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(_ref11){var _this10=this;var name=_ref11.name,contents=_ref11.contents,adobeExportData=_ref11.adobeExportData,download=_ref11.download,token=_ref11.token,keyIV=_ref11.keyIV,envelope=_ref11.envelope,onProgress=_ref11.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 _this10.client.crypto().encryptFileBlock(keyIV,block).then(function(block$){return _this10.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 _this10.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 _this11=this;var options=typeof _options==="string"?{fileId:_options}:_options;var fileId=options.fileId,onFileDetails=options.onFileDetails;return this.details(fileId).then(function(file){if(!options.silent){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 _this11._downloadFile(file,options)})};Files.prototype._downloadFile=function _downloadFile(file,options){var _this12=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 _this12.client.request("files.download-block",{proofId:file.assignedTo,fileId:file.id,block:blockIndex+1,s:options.silent?1:undefined},{onDownloadProgress:onDownloadProgress.bind(null,blockIndex)}).then(function(response){return _this12.client.crypto().decryptFileBlock(response.data,_this12.client.keyPairs.getPrivateKeyPEMs()).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(fileId){var _this13=this;return this.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(){return _this13._thumbnail(fileId)})};Files.prototype._thumbnail=function _thumbnail(fileId){var _this14=this;return this.client.request("files.thumbnail",{fileId:fileId}).then(function(response){return _this14.client.crypto().decryptImage(response.data,_this14.client.keyPairs.getPrivateKeyPEMs())}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.preview=function preview(fileId){var _this15=this;var pageNumber=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var quality=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"low";return this.client.cache.auto(_constants.PREVIEW_CACHE_PREFIX+fileId+pageNumber+quality,function(){return _this15._preview(fileId,pageNumber,quality)})};Files.prototype._preview=function _preview(fileId,pageNumber,quality){var _this16=this;return this.client.request("files.preview",{fileId:fileId,pageNumber:pageNumber,quality:{low:"lo",high:"hi"}[quality]||quality}).then(function(response){return _this16.client.crypto().decryptImage(response.data,_this16.client.keyPairs.getPrivateKeyPEMs())}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.thumbnails=function thumbnails(fileIds,_ref12){var _this17=this;var _ref12$async=_ref12.async,async=_ref12$async===undefined?false:_ref12$async,onLoadThumbnail=_ref12.onLoadThumbnail,onLoadThumbnails=_ref12.onLoadThumbnails,_ref12$onLoadThumbnai=_ref12.onLoadThumbnailsThrottleMs,onLoadThumbnailsThrottleMs=_ref12$onLoadThumbnai===undefined?1e3:_ref12$onLoadThumbnai,onLoadError=_ref12.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 _this17.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(resolve){scheduled.push({fileId:fileId,resolve:resolve})}).then(function(thumbnail){var _ref13;return thumbnail&&(_ref13={},_ref13[fileId]=thumbnail,_ref13)})})).then(function(entries){var more=Promise.all(scheduled.map(function(_ref14){var fileId=_ref14.fileId,resolve=_ref14.resolve;return _this17._thumbnail(fileId).then(function(thumbnail){var _ref15;resolve(thumbnail);if(onLoadThumbnail){var _onLoadThumbnail;onLoadThumbnail((_onLoadThumbnail={},_onLoadThumbnail[fileId]=thumbnail,_onLoadThumbnail))}pendingBatch[fileId]=thumbnail;scheduleOnLoadThumbnails();return _ref15={},_ref15[fileId]=thumbnail,_ref15}).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 _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._createWebsiteFile=function _createWebsiteFile(url){var _this3=this;return this._generateKeyIVEnvelope().then(function(_ref){var envelope=_ref.envelope;return _this3.client.request("files.import.web",{url:url,envelope:envelope})}).then(function(response){return response.data})};Files.prototype._importFileFromUrl=function _importFileFromUrl(_ref2){var _this4=this;var name=_ref2.name,url=_ref2.url,provider=_ref2.provider,auth=_ref2.auth,download=_ref2.download;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(_ref3){var envelope=_ref3.envelope;return _this4.client.request("files.import."+endpoint,{extn:extension,filename:filename,url:url,envelope:envelope,accessToken:auth,storeOriginal:download})}).then(function(response){return response.data})};Files.prototype.import=function _import(_ref4){var _this5=this;var name=_ref4.name,url=_ref4.url,_ref4$provider=_ref4.provider,provider=_ref4$provider===undefined?_ImportProvider2.default.NONE:_ref4$provider,auth=_ref4.auth,_ref4$download=_ref4.download,download=_ref4$download===undefined?false:_ref4$download,_ref4$process=_ref4.process,process=_ref4$process===undefined?false:_ref4$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+'"'))}return(provider===_ImportProvider2.default.WEBSITE?this._createWebsiteFile(url):this._importFileFromUrl({name:name,url:url,provider:provider,auth:auth,download:download})).then(function(token){if(process){return _this5._waitFileProcessed(token)}else{var file=new _File2.default;file.id=token;return file}})};Files.prototype.email=function email(){return this.client.request("files.create-email").then(function(response){return response.data})};Files.prototype._generateKeyIVEnvelope=function _generateKeyIVEnvelope(){var _this6=this;return this.client.crypto().generateKeyIV().then(function(keyIV){return Promise.all([keyIV,_this6.client.crypto().envelopeSeal(keyIV.keyIV,_this6.client.keyPairs.getPublicKeyPEMs())])}).then(function(_ref5){var keyIV=_ref5[0],envelope=_ref5[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 _this7=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 _this7.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 _ref6=[file.name,file.extension];name=_ref6[0];extension=_ref6[1]}else{var parsed=parseFilename(file.name);var _ref7=[parsed.name,parsed.extension];name=_ref7[0];extension=_ref7[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)}var entity=new _File2.default;entity.id=definition.FileId;if(file.onFileDetails){file.onFileDetails(entity)}return _this7._upload__v2(file,definition,opts,scheduleChunk,done).then(function(){return entity})}))}).then(function(results){return multipleFiles?results:results[0]})};Files.prototype._upload__v2=function _upload__v2(file,definition,options,schedule,done){var _this8=this;return this._generateKeyIVEnvelope().then(function(_ref8){var keyIV=_ref8.keyIV,envelope=_ref8.envelope;return new Promise(function(resolve,reject){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 _this8.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 _this8.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 _this8.client.crypto().encryptFileBlock(keyIV,block,true).then(function(block$_){return bluffer.createBase64(block$_)}).then(function(block$){var retries=0;var chunkRetryLimit=typeof options.chunkRetryLimit!=="undefined"?options.chunkRetryLimit:3;function attemptUploadData(){return uploadData(block$,blockIndex).then(function(response){if([200,201].indexOf(response.status)===-1){if(retries<chunkRetryLimit){retries++;if(options.chunkRetryDelay){return(0,_sleep2.default)(options.chunkRetryDelay).then(attemptUploadData)}return attemptUploadData()}else{var err=new Error("Failed to upload block #"+blockIndex+" (retried "+retries+" times).");reject(err);complete=true;throw err}}return response})}return attemptUploadData()})};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(_ref9){var _this9=this;var name=_ref9.name,contents=_ref9.contents,adobeExportData=_ref9.adobeExportData,assignedTo=_ref9.assignedTo,assignedType=_ref9.assignedType,_ref9$download=_ref9.download,download=_ref9$download===undefined?false:_ref9$download,_ref9$async=_ref9.async,async=_ref9$async===undefined?true:_ref9$async,onProgress=_ref9.onProgress,onError=_ref9.onError;return this.generateToken(assignedTo,assignedType).then(function(token){return Promise.all([token,_this9._generateKeyIVEnvelope()])}).then(function(_ref10){var token=_ref10[0],_ref10$=_ref10[1],keyIV=_ref10$.keyIV,envelope=_ref10$.envelope;var process=_this9._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(_ref11){var _this10=this;var name=_ref11.name,contents=_ref11.contents,adobeExportData=_ref11.adobeExportData,download=_ref11.download,token=_ref11.token,keyIV=_ref11.keyIV,envelope=_ref11.envelope,onProgress=_ref11.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 _this10.client.crypto().encryptFileBlock(keyIV,block).then(function(block$){return _this10.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 _this10.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 _this11=this;var options=typeof _options==="string"?{fileId:_options}:_options;var fileId=options.fileId,onFileDetails=options.onFileDetails;return this.details(fileId).then(function(file){if(!options.silent){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 _this11._downloadFile(file,options)})};Files.prototype._downloadFile=function _downloadFile(file,options){var _this12=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 _this12.client.request("files.download-block",{proofId:file.assignedTo,fileId:file.id,block:blockIndex+1,s:options.silent?1:undefined},{onDownloadProgress:onDownloadProgress.bind(null,blockIndex)}).then(function(response){return _this12.client.crypto().decryptFileBlock(response.data,_this12.client.keyPairs.getPrivateKeyPEMs()).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(fileId){var _this13=this;return this.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(){return _this13._thumbnail(fileId)})};Files.prototype._thumbnail=function _thumbnail(fileId){var _this14=this;return this.client.request("files.thumbnail",{fileId:fileId}).then(function(response){return _this14.client.crypto().decryptImage(response.data,_this14.client.keyPairs.getPrivateKeyPEMs())}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.preview=function preview(fileId){var _this15=this;var pageNumber=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var quality=arguments.length>2&&arguments[2]!==undefined?arguments[2]:"low";return this.client.cache.auto(_constants.PREVIEW_CACHE_PREFIX+fileId+pageNumber+quality,function(){return _this15._preview(fileId,pageNumber,quality)})};Files.prototype._preview=function _preview(fileId,pageNumber,quality){var _this16=this;return this.client.request("files.preview",{fileId:fileId,pageNumber:pageNumber,quality:{low:"lo",high:"hi"}[quality]||quality}).then(function(response){return _this16.client.crypto().decryptImage(response.data,_this16.client.keyPairs.getPrivateKeyPEMs())}).then(function(imageBase64){var bluffer=new _bluffer2.default;return bluffer.createBase64(imageBase64)})};Files.prototype.thumbnails=function thumbnails(fileIds,_ref12){var _this17=this;var _ref12$async=_ref12.async,async=_ref12$async===undefined?false:_ref12$async,onLoadThumbnail=_ref12.onLoadThumbnail,onLoadThumbnails=_ref12.onLoadThumbnails,_ref12$onLoadThumbnai=_ref12.onLoadThumbnailsThrottleMs,onLoadThumbnailsThrottleMs=_ref12$onLoadThumbnai===undefined?1e3:_ref12$onLoadThumbnai,onLoadError=_ref12.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 _this17.client.cache.auto(_constants.THUMBNAIL_CACHE_PREFIX+fileId,function(resolve){scheduled.push({fileId:fileId,resolve:resolve})}).then(function(thumbnail){var _ref13;return thumbnail&&(_ref13={},_ref13[fileId]=thumbnail,_ref13)})})).then(function(entries){var more=Promise.all(scheduled.map(function(_ref14){var fileId=_ref14.fileId,resolve=_ref14.resolve;return _this17._thumbnail(fileId).then(function(thumbnail){var _ref15;resolve(thumbnail);if(onLoadThumbnail){var _onLoadThumbnail;onLoadThumbnail((_onLoadThumbnail={},_onLoadThumbnail[fileId]=thumbnail,_onLoadThumbnail))}pendingBatch[fileId]=thumbnail;scheduleOnLoadThumbnails();return _ref15={},_ref15[fileId]=thumbnail,_ref15}).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))})};Files.prototype.duplicate=function duplicate(id){return this.client.request("files.duplicate",{id:id}).then(function(response){return response.data.file})};return Files}(_API3.default);exports.default=Files;
|
package/lib/api/Workflows.d.ts
CHANGED
|
@@ -392,6 +392,26 @@ declare class Workflows extends API {
|
|
|
392
392
|
* @returns {Promise<string|null>}
|
|
393
393
|
*/
|
|
394
394
|
getNudgeMessage(workflowId: string, userId: string): Promise<string>;
|
|
395
|
+
/**
|
|
396
|
+
* Set a workflow template as favorite.
|
|
397
|
+
*
|
|
398
|
+
* @example <caption>Set workflow template as favorite</caption>
|
|
399
|
+
* await client.workflows.favorite('W8VN0H4UYFVV1VQL');
|
|
400
|
+
*
|
|
401
|
+
* @param {string} workflowId The workflow id
|
|
402
|
+
* @returns {Promise}
|
|
403
|
+
*/
|
|
404
|
+
favorite(workflowId: string): Promise<any>;
|
|
405
|
+
/**
|
|
406
|
+
* Unfavorite a workflow template.
|
|
407
|
+
*
|
|
408
|
+
* @example <caption>Unfavorite a workflow template</caption>
|
|
409
|
+
* await client.workflows.unfavorite('W8VN0H4UYFVV1VQL');
|
|
410
|
+
*
|
|
411
|
+
* @param {string} workflowId The workflow id
|
|
412
|
+
* @returns {Promise}
|
|
413
|
+
*/
|
|
414
|
+
unfavorite(workflowId: string): Promise<any>;
|
|
395
415
|
/** @private */
|
|
396
416
|
_duplicateWorkflow(workflowId: any, options: any): any;
|
|
397
417
|
/** @private */
|
package/lib/api/Workflows.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Workflow=require("../models/Workflow");var _Workflow2=_interopRequireDefault(_Workflow);var _WorkflowStep=require("../models/WorkflowStep");var _WorkflowStep2=_interopRequireDefault(_WorkflowStep);var _WorkflowUser=require("../models/WorkflowUser");var _WorkflowUser2=_interopRequireDefault(_WorkflowUser);var _id=require("../util/id");var _WorkflowsSteps=require("./WorkflowsSteps");var _WorkflowsSteps2=_interopRequireDefault(_WorkflowsSteps);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}function hasEnoughUserDetails(workflowUser){return workflowUser&&((0,_id.isUserId)(workflowUser.id)||workflowUser.email)}function transformWorkflows(workflows){return(workflows||[]).map(function(workflowData){return(new _Workflow2.default).fromWorkflow(workflowData)})}var Workflows=function(_API){_inherits(Workflows,_API);function Workflows(client){_classCallCheck(this,Workflows);var _this=_possibleConstructorReturn(this,_API.call(this,client));_this.steps=new _WorkflowsSteps2.default(client);return _this}Workflows.prototype.create=function create(_ref){var _this2=this;var _ref$save=_ref.save,save=_ref$save===undefined?false:_ref$save,name=_ref.name,_ref$steps=_ref.steps,_steps=_ref$steps===undefined?[]:_ref$steps,reviewers=_ref.reviewers,approver=_ref.approver,owners=_ref.owners,_ref$isOwnedByTeam=_ref.isOwnedByTeam,isOwnedByTeam=_ref$isOwnedByTeam===undefined?false:_ref$isOwnedByTeam;if(approver&&!hasEnoughUserDetails(approver)){return Promise.reject(Error("Please provide an approver id or email address."))}if(save&&!name){return Promise.reject(Error("A workflow must have a name when saving it as a workflow template."))}var steps=_steps;if(reviewers&&reviewers.length){steps.splice(0,0,{users:reviewers})}if(approver){steps.push({position:1e3,users:[approver],start:approver.start})}var largestPosition=0;for(var i=0;i<steps.length;i++){var step=steps[i];step.users=step.users||[];if(!step.position||step.position<largestPosition){step.position=largestPosition+1}largestPosition=Math.max(largestPosition,step.position);for(var ii=0;ii<step.users.length;ii++){var user=step.users[ii];if(!hasEnoughUserDetails(user)){return Promise.reject(Error("A user id or email address must be provided for a workflow user."))}}}var workflowId=void 0;return this._createWorkflow(name,isOwnedByTeam).then(function(workflow){workflowId=workflow.id;return Promise.all([workflow,Promise.all(steps.map(function(step){var workflowStep=workflow.getStepByPosition(step.position);return workflowStep?Promise.resolve(step.dueDate&&_this2.steps.update(workflowStep.id,{dueDate:step.dueDate}).then(function(updatedWorkflowStep){workflowStep.dueDate=updatedWorkflowStep.dueDate})).then(function(){return _this2._setWorkflowStepUsersMutate(workflow.id,workflowStep,step.users,step.start)}):_this2._addWorkflowStepAndUsers(workflow.id,step,step.start)})),owners&&Promise.all(owners.map(function(owner){return _this2._addProofOwnerToWorkflowTemplate(workflowId,owner)}))])}).then(function(_ref2){var workflow=_ref2[0],workflowSteps=_ref2[1];workflow.steps=workflowSteps;return workflow}).then(function(workflow){if(save){return _this2._duplicateWorkflow(workflowId)}return workflow}).catch(function(err){return Promise.resolve(workflowId&&_this2._deleteWorkflow(workflowId)).then(function(){return Promise.reject(err)})})};Workflows.prototype.load=function load(workflowId){return this.client.request("workflows.load",{workflowId:workflowId}).then(function(response){return(new _Workflow2.default).fromWorkflow(response.data)})};Workflows.prototype.use=function use(workflowId,options){return this.duplicate(workflowId,options)};Workflows.prototype.duplicate=function duplicate(workflowId,options){return this._duplicateWorkflow(workflowId,options)};Workflows.prototype.delete=function _delete(workflowId){return this._deleteWorkflow(workflowId)};Workflows.prototype.all=function all(){return Promise.all([this.owned(),this.shared()]).then(function(_ref3){var owned=_ref3[0],shared=_ref3[1];return[].concat(owned,shared)})};Workflows.prototype.owned=function owned(){return this.client.request("workflows.owned").then(function(response){return transformWorkflows(response.data)})};Workflows.prototype.shared=function shared(){return this.client.request("workflows.shared").then(function(response){return transformWorkflows(response.data)})};Workflows.prototype.setApprover=function setApprover(workflowId,user){return this.client.request("workflows.users.set",{workflowId:workflowId,position:1e3,users:[user]})};Workflows.prototype.skipAll=function skipAll(workflowId){return this.client.request("workflows.users.skip-all",{workflowId:workflowId})};Workflows.prototype.nudgeUser=function nudgeUser(workflowId,userId){var message=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;return this.client.request("workflows.user.nudge",{workflowId:workflowId,userId:userId,message:message})};Workflows.prototype.nudgeAll=function nudgeAll(workflowId){var message=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;return this.client.request("workflows.nudge-all",{workflowId:workflowId,message:message})};Workflows.prototype.setStartingStep=function setStartingStep(workflowId,stepId){return this.client.request("workflows.set-starting-step",{workflowId:workflowId,stepId:stepId})};Workflows.prototype.replaceApprover=function replaceApprover(workflowIdOrIds,user){return this.client.request("workflows.replace-approver",{workflowIds:[].concat(workflowIdOrIds),user:user})};Workflows.prototype.update=function update(workflowId,_ref4){var name=_ref4.name,isOwnedByTeam=_ref4.isOwnedByTeam;return this.client.request("workflows.update",{workflowId:workflowId,title:name,ownedByTeam:isOwnedByTeam}).then(function(response){return(new _Workflow2.default).fromWorkflow(response.data)})};Workflows.prototype.getNudgeAllMessage=function getNudgeAllMessage(workflowId){return this.client.request("workflows.nudge-message",{workflowId:workflowId}).then(function(response){return response.data.Message})};Workflows.prototype.getNudgeMessage=function getNudgeMessage(workflowId,userId){return this.client.request("workflows.nudge-message",{workflowId:workflowId,userId:userId}).then(function(response){return response.data.Message})};Workflows.prototype._duplicateWorkflow=function _duplicateWorkflow(workflowId,options){var _this3=this;return this.client.request("workflows.duplicate",{workflowId:workflowId,noOwners:options&&options.includeOwners===false?true:undefined,excludeStepDueDates:options&&options.includeStepDueDates===false?true:undefined,includeOwnedByTeam:options&&options.includeOwnedByTeam===true||undefined,includeSharedUsers:options&&options.includeSharedUsers===true||undefined}).then(function(response){var duplicatedWorkflowId=response.data.WorkflowId;return _this3.load(duplicatedWorkflowId)})};Workflows.prototype._deleteWorkflow=function _deleteWorkflow(workflowId){return this.client.request("workflows.delete",{workflowId:workflowId})};Workflows.prototype._createWorkflow=function _createWorkflow(name,isOwnedByTeam){return this.client.request("workflows.create",{title:name,ownedByTeam:isOwnedByTeam}).then(function(response){return(new _Workflow2.default).fromWorkflow(response.data)})};Workflows.prototype._addWorkflowStepAndUsers=function _addWorkflowStepAndUsers(workflowId,step,start){var _this4=this;return this.client.request("workflows.steps.add",{workflowId:workflowId,title:step.name,position:step.position,dueDate:step.dueDate}).then(function(response){var workflowStep=(new _WorkflowStep2.default).fromWorkflowStep(response.data);return _this4._setWorkflowStepUsersMutate(workflowId,workflowStep,step.users,start)})};Workflows.prototype._setWorkflowStepUsersMutate=function _setWorkflowStepUsersMutate(workflowId,workflowStep,users,start){var _this5=this;return this.client.request("workflows.users.set",{workflowId:workflowId,stepId:workflowStep.id,users:users.map(function(user){return{email:user.email,userId:user.id,role:user.role,permissions:user.permissions&&{inviter:!!user.permissions.inviter}}})}).then(function(response){var workflowUsers=response.data.map(function(user){return(new _WorkflowUser2.default).fromWorkflowUser(user)});workflowStep.users=workflowUsers}).then(function(){if(start===true){return _this5.setStartingStep(workflowId,workflowStep.id).then(function(){return workflowStep})}return workflowStep})};Workflows.prototype._addProofOwnerToWorkflowTemplate=function _addProofOwnerToWorkflowTemplate(workflowId,user){return this.client.request("workflows.proof-owners.add",{relatedId:workflowId,workflowCopyToProof:1,userId:user.id,email:user.email})};return Workflows}(_API3.default);exports.default=Workflows;
|
|
1
|
+
"use strict";exports.__esModule=true;var _API2=require("./API");var _API3=_interopRequireDefault(_API2);var _Workflow=require("../models/Workflow");var _Workflow2=_interopRequireDefault(_Workflow);var _WorkflowStep=require("../models/WorkflowStep");var _WorkflowStep2=_interopRequireDefault(_WorkflowStep);var _WorkflowUser=require("../models/WorkflowUser");var _WorkflowUser2=_interopRequireDefault(_WorkflowUser);var _id=require("../util/id");var _WorkflowsSteps=require("./WorkflowsSteps");var _WorkflowsSteps2=_interopRequireDefault(_WorkflowsSteps);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}function hasEnoughUserDetails(workflowUser){return workflowUser&&((0,_id.isUserId)(workflowUser.id)||workflowUser.email)}function transformWorkflows(workflows){return(workflows||[]).map(function(workflowData){return(new _Workflow2.default).fromWorkflow(workflowData)})}var Workflows=function(_API){_inherits(Workflows,_API);function Workflows(client){_classCallCheck(this,Workflows);var _this=_possibleConstructorReturn(this,_API.call(this,client));_this.steps=new _WorkflowsSteps2.default(client);return _this}Workflows.prototype.create=function create(_ref){var _this2=this;var _ref$save=_ref.save,save=_ref$save===undefined?false:_ref$save,name=_ref.name,_ref$steps=_ref.steps,_steps=_ref$steps===undefined?[]:_ref$steps,reviewers=_ref.reviewers,approver=_ref.approver,owners=_ref.owners,_ref$isOwnedByTeam=_ref.isOwnedByTeam,isOwnedByTeam=_ref$isOwnedByTeam===undefined?false:_ref$isOwnedByTeam;if(approver&&!hasEnoughUserDetails(approver)){return Promise.reject(Error("Please provide an approver id or email address."))}if(save&&!name){return Promise.reject(Error("A workflow must have a name when saving it as a workflow template."))}var steps=_steps;if(reviewers&&reviewers.length){steps.splice(0,0,{users:reviewers})}if(approver){steps.push({position:1e3,users:[approver],start:approver.start})}var largestPosition=0;for(var i=0;i<steps.length;i++){var step=steps[i];step.users=step.users||[];if(!step.position||step.position<largestPosition){step.position=largestPosition+1}largestPosition=Math.max(largestPosition,step.position);for(var ii=0;ii<step.users.length;ii++){var user=step.users[ii];if(!hasEnoughUserDetails(user)){return Promise.reject(Error("A user id or email address must be provided for a workflow user."))}}}var workflowId=void 0;return this._createWorkflow(name,isOwnedByTeam).then(function(workflow){workflowId=workflow.id;return Promise.all([workflow,Promise.all(steps.map(function(step){var workflowStep=workflow.getStepByPosition(step.position);return workflowStep?Promise.resolve(step.dueDate&&_this2.steps.update(workflowStep.id,{dueDate:step.dueDate}).then(function(updatedWorkflowStep){workflowStep.dueDate=updatedWorkflowStep.dueDate})).then(function(){return _this2._setWorkflowStepUsersMutate(workflow.id,workflowStep,step.users,step.start)}):_this2._addWorkflowStepAndUsers(workflow.id,step,step.start)})),owners&&Promise.all(owners.map(function(owner){return _this2._addProofOwnerToWorkflowTemplate(workflowId,owner)}))])}).then(function(_ref2){var workflow=_ref2[0],workflowSteps=_ref2[1];workflow.steps=workflowSteps;return workflow}).then(function(workflow){if(save){return _this2._duplicateWorkflow(workflowId)}return workflow}).catch(function(err){return Promise.resolve(workflowId&&_this2._deleteWorkflow(workflowId)).then(function(){return Promise.reject(err)})})};Workflows.prototype.load=function load(workflowId){return this.client.request("workflows.load",{workflowId:workflowId}).then(function(response){return(new _Workflow2.default).fromWorkflow(response.data)})};Workflows.prototype.use=function use(workflowId,options){return this.duplicate(workflowId,options)};Workflows.prototype.duplicate=function duplicate(workflowId,options){return this._duplicateWorkflow(workflowId,options)};Workflows.prototype.delete=function _delete(workflowId){return this._deleteWorkflow(workflowId)};Workflows.prototype.all=function all(){return Promise.all([this.owned(),this.shared()]).then(function(_ref3){var owned=_ref3[0],shared=_ref3[1];return[].concat(owned,shared)})};Workflows.prototype.owned=function owned(){return this.client.request("workflows.owned").then(function(response){return transformWorkflows(response.data)})};Workflows.prototype.shared=function shared(){return this.client.request("workflows.shared").then(function(response){return transformWorkflows(response.data)})};Workflows.prototype.setApprover=function setApprover(workflowId,user){return this.client.request("workflows.users.set",{workflowId:workflowId,position:1e3,users:[user]})};Workflows.prototype.skipAll=function skipAll(workflowId){return this.client.request("workflows.users.skip-all",{workflowId:workflowId})};Workflows.prototype.nudgeUser=function nudgeUser(workflowId,userId){var message=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;return this.client.request("workflows.user.nudge",{workflowId:workflowId,userId:userId,message:message})};Workflows.prototype.nudgeAll=function nudgeAll(workflowId){var message=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;return this.client.request("workflows.nudge-all",{workflowId:workflowId,message:message})};Workflows.prototype.setStartingStep=function setStartingStep(workflowId,stepId){return this.client.request("workflows.set-starting-step",{workflowId:workflowId,stepId:stepId})};Workflows.prototype.replaceApprover=function replaceApprover(workflowIdOrIds,user){return this.client.request("workflows.replace-approver",{workflowIds:[].concat(workflowIdOrIds),user:user})};Workflows.prototype.update=function update(workflowId,_ref4){var name=_ref4.name,isOwnedByTeam=_ref4.isOwnedByTeam;return this.client.request("workflows.update",{workflowId:workflowId,title:name,ownedByTeam:isOwnedByTeam}).then(function(response){return(new _Workflow2.default).fromWorkflow(response.data)})};Workflows.prototype.getNudgeAllMessage=function getNudgeAllMessage(workflowId){return this.client.request("workflows.nudge-message",{workflowId:workflowId}).then(function(response){return response.data.Message})};Workflows.prototype.getNudgeMessage=function getNudgeMessage(workflowId,userId){return this.client.request("workflows.nudge-message",{workflowId:workflowId,userId:userId}).then(function(response){return response.data.Message})};Workflows.prototype.favorite=function favorite(workflowId){return this.client.request("workflows.favorite",{workflowId:workflowId})};Workflows.prototype.unfavorite=function unfavorite(workflowId){return this.client.request("workflows.unfavorite",{workflowId:workflowId})};Workflows.prototype._duplicateWorkflow=function _duplicateWorkflow(workflowId,options){var _this3=this;return this.client.request("workflows.duplicate",{workflowId:workflowId,noOwners:options&&options.includeOwners===false?true:undefined,excludeStepDueDates:options&&options.includeStepDueDates===false?true:undefined,includeOwnedByTeam:options&&options.includeOwnedByTeam===true||undefined,includeSharedUsers:options&&options.includeSharedUsers===true||undefined}).then(function(response){var duplicatedWorkflowId=response.data.WorkflowId;return _this3.load(duplicatedWorkflowId)})};Workflows.prototype._deleteWorkflow=function _deleteWorkflow(workflowId){return this.client.request("workflows.delete",{workflowId:workflowId})};Workflows.prototype._createWorkflow=function _createWorkflow(name,isOwnedByTeam){return this.client.request("workflows.create",{title:name,ownedByTeam:isOwnedByTeam}).then(function(response){return(new _Workflow2.default).fromWorkflow(response.data)})};Workflows.prototype._addWorkflowStepAndUsers=function _addWorkflowStepAndUsers(workflowId,step,start){var _this4=this;return this.client.request("workflows.steps.add",{workflowId:workflowId,title:step.name,position:step.position,dueDate:step.dueDate}).then(function(response){var workflowStep=(new _WorkflowStep2.default).fromWorkflowStep(response.data);return _this4._setWorkflowStepUsersMutate(workflowId,workflowStep,step.users,start)})};Workflows.prototype._setWorkflowStepUsersMutate=function _setWorkflowStepUsersMutate(workflowId,workflowStep,users,start){var _this5=this;return this.client.request("workflows.users.set",{workflowId:workflowId,stepId:workflowStep.id,users:users.map(function(user){return{email:user.email,userId:user.id,role:user.role,permissions:user.permissions&&{inviter:!!user.permissions.inviter}}})}).then(function(response){var workflowUsers=response.data.map(function(user){return(new _WorkflowUser2.default).fromWorkflowUser(user)});workflowStep.users=workflowUsers}).then(function(){if(start===true){return _this5.setStartingStep(workflowId,workflowStep.id).then(function(){return workflowStep})}return workflowStep})};Workflows.prototype._addProofOwnerToWorkflowTemplate=function _addProofOwnerToWorkflowTemplate(workflowId,user){return this.client.request("workflows.proof-owners.add",{relatedId:workflowId,workflowCopyToProof:1,userId:user.id,email:user.email})};return Workflows}(_API3.default);exports.default=Workflows;
|