generated from AdobeDocs/dev-site-documentation-template
-
Notifications
You must be signed in to change notification settings - Fork 27
/
index.js
330 lines (293 loc) · 9.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
Copyright 2018-2019 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const AWS = require('aws-sdk')
//Define your own config file setup. An example config is attached just with service url
const config = require('./config.json')
const fs = require('fs')
const request = require('request-promise')
const util = require("util")
/* turn off eslint warnings about console.log */
/* eslint no-console: 0 */
/* Declare service endpoints */
const documentManifestUrl = `${config.psdService}/documentManifest`
const renditionCreateUrl = `${config.psdService}/renditionCreate`
const documentOperationsUrl = `${config.psdService}/documentOperations`
/* Initialize S3 object -- we must use signatureVersion: 'v4' for presigned PUT urls */
const region = config.sample_file.s3_region || "us-east-1"
const S3 = new AWS.S3({ apiVersion: '2006-03-01', signatureVersion: 'v4', region })
/* Check job status every x milliseconds for up to y times */
const statusRetryMillis = 200
const statusRetries = 20
const imsConfig = {
clientId: "YOUR_ADOBE_CLIENT_ID",
clientSecret: "YOUR_ADOBE_CLIENT_SECRET",
};
async function generateIMSToken() {
const url = 'https://ims-na1.adobelogin.com/ims/token/v3';
const options = {
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
grant_type: 'client_credentials',
client_id: imsConfig.clientId,
client_secret: imsConfig.clientSecret,
scope: 'openid,AdobeID,read_organizations'
}
};
return new Promise((resolve, reject) => {
request(options, (err, res, body) => {
if(err || res.statusCode >= 400) {
reject( err || body )
}else{
resolve( body )
}
})
})
}
/* Use the AWS SDK to generate a presigned GET url for our sample file in S3 */
async function obtainS3PresignedGetUrl (bucket, prefix) {
const options = {
Bucket: bucket,
Key: prefix
}
return S3.getSignedUrl('getObject', options)
}
/*
Call the Photoshop API to retrieve the manifest for the sample file
The Photoshop API service will read the file from S3
*/
async function getDocumentManifest (token, presignedGetUrl) {
const body = {
inputs: [
{
href: presignedGetUrl,
storage: 'external'
}
]
}
return callPsdService(token, documentManifestUrl, body)
}
/* Use the AWS SDK to generate a presigned PUT url for our rendition */
async function obtainS3PresignedPutUrl (bucket, prefix) {
const options = {
Bucket: bucket,
Key: prefix
}
return S3.getSignedUrl('putObject', options)
}
/*
Call the Photoshop API to generate one rendition of the sample file
The Photoshop API service will read the file from S3, and,
write the rendition back to S3
*/
function getDocumentRendition(token, presignedGetUrl, presignedPutUrl, rendition_type, rendition_width) {
const body = {
inputs: [
{
href: presignedGetUrl,
storage: 'external'
}
],
outputs: [
{
href: presignedPutUrl,
storage: 'external',
type: rendition_type,
width: parseInt(rendition_width, 10)
}
]
}
return callPsdService(token, renditionCreateUrl, body)
}
/*
Call the Photoshop API to add a layer to the sample file, and,
write the new file back to S3
*/
async function addLayerToDocument(token, presignedGetUrl, addLayerPutUrl) {
/* Add an adjustment layer as first element in layers */
const layerToAdd = {
add: {
insertTop: true
},
adjustments: {
brightnessContrast: {
brightness: 25,
contrast: -40
}
},
name: 'NewBrightnessContrast',
type: 'adjustmentLayer'
}
const body = {
inputs: [
{
href: presignedGetUrl,
storage: "external"
}
],
options: {
layers: [layerToAdd]
},
outputs: [
{
href: addLayerPutUrl,
storage: "external",
type: "vnd.adobe.photoshop"
}
]
};
return callPsdService(token, documentOperationsUrl, body)
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
/* Helper function to call the psdService */
async function callPsdService (token, commandUri, body) {
/* Inside this function we post a request, then poll for a response
The success return for the callback is inside the checkStatus function
*/
/* Check for a valid response body from POST */
function validJobResponse (response) {
return !!(response._links && response._links.self && response._links.self.href)
}
/* Log status for all requested outputs */
function logOutputStatus(outputs) {
let statuses = []
for (let output in outputs) {
statuses.push(outputs[output].status)
}
console.log(` status: ${statuses.join(', ')}`)
}
/* Check if all output entries are reporting status as done */
function allOutputsDone(outputs) {
/* If any output shows status of not done, then job is still running */
for (let output in outputs) {
if (outputs[output].status !== 'succeeded' &&
outputs[output].status !== 'failed') {
return false
}
}
return true
}
/* Function to check for result - called from async.retry below */
function checkJobStatus(statusUri) {
/* Prepare the options for the HTTPS request call to get the status of our job */
let options = {
uri: statusUri,
headers: {
Authorization: `Bearer ${token}`,
"x-api-key": config.identity.client_id
},
json: true
}
/* Send a GET request for the status */
return request(options)
}
/* Prepare the options for the HTTPS POST call to the Photoshop API */
let options = {
method: 'post',
uri: commandUri,
headers: {
Authorization: `Bearer ${token}`,
'x-api-key': config.identity.client_id
},
body,
json: true
}
/* Send POST request to the Photoshop API */
writeStatus(`Call ${commandUri} API`)
const result = await request(options)
if (!validJobResponse(result)) {
throw new (`Bad job response: ${result}`)
}
const statusUri = result._links.self.href
let retries = statusRetries;
let done = false;
let showJobId = true;
while (retries-- > 0 && !done) {
await sleep(statusRetryMillis);
try {
const status = await checkJobStatus(statusUri);
if (showJobId) {
console.log(`jobId: ${status.jobId}`);
showJobId = false;
}
logOutputStatus(status.outputs);
done = allOutputsDone(status.outputs);
if (done) {
return status;
}
}
catch (err) {
if (err.statusCode && (err.statusCode >= 502 && err.statusCode <= 504)) {
console.log(`gateway error ${err.statusCode}; will retry`)
continue
}
else {
console.log(`error while retrieving status ${err.message}`)
throw err
}
}
}
return Promise.reject(new Error('exceeded number of retries'))
}
function removeSignature(presignedUrl) {
return presignedUrl.split('?')[0]
}
/* Main logic is here, using async waterfall */
async function main () {
writeStatus('1. START')
writeStatus('2. Get IMS Token')
const authDetails = await generateIMSToken();
let authInfo = JSON.parse(authDetails);
console.log(authInfo)
writeStatus('3. Request access token')
const token = authInfo.access_token
const bucket = config.sample_file.s3_bucket
writeStatus(`4. Obtain S3 presigned GET url for sample file: ${bucket}/${config.sample_file.s3_prefix}`)
const presignedGetUrl = await obtainS3PresignedGetUrl(bucket, config.sample_file.s3_prefix)
writeStatus(`5. Get documentManifest with url ${removeSignature(presignedGetUrl)}`)
const manifestResult = await getDocumentManifest(token, presignedGetUrl)
const layers = manifestResult.outputs[0].layers;
writeStatus(` layers ${JSON.stringify(layers)}`)
writeStatus(`6. Obtain S3 presigned PUT url for rendition: ${bucket}/${config.sample_file.s3_rendition_prefix}`)
const presignedPutUrl = await obtainS3PresignedPutUrl(bucket, config.sample_file.s3_rendition_prefix)
writeStatus( `7. Create rendition with url ${ removeSignature(presignedGetUrl) } and write to ${removeSignature(presignedPutUrl)}`)
const renditionResult = await getDocumentRendition(token, presignedGetUrl, presignedPutUrl,
config.sample_file.rendition_type, config.sample_file.rendition_width)
writeStatus(` rendition: ${renditionResult.outputs[0]._links.renditions[0].href}`)
writeStatus(`8. Obtain S3 presigned PUT url for add layer: ${bucket}/${config.sample_file.s3_add_layer_prefix}`)
const presignedPutUrlForAddLayer = await obtainS3PresignedPutUrl(bucket, config.sample_file.s3_add_layer_prefix)
writeStatus(
`9. Add layer to document at url ${
removeSignature(presignedGetUrl)
} and write to ${removeSignature(presignedPutUrlForAddLayer)}`
)
const addLayerResult = await addLayerToDocument(token, presignedGetUrl, presignedPutUrlForAddLayer)
writeStatus(
` addLayerResult: ${
addLayerResult.outputs[0]._links.renditions[0].href
}`
)
writeStatus('10. DONE SUCCESS')
}
main().catch(e => {
console.log(e)
writeStatus('DONE ERROR')
process.exit(5)
})
function writeStatus (message) {
console.log(message)
console.log('********')
}