-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
713 lines (690 loc) · 28.4 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
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
const chalk = require('chalk');
const CLI = require('clui');
const { Spinner } = CLI;
const clear = require('clear');
const figlet = require('figlet');
const Configstore = require('configstore');
const fs = require('mz/fs');
const AdmZip = require('adm-zip');
const yargs = require('yargs');
const files = require('./lib/file');
const inquirer = require('./lib/xnat-credentials');
const fetchData = require('./utils/fetch_data');
const utils = require('./utils/utils');
const processedFiles = require('./utils/process_upload');
const conf = new Configstore('credentials');
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// eslint-disable-next-line no-unused-vars
async function getDataType(mode, options) {
let dataType = {};
if (mode === 'interactive') {
if (!conf.get('data_type')) {
dataType = await inquirer.askDataType('upload');
} else {
dataType.DataType = conf.get('data_type');
}
}
if (mode === 'non-interactive') {
dataType.DataType = options.data_type;
}
return dataType;
}
async function getProject(mode, options, sessionId, host) {
let selectedProject = {};
if (mode === 'interactive') {
if (!conf.get('project')) {
const status = new Spinner('Getting XNAT project, please wait...');
status.start();
await sleep(1000);
const allProjects = await fetchData.get_all_projects(sessionId, host);
status.stop();
// prompt user to select a project
// eslint-disable-next-line no-unused-vars
selectedProject = await inquirer.askProject(allProjects);
} else {
selectedProject.project = conf.get('project');
}
}
if (mode === 'non-interactive') {
selectedProject.project = options.project;
}
return selectedProject;
}
async function getSubject(mode, options, sessionId, host, project) {
let selectedSubject = {};
if (mode === 'interactive') {
if (!conf.get('subject')) {
const status = new Spinner(`Getting subjects in ${project.project}, please wait...`);
status.start();
await sleep(1000);
const allSubjects = await fetchData.get_all_subjects(sessionId, host, project.project);
status.stop();
// prompt user to select a subject
// eslint-disable-next-line no-unused-vars
selectedSubject = await inquirer.askSubject(allSubjects);
} else {
selectedSubject.project = conf.get('subject');
}
}
return selectedSubject;
}
async function downloadFiles(selectedFiles, sessionId, host, dir) {
if (Object.prototype.hasOwnProperty.call(selectedFiles, 'files')) {
// eslint-disable-next-line no-restricted-syntax
for (const file of selectedFiles.files) {
// list resources
// eslint-disable-next-line no-unused-vars
// eslint-disable-next-line no-unused-vars
const rsStatus = await fetchData.download_file(sessionId, host, file, dir).then(() => {
});
}
}
}
// eslint-disable-next-line no-unused-vars
const run = async (options) => {
const mode = options._[0] === 'i' ? 'interactive' : 'non-interactive';
// check if credentials exist in store
let host; let username; let password;
if (mode === 'interactive') {
username = conf.get('username');
password = conf.get('password');
host = conf.get('host');
if (username && password && host) {
console.log(
chalk.yellow(`Found existing XNAT credentials at ${conf.path}`),
);
} else {
const credentials = await inquirer.askXNATCredentials();
conf.set('host', credentials.host);
conf.set('username', credentials.username);
conf.set('password', credentials.password);
host = conf.get('host');
username = conf.get('username');
password = conf.get('password');
}
}
if (mode === 'non-interactive') {
username = options.username;
password = options.password;
host = options.host;
}
// authenticate user
const response = await fetchData.authenticate_user(username, password, host);
let sessionId = null;
if (response.ok) {
// get sessionID
sessionId = await response.text();
} else {
console.log(chalk.red('Authentication Failed..Please check your credentials'));
return process.exit(1);
}
if (sessionId) {
console.log(chalk.green('Authentication OK'));
}
// ask upload or download
let methodType = null;
if (mode === 'interactive') {
if (!conf.get('method')) {
methodType = await inquirer.askMethodType();
const dataType = await inquirer.askDataType(methodType.DataType);
// eslint-disable-next-line no-param-reassign
options.data_type = dataType.DataType;
conf.data_type = dataType;
// console.log(`You have selected to ${conf.get('method')} data`);
} else {
methodType = {};
methodType.DataType = conf.get('method');
console.log(`You have selected to ${conf.get('method')}`);
}
}
if (mode === 'non-interactive') {
methodType = {};
methodType.DataType = options.method;
console.log(`You have selected to ${options.method}`);
}
if (methodType.DataType === 'Download Data' && options.data_type.includes('Raw')) {
const selectedProject = await getProject(mode, options, sessionId, host);
// get a subject
let selectedSubject = options.subject;
if (!options.subject) {
selectedSubject = (await getSubject(mode, options, sessionId, host, selectedProject)).subject;
}
// get visits
if (!options.visits) {
const visitList = [];
let visitInput = await inquirer.askVisitsInput();
visitList.push(visitInput.visit);
let cont = await inquirer.askAdditionalVisit();
while (cont.continue === true) {
visitInput = await inquirer.askVisitsInput();
visitList.push(visitInput.visit);
cont = await inquirer.askAdditionalVisit();
}
// eslint-disable-next-line no-param-reassign
options.visits = visitList;
// options.visits = await inquirer.askVisitsInput();
}
console.log(`Downloading Raw Data for subject ${selectedSubject} and visits ${options.visits}`);
// get list of mr seesion data
const subjectMrSessions = await fetchData.get_experiments(sessionId, host, selectedProject.project, selectedSubject, 'xnat:mrSessionData');
// filter mr session based on visits
const subjectMrSessionsArray = subjectMrSessions.ResultSet.Result;
const mrSessionsToDownload = [];
// eslint-disable-next-line array-callback-return
subjectMrSessionsArray.map((elem) => {
// convert to string to ints, ensures a numeric match e.g: 007 == 07
if (options.visits.map(Number).includes(Number(elem.label.slice(-2)))) {
mrSessionsToDownload.push({ id: elem.ID, visit: elem.label });
}
});
// Download data
if (mrSessionsToDownload.length > 0) {
// create a folder
if (!fs.existsSync(`./downloads/TRACK_FA_${selectedSubject}`)) {
fs.mkdirSync(`./downloads/TRACK_FA_${selectedSubject}`, { recursive: true });
}
mrSessionsToDownload.forEach((item) => {
if (!fs.existsSync(`./downloads/TRACK_FA_${selectedSubject}/${item.visit}`)) {
fs.mkdirSync(`./downloads/TRACK_FA_${selectedSubject}/${item.visit}`, { recursive: true });
}
// download data
const url = `data/projects/${selectedProject.project}/subjects/${selectedSubject}/experiments/${item.id}/scans/ALL/files?format=zip`;
fetchData.download_mr_zip(sessionId, host, url, `./downloads/TRACK_FA_${selectedSubject}/${item.visit}`, `${selectedSubject}_${item.visit}.zip`).then(
// console.log("Files Downloaded");
);
});
} else {
console.log('No matching RAW files found');
}
}
if (methodType.DataType === 'Download Data' && (options.data_type.includes('Processed') || options.data_type.includes('Pre-Processed'))) {
// const dataType = await getDataType(mode, options);
const dataType = {};
dataType.DataType = options.data_type;
// generate a map of pipeline name and visits based on dataType
// ask project
const status = new Spinner('Getting XNAT project, please wait...');
const selectedProject = await getProject(mode, options, sessionId, host, status);
const processedExpList = await fetchData
.get_all_experiments_by_data_type('data:ProcessedData', sessionId, host, selectedProject.project);
const preProcessedExpList = await fetchData
.get_all_experiments_by_data_type('data:PreProcessedData', sessionId, host, selectedProject.project);
// get unique visit number
let expTypeVisitMap = new Map();
expTypeVisitMap.set('PROC', []);
expTypeVisitMap.set('PREPROC', []);
expTypeVisitMap = utils
.get_unique_visits(expTypeVisitMap, processedExpList.ResultSet.Result);
expTypeVisitMap = utils
.get_unique_visits(expTypeVisitMap, preProcessedExpList.ResultSet.Result);
// ask visit
let selectedProcessedVisitIds = {};
if (dataType.DataType.includes('Processed')) {
if (mode === 'non-interactive') {
selectedProcessedVisitIds.visit = options.visits;
}
if (mode === 'interactive') {
// ask for processed visit number
selectedProcessedVisitIds = await inquirer.askVisits('Processed Data', expTypeVisitMap.get('PROC'));
}
}
let selectedPreProcessedVisitIds = {};
if (dataType.DataType.includes('Pre-Processed')) {
if (mode === 'non-interactive') {
selectedPreProcessedVisitIds.visit = options.visits;
}
if (mode === 'interactive') {
// ask for processed visit number
selectedPreProcessedVisitIds = await inquirer.askVisits('Pre-Processed Data', expTypeVisitMap.get('PREPROC'));
}
}
// get all experiments matching selected visit number
const matchedProcessedExpList = utils
.get_matched_experiments(
selectedProcessedVisitIds.visit,
processedExpList.ResultSet.Result,
);
const matchedPreProcessedExpList = utils
.get_matched_experiments(
selectedPreProcessedVisitIds.visit,
preProcessedExpList.ResultSet.Result,
);
// ask pipeline name
let pipeline = {};
if (mode === 'interactive') {
pipeline = await inquirer.askPipeline();
}
if (mode === 'non-interactive') {
pipeline.pipeline = options.pipeline;
}
const matchedProcessedFiles = [];
// eslint-disable-next-line no-restricted-syntax
for (const exp of matchedProcessedExpList) {
const resources = await fetchData.get_resources(sessionId, host, exp.ID);
const resourceFileList = resources.ResultSet.Result;
// filter by pipeline name
const matchingFiles = utils
.get_files_matching_pipeline_name(resourceFileList, pipeline.pipeline);
if (matchingFiles.length) {
matchingFiles.forEach((file) => {
matchedProcessedFiles.push(file);
});
}
}
const matchedPreProcessedFiles = [];
// eslint-disable-next-line no-restricted-syntax
for (const exp of matchedPreProcessedExpList) {
const resources = await fetchData.get_resources(sessionId, host, exp.ID);
const resourceFileList = resources.ResultSet.Result;
// filter by pipeline name
const matchingFiles = utils
.get_files_matching_pipeline_name(resourceFileList, pipeline.pipeline);
if (matchingFiles.length) {
matchingFiles.forEach((file) => {
matchedPreProcessedFiles.push(file);
});
}
}
// ask resource to Download
let processedSelectedFiles = {};
if (mode === 'interactive') {
if (matchedProcessedFiles.length > 0) {
processedSelectedFiles = await inquirer.askResourceToDownload(matchedProcessedFiles, 'Processed');
} else {
console.log('No matching Processed files found');
}
}
if (mode === 'non-interactive') {
console.log(chalk.yellow(`Found ${matchedProcessedFiles.length} matching Processed files for pipeline ${pipeline.pipeline}`));
const filesArray = [];
matchedProcessedFiles.forEach(((file) => {
filesArray.push(file.URI);
}));
processedSelectedFiles.files = filesArray;
}
// download file
// const downloadStatus = new Spinner('Downloading files, please wait...');
// downloadStatus.start();
// eslint-disable-next-line no-restricted-syntax
// create a directory with TRACKFA_PROC_{pipelineName}
if (Object.prototype.hasOwnProperty.call(processedSelectedFiles, 'files')) {
if (processedSelectedFiles.files.length > 0) {
const processedDir = `./downloads/TRACKFA_PROC_${pipeline.pipeline}`;
if (!fs.existsSync(processedDir)) {
fs.mkdirSync(processedDir, { recursive: true });
}
await downloadFiles(processedSelectedFiles, sessionId, host, processedDir);
}
}
let preprocessedSelectedFiles = {};
if (mode === 'interactive' && dataType.DataType.includes('Pre-Processed')) {
if (matchedPreProcessedFiles.length > 0) {
preprocessedSelectedFiles = await inquirer.askResourceToDownload(matchedPreProcessedFiles, 'Pre-Processed');
} else {
console.log('No matching PreProcessed files found');
}
}
if (mode === 'non-interactive') {
console.log(chalk.yellow(`Found ${matchedPreProcessedFiles.length} matching Pre-Processed files for pipeline ${pipeline.pipeline}`));
const filesArray = [];
matchedPreProcessedFiles.forEach(((file) => {
filesArray.push(file.URI);
}));
preprocessedSelectedFiles.files = filesArray;
}
if (Object.prototype.hasOwnProperty.call(preprocessedSelectedFiles, 'files')) {
if (preprocessedSelectedFiles.files.length > 0) {
const preProcessedDir = `./downloads/TRACKFA_PREPROC_${pipeline.pipeline}`;
if (!fs.existsSync(preProcessedDir)) {
fs.mkdirSync(preProcessedDir, { recursive: true });
}
await downloadFiles(preprocessedSelectedFiles, sessionId, host, preProcessedDir);
// downloadStatus.stop();
}
}
return 0;
}
if (methodType.DataType === 'Upload Data') {
let dataType = {};
if (mode === 'interactive') {
if (!conf.get('data_type')) {
dataType = await inquirer.askDataType('upload');
} else {
dataType.DataType = conf.get('data_type');
}
}
if (mode === 'non-interactive') {
dataType.DataType = options.data_type;
}
let selectedProject = null;
if (mode === 'interactive') {
if (!conf.get('project')) {
const status = new Spinner('Getting XNAT project, please wait...');
status.start();
await sleep(1000);
const allProjects = await fetchData.get_all_projects(sessionId, host);
status.stop();
// prompt user to select a project
// eslint-disable-next-line no-unused-vars
selectedProject = await inquirer.askProject(allProjects);
}
} else {
selectedProject = await getProject(mode, options, sessionId, host);
}
// get list of file to upload
const fileReadStatus = new Spinner('Reading directory, please wait...');
fileReadStatus.start();
await sleep(1000);
const filteredFileList = [];
try {
const fileList = await fs.readdir(files.getCurrentDirectoryBase());
fileList.forEach((file) => {
if ((file.startsWith('TRACKFA_PROC') && file.endsWith('zip'))
|| (file.startsWith('TRACKFA_PREPROC') && file.endsWith('zip'))) {
filteredFileList.push(file);
}
});
} catch (err) {
console.error(err);
}
fileReadStatus.stop();
// format for zip file name TRACKFA_PROC01_BrainMorph_BrainT1_FreeSurfer_Aachen_24Mar2020.zip
// unzip file and verify content
const extractToFolderList = [];
filteredFileList.forEach((file) => {
const zip = new AdmZip(file);
// extract this zip file
const extractToFolder = `./${file.replace('.zip', '')}_extracted`;
try {
zip.extractAllTo(extractToFolder, true);
extractToFolderList.push(extractToFolder);
} catch (e) {
console.log(`cannot extract file from provided zip file:${file}`);
}
});
// rename
extractToFolderList.forEach((folder) => {
const visitNumberString = String(folder.split('_')[1]);
const dataTypeString = visitNumberString.match(/\D+/g);
const visitNumber = visitNumberString.match(/\d+/g);
const piplineName = folder.split(/TRACKFA_[A-z]+[0-9]+_/)[1].slice(0, -10);
fs.readdirSync(folder).forEach(((subFolder) => {
const subjectId = subFolder.split('_')[1];
// rename subfolder
console.log(`${chalk.yellow(`Renaming ${subFolder}`)} to ${chalk.green(`TRACKFA_${subjectId}_${dataTypeString}${visitNumber}_${piplineName}`)}`);
fs.renameSync(`${folder}/${subFolder}`, `${folder}/TRACKFA_${subjectId}_${dataTypeString}${visitNumber}_${piplineName}`);
// zip renamed folder
}));
});
// zip renamed folders
extractToFolderList.forEach((folder) => {
const subFolders = fs.readdirSync(folder);
subFolders.forEach((elem) => {
const folderToZip = new AdmZip();
folderToZip.addLocalFolder(`${folder}/${elem}`);
// create a subfolder if not exist
const folderName = './upload_folder';
try {
if (!fs.existsSync(folderName)) {
fs.mkdirSync(folderName);
}
} catch (err) {
console.log(err);
}
folderToZip.writeZip(`upload_folder/${elem}.zip`);
});
});
// delete extracted folders
extractToFolderList.forEach((folder) => {
fs.rmdirSync(folder, { recursive: true });
});
// iterate and get processed file
const processedList = [];
const preProcessedList = [];
const uploadFileList = await fs.readdir('./upload_folder/');
uploadFileList.forEach((file) => {
const fileSplitArr = file.split('_');
const fileType = fileSplitArr[2];
if (fileType) {
if (fileType.startsWith('PRO')) {
// add to processed list
processedList.push(file);
}
if (fileType.startsWith('PRE')) {
// add to pre processed list
preProcessedList.push(file);
}
}
});
console.log(preProcessedList);
fileReadStatus.stop();
// eslint-disable-next-line no-restricted-syntax
for (const elem of dataType.DataType) {
if (elem === 'Processed') {
const ProcessedFileReadStatus = new Spinner('looking for processed data to upload, please wait...');
ProcessedFileReadStatus.start();
await sleep(1000);
// find list of processed data to upload
ProcessedFileReadStatus.stop();
const dataObj = await processedFiles
.processed_files(processedList, sessionId, host, true, 'ProcessedData', selectedProject.project);
const subjectToCreate = dataObj.get('subject_create');
const expToCreate = dataObj.get('exp_create');
const fileToUpload = dataObj.get('resource_upload');
if (subjectToCreate.length > 0) {
console.log(chalk.green(`This run will create following ${subjectToCreate.length} subjects`));
console.log(chalk.green(` ${subjectToCreate} `));
}
if (expToCreate.length > 0) {
console.log(chalk.green(`This run will create following ${expToCreate.length} experiments`));
console.log(chalk.green(` ${expToCreate} `));
}
if (fileToUpload.length > 0) {
console.log(chalk.green(`This run will upload following ${fileToUpload.length} files`));
console.log(chalk.green(` ${fileToUpload} `));
}
if (subjectToCreate.length === 0 || expToCreate.length === 0 || fileToUpload.length === 0) {
console.log(chalk.red('No new processed data found in current directory'));
}
// ask user if he wants to continue
if (mode === 'interactive') {
if (subjectToCreate.length > 0 || expToCreate.length > 0 || fileToUpload.length > 0) {
const userResponse = await inquirer.askContinue();
if (userResponse.continue) {
// upload
await processedFiles.processed_files(processedList, sessionId, host, false, 'ProcessedData', selectedProject.project);
} else {
return process.exit(1);
}
}
}
if (mode === 'non-interactive') {
await processedFiles.processed_files(processedList, sessionId, host, false, 'ProcessedData', selectedProject.project);
}
// read all files in a folder
} else if (elem === 'Pre-Processed') {
const PreProcessedFileReadStatus = new Spinner('looking for pre-processed data to upload, please wait...');
PreProcessedFileReadStatus.start();
await sleep(1000);
PreProcessedFileReadStatus.stop();
const dataObj = await processedFiles
.processed_files(preProcessedList, sessionId, host, true, 'PreProcessedData', selectedProject.project);
const subjectToCreate = dataObj.get('subject_create');
const expToCreate = dataObj.get('exp_create');
const fileToUpload = dataObj.get('resource_upload');
if (subjectToCreate.length > 0) {
console.log(chalk.green(`This run will create following ${subjectToCreate.length} subjects`));
console.log(chalk.green(` ${subjectToCreate} `));
}
if (expToCreate.length > 0) {
console.log(chalk.green(`This run will create following ${expToCreate.length} experiments`));
console.log(chalk.green(` ${expToCreate} `));
}
if (fileToUpload.length > 0) {
console.log(chalk.green(`This run will upload following ${fileToUpload.length} files`));
console.log(chalk.green(` ${fileToUpload} `));
}
if (subjectToCreate.length === 0 || expToCreate.length === 0 || fileToUpload.length === 0) {
console.log(chalk.red('No new pre-processed data found in current directory'));
}
if (mode === 'interactive') {
if (subjectToCreate.length > 0 || expToCreate.length > 0 || fileToUpload.length > 0) {
const userResponse = await inquirer.askContinue();
if (userResponse.continue) {
// upload
await processedFiles.processed_files(preProcessedList, sessionId, host, false, 'PreProcessedData', selectedProject.project);
} else {
return process.exit(1);
}
}
}
if (mode === 'non-interactive') {
await processedFiles.processed_files(preProcessedList, sessionId, host, false, 'PreProcessedData', selectedProject.project);
}
} else {
// TODO raw data
}
}
}
/* ------------------------
DELETE FILES FROM PROEJCT
---------------------------*/
if (methodType.DataType === 'Delete Data') {
// files to delete - resource id
const delFile = [];
// get the project and cycle through all the subjects/experiments/resources
// and fetch a list of files that matches the pipeline description
const project = await getProject(mode, options, sessionId, host);
const searchStatus = new Spinner(`Searching for files in "${project.project}" and files that match: "${options.pipeline}"`);
searchStatus.start();
const allSubjects = await fetchData.get_all_subjects(sessionId, host, project.project);
// get all experiments in subject
// eslint-disable-next-line no-restricted-syntax
for (const sub of allSubjects.ResultSet.Result) {
const allExp = await fetchData.get_all_experiments(sessionId, host, project.project, sub.ID);
// get all resources in experiment
// eslint-disable-next-line no-restricted-syntax
for (const exp of allExp.ResultSet.Result) {
const resourceFiles = await fetchData.get_resources(sessionId, host, exp.ID);
// search for all files that matches the pipeline in experiment
// eslint-disable-next-line no-restricted-syntax
for (const file of resourceFiles.ResultSet.Result) {
if (file.Name.includes(options.pipeline)) {
// add this file id to list of files to be deleted
delFile.push({ Name: file.Name, URI: file.URI });
}
}
}
}
searchStatus.stop();
if (delFile.length > 0) {
console.log(`Found the following files matching "${options.pipeline}"`);
console.log(delFile);
// confirm to delete files
const userResponse = await inquirer.askDelete();
if (userResponse.continue) {
// delete files
const delStatus = new Spinner('Deleting files.......');
delStatus.start();
// eslint-disable-next-line no-restricted-syntax
for (const file of delFile) {
await fetchData.delete_resource(sessionId, host, file.URI);
}
await sleep(1000);
console.log('Files deletion complete.');
delStatus.stop();
} else {
console.log('Delete cancelled, no files were deleted.');
}
} else {
console.log(`No files found matching the description: "${options.pipeline}"`);
}
}
return 0;
};
const options = yargs
.usage('Usage: Command <Options>')
.example(chalk.yellow('- Upload Processed and Pre-Processed data in non-interactive mode:'))
.example(chalk.green(' n -h https://xnat.monash.edu/ -u myUserName -p myPassword -m "Upload Data" -d "Pre-Processed" "Processed" -o TRACKFA'))
.example(chalk.yellow('- Download Processed and Pre-Processed data in non-interactive mode:') + chalk.green('\n\t n -h https://xnat.monash.edu/ -u myUserName -p myPassword -m "Download Data" -d "Processed" "Pre-Processed" -o TRACKFA -P "SpineMorph_SpineT2_SCT_UMN_10Sep2020" -v "01" "02"'))
.example(chalk.yellow('- Download Raw data in non-interactive mode:') + chalk.green('\n\t n -h https://xnat.monash.edu/ -u myUserName -p myPassword -m "Download Data" -d "Raw" -s TRACKFA_AAN001 -v "01" -o TRACKFA'))
.example(chalk.yellow('- Delete files matching specified pipeline in non-interactive mode:') + chalk.green('\n\t n -h https://xnat.monash.edu/ -u myUserName -p myPassword -m "Delete Data" -o TRACKFA -P "Pipeline_Name_To_Delete"'))
.command(['interactive', 'i'], 'Run in interactive mode', {}, () => { console.log('Running in interactive mode'); })
.command(['non-interactive', 'n'], 'Run in non-interactive mode',
() => yargs
.option('host', {
alias: 'h', describe: 'XNAT host URL', type: 'string', demandOption: true,
})
.option('username', {
alias: 'u', describe: 'XNAT username', type: 'string', demandOption: true,
})
.option('password', {
alias: 'p', describe: 'XNAT password', type: 'string', demandOption: true,
})
.option('method', {
alias: 'm', describe: 'Choose upload, Download or Delete', type: 'string', choices: ['Upload Data', 'Download Data', 'Delete Data'], demandOption: true,
})
.option('data_type', {
alias: 'd', describe: 'Choose data type', type: 'array', choices: ['Processed', 'Pre-Processed', 'Raw'],
})
.option('project', {
alias: 'o', describe: 'Choose project', type: 'string', demandOption: true,
})
.option('subject', {
alias: 's', describe: 'Choose subject', type: 'string',
})
.option('visits', {
alias: 'v', describe: 'Choose visits', type: 'array',
})
.option('pipeline', {
alias: 'P', describe: 'Choose pipeline name', type: 'string',
}),
() => {
console.log('Running in non-interactive mode');
// run
})
.demandCommand()
.check((args) => {
if (args.method === 'Download Data') {
if (args.data_type.includes('Raw') && (!args.subject && !args.visits)) {
throw new Error('You have selected to download Raw data, Please provide subject name and visits');
} else if ((args.data_type.includes('Processed') || args.data_type.includes('Pre-Processed')) && (!args.pipeline || !args.visits)) {
throw new Error('You have selected to download Processed or Pre-Processed data, Please provide pipeline name and visits');
}
}
return true;
})
.help()
.argv;
clear();
console.log(
chalk.yellow(
figlet.textSync('---------------------', { font: 'Big', horizontalLayout: 'full' }),
),
);
console.log(
chalk.yellow(
figlet.textSync('TRACK-FA-XNAT-CLIENT', { font: 'Big', horizontalLayout: 'full' }),
),
);
console.log(
chalk.green('A XNAT Client to upload and download Post-Processed or Processed data for TRACK-FA Project'),
);
console.log(
chalk.yellow(
figlet.textSync('---------------------', { font: 'Big', horizontalLayout: 'full' }),
),
);
console.log(
chalk.green(
`Current directory is: ${files.getCurrentDirectoryBase()}`,
),
);
run(
options,
);
// run();