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