forked from isabella232/indesign-api-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.jsx
More file actions
649 lines (581 loc) · 20.4 KB
/
utils.jsx
File metadata and controls
649 lines (581 loc) · 20.4 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// Utils functions which can be used across.
/* globals app, Errors, File, Folder, LinkStatus, SaveOptions */
// Globals.
var logFileObject
// eslint-disable-next-line no-extend-native
Array.prototype.indexOf = function (item) {
var index = 0
var length = this.length
for (; index < length; index++) {
if (this[index] === item) {
return index
}
}
return -1
}
// eslint-disable-next-line no-extend-native
if (typeof Array.isArray === 'undefined') {
Array.isArray = function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]'
}
}
var UTILS = {}
UTILS.Logs = []
UTILS.workingFolder = ''
UTILS.outputFolder = ''
UTILS.assetsToBeUploaded = [] // These are assets which are to be uploaded.
UTILS.createSeparateLogFile = true
UTILS.logFilePath = 'LogFile.txt'
// Converts the package in appropriate format, which can be returned from the capability.
UTILS.GetFinalReturnPackage = function (obj) {
UTILS.Log('Final package created')
return JSON.stringify(obj)
}
// Creates and returns the package to be returned in case the job is successful.
UTILS.GetSuccessReturnObj = function (data) {
var obj = {}
obj.status = 'SUCCESS'
obj.assetsToBeUploaded = UTILS.assetsToBeUploaded
var dataURL = UTILS.WriteToFile(data, 'outputData')
if (dataURL) {
obj.dataURL = dataURL
}
return obj
}
// Creates and returns the package to be returned in case the job has failed.
UTILS.GetFailureReturnObj = function (errorCode, errorString, data) {
var obj = {}
obj.status = 'FAILURE'
obj.errorCode = errorCode
obj.errorString = errorString
obj.data = data
return obj
}
// Add an asset which is to be uploaded and sent back to the caller.
UTILS.AddAssetToBeUploaded = function (assetPath, data) {
var assetToBeUploaded = {}
assetToBeUploaded.path = assetPath
if (data !== undefined) {
assetToBeUploaded.data = data
}
UTILS.assetsToBeUploaded.push(assetToBeUploaded)
}
// This handles errors in case an exception is raised. This results the capability returning error to the caller.
// Application error codes are from: SDK/docs/references/errorcodes.htm
UTILS.HandleError = function (exception) {
var errorCode, errorString
UTILS.Log('Exception occurred: ' + JSON.stringify(exception))
if (exception.message === 'open') {
exception.message = Errors.CannotOpenFileError.errorStrings[0]
exception.errorCode = Errors.CannotOpenFileError.errorCode
}
errorString = 'Script error: '
if (exception.isCustom === true) {
if (exception.message) {
errorString = errorString + exception.message
}
errorCode = exception.errorCode
} else {
errorCode = Errors.ProcessingErrorOccurred.errorCode
if (exception.message) {
errorString = errorString + Errors.ProcessingErrorOccurred.errorStrings[0] + ' ' + exception.message
}
if (exception.errorCode !== undefined) {
errorString = errorString + '\nInternal error code: ' + exception.errorCode + '.'
}
if (exception.line !== undefined) {
errorString = errorString + ' Line: ' + exception.line + '.'
}
if (exception.fileName !== undefined) {
errorString = errorString + ' FileName: ' + exception.fileName + '.'
}
UTILS.Log('Processing error occurred. ' + errorString)
}
return UTILS.GetFailureReturnObj(errorCode, errorString)
}
// This is used to raise an exception with all the required details.
// NOTE: This takes variable list of argument and then try to fill in the details in errorObj.errorStrings
UTILS.RaiseException = function (errorObj) {
UTILS.Log('RaiseException()')
var numMessageParameters = arguments.length
UTILS.Log('', 'numMessageParameters: ' + numMessageParameters)
var numErrorStrings = errorObj.errorStrings.length
UTILS.Log('', 'numErrorStrings: ' + numErrorStrings)
var numIterations = (numMessageParameters > numErrorStrings) ? numErrorStrings : numMessageParameters
var errorMessage = errorObj.errorStrings[0]
UTILS.Log('', 'Default errorMessage: ' + errorMessage)
for (var itr = 1; itr < numIterations; itr++) {
var parameter = arguments[itr]
if (parameter !== undefined && parameter !== '') {
var parameterMessage = errorObj.errorStrings[itr]
errorMessage = errorMessage + ' ' + parameterMessage.replace('^1', parameter)
UTILS.Log('', 'Appended errorMessage: ' + errorMessage)
}
}
var exceptionObj = {
number: errorObj.errorCode,
isCustom: true,
message: errorMessage
}
throw exceptionObj
}
// This updates all the links in the document.
UTILS.UpdateDocumentLinks = function (document) {
var links = document.links
var numLinks = links.length
var linkItr, link, uri
var outOfDateLinks = []
UTILS.Log('Number of links: ' + numLinks)
for (linkItr = 0; linkItr < numLinks; linkItr++) {
link = links[linkItr]
uri = link.linkResourceURI
UTILS.Log(linkItr + ': URI: ' + uri)
if (link.status === LinkStatus.LINK_OUT_OF_DATE) {
outOfDateLinks.push(link.id)
}
}
numLinks = outOfDateLinks.length
for (linkItr = 0; linkItr < numLinks; linkItr++) {
link = document.links.itemByID(outOfDateLinks[linkItr])
if (link.isValid) {
link.update()
}
}
var composeStartTime = new Date().getTime()
document.recompose()
var composedTime = (new Date()).getTime() - composeStartTime
UTILS.Log('document.recompose Time: ' + composedTime)
}
// This embeds all the links in the document.
UTILS.EmbedDocumentLinks = function (document) {
var links = document.links
var numLinks = links.length
var linkItr, link
for (linkItr = 0; linkItr < numLinks; linkItr++) {
link = links[linkItr]
if (link.status === LinkStatus.NORMAL) {
link.unlink()
}
}
}
// Trims the string which has been passed.
UTILS.Trim = function (val) {
return val.replace(/^\s+|\s+$/gm, '')
}
// Removes all the spaces from a string.
UTILS.RemoveAllSpaces = function (val) {
return val.replace(/\s/g, '')
}
// Converts a value to boolean. Exception is thrown if the conversion fails.
UTILS.GetBoolean = function (val) {
if (val === 'true' || val === true) {
return true
} else if (val === 'false' || val === false) {
return false
}
// throw exception.
UTILS.Log('GetBoolean() val: ' + val)
UTILS.RaiseException(Errors.ParsingBoolError, val)
}
// Gets a boolean from an 'object' defined with 'key'.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case, key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the conversion of the provided value fails.
UTILS.GetBooleanFromObject = function (object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetBooleanFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
if (val === 'true' || val === true) {
return true
} else if (val === 'false' || val === false) {
return false
}
UTILS.Log('GetBooleanFromObject() val: ' + val)
UTILS.RaiseException(Errors.ParsingBoolError, val, key)
} else if (defaultVal === undefined) {
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Converts a value to integer. Exception is thrown if the conversion fails.
UTILS.GetInteger = function (val) {
var returnVal = parseInt(val)
if (!isNaN(returnVal)) {
return returnVal
}
UTILS.Log('GetInteger() val: ' + val)
UTILS.RaiseException(Errors.ParsingIntError, val)
}
// Gets a integer from an 'object' defined with 'key'.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case, key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the conversion of the provided value fails.
UTILS.GetIntegerFromObject = function (object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetIntegerFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
var returnVal = parseInt(val)
if (!isNaN(returnVal)) {
return returnVal
}
UTILS.Log('GetIntegerFromObject() val: ' + val)
UTILS.RaiseException(Errors.ParsingIntError, val, key)
} else if (defaultVal === undefined) {
UTILS.Log('Missing key: ' + key)
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Converts a value to float. Exception is thrown if the conversion fails.
UTILS.GetFloat = function (val) {
var returnVal = parseFloat(val)
if (!isNaN(returnVal)) {
return returnVal
}
UTILS.Log('GetFloat() val: ' + val)
UTILS.RaiseException(Errors.ParsingFloatError, val)
}
// Gets a float from an 'object' defined with 'key'.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case, key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the conversion of the provided value fails.
UTILS.GetFloatFromObject = function (object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetFloatFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
var returnVal = parseFloat(val)
if (!isNaN(returnVal)) {
return returnVal
}
UTILS.Log('GetFloatFromObject() val: ' + val)
UTILS.RaiseException(Errors.ParsingFloatError, val, key)
} else if (defaultVal === undefined) {
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Validates a value to be one of the enum definitions.
UTILS.GetEnum = function (enumDef, val) {
try {
val = UTILS.Trim(val)
return UTILS.GetValueFromObject(enumDef, val)
} catch (e) {
UTILS.RaiseException(Errors.EnumError, val)
}
}
// Gets a enum value from an 'object' defined with 'key' and after comparing against an enum definition.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the value is not present in enum definition.
UTILS.GetEnumFromObject = function (enumDef, object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetEnumFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
try {
val = UTILS.Trim(val)
if (Array.isArray(enumDef) === false) {
return UTILS.GetValueFromObject(enumDef, val, ignoreCase)
} else {
if (enumDef.indexOf(val) >= 0) {
return val
}
}
} catch (e) {
UTILS.Log('GetEnumFromObject() val: ' + val)
UTILS.RaiseException(Errors.EnumError, val, key)
}
UTILS.Log('GetEnumFromObject() val: ' + val)
UTILS.RaiseException(Errors.EnumError, val, key)
} else if (defaultVal === undefined) {
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Gets a string from an 'object' defined with 'key'.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case, key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the value found is not string.
UTILS.GetStringFromObject = function (object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetStringFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
if (typeof val !== 'string') {
UTILS.RaiseException(Errors.ParsingStringError, val, key)
} else {
return val
}
} else if (defaultVal === undefined) {
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Gets an array from an 'object' defined with 'key'.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case, key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the value found is not an array.
UTILS.GetArrayFromObject = function (object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetArrayFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
if (Array.isArray(val) === false) {
UTILS.RaiseException(Errors.ArrayExpected, key)
} else {
return val
}
} else if (defaultVal === undefined) {
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Gets an object from an 'object' defined with 'key'.
// A default value can be passed via 'defaultVal' which will be used if the key is missing. The case of key can be ignored via 'ignoreCase'.
// In case, key is missing and a default value is not provided, an exception will be thrown. Exception will also be thrown if the value found is not an object.
UTILS.GetObjectFromObject = function (object, key, defaultVal, ignoreCase) {
var val
UTILS.Log('GetObjectFromObject ' + key)
if (UTILS.IsKeyPresent(object, key)) {
val = UTILS.GetValueFromObject(object, key, ignoreCase)
if (typeof val !== 'object' || Array.isArray(val)) {
UTILS.RaiseException(Errors.ObjectExpected, key)
} else {
return val
}
} else if (defaultVal === undefined) {
UTILS.RaiseException(Errors.MissingKey, key)
} else {
// default value provided.
return defaultVal
}
}
// Gets the value from an 'object' defined with 'key'.
// The case of key can be ignored via 'ignoreCase'. In case, key is missing an exception will be thrown.
UTILS.GetValueFromObject = function (object, key, ignoreCase) {
UTILS.Log('GetValueFromObject ' + key)
if (ignoreCase === true) {
var objectKey
for (objectKey in object) {
if (Object.prototype.hasOwnProperty.call(object, objectKey)) {
if (objectKey.toLowerCase() === key.toLowerCase()) {
return object[objectKey]
}
}
}
} else if (Object.prototype.hasOwnProperty.call(object, key)) {
return object[key]
}
UTILS.RaiseException(Errors.MissingKey, key)
}
// Checks whether a key is present in the object or not.
UTILS.IsKeyPresent = function (object, key) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
return true
}
return false
}
// Sets the working folder to be used across the capability.
UTILS.SetWorkingFolder = function (workingFolder) {
workingFolder = workingFolder.replace(/\//g, '\\')
if (workingFolder.charAt(workingFolder.length - 1) !== '\\') {
workingFolder = workingFolder + '\\'
}
UTILS.workingFolder = workingFolder
UTILS.OpenLogFileHandle()
}
// Gets the path of the directory for a given path.
UTILS.GetDirPath = function (path) {
path = path.replace(/\//g, '\\')
var indexOfSlash = path && path.lastIndexOf('\\')
if (indexOfSlash >= 0) {
return path.substr(0, indexOfSlash)
}
return ''
}
// Gets the path of the directory for a given path. If 'withExtension is true the file name consists of the file extension and not otherwise.
UTILS.GetFileName = function (path, withExtension) {
var fileName
var indexOfSlash = path.lastIndexOf('\\') + 1
if (indexOfSlash >= 1) {
fileName = path.substr(indexOfSlash)
if (withExtension === false) {
var indexOfDot = path.lastIndexOf('.')
fileName = path.substr(indexOfSlash, indexOfDot - indexOfSlash)
}
} else {
fileName = path
}
return fileName
}
// Get relative path to the working directory for a path.
UTILS.GetRelativePath = function (path) {
var index = path.indexOf(UTILS.workingFolder)
if (index === 0) {
return path.substr(UTILS.workingFolder.length)
}
return path
}
// Get relative path to the working directory for a path. This returns in unix notation.
UTILS.GetRelativeReturnPath = function (path) {
var index = path.indexOf(UTILS.workingFolder)
if (index === 0) {
var tempPath = path.substr(UTILS.workingFolder.length)
tempPath = tempPath.replace(/\\/g, '/')
return tempPath
}
}
// Get the full path from a relative and a base path. In absence of base path, working directory is used.
UTILS.GetFullPath = function (relativePath, basePath) {
var origRelativePath = relativePath
if (relativePath.indexOf('..') !== -1 || relativePath.indexOf('/') === 0) {
this.RaiseException(Errors.InCorrectRelativePath, origRelativePath)
}
relativePath = relativePath.replace(/\//g, '\\')
if (relativePath.indexOf('\\.\\') !== -1) {
this.RaiseException(Errors.InCorrectRelativePath, origRelativePath)
}
if (basePath === undefined) {
basePath = UTILS.workingFolder
} else {
basePath = basePath.replace(/\//g, '\\')
if (basePath.charAt(basePath.length - 1) !== '\\') {
basePath = basePath + '\\'
}
}
if (relativePath.charAt(0) === '.') {
relativePath = relativePath.slice(1)
}
if (relativePath.charAt(0) === '\\') {
relativePath = relativePath.slice(1)
}
var fullPath = basePath + relativePath
return fullPath
}
// Get a unique name.
UTILS.GetUniqueName = function () {
return Math.random().toString().substr(2, 6)
}
// Creates a directory for the path provided.
UTILS.CreateDirectory = function (path) {
var outputFolder = Folder(path)
return outputFolder.create()
}
// Creates a directory for the outputs on the basis of relative path passed. In case nothing is passed a random directory is created in working folder.
UTILS.GetOutputDirectory = function (outputFolderPath) {
var outputPath = ''
var created = false
if (outputFolderPath) {
outputPath = UTILS.GetFullPath(outputFolderPath)
created = UTILS.CreateDirectory(outputPath)
var outputFolder = Folder(outputPath)
if (outputFolder.exists === false) {
UTILS.RaiseException(Errors.OutputDirError)
}
} else {
var tempName = ''
do {
tempName = 'tmp' + UTILS.GetUniqueName()
outputPath = UTILS.GetFullPath(tempName)
created = UTILS.CreateDirectory(outputPath)
} while (!created)
}
UTILS.outputFolder = outputPath
return outputPath
}
// Setup to do the logging.
UTILS.InitiateLogging = function () {
UTILS.Logs = []
}
UTILS.OpenLogFileHandle = function () {
if (UTILS.createSeparateLogFile === true) {
logFileObject = new File(UTILS.GetFullPath(UTILS.logFilePath))
var exists = false
if (logFileObject.open('read')) {
exists = true
}
UTILS.Log('Creating log file at ' + UTILS.GetFullPath(UTILS.logFilePath))
if (exists) {
logFileObject.close()
logFileObject.open('append')
} else {
logFileObject.open('write')
}
}
}
// Ends logging.
UTILS.TerminateLogging = function () {
if (UTILS.createSeparateLogFile === true) {
logFileObject.close()
}
}
// This logs any information.
UTILS.Log = function (log) {
var logText
if (log === undefined) {
logText = ''
} else if (typeof primaryLog !== 'string') {
logText = JSON.stringify(log)
} else {
logText = log
}
if (UTILS.createSeparateLogFile === true) {
// Write to file.
if (logFileObject) {
if (UTILS.Logs.length > 0) {
for (var itr = 0; itr < UTILS.Logs.length; itr++) {
logFileObject.writeln(UTILS.Logs[itr])
}
UTILS.Logs = []
}
logFileObject.writeln(logText)
} else {
UTILS.Logs.push(logText)
}
} else {
UTILS.Logs.push(logText)
}
}
UTILS.WriteToFile = function (data, fileName) {
var fileURL, newFile
var exists = false
var suffix = ''
var counter = 1
if (fileName === undefined) {
fileName = UTILS.GetUniqueName()
}
do {
fileURL = UTILS.GetFullPath(fileName + suffix + '.json')
newFile = File(fileURL)
if (newFile.open('read')) {
exists = true
suffix = counter++
newFile.close()
} else {
exists = false
}
} while (exists)
newFile.encoding = 'UTF8'
newFile.open('write')
if (newFile.write(JSON.stringify(data))) {
UTILS.Log('Data was successfully written')
newFile.close()
return (fileName + suffix + '.json')
} else {
UTILS.Log('Data write failed')
newFile.close()
}
}
UTILS.CloseAllOpenDocuments = function () {
UTILS.Log('Closing all the documents')
app.documents.everyItem().close(SaveOptions.NO)
}