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