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