forked from Normation/ncf
/
ncf.js
1854 lines (1645 loc) · 66.5 KB
/
ncf.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
'use strict';
// Helpers functions
var converter = new showdown.Converter();
// Swap two two items in an array based on their index
function swapTwoArrayItems(array, index1, index2) {
var item = array[index1];
array[index1] = array[index2];
array[index2] = item;
return array;
};
// check if the parameter used contains $(somecontent), where somecontent is neither
// a valid variable name (key.value), nor does contain /
// If the content is invalid, returns true, else false
var re = new RegExp(/\$\([^./]*\)/, 'm');
function detectIfVariableIsInvalid(parameter) {
return re.test(parameter);
}
// define ncf app, using ui-bootstrap and its default templates
var app = angular.module('ncf', ['ui.bootstrap', 'ui.bootstrap.tpls', 'monospaced.elastic', 'ngToast', 'dndLists', 'ngMessages', 'FileManagerApp'])
// A directive to add a filter on the technique name controller
// It should prevent having techniques with same name (case insensitive)
// It should not check with the original name of the technique so we can change its case
app.directive('techniquename', function($filter) {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.techniqueName = function(modelValue, viewValue) {
if(viewValue===undefined) return false;
// Get all techniqueNames in lowercase
var techniqueNames = scope.techniques.map(function (technique,index) { return technique.name.toLowerCase()})
// Remove the original name from the technique names array
if (scope.originalTechnique !== undefined && scope.originalTechnique.name !== undefined) {
techniqueNames = $filter("filter")(techniqueNames, scope.originalTechnique.name.toLowerCase(), function(actual,expected) { return ! angular.equals(expected,actual)})
}
// technique name is ok if the current value is not in the array
return $.inArray(viewValue.toLowerCase(), techniqueNames) === -1
};
}
};
});
app.directive('focusOn', function() {
return function(scope, elem, attr) {
scope.$on('focusOn', function(e, name) {
if(name === attr.focusOn) {
elem[0].focus();
}
});
};
});
app.factory('focus', function ($rootScope, $timeout) {
return function(name) {
$timeout(function (){
$rootScope.$broadcast('focusOn', name);
});
}
});
app.directive('bundlename', function($filter) {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$validators.bundleName = function(modelValue, viewValue) {
// Get all bundleNames
var bundleNames = scope.techniques.map(function (technique,index) { return technique.bundle_name})
// Remove the original bundle name from the bundle names array
if (scope.originalTechnique !== undefined && scope.originalTechnique.bundle_name !== undefined) {
bundleNames = $filter("filter")(bundleNames, scope.originalTechnique.bundle_name, function(actual,expected) { return ! angular.equals(expected,actual)})
}
// bundle name is ok if the current value is not in the array
return $.inArray(viewValue, bundleNames) === -1
};
}
};
});
app.directive('constraint', function($http, $q, $timeout) {
return {
scope: {
parameter: '='
, parameterinfo: "="
},
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
if((scope.parameterinfo.constraints.allow_empty_string)&&(scope.parameter.value === undefined)){
scope.parameter.value = "";
}
ctrl.$asyncValidators.constraint = function(modelValue, viewValue) {
scope.parameter.$errors= [];
if (modelValue === undefined) {
return $q.reject("Value is empty");
}
var data = {"value" : modelValue, "constraints" : scope.parameterinfo.constraints}
var timeoutStatus = false;
var timeout = $q.defer();
var request = $http.post("/rudder/secure/api/internal/techniques/parameter/check",data, { 'timeout' : timeout.promise }).then(
function(successResult) {
scope.parameter.$errors= [];
if (! successResult.data.data.parameterCheck.result) {
scope.parameter.$errors = successResult.data.data.parameterCheck.errors;
return $q.reject('Constraint is not valid');
}
return $q.when(modelValue);
}
, function(errorResult) {
// If there was an error with the request, accept the value, it will be checked when saving
// Maybe we should display a warning but I'm not sure at all ...
if (timeoutStatus) {
return $q.when('request timeout');
}
return $q.when('Error during check request')
}
)
$timeout( function() {
timeoutStatus = true;
timeout.resolve();
}, 500);
return request;
};
}
};
});
app.directive('showErrors', function() {
return {
restrict: 'A',
require: '^form',
link: function (scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box so we know the property to check
// on the form controller
var inputName = inputNgEl.attr('name');
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function() {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
})
}
}
});
app.filter('parameterName', function () {
return function (text) {
if (!text) {
return text;
}
return text.charAt(0).toUpperCase() + text.substring(1).replace(/_/g, ' '); // Replaces all occurences
};
})
// Declare controller ncf-builder
app.controller('ncf-builder', function ($scope, $uibModal, $http, $q, $location, $anchorScroll, ngToast, $timeout, focus, $sce, fileManagerConfig, apiMiddleware, apiHandler, $window) {
// Variable we use in the whole application
//UI state
$scope.ui = {
showTechniques : true
, activeTab : 'general'
, showMethodsFilter : true
, methodTabs : {}
, selectedMethods : []
, editForm : {}
, openedParamDescription : []
}
// Path of ncf files, defined as a url parameter
$scope.path;
// generic methods container
$scope.generic_methods;
// Generic methods order by category, used when we want to add new methods
$scope.methodsByCategory;
// ncf technique container
$scope.techniques;
$scope.techniqueCategories = [];
$scope.fileManagerState = {
open : false,
updating : false,
};
$scope.closeWindow = function(event, enforce){
if((enforce)||(event.currentTarget == event.target)){
$scope.fileManagerState.open = false;
}
}
// Selected technique, undefined when there is no selected technique
$scope.parameters;
$scope.selectedTechnique;
$scope.originalTechnique;
// Are we authenticated on the interface
$scope.authenticated = undefined;
//Generic methods filters
$scope.filter = {
compatibility : "all"
, showDeprecated : false
, text : ""
}
//Array containing the divergences of a technique
$scope.diverges = [];
var usingRudder = false;
$scope.CForm = {};
$scope.setPath = function() {
var path = $location.search().path;
if (path === undefined) {
$scope.path = "";
} else if ( path === true) {
$scope.path = "";
} else {
$scope.path = path;
}
};
// Callback when an element is dropped on the list of method calls
// return the element that will be added, if false do not add anything
$scope.dropCallback = function(elem, nextIndex, type){
// Add element
// if type is a bundle, then transform it to a method call and add it
if (type === "bundle") {
return toMethodCall(elem);
}
var selectedMethodIndex = $scope.ui.selectedMethods.findIndex(function(m){return angular.equals(elem, m)});
// Keep the method opened if it was
if (selectedMethodIndex>=0) {
$scope.ui.selectedMethods[selectedMethodIndex] = elem;
}
return elem;
}
// Define path by getting url params now
$scope.setPath();
// Define hash location url, this will make the page scroll to the good element since we use $anchorScroll
$scope.scroll = function(id) {
$location.hash(id);
$anchorScroll();
};
// Capitalize first letter of a string
$scope.capitaliseFirstLetter = function (string) {
if (string.length === 0) {
return string;
} else {
return string.charAt(0).toUpperCase() + string.slice(1);
}
};
function errorNotification (message,details) {
var errorMessage = '<b>An Error occured!</b> ' + message
if (details !== undefined) {
errorMessage += '<br/><b>Details:</b><pre class="error-pre">' + $('<div>').text(details).html() +"</pre>"
}
ngToast.create({
content: errorMessage
, className: 'danger'
, dismissOnTimeout : false
, dismissButton : true
, dismissOnClick : false
});
}
function handle_error ( actionName ) {
return function(data, status, headers, config) {
if (status === 401) {
$scope.authenticated = false;
errorNotification('Could not authenticate '+ actionName, data.error.details);
} else {
if (data.error !== undefined) {
$.each(data.error, function(index,error) {
var details = error.details === undefined ? error.errorDetails : error.details
errorNotification(error.message,details);
})
} else {
errorNotification('Error '+ actionName, data.errorDetails)
}
}
}
};
function defineMethodClassContext (method_call) {
// First split from .
var myclasses = method_call.class_context.split(".");
// find os class from the first class of class_context
var osClass = find_os_class(myclasses[0], cfengine_OS_classes);
if ( $.isEmptyObject(osClass)) {
// first class is not an os class, class_context is only advanced class
method_call.advanced_class = method_call.class_context;
} else {
// We have an os class !
method_call.OS_class = osClass;
if (myclasses.length > 1) {
// We have more than one class, rest of the context is an advanced class
myclasses.splice(0,1);
var advanced_class = myclasses.join(".");
if (advanced_class.startsWith("(")) {
advanced_class = advanced_class.slice(1,-1);
}
method_call.advanced_class = advanced_class;
}
}
}
function updateResources() {
var urlParam= ($scope.originalTechnique.bundle_name !== undefined) ? $scope.selectedTechnique.bundle_name : "draft/" + $scope.selectedTechnique.internalId
var resourceUrl = '/rudder/secure/api/internal/techniques/' + urlParam +"/" + $scope.selectedTechnique.version +"/resources"
$http.get(resourceUrl).then(
function(response) {
$scope.selectedTechnique.resources = response.data.data.resources;
$scope.originalTechnique.resources = $scope.originalTechnique.resources === undefined ? response.data.data.resources : $scope.originalTechnique.resources;
$scope.fileManagerState.updating = false;
}
, function(response) {
// manage error
$scope.fileManagerState.updating = false;
}
)
}
function updateFileManagerConf () {
$scope.fileManagerState.updating = true;
var urlParam= $scope.originalTechnique.bundle_name !== undefined ? $scope.selectedTechnique.bundle_name+"/" + $scope.selectedTechnique.version +"/" + $scope.selectedTechnique.category : "draft/" + $scope.selectedTechnique.internalId +"/" + $scope.selectedTechnique.version
var newUrl = "/rudder/secure/api/resourceExplorer/"+ urlParam
updateResources()
apiHandler.prototype.deferredHandler = function(data, deferred, code, defaultMsg) {
updateResources()
if (!data || typeof data !== 'object') {
this.error = 'Error %s - Bridge response error, please check the API docs or this ajax response.'.replace('%s', code);
}
if (code == 404) {
this.error = 'Error 404 - Backend bridge is not working, please check the ajax response.';
}
if (data.result && data.result.error) {
this.error = data.result.error;
}
if (!this.error && data.error) {
this.error = data.error.message;
}
if (!this.error && defaultMsg) {
this.error = defaultMsg;
}
if (this.error) {
return deferred.reject(data);
}
return deferred.resolve(data);
};
apiMiddleware.prototype.list = function(path, customDeferredHandler) {
return this.apiHandler.list(newUrl, this.getPath(path), customDeferredHandler);
};
apiMiddleware.prototype.upload = function(files, path) {
if (! $window.FormData) {
throw new Error('Unsupported browser version');
}
var destination = this.getPath(path);
return this.apiHandler.upload(newUrl, destination, files);
};
apiMiddleware.prototype.createFolder = function(item) {
var path = item.tempModel.fullPath();
return this.apiHandler.createFolder(newUrl, path);
};
apiMiddleware.prototype.getContent = function(item) {
var itemPath = this.getFilePath(item);
return this.apiHandler.getContent(newUrl, itemPath);
};
apiMiddleware.prototype.rename = function(item) {
var itemPath = this.getFilePath(item);
var newPath = item.tempModel.fullPath();
return this.apiHandler.rename(newUrl, itemPath, newPath);
};
apiMiddleware.prototype.remove = function(files) {
var items = this.getFileList(files);
return this.apiHandler.remove(newUrl, items);
};
apiMiddleware.prototype.edit = function(item) {
var itemPath = this.getFilePath(item);
return this.apiHandler.edit(newUrl, itemPath, item.tempModel.content);
};
apiMiddleware.prototype.copy = function(files, path) {
var items = this.getFileList(files);
var singleFilename = items.length === 1 ? files[0].tempModel.name : undefined;
return this.apiHandler.copy(newUrl, items, this.getPath(path), singleFilename);
};
apiMiddleware.prototype.changePermissions = function(files, dataItem) {
var items = this.getFileList(files);
var code = dataItem.tempModel.perms.toCode();
var octal = dataItem.tempModel.perms.toOctal();
var recursive = !!dataItem.tempModel.recursive;
return this.apiHandler.changePermissions(newUrl, items, code, octal, recursive);
};
apiMiddleware.prototype.move = function(files, path) {
var items = this.getFileList(files);
return this.apiHandler.move(newUrl, items, this.getPath(path));
};
apiMiddleware.prototype.download = function(item, forceNewWindow) {
var itemPath = this.getFilePath(item);
var toFilename = item.model.name;
if (item.isFolder()) {
return;
}
return this.apiHandler.download(
newUrl,
itemPath,
toFilename,
fileManagerConfig.downloadFilesByAjax,
forceNewWindow
);
};
}
// Transform a ncf technique into a valid UI technique
// Add original_index to the method call, so we can track their modification on index
// Handle classes so we split them into OS classes (the first one only) and advanced classes
function toTechUI (technique, version) {
if ("method_calls" in technique) {
var calls = technique.method_calls.map( function (method_call, method_index) {
method_call["original_index"] = method_index;
// Handle class_context
defineMethodClassContext(method_call)
// support of version 1.0, method parameters are formatted like that : 'args':[param1,param2 ...]
// be careful position of the parameters in 'args' define in which method's parameters it will be paired
if(version == 1.0){
method_call.parameters=$scope.getMethodParameters(method_call)
}
return method_call;
} );
technique.method_calls = calls;
}
return technique;
};
// to support version 1.0 of technique
$scope.getMethodParameters = function(method_call) {
var params = [];
// parameter information are stored into generic methods (maybe a better solution would be to merge data when we fetch them ...)
if (method_call.method_name in $scope.generic_methods ) {
var method = angular.copy($scope.generic_methods[method_call.method_name]);
for (var i = 0; i < method.parameter.length; i++) {
var parameter = method.parameter[i];
var param_value = method_call.args[i];
// Maybe parameter does not exists in current method_call, replace with empty value
param_value = param_value !== undefined ? param_value : '';
parameter["value"] = param_value;
parameter["$errors"] = [];
params.push(parameter);
}
} else {
// We have no informations about this generic method, just call it 'parameter'
params = method_call.args.map( function(value) {
return {
"name" : "Paramter"
, "value" : value
, "description" : "Unknown parameter"
, "type" : "string"
, "$errors" : []
};
});
}
return params;
};
// Transform a ui technique into a valid ncf technique by removint original_index param
function toTechNcf (baseTechnique) {
var technique = angular.copy(baseTechnique);
var calls = technique.method_calls.map( function (method_call, method_index) {
delete method_call.original_index;
});
technique.method_calls = calls;
return technique;
};
// Check if a technique is selected
$scope.isSelected = function(technique) {
if($scope.originalTechnique==undefined || technique==undefined) return false;
return $scope.originalTechnique.bundle_name == technique.bundle_name;
};
$scope.getSelectedMethodIndex = function(method) {
var result = $scope.ui.selectedMethods.findIndex(function(m) {
return method["$$hashKey"] === m["$$hashKey"];
});
return result;
};
// Check if a method is selected
$scope.methodIsSelected = function(method) {
return $scope.getSelectedMethodIndex(method) >= 0;
};
$scope.getSessionStorage = function(){
$scope.resetFlags();
//Used to know if the technique has been deleted while the user was away
var deleted = false;
var storedSelectedTechnique,storedOriginalTechnique;
storedSelectedTechnique = JSON.parse(sessionStorage.getItem('storedSelectedTechnique'));
storedOriginalTechnique = JSON.parse(sessionStorage.getItem('storedOriginalTechnique'));
if(storedOriginalTechnique !== null && storedOriginalTechnique.bundle_name === "") storedOriginalTechnique.bundle_name=undefined;
if(storedSelectedTechnique !== null && storedSelectedTechnique.bundle_name === "") storedSelectedTechnique.bundle_name=undefined;
$scope.originalTechnique = angular.copy(storedOriginalTechnique);
if(storedSelectedTechnique !== null){
//Restore selected technique and inform user
ngToast.create({ content: "<b>Info: </b> Technique restored from current session.", className: 'info'});
$scope.selectedTechnique = angular.copy(storedSelectedTechnique);
updateFileManagerConf()
//Check if it's not a new technique
if(storedOriginalTechnique.bundle_name !== undefined){
var existingTechnique = $scope.techniques.find(function(technique){return technique.bundle_name === storedOriginalTechnique.bundle_name })
if (existingTechnique !== undefined) {
//Check if the origignal technique stored is different from the one actually saved
if($scope.checkDiff(existingTechnique, storedOriginalTechnique)){
$scope.conflictFlag = true;
var modalInstance = $uibModal.open({
templateUrl: 'RestoreWarningModal.html',
controller: RestoreWarningModalCtrl,
size: 'lg',
backdrop : 'static',
resolve: {
technique : function () {
return $scope.selectedTechnique;
}
, editForm : function() {
return $scope.ui.editForm
}
, diverges : function() {
return $scope.diverges;
}
}
});
modalInstance.result.then(function (doSave) {
$scope.originalTechnique = existingTechnique;
if (doSave) {
$scope.selectedTechnique = angular.copy($scope.originalTechnique);
updateFileManagerConf();
$scope.resetFlags();
}
});
}
}else{
//Technique has been deleted while user was away
deleted = true;
}
$scope.suppressFlag = (deleted && !$scope.conflictFlag && $scope.originalTechnique.bundle_name !== undefined);
if(!$scope.conflictFlag && !deleted){
$scope.originalTechnique = existingTechnique;
}
}else{// else : New technique
var saved = $scope.techniques.find(function(technique){return technique.bundle_name === $scope.selectedTechnique.bundle_name })
if(saved !== undefined){
$scope.originalTechnique = angular.copy(saved);
$scope.selectedTechnique = angular.copy(saved);
}
}
}// else : Empty session storage
(function() {
new ClipboardJS('.clipboard');
})();
//Correctly resize elastic textareas
$timeout(function() {
$scope.$broadcast("elastic:adjust");
}, 0);
}
$scope.$watch('selectedTechnique', function(newValue, oldValue) {
$scope.updateItemSessionStorage('storedSelectedTechnique' , oldValue, newValue);
},true);
$scope.$watch('originalTechnique', function(newValue, oldValue) {
$scope.updateItemSessionStorage('storedOriginalTechnique' , oldValue, newValue);
},true);
$scope.clearSessionStorage = function(){
//<Cleaning old cache>
sessionStorage.removeItem('selectedTechnique');
sessionStorage.removeItem('originalTechnique');
//</>
sessionStorage.removeItem('storedSelectedTechnique');
sessionStorage.removeItem('storedOriginalTechnique');
$scope.resetFlags();
}
$scope.resetFlags = function(){
$scope.suppressFlag = false;
$scope.conflictFlag = false;
}
$scope.updateItemSessionStorage = function(item, oldTechnique, newTechnique){
//Checking oldTechnique allows us to not clear the session storage when page is loading so $scope.selectedTechnique and $scope.originalTechnique are still undefined.
if(oldTechnique && !newTechnique){
$scope.clearSessionStorage();
} else if(newTechnique){
var checkList = $scope.getChecksList();
var savedTechnique = {};
var check, propertyChecked;
for(check in checkList){
propertyChecked = newTechnique[check];
//We can't store 'undefined' value, so we convert it into an empty string
savedTechnique[check] = propertyChecked === undefined ? "" : angular.copy(propertyChecked);
}
sessionStorage.setItem(item, JSON.stringify(savedTechnique));
}
}
// Call ncf api to get techniques
$scope.getTechniques = function () {
$scope.techniques = [];
$scope.generic_methods = {};
$http.get('/rudder/secure/api/internal/methods').
success(function(response, status, headers, config) {
if (response.data !== undefined && response.data.methods !== undefined) {
$.each( response.data.methods, function(methodName, method) {
method.documentation = converter.makeHtml(method.documentation)
$scope.generic_methods[methodName] = method;
});
$scope.methodsByCategory = $scope.groupMethodsByCategory();
$scope.authenticated = true;
} else {
errorNotification( "Error while fetching methods", "Data received via api are invalid")
}
$http.get('/rudder/secure/api/internal/techniques').
success(function(response, status, headers, config) {
if (response.data !== undefined && response.data.techniques !== undefined) {
$.each( response.data.techniques, function(techniqueName, technique_raw) {
var technique = toTechUI(technique_raw);
$scope.techniques.push(technique);
});
$scope.getSessionStorage();
} else {
errorNotification( "Error while fetching techniques", "Data received via api are invalid")
}
// Display single errors
$.each( response.errors, function(index, error) {
errorNotification(error.message,error.details)
})
} ).
error(handle_error(" while fetching techniques"));
} ).
error(handle_error(" while fetching methods"));
$http.get('/rudder/secure/api/internal/techniques/categories').
success(function(response, status, headers, config) {
if (response.data !== undefined && response.data.techniqueCategories !== undefined) {
for (var key in response.data.techniqueCategories) {
$scope.techniqueCategories.push({"key" :key, "value": response.data.techniqueCategories[key] })
}
} else {
errorNotification( "Error while fetching technique categories", "Data received via api are invalid")
}
// Display single errors
$.each( response.errors, function(index, error) {
errorNotification(error.message,error.details)
})
} ).
error(handle_error(" while fetching technique categories"));
};
// Group methods by category, a category of a method is the first word in its name
$scope.groupMethodsByCategory = function () {
var groupedMethods = {};
for (var methodKey in $scope.generic_methods) {
var method = $scope.generic_methods[methodKey];
var name = methodKey.split('_')[0];
var grouped = groupedMethods[name];
if (grouped === undefined) {
groupedMethods[name] = [method];
} else {
groupedMethods[name].push(method);
}
};
return groupedMethods;
};
// method to export technique content into a json file
$scope.exportTechnique = function(){
// selectedTechnique exists otherwise the buttons couldn't call us
var filename = $scope.selectedTechnique.name+'.json';
// build the exported technique object from the current selected technique
var calls = [];
for (var i = 0; i < $scope.selectedTechnique['method_calls'].length; i++) {
var call = $scope.selectedTechnique['method_calls'][i]
calls[i] = {
parameters: call["parameters"],
class_context: call["class_context"],
method_name: call["method_name"],
component: call["component"]
}
}
var exportedTechnique = {
type: 'ncf_technique', version: 2.0,
data: {
bundle_name : $scope.selectedTechnique["bundle_name"],
description : $scope.selectedTechnique["description"],
name : $scope.selectedTechnique["name"],
version : $scope.selectedTechnique["version"],
parameter : $scope.selectedTechnique["parameter"],
category : $scope.selectedTechnique["category"],
method_calls: calls
}
};
var blob = new Blob([angular.toJson(exportedTechnique, true)], {type: 'text/plain'});
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else{
var e = document.createEvent('MouseEvents'),
a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
e.initEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
// window.URL.revokeObjectURL(url); // clean the url.createObjectURL resource
}
}
// method to import technique content from a json file
$scope.onImportFileChange = function (fileEl) {
var files = fileEl.files;
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState === FileReader.DONE) {
$scope.$apply(function () {
var importedTechnique = JSON.parse(evt.target.result);
if(importedTechnique['type'] == 'ncf_technique') {
var version = importedTechnique['version']
if(version != 1.0 && version != 2.0){
alert("Unsupported technique version ! This version of Rudder only support import of ncf techniques files in format 1.0 and 2.0")
} else {
var technique = toTechUI(importedTechnique['data'], version);
$scope.checkSelect(technique, $scope.selectTechnique);
$scope.ui.editForm.$setDirty();
$scope.suppressFlag = true;
}
} else {
alert("Unsupported file type " + "'" + importedTechnique['type'] + "'");
}
});
}
};
reader.readAsText(file);
}
$scope.getCategory = function(selectedTechniqueCategory) {
var category = $scope.techniqueCategories.find(function(value) { return value.key === selectedTechniqueCategory});
category = category === undefined ? selectedTechniqueCategory : category
return category
}
// Method used to check if we can select a technique without losing changes
$scope.checkSelect = function(technique, select) {
// No selected technique, select technique
if ($scope.selectedTechnique === undefined) {
select(technique);
} else {
if ($scope.checkSelectedTechnique()) {
// Selected technique is the same than actual selected technique, unselect it
select(technique);
} else {
// Display popup that changes will be lost, and possible discard them
$scope.selectPopup(technique, select);
}
}
focus('focusTechniqueName');
};
// Click on a Technique
// Select it if it was not selected, unselect it otherwise
$scope.selectTechnique = function(technique) {
$scope.fileManagerState.open = false;
$scope.resetFlags();
// Always clean Selected methods and display methods list
$scope.ui.selectedMethods = [];
$scope.ui.openedParamDescription = [];
// Check if that technique is the same as the original selected one
var test1 = angular.copy($scope.originalTechnique)
var test2 = angular.copy(technique)
if(test1 && test1.resources !== undefined) delete test1.resources;
if(test2 && test2.resources !== undefined) delete test2.resources;
if(angular.equals(test1,test2) ) {
// It's the same, unselect the technique
$scope.selectedTechnique = undefined;
$scope.originalTechnique = undefined;
$scope.ui.activeTab = 'general';
} else {
// Select the technique, by using angular.copy to have different objects
$scope.selectedTechnique=angular.copy(technique);
$scope.originalTechnique=angular.copy($scope.selectedTechnique);
if (technique.isClone) {
$scope.originalTechnique.bundle_name = undefined;
}
$scope.$broadcast('endSaving');
updateFileManagerConf()
}
};
////////// OS Class ////////
// Structures we will use to select our class, we can't use the big structure os_classes, we have to use simple list with angular
// List of all OS types
$scope.type_classes = $.map(cfengine_OS_classes,function(val,i){return val.name;});
// Build Map of all OS by type
$scope.os_classes_by_type = {};
for (var index in cfengine_OS_classes) {
// for each type ...
var current_type = cfengine_OS_classes[index];
// Get all oses
var oses = $.map(current_type.childs, function(os,i) {
return os.name;
});
$scope.os_classes_by_type[current_type.name] = oses;
}
// Regexp used for input version fields
$scope.versionRegex = /^\d+$/;
// List of oses using major or minor version
$scope.major_OS = $.map(cfengine_OS_classes, function(v,i) { return $.map($.grep(v.childs,function(os,i2) { return os.major}), function(os,i2) {return os.name});});
$scope.minor_OS = $.map(cfengine_OS_classes, function(v,i) { return $.map($.grep(v.childs,function(os,i2) { return os.minor}), function(os,i2) {return os.name});});
// Functiopn to check if the os selected need major/minor versionning
function checkVersion (os_list, method) {
if (method.OS_class === undefined ) {
return false;
}
return $.inArray(method.OS_class.name,os_list) >= 0;
}
$scope.checkMajorVersion= function(method) {
return checkVersion($scope.major_OS, method);
}
$scope.checkMinorVersion= function(method) {
return checkVersion($scope.minor_OS, method);
}
$scope.checkDeprecatedFilter = function(methods){
return methods.some(function(method){return method.deprecated === undefined });
}
$scope.checkFilterCategory = function(methods){
//If this function returns true, the category is displayed. Else, it is hidden by filters.
var deprecatedFilter = $scope.filter.showDeprecated || $scope.checkDeprecatedFilter(methods);
var agentTypeFilter = false;
var nameFilter = methods.some(function(m) {return m.name.toLowerCase().includes($scope.filter.text.toLowerCase())});
var i = 0;
switch($scope.filter.compatibility){
case "dsc":
while(!agentTypeFilter && i<methods.length){
agentTypeFilter = methods[i].agent_support.some(function(agent){return agent === "dsc"});
i++;
}
break;
case "classic":
while(!agentTypeFilter && i<methods.length){
agentTypeFilter = methods[i].agent_support.some(function(agent){return agent === "cfengine-community"});
i++;
}
break;
case "all":
agentTypeFilter = true;
break;
}
return agentTypeFilter && deprecatedFilter && nameFilter;
}
$scope.checkMethodCallAgentSupport = function(methodName, agent){
var gKey = Object.keys($scope.generic_methods).find(function(method){return $scope.generic_methods[method].bundle_name === methodName});
var method = $scope.generic_methods[gKey];
return $scope.checkAgentSupport(method,agent);
}
$scope.checkAgentSupport = function(method, agentSupport){
return method.agent_support.some(function(agent){return agent === agentSupport});
}
$scope.checkFilterMethod = function(method){
//If this function returns true, the method is displayed. Else, it is hidden by filters.
var deprecatedFilter = $scope.filter.showDeprecated || !method.deprecated;
var agentTypeFilter = false;
switch($scope.filter.compatibility){
case "dsc":
agentTypeFilter = method.agent_support.some(function(agent){return agent === "dsc"});
break;
case "classic":
agentTypeFilter = method.agent_support.some(function(agent){return agent === "cfengine-community"});
break;
case "all":
agentTypeFilter = true;
break;
}
return agentTypeFilter && deprecatedFilter;
}
// Function used when changing os type
$scope.updateOSType = function(method) {
// Reset selected OS
method.OS_class.name = "Any";
// Do other update cleaning
$scope.updateOSName(method);
}
// Function used when changing selected os
$scope.updateOSName = function(method) {
// Reset versions inputs
method.OS_class.majorVersion = undefined;
method.OS_class.minorVersion = undefined;
// Update class context
$scope.updateClassContext(method);
}
// Update class context, after a change was made on classes
$scope.updateClassContext = function(method) {
// Define os class from selected inputs
var os = undefined;
// do not define os if nothing was selected
if ( !(method.OS_class === undefined) ) {
// Get class from os type and selected os
os = getClass(method.OS_class);
}
if (os === undefined) {
// No OS selected, only use advanced OS
method.class_context = method.advanced_class;
} else {
if (method.advanced_class === undefined || method.advanced_class === "") {
// No adanced class, use only OS
method.class_context = os;
} else {
// Both OS and advanced. Use class_context os.advanced
method.class_context = os+".("+method.advanced_class+")";
}
}
}