b8e816c24043e68abecd00b1f23b3c33fbab2dfa
[portal.git] / ecomp-portal-FE-os / client / src / views / userbar / userbar.controller.js
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017 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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 'use strict';
39
40 (function () {
41         
42     class UserbarCtrl {
43         constructor(userProfileService,userbarUpdateService, $log, $rootScope , $interval,$scope,$timeout,dashboardService) {
44             this.$log = $log;
45             var debug = false;
46             this.userProfileService = userProfileService;
47             this.$rootScope = $rootScope;
48             $rootScope.isAdminPortalAdmin = false;
49             $scope.updateRate = 10000; //default online user bar refreshing rate
50             var intervalPromise = null;
51             $scope.myservice = userbarUpdateService;
52             $scope.userList=this.userLists;
53             var websocket = '';
54             var currentUser = '';
55             var remoteUser = '';
56             var f = '';
57            
58                 
59             function socketSetup(initialPageVisit,_currentUser, _remoteUser, _f) {
60                 
61
62
63                 if( true) {
64                           
65                         var href = window.location.href;
66                     var hostPatt = new RegExp(window.location.host +"/[^/]*");
67                     var res = hostPatt.exec(href);
68                     var protocol = window.location.protocol.replace("http","ws");
69                       var signalingServerPath = protocol + "//" + res + "/opencontact";
70                           var wsUri = signalingServerPath;
71                           console.log("Connecting to " + wsUri);
72                           websocket = new WebSocket(wsUri);
73                           //localStorage.notifySocket = JSON.stringify(websocket);
74                           //window.top.notifySocket = websocket;
75                           
76                           currentUser = _currentUser;
77                           remoteUser = _remoteUser;
78                           f = socketSend;
79                          
80                           
81                 }
82                 
83                 //var websocket = JSON.parse(localStorage.notifySocket || "{}") ;
84                 if( websocket != null) {
85                         websocket.onopen = function(evt) { onOpen(evt); };
86                         websocket.onmessage = function(evt) { onMessage(evt); };
87                         websocket.onerror = function(evt) { onError(evt); };
88                 
89                 }
90                 
91                 //if(f != undefined)
92                  // f();
93                 
94                 //window.top.notifySocket.send("");
95             }
96             
97             function socketSend(currentUser, remoteUser) {
98                 
99
100
101                  websocket.send(JSON.stringify({
102                     from: currentUser,
103                     to: remoteUser
104                 }));
105                 
106                 //window.top.notifySocket.send("");
107            }
108
109
110
111
112            function onOpen(evt) {
113                console.log("onOpen");
114                //writeToScreen("CONNECTED");
115                
116                if(f != undefined)
117                         f(currentUser, remoteUser);
118                
119            }
120
121            function onMessage(evt) {
122                if (typeof evt.data == "string") {
123                    writeToScreen("RECEIVED (text): " + evt.data);
124                    var chatObject = JSON.parse(evt.data);
125                    if(confirm("User " + chatObject.from + " is requesting a chat session with you. Please click ok to accept")== true) {
126                            
127                            var url = userProfileService.getSortedUserIdCombination(chatObject.from, chatObject.to);
128                            var win = window.open(url, '_blank');
129                            win.focus();
130                    } else {
131                            //
132                    }
133                 
134                    
135                } else {
136                    writeToScreen("RECEIVED (binary): " + evt.data);
137                }
138            }
139
140            function onError(evt) {
141                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
142            }
143
144            function writeToScreen(message) {
145                    console.log(message);
146            }
147             
148             function updateActiveUsers() {
149                 // $log.debug('UserbarCtrl::updateActiveUsers: intervalPromise is ' + intervalPromise);
150                                 // $log.info("UserbarCtrl:updateActiveUsers invoked.")
151                 // decrement the counter every time updateActiveUser is called;
152                                 userbarUpdateService.decrementRefreshCount();
153                 userProfileService.getActiveUser()
154                 .then(res=> {
155                         if (debug)
156                                 $log.debug('UserbarCtrl::updateActiveUsers: service returned ' + JSON.stringify(res));
157                         if (res==null) {
158                                 $log.error('UserbarCtrl::updateActiveUsers: failed to get active user');
159                                 $scope.stop();
160                         } else {
161                                 $scope.userList = [];
162                                 // defend against huge list that should never happen.
163                                 var maxItems = 25;
164                                 if (res.length < maxItems)
165                                         maxItems = res.length;
166                                 for (var i=0; i < maxItems; i++) {
167                                         var data= {
168                                                         userId:res[i],
169                                                         linkQ:userProfileService.getSortedUserIdCombination(userProfileService.userProfile.orgUserId , res[i])
170                                         }
171                                         $scope.userList.push(data);
172                                 }               
173                                 if (debug)
174                                         $log.debug('UserbarCtrl::updateActiveUsers: user list ' + JSON.stringify($scope.userList));
175                         }       
176                 }).catch(err=> {
177                         $log.error('UserbarCtrl::updateActiveUsers: caught exception: ' + err);
178                         // Do not show stale result
179                         $scope.userList = [];
180                         $scope.stop();  
181                 }).finally(() => {
182                         var footerOff = $('#online-userbar').offset().top;
183                         var headOff = $('#footer').offset().top;
184                         var userbarHeight= parseInt($(".online-user-container").css('height'),10);
185                         var defaultOffSet = 45;
186                         $(".online-user-container").css({
187                                         "height" : headOff - footerOff-defaultOffSet
188                                 });
189                 });      
190             }
191             
192                         $scope.start = function(rate) {
193                                 // stops any running interval to avoid two intervals running at the same time
194                                 $scope.stop();  
195                                 // store the interval promise
196                                 intervalPromise = $interval(updateActiveUsers, rate);
197                         };
198
199                         $scope.stop = function() {
200                                 if (intervalPromise != null) {
201                                         $interval.cancel(intervalPromise);
202                                         intervalPromise = null;
203                                 }
204                         };
205
206                         $scope.$watch('myservice.getRefreshCount()', function (newVal,oldVal) {
207                                 //$log.info("refresh "+$scope.myservice.refreshCount + " more time(s)");
208                                 if (newVal<=0) {
209                                         // $log.info("UserbarCtrl: stopped refreshing online users");
210                                         $scope.stop();
211                                 } else if (newVal== $scope.myservice.maxCount){
212                                         // $log.info("UserbarCtrl: start refreshing online users at every "+($scope.updateRate/1000)+" sec");
213                                         // initial update of activate users
214                                         updateActiveUsers();
215                                         $scope.start($scope.updateRate);
216                                 }
217                         });
218
219             // Load the active users.
220             //updateActiveUsers();
221             dashboardService.getOnlineUserUpdateRate().then(res=> {
222                 // $log.info('getting Online User Update Rate init***********************', res);
223                 if (res == null || res.response == null) {
224                         $log.error('UserbarCtlr: failed to get online user update rate or duration, check system.properties file.');
225                 } else {
226                                 // $log.debug('UserbarCtlr: got online User Update Rate ' + res.response);                      
227                         var rate = parseInt(res.response.onlineUserUpdateRate);
228                                         // var updateRate = parseInt(res.response.onlineUserUpdateRate);
229                                         var duration = parseInt(res.response.onlineUserUpdateDuration);
230                                         userbarUpdateService.setMaxRefreshCount(parseInt(duration/rate)+1);
231                                         userbarUpdateService.setRefreshCount(userbarUpdateService.maxCount);
232                                         // $scope.refreshCount = userbarUpdateService.getRefreshCount();
233
234                                 if (rate != NaN && duration != NaN) {
235                                         // $log.debug('UserbarCtlr: scheduling function at interval ' + millis);
236                                                 $scope.updateRate=rate;
237                                                 $scope.start($scope.updateRate);
238                                 }                               
239                 }
240             }).catch(err=> {
241                 $log.error('UserbarCtlr: getOnlineUserUpdateRate() failed: ' + err);
242             });
243         }
244     }
245     UserbarCtrl.$inject = ['userProfileService', 'userbarUpdateService', '$log', '$rootScope','$interval','$scope','$timeout','dashboardService'];
246     angular.module('ecompApp').controller('UserbarCtrl', UserbarCtrl);
247 })();