]>
Commit | Line | Data |
---|---|---|
ecabd437 TL |
1 | Ext.ns('Proxmox'); |
2 | Ext.ns('Proxmox.Setup'); | |
3 | ||
4 | if (!Ext.isDefined(Proxmox.Setup.auth_cookie_name)) { | |
5 | throw "Proxmox library not initialized"; | |
6 | } | |
7 | ||
ecabd437 TL |
8 | // avoid errors when running without development tools |
9 | if (!Ext.isDefined(Ext.global.console)) { | |
10 | let console = { | |
11 | dir: function() { | |
12 | // do nothing | |
13 | }, | |
14 | log: function() { | |
15 | // do nothing | |
16 | }, | |
17 | warn: function() { | |
18 | // do nothing | |
19 | }, | |
20 | }; | |
21 | Ext.global.console = console; | |
22 | } | |
23 | ||
24 | Ext.Ajax.defaultHeaders = { | |
25 | 'Accept': 'application/json', | |
26 | }; | |
27 | ||
28 | Ext.Ajax.on('beforerequest', function(conn, options) { | |
29 | if (Proxmox.CSRFPreventionToken) { | |
30 | if (!options.headers) { | |
31 | options.headers = {}; | |
32 | } | |
33 | options.headers.CSRFPreventionToken = Proxmox.CSRFPreventionToken; | |
34 | } | |
b6d1735a TL |
35 | let storedAuth = Proxmox.Utils.getStoredAuth(); |
36 | if (storedAuth.token) { | |
37 | options.headers.Authorization = storedAuth.token; | |
63252ab6 | 38 | } |
ecabd437 TL |
39 | }); |
40 | ||
41 | Ext.define('Proxmox.Utils', { // a singleton | |
42 | utilities: { | |
43 | ||
44 | yesText: gettext('Yes'), | |
45 | noText: gettext('No'), | |
46 | enabledText: gettext('Enabled'), | |
47 | disabledText: gettext('Disabled'), | |
48 | noneText: gettext('none'), | |
49 | NoneText: gettext('None'), | |
50 | errorText: gettext('Error'), | |
64d85d96 | 51 | warningsText: gettext('Warnings'), |
ecabd437 TL |
52 | unknownText: gettext('Unknown'), |
53 | defaultText: gettext('Default'), | |
54 | daysText: gettext('days'), | |
55 | dayText: gettext('day'), | |
56 | runningText: gettext('running'), | |
57 | stoppedText: gettext('stopped'), | |
58 | neverText: gettext('never'), | |
59 | totalText: gettext('Total'), | |
60 | usedText: gettext('Used'), | |
61 | directoryText: gettext('Directory'), | |
62 | stateText: gettext('State'), | |
63 | groupText: gettext('Group'), | |
64 | ||
65 | language_map: { | |
66 | ar: 'Arabic', | |
67 | ca: 'Catalan', | |
998237fc TL |
68 | zh_CN: 'Chinese (Simplified)', |
69 | zh_TW: 'Chinese (Traditional)', | |
ecabd437 | 70 | da: 'Danish', |
6127ba88 | 71 | nl: 'Dutch', |
ecabd437 | 72 | en: 'English', |
ecabd437 | 73 | eu: 'Euskera (Basque)', |
ecabd437 | 74 | fr: 'French', |
998237fc | 75 | de: 'German', |
ecabd437 TL |
76 | he: 'Hebrew', |
77 | it: 'Italian', | |
78 | ja: 'Japanese', | |
abfc1857 | 79 | kr: 'Korean', |
ecabd437 TL |
80 | nb: 'Norwegian (Bokmal)', |
81 | nn: 'Norwegian (Nynorsk)', | |
998237fc | 82 | fa: 'Persian (Farsi)', |
ecabd437 TL |
83 | pl: 'Polish', |
84 | pt_BR: 'Portuguese (Brazil)', | |
85 | ru: 'Russian', | |
86 | sl: 'Slovenian', | |
998237fc | 87 | es: 'Spanish', |
ecabd437 TL |
88 | sv: 'Swedish', |
89 | tr: 'Turkish', | |
ecabd437 TL |
90 | }, |
91 | ||
92 | render_language: function(value) { | |
e06715d2 | 93 | if (!value || value === '__default__') { |
ecabd437 TL |
94 | return Proxmox.Utils.defaultText + ' (English)'; |
95 | } | |
96 | let text = Proxmox.Utils.language_map[value]; | |
97 | if (text) { | |
98 | return text + ' (' + value + ')'; | |
99 | } | |
100 | return value; | |
101 | }, | |
102 | ||
103 | language_array: function() { | |
104 | let data = [['__default__', Proxmox.Utils.render_language('')]]; | |
105 | Ext.Object.each(Proxmox.Utils.language_map, function(key, value) { | |
106 | data.push([key, Proxmox.Utils.render_language(value)]); | |
107 | }); | |
108 | ||
109 | return data; | |
110 | }, | |
111 | ||
112 | bond_mode_gettext_map: { | |
113 | '802.3ad': 'LACP (802.3ad)', | |
114 | 'lacp-balance-slb': 'LACP (balance-slb)', | |
115 | 'lacp-balance-tcp': 'LACP (balance-tcp)', | |
116 | }, | |
117 | ||
118 | render_bond_mode: value => Proxmox.Utils.bond_mode_gettext_map[value] || value || '', | |
119 | ||
120 | bond_mode_array: function(modes) { | |
121 | return modes.map(mode => [mode, Proxmox.Utils.render_bond_mode(mode)]); | |
122 | }, | |
123 | ||
124 | getNoSubKeyHtml: function(url) { | |
125 | // url http://www.proxmox.com/products/proxmox-ve/subscription-service-plans | |
126 | return Ext.String.format('You do not have a valid subscription for this server. Please visit <a target="_blank" href="{0}">www.proxmox.com</a> to get a list of available options.', url || 'https://www.proxmox.com'); | |
127 | }, | |
128 | ||
129 | format_boolean_with_default: function(value) { | |
130 | if (Ext.isDefined(value) && value !== '__default__') { | |
131 | return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText; | |
132 | } | |
133 | return Proxmox.Utils.defaultText; | |
134 | }, | |
135 | ||
136 | format_boolean: function(value) { | |
137 | return value ? Proxmox.Utils.yesText : Proxmox.Utils.noText; | |
138 | }, | |
139 | ||
140 | format_neg_boolean: function(value) { | |
141 | return !value ? Proxmox.Utils.yesText : Proxmox.Utils.noText; | |
142 | }, | |
143 | ||
144 | format_enabled_toggle: function(value) { | |
145 | return value ? Proxmox.Utils.enabledText : Proxmox.Utils.disabledText; | |
146 | }, | |
147 | ||
148 | format_expire: function(date) { | |
149 | if (!date) { | |
150 | return Proxmox.Utils.neverText; | |
151 | } | |
152 | return Ext.Date.format(date, "Y-m-d"); | |
153 | }, | |
154 | ||
155 | // somewhat like a human would tell durations, omit zero values and do not | |
156 | // give seconds precision if we talk days already | |
157 | format_duration_human: function(ut) { | |
3ccdce40 | 158 | let seconds = 0, minutes = 0, hours = 0, days = 0, years = 0; |
ecabd437 | 159 | |
b2d7d422 DC |
160 | if (ut <= 0.1) { |
161 | return '<0.1s'; | |
ecabd437 TL |
162 | } |
163 | ||
164 | let remaining = ut; | |
165 | seconds = Number((remaining % 60).toFixed(1)); | |
166 | remaining = Math.trunc(remaining / 60); | |
167 | if (remaining > 0) { | |
168 | minutes = remaining % 60; | |
169 | remaining = Math.trunc(remaining / 60); | |
170 | if (remaining > 0) { | |
171 | hours = remaining % 24; | |
172 | remaining = Math.trunc(remaining / 24); | |
173 | if (remaining > 0) { | |
3ccdce40 TL |
174 | days = remaining % 365; |
175 | remaining = Math.trunc(remaining / 365); // yea, just lets ignore leap years... | |
176 | if (remaining > 0) { | |
177 | years = remaining; | |
178 | } | |
ecabd437 TL |
179 | } |
180 | } | |
181 | } | |
182 | ||
183 | let res = []; | |
184 | let add = (t, unit) => { | |
185 | if (t > 0) res.push(t + unit); | |
186 | return t > 0; | |
187 | }; | |
188 | ||
3ccdce40 | 189 | let addMinutes = !add(years, 'y'); |
ecabd437 TL |
190 | let addSeconds = !add(days, 'd'); |
191 | add(hours, 'h'); | |
3ccdce40 TL |
192 | if (addMinutes) { |
193 | add(minutes, 'm'); | |
194 | if (addSeconds) { | |
195 | add(seconds, 's'); | |
196 | } | |
ecabd437 TL |
197 | } |
198 | return res.join(' '); | |
199 | }, | |
200 | ||
201 | format_duration_long: function(ut) { | |
202 | let days = Math.floor(ut / 86400); | |
203 | ut -= days*86400; | |
204 | let hours = Math.floor(ut / 3600); | |
205 | ut -= hours*3600; | |
206 | let mins = Math.floor(ut / 60); | |
207 | ut -= mins*60; | |
208 | ||
209 | let hours_str = '00' + hours.toString(); | |
210 | hours_str = hours_str.substr(hours_str.length - 2); | |
211 | let mins_str = "00" + mins.toString(); | |
212 | mins_str = mins_str.substr(mins_str.length - 2); | |
213 | let ut_str = "00" + ut.toString(); | |
214 | ut_str = ut_str.substr(ut_str.length - 2); | |
215 | ||
216 | if (days) { | |
217 | let ds = days > 1 ? Proxmox.Utils.daysText : Proxmox.Utils.dayText; | |
218 | return days.toString() + ' ' + ds + ' ' + | |
219 | hours_str + ':' + mins_str + ':' + ut_str; | |
220 | } else { | |
221 | return hours_str + ':' + mins_str + ':' + ut_str; | |
222 | } | |
223 | }, | |
224 | ||
225 | format_subscription_level: function(level) { | |
226 | if (level === 'c') { | |
227 | return 'Community'; | |
228 | } else if (level === 'b') { | |
229 | return 'Basic'; | |
230 | } else if (level === 's') { | |
231 | return 'Standard'; | |
232 | } else if (level === 'p') { | |
233 | return 'Premium'; | |
234 | } else { | |
235 | return Proxmox.Utils.noneText; | |
236 | } | |
237 | }, | |
238 | ||
239 | compute_min_label_width: function(text, width) { | |
240 | if (width === undefined) { width = 100; } | |
241 | ||
242 | let tm = new Ext.util.TextMetrics(); | |
243 | let min = tm.getWidth(text + ':'); | |
244 | ||
245 | return min < width ? width : min; | |
246 | }, | |
247 | ||
e722f108 TL |
248 | // returns username + realm |
249 | parse_userid: function(userid) { | |
250 | if (!Ext.isString(userid)) { | |
251 | return [undefined, undefined]; | |
252 | } | |
253 | ||
254 | let match = userid.match(/^(.+)@([^@]+)$/); | |
255 | if (match !== null) { | |
256 | return [match[1], match[2]]; | |
257 | } | |
258 | ||
259 | return [undefined, undefined]; | |
260 | }, | |
261 | ||
262 | render_username: function(userid) { | |
cd20320b | 263 | let username = Proxmox.Utils.parse_userid(userid)[0] || ""; |
e722f108 TL |
264 | return Ext.htmlEncode(username); |
265 | }, | |
266 | ||
267 | render_realm: function(userid) { | |
cd20320b | 268 | let username = Proxmox.Utils.parse_userid(userid)[1] || ""; |
e722f108 TL |
269 | return Ext.htmlEncode(username); |
270 | }, | |
271 | ||
63252ab6 TM |
272 | getStoredAuth: function() { |
273 | let storedAuth = JSON.parse(window.localStorage.getItem('ProxmoxUser')); | |
274 | return storedAuth || {}; | |
275 | }, | |
276 | ||
ecabd437 | 277 | setAuthData: function(data) { |
ecabd437 TL |
278 | Proxmox.UserName = data.username; |
279 | Proxmox.LoggedOut = data.LoggedOut; | |
280 | // creates a session cookie (expire = null) | |
281 | // that way the cookie gets deleted after the browser window is closed | |
63252ab6 TM |
282 | if (data.ticket) { |
283 | Proxmox.CSRFPreventionToken = data.CSRFPreventionToken; | |
284 | Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, data.ticket, null, '/', null, true); | |
285 | } | |
286 | ||
287 | if (data.token) { | |
288 | window.localStorage.setItem('ProxmoxUser', JSON.stringify(data)); | |
289 | } | |
ecabd437 TL |
290 | }, |
291 | ||
292 | authOK: function() { | |
293 | if (Proxmox.LoggedOut) { | |
294 | return undefined; | |
295 | } | |
b6d1735a | 296 | let storedAuth = Proxmox.Utils.getStoredAuth(); |
ecabd437 | 297 | let cookie = Ext.util.Cookies.get(Proxmox.Setup.auth_cookie_name); |
63252ab6 TM |
298 | if ((Proxmox.UserName !== '' && cookie && !cookie.startsWith("PVE:tfa!")) || storedAuth.token) { |
299 | return cookie || storedAuth.token; | |
ecabd437 TL |
300 | } else { |
301 | return false; | |
302 | } | |
303 | }, | |
304 | ||
305 | authClear: function() { | |
306 | if (Proxmox.LoggedOut) { | |
307 | return; | |
308 | } | |
c1a35841 | 309 | Ext.util.Cookies.set(Proxmox.Setup.auth_cookie_name, "", new Date(0), null, null, true); |
63252ab6 | 310 | window.localStorage.removeItem("ProxmoxUser"); |
ecabd437 TL |
311 | }, |
312 | ||
e8c60b32 TL |
313 | // The End-User gets redirected back here after login on the OpenID auth. portal, and in the |
314 | // redirection URL the state and auth.code are passed as URL GET params, this helper parses those | |
315 | getOpenIDRedirectionAuthorization: function() { | |
316 | const auth = Ext.Object.fromQueryString(window.location.search); | |
317 | if (auth.state !== undefined && auth.code !== undefined) { | |
318 | return auth; | |
319 | } | |
320 | return undefined; | |
321 | }, | |
322 | ||
ecabd437 TL |
323 | // comp.setLoading() is buggy in ExtJS 4.0.7, so we |
324 | // use el.mask() instead | |
325 | setErrorMask: function(comp, msg) { | |
326 | let el = comp.el; | |
327 | if (!el) { | |
328 | return; | |
329 | } | |
330 | if (!msg) { | |
331 | el.unmask(); | |
332 | } else if (msg === true) { | |
333 | el.mask(gettext("Loading...")); | |
334 | } else { | |
335 | el.mask(msg); | |
336 | } | |
337 | }, | |
338 | ||
339 | getResponseErrorMessage: (err) => { | |
340 | if (!err.statusText) { | |
341 | return gettext('Connection error'); | |
342 | } | |
343 | let msg = [`${err.statusText} (${err.status})`]; | |
344 | if (err.response && err.response.responseText) { | |
345 | let txt = err.response.responseText; | |
346 | try { | |
347 | let res = JSON.parse(txt); | |
348 | if (res.errors && typeof res.errors === 'object') { | |
349 | for (let [key, value] of Object.entries(res.errors)) { | |
350 | msg.push(Ext.String.htmlEncode(`${key}: ${value}`)); | |
351 | } | |
352 | } | |
353 | } catch (e) { | |
354 | // fallback to string | |
355 | msg.push(Ext.String.htmlEncode(txt)); | |
356 | } | |
357 | } | |
358 | return msg.join('<br>'); | |
359 | }, | |
360 | ||
661faeed | 361 | monStoreErrors: function(component, store, clearMaskBeforeLoad, errorCallback) { |
ecabd437 TL |
362 | if (clearMaskBeforeLoad) { |
363 | component.mon(store, 'beforeload', function(s, operation, eOpts) { | |
364 | Proxmox.Utils.setErrorMask(component, false); | |
365 | }); | |
366 | } else { | |
367 | component.mon(store, 'beforeload', function(s, operation, eOpts) { | |
368 | if (!component.loadCount) { | |
369 | component.loadCount = 0; // make sure it is nucomponent.ic | |
370 | Proxmox.Utils.setErrorMask(component, true); | |
371 | } | |
372 | }); | |
373 | } | |
374 | ||
375 | // only works with 'proxmox' proxy | |
376 | component.mon(store.proxy, 'afterload', function(proxy, request, success) { | |
377 | component.loadCount++; | |
378 | ||
379 | if (success) { | |
380 | Proxmox.Utils.setErrorMask(component, false); | |
381 | return; | |
382 | } | |
383 | ||
384 | let error = request._operation.getError(); | |
385 | let msg = Proxmox.Utils.getResponseErrorMessage(error); | |
661faeed SR |
386 | if (!errorCallback || !errorCallback(error, msg)) { |
387 | Proxmox.Utils.setErrorMask(component, msg); | |
388 | } | |
ecabd437 TL |
389 | }); |
390 | }, | |
391 | ||
392 | extractRequestError: function(result, verbose) { | |
393 | let msg = gettext('Successful'); | |
394 | ||
395 | if (!result.success) { | |
396 | msg = gettext("Unknown error"); | |
397 | if (result.message) { | |
398 | msg = result.message; | |
399 | if (result.status) { | |
400 | msg += ' (' + result.status + ')'; | |
401 | } | |
402 | } | |
403 | if (verbose && Ext.isObject(result.errors)) { | |
404 | msg += "<br>"; | |
405 | Ext.Object.each(result.errors, function(prop, desc) { | |
406 | msg += "<br><b>" + Ext.htmlEncode(prop) + "</b>: " + | |
407 | Ext.htmlEncode(desc); | |
408 | }); | |
409 | } | |
410 | } | |
411 | ||
412 | return msg; | |
413 | }, | |
414 | ||
415 | // Ext.Ajax.request | |
416 | API2Request: function(reqOpts) { | |
417 | let newopts = Ext.apply({ | |
418 | waitMsg: gettext('Please wait...'), | |
419 | }, reqOpts); | |
420 | ||
421 | if (!newopts.url.match(/^\/api2/)) { | |
422 | newopts.url = '/api2/extjs' + newopts.url; | |
423 | } | |
424 | delete newopts.callback; | |
425 | ||
426 | let createWrapper = function(successFn, callbackFn, failureFn) { | |
427 | Ext.apply(newopts, { | |
428 | success: function(response, options) { | |
429 | if (options.waitMsgTarget) { | |
430 | if (Proxmox.Utils.toolkit === 'touch') { | |
431 | options.waitMsgTarget.setMasked(false); | |
432 | } else { | |
433 | options.waitMsgTarget.setLoading(false); | |
434 | } | |
435 | } | |
436 | let result = Ext.decode(response.responseText); | |
437 | response.result = result; | |
438 | if (!result.success) { | |
439 | response.htmlStatus = Proxmox.Utils.extractRequestError(result, true); | |
440 | Ext.callback(callbackFn, options.scope, [options, false, response]); | |
441 | Ext.callback(failureFn, options.scope, [response, options]); | |
442 | return; | |
443 | } | |
444 | Ext.callback(callbackFn, options.scope, [options, true, response]); | |
445 | Ext.callback(successFn, options.scope, [response, options]); | |
446 | }, | |
447 | failure: function(response, options) { | |
448 | if (options.waitMsgTarget) { | |
449 | if (Proxmox.Utils.toolkit === 'touch') { | |
450 | options.waitMsgTarget.setMasked(false); | |
451 | } else { | |
452 | options.waitMsgTarget.setLoading(false); | |
453 | } | |
454 | } | |
455 | response.result = {}; | |
456 | try { | |
457 | response.result = Ext.decode(response.responseText); | |
458 | } catch (e) { | |
459 | // ignore | |
460 | } | |
461 | let msg = gettext('Connection error') + ' - server offline?'; | |
462 | if (response.aborted) { | |
463 | msg = gettext('Connection error') + ' - aborted.'; | |
464 | } else if (response.timedout) { | |
465 | msg = gettext('Connection error') + ' - Timeout.'; | |
466 | } else if (response.status && response.statusText) { | |
467 | msg = gettext('Connection error') + ' ' + response.status + ': ' + response.statusText; | |
468 | } | |
469 | response.htmlStatus = msg; | |
470 | Ext.callback(callbackFn, options.scope, [options, false, response]); | |
471 | Ext.callback(failureFn, options.scope, [response, options]); | |
472 | }, | |
473 | }); | |
474 | }; | |
475 | ||
476 | createWrapper(reqOpts.success, reqOpts.callback, reqOpts.failure); | |
477 | ||
478 | let target = newopts.waitMsgTarget; | |
479 | if (target) { | |
480 | if (Proxmox.Utils.toolkit === 'touch') { | |
481 | target.setMasked({ xtype: 'loadmask', message: newopts.waitMsg }); | |
482 | } else { | |
483 | // Note: ExtJS bug - this does not work when component is not rendered | |
484 | target.setLoading(newopts.waitMsg); | |
485 | } | |
486 | } | |
487 | Ext.Ajax.request(newopts); | |
488 | }, | |
489 | ||
106fe29e TL |
490 | // can be useful for catching displaying errors from the API, e.g.: |
491 | // Proxmox.Async.api2({ | |
492 | // ... | |
493 | // }).catch(Proxmox.Utils.alertResponseFailure); | |
494 | alertResponseFailure: (response) => { | |
495 | Ext.Msg.alert( | |
496 | gettext('Error'), | |
497 | response.htmlStatus || response.result.message, | |
498 | ); | |
499 | }, | |
500 | ||
ecabd437 | 501 | checked_command: function(orig_cmd) { |
a718654e TL |
502 | Proxmox.Utils.API2Request( |
503 | { | |
504 | url: '/nodes/localhost/subscription', | |
505 | method: 'GET', | |
506 | failure: function(response, opts) { | |
507 | Ext.Msg.alert(gettext('Error'), response.htmlStatus); | |
508 | }, | |
509 | success: function(response, opts) { | |
510 | let res = response.result; | |
511 | if (res === null || res === undefined || !res || res | |
57ba4cdc | 512 | .data.status.toLowerCase() !== 'active') { |
a718654e TL |
513 | Ext.Msg.show({ |
514 | title: gettext('No valid subscription'), | |
515 | icon: Ext.Msg.WARNING, | |
516 | message: Proxmox.Utils.getNoSubKeyHtml(res.data.url), | |
517 | buttons: Ext.Msg.OK, | |
518 | callback: function(btn) { | |
519 | if (btn !== 'ok') { | |
520 | return; | |
521 | } | |
522 | orig_cmd(); | |
523 | }, | |
524 | }); | |
525 | } else { | |
526 | orig_cmd(); | |
527 | } | |
528 | }, | |
ecabd437 | 529 | }, |
a718654e | 530 | ); |
ecabd437 TL |
531 | }, |
532 | ||
533 | assemble_field_data: function(values, data) { | |
534 | if (!Ext.isObject(data)) { | |
535 | return; | |
536 | } | |
537 | Ext.Object.each(data, function(name, val) { | |
538 | if (Object.prototype.hasOwnProperty.call(values, name)) { | |
539 | let bucket = values[name]; | |
540 | if (!Ext.isArray(bucket)) { | |
541 | bucket = values[name] = [bucket]; | |
542 | } | |
543 | if (Ext.isArray(val)) { | |
544 | values[name] = bucket.concat(val); | |
545 | } else { | |
546 | bucket.push(val); | |
547 | } | |
548 | } else { | |
549 | values[name] = val; | |
550 | } | |
551 | }); | |
552 | }, | |
553 | ||
fb4bb95e | 554 | updateColumnWidth: function(container, thresholdWidth) { |
ecabd437 TL |
555 | let mode = Ext.state.Manager.get('summarycolumns') || 'auto'; |
556 | let factor; | |
557 | if (mode !== 'auto') { | |
558 | factor = parseInt(mode, 10); | |
559 | if (Number.isNaN(factor)) { | |
560 | factor = 1; | |
561 | } | |
562 | } else { | |
fb4bb95e TL |
563 | thresholdWidth = (thresholdWidth || 1400) + 1; |
564 | factor = Math.ceil(container.getSize().width / thresholdWidth); | |
ecabd437 TL |
565 | } |
566 | ||
567 | if (container.oldFactor === factor) { | |
568 | return; | |
569 | } | |
570 | ||
017a6376 | 571 | let items = container.query('>'); // direct children |
ecabd437 TL |
572 | factor = Math.min(factor, items.length); |
573 | container.oldFactor = factor; | |
574 | ||
575 | items.forEach((item) => { | |
576 | item.columnWidth = 1 / factor; | |
577 | }); | |
578 | ||
579 | // we have to update the layout twice, since the first layout change | |
580 | // can trigger the scrollbar which reduces the amount of space left | |
581 | container.updateLayout(); | |
582 | container.updateLayout(); | |
583 | }, | |
584 | ||
8b7e349a TL |
585 | // NOTE: depreacated, use updateColumnWidth |
586 | updateColumns: container => Proxmox.Utils.updateColumnWidth(container), | |
587 | ||
ecabd437 TL |
588 | dialog_title: function(subject, create, isAdd) { |
589 | if (create) { | |
590 | if (isAdd) { | |
591 | return gettext('Add') + ': ' + subject; | |
592 | } else { | |
593 | return gettext('Create') + ': ' + subject; | |
594 | } | |
595 | } else { | |
596 | return gettext('Edit') + ': ' + subject; | |
597 | } | |
598 | }, | |
599 | ||
600 | network_iface_types: { | |
601 | eth: gettext("Network Device"), | |
602 | bridge: 'Linux Bridge', | |
603 | bond: 'Linux Bond', | |
604 | vlan: 'Linux VLAN', | |
605 | OVSBridge: 'OVS Bridge', | |
606 | OVSBond: 'OVS Bond', | |
607 | OVSPort: 'OVS Port', | |
608 | OVSIntPort: 'OVS IntPort', | |
609 | }, | |
610 | ||
611 | render_network_iface_type: function(value) { | |
612 | return Proxmox.Utils.network_iface_types[value] || | |
613 | Proxmox.Utils.unknownText; | |
614 | }, | |
615 | ||
fc0a18e6 | 616 | // NOTE: only add general, product agnostic, ones here! Else use override helper in product repos |
ecabd437 | 617 | task_desc_table: { |
3571d713 | 618 | aptupdate: ['', gettext('Update package database')], |
ecabd437 | 619 | diskinit: ['Disk', gettext('Initialize Disk with GPT')], |
ecabd437 | 620 | spiceshell: ['', gettext('Shell') + ' (Spice)'], |
3571d713 DC |
621 | srvreload: ['SRV', gettext('Reload')], |
622 | srvrestart: ['SRV', gettext('Restart')], | |
ecabd437 TL |
623 | srvstart: ['SRV', gettext('Start')], |
624 | srvstop: ['SRV', gettext('Stop')], | |
3571d713 DC |
625 | termproxy: ['', gettext('Console') + ' (xterm.js)'], |
626 | vncshell: ['', gettext('Shell')], | |
ecabd437 TL |
627 | }, |
628 | ||
629 | // to add or change existing for product specific ones | |
630 | override_task_descriptions: function(extra) { | |
631 | for (const [key, value] of Object.entries(extra)) { | |
632 | Proxmox.Utils.task_desc_table[key] = value; | |
633 | } | |
634 | }, | |
635 | ||
636 | format_task_description: function(type, id) { | |
637 | let farray = Proxmox.Utils.task_desc_table[type]; | |
638 | let text; | |
639 | if (!farray) { | |
640 | text = type; | |
641 | if (id) { | |
642 | type += ' ' + id; | |
643 | } | |
644 | return text; | |
645 | } else if (Ext.isFunction(farray)) { | |
646 | return farray(type, id); | |
647 | } | |
648 | let prefix = farray[0]; | |
649 | text = farray[1]; | |
650 | if (prefix && id !== undefined) { | |
651 | return prefix + ' ' + id + ' - ' + text; | |
652 | } | |
653 | return text; | |
654 | }, | |
655 | ||
b46ad78c TL |
656 | format_size: function(size, useSI) { |
657 | let units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']; | |
658 | let order = 0; | |
659 | const baseValue = useSI ? 1000 : 1024; | |
660 | while (size >= baseValue && order < units.length) { | |
661 | size = size / baseValue; | |
662 | order++; | |
ecabd437 TL |
663 | } |
664 | ||
b46ad78c TL |
665 | let unit = units[order], commaDigits = 2; |
666 | if (order === 0) { | |
667 | commaDigits = 0; | |
668 | } else if (!useSI) { | |
669 | unit += 'i'; | |
670 | } | |
671 | return `${size.toFixed(commaDigits)} ${unit}B`; | |
ecabd437 TL |
672 | }, |
673 | ||
1fad0e88 TL |
674 | SizeUnits: { |
675 | 'B': 1, | |
676 | ||
677 | 'KiB': 1024, | |
678 | 'MiB': 1024*1024, | |
679 | 'GiB': 1024*1024*1024, | |
680 | 'TiB': 1024*1024*1024*1024, | |
681 | 'PiB': 1024*1024*1024*1024*1024, | |
682 | ||
683 | 'KB': 1000, | |
684 | 'MB': 1000*1000, | |
685 | 'GB': 1000*1000*1000, | |
686 | 'TB': 1000*1000*1000*1000, | |
687 | 'PB': 1000*1000*1000*1000*1000, | |
688 | }, | |
689 | ||
851ebc36 TL |
690 | parse_size_unit: function(val) { |
691 | //let m = val.match(/([.\d])+\s?([KMGTP]?)(i?)B?\s*$/i); | |
692 | let m = val.match(/(\d+(?:\.\d+)?)\s?([KMGTP]?)(i?)B?\s*$/i); | |
693 | let size = parseFloat(m[1]); | |
694 | let scale = m[2].toUpperCase(); | |
695 | let binary = m[3].toLowerCase(); | |
696 | ||
697 | let unit = `${scale}${binary}B`; | |
698 | let factor = Proxmox.Utils.SizeUnits[unit]; | |
699 | ||
700 | return { size, factor, unit, binary }; // for convenience return all we got | |
701 | }, | |
702 | ||
703 | size_unit_to_bytes: function(val) { | |
704 | let { size, factor } = Proxmox.Utils.parse_size_unit(val); | |
705 | return size * factor; | |
706 | }, | |
707 | ||
708 | autoscale_size_unit: function(val) { | |
709 | let { size, factor, binary } = Proxmox.Utils.parse_size_unit(val); | |
710 | return Proxmox.Utils.format_size(size * factor, binary !== "i"); | |
711 | }, | |
712 | ||
713 | size_unit_ratios: function(a, b) { | |
714 | a = typeof a !== "undefined" ? a : 0; | |
715 | b = typeof b !== "undefined" ? b : Infinity; | |
716 | let aBytes = typeof a === "number" ? a : Proxmox.Utils.size_unit_to_bytes(a); | |
717 | let bBytes = typeof b === "number" ? b : Proxmox.Utils.size_unit_to_bytes(b); | |
718 | return aBytes / (bBytes || Infinity); // avoid division by zero | |
719 | }, | |
720 | ||
ecabd437 TL |
721 | render_upid: function(value, metaData, record) { |
722 | let task = record.data; | |
723 | let type = task.type || task.worker_type; | |
724 | let id = task.id || task.worker_id; | |
725 | ||
726 | return Proxmox.Utils.format_task_description(type, id); | |
727 | }, | |
728 | ||
729 | render_uptime: function(value) { | |
730 | let uptime = value; | |
731 | ||
732 | if (uptime === undefined) { | |
733 | return ''; | |
734 | } | |
735 | ||
736 | if (uptime <= 0) { | |
737 | return '-'; | |
738 | } | |
739 | ||
740 | return Proxmox.Utils.format_duration_long(uptime); | |
741 | }, | |
742 | ||
6221e40c | 743 | systemd_unescape: function(string_value) { |
6221e40c DM |
744 | const charcode_0 = '0'.charCodeAt(0); |
745 | const charcode_9 = '9'.charCodeAt(0); | |
746 | const charcode_A = 'A'.charCodeAt(0); | |
747 | const charcode_F = 'F'.charCodeAt(0); | |
748 | const charcode_a = 'a'.charCodeAt(0); | |
749 | const charcode_f = 'f'.charCodeAt(0); | |
750 | const charcode_x = 'x'.charCodeAt(0); | |
751 | const charcode_minus = '-'.charCodeAt(0); | |
752 | const charcode_slash = '/'.charCodeAt(0); | |
753 | const charcode_backslash = '\\'.charCodeAt(0); | |
754 | ||
755 | let parse_hex_digit = function(d) { | |
756 | if (d >= charcode_0 && d <= charcode_9) { | |
757 | return d - charcode_0; | |
758 | } | |
759 | if (d >= charcode_A && d <= charcode_F) { | |
760 | return d - charcode_A + 10; | |
761 | } | |
762 | if (d >= charcode_a && d <= charcode_f) { | |
763 | return d - charcode_a + 10; | |
764 | } | |
765 | throw "got invalid hex digit"; | |
766 | }; | |
767 | ||
768 | let value = new TextEncoder().encode(string_value); | |
769 | let result = new Uint8Array(value.length); | |
770 | ||
771 | let i = 0; | |
772 | let result_len = 0; | |
773 | ||
774 | while (i < value.length) { | |
775 | let c0 = value[i]; | |
776 | if (c0 === charcode_minus) { | |
777 | result.set([charcode_slash], result_len); | |
778 | result_len += 1; | |
779 | i += 1; | |
780 | continue; | |
781 | } | |
782 | if ((i + 4) < value.length) { | |
783 | let c1 = value[i+1]; | |
784 | if (c0 === charcode_backslash && c1 === charcode_x) { | |
785 | let h1 = parse_hex_digit(value[i+2]); | |
786 | let h0 = parse_hex_digit(value[i+3]); | |
787 | let ord = h1*16+h0; | |
788 | result.set([ord], result_len); | |
789 | result_len += 1; | |
790 | i += 4; | |
791 | continue; | |
792 | } | |
793 | } | |
794 | result.set([c0], result_len); | |
795 | result_len += 1; | |
796 | i += 1; | |
797 | } | |
798 | ||
799 | return new TextDecoder().decode(result.slice(0, result.len)); | |
800 | }, | |
801 | ||
ecabd437 TL |
802 | parse_task_upid: function(upid) { |
803 | let task = {}; | |
804 | ||
805 | let res = upid.match(/^UPID:([^\s:]+):([0-9A-Fa-f]{8}):([0-9A-Fa-f]{8,9}):(([0-9A-Fa-f]{8,16}):)?([0-9A-Fa-f]{8}):([^:\s]+):([^:\s]*):([^:\s]+):$/); | |
806 | if (!res) { | |
807 | throw "unable to parse upid '" + upid + "'"; | |
808 | } | |
809 | task.node = res[1]; | |
810 | task.pid = parseInt(res[2], 16); | |
811 | task.pstart = parseInt(res[3], 16); | |
812 | if (res[5] !== undefined) { | |
813 | task.task_id = parseInt(res[5], 16); | |
814 | } | |
815 | task.starttime = parseInt(res[6], 16); | |
816 | task.type = res[7]; | |
6221e40c | 817 | task.id = Proxmox.Utils.systemd_unescape(res[8]); |
ecabd437 TL |
818 | task.user = res[9]; |
819 | ||
820 | task.desc = Proxmox.Utils.format_task_description(task.type, task.id); | |
821 | ||
822 | return task; | |
823 | }, | |
824 | ||
b1d446d0 DC |
825 | parse_task_status: function(status) { |
826 | if (status === 'OK') { | |
827 | return 'ok'; | |
828 | } | |
829 | ||
830 | if (status === 'unknown') { | |
831 | return 'unknown'; | |
832 | } | |
833 | ||
834 | let match = status.match(/^WARNINGS: (.*)$/); | |
835 | if (match) { | |
836 | return 'warning'; | |
837 | } | |
838 | ||
839 | return 'error'; | |
840 | }, | |
841 | ||
9865b73e FE |
842 | format_task_status: function(status) { |
843 | let parsed = Proxmox.Utils.parse_task_status(status); | |
4294143f FE |
844 | switch (parsed) { |
845 | case 'unknown': return Proxmox.Utils.unknownText; | |
9865b73e | 846 | case 'error': return Proxmox.Utils.errorText + ': ' + status; |
9b4b243a | 847 | case 'warning': return status.replace('WARNINGS', Proxmox.Utils.warningsText); |
4294143f | 848 | case 'ok': // fall-through |
9865b73e | 849 | default: return status; |
4294143f FE |
850 | } |
851 | }, | |
852 | ||
ecabd437 TL |
853 | render_duration: function(value) { |
854 | if (value === undefined) { | |
855 | return '-'; | |
856 | } | |
857 | return Proxmox.Utils.format_duration_human(value); | |
858 | }, | |
859 | ||
860 | render_timestamp: function(value, metaData, record, rowIndex, colIndex, store) { | |
861 | let servertime = new Date(value * 1000); | |
862 | return Ext.Date.format(servertime, 'Y-m-d H:i:s'); | |
863 | }, | |
864 | ||
f29e6a66 DC |
865 | render_zfs_health: function(value) { |
866 | if (typeof value === 'undefined') { | |
867 | return ""; | |
868 | } | |
869 | var iconCls = 'question-circle'; | |
870 | switch (value) { | |
871 | case 'AVAIL': | |
872 | case 'ONLINE': | |
873 | iconCls = 'check-circle good'; | |
874 | break; | |
875 | case 'REMOVED': | |
876 | case 'DEGRADED': | |
877 | iconCls = 'exclamation-circle warning'; | |
878 | break; | |
879 | case 'UNAVAIL': | |
880 | case 'FAULTED': | |
881 | case 'OFFLINE': | |
882 | iconCls = 'times-circle critical'; | |
883 | break; | |
884 | default: //unknown | |
885 | } | |
886 | ||
887 | return '<i class="fa fa-' + iconCls + '"></i> ' + value; | |
888 | }, | |
889 | ||
ecabd437 TL |
890 | get_help_info: function(section) { |
891 | let helpMap; | |
892 | if (typeof proxmoxOnlineHelpInfo !== 'undefined') { | |
893 | helpMap = proxmoxOnlineHelpInfo; // eslint-disable-line no-undef | |
894 | } else if (typeof pveOnlineHelpInfo !== 'undefined') { | |
895 | // be backward compatible with older pve-doc-generators | |
896 | helpMap = pveOnlineHelpInfo; // eslint-disable-line no-undef | |
897 | } else { | |
898 | throw "no global OnlineHelpInfo map declared"; | |
899 | } | |
900 | ||
7f56fd0c TL |
901 | if (helpMap[section]) { |
902 | return helpMap[section]; | |
903 | } | |
904 | // try to normalize - and _ separators, to support asciidoc and sphinx | |
905 | // references at the same time. | |
63ec56e5 | 906 | let section_minus_normalized = section.replace(/_/g, '-'); |
7f56fd0c TL |
907 | if (helpMap[section_minus_normalized]) { |
908 | return helpMap[section_minus_normalized]; | |
909 | } | |
63ec56e5 | 910 | let section_underscore_normalized = section.replace(/-/g, '_'); |
7f56fd0c | 911 | return helpMap[section_underscore_normalized]; |
ecabd437 TL |
912 | }, |
913 | ||
914 | get_help_link: function(section) { | |
915 | let info = Proxmox.Utils.get_help_info(section); | |
916 | if (!info) { | |
917 | return undefined; | |
918 | } | |
919 | return window.location.origin + info.link; | |
920 | }, | |
921 | ||
922 | openXtermJsViewer: function(vmtype, vmid, nodename, vmname, cmd) { | |
923 | let url = Ext.Object.toQueryString({ | |
924 | console: vmtype, // kvm, lxc, upgrade or shell | |
925 | xtermjs: 1, | |
926 | vmid: vmid, | |
927 | vmname: vmname, | |
928 | node: nodename, | |
929 | cmd: cmd, | |
930 | ||
931 | }); | |
932 | let nw = window.open("?" + url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,resizable=yes,width=800,height=420'); | |
933 | if (nw) { | |
934 | nw.focus(); | |
935 | } | |
936 | }, | |
937 | ||
25680ef5 WB |
938 | render_optional_url: function(value) { |
939 | if (value && value.match(/^https?:\/\//) !== null) { | |
940 | return '<a target="_blank" href="' + value + '">' + value + '</a>'; | |
941 | } | |
942 | return value; | |
943 | }, | |
944 | ||
945 | render_san: function(value) { | |
946 | var names = []; | |
947 | if (Ext.isArray(value)) { | |
948 | value.forEach(function(val) { | |
949 | if (!Ext.isNumber(val)) { | |
950 | names.push(val); | |
951 | } | |
952 | }); | |
953 | return names.join('<br>'); | |
954 | } | |
955 | return value; | |
956 | }, | |
957 | ||
ce8289fc | 958 | render_usage: val => (val * 100).toFixed(2) + '%', |
ef3f1cfc DC |
959 | |
960 | render_cpu_usage: function(val, max) { | |
9e663a6a TL |
961 | return Ext.String.format( |
962 | `${gettext('{0}% of {1}')} ${gettext('CPU(s)')}`, | |
963 | (val*100).toFixed(2), | |
964 | max, | |
965 | ); | |
ef3f1cfc DC |
966 | }, |
967 | ||
b46ad78c | 968 | render_size_usage: function(val, max, useSI) { |
ef3f1cfc DC |
969 | if (max === 0) { |
970 | return gettext('N/A'); | |
971 | } | |
b46ad78c | 972 | let fmt = v => Proxmox.Utils.format_size(v, useSI); |
ce8289fc TL |
973 | let ratio = (val * 100 / max).toFixed(2); |
974 | return ratio + '% (' + Ext.String.format(gettext('{0} of {1}'), fmt(val), fmt(max)) + ')'; | |
ef3f1cfc DC |
975 | }, |
976 | ||
977 | render_cpu: function(value, metaData, record, rowIndex, colIndex, store) { | |
978 | if (!(record.data.uptime && Ext.isNumeric(value))) { | |
979 | return ''; | |
980 | } | |
981 | ||
9e663a6a | 982 | let maxcpu = record.data.maxcpu || 1; |
1334cdca | 983 | if (!Ext.isNumeric(maxcpu) || maxcpu < 1) { |
ef3f1cfc DC |
984 | return ''; |
985 | } | |
9e663a6a TL |
986 | let cpuText = maxcpu > 1 ? 'CPUs' : 'CPU'; |
987 | let ratio = (value * 100).toFixed(1); | |
988 | return `${ratio}% of ${maxcpu.toString()} ${cpuText}`; | |
ef3f1cfc DC |
989 | }, |
990 | ||
991 | render_size: function(value, metaData, record, rowIndex, colIndex, store) { | |
992 | if (!Ext.isNumeric(value)) { | |
993 | return ''; | |
994 | } | |
ef3f1cfc DC |
995 | return Proxmox.Utils.format_size(value); |
996 | }, | |
997 | ||
9e663a6a TL |
998 | render_cpu_model: function(cpu) { |
999 | let socketText = cpu.sockets > 1 ? gettext('Sockets') : gettext('Socket'); | |
1000 | return `${cpu.cpus} x ${cpu.model} (${cpu.sockets.toString()} ${socketText})`; | |
ef3f1cfc DC |
1001 | }, |
1002 | ||
1003 | /* this is different for nodes */ | |
1004 | render_node_cpu_usage: function(value, record) { | |
1005 | return Proxmox.Utils.render_cpu_usage(value, record.cpus); | |
1006 | }, | |
1007 | ||
1008 | render_node_size_usage: function(record) { | |
1009 | return Proxmox.Utils.render_size_usage(record.used, record.total); | |
1010 | }, | |
1011 | ||
25680ef5 WB |
1012 | loadTextFromFile: function(file, callback, maxBytes) { |
1013 | let maxSize = maxBytes || 8192; | |
1014 | if (file.size > maxSize) { | |
1015 | Ext.Msg.alert(gettext('Error'), gettext("Invalid file size: ") + file.size); | |
1016 | return; | |
1017 | } | |
1018 | let reader = new FileReader(); | |
1019 | reader.onload = evt => callback(evt.target.result); | |
1020 | reader.readAsText(file); | |
1021 | }, | |
1022 | ||
1023 | parsePropertyString: function(value, defaultKey) { | |
1024 | var res = {}, | |
1025 | error; | |
1026 | ||
1027 | if (typeof value !== 'string' || value === '') { | |
1028 | return res; | |
1029 | } | |
1030 | ||
1031 | Ext.Array.each(value.split(','), function(p) { | |
1032 | var kv = p.split('=', 2); | |
1033 | if (Ext.isDefined(kv[1])) { | |
1034 | res[kv[0]] = kv[1]; | |
1035 | } else if (Ext.isDefined(defaultKey)) { | |
1036 | if (Ext.isDefined(res[defaultKey])) { | |
1037 | error = 'defaultKey may be only defined once in propertyString'; | |
1038 | return false; // break | |
1039 | } | |
1040 | res[defaultKey] = kv[0]; | |
1041 | } else { | |
1042 | error = 'invalid propertyString, not a key=value pair and no defaultKey defined'; | |
1043 | return false; // break | |
1044 | } | |
1045 | return true; | |
1046 | }); | |
1047 | ||
1048 | if (error !== undefined) { | |
1049 | console.error(error); | |
1050 | return undefined; | |
1051 | } | |
1052 | ||
1053 | return res; | |
1054 | }, | |
1055 | ||
1056 | printPropertyString: function(data, defaultKey) { | |
1057 | var stringparts = [], | |
1058 | gotDefaultKeyVal = false, | |
1059 | defaultKeyVal; | |
1060 | ||
1061 | Ext.Object.each(data, function(key, value) { | |
1062 | if (defaultKey !== undefined && key === defaultKey) { | |
1063 | gotDefaultKeyVal = true; | |
1064 | defaultKeyVal = value; | |
1065 | } else if (Ext.isArray(value)) { | |
1066 | stringparts.push(key + '=' + value.join(';')); | |
1067 | } else if (value !== '') { | |
1068 | stringparts.push(key + '=' + value); | |
1069 | } | |
1070 | }); | |
1071 | ||
1072 | stringparts = stringparts.sort(); | |
1073 | if (gotDefaultKeyVal) { | |
1074 | stringparts.unshift(defaultKeyVal); | |
1075 | } | |
1076 | ||
1077 | return stringparts.join(','); | |
1078 | }, | |
1079 | ||
1080 | acmedomain_count: 5, | |
1081 | ||
1082 | parseACMEPluginData: function(data) { | |
1083 | let res = {}; | |
1084 | let extradata = []; | |
1085 | data.split('\n').forEach((line) => { | |
1086 | // capture everything after the first = as value | |
1087 | let [key, value] = line.split('='); | |
1088 | if (value !== undefined) { | |
1089 | res[key] = value; | |
1090 | } else { | |
1091 | extradata.push(line); | |
1092 | } | |
1093 | }); | |
1094 | return [res, extradata]; | |
1095 | }, | |
1096 | ||
1097 | delete_if_default: function(values, fieldname, default_val, create) { | |
1098 | if (values[fieldname] === '' || values[fieldname] === default_val) { | |
1099 | if (!create) { | |
1100 | if (values.delete) { | |
1101 | if (Ext.isArray(values.delete)) { | |
1102 | values.delete.push(fieldname); | |
1103 | } else { | |
1104 | values.delete += ',' + fieldname; | |
1105 | } | |
1106 | } else { | |
1107 | values.delete = fieldname; | |
1108 | } | |
1109 | } | |
1110 | ||
1111 | delete values[fieldname]; | |
1112 | } | |
1113 | }, | |
1114 | ||
1115 | printACME: function(value) { | |
1116 | if (Ext.isArray(value.domains)) { | |
1117 | value.domains = value.domains.join(';'); | |
1118 | } | |
1119 | return Proxmox.Utils.printPropertyString(value); | |
1120 | }, | |
1121 | ||
1122 | parseACME: function(value) { | |
1123 | if (!value) { | |
1124 | return {}; | |
1125 | } | |
1126 | ||
1127 | var res = {}; | |
1128 | var error; | |
1129 | ||
1130 | Ext.Array.each(value.split(','), function(p) { | |
1131 | var kv = p.split('=', 2); | |
1132 | if (Ext.isDefined(kv[1])) { | |
1133 | res[kv[0]] = kv[1]; | |
1134 | } else { | |
1135 | error = 'Failed to parse key-value pair: '+p; | |
1136 | return false; | |
1137 | } | |
1138 | return true; | |
1139 | }); | |
1140 | ||
1141 | if (error !== undefined) { | |
1142 | console.error(error); | |
1143 | return undefined; | |
1144 | } | |
1145 | ||
1146 | if (res.domains !== undefined) { | |
1147 | res.domains = res.domains.split(/;/); | |
1148 | } | |
1149 | ||
1150 | return res; | |
1151 | }, | |
1152 | ||
1153 | add_domain_to_acme: function(acme, domain) { | |
1154 | if (acme.domains === undefined) { | |
1155 | acme.domains = [domain]; | |
1156 | } else { | |
1157 | acme.domains.push(domain); | |
1158 | acme.domains = acme.domains.filter((value, index, self) => self.indexOf(value) === index); | |
1159 | } | |
1160 | return acme; | |
1161 | }, | |
1162 | ||
1163 | remove_domain_from_acme: function(acme, domain) { | |
1164 | if (acme.domains !== undefined) { | |
1165 | acme.domains = acme.domains.filter( | |
1166 | (value, index, self) => self.indexOf(value) === index && value !== domain, | |
1167 | ); | |
1168 | } | |
1169 | return acme; | |
1170 | }, | |
d365540e | 1171 | |
fbbe68fd DC |
1172 | get_health_icon: function(state, circle) { |
1173 | if (circle === undefined) { | |
1174 | circle = false; | |
1175 | } | |
1176 | ||
1177 | if (state === undefined) { | |
1178 | state = 'uknown'; | |
1179 | } | |
1180 | ||
1181 | var icon = 'faded fa-question'; | |
1182 | switch (state) { | |
1183 | case 'good': | |
1184 | icon = 'good fa-check'; | |
1185 | break; | |
1186 | case 'upgrade': | |
1187 | icon = 'warning fa-upload'; | |
1188 | break; | |
1189 | case 'old': | |
1190 | icon = 'warning fa-refresh'; | |
1191 | break; | |
1192 | case 'warning': | |
1193 | icon = 'warning fa-exclamation'; | |
1194 | break; | |
1195 | case 'critical': | |
1196 | icon = 'critical fa-times'; | |
1197 | break; | |
1198 | default: break; | |
1199 | } | |
1200 | ||
1201 | if (circle) { | |
1202 | icon += '-circle'; | |
1203 | } | |
1204 | ||
1205 | return icon; | |
1206 | }, | |
40296471 | 1207 | |
7c65b8bf FE |
1208 | formatNodeRepoStatus: function(status, product) { |
1209 | let fmt = (txt, cls) => `<i class="fa fa-fw fa-lg fa-${cls}"></i>${txt}`; | |
1210 | ||
1211 | let getUpdates = Ext.String.format(gettext('{0} updates'), product); | |
1212 | let noRepo = Ext.String.format(gettext('No {0} repository enabled!'), product); | |
1213 | ||
1214 | if (status === 'ok') { | |
1215 | return fmt(getUpdates, 'check-circle good') + ' ' + | |
1216 | fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good'); | |
1217 | } else if (status === 'no-sub') { | |
1218 | return fmt(gettext('Production-ready Enterprise repository enabled'), 'check-circle good') + ' ' + | |
1219 | fmt(gettext('Enterprise repository needs valid subscription'), 'exclamation-circle warning'); | |
1220 | } else if (status === 'non-production') { | |
1221 | return fmt(getUpdates, 'check-circle good') + ' ' + | |
1222 | fmt(gettext('Non production-ready repository enabled!'), 'exclamation-circle warning'); | |
1223 | } else if (status === 'no-repo') { | |
1224 | return fmt(noRepo, 'exclamation-circle critical'); | |
1225 | } | |
1226 | ||
1227 | return Proxmox.Utils.unknownText; | |
1228 | }, | |
c7f2b15a WB |
1229 | |
1230 | render_u2f_error: function(error) { | |
1231 | var ErrorNames = { | |
1232 | '1': gettext('Other Error'), | |
1233 | '2': gettext('Bad Request'), | |
1234 | '3': gettext('Configuration Unsupported'), | |
1235 | '4': gettext('Device Ineligible'), | |
1236 | '5': gettext('Timeout'), | |
1237 | }; | |
1238 | return "U2F Error: " + ErrorNames[error] || Proxmox.Utils.unknownText; | |
1239 | }, | |
1240 | ||
1241 | // Convert an ArrayBuffer to a base64url encoded string. | |
1242 | // A `null` value will be preserved for convenience. | |
1243 | bytes_to_base64url: function(bytes) { | |
1244 | if (bytes === null) { | |
1245 | return null; | |
1246 | } | |
1247 | ||
1248 | return btoa(Array | |
1249 | .from(new Uint8Array(bytes)) | |
1250 | .map(val => String.fromCharCode(val)) | |
1251 | .join(''), | |
1252 | ) | |
1253 | .replace(/\+/g, '-') | |
1254 | .replace(/\//g, '_') | |
1255 | .replace(/[=]/g, ''); | |
1256 | }, | |
1257 | ||
1258 | // Convert an a base64url string to an ArrayBuffer. | |
1259 | // A `null` value will be preserved for convenience. | |
1260 | base64url_to_bytes: function(b64u) { | |
1261 | if (b64u === null) { | |
1262 | return null; | |
1263 | } | |
1264 | ||
1265 | return new Uint8Array( | |
1266 | atob(b64u | |
1267 | .replace(/-/g, '+') | |
1268 | .replace(/_/g, '/'), | |
1269 | ) | |
1270 | .split('') | |
1271 | .map(val => val.charCodeAt(0)), | |
1272 | ); | |
1273 | }, | |
ecabd437 TL |
1274 | }, |
1275 | ||
1276 | singleton: true, | |
1277 | constructor: function() { | |
1278 | let me = this; | |
1279 | Ext.apply(me, me.utilities); | |
1280 | ||
1281 | let IPV4_OCTET = "(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])"; | |
1282 | let IPV4_REGEXP = "(?:(?:" + IPV4_OCTET + "\\.){3}" + IPV4_OCTET + ")"; | |
1283 | let IPV6_H16 = "(?:[0-9a-fA-F]{1,4})"; | |
1284 | let IPV6_LS32 = "(?:(?:" + IPV6_H16 + ":" + IPV6_H16 + ")|" + IPV4_REGEXP + ")"; | |
1285 | let IPV4_CIDR_MASK = "([0-9]{1,2})"; | |
1286 | let IPV6_CIDR_MASK = "([0-9]{1,3})"; | |
1287 | ||
1288 | ||
1289 | me.IP4_match = new RegExp("^(?:" + IPV4_REGEXP + ")$"); | |
1290 | me.IP4_cidr_match = new RegExp("^(?:" + IPV4_REGEXP + ")/" + IPV4_CIDR_MASK + "$"); | |
1291 | ||
1292 | /* eslint-disable no-useless-concat,no-multi-spaces */ | |
1293 | let IPV6_REGEXP = "(?:" + | |
1294 | "(?:(?:" + "(?:" + IPV6_H16 + ":){6})" + IPV6_LS32 + ")|" + | |
1295 | "(?:(?:" + "::" + "(?:" + IPV6_H16 + ":){5})" + IPV6_LS32 + ")|" + | |
1296 | "(?:(?:(?:" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){4})" + IPV6_LS32 + ")|" + | |
1297 | "(?:(?:(?:(?:" + IPV6_H16 + ":){0,1}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){3})" + IPV6_LS32 + ")|" + | |
1298 | "(?:(?:(?:(?:" + IPV6_H16 + ":){0,2}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){2})" + IPV6_LS32 + ")|" + | |
1299 | "(?:(?:(?:(?:" + IPV6_H16 + ":){0,3}" + IPV6_H16 + ")?::" + "(?:" + IPV6_H16 + ":){1})" + IPV6_LS32 + ")|" + | |
1300 | "(?:(?:(?:(?:" + IPV6_H16 + ":){0,4}" + IPV6_H16 + ")?::" + ")" + IPV6_LS32 + ")|" + | |
1301 | "(?:(?:(?:(?:" + IPV6_H16 + ":){0,5}" + IPV6_H16 + ")?::" + ")" + IPV6_H16 + ")|" + | |
1302 | "(?:(?:(?:(?:" + IPV6_H16 + ":){0,7}" + IPV6_H16 + ")?::" + ")" + ")" + | |
1303 | ")"; | |
1304 | /* eslint-enable no-useless-concat,no-multi-spaces */ | |
1305 | ||
1306 | me.IP6_match = new RegExp("^(?:" + IPV6_REGEXP + ")$"); | |
1307 | me.IP6_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + ")/" + IPV6_CIDR_MASK + "$"); | |
1308 | me.IP6_bracket_match = new RegExp("^\\[(" + IPV6_REGEXP + ")\\]"); | |
1309 | ||
1310 | me.IP64_match = new RegExp("^(?:" + IPV6_REGEXP + "|" + IPV4_REGEXP + ")$"); | |
1311 | me.IP64_cidr_match = new RegExp("^(?:" + IPV6_REGEXP + "/" + IPV6_CIDR_MASK + ")|(?:" + IPV4_REGEXP + "/" + IPV4_CIDR_MASK + ")$"); | |
1312 | ||
a1d40d37 | 1313 | let DnsName_REGEXP = "(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?)\\.)*(?:[A-Za-z0-9](?:[A-Za-z0-9\\-]*[A-Za-z0-9])?))"; |
ecabd437 | 1314 | me.DnsName_match = new RegExp("^" + DnsName_REGEXP + "$"); |
66c5ceb8 | 1315 | me.DnsName_or_Wildcard_match = new RegExp("^(?:\\*\\.)?" + DnsName_REGEXP + "$"); |
ecabd437 | 1316 | |
a1d40d37 DC |
1317 | me.HostPort_match = new RegExp("^(" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")(?::(\\d+))?$"); |
1318 | me.HostPortBrackets_match = new RegExp("^\\[(" + IPV6_REGEXP + "|" + IPV4_REGEXP + "|" + DnsName_REGEXP + ")\\](?::(\\d+))?$"); | |
1319 | me.IP6_dotnotation_match = new RegExp("^(" + IPV6_REGEXP + ")(?:\\.(\\d+))?$"); | |
7bff067a DJ |
1320 | me.Vlan_match = /^vlan(\d+)/; |
1321 | me.VlanInterface_match = /(\w+)\.(\d+)/; | |
ecabd437 TL |
1322 | }, |
1323 | }); | |
c2c12542 TL |
1324 | |
1325 | Ext.define('Proxmox.Async', { | |
1326 | singleton: true, | |
1327 | ||
106fe29e | 1328 | // Returns a Promise resolving to the result of an `API2Request` or rejecting to the error |
017a6376 | 1329 | // response on failure |
c2c12542 TL |
1330 | api2: function(reqOpts) { |
1331 | return new Promise((resolve, reject) => { | |
1332 | delete reqOpts.callback; // not allowed in this api | |
1333 | reqOpts.success = response => resolve(response); | |
106fe29e | 1334 | reqOpts.failure = response => reject(response); |
c2c12542 TL |
1335 | Proxmox.Utils.API2Request(reqOpts); |
1336 | }); | |
1337 | }, | |
1338 | ||
1339 | // Delay for a number of milliseconds. | |
1340 | sleep: function(millis) { | |
1341 | return new Promise((resolve, _reject) => setTimeout(resolve, millis)); | |
1342 | }, | |
1343 | }); |