nexus site path corrected
[portal.git] / ecomp-portal-FE / client / app / views / userbar / userbar.controller.js
1 /*-
2  * ================================================================================
3  * eCOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ================================================================================
19  */
20 'use strict';
21
22 (function () {
23         
24     class UserbarCtrl {
25         constructor(userProfileService,userbarUpdateService, $log, $rootScope , $interval,$scope,$timeout,dashboardService) {
26             this.$log = $log;
27             this.userProfileService = userProfileService;
28             this.$rootScope = $rootScope;
29             $rootScope.isAdminPortalAdmin = false;
30             $scope.updateRate = 10000; //default online user bar refreshing rate
31             var intervalPromise = null;
32             $scope.myservice = userbarUpdateService;
33             $scope.userList=this.userLists;
34             var websocket = '';
35             var currentUser = '';
36             var remoteUser = '';
37             var f = '';
38            
39                 
40             function socketSetup(initialPageVisit,_currentUser, _remoteUser, _f) {
41                 
42
43
44                 if( true) {
45                           
46                         var href = window.location.href;
47                     var hostPatt = new RegExp(window.location.host +"/[^/]*");
48                     var res = hostPatt.exec(href);
49                     var protocol = window.location.protocol.replace("http","ws");
50                       var signalingServerPath = protocol + "//" + res + "/opencontact";
51                           var wsUri = signalingServerPath;
52                           console.log("Connecting to " + wsUri);
53                           websocket = new WebSocket(wsUri);
54                           //localStorage.notifySocket = JSON.stringify(websocket);
55                           //window.top.notifySocket = websocket;
56                           
57                           currentUser = _currentUser;
58                           remoteUser = _remoteUser;
59                           f = socketSend;
60                          
61                           
62                 }
63                 
64                 //var websocket = JSON.parse(localStorage.notifySocket || "{}") ;
65                 if( websocket != null) {
66                         websocket.onopen = function(evt) { onOpen(evt); };
67                         websocket.onmessage = function(evt) { onMessage(evt); };
68                         websocket.onerror = function(evt) { onError(evt); };
69                 
70                 }
71                 
72                 //if(f != undefined)
73                  // f();
74                 
75                 //window.top.notifySocket.send("");
76             }
77             
78             function socketSend(currentUser, remoteUser) {
79                 
80
81
82                  websocket.send(JSON.stringify({
83                     from: currentUser,
84                     to: remoteUser
85                 }));
86                 
87                 //window.top.notifySocket.send("");
88            }
89
90
91
92
93            function onOpen(evt) {
94                console.log("onOpen");
95                //writeToScreen("CONNECTED");
96                
97                if(f != undefined)
98                         f(currentUser, remoteUser);
99                
100            }
101
102            function onMessage(evt) {
103                if (typeof evt.data == "string") {
104                    writeToScreen("RECEIVED (text): " + evt.data);
105                    var chatObject = JSON.parse(evt.data);
106                    if(confirm("User " + chatObject.from + " is requesting a chat session with you. Please click ok to accept")== true) {
107                            
108                            var url = userProfileService.getSortedUserIdCombination(chatObject.from, chatObject.to);
109                            var win = window.open(url, '_blank');
110                            win.focus();
111                    } else {
112                            //
113                    }
114                 
115                    
116                } else {
117                    writeToScreen("RECEIVED (binary): " + evt.data);
118                }
119            }
120
121            function onError(evt) {
122                writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
123            }
124
125            function writeToScreen(message) {
126                    console.log(message);
127            }
128             
129             function callAtInterval() {
130                 userProfileService.getActiveUser()
131                 .then(res=> {
132                         $log.info('sasasasasa getting userinfo from shared context.. ');
133                         if(res==null){
134                                 $log.info('failed getting userinfo from shared context.. ');
135                                 $log.info('getting userinfo from session ');
136                         }else{
137                                 $log.info('getting ActiveUser successfully',res);   
138                                 $scope.userList = [];
139                                 for(var i=0;i<res.length;i++){
140                                         var data= {
141                                                         userId:res[i][0],
142                                                         linkQ:userProfileService.getSortedUserIdCombination(userProfileService.userProfile.userId , res[i][0])
143                                         }
144                                         $scope.userList.push(data);
145                                 }               
146                                 $log.info(' ActiveUser =',$scope.userList);             
147                         }       
148                 }).catch(err=> {
149                         $log.error('Header Controller:: getActiveUser() failed: ' + err);
150                 }).finally(() => {
151                         var footerOff = $('#online-userbar').offset().top;
152                         var headOff = $('#footer').offset().top;
153                         var userbarHeight= parseInt($(".online-user-container").css('height'),10);
154                         var defaultOffSet = 45;
155                         $(".online-user-container").css({
156                                         "height" : headOff - footerOff-defaultOffSet
157                                 });
158                 });      
159             }
160             
161             
162             var intervalPromise;
163             dashboardService.getOnlineUserUpdateRate().then(res=> {
164                 // $log.info('getting Online User Update Rate init***********************', res);
165                 if (res == null || res.response == null) {
166                         $log.error('UserbarCtlr: failed to get online user update rate!');
167                 } else {
168                                 // $log.debug('UserbarCtlr: got online User Update Rate ' + res.response);                      
169                         var rate = parseInt(res.response.onlineUserUpdateRate);
170                                         // var updateRate = parseInt(res.response.onlineUserUpdateRate);
171                                         var duration = parseInt(res.response.onlineUserUpdateDuration);
172                                         userbarUpdateService.setMaxRefreshCount(parseInt(duration/rate)+1);
173                                         userbarUpdateService.setRefreshCount(userbarUpdateService.maxCount);
174                                         // $scope.refreshCount = userbarUpdateService.getRefreshCount();
175
176                                 if (rate != NaN && duration != NaN) {
177                                         // $log.debug('UserbarCtlr: scheduling function at interval ' + millis);
178                                                 $scope.updateRate=rate;
179                                                 $scope.start($scope.updateRate);
180                                 }                                       
181                 }
182             }).catch(err=> {
183                 $log.error('Header Controller:: getOnlineUserUpdateRate() failed: ' + err);
184             });
185             
186             $scope.start = function(rate) {
187                                 // stops any running interval to avoid two intervals running at the same time
188                                 $scope.stop();  
189                                 // store the interval promise
190                                 intervalPromise = $interval(updateActiveUsers, rate);
191                         };
192
193                         $scope.stop = function() {
194                                 $interval.cancel(intervalPromise);
195                         };
196                 
197                         $scope.$watch('myservice.getRefreshCount()', function (newVal,oldVal) {
198                                 //$log.info("refresh "+$scope.myservice.refreshCount + " more time(s)");
199                                 if (newVal<=0) {
200                                         // $log.info("UserbarCtrl: stopped refreshing online users");
201                                         $scope.stop();
202                                 } else if (newVal== $scope.myservice.maxCount){
203                                         // $log.info("UserbarCtrl: start refreshing online users at every "+($scope.updateRate/1000)+" sec");
204                                         // initial update of activate users
205                                         userProfileService.getUserProfile().then(res=> { 
206                                                 if (res == null || res.orgUserId == null) {
207                                                         $log.error('UserbarCtlr: failed to get profile of the user!');
208                                                 }
209                                                 else {
210                                                         updateActiveUsers();
211                                                         $scope.start($scope.updateRate);
212                                                         socketSetup(null, res.orgUserId, null, "socketSend");
213                                                 }
214                                         });
215                                         
216                                         
217                                 }
218                         });
219                 function updateActiveUsers() {
220             userProfileService.getActiveUser()
221             .then(res=> {
222                 $log.info('getting Active User init***********************');
223                 // decrement the counter every time updateActiveUser is called;
224                                 userbarUpdateService.decrementRefreshCount();
225             
226                 if(res==null ||res.status!='OK'){
227                         $log.error('failed updateActiveUsers res is null.. ');
228                         
229                 }else{
230                         $log.info('getting ActiveUser successfully',res);   
231                         $scope.userList = [];
232                         var maxItems = 10;
233                         var users = res.response;
234                         if (users.length < maxItems)
235                                 maxItems = users.length;
236                         for(var i=0;i<maxItems;i++){
237                                 var data= {
238                                                 userId:users[i][0],
239                                                 linkQ:userProfileService.getSortedUserIdCombination(userProfileService.userProfile.orgUserId , users[i][0])
240                                 }
241                                 $scope.userList.push(data);
242                         }
243                         
244                         $log.info(' ActiveUser =',$scope.userList);   
245                 }       
246             }).catch(err=> {
247                 $log.error('Header Controller:: getActiveUser() failed: ' + err);
248             }).finally(() => {
249                 var footerOff = $('#online-userbar').offset().top;
250                         var headOff = $('#footer').offset().top;
251                         var userbarHeight= parseInt($(".online-user-container").css('height'),10);
252                         var defaultOffSet = 45;
253                         $(".online-user-container").css({
254                                 "height" : headOff - footerOff-defaultOffSet
255                         });
256             });
257                 }
258         }
259     }
260     UserbarCtrl.$inject = ['userProfileService', 'userbarUpdateService', '$log', '$rootScope','$interval','$scope','$timeout','dashboardService'];
261     angular.module('ecompApp').controller('UserbarCtrl', UserbarCtrl);
262 })();