forked from awslabs/aws-js-s3-explorer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
explorer.js
1577 lines (1355 loc) · 58.5 KB
/
explorer.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
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
//
// You may not use this file except in compliance with the License. A copy
// of the License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
/* ESLint file-level overrides */
/* global AWS bootbox document moment window $ angular:true */
/* eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }] */
/* eslint-disable no-console */
/* eslint no-plusplus: "off" */
/* eslint-env es6 */
// __ _
// / _|_ __ ___ _ __ ___| |__
// | |_| '__/ _ \ '_ \ / __| '_ \
// | _| | | __/ | | | (__| | | |
// |_| |_| \___|_| |_|\___|_| |_|
frenchConfig = {
pageTitle: "Application d'exploration de fichiers",
settings: "AAW Storage Explorer: Paramètres",
initialView: "vue initiale",
initialPrefix: "préfixe initial",
folderDescription: "Dossier (montre dossier par dossier)",
bucketDescription: "S3 Bucket (montre le contenu entier du S3 bucket)",
cancel: "annuler",
queryS3: "interroger S3",
newFolder: "AAW Storage Explorer: Nouveau dossier",
newFolderExplanation: "Veuillez entrer le chemin relatif du dossier S3 à ajouter, par exemple dossier-01 ou papier-peint/animaux/chiens.",
addFolder: "ajouter un dossier",
confirmDelete: "Veuillez confirmer que vous voulez supprimer les objets suivants de S3.",
bucket: "<b>Bucket</b>: Veuillez indiquer la région et le S3 bucket que vous souhaitez explorer.",
probdisclaimer: "<b>Note</b>: Le bucket protégé B est accessible seulement à partir d'un notebook protégé B.",
options: "<b>Options</b>: AAW Storage Explorer peut afficher le contenu de votre S3 bucket dossier par dossier ou afficher une vue plate de l'ensemble du bucket. En outre, si vous voulez commencer dans un dossier qui n'est pas le dossier racine, entrez le préfixe initial ci-dessous, par exemple <i>song</i>.",
object: "Objet",
folder: "Dossier",
lastModified: "Dernière Modification",
timestamp: "Horodatage",
class: "Classe",
size: "Taille",
result: "Résultat",
key: "Clé",
value: "Valeur",
advanced: "Avancé",
close: "Fermer",
confirmUpload: "Veuillez confirmer que vous voulez télécharger les fichiers suivants vers S3.",
filename: "Nom de Fichier",
progress: "Progrès",
uploadDestination: "Les fichiers sélectionnés seront téléchargés vers: ",
select: "Sélectionnez",
unclassified: "Non classifié",
unclassifiedro: "Non classifié (lecture seule)",
protectedb: "Protégé B",
}
// _ _ _
// ___ _ __ __ _| (_)___| |__
// / _ \ '_ \ / _` | | / __| '_ \
// | __/ | | | (_| | | \__ \ | | |
// \___|_| |_|\__, |_|_|___/_| |_|
// |___/
englishConfig = {
pageTitle: "AAW Storage Explorer",
settings: "AAW Storage Explorer: Settings",
initialView: "Initial View",
initialPrefix: "Initial Prefix",
folderDescription: "Folder (shows folder-by-folder)",
bucketDescription: "Bucket (shows entire bucket contents)",
cancel: "Cancel",
queryS3: "Query S3",
newFolder: "AAW Storage Explorer: New Folder",
newFolderExplanation: "Please enter the relative path of the S3 folder to add, for example folder-01 or wallpaper/animals/dogs.",
addFolder: "Add folder",
confirmDelete: "Please confirm that you want to delete the following objects from S3.",
bucket: "<b>Bucket</b>: Please indicate which region and S3 bucket you want to explore.",
probdisclaimer: "<b>Note</b>: Protected B bucket can only be accessed from a Protected B notebook.",
options: "<b>Options</b>: AAW Storage Explorer can show your S3 bucket contents folder-by-folder or it can show a flat view of the entire bucket. Also, if you want to start in a folder that is not the root folder then enter the initial prefix below, for example <i>songs/</i>.",
object: "object",
folder: "folder",
lastModified: "Last Modified",
timestamp: "Timestamp",
class: "Class",
size: "Size",
result: "Result",
key: "Key",
value: "Value",
advanced: "Advanced",
close: "Close",
confirmUpload: "Please confirm that you want to upload the following files to S3.",
filename: "Filename",
progress: "Progress",
uploadDestination: "The selected files will be uploaded to:",
select: "Select",
unclassified: "Unclassified",
unclassifiedro: "Unclassified (Read Only)",
protectedb: "Protected B",
}
/**
* Register service worker if supported by browser; otherwise log error message.
*/
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('sw_modify_header.js')
.then(reg => console.log("Service Worker: Registered"))
.catch(err => console.log(`Service Worker: Error: ${err}`))
})
}
const s3ExplorerColumns = {
check: 0, object: 1, folder: 2, date: 3, timestamp: 4, storageclass: 5, size: 6,
};
// Cache frequently-used selectors and data table
const $tb = $('#s3objects-table');
const $bc = $('#breadcrumb');
const $bl = $('#bucket-loader');
// Map S3 storage types to text
const mapStorage = {
STANDARD: 'Standard',
STANDARD_IA: 'Standard IA',
ONEZONE_IA: 'One Zone-IA',
REDUCED_REDUNDANCY: 'Reduced Redundancy',
GLACIER: 'Glacier',
INTELLIGENT_TIERING: 'Intelligent Tiering',
DEEP_ARCHIVE: 'Deep Archive',
};
// Debug utility to complement console.log
const DEBUG = (() => {
const timestamp = () => {};
timestamp.toString = () => `[DEBUG ${moment().format()}]`;
return {
log: console.log.bind(console, '%s', timestamp),
};
})();
// Utility to convert bytes to readable text e.g. "2 KB" or "5 MB"
function bytesToSize(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Bytes';
const ii = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
return `${Math.round(bytes / (1024 ** ii), 2)} ${sizes[ii]}`;
}
// Escape strings of HTML
function htmlEscape(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/')
.replace(/`/g, '`')
.replace(/=/g, '=');
}
// Convert cars/vw/golf.png to golf.png
function fullpath2filename(path, escape = false) {
const rc = path.replace(/^.*[\\/]/, '');
return escape ? htmlEscape(rc) : rc;
}
// Convert cars/vw/golf.png to cars/vw/
function fullpath2pathname(path, escape = false) {
const index = path.lastIndexOf('/');
const rc = (index === -1) ? '/' : path.substring(0, index + 1);
return escape ? htmlEscape(rc) : rc;
}
// Convert cars/vw/ to vw/
function prefix2folder(prefix, escape = false) {
const parts = prefix.split('/');
const rc = `${parts[parts.length - 2]}/`;
return escape ? htmlEscape(rc) : rc;
}
// Convert cars/vw/sedans/ to cars/vw/
function prefix2parentfolder(prefix, escape = false) {
const parts = prefix.split('/');
parts.splice(parts.length - 2, 1);
const rc = parts.join('/');
return escape ? htmlEscape(rc) : rc;
}
// Convert cars/vw/golf.png to cars/.../golf.png
const pathLimit = 80; // Max allowed path length
const pathHellip = String.fromCharCode(8230); // '…' char
function path2short(path, escape = false) {
if (path.length < pathLimit) return escape ? htmlEscape(path) : path;
const soft = `${prefix2parentfolder(fullpath2pathname(path)) + pathHellip}/${fullpath2filename(path)}`;
if (soft.length < pathLimit && soft.length > 2) return escape ? htmlEscape(soft) : soft;
const hard = `${path.substring(0, path.indexOf('/') + 1) + pathHellip}/${fullpath2filename(path)}`;
const rc = hard.length < pathLimit ? hard : path.substring(0, pathLimit) + pathHellip;
return escape ? htmlEscape(rc) : rc;
}
// Virtual-hosted-style URL, ex: https://mybucket1.s3.amazonaws.com/index.html
function object2hrefvirt(bucket, key, escape = false) {
const enckey = key.split('/').map(x => encodeURIComponent(x)).join('/');
const rc = `${document.location.protocol}//${document.location.host}/${bucket}/${enckey}`;
return escape ? htmlEscape(rc) : rc;
}
// Path-style URLs, ex: https://s3.amazonaws.com/mybucket1/index.html
// eslint-disable-next-line no-unused-vars
function object2hrefpath(bucket, key, escape = false) {
const enckey = key.split('/').map(x => encodeURIComponent(x)).join('/');
const rc = `${document.location.protocol}//${document.location.host}/${bucket}/${enckey}`;
return escape ? htmlEscape(rc) : rc;
}
function isfolder(path) {
return path.endsWith('/');
}
function stripLeadTrailSlash(s) {
return s.replace(/^\/+/g, '').replace(/\/+$/g, '');
}
//
// Shared service that all controllers can use
//
function SharedService($rootScope) {
DEBUG.log('SharedService init');
const shared = {
settings: null, viewprefix: null, skew: true,
};
shared.getSettings = () => this.settings;
shared.addFiles = (files) => { this.added_files = files; };
shared.getAddedFiles = () => this.added_files;
shared.hasAddedFiles = () => Object.prototype.hasOwnProperty.call(this, 'added_files');
shared.resetAddedFiles = () => { delete this.added_files; };
shared.changeSettings = (settings) => {
DEBUG.log('SharedService::changeSettings');
DEBUG.log('SharedService::changeSettings settings', settings);
this.settings = settings;
this.viewprefix = null;
$.fn.dataTableExt.afnFiltering.length = 0;
// AWS.config.update(settings.cred);
AWS.config.update({ region: "" });
AWS.config.update(Object.assign(settings.cred, {
region: settings.region,
ep: document.location.hostname
}));
if (this.skew) {
this.correctClockSkew(settings.bucket);
this.skew = false;
}
if (settings.mfa.use === 'yes') {
const iam = new AWS.IAM();
DEBUG.log('listMFADevices');
iam.listMFADevices({}, (err1, data1) => {
if (err1) {
DEBUG.log('listMFADevices error:', err1);
} else {
const sts = new AWS.STS();
DEBUG.log('listMFADevices data:', data1);
const params = {
DurationSeconds: 3600,
SerialNumber: data1.MFADevices[0].SerialNumber,
TokenCode: settings.mfa.code,
};
DEBUG.log('getSessionToken params:', params);
sts.getSessionToken(params, (err2, data2) => {
if (err2) {
DEBUG.log('getSessionToken error:', err2);
} else {
DEBUG.log('getSessionToken data:', data2);
this.settings.stscred = {
accessKeyId: data2.Credentials.AccessKeyId,
secretAccessKey: data2.Credentials.SecretAccessKey,
sessionToken: data2.Credentials.SessionToken,
};
AWS.config.update(this.settings.stscred);
$rootScope.$broadcast('broadcastChangeSettings', { settings: this.settings });
}
});
}
});
} else {
$rootScope.$broadcast('broadcastChangeSettings', { settings });
}
};
shared.changeViewPrefix = (prefix) => {
DEBUG.log('SharedService::changeViewPrefix');
if (this.settings.delimiter) {
// Folder-level view
this.settings.prefix = prefix;
this.viewprefix = null;
$.fn.dataTableExt.afnFiltering.length = 0;
$rootScope.$broadcast('broadcastChangePrefix', { prefix });
} else {
// Bucket-level view
this.viewprefix = prefix;
$rootScope.$broadcast('broadcastChangePrefix', { viewprefix: prefix });
}
};
shared.getViewPrefix = () => this.viewprefix || this.settings.prefix;
shared.viewRefresh = () => $rootScope.$broadcast('broadcastViewRefresh');
shared.trashObjects = (bucket, keys) => $rootScope.$broadcast('broadcastTrashObjects', { bucket, keys });
shared.addFolder = (_bucket, _folder) => $rootScope.$broadcast('broadcastViewRefresh');
// We use pre-signed URLs so that the user can securely download
// objects. For security reasons, we make these URLs time-limited and in
// order to do that we need the client's clock to be in sync with the AWS
// S3 endpoint otherwise we might create URLs that are immediately invalid,
// for example if the client's browser time is 55 minutes behind S3's time.
shared.correctClockSkew = (Bucket) => {
const s3 = new AWS.S3();
DEBUG.log('Invoke headBucket:', Bucket);
// Head the bucket to get a Date response. The 'date' header will need
// to be exposed in S3 CORS configuration.
s3.headBucket({ Bucket }, (err, data) => {
if (err) {
DEBUG.log('headBucket error:', err);
} else {
DEBUG.log('headBucket data:', JSON.stringify(data));
DEBUG.log('headBucket headers:', JSON.stringify(this.httpResponse.headers));
if (this.httpResponse.headers.date) {
const date = Date.parse(this.httpResponse.headers.date);
DEBUG.log('headers date:', date);
AWS.config.systemClockOffset = new Date() - date;
DEBUG.log('clock offset:', AWS.config.systemClockOffset);
// Can now safely generate presigned urls
}
}
});
};
// Common error handling is done here in the shared service.
shared.showError = (params, err) => {
DEBUG.log(err);
const { message, code } = err;
const errors = Object.entries(err).map(([key, value]) => ({ key, value }));
const args = {
params, message, code, errors,
};
$rootScope.$broadcast('broadcastError', args);
};
return shared;
}
//
// ViewController: code associated with the main S3 Explorer table that shows
// the contents of the current bucket/folder and allows the user to downloads
// files, delete files, and do various other S3 functions.
//
// eslint-disable-next-line no-shadow
function ViewController($scope, SharedService) {
DEBUG.log('ViewController init');
window.viewScope = $scope; // for debugging
$scope.view = {
bucket: null, prefix: null, settings: null, objectCount: 0, keys_selected: [],
};
$scope.stop = false;
// Delegated event handler for S3 object/folder clicks. This is delegated
// because the object/folder rows are added dynamically and we do not want
// to have to assign click handlers to each and every row.
$tb.on('click', 'a', (e) => {
const { currentTarget: target } = e;
e.preventDefault();
DEBUG.log('target href:', target.href);
DEBUG.log('target dataset:', JSON.stringify(target.dataset));
if (target.dataset.s3 === 'folder') {
// User has clicked on a folder so navigate into that folder
SharedService.changeViewPrefix(target.dataset.s3key);
} else if ($scope.view.settings.auth === 'anon') {
// Unauthenticated user has clicked on an object so download it
// in new window/tab
window.open(target.href, '_blank');
} else {
// Authenticated user has clicked on an object so create pre-signed
// URL and download it in new window/tab
const s3 = new AWS.S3({endpoint: `${document.location.protocol}//${document.location.hostname}`});
const params = {
Bucket: $scope.view.settings.bucket, Key: target.dataset.s3key, Expires: 15,
};
DEBUG.log('params:', params);
s3.getSignedUrl('getObject', params, (err, url) => {
if (err) {
DEBUG.log('err:', err);
SharedService.showError(params, err);
} else {
DEBUG.log('url:', url);
window.open(url, '_blank');
}
});
}
return false;
});
// Delegated event handler for breadcrumb clicks.
$bc.on('click', 'a', (e) => {
DEBUG.log('breadcrumb li click');
e.preventDefault();
const { currentTarget: target } = e;
DEBUG.log('target dataset:', JSON.stringify(target.dataset));
SharedService.changeViewPrefix(target.dataset.prefix);
return false;
});
$scope.$on('broadcastChangeSettings', (e, args) => {
DEBUG.log('ViewController', 'broadcast change settings:', args.settings);
$scope.view.objectCount = 0;
$scope.view.settings = args.settings;
$scope.refresh();
});
$scope.$on('broadcastChangePrefix', (e, args) => {
DEBUG.log('ViewController', 'broadcast change prefix args:', args);
$scope.$apply(() => {
// Create breadcrumbs from current path (S3 bucket plus folder hierarchy)
$scope.folder2breadcrumbs($scope.view.settings.bucket, args.viewprefix || args.prefix);
if (args.viewprefix !== undefined && args.viewprefix !== null) {
// In bucket-level view we already have the data so we just need to
// filter it on prefix.
$.fn.dataTableExt.afnFiltering.length = 0;
$.fn.dataTableExt.afnFiltering.push(
// Filter function returns true to include item in view
(_o, d, _i) => d[1] !== args.viewprefix && d[1].startsWith(args.viewprefix),
);
// Re-draw the table
$tb.DataTable().draw();
} else {
// In folder-level view, we actually need to query the data for the
// the newly-selected folder.
$.fn.dataTableExt.afnFiltering.length = 0;
$scope.view.settings.prefix = args.prefix;
$scope.refresh();
}
});
});
$scope.$on('broadcastViewRefresh', () => {
DEBUG.log('ViewController', 'broadcast view refresh');
$scope.$apply(() => {
$scope.refresh();
});
});
$scope.renderObject = (data, _type, full) => {
// DEBUG.log('renderObject:', JSON.stringify(full));
const hrefv = object2hrefvirt($scope.view.settings.bucket, data);
function buildAnchor(s3key, href, text, download) {
const a = $('<a>');
a.attr({ 'data-s3key': s3key });
a.attr({ href });
if (download) {
a.attr({ 'data-s3': 'object' });
a.attr({ download });
} else {
a.attr({ 'data-s3': 'folder' });
}
a.text(text);
return a.prop('outerHTML');
}
function render(d, href, text, download) {
if (download) {
return buildAnchor(d, href, text, download);
}
return buildAnchor(d, href, text);
}
if (full.CommonPrefix) {
if ($scope.view.settings.prefix) {
return render(data, hrefv, prefix2folder(data));
}
return render(data, hrefv, data);
}
return render(data, hrefv, fullpath2filename(data), fullpath2filename(data));
};
$scope.renderFolder = (data, _type, full) => (full.CommonPrefix ? '' : fullpath2pathname(data, true));
$scope.progresscb = (objects, folders) => {
DEBUG.log('ViewController', 'Progress cb objects:', objects);
DEBUG.log('ViewController', 'Progress cb folders:', folders);
$scope.$apply(() => {
$scope.view.objectCount += objects + folders;
});
};
$scope.refresh = () => {
DEBUG.log('refresh');
if ($scope.running()) {
DEBUG.log('running, stop');
$scope.listobjectsstop();
} else {
DEBUG.log('refresh', $scope.view.settings);
$scope.view.objectCount = 0;
$scope.folder2breadcrumbs(
$scope.view.settings.bucket,
SharedService.getViewPrefix(),
);
$scope.listobjects(
$scope.view.settings.bucket,
$scope.view.settings.prefix,
$scope.view.settings.delimiter,
);
}
};
$scope.upload = () => {
DEBUG.log('Add files');
$('#addedFiles').trigger('click');
};
$scope.trash = () => {
DEBUG.log('Trash:', $scope.view.keys_selected);
if ($scope.view.keys_selected.length > 0) {
SharedService.trashObjects($scope.view.settings.bucket, $scope.view.keys_selected);
}
};
/**
* Toggle between french and english.
*/
$scope.english = true
$scope.toggle = () => {
$scope.english = !$scope.english;
const translatePhrase = (key) => {
if ($scope.english) {
return englishConfig[key]
} else {
return frenchConfig[key]
}
}
const replaceText = (el) => {
el.innerHTML = translatePhrase(el.attributes["base-value"].nodeValue)
}
const elements = document.querySelectorAll("[data-i18n]");
elements.forEach(el => replaceText(el))
}
$scope.running = () => $bl.hasClass('fa-spin');
$scope.folder2breadcrumbs = (bucket, prefix) => {
DEBUG.log('Breadcrumbs bucket:', bucket);
DEBUG.log('Breadcrumbs prefix:', prefix);
// Empty the current breadcrumb list
$('#breadcrumb li').remove();
// This array will contain the needed prefixes for each folder level.
const prefixes = [''];
let buildprefix = '';
if (prefix) {
prefixes.push(...prefix.replace(/\/$/g, '').split('/'));
}
// Add bucket followed by prefix segments to make breadcrumbs
for (let ii = 0; ii < prefixes.length; ii++) {
let li;
// Bucket
if (ii === 0) {
const a1 = $('<a>').attr('href', '#').text(bucket);
li = $('<li>').append(a1);
// Followed by n - 1 intermediate folders
} else if (ii < prefixes.length - 1) {
const a2 = $('<a>').attr('href', '#').text(prefixes[ii]);
li = $('<li>').append(a2);
// Followed by current folder
} else {
li = $('<li>').text(prefixes[ii]);
}
// Accumulate prefix
if (ii) {
buildprefix = `${buildprefix}${prefixes[ii]}/`;
}
// Save prefix & bucket data for later click handler
li.children('a').attr('data-prefix', buildprefix).attr('data-bucket', bucket);
// Add to breadcrumbs
$bc.append(li);
}
// Make last breadcrumb active
$('#breadcrumb li:last').addClass('active');
};
$scope.listobjectsstop = (stop) => {
DEBUG.log('ViewController', 'listobjectsstop:', stop || true);
$scope.stop = stop || true;
};
// This is the listObjects callback
$scope.listobjectscb = (err, data) => {
DEBUG.log('Enter listobjectscb');
if (err) {
DEBUG.log('Error:', JSON.stringify(err));
DEBUG.log('Error:', err.stack);
$bl.removeClass('fa-spin');
const params = { bucket: $scope.view.bucket, prefix: $scope.view.prefix };
SharedService.showError(params, err);
} else {
let marker;
// Store marker before filtering data. Note that Marker is the
// previous request marker, not the marker to use on the next call
// to listObject. For the one to use on the next invocation you
// need to use NextMarker or retrieve the key of the last item.
if (data.IsTruncated) {
if (data.NextMarker) {
marker = data.NextMarker;
} else if (data.Contents.length > 0) {
marker = data.Contents[data.Contents.length - 1].Key;
}
}
const count = { objects: 0, folders: 0 };
// NOTE: folders are returned in CommonPrefixes if delimiter is
// supplied on the listObjects call and in Contents if delimiter
// is not supplied on the listObjects call, so we may need to
// source our DataTable folders from Contents or CommonPrefixes.
// DEBUG.log("Contents", data.Contents);
$.each(data.Contents, (index, value) => {
if (value.Key === data.Prefix) {
// ignore this folder
} else if (isfolder(value.Key)) {
$tb.DataTable().row.add({
CommonPrefix: true, Key: value.Key, StorageClass: null,
});
count.folders++;
} else {
$tb.DataTable().row.add(value);
count.objects++;
}
});
// Add folders to the datatable. Note that folder entries in the
// DataTable will have different content to object entries and the
// folders can be identified by CommonPrefix=true.
// DEBUG.log("CommonPrefixes:", data.CommonPrefixes);
$.each(data.CommonPrefixes, (index, value) => {
$tb.DataTable().rows.add([
{ CommonPrefix: true, Key: value.Prefix, StorageClass: null },
]);
count.objects++;
});
// Re-draw the table
$tb.DataTable().draw();
// Make progress callback to report objects read so far
$scope.progresscb(count.objects, count.folders);
const params = {
Bucket: data.Name, Prefix: data.Prefix, Delimiter: data.Delimiter, Marker: marker,
};
// DEBUG.log("AWS.config:", JSON.stringify(AWS.config));
if ($scope.stop) {
DEBUG.log('Bucket', data.Name, 'stopped');
$bl.removeClass('fa-spin');
} else if (data.IsTruncated) {
DEBUG.log('Bucket', data.Name, 'truncated');
const s3 = new AWS.S3(AWS.config);
if (AWS.config.credentials && AWS.config.credentials.accessKeyId) {
DEBUG.log('Make S3 authenticated call to listObjects');
s3.listObjects(params, $scope.listobjectscb);
} else {
DEBUG.log('Make S3 unauthenticated call to listObjects');
s3.makeUnauthenticatedRequest('listObjects', params, $scope.listobjectscb);
}
} else {
DEBUG.log('Bucket', data.Name, 'listing complete');
$bl.removeClass('fa-spin');
}
}
};
// Start the spinner, clear the table, make an S3 listObjects request
$scope.listobjects = (Bucket, Prefix, Delimiter, Marker) => {
DEBUG.log('Enter listobjects');
// If this is the initial listObjects
if (!Marker) {
// Checked on each event cycle to stop list prematurely
$scope.stop = false;
// Start spinner and clear table
$scope.view.keys_selected = [];
$bl.addClass('fa-spin');
$tb.DataTable().clear();
$tb.DataTable().column(s3ExplorerColumns.folder).visible(!Delimiter);
}
const s3 = new AWS.S3(AWS.config);
const params = {
Bucket, Prefix, Delimiter, Marker,
};
// DEBUG.log("AWS.config:", JSON.stringify(AWS.config));
// Now make S3 listObjects call(s)
if (AWS.config.credentials && AWS.config.credentials.accessKeyId) {
DEBUG.log('Make S3 authenticated call to listObjects, params:', params);
s3.listObjects(params, $scope.listobjectscb);
} else {
DEBUG.log('Make S3 unauthenticated call to listObjects, params:', params);
s3.makeUnauthenticatedRequest('listObjects', params, $scope.listobjectscb);
}
};
this.isfolder = path => path.endsWith('/');
// Individual render functions so that we can control how column data appears
this.renderSelect = (data, type, _full) => {
if (type === 'display') {
return '<span class="text-center"><input type="checkbox"></span>';
}
return '';
};
this.renderObject = (data, type, full) => {
if (type === 'display') {
return $scope.renderObject(data, type, full);
}
return data;
};
this.renderFolder = (data, type, full) => $scope.renderFolder(data, type, full);
this.renderLastModified = (data, _type, _full) => {
if (data) {
return moment(data).fromNow();
}
return '';
};
this.renderTimestamp = (data, _type, _full) => {
if (data) {
return moment(data).local().format('YYYY-MM-DD HH:mm:ss');
}
return '';
};
this.renderStorageClass = (data, _type, _full) => {
if (data) {
return mapStorage[data];
}
return '';
};
// Object sizes are displayed in nicer format e.g. 1.2 MB but are otherwise
// handled as simple number of bytes e.g. for sorting purposes
this.dataSize = (source, type, _val) => {
if (source.Size) {
return (type === 'display') ? bytesToSize(source.Size) : source.Size;
}
return '';
};
// Initial DataTable settings (must only do this one time)
$tb.DataTable({
iDisplayLength: 25,
order: [[2, 'asc'], [1, 'asc']],
aoColumnDefs: [
{
aTargets: [0], mData: null, mRender: this.renderSelect, sClass: 'text-center', sWidth: '20px', bSortable: false,
},
{
aTargets: [1], mData: 'Key', mRender: this.renderObject, sType: 'key',
},
{
aTargets: [2], mData: 'Key', mRender: this.renderFolder,
},
{
aTargets: [3], mData: 'LastModified', mRender: this.renderLastModified,
},
{
aTargets: [4], mData: 'LastModified', mRender: this.renderTimestamp,
},
{
aTargets: [5], mData: 'StorageClass', mRender: this.renderStorageClass,
},
{
aTargets: [6], mData: this.dataSize,
},
],
});
// Custom ascending sort for Key column so folders appear before objects
$.fn.dataTableExt.oSort['key-asc'] = (a, b) => {
const x = (isfolder(a) ? `0-${a}` : `1-${a}`).toLowerCase();
const y = (isfolder(b) ? `0-${b}` : `1-${b}`).toLowerCase();
if (x < y) return -1;
if (x > y) return 1;
return 0;
};
// Custom descending sort for Key column so folders appear before objects
$.fn.dataTableExt.oSort['key-desc'] = (a, b) => {
const x = (isfolder(a) ? `1-${a}` : `0-${a}`).toLowerCase();
const y = (isfolder(b) ? `1-${b}` : `0-${b}`).toLowerCase();
if (x < y) return 1;
if (x > y) return -1;
return 0;
};
// Handle click on selection checkbox
$('#s3objects-table tbody').on('click', 'input[type="checkbox"]', (e1) => {
const checkbox = e1.currentTarget;
const $row = $(checkbox).closest('tr');
const data = $tb.DataTable().row($row).data();
let index = -1;
// Prevent click event from propagating to parent
e1.stopPropagation();
// Find matching key in currently checked rows
index = $scope.view.keys_selected.findIndex(e2 => e2.Key === data.Key);
// Remove or add checked row as appropriate
if (checkbox.checked && index === -1) {
$scope.view.keys_selected.push(data);
} else if (!checkbox.checked && index !== -1) {
$scope.view.keys_selected.splice(index, 1);
}
$scope.$apply(() => {
// Doing this to force Angular to update models
DEBUG.log('Selected rows:', $scope.view.keys_selected);
});
if (checkbox.checked) {
$row.addClass('selected');
} else {
$row.removeClass('selected');
}
});
// Handle click on table cells
$('#s3objects-table tbody').on('click', 'td', (e) => {
$(e.currentTarget).parent().find('input[type="checkbox"]').trigger('click');
});
}
//
// AddFolderController: code associated with the add folder function.
//
// eslint-disable-next-line no-shadow
function AddFolderController($scope, SharedService) {
DEBUG.log('AddFolderController init');
$scope.add_folder = {
settings: null, bucket: null, entered_folder: '', view_prefix: '/',
};
window.addFolderScope = $scope; // for debugging
DEBUG.log('AddFolderController add_folder init', $scope.add_folder);
$scope.$on('broadcastChangeSettings', (e, args) => {
DEBUG.log('AddFolderController', 'broadcast change settings bucket:', args.settings.bucket);
$scope.add_folder.settings = args.settings;
$scope.add_folder.bucket = args.settings.bucket;
$scope.add_folder.view_prefix = args.settings.prefix || '/';
DEBUG.log('AddFolderController add_folder bcs', $scope.add_folder);
});
$scope.$on('broadcastChangePrefix', (e, args) => {
DEBUG.log('AddFolderController', 'broadcast change prefix args:', args);
$scope.add_folder.view_prefix = args.prefix || args.viewprefix || '/';
DEBUG.log('AddFolderController add_folder bcp', $scope.add_folder);
});
$scope.addFolder = () => {
DEBUG.log('Add folder');
DEBUG.log('Current prefix:', $scope.add_folder.view_prefix);
const ef = stripLeadTrailSlash($scope.add_folder.entered_folder);
const vpef = $scope.add_folder.view_prefix + ef;
const folder = `${stripLeadTrailSlash(vpef)}/`;
DEBUG.log('Calculated folder:', folder);
const s3 = new AWS.S3(AWS.config);
// we need to attach a '.empty' file as the request is attempting to create a directory,
// so that the new folder is able to be displayed.
const emptyFile = new File([''], '.empty', { type: 'text/plain' });
const headParams = {
Bucket: $scope.add_folder.bucket, Key: folder
};
const params = {
Body: emptyFile, Bucket: $scope.add_folder.bucket, Key: folder + ".empty", ContentType: emptyFile.type
};
DEBUG.log('Invoke headObject:', headParams);
// Test if an object with this key already exists
s3.headObject(headParams, (err1, _data1) => {
if (err1 && err1.code === 'NotFound') {
DEBUG.log('Invoke putObject:', params);
// Create a zero-sized object to simulate a folder
s3.putObject(params, (err2, _data2) => {
if (err2) {
DEBUG.log('putObject error:', err2);
bootbox.alert('Error creating folder');
} else {
SharedService.addFolder(params.Bucket, params.Key);
$('#AddFolderModal').modal('hide');
$scope.add_folder.entered_folder = '';
}
});
} else if (err1) {
DEBUG.log('headObject error:', err1);
bootbox.alert('Error checking existence of folder');
} else {
bootbox.alert('Error: folder or object already exists at: ' + params.Key);
}
});
};
}
//
// InfoController: code associated with the Info modal where the user can
// view bucket policies, CORS configuration and About text.
//
// Note: do not be tempted to correct the eslint no-unused-vars error
// with SharedService below. Doing so will break injection.
//
// eslint-disable-next-line no-shadow
function InfoController($scope) {
DEBUG.log('InfoController init');
window.infoScope = $scope; // for debugging
$scope.info = {
cors: null, policy: null, bucket: null, settings: null,
};
$scope.$on('broadcastChangeSettings', (e, args) => {
DEBUG.log('InfoController', 'broadcast change settings bucket:', args.settings.bucket);
$scope.info.settings = args.settings;
$scope.info.bucket = args.settings.bucket;
$scope.getBucketCors(args.settings.bucket);
$scope.getBucketPolicy(args.settings.bucket);
});
$scope.getBucketPolicy = (Bucket) => {
const params = { Bucket };
$scope.info.policy = 'No bucket policy';
};