be3278d088237236ab325796c4c80e505f28741f
[osm/UI.git] / skyquake / framework / utils / utils.js
1 /*
2 *
3 * Copyright 2016 RIFT.IO Inc
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18 //Login needs to be refactored. Too many cross dependencies
19 var AuthActions = require('../widgets/login/loginAuthActions.js');
20 var $ = require('jquery');
21 var rw = require('utils/rw.js');
22 var API_SERVER = rw.getSearchParams(window.location).api_server;
23 let NODE_PORT = require('utils/rw.js').getSearchParams(window.location).api_port || ((window.location.protocol == 'https:') ? 8443 : 8000);
24 var SockJS = require('sockjs-client');
25
26 var Utils = {};
27
28 Utils.DescriptorModelMeta = null;
29
30 var INACTIVITY_TIMEOUT = 600000;
31
32 Utils.getInactivityTimeout = function() {
33 return new Promise(function(resolve, reject) {
34 $.ajax({
35 url: '/inactivity-timeout',
36 type: 'GET',
37 success: function(data) {
38 resolve(data);
39 },
40 error: function(error) {
41 console.log("There was an error getting the inactivity-timeout: ", error);
42 reject(error);
43 }
44 }).fail(function(xhr) {
45 console.log('There was an xhr error getting the inactivity-timeout', xhr);
46 reject(xhr);
47 });
48 });
49 };
50
51 Utils.isMultiplexerLoaded = function() {
52 if (window.multiplexer) {
53 return true;
54 }
55 return false;
56 };
57
58 Utils.setupMultiplexClient = function() {
59 var sockjs_url = '/multiplex';
60
61 var sockjs = new SockJS(sockjs_url);
62
63 var loadChecker = function() {
64 try {
65 window.multiplexer = new WebSocketMultiplex(sockjs);
66 console.log('WebSocketMultiplex loaded');
67 } catch (e) {
68 // caught an error, retry in someTime
69 console.log('WebSocketMultiplex not loaded yet. will try again in 1 second:', e);
70 setTimeout(function() {
71 loadChecker();
72 }, 1000);
73 }
74 }
75 loadChecker();
76 };
77
78 Utils.checkAndResolveSocketRequest = function(data, resolve, reject) {
79 const checker = () => {
80 if (!Utils.isMultiplexerLoaded()) {
81 setTimeout(() => {
82 checker();
83 }, 500);
84 } else {
85 resolve(data.id);
86 }
87 };
88
89 checker();
90 };
91
92 Utils.bootstrapApplication = function() {
93 var self = this;
94 return new Promise(function(resolve, reject) {
95 Promise.all([self.getInactivityTimeout()]).then(function(results) {
96 INACTIVITY_TIMEOUT = results[0]['inactivity-timeout'];
97 resolve();
98 }, function(error) {
99 console.log("Error bootstrapping application ", error);
100 reject();
101 });
102 });
103 };
104
105 Utils.getDescriptorModelMeta = function() {
106 return new Promise(function(resolve, reject) {
107 if (!Utils.DescriptorModelMeta) {
108 $.ajax({
109 url: '/descriptor-model-meta?api_server=' + API_SERVER,
110 type: 'GET',
111 beforeSend: Utils.addAuthorizationStub,
112 success: function(data) {
113 Utils.DescriptorModelMeta = data;
114 Utils.DescriptorModelMetaLoaded = true;
115 resolve(data);
116 },
117 error: function(error) {
118 console.log("There was an error getting the schema: ", error);
119 reject(error);
120 }
121 }).fail(function(xhr) {
122 console.log("There was an error getting the schema: ", xhr);
123 Utils.checkAuthentication(xhr.status);
124 });
125 } else {
126 resolve(Utils.DescriptorModelMeta);
127 }
128 })
129 }
130
131 Utils.addAuthorizationStub = function(xhr) {
132 // NO-OP now that we are dealing with it on the server
133 // var Auth = window.sessionStorage.getItem("auth");
134 // xhr.setRequestHeader('Authorization', 'Basic ' + Auth);
135 };
136
137 Utils.getByteDataWithUnitPrefix = function(number, precision) {
138 var toPrecision = precision || 3;
139 if (number < Math.pow(10, 3)) {
140 return [number, 'B'];
141 } else if (number < Math.pow(10, 6)) {
142 return [(number / Math.pow(10, 3)).toPrecision(toPrecision), 'KB'];
143 } else if (number < Math.pow(10, 9)) {
144 return [(number / Math.pow(10, 6)).toPrecision(toPrecision), 'MB'];
145 } else if (number < Math.pow(10, 12)) {
146 return [(number / Math.pow(10, 9)).toPrecision(toPrecision), 'GB'];
147 } else if (number < Math.pow(10, 15)) {
148 return [(number / Math.pow(10, 12)).toPrecision(toPrecision), 'TB'];
149 } else if (number < Math.pow(10, 18)) {
150 return [(number / Math.pow(10, 15)).toPrecision(toPrecision), 'PB'];
151 } else if (number < Math.pow(10, 21)) {
152 return [(number / Math.pow(10, 18)).toPrecision(toPrecision), 'EB'];
153 } else if (number < Math.pow(10, 24)) {
154 return [(number / Math.pow(10, 21)).toPrecision(toPrecision), 'ZB'];
155 } else if (number < Math.pow(10, 27)) {
156 return [(number / Math.pow(10, 24)).toPrecision(toPrecision), 'ZB'];
157 } else {
158 return [(number / Math.pow(10, 27)).toPrecision(toPrecision), 'YB'];
159 }
160 }
161
162 Utils.getPacketDataWithUnitPrefix = function(number, precision) {
163 var toPrecision = precision || 3;
164 if (number < Math.pow(10, 3)) {
165 return [number, 'P'];
166 } else if (number < Math.pow(10, 6)) {
167 return [(number / Math.pow(10, 3)).toPrecision(toPrecision), 'KP'];
168 } else if (number < Math.pow(10, 9)) {
169 return [(number / Math.pow(10, 6)).toPrecision(toPrecision), 'MP'];
170 } else if (number < Math.pow(10, 12)) {
171 return [(number / Math.pow(10, 9)).toPrecision(toPrecision), 'GP'];
172 } else if (number < Math.pow(10, 15)) {
173 return [(number / Math.pow(10, 12)).toPrecision(toPrecision), 'TP'];
174 } else if (number < Math.pow(10, 18)) {
175 return [(number / Math.pow(10, 15)).toPrecision(toPrecision), 'PP'];
176 } else if (number < Math.pow(10, 21)) {
177 return [(number / Math.pow(10, 18)).toPrecision(toPrecision), 'EP'];
178 } else if (number < Math.pow(10, 24)) {
179 return [(number / Math.pow(10, 21)).toPrecision(toPrecision), 'ZP'];
180 } else if (number < Math.pow(10, 27)) {
181 return [(number / Math.pow(10, 24)).toPrecision(toPrecision), 'ZP'];
182 } else {
183 return [(number / Math.pow(10, 27)).toPrecision(toPrecision), 'YP'];
184 }
185 }
186 Utils.loginHash = "#/login";
187 Utils.setAuthentication = function(username, password, cb) {
188 var self = this;
189 var AuthBase64 = btoa(username + ":" + password);
190 window.sessionStorage.setItem("auth", AuthBase64);
191 self.detectInactivity();
192 $.ajax({
193 url: '//' + window.location.hostname + ':' + window.location.port + '/check-auth?api_server=' + API_SERVER,
194 type: 'GET',
195 beforeSend: Utils.addAuthorizationStub,
196 success: function(data) {
197 //console.log("LoggingSource.getLoggingConfig success call. data=", data);
198 if (cb) {
199 cb();
200 };
201 },
202 error: function(data) {
203 Utils.clearAuthentication();
204 }
205 });
206 }
207 Utils.clearAuthentication = function(callback) {
208 var self = this;
209 window.sessionStorage.removeItem("auth");
210 AuthActions.notAuthenticated();
211 window.sessionStorage.setItem("locationRefHash", window.location.hash);
212 $.ajax({
213 url: '//' + window.location.hostname + ':' + window.location.port + '/session?api_server=' + API_SERVER,
214 type: 'DELETE',
215 success: function(data) {
216 console.log('User logged out');
217 },
218 error: function(data) {
219 console.log('Problem logging user out');
220 }
221 });
222
223
224 if (callback) {
225 callback();
226 } else {
227 window.location.replace(window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/?api_server=' + API_SERVER);
228 }
229 }
230 Utils.isNotAuthenticated = function(windowLocation, callback) {
231 var self = this;
232 self.detectInactivity();
233 if (!window.sessionStorage.getItem("auth")) {
234 Utils.clearAuthentication();
235 }
236 }
237 Utils.isDetecting = false;
238 Utils.detectInactivity = function(callback, duration) {
239 var self = this;
240 if (!self.isDetecting) {
241 var cb = function() {
242 self.clearAuthentication();
243 if (callback) {
244 callback();
245 }
246 };
247 var isInactive;
248 var timeout = duration || INACTIVITY_TIMEOUT;
249 var setInactive = function() {
250 isInactive = setTimeout(cb, timeout);
251 };
252 var reset = function() {
253 clearTimeout(isInactive);
254 setInactive();
255 }
256 setInactive();
257 window.addEventListener('mousemove', reset);
258 window.addEventListener("keypress", reset);
259 self.isDetecting = true;
260 }
261 }
262 Utils.checkAuthentication = function(statusCode, cb) {
263 var self = this;
264 if (statusCode == 401) {
265 if (cb) {
266 cb();
267 }
268 window.sessionStorage.removeItem("auth")
269 self.isNotAuthenticated(window.location)
270 return true;
271 }
272 return false;
273 }
274
275 Utils.isAuthenticationCached = function() {
276 var self = this;
277 if (window.sessionStorage.getItem("auth")) {
278 return true;
279 }
280 return false;
281 }
282
283 Utils.getHostNameFromURL = function(url) {
284 var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([^?#]*)(\?[^#]*|)(#.*|)$/);
285 return match && match[3];
286 }
287
288 Utils.webSocketProtocol = function() {
289 if (this.wsProto) {
290 return this.wsProto;
291 } else {
292 if (window.location.protocol == 'http:') {
293 this.wsProto = 'ws:'
294 } else {
295 this.wsProto = 'wss:'
296 }
297 }
298 return this.wsProto;
299 }
300
301 Utils.arrayIntersperse = (arr, sep) => {
302 if (arr.length === 0) {
303 return [];
304 }
305
306 return arr.slice(1).reduce((xs, x, i) => {
307 return xs.concat([sep, x]);
308 }, [arr[0]]);
309 }
310
311 Utils.cleanImageDataURI = (imageString, type, id) => {
312 if (/\bbase64\b/g.test(imageString)) {
313 return imageString;
314 } else if (/<\?xml\b/g.test(imageString)) {
315 const imgStr = imageString.substring(imageString.indexOf('<?xml'));
316 return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(imgStr);
317 } else if (/\.(svg|png|gif|jpeg|jpg)$/.test(imageString)) {
318 return '/composer/assets/logos/' + type + '/' + id + '/' + imageString;
319 // return require('../images/logos/' + imageString);
320 }
321 if(type == 'nsd' || type == 'vnfd') {
322 return require('style/img/catalog-'+type+'-default.svg');
323 }
324 return require('style/img/catalog-default.svg');
325 }
326
327 module.exports = Utils;