luci-base: luci.js: add LuCI.session.getToken()
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / luci.js
1 /**
2 * @class LuCI
3 * @classdesc
4 *
5 * This is the LuCI base class. It is automatically instantiated and
6 * accessible using the global `L` variable.
7 *
8 * @param {Object} env
9 * The environment settings to use for the LuCI runtime.
10 */
11
12 (function(window, document, undefined) {
13 'use strict';
14
15 var env = {};
16
17 /* Object.assign polyfill for IE */
18 if (typeof Object.assign !== 'function') {
19 Object.defineProperty(Object, 'assign', {
20 value: function assign(target, varArgs) {
21 if (target == null)
22 throw new TypeError('Cannot convert undefined or null to object');
23
24 var to = Object(target);
25
26 for (var index = 1; index < arguments.length; index++)
27 if (arguments[index] != null)
28 for (var nextKey in arguments[index])
29 if (Object.prototype.hasOwnProperty.call(arguments[index], nextKey))
30 to[nextKey] = arguments[index][nextKey];
31
32 return to;
33 },
34 writable: true,
35 configurable: true
36 });
37 }
38
39 /* Promise.finally polyfill */
40 if (typeof Promise.prototype.finally !== 'function') {
41 Promise.prototype.finally = function(fn) {
42 var onFinally = function(cb) {
43 return Promise.resolve(fn.call(this)).then(cb);
44 };
45
46 return this.then(
47 function(result) { return onFinally.call(this, function() { return result }) },
48 function(reason) { return onFinally.call(this, function() { return Promise.reject(reason) }) }
49 );
50 };
51 }
52
53 /*
54 * Class declaration and inheritance helper
55 */
56
57 var toCamelCase = function(s) {
58 return s.replace(/(?:^|[\. -])(.)/g, function(m0, m1) { return m1.toUpperCase() });
59 };
60
61 /**
62 * @class baseclass
63 * @hideconstructor
64 * @memberof LuCI
65 * @classdesc
66 *
67 * `LuCI.baseclass` is the abstract base class all LuCI classes inherit from.
68 *
69 * It provides simple means to create subclasses of given classes and
70 * implements prototypal inheritance.
71 */
72 var superContext = {}, classIndex = 0, Class = Object.assign(function() {}, {
73 /**
74 * Extends this base class with the properties described in
75 * `properties` and returns a new subclassed Class instance
76 *
77 * @memberof LuCI.baseclass
78 *
79 * @param {Object<string, *>} properties
80 * An object describing the properties to add to the new
81 * subclass.
82 *
83 * @returns {LuCI.baseclass}
84 * Returns a new LuCI.baseclass sublassed from this class, extended
85 * by the given properties and with its prototype set to this base
86 * class to enable inheritance. The resulting value represents a
87 * class constructor and can be instantiated with `new`.
88 */
89 extend: function(properties) {
90 var props = {
91 __id__: { value: classIndex },
92 __base__: { value: this.prototype },
93 __name__: { value: properties.__name__ || 'anonymous' + classIndex++ }
94 };
95
96 var ClassConstructor = function() {
97 if (!(this instanceof ClassConstructor))
98 throw new TypeError('Constructor must not be called without "new"');
99
100 if (Object.getPrototypeOf(this).hasOwnProperty('__init__')) {
101 if (typeof(this.__init__) != 'function')
102 throw new TypeError('Class __init__ member is not a function');
103
104 this.__init__.apply(this, arguments)
105 }
106 else {
107 this.super('__init__', arguments);
108 }
109 };
110
111 for (var key in properties)
112 if (!props[key] && properties.hasOwnProperty(key))
113 props[key] = { value: properties[key], writable: true };
114
115 ClassConstructor.prototype = Object.create(this.prototype, props);
116 ClassConstructor.prototype.constructor = ClassConstructor;
117 Object.assign(ClassConstructor, this);
118 ClassConstructor.displayName = toCamelCase(props.__name__.value + 'Class');
119
120 return ClassConstructor;
121 },
122
123 /**
124 * Extends this base class with the properties described in
125 * `properties`, instantiates the resulting subclass using
126 * the additional optional arguments passed to this function
127 * and returns the resulting subclassed Class instance.
128 *
129 * This function serves as a convenience shortcut for
130 * {@link LuCI.baseclass.extend Class.extend()} and subsequent
131 * `new`.
132 *
133 * @memberof LuCI.baseclass
134 *
135 * @param {Object<string, *>} properties
136 * An object describing the properties to add to the new
137 * subclass.
138 *
139 * @param {...*} [new_args]
140 * Specifies arguments to be passed to the subclass constructor
141 * as-is in order to instantiate the new subclass.
142 *
143 * @returns {LuCI.baseclass}
144 * Returns a new LuCI.baseclass instance extended by the given
145 * properties with its prototype set to this base class to
146 * enable inheritance.
147 */
148 singleton: function(properties /*, ... */) {
149 return Class.extend(properties)
150 .instantiate(Class.prototype.varargs(arguments, 1));
151 },
152
153 /**
154 * Calls the class constructor using `new` with the given argument
155 * array being passed as variadic parameters to the constructor.
156 *
157 * @memberof LuCI.baseclass
158 *
159 * @param {Array<*>} params
160 * An array of arbitrary values which will be passed as arguments
161 * to the constructor function.
162 *
163 * @param {...*} [new_args]
164 * Specifies arguments to be passed to the subclass constructor
165 * as-is in order to instantiate the new subclass.
166 *
167 * @returns {LuCI.baseclass}
168 * Returns a new LuCI.baseclass instance extended by the given
169 * properties with its prototype set to this base class to
170 * enable inheritance.
171 */
172 instantiate: function(args) {
173 return new (Function.prototype.bind.apply(this,
174 Class.prototype.varargs(args, 0, null)))();
175 },
176
177 /* unused */
178 call: function(self, method) {
179 if (typeof(this.prototype[method]) != 'function')
180 throw new ReferenceError(method + ' is not defined in class');
181
182 return this.prototype[method].apply(self, self.varargs(arguments, 1));
183 },
184
185 /**
186 * Checks whether the given class value is a subclass of this class.
187 *
188 * @memberof LuCI.baseclass
189 *
190 * @param {LuCI.baseclass} classValue
191 * The class object to test.
192 *
193 * @returns {boolean}
194 * Returns `true` when the given `classValue` is a subclass of this
195 * class or `false` if the given value is not a valid class or not
196 * a subclass of this class'.
197 */
198 isSubclass: function(classValue) {
199 return (classValue != null &&
200 typeof(classValue) == 'function' &&
201 classValue.prototype instanceof this);
202 },
203
204 prototype: {
205 /**
206 * Extract all values from the given argument array beginning from
207 * `offset` and prepend any further given optional parameters to
208 * the beginning of the resulting array copy.
209 *
210 * @memberof LuCI.baseclass
211 * @instance
212 *
213 * @param {Array<*>} args
214 * The array to extract the values from.
215 *
216 * @param {number} offset
217 * The offset from which to extract the values. An offset of `0`
218 * would copy all values till the end.
219 *
220 * @param {...*} [extra_args]
221 * Extra arguments to add to prepend to the resultung array.
222 *
223 * @returns {Array<*>}
224 * Returns a new array consisting of the optional extra arguments
225 * and the values extracted from the `args` array beginning with
226 * `offset`.
227 */
228 varargs: function(args, offset /*, ... */) {
229 return Array.prototype.slice.call(arguments, 2)
230 .concat(Array.prototype.slice.call(args, offset));
231 },
232
233 /**
234 * Walks up the parent class chain and looks for a class member
235 * called `key` in any of the parent classes this class inherits
236 * from. Returns the member value of the superclass or calls the
237 * member as function and returns its return value when the
238 * optional `callArgs` array is given.
239 *
240 * This function has two signatures and is sensitive to the
241 * amount of arguments passed to it:
242 * - `super('key')` -
243 * Returns the value of `key` when found within one of the
244 * parent classes.
245 * - `super('key', ['arg1', 'arg2'])` -
246 * Calls the `key()` method with parameters `arg1` and `arg2`
247 * when found within one of the parent classes.
248 *
249 * @memberof LuCI.baseclass
250 * @instance
251 *
252 * @param {string} key
253 * The name of the superclass member to retrieve.
254 *
255 * @param {Array<*>} [callArgs]
256 * An optional array of function call parameters to use. When
257 * this parameter is specified, the found member value is called
258 * as function using the values of this array as arguments.
259 *
260 * @throws {ReferenceError}
261 * Throws a `ReferenceError` when `callArgs` are specified and
262 * the found member named by `key` is not a function value.
263 *
264 * @returns {*|null}
265 * Returns the value of the found member or the return value of
266 * the call to the found method. Returns `null` when no member
267 * was found in the parent class chain or when the call to the
268 * superclass method returned `null`.
269 */
270 super: function(key, callArgs) {
271 if (key == null)
272 return null;
273
274 var slotIdx = this.__id__ + '.' + key,
275 symStack = superContext[slotIdx],
276 protoCtx = null;
277
278 for (protoCtx = Object.getPrototypeOf(symStack ? symStack[0] : Object.getPrototypeOf(this));
279 protoCtx != null && !protoCtx.hasOwnProperty(key);
280 protoCtx = Object.getPrototypeOf(protoCtx)) {}
281
282 if (protoCtx == null)
283 return null;
284
285 var res = protoCtx[key];
286
287 if (arguments.length > 1) {
288 if (typeof(res) != 'function')
289 throw new ReferenceError(key + ' is not a function in base class');
290
291 if (typeof(callArgs) != 'object')
292 callArgs = this.varargs(arguments, 1);
293
294 if (symStack)
295 symStack.unshift(protoCtx);
296 else
297 superContext[slotIdx] = [ protoCtx ];
298
299 res = res.apply(this, callArgs);
300
301 if (symStack && symStack.length > 1)
302 symStack.shift(protoCtx);
303 else
304 delete superContext[slotIdx];
305 }
306
307 return res;
308 },
309
310 /**
311 * Returns a string representation of this class.
312 *
313 * @returns {string}
314 * Returns a string representation of this class containing the
315 * constructor functions `displayName` and describing the class
316 * members and their respective types.
317 */
318 toString: function() {
319 var s = '[' + this.constructor.displayName + ']', f = true;
320 for (var k in this) {
321 if (this.hasOwnProperty(k)) {
322 s += (f ? ' {\n' : '') + ' ' + k + ': ' + typeof(this[k]) + '\n';
323 f = false;
324 }
325 }
326 return s + (f ? '' : '}');
327 }
328 }
329 });
330
331
332 /**
333 * @class headers
334 * @memberof LuCI
335 * @hideconstructor
336 * @classdesc
337 *
338 * The `Headers` class is an internal utility class exposed in HTTP
339 * response objects using the `response.headers` property.
340 */
341 var Headers = Class.extend(/** @lends LuCI.headers.prototype */ {
342 __name__: 'LuCI.headers',
343 __init__: function(xhr) {
344 var hdrs = this.headers = {};
345 xhr.getAllResponseHeaders().split(/\r\n/).forEach(function(line) {
346 var m = /^([^:]+):(.*)$/.exec(line);
347 if (m != null)
348 hdrs[m[1].trim().toLowerCase()] = m[2].trim();
349 });
350 },
351
352 /**
353 * Checks whether the given header name is present.
354 * Note: Header-Names are case-insensitive.
355 *
356 * @instance
357 * @memberof LuCI.headers
358 * @param {string} name
359 * The header name to check
360 *
361 * @returns {boolean}
362 * Returns `true` if the header name is present, `false` otherwise
363 */
364 has: function(name) {
365 return this.headers.hasOwnProperty(String(name).toLowerCase());
366 },
367
368 /**
369 * Returns the value of the given header name.
370 * Note: Header-Names are case-insensitive.
371 *
372 * @instance
373 * @memberof LuCI.headers
374 * @param {string} name
375 * The header name to read
376 *
377 * @returns {string|null}
378 * The value of the given header name or `null` if the header isn't present.
379 */
380 get: function(name) {
381 var key = String(name).toLowerCase();
382 return this.headers.hasOwnProperty(key) ? this.headers[key] : null;
383 }
384 });
385
386 /**
387 * @class response
388 * @memberof LuCI
389 * @hideconstructor
390 * @classdesc
391 *
392 * The `Response` class is an internal utility class representing HTTP responses.
393 */
394 var Response = Class.extend({
395 __name__: 'LuCI.response',
396 __init__: function(xhr, url, duration, headers, content) {
397 /**
398 * Describes whether the response is successful (status codes `200..299`) or not
399 * @instance
400 * @memberof LuCI.response
401 * @name ok
402 * @type {boolean}
403 */
404 this.ok = (xhr.status >= 200 && xhr.status <= 299);
405
406 /**
407 * The numeric HTTP status code of the response
408 * @instance
409 * @memberof LuCI.response
410 * @name status
411 * @type {number}
412 */
413 this.status = xhr.status;
414
415 /**
416 * The HTTP status description message of the response
417 * @instance
418 * @memberof LuCI.response
419 * @name statusText
420 * @type {string}
421 */
422 this.statusText = xhr.statusText;
423
424 /**
425 * The HTTP headers of the response
426 * @instance
427 * @memberof LuCI.response
428 * @name headers
429 * @type {LuCI.headers}
430 */
431 this.headers = (headers != null) ? headers : new Headers(xhr);
432
433 /**
434 * The total duration of the HTTP request in milliseconds
435 * @instance
436 * @memberof LuCI.response
437 * @name duration
438 * @type {number}
439 */
440 this.duration = duration;
441
442 /**
443 * The final URL of the request, i.e. after following redirects.
444 * @instance
445 * @memberof LuCI.response
446 * @name url
447 * @type {string}
448 */
449 this.url = url;
450
451 /* privates */
452 this.xhr = xhr;
453
454 if (content instanceof Blob) {
455 this.responseBlob = content;
456 this.responseJSON = null;
457 this.responseText = null;
458 }
459 else if (content != null && typeof(content) == 'object') {
460 this.responseBlob = null;
461 this.responseJSON = content;
462 this.responseText = null;
463 }
464 else if (content != null) {
465 this.responseBlob = null;
466 this.responseJSON = null;
467 this.responseText = String(content);
468 }
469 else {
470 this.responseJSON = null;
471
472 if (xhr.responseType == 'blob') {
473 this.responseBlob = xhr.response;
474 this.responseText = null;
475 }
476 else {
477 this.responseBlob = null;
478 this.responseText = xhr.responseText;
479 }
480 }
481 },
482
483 /**
484 * Clones the given response object, optionally overriding the content
485 * of the cloned instance.
486 *
487 * @instance
488 * @memberof LuCI.response
489 * @param {*} [content]
490 * Override the content of the cloned response. Object values will be
491 * treated as JSON response data, all other types will be converted
492 * using `String()` and treated as response text.
493 *
494 * @returns {LuCI.response}
495 * The cloned `Response` instance.
496 */
497 clone: function(content) {
498 var copy = new Response(this.xhr, this.url, this.duration, this.headers, content);
499
500 copy.ok = this.ok;
501 copy.status = this.status;
502 copy.statusText = this.statusText;
503
504 return copy;
505 },
506
507 /**
508 * Access the response content as JSON data.
509 *
510 * @instance
511 * @memberof LuCI.response
512 * @throws {SyntaxError}
513 * Throws `SyntaxError` if the content isn't valid JSON.
514 *
515 * @returns {*}
516 * The parsed JSON data.
517 */
518 json: function() {
519 if (this.responseJSON == null)
520 this.responseJSON = JSON.parse(this.responseText);
521
522 return this.responseJSON;
523 },
524
525 /**
526 * Access the response content as string.
527 *
528 * @instance
529 * @memberof LuCI.response
530 * @returns {string}
531 * The response content.
532 */
533 text: function() {
534 if (this.responseText == null && this.responseJSON != null)
535 this.responseText = JSON.stringify(this.responseJSON);
536
537 return this.responseText;
538 },
539
540 /**
541 * Access the response content as blob.
542 *
543 * @instance
544 * @memberof LuCI.response
545 * @returns {Blob}
546 * The response content as blob.
547 */
548 blob: function() {
549 return this.responseBlob;
550 }
551 });
552
553
554 var requestQueue = [];
555
556 function isQueueableRequest(opt) {
557 if (!classes.rpc)
558 return false;
559
560 if (opt.method != 'POST' || typeof(opt.content) != 'object')
561 return false;
562
563 if (opt.nobatch === true)
564 return false;
565
566 var rpcBaseURL = Request.expandURL(classes.rpc.getBaseURL());
567
568 return (rpcBaseURL != null && opt.url.indexOf(rpcBaseURL) == 0);
569 }
570
571 function flushRequestQueue() {
572 if (!requestQueue.length)
573 return;
574
575 var reqopt = Object.assign({}, requestQueue[0][0], { content: [], nobatch: true }),
576 batch = [];
577
578 for (var i = 0; i < requestQueue.length; i++) {
579 batch[i] = requestQueue[i];
580 reqopt.content[i] = batch[i][0].content;
581 }
582
583 requestQueue.length = 0;
584
585 Request.request(rpcBaseURL, reqopt).then(function(reply) {
586 var json = null, req = null;
587
588 try { json = reply.json() }
589 catch(e) { }
590
591 while ((req = batch.shift()) != null)
592 if (Array.isArray(json) && json.length)
593 req[2].call(reqopt, reply.clone(json.shift()));
594 else
595 req[1].call(reqopt, new Error('No related RPC reply'));
596 }).catch(function(error) {
597 var req = null;
598
599 while ((req = batch.shift()) != null)
600 req[1].call(reqopt, error);
601 });
602 }
603
604 /**
605 * @class request
606 * @memberof LuCI
607 * @hideconstructor
608 * @classdesc
609 *
610 * The `Request` class allows initiating HTTP requests and provides utilities
611 * for dealing with responses.
612 */
613 var Request = Class.singleton(/** @lends LuCI.request.prototype */ {
614 __name__: 'LuCI.request',
615
616 interceptors: [],
617
618 /**
619 * Turn the given relative URL into an absolute URL if necessary.
620 *
621 * @instance
622 * @memberof LuCI.request
623 * @param {string} url
624 * The URL to convert.
625 *
626 * @returns {string}
627 * The absolute URL derived from the given one, or the original URL
628 * if it already was absolute.
629 */
630 expandURL: function(url) {
631 if (!/^(?:[^/]+:)?\/\//.test(url))
632 url = location.protocol + '//' + location.host + url;
633
634 return url;
635 },
636
637 /**
638 * @typedef {Object} RequestOptions
639 * @memberof LuCI.request
640 *
641 * @property {string} [method=GET]
642 * The HTTP method to use, e.g. `GET` or `POST`.
643 *
644 * @property {Object<string, Object|string>} [query]
645 * Query string data to append to the URL. Non-string values of the
646 * given object will be converted to JSON.
647 *
648 * @property {boolean} [cache=false]
649 * Specifies whether the HTTP response may be retrieved from cache.
650 *
651 * @property {string} [username]
652 * Provides a username for HTTP basic authentication.
653 *
654 * @property {string} [password]
655 * Provides a password for HTTP basic authentication.
656 *
657 * @property {number} [timeout]
658 * Specifies the request timeout in seconds.
659 *
660 * @property {boolean} [credentials=false]
661 * Whether to include credentials such as cookies in the request.
662 *
663 * @property {string} [responseType=text]
664 * Overrides the request response type. Valid values or `text` to
665 * interpret the response as UTF-8 string or `blob` to handle the
666 * response as binary `Blob` data.
667 *
668 * @property {*} [content]
669 * Specifies the HTTP message body to send along with the request.
670 * If the value is a function, it is invoked and the return value
671 * used as content, if it is a FormData instance, it is used as-is,
672 * if it is an object, it will be converted to JSON, in all other
673 * cases it is converted to a string.
674 *
675 * @property {Object<string, string>} [header]
676 * Specifies HTTP headers to set for the request.
677 *
678 * @property {function} [progress]
679 * An optional request callback function which receives ProgressEvent
680 * instances as sole argument during the HTTP request transfer.
681 */
682
683 /**
684 * Initiate an HTTP request to the given target.
685 *
686 * @instance
687 * @memberof LuCI.request
688 * @param {string} target
689 * The URL to request.
690 *
691 * @param {LuCI.request.RequestOptions} [options]
692 * Additional options to configure the request.
693 *
694 * @returns {Promise<LuCI.response>}
695 * The resulting HTTP response.
696 */
697 request: function(target, options) {
698 var state = { xhr: new XMLHttpRequest(), url: this.expandURL(target), start: Date.now() },
699 opt = Object.assign({}, options, state),
700 content = null,
701 contenttype = null,
702 callback = this.handleReadyStateChange;
703
704 return new Promise(function(resolveFn, rejectFn) {
705 opt.xhr.onreadystatechange = callback.bind(opt, resolveFn, rejectFn);
706 opt.method = String(opt.method || 'GET').toUpperCase();
707
708 if ('query' in opt) {
709 var q = (opt.query != null) ? Object.keys(opt.query).map(function(k) {
710 if (opt.query[k] != null) {
711 var v = (typeof(opt.query[k]) == 'object')
712 ? JSON.stringify(opt.query[k])
713 : String(opt.query[k]);
714
715 return '%s=%s'.format(encodeURIComponent(k), encodeURIComponent(v));
716 }
717 else {
718 return encodeURIComponent(k);
719 }
720 }).join('&') : '';
721
722 if (q !== '') {
723 switch (opt.method) {
724 case 'GET':
725 case 'HEAD':
726 case 'OPTIONS':
727 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + q;
728 break;
729
730 default:
731 if (content == null) {
732 content = q;
733 contenttype = 'application/x-www-form-urlencoded';
734 }
735 }
736 }
737 }
738
739 if (!opt.cache)
740 opt.url += ((/\?/).test(opt.url) ? '&' : '?') + (new Date()).getTime();
741
742 if (isQueueableRequest(opt)) {
743 requestQueue.push([opt, rejectFn, resolveFn]);
744 requestAnimationFrame(flushRequestQueue);
745 return;
746 }
747
748 if ('username' in opt && 'password' in opt)
749 opt.xhr.open(opt.method, opt.url, true, opt.username, opt.password);
750 else
751 opt.xhr.open(opt.method, opt.url, true);
752
753 opt.xhr.responseType = opt.responseType || 'text';
754
755 if ('overrideMimeType' in opt.xhr)
756 opt.xhr.overrideMimeType('application/octet-stream');
757
758 if ('timeout' in opt)
759 opt.xhr.timeout = +opt.timeout;
760
761 if ('credentials' in opt)
762 opt.xhr.withCredentials = !!opt.credentials;
763
764 if (opt.content != null) {
765 switch (typeof(opt.content)) {
766 case 'function':
767 content = opt.content(xhr);
768 break;
769
770 case 'object':
771 if (!(opt.content instanceof FormData)) {
772 content = JSON.stringify(opt.content);
773 contenttype = 'application/json';
774 }
775 else {
776 content = opt.content;
777 }
778 break;
779
780 default:
781 content = String(opt.content);
782 }
783 }
784
785 if ('headers' in opt)
786 for (var header in opt.headers)
787 if (opt.headers.hasOwnProperty(header)) {
788 if (header.toLowerCase() != 'content-type')
789 opt.xhr.setRequestHeader(header, opt.headers[header]);
790 else
791 contenttype = opt.headers[header];
792 }
793
794 if ('progress' in opt && 'upload' in opt.xhr)
795 opt.xhr.upload.addEventListener('progress', opt.progress);
796
797 if (contenttype != null)
798 opt.xhr.setRequestHeader('Content-Type', contenttype);
799
800 try {
801 opt.xhr.send(content);
802 }
803 catch (e) {
804 rejectFn.call(opt, e);
805 }
806 });
807 },
808
809 handleReadyStateChange: function(resolveFn, rejectFn, ev) {
810 var xhr = this.xhr,
811 duration = Date.now() - this.start;
812
813 if (xhr.readyState !== 4)
814 return;
815
816 if (xhr.status === 0 && xhr.statusText === '') {
817 if (duration >= this.timeout)
818 rejectFn.call(this, new Error('XHR request timed out'));
819 else
820 rejectFn.call(this, new Error('XHR request aborted by browser'));
821 }
822 else {
823 var response = new Response(
824 xhr, xhr.responseURL || this.url, duration);
825
826 Promise.all(Request.interceptors.map(function(fn) { return fn(response) }))
827 .then(resolveFn.bind(this, response))
828 .catch(rejectFn.bind(this));
829 }
830 },
831
832 /**
833 * Initiate an HTTP GET request to the given target.
834 *
835 * @instance
836 * @memberof LuCI.request
837 * @param {string} target
838 * The URL to request.
839 *
840 * @param {LuCI.request.RequestOptions} [options]
841 * Additional options to configure the request.
842 *
843 * @returns {Promise<LuCI.response>}
844 * The resulting HTTP response.
845 */
846 get: function(url, options) {
847 return this.request(url, Object.assign({ method: 'GET' }, options));
848 },
849
850 /**
851 * Initiate an HTTP POST request to the given target.
852 *
853 * @instance
854 * @memberof LuCI.request
855 * @param {string} target
856 * The URL to request.
857 *
858 * @param {*} [data]
859 * The request data to send, see {@link LuCI.request.RequestOptions} for details.
860 *
861 * @param {LuCI.request.RequestOptions} [options]
862 * Additional options to configure the request.
863 *
864 * @returns {Promise<LuCI.response>}
865 * The resulting HTTP response.
866 */
867 post: function(url, data, options) {
868 return this.request(url, Object.assign({ method: 'POST', content: data }, options));
869 },
870
871 /**
872 * Interceptor functions are invoked whenever an HTTP reply is received, in the order
873 * these functions have been registered.
874 * @callback LuCI.request.interceptorFn
875 * @param {LuCI.response} res
876 * The HTTP response object
877 */
878
879 /**
880 * Register an HTTP response interceptor function. Interceptor
881 * functions are useful to perform default actions on incoming HTTP
882 * responses, such as checking for expired authentication or for
883 * implementing request retries before returning a failure.
884 *
885 * @instance
886 * @memberof LuCI.request
887 * @param {LuCI.request.interceptorFn} interceptorFn
888 * The interceptor function to register.
889 *
890 * @returns {LuCI.request.interceptorFn}
891 * The registered function.
892 */
893 addInterceptor: function(interceptorFn) {
894 if (typeof(interceptorFn) == 'function')
895 this.interceptors.push(interceptorFn);
896 return interceptorFn;
897 },
898
899 /**
900 * Remove an HTTP response interceptor function. The passed function
901 * value must be the very same value that was used to register the
902 * function.
903 *
904 * @instance
905 * @memberof LuCI.request
906 * @param {LuCI.request.interceptorFn} interceptorFn
907 * The interceptor function to remove.
908 *
909 * @returns {boolean}
910 * Returns `true` if any function has been removed, else `false`.
911 */
912 removeInterceptor: function(interceptorFn) {
913 var oldlen = this.interceptors.length, i = oldlen;
914 while (i--)
915 if (this.interceptors[i] === interceptorFn)
916 this.interceptors.splice(i, 1);
917 return (this.interceptors.length < oldlen);
918 },
919
920 /**
921 * @class
922 * @memberof LuCI.request
923 * @hideconstructor
924 * @classdesc
925 *
926 * The `Request.poll` class provides some convience wrappers around
927 * {@link LuCI.poll} mainly to simplify registering repeating HTTP
928 * request calls as polling functions.
929 */
930 poll: {
931 /**
932 * The callback function is invoked whenever an HTTP reply to a
933 * polled request is received or when the polled request timed
934 * out.
935 *
936 * @callback LuCI.request.poll~callbackFn
937 * @param {LuCI.response} res
938 * The HTTP response object.
939 *
940 * @param {*} data
941 * The response JSON if the response could be parsed as such,
942 * else `null`.
943 *
944 * @param {number} duration
945 * The total duration of the request in milliseconds.
946 */
947
948 /**
949 * Register a repeating HTTP request with an optional callback
950 * to invoke whenever a response for the request is received.
951 *
952 * @instance
953 * @memberof LuCI.request.poll
954 * @param {number} interval
955 * The poll interval in seconds.
956 *
957 * @param {string} url
958 * The URL to request on each poll.
959 *
960 * @param {LuCI.request.RequestOptions} [options]
961 * Additional options to configure the request.
962 *
963 * @param {LuCI.request.poll~callbackFn} [callback]
964 * {@link LuCI.request.poll~callbackFn Callback} function to
965 * invoke for each HTTP reply.
966 *
967 * @throws {TypeError}
968 * Throws `TypeError` when an invalid interval was passed.
969 *
970 * @returns {function}
971 * Returns the internally created poll function.
972 */
973 add: function(interval, url, options, callback) {
974 if (isNaN(interval) || interval <= 0)
975 throw new TypeError('Invalid poll interval');
976
977 var ival = interval >>> 0,
978 opts = Object.assign({}, options, { timeout: ival * 1000 - 5 });
979
980 var fn = function() {
981 return Request.request(url, options).then(function(res) {
982 if (!Poll.active())
983 return;
984
985 try {
986 callback(res, res.json(), res.duration);
987 }
988 catch (err) {
989 callback(res, null, res.duration);
990 }
991 });
992 };
993
994 return (Poll.add(fn, ival) ? fn : null);
995 },
996
997 /**
998 * Remove a polling request that has been previously added using `add()`.
999 * This function is essentially a wrapper around
1000 * {@link LuCI.poll.remove LuCI.poll.remove()}.
1001 *
1002 * @instance
1003 * @memberof LuCI.request.poll
1004 * @param {function} entry
1005 * The poll function returned by {@link LuCI.request.poll#add add()}.
1006 *
1007 * @returns {boolean}
1008 * Returns `true` if any function has been removed, else `false`.
1009 */
1010 remove: function(entry) { return Poll.remove(entry) },
1011
1012 /**
1013 * Alias for {@link LuCI.poll.start LuCI.poll.start()}.
1014 *
1015 * @instance
1016 * @memberof LuCI.request.poll
1017 */
1018 start: function() { return Poll.start() },
1019
1020 /**
1021 * Alias for {@link LuCI.poll.stop LuCI.poll.stop()}.
1022 *
1023 * @instance
1024 * @memberof LuCI.request.poll
1025 */
1026 stop: function() { return Poll.stop() },
1027
1028 /**
1029 * Alias for {@link LuCI.poll.active LuCI.poll.active()}.
1030 *
1031 * @instance
1032 * @memberof LuCI.request.poll
1033 */
1034 active: function() { return Poll.active() }
1035 }
1036 });
1037
1038 /**
1039 * @class poll
1040 * @memberof LuCI
1041 * @hideconstructor
1042 * @classdesc
1043 *
1044 * The `Poll` class allows registering and unregistering poll actions,
1045 * as well as starting, stopping and querying the state of the polling
1046 * loop.
1047 */
1048 var Poll = Class.singleton(/** @lends LuCI.poll.prototype */ {
1049 __name__: 'LuCI.poll',
1050
1051 queue: [],
1052
1053 /**
1054 * Add a new operation to the polling loop. If the polling loop is not
1055 * already started at this point, it will be implicitely started.
1056 *
1057 * @instance
1058 * @memberof LuCI.poll
1059 * @param {function} fn
1060 * The function to invoke on each poll interval.
1061 *
1062 * @param {number} interval
1063 * The poll interval in seconds.
1064 *
1065 * @throws {TypeError}
1066 * Throws `TypeError` when an invalid interval was passed.
1067 *
1068 * @returns {boolean}
1069 * Returns `true` if the function has been added or `false` if it
1070 * already is registered.
1071 */
1072 add: function(fn, interval) {
1073 if (interval == null || interval <= 0)
1074 interval = env.pollinterval || null;
1075
1076 if (isNaN(interval) || typeof(fn) != 'function')
1077 throw new TypeError('Invalid argument to LuCI.poll.add()');
1078
1079 for (var i = 0; i < this.queue.length; i++)
1080 if (this.queue[i].fn === fn)
1081 return false;
1082
1083 var e = {
1084 r: true,
1085 i: interval >>> 0,
1086 fn: fn
1087 };
1088
1089 this.queue.push(e);
1090
1091 if (this.tick != null && !this.active())
1092 this.start();
1093
1094 return true;
1095 },
1096
1097 /**
1098 * Remove an operation from the polling loop. If no further operatons
1099 * are registered, the polling loop is implicitely stopped.
1100 *
1101 * @instance
1102 * @memberof LuCI.poll
1103 * @param {function} fn
1104 * The function to remove.
1105 *
1106 * @throws {TypeError}
1107 * Throws `TypeError` when the given argument isn't a function.
1108 *
1109 * @returns {boolean}
1110 * Returns `true` if the function has been removed or `false` if it
1111 * wasn't found.
1112 */
1113 remove: function(fn) {
1114 if (typeof(fn) != 'function')
1115 throw new TypeError('Invalid argument to LuCI.poll.remove()');
1116
1117 var len = this.queue.length;
1118
1119 for (var i = len; i > 0; i--)
1120 if (this.queue[i-1].fn === fn)
1121 this.queue.splice(i-1, 1);
1122
1123 if (!this.queue.length && this.stop())
1124 this.tick = 0;
1125
1126 return (this.queue.length != len);
1127 },
1128
1129 /**
1130 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1131 * to the `document` object upon successful start.
1132 *
1133 * @instance
1134 * @memberof LuCI.poll
1135 * @returns {boolean}
1136 * Returns `true` if polling has been started (or if no functions
1137 * where registered) or `false` when the polling loop already runs.
1138 */
1139 start: function() {
1140 if (this.active())
1141 return false;
1142
1143 this.tick = 0;
1144
1145 if (this.queue.length) {
1146 this.timer = window.setInterval(this.step, 1000);
1147 this.step();
1148 document.dispatchEvent(new CustomEvent('poll-start'));
1149 }
1150
1151 return true;
1152 },
1153
1154 /**
1155 * Stop the polling loop. Dispatches a custom `poll-stop` event
1156 * to the `document` object upon successful stop.
1157 *
1158 * @instance
1159 * @memberof LuCI.poll
1160 * @returns {boolean}
1161 * Returns `true` if polling has been stopped or `false` if it din't
1162 * run to begin with.
1163 */
1164 stop: function() {
1165 if (!this.active())
1166 return false;
1167
1168 document.dispatchEvent(new CustomEvent('poll-stop'));
1169 window.clearInterval(this.timer);
1170 delete this.timer;
1171 delete this.tick;
1172 return true;
1173 },
1174
1175 /* private */
1176 step: function() {
1177 for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
1178 if ((Poll.tick % e.i) != 0)
1179 continue;
1180
1181 if (!e.r)
1182 continue;
1183
1184 e.r = false;
1185
1186 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
1187 }
1188
1189 Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
1190 },
1191
1192 /**
1193 * Test whether the polling loop is running.
1194 *
1195 * @instance
1196 * @memberof LuCI.poll
1197 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1198 */
1199 active: function() {
1200 return (this.timer != null);
1201 }
1202 });
1203
1204 /**
1205 * @class dom
1206 * @memberof LuCI
1207 * @hideconstructor
1208 * @classdesc
1209 *
1210 * The `dom` class provides convenience method for creating and
1211 * manipulating DOM elements.
1212 *
1213 * To import the class in views, use `'require dom'`, to import it in
1214 * external JavaScript, use `L.require("dom").then(...)`.
1215 */
1216 var DOM = Class.singleton(/** @lends LuCI.dom.prototype */ {
1217 __name__: 'LuCI.dom',
1218
1219 /**
1220 * Tests whether the given argument is a valid DOM `Node`.
1221 *
1222 * @instance
1223 * @memberof LuCI.dom
1224 * @param {*} e
1225 * The value to test.
1226 *
1227 * @returns {boolean}
1228 * Returns `true` if the value is a DOM `Node`, else `false`.
1229 */
1230 elem: function(e) {
1231 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
1232 },
1233
1234 /**
1235 * Parses a given string as HTML and returns the first child node.
1236 *
1237 * @instance
1238 * @memberof LuCI.dom
1239 * @param {string} s
1240 * A string containing an HTML fragment to parse. Note that only
1241 * the first result of the resulting structure is returned, so an
1242 * input value of `<div>foo</div> <div>bar</div>` will only return
1243 * the first `div` element node.
1244 *
1245 * @returns {Node}
1246 * Returns the first DOM `Node` extracted from the HTML fragment or
1247 * `null` on parsing failures or if no element could be found.
1248 */
1249 parse: function(s) {
1250 var elem;
1251
1252 try {
1253 domParser = domParser || new DOMParser();
1254 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1255 }
1256 catch(e) {}
1257
1258 if (!elem) {
1259 try {
1260 dummyElem = dummyElem || document.createElement('div');
1261 dummyElem.innerHTML = s;
1262 elem = dummyElem.firstChild;
1263 }
1264 catch (e) {}
1265 }
1266
1267 return elem || null;
1268 },
1269
1270 /**
1271 * Tests whether a given `Node` matches the given query selector.
1272 *
1273 * This function is a convenience wrapper around the standard
1274 * `Node.matches("selector")` function with the added benefit that
1275 * the `node` argument may be a non-`Node` value, in which case
1276 * this function simply returns `false`.
1277 *
1278 * @instance
1279 * @memberof LuCI.dom
1280 * @param {*} node
1281 * The `Node` argument to test the selector against.
1282 *
1283 * @param {string} [selector]
1284 * The query selector expression to test against the given node.
1285 *
1286 * @returns {boolean}
1287 * Returns `true` if the given node matches the specified selector
1288 * or `false` when the node argument is no valid DOM `Node` or the
1289 * selector didn't match.
1290 */
1291 matches: function(node, selector) {
1292 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
1293 return m ? m.call(node, selector) : false;
1294 },
1295
1296 /**
1297 * Returns the closest parent node that matches the given query
1298 * selector expression.
1299 *
1300 * This function is a convenience wrapper around the standard
1301 * `Node.closest("selector")` function with the added benefit that
1302 * the `node` argument may be a non-`Node` value, in which case
1303 * this function simply returns `null`.
1304 *
1305 * @instance
1306 * @memberof LuCI.dom
1307 * @param {*} node
1308 * The `Node` argument to find the closest parent for.
1309 *
1310 * @param {string} [selector]
1311 * The query selector expression to test against each parent.
1312 *
1313 * @returns {Node|null}
1314 * Returns the closest parent node matching the selector or
1315 * `null` when the node argument is no valid DOM `Node` or the
1316 * selector didn't match any parent.
1317 */
1318 parent: function(node, selector) {
1319 if (this.elem(node) && node.closest)
1320 return node.closest(selector);
1321
1322 while (this.elem(node))
1323 if (this.matches(node, selector))
1324 return node;
1325 else
1326 node = node.parentNode;
1327
1328 return null;
1329 },
1330
1331 /**
1332 * Appends the given children data to the given node.
1333 *
1334 * @instance
1335 * @memberof LuCI.dom
1336 * @param {*} node
1337 * The `Node` argument to append the children to.
1338 *
1339 * @param {*} [children]
1340 * The childrens to append to the given node.
1341 *
1342 * When `children` is an array, then each item of the array
1343 * will be either appended as child element or text node,
1344 * depending on whether the item is a DOM `Node` instance or
1345 * some other non-`null` value. Non-`Node`, non-`null` values
1346 * will be converted to strings first before being passed as
1347 * argument to `createTextNode()`.
1348 *
1349 * When `children` is a function, it will be invoked with
1350 * the passed `node` argument as sole parameter and the `append`
1351 * function will be invoked again, with the given `node` argument
1352 * as first and the return value of the `children` function as
1353 * second parameter.
1354 *
1355 * When `children` is is a DOM `Node` instance, it will be
1356 * appended to the given `node`.
1357 *
1358 * When `children` is any other non-`null` value, it will be
1359 * converted to a string and appened to the `innerHTML` property
1360 * of the given `node`.
1361 *
1362 * @returns {Node|null}
1363 * Returns the last children `Node` appended to the node or `null`
1364 * if either the `node` argument was no valid DOM `node` or if the
1365 * `children` was `null` or didn't result in further DOM nodes.
1366 */
1367 append: function(node, children) {
1368 if (!this.elem(node))
1369 return null;
1370
1371 if (Array.isArray(children)) {
1372 for (var i = 0; i < children.length; i++)
1373 if (this.elem(children[i]))
1374 node.appendChild(children[i]);
1375 else if (children !== null && children !== undefined)
1376 node.appendChild(document.createTextNode('' + children[i]));
1377
1378 return node.lastChild;
1379 }
1380 else if (typeof(children) === 'function') {
1381 return this.append(node, children(node));
1382 }
1383 else if (this.elem(children)) {
1384 return node.appendChild(children);
1385 }
1386 else if (children !== null && children !== undefined) {
1387 node.innerHTML = '' + children;
1388 return node.lastChild;
1389 }
1390
1391 return null;
1392 },
1393
1394 /**
1395 * Replaces the content of the given node with the given children.
1396 *
1397 * This function first removes any children of the given DOM
1398 * `Node` and then adds the given given children following the
1399 * rules outlined below.
1400 *
1401 * @instance
1402 * @memberof LuCI.dom
1403 * @param {*} node
1404 * The `Node` argument to replace the children of.
1405 *
1406 * @param {*} [children]
1407 * The childrens to replace into the given node.
1408 *
1409 * When `children` is an array, then each item of the array
1410 * will be either appended as child element or text node,
1411 * depending on whether the item is a DOM `Node` instance or
1412 * some other non-`null` value. Non-`Node`, non-`null` values
1413 * will be converted to strings first before being passed as
1414 * argument to `createTextNode()`.
1415 *
1416 * When `children` is a function, it will be invoked with
1417 * the passed `node` argument as sole parameter and the `append`
1418 * function will be invoked again, with the given `node` argument
1419 * as first and the return value of the `children` function as
1420 * second parameter.
1421 *
1422 * When `children` is is a DOM `Node` instance, it will be
1423 * appended to the given `node`.
1424 *
1425 * When `children` is any other non-`null` value, it will be
1426 * converted to a string and appened to the `innerHTML` property
1427 * of the given `node`.
1428 *
1429 * @returns {Node|null}
1430 * Returns the last children `Node` appended to the node or `null`
1431 * if either the `node` argument was no valid DOM `node` or if the
1432 * `children` was `null` or didn't result in further DOM nodes.
1433 */
1434 content: function(node, children) {
1435 if (!this.elem(node))
1436 return null;
1437
1438 var dataNodes = node.querySelectorAll('[data-idref]');
1439
1440 for (var i = 0; i < dataNodes.length; i++)
1441 delete this.registry[dataNodes[i].getAttribute('data-idref')];
1442
1443 while (node.firstChild)
1444 node.removeChild(node.firstChild);
1445
1446 return this.append(node, children);
1447 },
1448
1449 /**
1450 * Sets attributes or registers event listeners on element nodes.
1451 *
1452 * @instance
1453 * @memberof LuCI.dom
1454 * @param {*} node
1455 * The `Node` argument to set the attributes or add the event
1456 * listeners for. When the given `node` value is not a valid
1457 * DOM `Node`, the function returns and does nothing.
1458 *
1459 * @param {string|Object<string, *>} key
1460 * Specifies either the attribute or event handler name to use,
1461 * or an object containing multiple key, value pairs which are
1462 * each added to the node as either attribute or event handler,
1463 * depending on the respective value.
1464 *
1465 * @param {*} [val]
1466 * Specifies the attribute value or event handler function to add.
1467 * If the `key` parameter is an `Object`, this parameter will be
1468 * ignored.
1469 *
1470 * When `val` is of type function, it will be registered as event
1471 * handler on the given `node` with the `key` parameter being the
1472 * event name.
1473 *
1474 * When `val` is of type object, it will be serialized as JSON and
1475 * added as attribute to the given `node`, using the given `key`
1476 * as attribute name.
1477 *
1478 * When `val` is of any other type, it will be added as attribute
1479 * to the given `node` as-is, with the underlying `setAttribute()`
1480 * call implicitely turning it into a string.
1481 */
1482 attr: function(node, key, val) {
1483 if (!this.elem(node))
1484 return null;
1485
1486 var attr = null;
1487
1488 if (typeof(key) === 'object' && key !== null)
1489 attr = key;
1490 else if (typeof(key) === 'string')
1491 attr = {}, attr[key] = val;
1492
1493 for (key in attr) {
1494 if (!attr.hasOwnProperty(key) || attr[key] == null)
1495 continue;
1496
1497 switch (typeof(attr[key])) {
1498 case 'function':
1499 node.addEventListener(key, attr[key]);
1500 break;
1501
1502 case 'object':
1503 node.setAttribute(key, JSON.stringify(attr[key]));
1504 break;
1505
1506 default:
1507 node.setAttribute(key, attr[key]);
1508 }
1509 }
1510 },
1511
1512 /**
1513 * Creates a new DOM `Node` from the given `html`, `attr` and
1514 * `data` parameters.
1515 *
1516 * This function has multiple signatures, it can be either invoked
1517 * in the form `create(html[, attr[, data]])` or in the form
1518 * `create(html[, data])`. The used variant is determined from the
1519 * type of the second argument.
1520 *
1521 * @instance
1522 * @memberof LuCI.dom
1523 * @param {*} html
1524 * Describes the node to create.
1525 *
1526 * When the value of `html` is of type array, a `DocumentFragment`
1527 * node is created and each item of the array is first converted
1528 * to a DOM `Node` by passing it through `create()` and then added
1529 * as child to the fragment.
1530 *
1531 * When the value of `html` is a DOM `Node` instance, no new
1532 * element will be created but the node will be used as-is.
1533 *
1534 * When the value of `html` is a string starting with `<`, it will
1535 * be passed to `dom.parse()` and the resulting value is used.
1536 *
1537 * When the value of `html` is any other string, it will be passed
1538 * to `document.createElement()` for creating a new DOM `Node` of
1539 * the given name.
1540 *
1541 * @param {Object<string, *>} [attr]
1542 * Specifies an Object of key, value pairs to set as attributes
1543 * or event handlers on the created node. Refer to
1544 * {@link LuCI.dom#attr dom.attr()} for details.
1545 *
1546 * @param {*} [data]
1547 * Specifies children to append to the newly created element.
1548 * Refer to {@link LuCI.dom#append dom.append()} for details.
1549 *
1550 * @throws {InvalidCharacterError}
1551 * Throws an `InvalidCharacterError` when the given `html`
1552 * argument contained malformed markup (such as not escaped
1553 * `&` characters in XHTML mode) or when the given node name
1554 * in `html` contains characters which are not legal in DOM
1555 * element names, such as spaces.
1556 *
1557 * @returns {Node}
1558 * Returns the newly created `Node`.
1559 */
1560 create: function() {
1561 var html = arguments[0],
1562 attr = arguments[1],
1563 data = arguments[2],
1564 elem;
1565
1566 if (!(attr instanceof Object) || Array.isArray(attr))
1567 data = attr, attr = null;
1568
1569 if (Array.isArray(html)) {
1570 elem = document.createDocumentFragment();
1571 for (var i = 0; i < html.length; i++)
1572 elem.appendChild(this.create(html[i]));
1573 }
1574 else if (this.elem(html)) {
1575 elem = html;
1576 }
1577 else if (html.charCodeAt(0) === 60) {
1578 elem = this.parse(html);
1579 }
1580 else {
1581 elem = document.createElement(html);
1582 }
1583
1584 if (!elem)
1585 return null;
1586
1587 this.attr(elem, attr);
1588 this.append(elem, data);
1589
1590 return elem;
1591 },
1592
1593 registry: {},
1594
1595 /**
1596 * Attaches or detaches arbitrary data to and from a DOM `Node`.
1597 *
1598 * This function is useful to attach non-string values or runtime
1599 * data that is not serializable to DOM nodes. To decouple data
1600 * from the DOM, values are not added directly to nodes, but
1601 * inserted into a registry instead which is then referenced by a
1602 * string key stored as `data-idref` attribute in the node.
1603 *
1604 * This function has multiple signatures and is sensitive to the
1605 * number of arguments passed to it.
1606 *
1607 * - `dom.data(node)` -
1608 * Fetches all data associated with the given node.
1609 * - `dom.data(node, key)` -
1610 * Fetches a specific key associated with the given node.
1611 * - `dom.data(node, key, val)` -
1612 * Sets a specific key to the given value associated with the
1613 * given node.
1614 * - `dom.data(node, null)` -
1615 * Clears any data associated with the node.
1616 * - `dom.data(node, key, null)` -
1617 * Clears the given key associated with the node.
1618 *
1619 * @instance
1620 * @memberof LuCI.dom
1621 * @param {Node} node
1622 * The DOM `Node` instance to set or retrieve the data for.
1623 *
1624 * @param {string|null} [key]
1625 * This is either a string specifying the key to retrieve, or
1626 * `null` to unset the entire node data.
1627 *
1628 * @param {*|null} [val]
1629 * This is either a non-`null` value to set for a given key or
1630 * `null` to remove the given `key` from the specified node.
1631 *
1632 * @returns {*}
1633 * Returns the get or set value, or `null` when no value could
1634 * be found.
1635 */
1636 data: function(node, key, val) {
1637 if (!node || !node.getAttribute)
1638 return null;
1639
1640 var id = node.getAttribute('data-idref');
1641
1642 /* clear all data */
1643 if (arguments.length > 1 && key == null) {
1644 if (id != null) {
1645 node.removeAttribute('data-idref');
1646 val = this.registry[id]
1647 delete this.registry[id];
1648 return val;
1649 }
1650
1651 return null;
1652 }
1653
1654 /* clear a key */
1655 else if (arguments.length > 2 && key != null && val == null) {
1656 if (id != null) {
1657 val = this.registry[id][key];
1658 delete this.registry[id][key];
1659 return val;
1660 }
1661
1662 return null;
1663 }
1664
1665 /* set a key */
1666 else if (arguments.length > 2 && key != null && val != null) {
1667 if (id == null) {
1668 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1669 while (this.registry.hasOwnProperty(id));
1670
1671 node.setAttribute('data-idref', id);
1672 this.registry[id] = {};
1673 }
1674
1675 return (this.registry[id][key] = val);
1676 }
1677
1678 /* get all data */
1679 else if (arguments.length == 1) {
1680 if (id != null)
1681 return this.registry[id];
1682
1683 return null;
1684 }
1685
1686 /* get a key */
1687 else if (arguments.length == 2) {
1688 if (id != null)
1689 return this.registry[id][key];
1690 }
1691
1692 return null;
1693 },
1694
1695 /**
1696 * Binds the given class instance ot the specified DOM `Node`.
1697 *
1698 * This function uses the `dom.data()` facility to attach the
1699 * passed instance of a Class to a node. This is needed for
1700 * complex widget elements or similar where the corresponding
1701 * class instance responsible for the element must be retrieved
1702 * from DOM nodes obtained by `querySelector()` or similar means.
1703 *
1704 * @instance
1705 * @memberof LuCI.dom
1706 * @param {Node} node
1707 * The DOM `Node` instance to bind the class to.
1708 *
1709 * @param {Class} inst
1710 * The Class instance to bind to the node.
1711 *
1712 * @throws {TypeError}
1713 * Throws a `TypeError` when the given instance argument isn't
1714 * a valid Class instance.
1715 *
1716 * @returns {Class}
1717 * Returns the bound class instance.
1718 */
1719 bindClassInstance: function(node, inst) {
1720 if (!(inst instanceof Class))
1721 LuCI.prototype.error('TypeError', 'Argument must be a class instance');
1722
1723 return this.data(node, '_class', inst);
1724 },
1725
1726 /**
1727 * Finds a bound class instance on the given node itself or the
1728 * first bound instance on its closest parent node.
1729 *
1730 * @instance
1731 * @memberof LuCI.dom
1732 * @param {Node} node
1733 * The DOM `Node` instance to start from.
1734 *
1735 * @returns {Class|null}
1736 * Returns the founds class instance if any or `null` if no bound
1737 * class could be found on the node itself or any of its parents.
1738 */
1739 findClassInstance: function(node) {
1740 var inst = null;
1741
1742 do {
1743 inst = this.data(node, '_class');
1744 node = node.parentNode;
1745 }
1746 while (!(inst instanceof Class) && node != null);
1747
1748 return inst;
1749 },
1750
1751 /**
1752 * Finds a bound class instance on the given node itself or the
1753 * first bound instance on its closest parent node and invokes
1754 * the specified method name on the found class instance.
1755 *
1756 * @instance
1757 * @memberof LuCI.dom
1758 * @param {Node} node
1759 * The DOM `Node` instance to start from.
1760 *
1761 * @param {string} method
1762 * The name of the method to invoke on the found class instance.
1763 *
1764 * @param {...*} params
1765 * Additional arguments to pass to the invoked method as-is.
1766 *
1767 * @returns {*|null}
1768 * Returns the return value of the invoked method if a class
1769 * instance and method has been found. Returns `null` if either
1770 * no bound class instance could be found, or if the found
1771 * instance didn't have the requested `method`.
1772 */
1773 callClassMethod: function(node, method /*, ... */) {
1774 var inst = this.findClassInstance(node);
1775
1776 if (inst == null || typeof(inst[method]) != 'function')
1777 return null;
1778
1779 return inst[method].apply(inst, inst.varargs(arguments, 2));
1780 },
1781
1782 /**
1783 * The ignore callback function is invoked by `isEmpty()` for each
1784 * child node to decide whether to ignore a child node or not.
1785 *
1786 * When this function returns `false`, the node passed to it is
1787 * ignored, else not.
1788 *
1789 * @callback LuCI.dom~ignoreCallbackFn
1790 * @param {Node} node
1791 * The child node to test.
1792 *
1793 * @returns {boolean}
1794 * Boolean indicating whether to ignore the node or not.
1795 */
1796
1797 /**
1798 * Tests whether a given DOM `Node` instance is empty or appears
1799 * empty.
1800 *
1801 * Any element child nodes which have the CSS class `hidden` set
1802 * or for which the optionally passed `ignoreFn` callback function
1803 * returns `false` are ignored.
1804 *
1805 * @instance
1806 * @memberof LuCI.dom
1807 * @param {Node} node
1808 * The DOM `Node` instance to test.
1809 *
1810 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
1811 * Specifies an optional function which is invoked for each child
1812 * node to decide whether the child node should be ignored or not.
1813 *
1814 * @returns {boolean}
1815 * Returns `true` if the node does not have any children or if
1816 * any children node either has a `hidden` CSS class or a `false`
1817 * result when testing it using the given `ignoreFn`.
1818 */
1819 isEmpty: function(node, ignoreFn) {
1820 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1821 if (!child.classList.contains('hidden') && (!ignoreFn || !ignoreFn(child)))
1822 return false;
1823
1824 return true;
1825 }
1826 });
1827
1828 /**
1829 * @class session
1830 * @memberof LuCI
1831 * @hideconstructor
1832 * @classdesc
1833 *
1834 * The `session` class provides various session related functionality.
1835 */
1836 var Session = Class.singleton(/** @lends LuCI.session.prototype */ {
1837 __name__: 'LuCI.session',
1838
1839 /**
1840 * Retrieve the current session ID.
1841 *
1842 * @returns {string}
1843 * Returns the current session ID.
1844 */
1845 getID: function() {
1846 return env.sessionid || '00000000000000000000000000000000';
1847 },
1848
1849 /**
1850 * Retrieve the current session token.
1851 *
1852 * @returns {string|null}
1853 * Returns the current session token or `null` if not logged in.
1854 */
1855 getToken: function() {
1856 return env.token || null;
1857 },
1858
1859 /**
1860 * Retrieve data from the local session storage.
1861 *
1862 * @param {string} [key]
1863 * The key to retrieve from the session data store. If omitted, all
1864 * session data will be returned.
1865 *
1866 * @returns {*}
1867 * Returns the stored session data or `null` if the given key wasn't
1868 * found.
1869 */
1870 getLocalData: function(key) {
1871 try {
1872 var sid = this.getID(),
1873 item = 'luci-session-store',
1874 data = JSON.parse(window.sessionStorage.getItem(item));
1875
1876 if (!LuCI.prototype.isObject(data) || !data.hasOwnProperty(sid)) {
1877 data = {};
1878 data[sid] = {};
1879 }
1880
1881 if (key != null)
1882 return data[sid].hasOwnProperty(key) ? data[sid][key] : null;
1883
1884 return data[sid];
1885 }
1886 catch (e) {
1887 return (key != null) ? null : {};
1888 }
1889 },
1890
1891 /**
1892 * Set data in the local session storage.
1893 *
1894 * @param {string} key
1895 * The key to set in the session data store.
1896 *
1897 * @param {*} value
1898 * The value to store. It will be internally converted to JSON before
1899 * being put in the session store.
1900 *
1901 * @returns {boolean}
1902 * Returns `true` if the data could be stored or `false` on error.
1903 */
1904 setLocalData: function(key, value) {
1905 if (key == null)
1906 return false;
1907
1908 try {
1909 var sid = this.getID(),
1910 item = 'luci-session-store',
1911 data = JSON.parse(window.sessionStorage.getItem(item));
1912
1913 if (!LuCI.prototype.isObject(data) || !data.hasOwnProperty(sid)) {
1914 data = {};
1915 data[sid] = {};
1916 }
1917
1918 if (value != null)
1919 data[sid][key] = value;
1920 else
1921 delete data[sid][key];
1922
1923 window.sessionStorage.setItem(item, JSON.stringify(data));
1924
1925 return true;
1926 }
1927 catch (e) {
1928 return false;
1929 }
1930 }
1931 });
1932
1933 /**
1934 * @class view
1935 * @memberof LuCI
1936 * @hideconstructor
1937 * @classdesc
1938 *
1939 * The `view` class forms the basis of views and provides a standard
1940 * set of methods to inherit from.
1941 */
1942 var View = Class.extend(/** @lends LuCI.view.prototype */ {
1943 __name__: 'LuCI.view',
1944
1945 __init__: function() {
1946 var vp = document.getElementById('view');
1947
1948 DOM.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1949
1950 return Promise.resolve(this.load())
1951 .then(LuCI.prototype.bind(this.render, this))
1952 .then(LuCI.prototype.bind(function(nodes) {
1953 var vp = document.getElementById('view');
1954
1955 DOM.content(vp, nodes);
1956 DOM.append(vp, this.addFooter());
1957 }, this)).catch(LuCI.prototype.error);
1958 },
1959
1960 /**
1961 * The load function is invoked before the view is rendered.
1962 *
1963 * The invocation of this function is wrapped by
1964 * `Promise.resolve()` so it may return Promises if needed.
1965 *
1966 * The return value of the function (or the resolved values
1967 * of the promise returned by it) will be passed as first
1968 * argument to `render()`.
1969 *
1970 * This function is supposed to be overwritten by subclasses,
1971 * the default implementation does nothing.
1972 *
1973 * @instance
1974 * @abstract
1975 * @memberof LuCI.view
1976 *
1977 * @returns {*|Promise<*>}
1978 * May return any value or a Promise resolving to any value.
1979 */
1980 load: function() {},
1981
1982 /**
1983 * The render function is invoked after the
1984 * {@link LuCI.view#load load()} function and responsible
1985 * for setting up the view contents. It must return a DOM
1986 * `Node` or `DocumentFragment` holding the contents to
1987 * insert into the view area.
1988 *
1989 * The invocation of this function is wrapped by
1990 * `Promise.resolve()` so it may return Promises if needed.
1991 *
1992 * The return value of the function (or the resolved values
1993 * of the promise returned by it) will be inserted into the
1994 * main content area using
1995 * {@link LuCI.dom#append dom.append()}.
1996 *
1997 * This function is supposed to be overwritten by subclasses,
1998 * the default implementation does nothing.
1999 *
2000 * @instance
2001 * @abstract
2002 * @memberof LuCI.view
2003 * @param {*|null} load_results
2004 * This function will receive the return value of the
2005 * {@link LuCI.view#load view.load()} function as first
2006 * argument.
2007 *
2008 * @returns {Node|Promise<Node>}
2009 * Should return a DOM `Node` value or a `Promise` resolving
2010 * to a `Node` value.
2011 */
2012 render: function() {},
2013
2014 /**
2015 * The handleSave function is invoked when the user clicks
2016 * the `Save` button in the page action footer.
2017 *
2018 * The default implementation should be sufficient for most
2019 * views using {@link form#Map form.Map()} based forms - it
2020 * will iterate all forms present in the view and invoke
2021 * the {@link form#Map#save Map.save()} method on each form.
2022 *
2023 * Views not using `Map` instances or requiring other special
2024 * logic should overwrite `handleSave()` with a custom
2025 * implementation.
2026 *
2027 * To disable the `Save` page footer button, views extending
2028 * this base class should overwrite the `handleSave` function
2029 * with `null`.
2030 *
2031 * The invocation of this function is wrapped by
2032 * `Promise.resolve()` so it may return Promises if needed.
2033 *
2034 * @instance
2035 * @memberof LuCI.view
2036 * @param {Event} ev
2037 * The DOM event that triggered the function.
2038 *
2039 * @returns {*|Promise<*>}
2040 * Any return values of this function are discarded, but
2041 * passed through `Promise.resolve()` to ensure that any
2042 * returned promise runs to completion before the button
2043 * is reenabled.
2044 */
2045 handleSave: function(ev) {
2046 var tasks = [];
2047
2048 document.getElementById('maincontent')
2049 .querySelectorAll('.cbi-map').forEach(function(map) {
2050 tasks.push(DOM.callClassMethod(map, 'save'));
2051 });
2052
2053 return Promise.all(tasks);
2054 },
2055
2056 /**
2057 * The handleSaveApply function is invoked when the user clicks
2058 * the `Save & Apply` button in the page action footer.
2059 *
2060 * The default implementation should be sufficient for most
2061 * views using {@link form#Map form.Map()} based forms - it
2062 * will first invoke
2063 * {@link LuCI.view.handleSave view.handleSave()} and then
2064 * call {@link ui#changes#apply ui.changes.apply()} to start the
2065 * modal config apply and page reload flow.
2066 *
2067 * Views not using `Map` instances or requiring other special
2068 * logic should overwrite `handleSaveApply()` with a custom
2069 * implementation.
2070 *
2071 * To disable the `Save & Apply` page footer button, views
2072 * extending this base class should overwrite the
2073 * `handleSaveApply` function with `null`.
2074 *
2075 * The invocation of this function is wrapped by
2076 * `Promise.resolve()` so it may return Promises if needed.
2077 *
2078 * @instance
2079 * @memberof LuCI.view
2080 * @param {Event} ev
2081 * The DOM event that triggered the function.
2082 *
2083 * @returns {*|Promise<*>}
2084 * Any return values of this function are discarded, but
2085 * passed through `Promise.resolve()` to ensure that any
2086 * returned promise runs to completion before the button
2087 * is reenabled.
2088 */
2089 handleSaveApply: function(ev, mode) {
2090 return this.handleSave(ev).then(function() {
2091 classes.ui.changes.apply(mode == '0');
2092 });
2093 },
2094
2095 /**
2096 * The handleReset function is invoked when the user clicks
2097 * the `Reset` button in the page action footer.
2098 *
2099 * The default implementation should be sufficient for most
2100 * views using {@link form#Map form.Map()} based forms - it
2101 * will iterate all forms present in the view and invoke
2102 * the {@link form#Map#save Map.reset()} method on each form.
2103 *
2104 * Views not using `Map` instances or requiring other special
2105 * logic should overwrite `handleReset()` with a custom
2106 * implementation.
2107 *
2108 * To disable the `Reset` page footer button, views extending
2109 * this base class should overwrite the `handleReset` function
2110 * with `null`.
2111 *
2112 * The invocation of this function is wrapped by
2113 * `Promise.resolve()` so it may return Promises if needed.
2114 *
2115 * @instance
2116 * @memberof LuCI.view
2117 * @param {Event} ev
2118 * The DOM event that triggered the function.
2119 *
2120 * @returns {*|Promise<*>}
2121 * Any return values of this function are discarded, but
2122 * passed through `Promise.resolve()` to ensure that any
2123 * returned promise runs to completion before the button
2124 * is reenabled.
2125 */
2126 handleReset: function(ev) {
2127 var tasks = [];
2128
2129 document.getElementById('maincontent')
2130 .querySelectorAll('.cbi-map').forEach(function(map) {
2131 tasks.push(DOM.callClassMethod(map, 'reset'));
2132 });
2133
2134 return Promise.all(tasks);
2135 },
2136
2137 /**
2138 * Renders a standard page action footer if any of the
2139 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2140 * functions are defined.
2141 *
2142 * The default implementation should be sufficient for most
2143 * views - it will render a standard page footer with action
2144 * buttons labeled `Save`, `Save & Apply` and `Reset`
2145 * triggering the `handleSave()`, `handleSaveApply()` and
2146 * `handleReset()` functions respectively.
2147 *
2148 * When any of these `handle*()` functions is overwritten
2149 * with `null` by a view extending this class, the
2150 * corresponding button will not be rendered.
2151 *
2152 * @instance
2153 * @memberof LuCI.view
2154 * @returns {DocumentFragment}
2155 * Returns a `DocumentFragment` containing the footer bar
2156 * with buttons for each corresponding `handle*()` action
2157 * or an empty `DocumentFragment` if all three `handle*()`
2158 * methods are overwritten with `null`.
2159 */
2160 addFooter: function() {
2161 var footer = E([]),
2162 vp = document.getElementById('view'),
2163 hasmap = false,
2164 readonly = true;
2165
2166 vp.querySelectorAll('.cbi-map').forEach(function(map) {
2167 var m = DOM.findClassInstance(map);
2168 if (m) {
2169 hasmap = true;
2170
2171 if (!m.readonly)
2172 readonly = false;
2173 }
2174 });
2175
2176 if (!hasmap)
2177 readonly = !LuCI.prototype.hasViewPermission();
2178
2179 var saveApplyBtn = this.handleSaveApply ? new classes.ui.ComboButton('0', {
2180 0: [ _('Save & Apply') ],
2181 1: [ _('Apply unchecked') ]
2182 }, {
2183 classes: {
2184 0: 'btn cbi-button cbi-button-apply important',
2185 1: 'btn cbi-button cbi-button-negative important'
2186 },
2187 click: classes.ui.createHandlerFn(this, 'handleSaveApply'),
2188 disabled: readonly || null
2189 }).render() : E([]);
2190
2191 if (this.handleSaveApply || this.handleSave || this.handleReset) {
2192 footer.appendChild(E('div', { 'class': 'cbi-page-actions control-group' }, [
2193 saveApplyBtn, ' ',
2194 this.handleSave ? E('button', {
2195 'class': 'cbi-button cbi-button-save',
2196 'click': classes.ui.createHandlerFn(this, 'handleSave'),
2197 'disabled': readonly || null
2198 }, [ _('Save') ]) : '', ' ',
2199 this.handleReset ? E('button', {
2200 'class': 'cbi-button cbi-button-reset',
2201 'click': classes.ui.createHandlerFn(this, 'handleReset'),
2202 'disabled': readonly || null
2203 }, [ _('Reset') ]) : ''
2204 ]));
2205 }
2206
2207 return footer;
2208 }
2209 });
2210
2211
2212 var dummyElem = null,
2213 domParser = null,
2214 originalCBIInit = null,
2215 rpcBaseURL = null,
2216 sysFeatures = null,
2217 preloadClasses = null;
2218
2219 /* "preload" builtin classes to make the available via require */
2220 var classes = {
2221 baseclass: Class,
2222 dom: DOM,
2223 poll: Poll,
2224 request: Request,
2225 session: Session,
2226 view: View
2227 };
2228
2229 var LuCI = Class.extend(/** @lends LuCI.prototype */ {
2230 __name__: 'LuCI',
2231 __init__: function(setenv) {
2232
2233 document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
2234 if (setenv.base_url == null || setenv.base_url == '') {
2235 var m = (s.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
2236 if (m) {
2237 setenv.base_url = m[1];
2238 setenv.resource_version = m[2];
2239 }
2240 }
2241 });
2242
2243 if (setenv.base_url == null)
2244 this.error('InternalError', 'Cannot find url of luci.js');
2245
2246 setenv.cgi_base = setenv.scriptname.replace(/\/[^\/]+$/, '');
2247
2248 Object.assign(env, setenv);
2249
2250 var domReady = new Promise(function(resolveFn, rejectFn) {
2251 document.addEventListener('DOMContentLoaded', resolveFn);
2252 });
2253
2254 Promise.all([
2255 domReady,
2256 this.require('ui'),
2257 this.require('rpc'),
2258 this.require('form'),
2259 this.probeRPCBaseURL()
2260 ]).then(this.setupDOM.bind(this)).catch(this.error);
2261
2262 originalCBIInit = window.cbi_init;
2263 window.cbi_init = function() {};
2264 },
2265
2266 /**
2267 * Captures the current stack trace and throws an error of the
2268 * specified type as a new exception. Also logs the exception as
2269 * error to the debug console if it is available.
2270 *
2271 * @instance
2272 * @memberof LuCI
2273 *
2274 * @param {Error|string} [type=Error]
2275 * Either a string specifying the type of the error to throw or an
2276 * existing `Error` instance to copy.
2277 *
2278 * @param {string} [fmt=Unspecified error]
2279 * A format string which is used to form the error message, together
2280 * with all subsequent optional arguments.
2281 *
2282 * @param {...*} [args]
2283 * Zero or more variable arguments to the supplied format string.
2284 *
2285 * @throws {Error}
2286 * Throws the created error object with the captured stack trace
2287 * appended to the message and the type set to the given type
2288 * argument or copied from the given error instance.
2289 */
2290 raise: function(type, fmt /*, ...*/) {
2291 var e = null,
2292 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
2293 stack = null;
2294
2295 if (type instanceof Error) {
2296 e = type;
2297
2298 if (msg)
2299 e.message = msg + ': ' + e.message;
2300 }
2301 else {
2302 try { throw new Error('stacktrace') }
2303 catch (e2) { stack = (e2.stack || '').split(/\n/) }
2304
2305 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
2306 e.name = type || 'Error';
2307 }
2308
2309 stack = (stack || []).map(function(frame) {
2310 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
2311 return frame ? ' ' + frame : '';
2312 });
2313
2314 if (!/^ at /.test(stack[0]))
2315 stack.shift();
2316
2317 if (/\braise /.test(stack[0]))
2318 stack.shift();
2319
2320 if (/\berror /.test(stack[0]))
2321 stack.shift();
2322
2323 if (stack.length)
2324 e.message += '\n' + stack.join('\n');
2325
2326 if (window.console && console.debug)
2327 console.debug(e);
2328
2329 throw e;
2330 },
2331
2332 /**
2333 * A wrapper around {@link LuCI#raise raise()} which also renders
2334 * the error either as modal overlay when `ui.js` is already loaed
2335 * or directly into the view body.
2336 *
2337 * @instance
2338 * @memberof LuCI
2339 *
2340 * @param {Error|string} [type=Error]
2341 * Either a string specifying the type of the error to throw or an
2342 * existing `Error` instance to copy.
2343 *
2344 * @param {string} [fmt=Unspecified error]
2345 * A format string which is used to form the error message, together
2346 * with all subsequent optional arguments.
2347 *
2348 * @param {...*} [args]
2349 * Zero or more variable arguments to the supplied format string.
2350 *
2351 * @throws {Error}
2352 * Throws the created error object with the captured stack trace
2353 * appended to the message and the type set to the given type
2354 * argument or copied from the given error instance.
2355 */
2356 error: function(type, fmt /*, ...*/) {
2357 try {
2358 LuCI.prototype.raise.apply(LuCI.prototype,
2359 Array.prototype.slice.call(arguments));
2360 }
2361 catch (e) {
2362 if (!e.reported) {
2363 if (classes.ui)
2364 classes.ui.addNotification(e.name || _('Runtime error'),
2365 E('pre', {}, e.message), 'danger');
2366 else
2367 DOM.content(document.querySelector('#maincontent'),
2368 E('pre', { 'class': 'alert-message error' }, e.message));
2369
2370 e.reported = true;
2371 }
2372
2373 throw e;
2374 }
2375 },
2376
2377 /**
2378 * Return a bound function using the given `self` as `this` context
2379 * and any further arguments as parameters to the bound function.
2380 *
2381 * @instance
2382 * @memberof LuCI
2383 *
2384 * @param {function} fn
2385 * The function to bind.
2386 *
2387 * @param {*} self
2388 * The value to bind as `this` context to the specified function.
2389 *
2390 * @param {...*} [args]
2391 * Zero or more variable arguments which are bound to the function
2392 * as parameters.
2393 *
2394 * @returns {function}
2395 * Returns the bound function.
2396 */
2397 bind: function(fn, self /*, ... */) {
2398 return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
2399 },
2400
2401 /**
2402 * Load an additional LuCI JavaScript class and its dependencies,
2403 * instantiate it and return the resulting class instance. Each
2404 * class is only loaded once. Subsequent attempts to load the same
2405 * class will return the already instantiated class.
2406 *
2407 * @instance
2408 * @memberof LuCI
2409 *
2410 * @param {string} name
2411 * The name of the class to load in dotted notation. Dots will
2412 * be replaced by spaces and joined with the runtime-determined
2413 * base URL of LuCI.js to form an absolute URL to load the class
2414 * file from.
2415 *
2416 * @throws {DependencyError}
2417 * Throws a `DependencyError` when the class to load includes
2418 * circular dependencies.
2419 *
2420 * @throws {NetworkError}
2421 * Throws `NetworkError` when the underlying {@link LuCI.request}
2422 * call failed.
2423 *
2424 * @throws {SyntaxError}
2425 * Throws `SyntaxError` when the loaded class file code cannot
2426 * be interpreted by `eval`.
2427 *
2428 * @throws {TypeError}
2429 * Throws `TypeError` when the class file could be loaded and
2430 * interpreted, but when invoking its code did not yield a valid
2431 * class instance.
2432 *
2433 * @returns {Promise<LuCI.baseclass>}
2434 * Returns the instantiated class.
2435 */
2436 require: function(name, from) {
2437 var L = this, url = null, from = from || [];
2438
2439 /* Class already loaded */
2440 if (classes[name] != null) {
2441 /* Circular dependency */
2442 if (from.indexOf(name) != -1)
2443 LuCI.prototype.raise('DependencyError',
2444 'Circular dependency: class "%s" depends on "%s"',
2445 name, from.join('" which depends on "'));
2446
2447 return Promise.resolve(classes[name]);
2448 }
2449
2450 url = '%s/%s.js%s'.format(env.base_url, name.replace(/\./g, '/'), (env.resource_version ? '?v=' + env.resource_version : ''));
2451 from = [ name ].concat(from);
2452
2453 var compileClass = function(res) {
2454 if (!res.ok)
2455 LuCI.prototype.raise('NetworkError',
2456 'HTTP error %d while loading class file "%s"', res.status, url);
2457
2458 var source = res.text(),
2459 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
2460 strictmatch = /^use[ \t]+strict$/,
2461 depends = [],
2462 args = '';
2463
2464 /* find require statements in source */
2465 for (var i = 0, off = -1, quote = -1, esc = false; i < source.length; i++) {
2466 var chr = source.charCodeAt(i);
2467
2468 if (esc) {
2469 esc = false;
2470 }
2471 else if (chr == 92) {
2472 esc = true;
2473 }
2474 else if (chr == quote) {
2475 var s = source.substring(off, i),
2476 m = requirematch.exec(s);
2477
2478 if (m) {
2479 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
2480 depends.push(LuCI.prototype.require(dep, from));
2481 args += ', ' + as;
2482 }
2483 else if (!strictmatch.exec(s)) {
2484 break;
2485 }
2486
2487 off = -1;
2488 quote = -1;
2489 }
2490 else if (quote == -1 && (chr == 34 || chr == 39)) {
2491 off = i + 1;
2492 quote = chr;
2493 }
2494 }
2495
2496 /* load dependencies and instantiate class */
2497 return Promise.all(depends).then(function(instances) {
2498 var _factory, _class;
2499
2500 try {
2501 _factory = eval(
2502 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
2503 .format(args, source, res.url));
2504 }
2505 catch (error) {
2506 LuCI.prototype.raise('SyntaxError', '%s\n in %s:%s',
2507 error.message, res.url, error.lineNumber || '?');
2508 }
2509
2510 _factory.displayName = toCamelCase(name + 'ClassFactory');
2511 _class = _factory.apply(_factory, [window, document, L].concat(instances));
2512
2513 if (!Class.isSubclass(_class))
2514 LuCI.prototype.error('TypeError', '"%s" factory yields invalid constructor', name);
2515
2516 if (_class.displayName == 'AnonymousClass')
2517 _class.displayName = toCamelCase(name + 'Class');
2518
2519 var ptr = Object.getPrototypeOf(L),
2520 parts = name.split(/\./),
2521 instance = new _class();
2522
2523 for (var i = 0; ptr && i < parts.length - 1; i++)
2524 ptr = ptr[parts[i]];
2525
2526 if (ptr)
2527 ptr[parts[i]] = instance;
2528
2529 classes[name] = instance;
2530
2531 return instance;
2532 });
2533 };
2534
2535 /* Request class file */
2536 classes[name] = Request.get(url, { cache: true }).then(compileClass);
2537
2538 return classes[name];
2539 },
2540
2541 /* DOM setup */
2542 probeRPCBaseURL: function() {
2543 if (rpcBaseURL == null)
2544 rpcBaseURL = Session.getLocalData('rpcBaseURL');
2545
2546 if (rpcBaseURL == null) {
2547 var rpcFallbackURL = this.url('admin/ubus');
2548
2549 rpcBaseURL = Request.get(env.ubuspath).then(function(res) {
2550 return (rpcBaseURL = (res.status == 400) ? env.ubuspath : rpcFallbackURL);
2551 }, function() {
2552 return (rpcBaseURL = rpcFallbackURL);
2553 }).then(function(url) {
2554 Session.setLocalData('rpcBaseURL', url);
2555 return url;
2556 });
2557 }
2558
2559 return Promise.resolve(rpcBaseURL);
2560 },
2561
2562 probeSystemFeatures: function() {
2563 if (sysFeatures == null)
2564 sysFeatures = Session.getLocalData('features');
2565
2566 if (!this.isObject(sysFeatures)) {
2567 sysFeatures = classes.rpc.declare({
2568 object: 'luci',
2569 method: 'getFeatures',
2570 expect: { '': {} }
2571 })().then(function(features) {
2572 Session.setLocalData('features', features);
2573 sysFeatures = features;
2574
2575 return features;
2576 });
2577 }
2578
2579 return Promise.resolve(sysFeatures);
2580 },
2581
2582 probePreloadClasses: function() {
2583 if (preloadClasses == null)
2584 preloadClasses = Session.getLocalData('preload');
2585
2586 if (!Array.isArray(preloadClasses)) {
2587 preloadClasses = this.resolveDefault(classes.rpc.declare({
2588 object: 'file',
2589 method: 'list',
2590 params: [ 'path' ],
2591 expect: { 'entries': [] }
2592 })(this.fspath(this.resource('preload'))), []).then(function(entries) {
2593 var classes = [];
2594
2595 for (var i = 0; i < entries.length; i++) {
2596 if (entries[i].type != 'file')
2597 continue;
2598
2599 var m = entries[i].name.match(/(.+)\.js$/);
2600
2601 if (m)
2602 classes.push('preload.%s'.format(m[1]));
2603 }
2604
2605 Session.setLocalData('preload', classes);
2606 preloadClasses = classes;
2607
2608 return classes;
2609 });
2610 }
2611
2612 return Promise.resolve(preloadClasses);
2613 },
2614
2615 /**
2616 * Test whether a particular system feature is available, such as
2617 * hostapd SAE support or an installed firewall. The features are
2618 * queried once at the beginning of the LuCI session and cached in
2619 * `SessionStorage` throughout the lifetime of the associated tab or
2620 * browser window.
2621 *
2622 * @instance
2623 * @memberof LuCI
2624 *
2625 * @param {string} feature
2626 * The feature to test. For detailed list of known feature flags,
2627 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
2628 *
2629 * @param {string} [subfeature]
2630 * Some feature classes like `hostapd` provide sub-feature flags,
2631 * such as `sae` or `11w` support. The `subfeature` argument can
2632 * be used to query these.
2633 *
2634 * @return {boolean|null}
2635 * Return `true` if the queried feature (and sub-feature) is available
2636 * or `false` if the requested feature isn't present or known.
2637 * Return `null` when a sub-feature was queried for a feature which
2638 * has no sub-features.
2639 */
2640 hasSystemFeature: function() {
2641 var ft = sysFeatures[arguments[0]];
2642
2643 if (arguments.length == 2)
2644 return this.isObject(ft) ? ft[arguments[1]] : null;
2645
2646 return (ft != null && ft != false);
2647 },
2648
2649 /* private */
2650 notifySessionExpiry: function() {
2651 Poll.stop();
2652
2653 classes.ui.showModal(_('Session expired'), [
2654 E('div', { class: 'alert-message warning' },
2655 _('A new login is required since the authentication session expired.')),
2656 E('div', { class: 'right' },
2657 E('div', {
2658 class: 'btn primary',
2659 click: function() {
2660 var loc = window.location;
2661 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
2662 }
2663 }, _('To login…')))
2664 ]);
2665
2666 LuCI.prototype.raise('SessionError', 'Login session is expired');
2667 },
2668
2669 /* private */
2670 setupDOM: function(res) {
2671 var domEv = res[0],
2672 uiClass = res[1],
2673 rpcClass = res[2],
2674 formClass = res[3],
2675 rpcBaseURL = res[4];
2676
2677 rpcClass.setBaseURL(rpcBaseURL);
2678
2679 rpcClass.addInterceptor(function(msg, req) {
2680 if (!LuCI.prototype.isObject(msg) ||
2681 !LuCI.prototype.isObject(msg.error) ||
2682 msg.error.code != -32002)
2683 return;
2684
2685 if (!LuCI.prototype.isObject(req) ||
2686 (req.object == 'session' && req.method == 'access'))
2687 return;
2688
2689 return rpcClass.declare({
2690 'object': 'session',
2691 'method': 'access',
2692 'params': [ 'scope', 'object', 'function' ],
2693 'expect': { access: true }
2694 })('uci', 'luci', 'read').catch(LuCI.prototype.notifySessionExpiry);
2695 });
2696
2697 Request.addInterceptor(function(res) {
2698 var isDenied = false;
2699
2700 if (res.status == 403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
2701 isDenied = true;
2702
2703 if (!isDenied)
2704 return;
2705
2706 LuCI.prototype.notifySessionExpiry();
2707 });
2708
2709 document.addEventListener('poll-start', function(ev) {
2710 uiClass.showIndicator('poll-status', _('Refreshing'), function(ev) {
2711 Request.poll.active() ? Request.poll.stop() : Request.poll.start();
2712 });
2713 });
2714
2715 document.addEventListener('poll-stop', function(ev) {
2716 uiClass.showIndicator('poll-status', _('Paused'), null, 'inactive');
2717 });
2718
2719 return Promise.all([
2720 this.probeSystemFeatures(),
2721 this.probePreloadClasses()
2722 ]).finally(LuCI.prototype.bind(function() {
2723 var tasks = [];
2724
2725 if (Array.isArray(preloadClasses))
2726 for (var i = 0; i < preloadClasses.length; i++)
2727 tasks.push(this.require(preloadClasses[i]));
2728
2729 return Promise.all(tasks);
2730 }, this)).finally(this.initDOM);
2731 },
2732
2733 /* private */
2734 initDOM: function() {
2735 originalCBIInit();
2736 Poll.start();
2737 document.dispatchEvent(new CustomEvent('luci-loaded'));
2738 },
2739
2740 /**
2741 * The `env` object holds environment settings used by LuCI, such
2742 * as request timeouts, base URLs etc.
2743 *
2744 * @instance
2745 * @memberof LuCI
2746 */
2747 env: env,
2748
2749 /**
2750 * Construct an absolute filesystem path relative to the server
2751 * document root.
2752 *
2753 * @instance
2754 * @memberof LuCI
2755 *
2756 * @param {...string} [parts]
2757 * An array of parts to join into a path.
2758 *
2759 * @return {string}
2760 * Return the joined path.
2761 */
2762 fspath: function(/* ... */) {
2763 var path = env.documentroot;
2764
2765 for (var i = 0; i < arguments.length; i++)
2766 path += '/' + arguments[i];
2767
2768 var p = path.replace(/\/+$/, '').replace(/\/+/g, '/').split(/\//),
2769 res = [];
2770
2771 for (var i = 0; i < p.length; i++)
2772 if (p[i] == '..')
2773 res.pop();
2774 else if (p[i] != '.')
2775 res.push(p[i]);
2776
2777 return res.join('/');
2778 },
2779
2780 /**
2781 * Construct a relative URL path from the given prefix and parts.
2782 * The resulting URL is guaranteed to only contain the characters
2783 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2784 * as `/` for the path separator.
2785 *
2786 * @instance
2787 * @memberof LuCI
2788 *
2789 * @param {string} [prefix]
2790 * The prefix to join the given parts with. If the `prefix` is
2791 * omitted, it defaults to an empty string.
2792 *
2793 * @param {string[]} [parts]
2794 * An array of parts to join into an URL path. Parts may contain
2795 * slashes and any of the other characters mentioned above.
2796 *
2797 * @return {string}
2798 * Return the joined URL path.
2799 */
2800 path: function(prefix, parts) {
2801 var url = [ prefix || '' ];
2802
2803 for (var i = 0; i < parts.length; i++)
2804 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
2805 url.push('/', parts[i]);
2806
2807 if (url.length === 1)
2808 url.push('/');
2809
2810 return url.join('');
2811 },
2812
2813 /**
2814 * Construct an URL pathrelative to the script path of the server
2815 * side LuCI application (usually `/cgi-bin/luci`).
2816 *
2817 * The resulting URL is guaranteed to only contain the characters
2818 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2819 * as `/` for the path separator.
2820 *
2821 * @instance
2822 * @memberof LuCI
2823 *
2824 * @param {string[]} [parts]
2825 * An array of parts to join into an URL path. Parts may contain
2826 * slashes and any of the other characters mentioned above.
2827 *
2828 * @return {string}
2829 * Returns the resulting URL path.
2830 */
2831 url: function() {
2832 return this.path(env.scriptname, arguments);
2833 },
2834
2835 /**
2836 * Construct an URL path relative to the global static resource path
2837 * of the LuCI ui (usually `/luci-static/resources`).
2838 *
2839 * The resulting URL is guaranteed to only contain the characters
2840 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2841 * as `/` for the path separator.
2842 *
2843 * @instance
2844 * @memberof LuCI
2845 *
2846 * @param {string[]} [parts]
2847 * An array of parts to join into an URL path. Parts may contain
2848 * slashes and any of the other characters mentioned above.
2849 *
2850 * @return {string}
2851 * Returns the resulting URL path.
2852 */
2853 resource: function() {
2854 return this.path(env.resource, arguments);
2855 },
2856
2857 /**
2858 * Construct an URL path relative to the media resource path of the
2859 * LuCI ui (usually `/luci-static/$theme_name`).
2860 *
2861 * The resulting URL is guaranteed to only contain the characters
2862 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2863 * as `/` for the path separator.
2864 *
2865 * @instance
2866 * @memberof LuCI
2867 *
2868 * @param {string[]} [parts]
2869 * An array of parts to join into an URL path. Parts may contain
2870 * slashes and any of the other characters mentioned above.
2871 *
2872 * @return {string}
2873 * Returns the resulting URL path.
2874 */
2875 media: function() {
2876 return this.path(env.media, arguments);
2877 },
2878
2879 /**
2880 * Return the complete URL path to the current view.
2881 *
2882 * @instance
2883 * @memberof LuCI
2884 *
2885 * @return {string}
2886 * Returns the URL path to the current view.
2887 */
2888 location: function() {
2889 return this.path(env.scriptname, env.requestpath);
2890 },
2891
2892
2893 /**
2894 * Tests whether the passed argument is a JavaScript object.
2895 * This function is meant to be an object counterpart to the
2896 * standard `Array.isArray()` function.
2897 *
2898 * @instance
2899 * @memberof LuCI
2900 *
2901 * @param {*} [val]
2902 * The value to test
2903 *
2904 * @return {boolean}
2905 * Returns `true` if the given value is of type object and
2906 * not `null`, else returns `false`.
2907 */
2908 isObject: function(val) {
2909 return (val != null && typeof(val) == 'object');
2910 },
2911
2912 /**
2913 * Return an array of sorted object keys, optionally sorted by
2914 * a different key or a different sorting mode.
2915 *
2916 * @instance
2917 * @memberof LuCI
2918 *
2919 * @param {object} obj
2920 * The object to extract the keys from. If the given value is
2921 * not an object, the function will return an empty array.
2922 *
2923 * @param {string} [key]
2924 * Specifies the key to order by. This is mainly useful for
2925 * nested objects of objects or objects of arrays when sorting
2926 * shall not be performed by the primary object keys but by
2927 * some other key pointing to a value within the nested values.
2928 *
2929 * @param {string} [sortmode]
2930 * May be either `addr` or `num` to override the natural
2931 * lexicographic sorting with a sorting suitable for IP/MAC style
2932 * addresses or numeric values respectively.
2933 *
2934 * @return {string[]}
2935 * Returns an array containing the sorted keys of the given object.
2936 */
2937 sortedKeys: function(obj, key, sortmode) {
2938 if (obj == null || typeof(obj) != 'object')
2939 return [];
2940
2941 return Object.keys(obj).map(function(e) {
2942 var v = (key != null) ? obj[e][key] : e;
2943
2944 switch (sortmode) {
2945 case 'addr':
2946 v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
2947 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
2948 break;
2949
2950 case 'num':
2951 v = (v != null) ? +v : null;
2952 break;
2953 }
2954
2955 return [ e, v ];
2956 }).filter(function(e) {
2957 return (e[1] != null);
2958 }).sort(function(a, b) {
2959 return (a[1] > b[1]);
2960 }).map(function(e) {
2961 return e[0];
2962 });
2963 },
2964
2965 /**
2966 * Converts the given value to an array. If the given value is of
2967 * type array, it is returned as-is, values of type object are
2968 * returned as one-element array containing the object, empty
2969 * strings and `null` values are returned as empty array, all other
2970 * values are converted using `String()`, trimmed, split on white
2971 * space and returned as array.
2972 *
2973 * @instance
2974 * @memberof LuCI
2975 *
2976 * @param {*} val
2977 * The value to convert into an array.
2978 *
2979 * @return {Array<*>}
2980 * Returns the resulting array.
2981 */
2982 toArray: function(val) {
2983 if (val == null)
2984 return [];
2985 else if (Array.isArray(val))
2986 return val;
2987 else if (typeof(val) == 'object')
2988 return [ val ];
2989
2990 var s = String(val).trim();
2991
2992 if (s == '')
2993 return [];
2994
2995 return s.split(/\s+/);
2996 },
2997
2998 /**
2999 * Returns a promise resolving with either the given value or or with
3000 * the given default in case the input value is a rejecting promise.
3001 *
3002 * @instance
3003 * @memberof LuCI
3004 *
3005 * @param {*} value
3006 * The value to resolve the promise with.
3007 *
3008 * @param {*} defvalue
3009 * The default value to resolve the promise with in case the given
3010 * input value is a rejecting promise.
3011 *
3012 * @returns {Promise<*>}
3013 * Returns a new promise resolving either to the given input value or
3014 * to the given default value on error.
3015 */
3016 resolveDefault: function(value, defvalue) {
3017 return Promise.resolve(value).catch(function() { return defvalue });
3018 },
3019
3020 /**
3021 * The request callback function is invoked whenever an HTTP
3022 * reply to a request made using the `L.get()`, `L.post()` or
3023 * `L.poll()` function is timed out or received successfully.
3024 *
3025 * @instance
3026 * @memberof LuCI
3027 *
3028 * @callback LuCI.requestCallbackFn
3029 * @param {XMLHTTPRequest} xhr
3030 * The XMLHTTPRequest instance used to make the request.
3031 *
3032 * @param {*} data
3033 * The response JSON if the response could be parsed as such,
3034 * else `null`.
3035 *
3036 * @param {number} duration
3037 * The total duration of the request in milliseconds.
3038 */
3039
3040 /**
3041 * Issues a GET request to the given url and invokes the specified
3042 * callback function. The function is a wrapper around
3043 * {@link LuCI.request#request Request.request()}.
3044 *
3045 * @deprecated
3046 * @instance
3047 * @memberof LuCI
3048 *
3049 * @param {string} url
3050 * The URL to request.
3051 *
3052 * @param {Object<string, string>} [args]
3053 * Additional query string arguments to append to the URL.
3054 *
3055 * @param {LuCI.requestCallbackFn} cb
3056 * The callback function to invoke when the request finishes.
3057 *
3058 * @return {Promise<null>}
3059 * Returns a promise resolving to `null` when concluded.
3060 */
3061 get: function(url, args, cb) {
3062 return this.poll(null, url, args, cb, false);
3063 },
3064
3065 /**
3066 * Issues a POST request to the given url and invokes the specified
3067 * callback function. The function is a wrapper around
3068 * {@link LuCI.request#request Request.request()}. The request is
3069 * sent using `application/x-www-form-urlencoded` encoding and will
3070 * contain a field `token` with the current value of `LuCI.env.token`
3071 * by default.
3072 *
3073 * @deprecated
3074 * @instance
3075 * @memberof LuCI
3076 *
3077 * @param {string} url
3078 * The URL to request.
3079 *
3080 * @param {Object<string, string>} [args]
3081 * Additional post arguments to append to the request body.
3082 *
3083 * @param {LuCI.requestCallbackFn} cb
3084 * The callback function to invoke when the request finishes.
3085 *
3086 * @return {Promise<null>}
3087 * Returns a promise resolving to `null` when concluded.
3088 */
3089 post: function(url, args, cb) {
3090 return this.poll(null, url, args, cb, true);
3091 },
3092
3093 /**
3094 * Register a polling HTTP request that invokes the specified
3095 * callback function. The function is a wrapper around
3096 * {@link LuCI.request.poll#add Request.poll.add()}.
3097 *
3098 * @deprecated
3099 * @instance
3100 * @memberof LuCI
3101 *
3102 * @param {number} interval
3103 * The poll interval to use. If set to a value less than or equal
3104 * to `0`, it will default to the global poll interval configured
3105 * in `LuCI.env.pollinterval`.
3106 *
3107 * @param {string} url
3108 * The URL to request.
3109 *
3110 * @param {Object<string, string>} [args]
3111 * Specifies additional arguments for the request. For GET requests,
3112 * the arguments are appended to the URL as query string, for POST
3113 * requests, they'll be added to the request body.
3114 *
3115 * @param {LuCI.requestCallbackFn} cb
3116 * The callback function to invoke whenever a request finishes.
3117 *
3118 * @param {boolean} [post=false]
3119 * When set to `false` or not specified, poll requests will be made
3120 * using the GET method. When set to `true`, POST requests will be
3121 * issued. In case of POST requests, the request body will contain
3122 * an argument `token` with the current value of `LuCI.env.token` by
3123 * default, regardless of the parameters specified with `args`.
3124 *
3125 * @return {function}
3126 * Returns the internally created function that has been passed to
3127 * {@link LuCI.request.poll#add Request.poll.add()}. This value can
3128 * be passed to {@link LuCI.poll.remove Poll.remove()} to remove the
3129 * polling request.
3130 */
3131 poll: function(interval, url, args, cb, post) {
3132 if (interval !== null && interval <= 0)
3133 interval = env.pollinterval;
3134
3135 var data = post ? { token: env.token } : null,
3136 method = post ? 'POST' : 'GET';
3137
3138 if (!/^(?:\/|\S+:\/\/)/.test(url))
3139 url = this.url(url);
3140
3141 if (args != null)
3142 data = Object.assign(data || {}, args);
3143
3144 if (interval !== null)
3145 return Request.poll.add(interval, url, { method: method, query: data }, cb);
3146 else
3147 return Request.request(url, { method: method, query: data })
3148 .then(function(res) {
3149 var json = null;
3150 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
3151 try { json = res.json() } catch(e) {}
3152 cb(res.xhr, json, res.duration);
3153 });
3154 },
3155
3156 /**
3157 * Check whether a view has sufficient permissions.
3158 *
3159 * @return {boolean|null}
3160 * Returns `null` if the current session has no permission at all to
3161 * load resources required by the view. Returns `false` if readonly
3162 * permissions are granted or `true` if at least one required ACL
3163 * group is granted with write permissions.
3164 */
3165 hasViewPermission: function() {
3166 if (!this.isObject(env.nodespec) || !env.nodespec.satisfied)
3167 return null;
3168
3169 return !env.nodespec.readonly;
3170 },
3171
3172 /**
3173 * Deprecated wrapper around {@link LuCI.poll.remove Poll.remove()}.
3174 *
3175 * @deprecated
3176 * @instance
3177 * @memberof LuCI
3178 *
3179 * @param {function} entry
3180 * The polling function to remove.
3181 *
3182 * @return {boolean}
3183 * Returns `true` when the function has been removed or `false` if
3184 * it could not be found.
3185 */
3186 stop: function(entry) { return Poll.remove(entry) },
3187
3188 /**
3189 * Deprecated wrapper around {@link LuCI.poll.stop Poll.stop()}.
3190 *
3191 * @deprecated
3192 * @instance
3193 * @memberof LuCI
3194 *
3195 * @return {boolean}
3196 * Returns `true` when the polling loop has been stopped or `false`
3197 * when it didn't run to begin with.
3198 */
3199 halt: function() { return Poll.stop() },
3200
3201 /**
3202 * Deprecated wrapper around {@link LuCI.poll.start Poll.start()}.
3203 *
3204 * @deprecated
3205 * @instance
3206 * @memberof LuCI
3207 *
3208 * @return {boolean}
3209 * Returns `true` when the polling loop has been started or `false`
3210 * when it was already running.
3211 */
3212 run: function() { return Poll.start() },
3213
3214 /**
3215 * Legacy `L.dom` class alias. New view code should use `'require dom';`
3216 * to request the `LuCI.dom` class.
3217 *
3218 * @instance
3219 * @memberof LuCI
3220 * @deprecated
3221 */
3222 dom: DOM,
3223
3224 /**
3225 * Legacy `L.view` class alias. New view code should use `'require view';`
3226 * to request the `LuCI.view` class.
3227 *
3228 * @instance
3229 * @memberof LuCI
3230 * @deprecated
3231 */
3232 view: View,
3233
3234 /**
3235 * Legacy `L.Poll` class alias. New view code should use `'require poll';`
3236 * to request the `LuCI.poll` class.
3237 *
3238 * @instance
3239 * @memberof LuCI
3240 * @deprecated
3241 */
3242 Poll: Poll,
3243
3244 /**
3245 * Legacy `L.Request` class alias. New view code should use `'require request';`
3246 * to request the `LuCI.request` class.
3247 *
3248 * @instance
3249 * @memberof LuCI
3250 * @deprecated
3251 */
3252 Request: Request,
3253
3254 /**
3255 * Legacy `L.Class` class alias. New view code should use `'require baseclass';`
3256 * to request the `LuCI.baseclass` class.
3257 *
3258 * @instance
3259 * @memberof LuCI
3260 * @deprecated
3261 */
3262 Class: Class
3263 });
3264
3265 /**
3266 * @class xhr
3267 * @memberof LuCI
3268 * @deprecated
3269 * @classdesc
3270 *
3271 * The `LuCI.xhr` class is a legacy compatibility shim for the
3272 * functionality formerly provided by `xhr.js`. It is registered as global
3273 * `window.XHR` symbol for compatibility with legacy code.
3274 *
3275 * New code should use {@link LuCI.request} instead to implement HTTP
3276 * request handling.
3277 */
3278 var XHR = Class.extend(/** @lends LuCI.xhr.prototype */ {
3279 __name__: 'LuCI.xhr',
3280 __init__: function() {
3281 if (window.console && console.debug)
3282 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
3283 },
3284
3285 _response: function(cb, res, json, duration) {
3286 if (this.active)
3287 cb(res, json, duration);
3288 delete this.active;
3289 },
3290
3291 /**
3292 * This function is a legacy wrapper around
3293 * {@link LuCI#get LuCI.get()}.
3294 *
3295 * @instance
3296 * @deprecated
3297 * @memberof LuCI.xhr
3298 *
3299 * @param {string} url
3300 * The URL to request
3301 *
3302 * @param {Object} [data]
3303 * Additional query string data
3304 *
3305 * @param {LuCI.requestCallbackFn} [callback]
3306 * Callback function to invoke on completion
3307 *
3308 * @param {number} [timeout]
3309 * Request timeout to use
3310 *
3311 * @return {Promise<null>}
3312 */
3313 get: function(url, data, callback, timeout) {
3314 this.active = true;
3315 LuCI.prototype.get(url, data, this._response.bind(this, callback), timeout);
3316 },
3317
3318 /**
3319 * This function is a legacy wrapper around
3320 * {@link LuCI#post LuCI.post()}.
3321 *
3322 * @instance
3323 * @deprecated
3324 * @memberof LuCI.xhr
3325 *
3326 * @param {string} url
3327 * The URL to request
3328 *
3329 * @param {Object} [data]
3330 * Additional data to append to the request body.
3331 *
3332 * @param {LuCI.requestCallbackFn} [callback]
3333 * Callback function to invoke on completion
3334 *
3335 * @param {number} [timeout]
3336 * Request timeout to use
3337 *
3338 * @return {Promise<null>}
3339 */
3340 post: function(url, data, callback, timeout) {
3341 this.active = true;
3342 LuCI.prototype.post(url, data, this._response.bind(this, callback), timeout);
3343 },
3344
3345 /**
3346 * Cancels a running request.
3347 *
3348 * This function does not actually cancel the underlying
3349 * `XMLHTTPRequest` request but it sets a flag which prevents the
3350 * invocation of the callback function when the request eventually
3351 * finishes or timed out.
3352 *
3353 * @instance
3354 * @deprecated
3355 * @memberof LuCI.xhr
3356 */
3357 cancel: function() { delete this.active },
3358
3359 /**
3360 * Checks the running state of the request.
3361 *
3362 * @instance
3363 * @deprecated
3364 * @memberof LuCI.xhr
3365 *
3366 * @returns {boolean}
3367 * Returns `true` if the request is still running or `false` if it
3368 * already completed.
3369 */
3370 busy: function() { return (this.active === true) },
3371
3372 /**
3373 * Ignored for backwards compatibility.
3374 *
3375 * This function does nothing.
3376 *
3377 * @instance
3378 * @deprecated
3379 * @memberof LuCI.xhr
3380 */
3381 abort: function() {},
3382
3383 /**
3384 * Existing for backwards compatibility.
3385 *
3386 * This function simply throws an `InternalError` when invoked.
3387 *
3388 * @instance
3389 * @deprecated
3390 * @memberof LuCI.xhr
3391 *
3392 * @throws {InternalError}
3393 * Throws an `InternalError` with the message `Not implemented`
3394 * when invoked.
3395 */
3396 send_form: function() { LuCI.prototype.error('InternalError', 'Not implemented') },
3397 });
3398
3399 XHR.get = function() { return LuCI.prototype.get.apply(LuCI.prototype, arguments) };
3400 XHR.post = function() { return LuCI.prototype.post.apply(LuCI.prototype, arguments) };
3401 XHR.poll = function() { return LuCI.prototype.poll.apply(LuCI.prototype, arguments) };
3402 XHR.stop = Request.poll.remove.bind(Request.poll);
3403 XHR.halt = Request.poll.stop.bind(Request.poll);
3404 XHR.run = Request.poll.start.bind(Request.poll);
3405 XHR.running = Request.poll.active.bind(Request.poll);
3406
3407 window.XHR = XHR;
3408 window.LuCI = LuCI;
3409 })(window, document);