d08fe5f83d1765e49d7bb676aac2936dc929f44c
[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 var NODE_PORT = 3000;
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 if (cb) {
192 cb();
193 }
194 }
195 Utils.clearAuthentication = function(callback) {
196 var self = this;
197 window.sessionStorage.removeItem("auth");
198 AuthActions.notAuthenticated();
199 window.sessionStorage.setItem("locationRefHash", window.location.hash);
200 if (callback) {
201 callback();
202 } else {
203 window.location.hash = Utils.loginHash;
204 }
205 }
206 Utils.isNotAuthenticated = function(windowLocation, callback) {
207 var self = this;
208 self.detectInactivity();
209 if (!window.sessionStorage.getItem("auth")) {
210 Utils.clearAuthentication();
211 }
212 }
213 Utils.isDetecting = false;
214 Utils.detectInactivity = function(callback, duration) {
215 var self = this;
216 if (!self.isDetecting) {
217 var cb = function() {
218 self.clearAuthentication();
219 if (callback) {
220 callback();
221 }
222 };
223 var isInactive;
224 var timeout = duration || INACTIVITY_TIMEOUT;
225 var setInactive = function() {
226 isInactive = setTimeout(cb, timeout);
227 };
228 var reset = function() {
229 clearTimeout(isInactive);
230 setInactive();
231 }
232 setInactive();
233 window.addEventListener('mousemove', reset);
234 window.addEventListener("keypress", reset);
235 self.isDetecting = true;
236 }
237 }
238 Utils.checkAuthentication = function(statusCode, cb) {
239 var self = this;
240 if (statusCode == 401) {
241 if (cb) {
242 cb();
243 }
244 window.sessionStorage.removeItem("auth")
245 self.isNotAuthenticated(window.location)
246 return true;
247 }
248 return false;
249 }
250
251 Utils.isAuthenticationCached = function() {
252 var self = this;
253 if (window.sessionStorage.getItem("auth")) {
254 return true;
255 }
256 return false;
257 }
258
259 Utils.getHostNameFromURL = function(url) {
260 var match = url.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([^?#]*)(\?[^#]*|)(#.*|)$/);
261 return match && match[3];
262 }
263
264 Utils.webSocketProtocol = function() {
265 if (this.wsProto) {
266 return this.wsProto;
267 } else {
268 if (window.location.protocol == 'http:') {
269 this.wsProto = 'ws:'
270 } else {
271 this.wsProto = 'wss:'
272 }
273 }
274 return this.wsProto;
275 }
276
277 Utils.arrayIntersperse = (arr, sep) => {
278 if (arr.length === 0) {
279 return [];
280 }
281
282 return arr.slice(1).reduce((xs, x, i) => {
283 return xs.concat([sep, x]);
284 }, [arr[0]]);
285 }
286
287 module.exports = Utils;