Merge "RIFT-15032: launchpad UI - Viewport - icons for nsr"
[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 var Auth = window.sessionStorage.getItem("auth");
133 xhr.setRequestHeader('Authorization', 'Basic ' + Auth);
134 };
135
136 Utils.getByteDataWithUnitPrefix = function(number, precision) {
137 var toPrecision = precision || 3;
138 if (number < Math.pow(10, 3)) {
139 return [number, 'B'];
140 } else if (number < Math.pow(10, 6)) {
141 return [(number / Math.pow(10, 3)).toPrecision(toPrecision), 'KB'];
142 } else if (number < Math.pow(10, 9)) {
143 return [(number / Math.pow(10, 6)).toPrecision(toPrecision), 'MB'];
144 } else if (number < Math.pow(10, 12)) {
145 return [(number / Math.pow(10, 9)).toPrecision(toPrecision), 'GB'];
146 } else if (number < Math.pow(10, 15)) {
147 return [(number / Math.pow(10, 12)).toPrecision(toPrecision), 'TB'];
148 } else if (number < Math.pow(10, 18)) {
149 return [(number / Math.pow(10, 15)).toPrecision(toPrecision), 'PB'];
150 } else if (number < Math.pow(10, 21)) {
151 return [(number / Math.pow(10, 18)).toPrecision(toPrecision), 'EB'];
152 } else if (number < Math.pow(10, 24)) {
153 return [(number / Math.pow(10, 21)).toPrecision(toPrecision), 'ZB'];
154 } else if (number < Math.pow(10, 27)) {
155 return [(number / Math.pow(10, 24)).toPrecision(toPrecision), 'ZB'];
156 } else {
157 return [(number / Math.pow(10, 27)).toPrecision(toPrecision), 'YB'];
158 }
159 }
160
161 Utils.getPacketDataWithUnitPrefix = function(number, precision) {
162 var toPrecision = precision || 3;
163 if (number < Math.pow(10, 3)) {
164 return [number, 'P'];
165 } else if (number < Math.pow(10, 6)) {
166 return [(number / Math.pow(10, 3)).toPrecision(toPrecision), 'KP'];
167 } else if (number < Math.pow(10, 9)) {
168 return [(number / Math.pow(10, 6)).toPrecision(toPrecision), 'MP'];
169 } else if (number < Math.pow(10, 12)) {
170 return [(number / Math.pow(10, 9)).toPrecision(toPrecision), 'GP'];
171 } else if (number < Math.pow(10, 15)) {
172 return [(number / Math.pow(10, 12)).toPrecision(toPrecision), 'TP'];
173 } else if (number < Math.pow(10, 18)) {
174 return [(number / Math.pow(10, 15)).toPrecision(toPrecision), 'PP'];
175 } else if (number < Math.pow(10, 21)) {
176 return [(number / Math.pow(10, 18)).toPrecision(toPrecision), 'EP'];
177 } else if (number < Math.pow(10, 24)) {
178 return [(number / Math.pow(10, 21)).toPrecision(toPrecision), 'ZP'];
179 } else if (number < Math.pow(10, 27)) {
180 return [(number / Math.pow(10, 24)).toPrecision(toPrecision), 'ZP'];
181 } else {
182 return [(number / Math.pow(10, 27)).toPrecision(toPrecision), 'YP'];
183 }
184 }
185 Utils.loginHash = "#/login";
186 Utils.setAuthentication = function(username, password, cb) {
187 var self = this;
188 var AuthBase64 = btoa(username + ":" + password);
189 window.sessionStorage.setItem("auth", AuthBase64);
190 self.detectInactivity();
191 $.ajax({
192 url: '//' + window.location.hostname + ':' + NODE_PORT + '/check-auth?api_server=' + API_SERVER,
193 type: 'GET',
194 beforeSend: Utils.addAuthorizationStub,
195 success: function(data) {
196 //console.log("LoggingSource.getLoggingConfig success call. data=", data);
197 if (cb) {
198 cb();
199 };
200 },
201 error: function(data) {
202 Utils.clearAuthentication();
203 }
204 });
205 }
206 Utils.clearAuthentication = function(callback) {
207 var self = this;
208 window.sessionStorage.removeItem("auth");
209 AuthActions.notAuthenticated();
210 window.sessionStorage.setItem("locationRefHash", window.location.hash);
211 if (callback) {
212 callback();
213 } else {
214 window.location.hash = Utils.loginHash;
215 }
216 }
217 Utils.isNotAuthenticated = function(windowLocation, callback) {
218 var self = this;
219 self.detectInactivity();
220 if (!window.sessionStorage.getItem("auth")) {
221 Utils.clearAuthentication();
222 }
223 }
224 Utils.isDetecting = false;
225 Utils.detectInactivity = function(callback, duration) {
226 var self = this;
227 if (!self.isDetecting) {
228 var cb = function() {
229 self.clearAuthentication();
230 if (callback) {
231 callback();
232 }
233 };
234 var isInactive;
235 var timeout = duration || INACTIVITY_TIMEOUT;
236 var setInactive = function() {
237 isInactive = setTimeout(cb, timeout);
238 };
239 var reset = function() {
240 clearTimeout(isInactive);
241 setInactive();
242 }
243 setInactive();
244 window.addEventListener('mousemove', reset);
245 window.addEventListener("keypress", reset);
246 self.isDetecting = true;
247 }
248 }
249 Utils.checkAuthentication = function(statusCode, cb) {
250 var self = this;
251 if (statusCode == 401) {
252 if (cb) {
253 cb();
254 }
255 window.sessionStorage.removeItem("auth")
256 self.isNotAuthenticated(window.location)
257 return true;
258 }
259 return false;
260 }
261
262 Utils.isAuthenticationCached = function() {
263 var self = this;
264 if (window.sessionStorage.getItem("auth")) {
265 return true;
266 }
267 return false;
268 }
269
270 Utils.getHostNameFromURL = function(url) {
271 var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([^?#]*)(\?[^#]*|)(#.*|)$/);
272 return match && match[3];
273 }
274
275 Utils.webSocketProtocol = function() {
276 if (this.wsProto) {
277 return this.wsProto;
278 } else {
279 if (window.location.protocol == 'http:') {
280 this.wsProto = 'ws:'
281 } else {
282 this.wsProto = 'wss:'
283 }
284 }
285 return this.wsProto;
286 }
287
288 Utils.arrayIntersperse = (arr, sep) => {
289 if (arr.length === 0) {
290 return [];
291 }
292
293 return arr.slice(1).reduce((xs, x, i) => {
294 return xs.concat([sep, x]);
295 }, [arr[0]]);
296 }
297
298 Utils.cleanImageDataURI = (imageString, type, id) => {
299 if (/\bbase64\b/g.test(imageString)) {
300 return imageString;
301 } else if (/<\?xml\b/g.test(imageString)) {
302 const imgStr = imageString.substring(imageString.indexOf('<?xml'));
303 return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(imgStr);
304 } else if (/\.(svg|png|gif|jpeg|jpg)$/.test(imageString)) {
305 return '/composer/assets/logos/' + type + '/' + id + '/' + imageString;
306 // return require('../images/logos/' + imageString);
307 }
308 if(type == 'nsd' || type == 'vnfd') {
309 return require('style/img/catalog-'+type+'-default.svg');
310 }
311 return require('style/img/catalog-default.svg');
312 }
313
314 module.exports = Utils;