forked from kacole2/s3motion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3motion.js
executable file
·1422 lines (1364 loc) · 53.1 KB
/
s3motion.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
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env node
var AWS = require('aws-sdk'),
fs = require('fs'),
s3 = require('s3'),
async = require('async'),
ProgressBar = require('progress'),
chalk = require('chalk'),
program = require('commander'),
prompt = require('prompt'),
optimist = require('optimist'),
osenv = require('osenv');
//Functions that make all the magic happen
//=============================================================
// @description Returns a client object for the AWS SDK
// @object awsClientArgs Paramters passed from outside functions.
// @string accessKeyId Pipes in the access key for S3 access
// @string secretAccessKey Pipes in the secret key for S3 access
// @string endpoint Pipes in an endpoint for 3rd party S3 services
// @return client object for AWS SDK
var awsClient = function(awsClientArgs){
var client = new AWS.S3({accessKeyId: awsClientArgs.accessKeyId, secretAccessKey: awsClientArgs.secretAccessKey, endpoint: awsClientArgs.endpoint});
return client;
}
// @description Returns a client object for the S3 NPM package
// @object s3ClientArgs Paramters passed from outside functions.
// @string accessKeyId Pipes in the access key for S3 access
// @string secretAccessKey Pipes in the secret key for S3 access
// @string endpoint Pipes in an endpoint for 3rd party S3 services
// @return client object for S3 NPM package
var s3Client = function(s3ClientArgs) {
var client = s3.createClient({
s3Options: {
accessKeyId: s3ClientArgs.accessKeyId,
secretAccessKey: s3ClientArgs.secretAccessKey,
endpoint: s3ClientArgs.endpoint
// any other options are passed to new AWS.S3()
// See: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Config.html#constructor-property
},
});
return client;
}
// @description Creates a new client json object
// @object newClientArgs Paramters passed from outside functions.
var newClient = function(newClientArgs, done){
var home = osenv.home(); //get the home directory for the current user
// Two String functions needed to searching and inserting text to the json file
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
else
return string + this;
};
String.prototype.includes = function() {'use strict';
return String.prototype.indexOf.apply(this, arguments) !== -1;
};
// Read the s3motionClients.json file to add a new client
fs.readFile(home + '/s3motionClients.json', function (err, data) { //buffer file into memory
if (err) {
// if s3motionClients.json does not exist, create it and then continue
console.log("creating 's3motionClients.json' file in " + home);
fs.writeFileSync(home + '/s3motionClients.json', '{"clients":[\n\t{\n\t}\n\t]\n}');
var data = fs.readFileSync(home + '/s3motionClients.json');
}
var content = data.toString('utf8'); //change buffer content to string for manipulation
var contentJSON = JSON.parse(content); //parse the content to JSON
var clients = contentJSON['clients']; //tab over to clients
var clientExists = false; //set to false for error checking
for (var i = 0; i < clients.length; i++) { //loop through all clients to see if the specified name exists
if(clients[i]['name'] == newClientArgs.name) clientExists = true; //if it exists, set error handler to true
}
if(clientExists == true){ //if the error is true kill the process and send message to console
done(chalk.yellow.bold(newClientArgs.name) + chalk.red(" already exists. Please use a different name or edit the 's3motionClients.json' file"));
} else {
if(typeof newClientArgs.endpoint === 'undefined'){ //if endpoint is undefined (AWS), remove it from the insertion
content = content.insert(13, '\t{ \n\t\t"name": "' + newClientArgs.name + '",\n\t\t"accessKeyId": "' + newClientArgs.accessKeyId + '",\n\t\t"secretAccessKey": "' + newClientArgs.secretAccessKey + '"\n\t},\n');
} else {
content = content.insert(13, '\t{ \n\t\t"name": "' + newClientArgs.name + '",\n\t\t"accessKeyId": "' + newClientArgs.accessKeyId + '",\n\t\t"secretAccessKey": "' + newClientArgs.secretAccessKey + '",\n\t\t"endpoint": "' + newClientArgs.endpoint + '"\n\t},\n');
};
fs.writeFile(home + '/s3motionClients.json', content, function (err) { //save the file with the new content
if (err) throw err;
done(chalk.yellow.bold(newClientArgs.name) + chalk.green.bold(" client created")); //deliver success message
});
}
});
}
// @description Retrieve client from JSON file and return client
// @object getClientArgs Paramters passed from outside functions.
// @return client object
var getClient = function(getClientArgs, done){
var home = osenv.home(); //get current home directory
fs.readFile(home + '/s3motionClients.json', function (err, data) { //read the file into buffer
if (err) throw err; //error if file isn't found.
var clientExists = false; //set error handler to FALSE
var clients = JSON.parse(data); //put buffer data to JSON
clients = clients['clients']; //tab into JSON
for (var i = 0; i < clients.length; i++) { //loop through all JSON objects and
if(clients[i]['name'] == getClientArgs.name) { //find the matching name supplied from the user input
var clientExists = true; //set error handler to TRUE
if(getClientArgs.client == 's3'){ //run function depending on type of client needed
var s3clientReturn = s3Client({accessKeyId: clients[i]['accessKeyId'], secretAccessKey: clients[i]['secretAccessKey'], endpoint: clients[i]['endpoint']});
done(s3clientReturn);
} else if (getClientArgs.client == 'aws') {
var awsClientReturn = awsClient({accessKeyId: clients[i]['accessKeyId'], secretAccessKey: clients[i]['secretAccessKey'], endpoint: clients[i]['endpoint']});
done(awsClientReturn) ;
}
}
}
// if the supplied client isn't found, let the user know. Using '' as a return for nothing
if(clientExists == false) {
done('');
}
});
}
// @description List all clients
// @return JSON object
var listClients = function(done){
var home = osenv.home();
fs.readFile(home + '/s3motionClients.json', function (err, data) { //read the file into buffer
if (err) {
done({message : 'Error: cannot open or find s3motionClients.json file in ' + home});
} else {
var clients = JSON.parse(data);
done(clients); //pass all clients as JSON object back
}
});
}
// @description List all buckets for a client
// @object clientArgs Paramters passed from outside functions.
// @return JSON object if passed. console error message.
var listBuckets = function(clientArgs, done){
clientArgs.site.listBuckets(function(err, data) {
if (err) {
done(chalk.red('Could not retrieve buckets. Error: ' + err)); // error is Response.error
} else {
done(data); // data is Response.data
}
});
}
// @description Create new bucket for a client
// @object newBucketParams Paramters passed from outside functions.
// @return JSON object if passed. Sting on error message
var newBucket = function(newBucketParams, done){
var params = {
Bucket: newBucketParams.bucket //new bucket name is passed as a parameter
};
newBucketParams.site.createBucket(params, function(err, data) {
if (err) done(err, err.stack); // an error occurred
else {
done(data);
}
});
}
// @description List objects in a bucket for a client
// @object listArgs Paramters passed from outside functions.
// @return Array
var listObjects = function(listArgs, done) {
var objectLists = []; //set the array to hold list of all Objects
var objectCount = 0; //count how many objects are discovered
var params = {
s3Params: {
Bucket: listArgs.bucket, //bucket name is passed as a parameter
},
};
var lister = listArgs.site.listObjects(params); //specify site, passed as a listArgs param, to list bucket items
lister.on('error', function(err) {
done("unable to list " + listArgs.bucket + " : " + err.stack);
//console.error(chalk.red("unable to list: " + chalk.red.bold(listArgs.bucket) + ""), chalk.yellow(err.stack));
});
lister.on('data', function(data) { //keep streaming data as its discovered
var objects = data['Contents']; //drill down one layer in JSON
objectCount += data['Contents'].length; //add the discovered amount to the Count
objectLists.push(objects); //add this discovered list to the array
console.log(chalk.blue('Gathering list of objects from ' + listArgs.bucket + '... Discovered ' + objectCount + ' objects so far'));
});
lister.on('end', function(data) {
done(objectLists); //pass the array full of JSON back to the callback
});
}
// @description Download an object or set of objects from a bucket for a client
// @object downloadArgs Paramters passed from outside functions.
// @return Array for progress and String on completion for each object download
var downloadObject = function(downloadArgs, done) {
var folder; //set the folder variable and run if/else if folder is not passed as a param to set a default.
if(typeof downloadArgs.folder === 'undefined'){
folder = ''
} else {
var lastChar = downloadArgs.folder.substr(downloadArgs.folder.length - 1);
if (lastChar == '/') {
folder = downloadArgs.folder
} else {
folder = downloadArgs.folder + '/'
}
};
var downloadObjectProcess = function(downloadArgs, done){
var params = {
//specify download location and the object name. no name changes are made to the object on the fly
localFile: downloadArgs.folder + downloadArgs.object,
s3Params: {
Bucket: downloadArgs.bucket, //specify bucket to download from
Key: downloadArgs.object, //specify name of object to download
},
};
var downloader = downloadArgs.site.downloadFile(params);
downloader.on('error', function(err) {
done(chalk.red("Unable to download " + chalk.red.bold(downloadArgs.object) + ". Check bucket name and object name :"), chalk.yellow(err.stack));
});
downloader.on('progress', function() {
done([downloadArgs.folder + downloadArgs.object, downloader.progressAmount, downloader.progressTotal]);
});
downloader.on('end', function() {
done(downloadArgs.object + chalk.green.bold(" downloaded"));
});
}
//Using CLI & REST, all objects are added to this function as an array. This 'if' statement is here in case this becomes
//a npm package for inclusion in other projects where objects are not passed in as arrays from the original function
//When objects are passed in as an array, only do 10 objects at a time until completed
if (downloadArgs.object instanceof Array){
async.eachLimit(downloadArgs.object, 10, function(object, callback){
downloadObjectProcess({site: downloadArgs.site, bucket: downloadArgs.bucket, object: object, folder: folder}, function(data){
done(data); //send data to the done callback from the source function
callback(); //send a callback response to the async callback.
});
});
} else {
downloadObjectProcess({site: downloadArgs.site, bucket: downloadArgs.bucket, object: downloadArgs.object, folder: folder}, function(data){
done(data); //send data to the done callback from the source function
});
}
}
// @description Upload an object or set of objects from a local location for a client
// @object uploadArgs Paramters passed from outside functions.
// @return Array for progress and String on completion for each object upload
var uploadObject = function(uploadArgs, done) {
var folder; //set the folder variable and run if/else if folder is not passed as a param to set a default.
if(typeof uploadArgs.folder === 'undefined'){
folder = ''
} else {
//add the trailing / if not specified in the folder param
var lastChar = uploadArgs.folder.substr(uploadArgs.folder.length - 1);
if (lastChar == '/') {
folder = uploadArgs.folder
} else {
folder = uploadArgs.folder + '/'
}
};
var uploadObjectProcess = function(uploadArgs, done){
var params = {
localFile: uploadArgs.folder + uploadArgs.object, //specifying upload location
s3Params: {
Bucket: uploadArgs.bucket, //specify bucket name to upload to
Key: uploadArgs.object, //specify what the object will be called. In our case we are using same names. no changes
},
};
var uploader = uploadArgs.site.uploadFile(params);
var i = 0; //set variables for progress
var l = 0;
uploader.on('error', function(err) {
done(chalk.red("unable to upload " + chalk.red.bold(uploadArgs.object) + ":"), chalk.yellow(err.stack));
});
uploader.on('progress', function() {
//if statement to run because of an incorrect amount of callback returns causing errors on the progress bar
// once the progressAmount equals the progressTotal then we don't need to send anymore progress data
// data is returned as Array
if (i != 0){
if(l == 0){
done([uploadArgs.folder + uploadArgs.object, uploader.progressAmount, uploader.progressTotal]);
if(uploader.progressAmount == uploader.progressTotal){
l += 1;
}
}
}
i += 1;
});
uploader.on('end', function() {
//send success String
done(chalk.green.bold(uploadArgs.object + " uploaded"));
});
}
//Using CLI & REST, all objects are added to this function as an array. This 'if' statement is here in case this becomes
//a npm package for inclusion in other projects where objects are not passed in as arrays from the original function
//When objects are passed in as an array, only do 10 objects at a time until completed
if (uploadArgs.object instanceof Array){
async.eachLimit(uploadArgs.object, 10, function(object, callback){
uploadObjectProcess({site: uploadArgs.site, bucket: uploadArgs.bucket, object: object, folder: folder}, function(data){
done(data); //send data to the done callback from the source function
callback(); //send a callback response to the async callback.
});
});
} else {
uploadObjectProcess({site: uploadArgs.site, bucket: uploadArgs.bucket, object: uploadArgs.object, folder: folder}, function(data){
done(data);
});
}
}
// @description Copy an object or set of objects from an S3 bucket to another bucket and between clients
// @object copyArgs Paramters passed from outside functions.
// @return String on completion
var copyObject = function(copyArgs, done) {
var copyProcess = function(copyProcessArgs, done) {
//create a progress bar to show the copy process
var bar = new ProgressBar('copy: ' + copyProcessArgs.object + ' [:bar :title] ', {
complete: chalk.green('='),
incomplete: ' ',
width: 30,
total: 3
});
//process goes to download object, upload object, and remove from local filesystem. must be sequential.
async.series([
function(done) {
bar.tick({ title: chalk.blue('downloading') });
downloadObject({site: copyProcessArgs.sourceSite, bucket: copyProcessArgs.sourceBucket, object: copyProcessArgs.object, folder: __dirname + '/s3motionTransfer/', transfer: true}, function(data){
if(data == copyProcessArgs.object + chalk.green.bold(" downloaded")) {
done(); //async callback to go to the next
}
});
},
function(done) {
bar.tick({ title: chalk.blue('uploading') });
uploadObject({site: copyProcessArgs.destinationSite, bucket: copyProcessArgs.destinationBucket, object: copyProcessArgs.object, folder: __dirname + '/s3motionTransfer/', transfer: true}, function(data){
if(data == chalk.green.bold(copyProcessArgs.object + " uploaded")) {
done(); //async callback to go to the next
}
});
},
function(done) {
fs.unlink(__dirname + '/s3motionTransfer/' + copyProcessArgs.object, function (err) {
if (err) throw err;
bar.tick({ title: chalk.cyan('complete') });
done(); //async callback to go to the next
});
}
],
function(err, results){
if (err) {
done(chalk.red.bold('error occured: ') + chalk.yellow(err));
}
done(copyProcessArgs.object + chalk.green('successfully copied'));
});
}
//Using CLI & REST, all objects are added to this function as an array. This 'if' statement is here in case this becomes
//a npm package for inclusion in other projects where objects are not passed in as arrays from the original function
//When objects are passed in as an array, only do 10 objects at a time until completed
if (copyArgs.object instanceof Array){
async.eachLimit(copyArgs.object, 10, function(object, callback){
copyProcess({sourceSite: copyArgs.sourceSite, sourceBucket: copyArgs.sourceBucket, object: object, destinationSite: copyArgs.destinationSite, destinationBucket: copyArgs.destinationBucket}, function(data){
done(); //send data to the done callback from the source function
callback(); //send a callback response to the async callback.
});
});
} else {
copyProcess({sourceSite: copyArgs.sourceSite, sourceBucket: copyArgs.sourceBucket, object: copyArgs.object, destinationSite: copyArgs.destinationSite, destinationBucket: copyArgs.destinationBucket}, function(data){
done();
});
}
}
// @description Delete an object or set of objects from an S3 bucket
// @object deleteArgs Paramters passed from outside functions.
// @return Array for progress and String on completion for each object upload
var deleteObject = function(deleteArgs, done){
var objectsToDelete = []; //array syntax needed for multi-object deletion in s3param payload
if (deleteArgs.object instanceof Array){
length = deleteArgs.object.length;
for (var i = 0; i < length; i++) {
var obj = {Key: deleteArgs.object[i],};
objectsToDelete.push(obj);
}
} else {
var obj = {Key: deleteArgs.object,};
objectsToDelete.push(obj);
}
var s3params = {
Bucket: deleteArgs.bucket,
Delete: {
Objects:
objectsToDelete,
},
};
var deleter = deleteArgs.site.deleteObjects(s3params);
deleter.on('error', function(err) {
done(chalk.red.bold("unable to delete:"), chalk.yellow(err.stack));
});
deleter.on('progress', function() {
done([deleter.progressAmount, deleter.progressTotal]);
});
deleter.on('end', function() {
done(deleteArgs.object + chalk.red(" deleted"));
});
}
// @description Move an object or set of objects from an S3 bucket. Same as copy but calls the delete function in addition on the source
// @object moveArgs Paramters passed from outside functions.
// @return String on completion for each object upload
var moveObject = function(moveArgs, done) {
var moveProcess = function(moveProcessArgs, done) {
var bar = new ProgressBar('move: ' + moveProcessArgs.object + ' [:bar :title] ', {
complete: chalk.green('='),
incomplete: ' ',
width: 30,
total: 5
});
async.series([
function(done) {
bar.tick({ title: chalk.blue('downloading') });
downloadObject({site: moveProcessArgs.sourceSite, bucket: moveProcessArgs.sourceBucket, object: moveProcessArgs.object, folder: __dirname + 's3motionTransfer/', transfer: true}, function(data){
if(data == moveProcessArgs.object + chalk.green.bold(" downloaded")) {
done();
}
});
},
function(done) {
bar.tick({ title: chalk.blue('uploading') });
uploadObject({site: moveProcessArgs.destinationSite, bucket: moveProcessArgs.destinationBucket, object: moveProcessArgs.object, folder: __dirname + 's3motionTransfer/', transfer: true}, function(data){
if(data == chalk.green.bold(moveProcessArgs.object + " uploaded")) {
done();
}
});
},
function(done) {
bar.tick({ title: chalk.blue('deleting locally') });
fs.unlink(__dirname + 's3motionTransfer/' + moveProcessArgs.object, function (err) {
if (err) throw err;
done();
});
},
function(done) {
bar.tick({ title: chalk.blue('deleting from source' ) });
deleteObject({site: moveProcessArgs.sourceSite, bucket: moveProcessArgs.sourceBucket, object: moveProcessArgs.object, transfer: true}, function(data){
done();
});
},
function(done) {
bar.tick({ title: chalk.cyan('complete') });
done();
}
],
function(err, results){
if (err) {
done(chalk.red.bold('error occured while moving ' + moveProcessArgs.object + ': ') + chalk.yellow(err));
}
done(moveProcessArgs.object + chalk.green('successfully moved'));
});
}
//Using CLI & REST, all objects are added to this function as an array. This 'if' statement is here in case this becomes
//a npm package for inclusion in other projects where objects are not passed in as arrays from the original function
//When objects are passed in as an array, only do 10 objects at a time until completed
if (moveArgs.object instanceof Array){
async.eachLimit(moveArgs.object, 10, function(object, callback){
moveProcess({sourceSite: moveArgs.sourceSite, sourceBucket: moveArgs.sourceBucket, object: object, destinationSite: moveArgs.destinationSite, destinationBucket: moveArgs.destinationBucket}, function(data){
done();
callback();
});
});
} else {
moveProcess({sourceSite: moveArgs.sourceSite, sourceBucket: moveArgs.sourceBucket, object: moveArgs.object, destinationSite: moveArgs.destinationSite, destinationBucket: moveArgs.destinationBucket}, function(data){
done();
});
}
}
// @description Copy all object within a bucket to another bucket between.
// @object copyArgs Paramters passed from outside functions.
// @return String on completion for each object upload
var copyBucket = function(copyArgs, done) {
var objectLists = []; //array to hold all the list of objects gatehres from the lister
var objectCount = 0; //iterating counter for all objects found
var params = {
s3Params: {
Bucket: copyArgs.sourceBucket,
},
};
var lister = copyArgs.sourceSite.listObjects(params);
lister.on('error', function(err) {
console.error(chalk.red.bold("unable to list:"), chalk.yellow(err.stack));
});
lister.on('data', function(data) {
var objects = data['Contents']; //drill down one
objectCount += data['Contents'].length; //add the amount of discovered objects to array
objectLists.push(objects); //add the list to the array. this includes empty folders that will not transfer
console.log(chalk.blue('Gathering list of objects from ' + copyArgs.sourceBucket + '... Discovered ' + objectCount + ' objects so far'));
});
lister.on('end', function(data) {
console.log(chalk.blue(objectCount + ' objects found. Beginning transfer:'));
//the eachSeries call will do 1 objectList at a time and won't start the next until it has completed
async.eachSeries(objectLists,
function(objectList, callback){
var copyProcess = function(copyProcessArgs, done) {
var bar = new ProgressBar('copy: ' + copyProcessArgs.object + ' [:bar :title] ', {
complete: chalk.green('='),
incomplete: ' ',
width: 30,
total: 3
});
async.series([
function(done) {
bar.tick({ title: chalk.blue('downloading') });
downloadObject({site: copyProcessArgs.sourceSite, bucket: copyProcessArgs.sourceBucket, object: copyProcessArgs.object, folder: __dirname + '/s3motionTransfer/', transfer: true}, function(data){
if(data == copyProcessArgs.object + chalk.green.bold(" downloaded")) {
done();
}
});
},
function(done) {
bar.tick({ title: chalk.blue('uploading') });
uploadObject({site: copyProcessArgs.destinationSite, bucket: copyProcessArgs.destinationBucket, object: copyProcessArgs.object, folder: __dirname + '/s3motionTransfer/', transfer: true}, function(data){
if(data == chalk.green.bold(copyProcessArgs.object + " uploaded")) {
done();
}
});
},
function(done) {
fs.unlink(__dirname + '/s3motionTransfer/' + copyProcessArgs.object, function (err) {
if (err) throw err;
bar.tick({ title: chalk.cyan('complete') });
done();
});
}
],
function(err, results){
if (err) {
done(chalk.red.bold('error occured with ' + copyProcessArgs.object + ': ') + chalk.yellow(err));
}
done(copyProcessArgs.object + chalk.green('successfully copied'));
});
}
//Using CLI & REST, all objects are added to this function as an array. This 'if' statement is here in case this becomes
//a npm package for inclusion in other projects where objects are not passed in as arrays from the original function
//When objects are passed in as an array, only do 10 objects at a time until completed
async.eachLimit(objectList, 10,
function(object, callback){
copyProcess({sourceSite: copyArgs.sourceSite, sourceBucket: copyArgs.sourceBucket, object: object['Key'], destinationSite: copyArgs.destinationSite, destinationBucket: copyArgs.destinationBucket}, function(data){
done(); //send data to the done callback from the source function
callback(); //send a callback response to the async callback.
});
}, function(err){
}
);
callback(); //send a callback response to the async callback to start the next List
done(); //send data to the done callback from the source function
}, function(err){
});
});
}
// @description Starts a web service to accept REST requests
var microservice = function() {
// call the packages we need to run the web service
var express = require('express'); // call express
var app = express(); // define our app using express
var timeout = require('connect-timeout');// set the timeout because waiting for object lists takes a while!
var bodyParser = require('body-parser'); // read POST
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// set the application timeout to 5 minutes.
app.use(timeout(300000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
next(); // make sure we go to the next routes and don't stop here
});
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'This is the API. Go read the documentation on how to use it' });
});
//creating a psuedo-model for clients
router.route('/clients')
.post(function(req, res) {
if (req.body.name == undefined || req.body.name == '' || req.body.accessKeyId == undefined || req.body.accessKeyId == '' || req.body.secretAccessKey == undefined || req.body.secretAccessKey == '') {
res.status(400)
.json({
operation: 'newClient',
client: req.params.client,
status: 'fail',
message: 'Incorrect Payload params. "name", "accessKeyId", and "secretAccessKey" are required',
});
} else {
newClient({name: req.body.name, accessKeyId: req.body.accessKeyId, secretAccessKey: req.body.secretAccessKey, endpoint: req.body.endpoint}, function(data){
console.log(data);
if (data == chalk.yellow.bold(req.body.name) + chalk.green.bold(" client created")){
res.json({
operation: 'newClient',
client: req.body.name,
accessKeyId: req.body.accessKeyId,
secretAccessKey: req.body.secretAccessKey,
endpoint: req.body.endpoint,
status: 'success',
});
} else if (data == chalk.yellow.bold(req.body.name) + chalk.red(" already exists. Please use a different name or edit the 's3motionClients.json' file")){
res.json({
operation: 'newClient',
client: req.body.name,
accessKeyId: req.body.accessKeyId,
secretAccessKey: req.body.secretAccessKey,
endpoint: req.body.endpoint,
status: 'fail',
message: req.body.name + ' already exists in s3motionClients.json'
});
}
});
}
})
.get(function(req, res) {
listClients(function(data){
res.json(data);
});
});
//creating a psuedo-model for buckets
router.route('/buckets/:client')
.post(function(req, res) {
if (req.body.name == undefined || req.body.name == '') {
res.status(400)
.json({
operation: 'newBucket',
client: req.params.client,
status: 'fail',
message: '"name" value not passed as payload. Please specify a "name" for the new bucket',
});
} else {
var name = req.body.name;
getClient({name: req.params.client, client: 'aws'}, function(client){
if (client == '') {
res.status(404)
.json({
operation: 'newBucket',
client: req.params.client,
status: 'fail',
message: client + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
newBucket({site: client, bucket: name}, function(data) {
res.json({
operation: 'newBucket',
client: req.params.client,
status: 'complete',
message: data
});
});
}
});
}
})
.get(function(req, res) {
getClient({name: req.params.client, client: 'aws'}, function(client){
if (client == '') {
res.status(404)
.json({
operation: 'listBuckets',
client: req.params.client,
status: 'fail',
message: client + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
listBuckets({site: client}, function(data) {
res.json(data);
});
}
});
});
//not even a model, just a generic POST call for bucket copy operations
router.route('/bucket/copy')
.post(function(req, res) {
if (req.body.sourceClient == undefined || req.body.sourceClient == '' || req.body.destClient == undefined || req.body.destClient == '' || req.body.sourceBucket == undefined || req.body.sourceBucket == '' || req.body.destBucket == undefined || req.body.destBucket == '') {
res.status(400)
.json({
operation: 'copyBucket',
client: req.params.client,
status: 'fail',
message: 'Incorrect Payload params. "sourceClient", "sourceBucket", "destClient" and "destBucket" are required',
});
} else {
getClient({name: req.body.sourceClient, client: 's3'}, function(sclient){
if (sclient == '') {
res.status(404)
.json({
operation: 'copyBucket',
sourceClient: req.body.sourceClient,
sourceBucket: req.body.sourceBucket,
destClient: req.body.destClient,
destBucket: req.body.destBucket,
status: 'fail',
message: req.body.sourceClient + ' not found in s3motionClients.json. Create it using /clients'
});
}
var sourceClient = sclient;
getClient({name: req.body.destClient, client: 's3'}, function(dclient){
if (dclient == '') {
res.status(404)
.json({
operation: 'copyBucket',
sourceClient: req.body.sourceClient,
sourceBucket: req.body.sourceBucket,
destClient: req.body.destClient,
destBucket: req.body.destBucket,
status: 'fail',
message: req.body.destClient + ' not found in s3motionClients.json. Create it using /clients'
});
}
var destClient = dclient
copyBucket({sourceSite: sourceClient, sourceBucket: req.body.sourceBucket, destinationSite: destClient, destinationBucket: req.body.destBucket}, function(data) {
});
res.json({
operation: 'copyBucket',
sourceClient: req.body.sourceClient,
sourceBucket: req.body.sourceBucket,
destClient: req.body.destClient,
destBucket: req.body.destBucket,
status: 'running',
});
});
});
}
});
//creating a psuedo-model for objects
router.route('/objects/:client/:bucket')
.post(function(req, res) {
if (req.body.object == undefined || req.body.object == '') {
res.status(400)
.json({
operation: 'objectUpload',
client: req.params.client,
status: 'fail',
message: 'Incorrect Payload params. "object" is required',
});
} else {
var folder = req.body.folder;
var objects = req.body.object.split(',');
var objectsArrayLength = objects.length - 1;
getClient({name: req.params.client, client: 's3'}, function(client){
if (client == '') {
res.status(404)
.json({
operation: 'objectUpload',
objects: req.body.object,
client: req.params.client,
bucket: req.params.bucket,
status: 'fail',
message: req.params.client + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
if(folder == ''){
folder = undefined;
}
uploadObject({site: client, bucket: req.params.bucket, object: objects, folder: folder}, function(data) {
if (data instanceof Array){
//
} else if (data == chalk.green.bold(objects[objectsArrayLength] + " uploaded")) {
res.json({
operation: 'objectUpload',
objects: req.body.object,
folder: req.body.folder,
client: req.params.client,
bucket: req.params.bucket,
status: 'complete'
});
}
});
}
});
}
})
.get(function(req, res) {
getClient({name: req.params.client, client: 's3'}, function(client){
if (client == '') {
res.status(404)
.json({
operation: 'objectList',
client: req.params.client,
bucket: req.params.bucket,
status: 'fail',
message: client + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
listObjects({site: client, bucket: req.params.bucket}, function(data) {
res.json(data);
});
}
});
})
.delete(function(req, res) {
if (req.body.object == undefined || req.body.object == '') {
res.status(400)
.json({
operation: 'objectUpload',
client: req.params.client,
bucket: req.params.bucket,
status: 'fail',
message: 'Incorrect Payload params. "object" is required',
});
} else {
var objects = req.body.object.split(',');
getClient({name: req.params.client, client: 's3'}, function(client){
if (client == '') {
res.status(404)
.json({
operation: 'objectDelete',
objects: objects.toString(),
client: req.params.client,
bucket: req.params.bucket,
status: 'fail',
message: client + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
deleteObject({site: client, bucket: req.params.bucket, object: objects}, function(data) {
if (data instanceof Array){
//
} else {
res.json({
operation: 'objectDelete',
objects: objects.toString(),
client: req.params.client,
bucket: req.params.bucket,
status: 'complete'
});
}
});
}
});
}
});
//not even a model, just a generic POST call for object copy operations
router.route('/object/copy')
.post(function(req, res) {
var operation;
if (req.body.delete == 'Y'){
operation = 'objectMove';
} else {
operation = 'objectCopy';
}
if (req.body.sourceClient == undefined || req.body.sourceClient == '' || req.body.sourceBucket == undefined || req.body.sourceBucket == '' || req.body.destClient == undefined || req.body.destClient == '' || req.body.destBucket == undefined || req.body.destBucket == '' || req.body.object == undefined || req.body.object == '') {
res.status(400)
.json({
operation: operation,
status: 'fail',
message: 'Incorrect Payload params. "sourceClient", "sourceBucket", "destClient", "destBucket", "object" is required',
});
} else {
getClient({name: req.body.sourceClient, client: 's3'}, function(sclient){
if (sclient == '') {
res.status(404)
.json({
operation: operation,
objects: req.body.object,
sourceClient: req.body.sourceClient,
sourceBucket: req.body.sourceBucket,
destClient: req.body.destClient,
destBucket: req.body.destBucket,
status: 'fail',
message: req.body.sourceClient + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
var sourceClient = sclient;
getClient({name: req.body.destClient, client: 's3'}, function(dclient){
if (dclient == '') {
res.status(404)
.json({
operation: operation,
objects: req.body.object,
sourceClient: req.body.sourceClient,
sourceBucket: req.body.sourceBucket,
destClient: req.body.destClient,
destBucket: req.body.destBucket,
status: 'fail',
message: req.body.destClient + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
var destClient = dclient
var objects = req.body.object.split(',');
if (req.body.delete == 'Y'){
moveObject({sourceSite: sourceClient, sourceBucket: req.body.sourceBucket, object: objects, destinationSite: destClient, destinationBucket: req.body.destBucket}, function(data) {
//console.log(data);
});
} else {
copyObject({sourceSite: sourceClient, sourceBucket: req.body.sourceBucket, object: objects, destinationSite: destClient, destinationBucket: req.body.destBucket}, function(data) {
//console.log(data);
});
}
res.json({
operation: operation,
objects: objects.toString(),
sourceClient: req.body.sourceClient,
sourceBucket: req.body.sourceBucket,
destClient: req.body.destClient,
destBucket: req.body.destBucket,
status: 'running'
});
}
});
}
});
}
});
router.route('/object/download')
.post(function(req, res) {
if (req.body.client == undefined || req.body.client == '' || req.body.bucket == undefined || req.body.bucket == '' || req.body.object == undefined || req.body.object == '') {
res.status(400)
.json({
operation: 'downloadObject',
status: 'fail',
message: 'Incorrect Payload params. "client", "bucket", and "object" are required',
});
} else {
getClient({name: req.body.client, client: 's3'}, function(client){
if (client == '') {
res.status(404)
.json({
operation: 'downloadObject',
object: req.body.object,
folder: req.body.folder,
client: req.body.client,
bucket: req.body.bucket,
status: 'fail',
message: req.body.client + ' not found in s3motionClients.json. Create it using /clients'
});
} else {
if(req.body.folder == ''){
req.body.folder = undefined;
}
var objects = req.body.object.split(',');
var objectsArrayLength = objects.length - 1;
downloadObject({site: client, bucket: req.body.bucket, object: objects, folder: req.body.folder}, function(data) {
if (data instanceof Array){
//
} else if (data == objects[objectsArrayLength] + chalk.green.bold(" downloaded")) {
res.json({
operation: 'downloadObject',
object: req.body.object,
folder: req.body.folder,
client: req.body.client,
bucket: req.body.bucket,
status: 'complete'
});
}
});
}
});
}
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('s3motion microservice started on port ' + port);
}
// @description Commander for using s3motion as a Command Line (CLI) tool
program
.version('0.1.0')
.usage('-flag <Args> Supply only 1 flag. Args will vary based on flag. To use the wizard, type the flag and "wizard" (ie. s3motion -n wizard)')
.option('-n, --newClient <--name --accessKeyId --secretAccessKey --endpoint>', 'Add a New Client (will be stored in clients.json)')
.option('-L, --listClients', 'List clients')
.option('-b, --listBuckets <--client>', 'List buckets for a specific client')