login and Certman AAF Integration changes
[portal.git] / ecomp-portal-FE-common / client / app / views / tabs / tabs.controller.js
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * 
37  */
38 'use strict';
39 (function () {
40     const HTTP_PROTOCOL_RGX = /https?:\/\//;
41     class  TabsCtrl {
42         constructor(applicationsService, $log, $window, conf, userProfileService, userbarUpdateService, $scope,$cookies,$rootScope,confirmBoxService,auditLogService,schedulerService) {                
43                 // Tab counter
44             var counter = 1;
45             var tabLimit = 6;
46             this.conf = conf;
47             var cookieDomain = this.conf.cookieDomain;
48             // Array to store the tabs
49             $scope.tabs = [];
50             $scope.notificationShow=true;
51             $rootScope.showFooter = "";
52             $cookies.putObject('show_app_header', false,{domain: cookieDomain, path : '/'});
53
54             let  getCookieDomain = function() {
55                    return window.location.hostname;
56                 }
57           let getContextPath=function() {
58                    return  window.location.pathname.substring( 0, window.location.pathname.lastIndexOf( '/' ) + 1 );
59                 }
60
61             let noRefresh = function () {
62                     window.onbeforeunload = function(e) {
63
64                         var isQtoHref = false;
65                         try{
66                                 isQtoHref = e.srcElement.activeElement.href.includes("to");
67                         } catch(err) {
68
69                         }
70
71                         if ($scope.tabs.length > 1 && isQtoHref == false) {
72                             return "Changes you made may not be saved. Are you sure you want to refresh?";
73                         } else {
74                             return null;
75                         }
76                     }
77             }
78             // Add tab to the end of the array
79             var addTab = function (title, content) {
80                 
81                 if($scope.tabs.length===tabLimit){
82                         //alert
83                         confirmBoxService.showInformation('You have reached your maximum limit of tabs allowed.').then(isConfirmed => {});
84                 } else {
85                         // console.log(window.performance.memory);
86                         // var usedperc = (window.performance.memory.usedJSHeapSize/window.performance.memory.jsHeapSizeLimit)*100;
87                         // console.log('Current memory usage: '+usedperc+'%');
88                         if(title!=='Home' && content.indexOf('https') == -1){
89                                 console.log('App URL: '+content+'. The application URL you are trying to open is not HTTPS. We recommend to use secured HTTPS URL while on-boarding the application.');
90                                 //confirmBoxService.showInformation('The application URL you are trying to open is not HTTPS. We recommend to use secured HTTPS URL while on-boarding the application.').then(isConfirmed => {});
91                         }
92                         
93                     $scope.tabs.push({ title: title, content: content });
94                     counter++;
95                     //$scope.tabs[$scope.tabs.length - 1].disabled = false;
96                     $scope.selectedIndex = $scope.tabs.length - 1;
97                     if ($scope.tabs.length > 1) {
98                         noRefresh();
99                     }
100                     $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
101                     $cookies.putObject('visInVisCookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
102                    
103                 }
104             };
105             
106             //with APP ID
107             var addTab = function (title, content, appId) {
108                 if($scope.tabs.length===tabLimit){
109                         //alert
110                         confirmBoxService.showInformation('You have reached your maximum limit of tabs allowed.').then(isConfirmed => {});
111                 } else {                
112                         if(title!=='Home' && content.indexOf('https') === -1){
113                                 console.log('App URL: '+content+'. The application URL you are trying to open is not HTTPS. We recommend to use secured HTTPS URL while on-boarding the application.');
114                         }
115                     $scope.tabs.push({ title: title, content: content, appId:appId });
116                     counter++;
117                     $scope.selectedIndex = $scope.tabs.length - 1;
118                     if ($scope.tabs.length > 1) {
119                         noRefresh();
120                     }
121                     $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
122                     $cookies.putObject('visInVisCookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
123                 }
124             };
125             
126             // adjust title - trim the title and append ...
127             var adjustTitle = function (title) {
128                 var index = 15;
129                 var nonEmptyCharPattern = /(\s|\w)/;
130                 var adjustedTitle = title.substring(0,index);
131                 var ext = title.charAt(index).replace(nonEmptyCharPattern,'...');
132                 return adjustedTitle.concat(ext);
133                 
134                 
135             };
136             
137             //store audit log
138             $scope.auditLog = function(app) {
139                 $log.debug('auditLog::auditLog: auditLog.ping() = ' + app);
140                 var comment = '';
141                 if(app.content==null || app.content=='')
142                         comment= app.title;
143                 else
144                         comment = app.content;
145                 auditLogService.storeAudit(app.appId, 'tab', comment);
146                 };
147             
148             // Remove tab by index
149             var removeTab = function (event, index) {
150               event.preventDefault();
151               event.stopPropagation();
152               $scope.tabs.splice(index, 1);
153               $cookies.putObject('cookieTabs', $scope.tabs,{domain: getCookieDomain(), path : getContextPath()});
154             };
155             
156           //adjust height of the tab due to the search popup being hidden 
157                 $scope.adjustTabStyle = function(title){
158                         if(title=='Home'){
159                                 $(".w-ecomp-tabs").css('height',"50px");
160                         }else{
161                                 $(".w-ecomp-tabs").css('height',"100%");
162                         }
163                 }
164                 
165            // select tab 
166             var selectTab = function (title) {
167                 $scope.adjustTabStyle(title);
168                 if(title==='Home') {
169                     $rootScope.ContentModel.IsVisible=true;
170                     $rootScope.showFooter = true;
171                     $rootScope.tabBottom = 75;
172                     userbarUpdateService.setRefreshCount(userbarUpdateService.maxCount);
173                 }
174                 else {
175                     $rootScope.ContentModel.IsVisible=false;
176                     $rootScope.showFooter = false;
177                     $rootScope.tabBottom = 0;
178                 }
179             };
180
181             // Initialize the scope functions
182             $scope.addTab    = addTab;
183             $scope.removeTab = removeTab;
184             $scope.selectTab = selectTab;
185             $scope.adjustTitle = adjustTitle;
186             
187
188             $rootScope.ContentModel = {
189                     IsVisible : false,
190                     ViewUrl : null,
191                 };
192             
193             
194                 var sessionActive = applicationsService.ping()
195                 .then(sessionActive => {
196             // $log.debug('TabsCtrl::addTab: applicationsService.ping() = ' + JSON.stringify(sessionActive));
197                 // For demonstration add 5 tabs
198                
199             var cookieTabs = $cookies.getObject('cookieTabs');
200                 if(cookieTabs!=null){
201                         for(var t in cookieTabs){
202                                 // console.log('TabsCtrl::addTab: cookieTabs title: '+cookieTabs[t].title);
203                                 if(cookieTabs[t].title!=null && cookieTabs[t].title==='Home'){
204                                         cookieTabs[t].content = "";
205                                         $rootScope.ContentModel.IsVisible=true;
206                                 addTab( cookieTabs[t].title, cookieTabs[t].content,1) ;
207                                 }else{
208                                 addTab( cookieTabs[t].title, cookieTabs[t].content,cookieTabs[t].appId) ;
209                                 }
210                                         
211                         }
212                 } else {
213             for (var i = 0; i < 1; i++) {
214                 var content="";
215                 var title="";
216                 var appId=""
217                 if(i===0){
218                         title="Home";
219                         $rootScope.ContentModel.IsVisible=true;
220                     addTab(title, content,1);
221                 }else{
222                     addTab(title, content,appId);
223                 } 
224             }
225                 }
226             
227
228             
229             //$scope.tabs[$scope.tabs.length - 1].active = false;
230             //$scope.tabs[0].disabled = false;
231             $scope.selectedIndex = 0;
232                 });
233                 
234             $scope.$watchCollection(function() { return $cookies.getObject('addTab'); }, function(newValue) {
235                 // $log.log('Cookie string: ' + $cookies.get('test'))
236                 var tabContent = $cookies.getObject('addTab');
237                 if(tabContent!=null && tabContent.url!=null){
238                         var tabExists = false;
239                         for(var x in $scope.tabs){
240                                 // console.log($scope.tabs[x].content);
241                                 if($scope.tabs[x].title==tabContent.title){
242                                         tabExists = true;
243                                         //$scope.tabs[x].disabled = false;
244                                         $scope.selectedIndex = x;
245                             // added dummy variable to get iframe reloded if tab is already opened.
246                             if(tabContent.url.indexOf('?')===-1){
247                                 $scope.tabs[x].content=tabContent.url+'?dummyVar='+(new Date()).getTime();
248                             }
249                             else{
250                                 $scope.tabs[x].content=tabContent.url+'&dummyVar='+(new Date()).getTime();
251                             }
252                                 }
253                         }
254                         if(!tabExists){
255                          addTab( tabContent.title, tabContent.url,tabContent.appId) ;
256                         }
257                         $cookies.remove('addTab');
258                 }
259             });
260             
261             /*Listening on partner applications */
262             var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
263             var eventer = window[eventMethod];
264             var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
265             eventer(messageEvent,function(e) {
266                   $scope.openModal(e.data);
267                 },false);
268             
269             $scope.openModal = function(data){
270                 if(data!=null && data!='' && data.widgetData!=null)
271                         schedulerService.showWidget(data.widgetName,data.widgetData,data.widgetParameter).then(isConfirmed => {});
272             }
273         }
274     }
275     TabsCtrl.$inject = ['applicationsService', '$log', '$window', 'conf', 'userProfileService', 'userbarUpdateService', '$scope','$cookies','$rootScope','confirmBoxService','auditLogService','schedulerService'];
276     angular.module('ecompApp').controller('TabsCtrl', TabsCtrl);
277     
278     angular.module('ecompApp').directive('mainArea', function() {
279         return {
280             restrict: "E",
281             templateUrl: 'app/views/tabs/tabframe.html',
282             link: function(scope, element) {
283         
284                 var iframeId = "tabframe-" + scope.$parent.tab.title.split(' ').join('-');
285                 var iframeVal = scope.$parent.tab.content;// +  "| trusted";
286                 if(iframeId != 'tabframe-Home') {
287                         sessionStorage.setItem("currentTabFrameId",iframeId);
288                         sessionStorage.setItem("currentTabFrameVal",iframeVal);
289                 }
290                 //console.log(document.getElementById(sessionStorage.getItem("currentTabFrameId")));
291                 
292                 // jQuery(iframeId).load(function() {
293                   //      alert("hello");
294                 //   }); //.attr("src",'{{tab.content | trusted}}' ); //src='{{tab.content | trusted}}'
295                 // jQuery(iframeId).attr('src', '{{tab.content | trusted}}');
296                  
297                 //element.childNodes[0].on('load', function() {
298                 //      alert('hello');
299                 //});
300             }
301         }
302     });
303     
304    
305     
306     angular.module('ecompApp').directive('tabHighlight', [function () {
307         return {
308           restrict: 'A',
309           link: function (scope, element) {
310             // Here is the major jQuery usage where we add the event
311             // listeners mousemove and mouseout on the tabs to initalize
312             // the moving highlight for the inactive tabs
313             var x, y, initial_background = '#c3d5e6';
314
315             element
316               .removeAttr('style')
317               .mousemove(function (e) {
318                 // Add highlight effect on inactive tabs
319                 if(!element.hasClass('md-active'))
320                 {
321                   x = e.pageX - this.offsetLeft;
322                   y = e.pageY - this.offsetTop;
323
324                   // Set the background when mouse moves over inactive tabs
325                   element
326                     .css({ background: '-moz-radial-gradient(circle at ' + x + 'px ' + y + 'px, rgba(255,255,255,0.4) 0px, rgba(255,255,255,0.0) 45px), ' + initial_background })
327                     .css({ background: '-webkit-radial-gradient(circle at ' + x + 'px ' + y + 'px, rgba(255,255,255,0.4) 0px, rgba(255,255,255,0.0) 45px), ' + initial_background })
328                     .css({ background: 'radial-gradient(circle at ' + x + 'px ' + y + 'px, rgba(255,255,255,0.4) 0px, rgba(255,255,255,0.0) 45px), ' + initial_background });
329                 }
330               })
331               .mouseout(function () {
332                 // Return the inital background color of the tab
333                 element.removeAttr('style');
334               });
335           }
336         };
337       }]);
338
339
340     
341 })();
342
343 function getParameterByName(name, url) {
344     if (!url) url = window.location.href;
345     name = name.replace(/[\[\]]/g, "\\$&");
346     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
347         results = regex.exec(url);
348     if (!results) return '';
349     if (!results[2]) return '';
350     return (results[2].replace(/\+/g, " "));
351 }
352
353 function isCascadeFrame(ref) {
354           // alert(ref.id);
355            if (self != top) {
356                    var e = document.body;
357                    e.parentNode.removeChild(e);
358                    window.location = "unKnownError";
359                    }
360 }
361
362 function loadFrame() {
363         
364                 var interval = setInterval(function() {
365                         
366                         if(sessionStorage.getItem("currentTabFrameId") == null && sessionStorage.getItem("currentTabFrameVal") == null)
367                                 clearInterval(interval);
368                         else if(document.getElementById(sessionStorage.getItem("currentTabFrameId")).src != sessionStorage.getItem("currentTabFrameVal")) {
369                 document.getElementById(sessionStorage.getItem("currentTabFrameId")).src = sessionStorage.getItem("currentTabFrameVal");
370                                 sessionStorage.removeItem("currentTabFrameId");
371                 sessionStorage.removeItem("currentTabFrameVal");
372                 clearInterval(interval);
373                         }
374                         },1000);
375
376         
377         }