-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib-scriptable.js
More file actions
806 lines (713 loc) · 27.2 KB
/
lib-scriptable.js
File metadata and controls
806 lines (713 loc) · 27.2 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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
/* globals args DocumentPicker Alert FileManager WebView Safari Script */
/* globals Pasteboard DatePicker importModule */
///<reference path="../types/scriptable.d.ts" />
///<reference path="../types/lib.d.ts" />
const {
DatePicker, Request, Alert, DocumentPicker, FileManager, WebView, args,
Script, Safari, Notification, Pasteboard, importModule, Data
} = /** @type {Scriptable}*/(/** @type {any}*/(this));
/** @type {import("./external/external.cjs")} */
const external = importModule('./external/external.cjs.js');
/** @type {ArgStructureOutputType|undefined} */
let outputType = undefined;
const scriptableCopyUri = 'scriptable:///run' +
'?scriptName=ScriptableHelperCopy' +
'&text=';
let logView = /** @type {Scriptable.WebView|null} */(null);
let log = '';
let status = '';
const b64Digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const b64Map = /** @type {Object<string, number>} */({});
for(let i=0; i < b64Digits.length; i += 1) {
b64Map[b64Digits.charAt(i)] = i;
}
/**
* The same as the DOM's `encodeURIComponent` function.
* @param {string} str the string to encode
* @return {string} the encoded string
*/
const encodeUriComponent = str => {
const hexDigits = '0123456789ABCDEF';
let ret = '';
for(let i = 0; i < str.length; i += 1) {
const char = str.charCodeAt(i);
const isValid =
(char >= 48 && char <= 57 ) || // 0-9
(char >= 97 && char <= 122) || // a-z
(char >= 65 && char <= 90 ) || // A-Z
(char >= 39 && char <= 42 ) || // '()*
(char >= 45 && char <= 46 ) || // -.
char === 95 || char === 126 || char === 33; // _~!
ret += isValid
? str[i]
: '%' + hexDigits[(char & 0xF0) >> 4] + hexDigits[(char & 0x0F)];
}
return ret;
};
/**
* The same as the DOM's `decodeURIComponent` function.
* @param {string} input the string to decode
* @return {string|null} decoded text, or null if `input` is malformed
*/
const decodeUriComponent = (input) => {
const length = input.length;
let result = "";
for (let k = 0; k < length; k++) {
let chr = input[k];
if (chr === '%') {
let byte = +`0x${input.slice(k+1, k+3)}`;
if (Number.isNaN(byte) || k + 2 >= length) { return null; }
k += 2;
if (byte < 0x80) {
chr = String.fromCharCode(byte);
} else {
let n = Math.clz32(byte ^ 0xFF) - 24;
if (n < 2 || n > 4) { return null; }
let value = byte & (0x3F >> n);
if (k + (3 * (n - 1)) >= length) { return null; }
for (let j = 1; j < n; j++) {
if (input[++k] !== '%') { return null; }
let byte = +`0x${input.slice(k+1, k+3)}`;
if (Number.isNaN(byte) || ((byte & 0xC0) != 0x80)) {
return null;
}
k += 2;
value = (value<<6) + (byte & 0x3F);
}
if (value >= 0xD800 && value < 0xE000 || value >= 0x110000) {
return null;
}
if (value < 0x10000) {
chr = String.fromCharCode(value);
} else {
const low = ((value - 0x10000) & 0x3FF) + 0xDC00;
const high = (((value - 0x10000) >> 10) & 0x3FF) + 0xD800;
chr = String.fromCharCode(high) + String.fromCharCode(low);
}
}
}
result += chr;
}
return result;
};
/**
* The same as the browser's `atob` function.
* @param {string} data the data to decode from base64
* @return {string|null} the text, or null if `data` is not valid base64
*/
const atob = (data) => {
const disallowed = /[^\d+/a-z]/i;
let string = data.replaceAll(/[\t\n\f\r ]+/g, '');
let output = '';
let position = 0;
let bc = 0;
let chr = '';
let bs = 0;
if (string.length % 4 === 0) {
string = string.replace(/[=]{1,2}$/, '');
}
const length = string.length;
if (length % 4 === 1 || disallowed.exec(string)) {
return null;
}
while (position < length) {
chr = string.charAt(position++);
bs = bc % 4 ? bs * 64 + b64Map[chr] : b64Map[chr];
if (bc++ % 4) {
output += String.fromCharCode(255 & bs >> (-2 * bc & 6));
}
}
return output;
};
/**
* The same as the browser's `btoa` function.
* @param {string} text the text to encode into base64
* @return {string|null} base64 text, or `null` if it could not encode
*/
const btoa = text => {
let output = '';
let position = 0;
let map = b64Digits;
let block = 0
while (text.charAt(position) || (map = '=', position % 1)) {
position += 3 / 4;
const charCode = text.charCodeAt(position);
if (charCode > 0xFF) {
return null;
}
block = block << 8 | charCode;
output += map.charAt(63 & block >> 8 - position % 1 * 8);
}
return output;
};
/**
* Given an array of bytes, create a base64 string.
* @param {number[]|Uint8Array} bytes the byte list to encode
* @return {string} the bytes, converted to base-64
*/
const bytesToBase64 = bytes => {
let result = '';
const remainder = bytes.length % 3;
for(let i = 0; i < bytes.length; i += 3) {
const byte1 = Math.floor(bytes[i] || 0);
const byte2 = Math.floor(bytes[i + 1] || 0);
const byte3 = Math.floor(bytes[i + 2] || 0);
const bitmap = (byte1 << 16) | (byte2 << 8) | byte3;
result +=
b64Digits.charAt(bitmap >> 18 & 63) +
b64Digits.charAt(bitmap >> 12 & 63) +
b64Digits.charAt(bitmap >> 6 & 63) +
b64Digits.charAt(bitmap & 63);
}
return remainder
? result.slice(0, remainder - 3) + '==='.substring(remainder)
: result;
};
// Helper Functions
/**
* Parses a JSON string, returning `null` if it fails to parse.
* @param {string|null} json the JSON to parse
* @param {boolean} [adaptJs] if explicitly true, also read single-export JS
* @return {Object|null}
*/
const jsonParse = (json, adaptJs) => {
if (!json) { return null; }
const removeExport = /^export const \w+\s*=\s*/gm;
const jsonNoExport = adaptJs ? json.replace(removeExport, '') : json;
try { return external.json5.parse(jsonNoExport); } catch(e) { }
return null;
};
/**
*
* @param {string} path
* @return {string}
*/
const resolvePath = path => {
const fm = FileManager.iCloud();
const rootPath = fm.documentsDirectory();
return path
.replace(/^[$.]/, rootPath)
.replace(/\/\//g, '/');
};
/**
* Saves an argument structure object to the argument cache.
* @param {ArgStructure} argStructure the argument structure to write
* @return {Promise<void>} a promise resolving after the file is written
*/
const cacheArgStructure = async (argStructure) => {
const argPath = `$/args/${argStructure.name}.json`;
const argText = JSON.stringify(argStructure, null, ' ');
FileManager.local().writeString(resolvePath(argPath), argText);
};
/**
* Given HTML body content, returns an HTML page.
* @param {string} statusText the content to put in the status div
* @param {string} logText the content to put in the log div
* @return {string} the full HTML content
*/
const html = (statusText, logText) => external.markedTemplates.html(
`<div class="status">${statusText}</div><div class="log">${logText}</div>`,
`body { font-family: -apple-system, Helvetica, sans-serif; }
.status { font-size: 30px; }
.log { font-size: 20px; }`
);
/**
* Displays a "logging" window showing a status and list of log lines.
* @param {string|null} statusMessage a new status, or null to not update
* @param {string|null} logMessage a new log to append, or null to not append
*/
const showWebLog = (statusMessage, logMessage) => {
status = statusMessage === null ? status : statusMessage;
log += logMessage === null ? '' : logMessage + '<br/>';
const isNewWebView = !logView;
logView = logView || new WebView();
logView.loadHTML(html(status, log));
if (isNewWebView) {
logView.present();
}
};
/**
* Formats the "help" messages passed into the getInput function.
* @param {string} help the message to format
* @return {string} the formatted message
*/
const formatHelp = help => help.replace(/[ \n\r]+/gm, ' ');
/**
* @param {ObjectMap<string>} map the key/value map to encode
* @return {string} the encoded map
*/
const encodeUriMap = map =>
Object.entries(map)
.map(([k, v]) => encodeUriComponent(k) + '=' + encodeUriComponent(v))
.join('&');
module.exports.encodeURIComponent = encodeUriComponent;
module.exports.decodeURIComponent = decodeUriComponent;
module.exports.atob = atob;
module.exports.btoa = btoa;
/**
* Waits for a given number of milliseconds before resolving.
* @param {number} time the number of milliseconds to wait before resolving
* @return {Promise<void>} a promise resolving after `time` milliseconds
*/
module.exports.wait = time => new Promise(yes => setTimeout(() => yes(), time));
/**
* Given a string, converts it into a list of byte values.
* @param {string} text the string to convert into bytes
* @return {Uint8Array|number[]} the bytes making up the string
*/
module.exports.stringToBytes = text => Data.fromString(text).getBytes();
/**
* Given any object, returns it if it is a string, otherwise returns `''`.
* @param {string} str the maybe-string to return
* @return {string} the passed in `str` if it is a string, otherwise `''`
*/
module.exports.string = str => typeof str === 'string' ? str : '';
/**
* Combines multiple path segments into a single path.
* @param {...string} segments the path segments to join together
* @return {string} a combination of all segments
*/
module.exports.pathJoin = (...segments) => {
/** @type {string[]} */
const output = [ ];
for(const segment of segments.flatMap(x => x.split('/'))) {
if (segment === '..') {
output.pop();
} else if (segment !== '' && segment !== '.') {
output.push(segment);
}
}
return (segments[0].charAt(0) === '/' ? '/' : '') + output.join('/');
};
/**
* This should be called at the beginning of every script. It gathers
* input from the user in an environment-specific way. For instance, in
* the CLI each argument is pulled from the flags, whereas in Scriptable
* an argument-type-specific chooser UI is presented for each argument.
*
* It returns a promise that resolves to an object. This object has one
* key/value pair per `args[]` element. The keys correspond to the
* `args[*].name` values, while the values are the user's responses as
* strings (or booleans, for each `args[*].type === "boolean"`).
*
* Alternatively, the returned promise may resolve to `null`. This signals
* that the script should immediately exit. For example, `null` is returned
* on a CLI given `-h` or `--help` flags, or when Shortcuts requests
* argument metadata.
*
* @param {ArgStructure} argStructure describes all inputs the user should
* provide. See the "Helper Types" section of `api.md` for full details.
* @param {boolean} [cacheArgs] if `true`, write these args to the cache
* @return {Promise<ObjectMap<boolean|string>|null>} Resolves to an object
* with a key/value for each desired argument, or `null` if this script
* should immediately terminate (ex: `--help` was asked for).
*/
module.exports.getInput = async (argStructure, cacheArgs) => {
const result = /** @type {ObjectMap<boolean|string>} */({});
let shareIndex = 0;
outputType = argStructure.outputType;
const argSpecs = argStructure.args ?? [ ];
const command = args.plainTexts[1] || args.urls[1] || '';
if (command === 'shortcuts.getArgs') {
await cacheArgStructure(argStructure);
const fm = FileManager.local();
argStructure.bookmarks = fm.allFileBookmarks()
.filter(x => x.source === 'siri_shortcuts')
.map(x => x.name);
Script.setShortcutOutput(JSON.stringify(argStructure));
Script.complete();
return null;
}
if (cacheArgs) {
await cacheArgStructure(argStructure);
}
if (command === 'shortcuts.setArgs') {
const fm = FileManager.local();
try {
const jsonString = args.plainTexts[0] || args.urls[0] || '{}';
const argMap = JSON.parse(jsonString);
for(const arg of argSpecs) {
const value = argMap[arg.name];
if (arg.type === 'pathFile' || arg.type === 'pathFolder') {
try {
argMap[arg.name] = fm.bookmarkedPath(value) || value;
} catch(e) {
argMap[arg.name] = value;
}
}
}
return argMap;
} catch(e) { return { }; }
}
for(const arg of argSpecs) {
const sharedArg = args.plainTexts[shareIndex] || args.urls[shareIndex];
if (arg.share && typeof sharedArg === 'string') {
result[arg.name] = sharedArg;
shareIndex += 1;
} else if (arg.type === 'pathFolder') {
const popup = new Alert();
popup.title = arg.name;
popup.message = formatHelp(arg.help);
popup.addAction('Choose Folder');
await popup.presentAlert();
result[arg.name] = await DocumentPicker.openFolder();
} else if (arg.type === 'pathFile') {
const popup = new Alert();
popup.title = arg.name;
popup.message = formatHelp(arg.help);
popup.addAction('Choose File');
await popup.presentAlert();
result[arg.name] = arg.pathType
? (await DocumentPicker.open([ arg.pathType ]))[0]
: await DocumentPicker.openFile();
} else if (arg.type === 'enum' && arg.choices.length) {
const menu = new Alert();
menu.title = arg.name;
menu.message = formatHelp(arg.help);
arg.choices.forEach(x => menu.addAction(x.title));
const chosen = await menu.presentSheet();
result[arg.name] = arg.choices[chosen || 0].code;
} else if (arg.type === 'boolean') {
const popup = new Alert();
popup.title = arg.name;
popup.message = formatHelp(arg.help);
popup.addAction('No');
popup.addAction('Yes');
result[arg.name] = (await popup.presentAlert()) === 1;
} else if (arg.type === 'string') {
const popup = new Alert();
popup.title = arg.name;
popup.message = formatHelp(arg.help);
popup.addTextField('Type a Value Here', '');
popup.addAction('OK');
await popup.presentAlert();
result[arg.name] = popup.textFieldValue(0);
} else if (arg.type === 'date') {
const picker = new DatePicker();
picker.initialDate = new Date();
const picked = await picker.pickDateAndTime();
result[arg.name] = picked.getTime().toString();
}
}
return result;
};
/**
* Compiles an HTML file at a given path and displays the result.
* @param {string} appPath the path to the directory to compile
*/
module.exports.compile = async (appPath) => {
const srcRegex = /src\s*=\s*['"]([^'"]*)['"]/;
const hrefRegex = /href\s*=\s*['"]([^'"]*)['"]/;
const relRegex = /rel\s*=\s*['"]stylesheet['"]/;
const dotRegex = /^\.\//;
appPath = resolvePath(appPath);
const fm = FileManager.iCloud();
const htmlPath = fm.joinPath(appPath, 'index.html');
/** @type {(path: string) => string} */
const loadFile = path => {
const content = fm.readString(path);
if (content !== null) { return content; }
return '';
};
const html = loadFile(htmlPath);
const transformedHtml = html.replace(/<(script|link)[^>]*>/g, tag => {
const srcMatch = tag.match(srcRegex);
const hrefMatch = tag.match(hrefRegex);
const src = srcMatch && srcMatch[1];
const href = hrefMatch && hrefMatch[1];
const isStyle = relRegex.test(tag);
if (src) {
const resPath = fm.joinPath(appPath, src.replace(dotRegex, ''));
const resText = loadFile(resPath) || 'null';
return tag.replace(srcRegex, `data-name="${src}"`) + '\n' +
resText + '\n';
}
if (isStyle && href) {
const resPath = fm.joinPath(appPath, href.replace(dotRegex, ''));
const resText = loadFile(resPath) || '/* CSS NOT LOADED */';
return '<style>\n' + resText + '\n</style>';
}
return tag;
});
WebView.loadHTML(transformedHtml, '', undefined, true);
};
/**
* Displays some HTML to the user.
* @param {string} html the html to show
*/
module.exports.showHtml = async (html) => {
WebView.loadHTML(html, '', undefined, true);
};
/**
* Downloads some text from a given URL and returns the result.
* @param {string} url the URL to download JSON from
* @return {Promise<string>} downloaded string, or null if invalid
*/
module.exports.downloadText = async (url) =>
await (new Request(url)).loadString();
/**
* Downloads JSON from a given URL and returns the result.
* @param {string} url the URL to download the JSON from
* @return {Promise<Object|null>} downloaded JSON or null if invalid
*/
module.exports.downloadJson = async (url) => {
const searchReq = new Request(url);
return jsonParse(await searchReq.loadString());
};
/**
* Downloads a file from a URL and stores it at the given filePath.
* @param {string} url the URL to download from
* @param {string} filePath the local path to store the file
* @return {Promise<number>} resolves to the status code for the request
*/
module.exports.downloadFile = async (url, filePath) => {
const fileReq = new Request(url);
const file = await fileReq.load();
const statusCode = Number(fileReq.response['statusCode']) || 0;
if (statusCode === 200) {
FileManager.local().write(resolvePath(filePath), file);
}
return statusCode;
};
/**
* POSTs some form data to a given URL.
* @param {string} url the url to upload the form to
* @param {ObjectMap<string>} form the form data to submit
* @return {Promise<string>} a promise resolving with the response body
*/
module.exports.uploadForm = async (url, form) => {
const formEncoded = encodeUriMap(form);
const request = new Request(url);
request.method = 'POST';
request.headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': formEncoded.length.toString()
};
request.body = formEncoded;
return await request.loadString();
};
/**
* Sends a generic request, returning the response string.
* @param {string} url the URL to send the request to
* @param {ObjectMap<string>} [headers] the map of header data to send
* @param {string} [body] the body string data to send
* @param {'GET'|'POST'|'PUT'} [method='POST'] the HTTP method to use
* @return {Promise<string>} a promise resolving to the response body
*/
module.exports.sendRequest = async (url, headers, body, method) => {
const request = new Request(url);
request.method = method ?? 'POST';
request.headers = headers ?? { };
request.body = body ?? '';
return await request.loadString();
};
/**
* POSTs a file with a multipart form to a given URL.
* @param {string} url the url to upload the data to
* @param {ObjectMap<string>} options any extra parameters to add to body
* @param {string} filePath the path to the file to upload
* @return {Promise<string>} a promise resolving with the response body
*/
module.exports.uploadFile = async (url, options, filePath) => {
const request = new Request(url);
request.method = 'POST';
for(const key in options) {
request.addParameterToMultipart(key, options[key]);
}
request.addFileToMultipart(filePath, 'files[]');
return await request.loadString();
};
/**
* Reads a text file at a given path and returns the result.
* @param {string} textPath the file path to the text file
* @return {Promise<string>} resolves to the text content
*/
module.exports.readText = async (textPath) =>
FileManager.local().readString(resolvePath(textPath));
/**
* Reads a JSON file at a given path and returns the result.
* @param {string} jsonPath the file path to the JSON file
* @return {Promise<Object|null>} resolves to the object or null if invalid
*/
module.exports.readJson = async jsonPath =>
jsonParse(FileManager.local().readString(resolvePath(jsonPath)), true);
/**
* Reads a binary file at a given path and returns the result.
* @param {string} bytesPath the file path to the binary file
* @return {Promise<Uint8Array|null>} resolves to the content bytes
*/
module.exports.readBytes = async (bytesPath) =>
new Uint8Array(FileManager.local().read(resolvePath(bytesPath)).getBytes());
/**
* Writes a string to a text file.
* @param {string} textPath the file path to the text file to write
* @param {string} text the text to write
* @return {Promise<void>} a promise resolving after the file is written
*/
module.exports.writeText = async (textPath, text) => {
FileManager.local().writeString(resolvePath(textPath), text);
};
/**
* Writes an object to a JSON file.
* @param {string} jsonPath the file path to the JSON file to write
* @param {Object} json the JSON object to write
* @return {Promise<void>} a promise resolving after the file is written
*/
module.exports.writeJson = async (jsonPath, json) => {
const fm = FileManager.local();
fm.writeString(resolvePath(jsonPath), JSON.stringify(json, null, ' '));
};
/**
* Writes an array of bytes to a file at a particular path.
* @param {string} bytesPath the file path to the binary file to write
* @param {number[]|Uint8Array} bytes the list of bytes to write
* @return {Promise<void>} a promise resolving after the file is written
*/
module.exports.writeBytes = async (bytesPath, bytes) => {
const data = Data.fromBase64String(bytesToBase64(bytes));
FileManager.local().write(resolvePath(bytesPath), data);
};
/**
* Saves an argument structure object to the argument cache.
* @param {ArgStructure} argStructure the argument structure to write
* @return {Promise<void>} a promise resolving after the file is written
*/
module.exports.cacheArgStructure = cacheArgStructure;
/**
* Lists the files within a particular directory.
* @param {string} folderPath the path to the folder whose children this lists
* @return {Promise<string[]>} a promise resolving with the list of file names
*/
module.exports.listFiles = async (folderPath) => {
//const fileNames = filePaths.map(x => x.replace(/^.*\/([^/]+)\/?$/, '$1'));
const local = FileManager.local();
return local.fileExists(folderPath) ? local.listContents(folderPath) : [ ];
};
/**
* Gets whether or not a path is a file that exists.
* @param {string} filePath the path to the potential file
* @return {Promise<boolean>} true if the path is an existing file
*/
module.exports.isFile = async (filePath) =>
FileManager.local().fileExists(filePath) &&
!FileManager.local().isDirectory(filePath);
/**
* Gets whether or not a given path is a directory
* @param {string} folderPath the path to the file or folder
* @return {Promise<boolean>} true if a folder is at `folderPath`
*/
module.exports.isDirectory = async (folderPath) =>
FileManager.local().isDirectory(folderPath);
/**
* Gets the size of a file in kilobytes (floored).
* @param {string} filePath the path to the file whose size we get
* @return {Promise<number>} the size of the file, in kilobytes
*/
module.exports.getFileSize = async (filePath) =>
FileManager.local().fileSize(filePath);
/**
* Gets the last modified date of a particular file.
* @param {string} filePath the path to the file whose date we get
* @return {Promise<Date|null>} this file's last-modified date
*/
module.exports.getFileModificationDate = async (filePath) =>
FileManager.local().modificationDate(filePath);
/**
* Creates a folder at a given path.
* @param {string} folderPath the path to the folder to create
* @return {Promise<boolean>} true if the folder was created
*/
module.exports.makeDirectory = async folderPath => {
FileManager.local().createDirectory(folderPath, true);
return true;
};
/**
* Moves a file from one path to another.
* @param {string} sourcePath the path to read a file from
* @param {string} destinationPath the path to move the file to
* @return {Promise<boolean>} resolves to true when move is successful
*/
module.exports.moveFile = async (sourcePath, destinationPath) => {
if (sourcePath !== destinationPath) {
FileManager.local().move(sourcePath, destinationPath);
}
return true;
};
/**
* Copies a file from one path to another.
* @param {string} sourcePath the path to read a file from
* @param {string} destinationPath the path to copy the file to
* @return {Promise<boolean>} resolves to true when copy is successful
*/
module.exports.copyFile = async (sourcePath, destinationPath) => {
const local = FileManager.local();
if (!local.fileExists(sourcePath)) {
return false;
}
if (sourcePath !== destinationPath) {
if (local.fileExists(destinationPath)) {
local.remove(destinationPath);
}
local.copy(sourcePath, destinationPath);
}
return true;
};
/**
* Opens a given URL in safari or the program handling the given protocol.
* @param {string} url the url to open
*/
module.exports.open = url => { Safari.open(url); };
/**
* Prints a transient info status message.
* @param {string} msg the message. Should not be important.
*/
module.exports.status = (msg) => showWebLog(msg, null);
/**
* Prints a permanent informational log message.
* @param {string} msg the message to log until the end of the app
*/
module.exports.log = (msg) => showWebLog(null, msg);
/**
* Prints the final output of the program.
* @param {string|null} title a string describing the final output
* @param {string|number|boolean} data the easy-to-copy final output
*/
const output = (title, data) => {
const message = '' + data;
const messageUri = encodeURIComponent(message);
if (title) {
const notification = new Notification();
notification.title = title;
notification.subtitle = message;
notification.addAction('Copy', scriptableCopyUri + messageUri);
notification.schedule();
}
if (outputType === 'data') {
Pasteboard.copyString(message);
}
Script.setShortcutOutput(message);
Script.complete();
};
module.exports.output = output;
/**
* Shows an error message.
* @param {string} title the title of the script that threw
* @param {string|number|boolean} data the easy-to-copy final output string
*/
module.exports.error = (title, data) => { output('Error: ' + title, data); };
/**
* Puts a string onto the clipboard.
* @param {string} data the string to put onto the clipboard
*/
module.exports.copy = (data) => { Pasteboard.copyString(data); };
/**
* Gets the data that's on the clipboard
* @return {string} the data that was on the clipboard
*/
module.exports.paste = () => Pasteboard.pasteString();
/**
* A collection of useful third-party libraries.
* See lib/external/entry.js.
*/
module.exports.external = external;