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