-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.js
863 lines (801 loc) · 31.2 KB
/
api.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
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
// #region Typedefs
/**
* @typedef {Object} TokenObject
* @property {string} auth The authentication token to the remote endpoint
*/
/**
* @typedef {Object} CredentialsObject
* @property {string} user The username to use for authentication
* @property {string} pass The password to use for authentication
*/
/**
* @typedef {Object} InternalResult
* @property {Boolean} success True if the action was successful, otherwise false
* @property {(undefined|Error)} error Undefined if the request didn't throw an error, otherwise the error object itself
* @property {Boolean} session True if the action failed due to issues with the session authentication, otherwise false
* @property {Any} result The result of the action
*/
/**
* @typedef {Object} MultipartMixedResult
* @property {Boolean} success True if the action was successful, otherwise false
* @property {(undefined|Error)} error Undefined if the request didn't throw an error, otherwise the error object itself
* @property {Boolean} session True if the action failed due to issues with the session authentication, otherwise false
* @property {(undefined|Number)} statusCode The status code of the response, undefined if success is false
* @property {(undefined|string)} content The response body, undefined if success if false
*/
/**
* @typedef {Object} AbstractedResult
* @property {Boolean} success The internal function's success
* @property {Any} data The result of the internal function
*/
/**
* @typedef {Object} RemoteEntry
* @property {string} id The ID of the remote entry
* @property {string} name The name of the remote entry
* @property {Boolean} isDir True if the remote entry is a directory, otherwise false
*/
/**
* Called when the file transfer progress updates
* @callback InternalTransferProgress
* @param {number} progress The current offset where the transfer is happening from
*/
/**
* Called when the file transfer is done
* @callback InternalTransferDone
* @param {InternalResult} result The result of the file transfer
*/
// #endregion
// #region Imports and Globals
/**
* Import fs for cheking file size and existence
*/
const fs = require('fs');
/**
* Import path for getting the name of a file to be uploaded
*/
const path = require('path');
/**
* Module for web requests
*/
const request = require('request');
/**
* Low level nodejs web request module over https
*/
const https = require('https');
/**
* API logging utility getter
*/
const { getAPILogger } = require('./logging');
// const httpsProxy = require('./https-proxy'); // For debugging purposes
/**
* History of visited folders
* @type {Array<string>}
*/
let pathStack = [];
/**
* Store session id and local storage data
* @type {TokenObject}
*/
let tokens = {};
/**
* Store username and password for auto re-login in case of a session timeout
* @type {CredentialsObject}
*/
let creds = {};
/**
* Indicates whether the API should print debug messages
*/
let log = getAPILogger();
/**
* Host to send the requests to
* @type {string}
*/
let wdHost = '';
// #endregion
// #region Util functions
/**
* Send multipart request to the wdc device
* @param {String} mpData Multipart mixed data to send
* @param {String} auth Authentication token
* @returns {Promise<MultipartMixedResult>} The result of the multipart mixed request
*/
function multipartMixed(mpData, auth) {
return new Promise((resolve) => {
// process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0; // Required for https proxy debugging
const boundary = '3cb3d25a-a9b9-4906-a267-9b65ae299d0f'; // Some random boundary I copied from one of the delete folder requests
const data = `--${boundary}\r\n${mpData}\r\n--${boundary}--`;
// const proxyAgent = new httpsProxy({proxyHost: 'localhost', proxyPort: 8080});
// NodeJS https module request options
const options = {
hostname: `${wdHost}.remotewd.com`,
port: 443,
path: '/sdk/v1/batch',
method: 'POST',
headers: {
'authorizaiton': auth,
'content-type': 'multipart/mixed; boundary=' + boundary,
'content-length': Buffer.byteLength(data),
},
// agent: proxyAgent,
};
const req = https.request(options, (response) => {
if (response.statusCode === 401) {
resolve({ success: false, error: undefined, session: false });
return;
}
let currentData = '';
response.on('data', d => { // Collect response data
currentData += d;
});
response.on('error', (error) => { // Check for errors
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
resolve({ success: false, error: error, session: true });
});
response.on('end', () => resolve({ success: true, error: undefined, session: true, status: response.statusCode, content: currentData })); // Response finished
});
req.write(data); // Send the data to the server
req.end(); // Finish sending the data
});
}
/**
* Format the time based on the cloud's format for mTime in the file upload request
* WARNING: the GMT time offset is hardcoded to +02:00 for now
* @returns {string} The formatted time
*/
function getFormattedTime() { // TODO: set the GMT offset dynamically
const date = new Date();
// 0 prefix function
const pf = (input) => {
if (input.toString().length < 2) return '0' + input.toString();
return input;
};
const result = `${date.getFullYear()}-${pf(date.getMonth() + 1)}-${pf(date.getDate())}T${pf(date.getHours())}:${pf(date.getMinutes())}:${pf(date.getSeconds())}+02:00`;
return result;
}
/**
* Yield the specified file's content in blocks
* @param {String} filePath The path ofthe file on the local system
*/
function* getFileContent(filePath) {
let currentOffset = 0;
const totalSize = fs.statSync(filePath).size;
const bufferSize = 20480; // Block size, each loop reads this many bytes
const fd = fs.openSync(filePath, 'r');
const buffer = Buffer.alloc(bufferSize); // Buffer to read file contents to
while (true) {
if (currentOffset >= totalSize) break;
const bytesRead = fs.readSync(fd, buffer, 0, bufferSize, currentOffset > totalSize ? currentOffset - totalSize : currentOffset);
const isDone = bytesRead != bufferSize; // EOF
yield { buffer, bytesRead, currentOffset, isDone };
if (isDone) break;
currentOffset += bytesRead;
}
}
/**
* Retry an abstracted function a certain if failed
* @param {number} tryLimit The number of maxiumum executions of the specified function
* @param {string} actionName The friendly display name of the action
* @param {Function} abstractedFunction The abstracted function to call to exectue the action
* @param {Array} afArgs An array of arguments to pass to the abstracted function
* @returns {any} The result of the abstracted function
*/
async function retryLimited(tryLimit, actionName, abstractedFunction, afArgs) {
let tryCounter = 0;
/**
* Execute the abstracted function the given amount of times if failing
* @returns {AbstractedResult}
*/
const callAbstracted = async () => {
if (tryCounter > tryLimit) {
return { success: false };
}
tryCounter++;
if (tryCounter > 1) log.debug(`Attempt ${tryCounter} to ${actionName}`);
/**
* @type {AbstractedResult}
*/
const result = await abstractedFunction(...afArgs);
if (!result.success) return await callAbstracted();
else return { success: true, data: result.data };
};
const recursiveResult = await callAbstracted();
if (recursiveResult.success) return recursiveResult.data;
else throw new Error(`Tried to ${actionName} 10 times and failed`);
}
/**
* Re-authenticate the client and try the current action again
* @param {Function} func The function to call after re-authenticating
* @param {Array} args An array of arguments to pass to the function
* @returns {Promise} The result of the abstracted function
*/
async function authRetry(func, args) {
log.warn('Re-authentication initiated');
await authenticate(creds.user, creds.pass); // Authenticate with cached credentials
return func(...args); // Re-call the parent function
}
// #endregion
// #region Internal functions
/**
* Login to your wdc device
* @param {String} username The username to use for wdc login
* @param {String} password The password to use for wdc login
* @returns {Promise<Boolean>} Promise, true if authentication is successful, otherwise false
*/
function login(username, password) {
return new Promise((resolve) => {
const authUrl = 'https://wdc.auth0.com/oauth/ro';
const wdcAuth0ClientID = '56pjpE1J4c6ZyATz3sYP8cMT47CZd6rk';
request.post(authUrl, {
body: JSON.stringify({ // Auth0 specific request, copied from the wdc login request to the authUrl endpoint
client_id: wdcAuth0ClientID,
connection: 'Username-Password-Authentication',
device: '123456789',
grant_type: 'password',
password: password,
username: username,
scope: 'openid offline_access',
}),
headers: {
'content-type': 'application/json',
}
}, (error, response, body) => {
if (response.statusCode === 401) {
resolve(false);
return;
}
if (error) {
log.fatal('Error occurred while authenticating to server');
log.error(error);
resolve(false);
return;
}
tokens.auth = 'Bearer ' + JSON.parse(body).id_token; // Save the Bearer authorization token
resolve(true);
});
});
}
/**
* List files in a specific folder
* @param {String} authToken The authentication token
* @param {String} subPath The folder to list the entries of
* @returns {Promise<InternalResult>} The result of the file listing
*/
function ls(authToken, subPath) {
return new Promise((resolve) => {
const listFilesUrl = `https://${wdHost}.remotewd.com/sdk/v2/filesSearch/parents?ids=${subPath}&fields=id,mimeType,name&pretty=false&orderBy=name&order=asc`;
request.get(listFilesUrl, { headers: { 'authorization': authToken } }, (error, response, body) => {
if (response.statusCode === 401) {
resolve({ success: false, error: undefined, session: false });
return;
}
if (error) {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
resolve({ success: false, error: error, session: true });
return;
}
const obj = JSON.parse(body);
if (obj.files === undefined) {
resolve({ success: true, error: undefined, session: true, result: [] });
return;
}
const parsedResult = JSON.parse(body).files.map(item => {
return {
name: item.name,
id: item.id,
isDir: item.mimeType == 'application/x.wd.dir',
};
});
resolve({ success: true, error: undefined, session: true, result: parsedResult });
});
});
}
/**
* Create a new directory in the specified directory
* @param {String} authToken The authentication token
* @param {String} subPath The folder to create the new folder in
* @param {String} folderName The name of the new folder
* @returns {Promise<InternalResult>} The result of the create directoy action
*/
function mkdir(authToken, subPath, folderName) {
return new Promise((resolve) => {
const mkdirUrl = `https://${wdHost}.remotewd.com/sdk/v2/files?resolveNameConflict=true`;
request.post(mkdirUrl, {
headers: { 'authorization': authToken }, multipart: [
{
body: JSON.stringify({ // Directory creation parameters copied from wdc request to mkdirUrl endpoint
'name': folderName,
'parentID': subPath,
'mimeType': 'application/x.wd.dir',
})
}
]
}, (error, response) => {
if (response.statusCode === 401) {
resolve({ success: false, error: undefined, session: false });
return;
}
if (error) {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
resolve({ success: false, error: error, session: true });
return;
}
const locationParts = response.headers['location'].split('/'); // ID of the new folder gets sent in the location header
resolve({ success: true, error: undefined, session: true, result: locationParts[locationParts.length - 1] });
});
});
}
/**
* Remove an entry from the wdc
* @param {String} authToken The authenticaiton token
* @param {String} entryID The ID of the entry to remove
* @returns {Promise<InternalResult>} The result of the delete action
*/
function rm(authToken, entryID) {
return new Promise(async (resolve) => {
// Request body copied from a folder delete request
const postBody = `Content-Id: 0\r\n\r\nDELETE /sdk/v2/files/${entryID} HTTP/1.1\r\nHost: ${wdHost}.remotewd.com\r\nAuthorization: ${authToken}\r\n\r\n`;
// Send multipart/mixed to the server (since request module doesn't support the /mixed multipart MIME)
const result = await multipartMixed(postBody, authToken);
if (!result.success) resolve(result);
else resolve({ success: result.status == 200, error: undefined, session: true, result: true });
});
}
/**
* Upload a file to the wdc
* @param {String} authToken The authentication token
* @param {String} subPath The folder ID to upload the file to
* @param {String} pathToFile Path to the file on the local system
* @param {InternalTransferProgress} reportCompleted Function to call with current offset
* @param {InternalTransferDone} reportDone Function to call when the upload is done
*/
function upl(authToken, subPath, pathToFile, reportCompleted, reportDone) {
/**
* Start a new file upload
* @param {string} activityID The activity ID returned by the upload init request
*/
const startUpload = (activityID) => {
const initUploadUrl = `https://${wdHost}.remotewd.com/sdk/v2/files/resumable?resolveNameConflict=1&done=false`;
request.post(initUploadUrl, {
headers: {
'authorization': authToken,
'x-activity-tag': activityID,
},
multipart: [
{
body: JSON.stringify({ // Request copied from a file upload request to the initUploadUrl endpoint
name: path.basename(pathToFile),
parentID: subPath,
mTime: getFormattedTime(),
})
},
{ body: '' }
]
}, (error, response) => {
if (response.statusCode === 401) {
reportDone({ success: false, error: undefined, session: false });
return;
}
if (error) {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
reportDone({ success: false, error: error, session: true });
return;
}
const fileUrl = `https://${wdHost}.remotewd.com${response.headers['location']}/resumable/content`;
uploadManual({ authorization: authToken, xActivityTag: activityID, url: fileUrl }, reportCompleted, reportDone, pathToFile); // Upload the file to the server
});
};
/**
* Start activity and get its ID
*/
const startActivity = () => {
request.post(`https://${wdHost}.remotewd.com/sdk/v1/activityStart`, { headers: { 'authorization': authToken } }, (error, response, body) => {
if (response.statusCode === 401) {
reportDone({ success: false, error: undefined, session: false });
return;
}
if (error) {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
reportDone({ success: false, error: error, session: true });
return;
}
const activityTag = JSON.parse(body).tag;
startUpload(activityTag); // Init the upload of the file
});
};
startActivity();
}
/**
* Upload file to the server in chunks
* @param {Object} data Object with requested header and url data for uploading
* @param {InternalTransferProgress} progressCallback Function to call with the current offset
* @param {InternalTransferDone} doneCallback Function to call when the upload is done
* @param {String} filePath The path of the file on the local system
*/
async function uploadManual(data, progressCallback, doneCallback, filePath) {
for (const { buffer, bytesRead, currentOffset, isDone } of getFileContent(filePath)) {
const currentUrl = `${data.url}?offset=${currentOffset}&done=${isDone}`; // Construct endpoint url
progressCallback(currentOffset); // Update upload progress
// Convert request callback to awaitable promise
const uploadBytes = () => {
return new Promise((resolve) => {
request.put(currentUrl, { headers: { 'authorization': data.authorization, 'x-activity-tag': data.xActivityTag }, body: buffer.slice(0, bytesRead) }, (error, response) => {
if (response.statusCode === 401) {
resolve({ success: false, error: undefined, session: false });
return;
}
if (error) {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
reportDone({ success: false, error: error, session: true });
return;
}
resolve({ success: true, error: undefined, session: true });
});
});
};
const uploadResult = await uploadBytes(); // Upload chunk
if (!uploadResult.success) {
doneCallback(uploadResult);
break;
}
if (isDone) doneCallback({ success: true, error: undefined, session: true, result: true }); // Upload is done
}
}
/**
* Get the size of a file on the wdc
* @param {String} authToken The authentication token
* @param {String} fileID The ID of the file to get the size of
* @returns {Promise<InternalResult>} The result of getting the file size of a remote file
*/
function getFileSize(authToken, fileID) {
return new Promise((resolve) => {
const dataUrl = `https://${wdHost}.remotewd.com/sdk/v2/files/${fileID}?pretty=false&fields=size`; // Endpoint to get the size of the file
request.get(dataUrl, { headers: { 'authorization': authToken } }, (error, response, body) => {
if (response.statusCode === 401) {
resolve({ sucess: false, error: undefined, session: false });
return;
}
if (error) {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
resolve({ success: false, error: error, session: true });
return;
}
resolve({ success: true, error: undefined, session: true, result: JSON.parse(body).size }); // Get the size of the file from the response
});
});
}
/**
* Download a file to the local file system
* @param {String} authToken The authentication token
* @param {String} fileID The ID of the file
* @param {String} localPath The path of the local file to download to
* @param {InternalTransferProgress} progressCallback Function to call with offset and total size
*/
function dwl(authToken, fileID, localPath, progressCallback) {
return new Promise(async (resolve) => {
const downloadUrl = `https://${wdHost}.remotewd.com/sdk/v2/files/${fileID}/content?download=true&access_token=${authToken.substring(7)}`;
let totalSize = 0;
const sizeData = await getFileSize(authToken, fileID);
if (!sizeData.success) {
resolve(sizeData);
return;
};
totalSize = sizeData.result;
const req = request.get(downloadUrl);
let currentOffset = 0;
req.on('response', (response) => {
if (response.statusCode === 401) {
resolve({ sucess: false, error: undefined, session: false });
}
});
req.on('error', (error) => {
log.fatal('Something went wrong');
log.debug('Status code: ' + response.statusCode);
log.error(error);
resolve({ success: false, error: error, session: true });
});
req.on('data', (chunk) => {
fs.appendFileSync(localPath, chunk);
progressCallback({ offset: currentOffset, total: totalSize });
currentOffset += chunk.length;
});
req.on('end', () => resolve({ success: true, error: undefined, session: true, result: true }));
});
}
// #endregion
// #region Abstracted functions
/**
* Retryable function for listing files
* @returns {Promise<AbstractedResult>} The result of the abstracted function
*/
async function _listFiles() {
const currentPath = pathStack.length > 0 ? pathStack[pathStack.length - 1] : 'root';
// List files
const result = await ls(tokens.auth, currentPath);
if (result.success) {
return { success: true, data: result.result };
} else {
if (result.error) {
return { success: false };
} else {
// Session timed out, login and run the function again
const self = await authRetry(_listFiles, []);
const result = await self;
return result;
}
}
}
/**
* Retryable function for creating new directories
* @param {String} dirName The name of the directory to create
* @returns {Promise<AbstractedResult>} The result of the abstracted function
*/
function _createDirectory(dirName) {
return new Promise(async (resolve) => {
// Get the current path
const currentPath = pathStack.length > 0 ? pathStack[pathStack.length - 1] : 'root';
// Create the directory
const result = await mkdir(tokens.auth, currentPath, dirName);
if (result.success) {
resolve({ success: true, data: result.result });
} else {
if (result.error) {
resolve({ success: false });
} else {
// Session timed out, login and run the function again
const self = await authRetry(_createDirectory, [dirName]);
const result = await self;
resolve(result);
}
}
});
}
/**
* Retryable function for removing entries
* @param {String} fileID The ID of the entry to remove
* @returns {Promise<AbstractedResult>} The result of the abstracted function
*/
async function _removeFile(fileID) {
// Remove the file/folder
const result = await rm(tokens.auth, fileID);
if (result.success) {
return { success: true, data: result.result };
} else {
if (result.error) {
return { success: false };
} else {
// Session timed out, login and run the function again
const self = await authRetry(_removeFile, [fileID]);
const result = await self;
return result;
}
}
}
/**
* Retryable function for uploading a file
* @param {String} filePath The path of the file on the local system
* @param {InternalTransferProgress} progressCallback The function to be called with the progress of the upload
* @returns {Promise<AbstractedResult>} The result of the abstracted function
*/
function _uploadFile(filePath, progressCallback) {
return new Promise((resolve) => {
const currentPath = pathStack.length > 0 ? pathStack[pathStack.length - 1] : 'root';
// Check if file exists
if (!fs.existsSync(filePath)) {
resolve({ success: false });
return;
}
// Get the size of the file, required to calculate percentage of the progress
const totalSize = fs.statSync(filePath).size;
// Upload the file
upl(tokens.auth, currentPath, filePath, (bytesWritten) => {
if (totalSize == 0) {
progressCallback(100);
return;
}
const percentage = bytesWritten * 100 / totalSize;
// Send the progress to the caller
progressCallback(percentage);
}, async (finalResult) => {
// Upload finished or error or session is invalid
if (finalResult.success) {
resolve({ success: true, data: finalResult.result });
} else {
if (finalResult.error) {
resolve({ success: false });
} else {
// Session timed out, login and run the function again
const self = await authRetry(_uploadFile, [filePath, progressCallback]);
const result = await self;
resolve(result);
}
}
});
});
}
/**
* Retryable function for downloading files from the wdc
* @param {String} fileID The ID of the file to download
* @param {String} localFilePath The path to save the remote file to on the local system
* @param {InternalTransferProgress} progressCallback Function to call with the percentage progress
* @returns {Promise<AbstractedResult>} The result of the abstracted function
*/
async function _downloadFile(fileID, localFilePath, progressCallback) {
const result = await dwl(tokens.auth, fileID, localFilePath, (data) => {
if (data.total == 0) progressCallback(100); // Can't divide by 0 if total size is 0
else {
progressCallback(data.offset * 100 / data.total);
}
});
if (result.success) {
return { success: true, data: result.result };
} else {
if (result.error) {
return { success: false };
} else {
// Session timed out, login and run the function again
const self = await authRetry(_downloadFile, [fileID, localFilePath, progressCallback]);
const result = await self;
return result;
}
}
}
// #endregion
// #region External functions
/**
* Enter to a directory on the server, equivalent to 'cd' command with relative path
* @param {String} folderID The ID of the folder to enter to
*/
function enterDirectory(folderID) {
if (folderID === undefined) return;
pathStack.push(folderID);
}
/**
* Enters the previous directory (if there's one)
*/
function enterParentDirectory() {
if (pathStack.length > 0) pathStack.splice(pathStack.length - 1, 1);
else return false;
return true;
}
/**
* Get the current folder ID of the pathStack
* @returns {(undefined|string)} The current working directory on the remote system, undefined if there were no changes at all
*/
function getCurrentFolder() {
if (pathStack.length > 0) return pathStack[pathStack.length - 1];
else return undefined;
}
/**
* Remove the last x entries of the pathStack
* @param {number} removeCount Number of entries to remove from the pathStack
*/
function removePathStackEntries(removeCount) {
for (let i = 0; i < removeCount; i++) {
if (!enterParentDirectory()) break;
}
}
/**
* Login the to my cloud website
* @param {String} username The username
* @param {String} password The password
* @returns {Promise<Boolean>} The result of the authentication
*/
function authenticate(username, password) {
creds.user = username;
creds.pass = password;
return new Promise(async (resolve) => {
const loginResult = await login(username, password);
resolve(loginResult);
});
}
/**
* List the files in the current folder
* @returns {Array<RemoteEntry>} An array of the remote entries in the current directory
*/
async function listFiles() {
try {
return await retryLimited(10, 'list files', _listFiles, []);
} catch (error) {
throw error;
}
}
/**
* Create a new directory in the current directory
* @param {String} dirName The name of the new directory
* @returns {string} The ID of the newly created directory
*/
async function createDirectory(dirName) {
try {
return await retryLimited(10, 'create new directory', _createDirectory, [dirName]);
} catch (error) {
throw error;
}
}
/**
* Deletes a file/folder in the current directory
* @param {String} fileID The ID of the file/folder to remove
* @returns {Boolean} True if the deletion succeeded, otherwise false
*/
async function removeFile(fileID) {
try {
return await retryLimited(10, 'remove file', _removeFile, [fileID]);
} catch (error) {
throw error;
}
}
/**
* Uploads a local file to the current folder on the cloud
* @param {String} filePath The local path of the file to upload
* @param {InternalTransferProgress} progressCallback A function to send the percentage to
* @returns {Boolean} True if the upload succeeded, otherwise false
*/
async function uploadFile(filePath, progressCallback) {
try {
return await retryLimited(10, 'upload file', _uploadFile, [filePath, progressCallback]);
} catch (error) {
throw error;
}
}
/**
* Download a file from the wdc
* @param {String} fileID The ID of the file to download
* @param {String} localFilePath The path to save the remote file to on the local system
* @param {InternalTransferProgress} progressCallback Function to call with the percentage progress
* @returns {Boolean} True if the upload succeeded, otherwise false
*/
async function downloadFile(fileID, localFilePath, progressCallback) {
try {
return await retryLimited(10, 'download file', _downloadFile, [fileID, localFilePath, progressCallback]);
} catch (error) {
throw error;
}
}
/**
* Enable the logging of API level messages
*/
function enableAPIMessages() {
log.enable();
}
/**
* Disable the logging of API level messages
*/
function disableAPIMessages() {
log.disable();
}
/**
* Set the host to send the requests to
* @param {String} host The host to send the requests to
*/
function setWdHost(host) {
wdHost = host;
}
// #endregion
module.exports = {
authenticate,
enterDirectory,
enterParentDirectory,
getCurrentFolder,
removePathStackEntries,
listFiles,
createDirectory,
removeFile,
uploadFile,
downloadFile,
enableAPIMessages,
disableAPIMessages,
setWdHost
};