78e8b8b30bb010f6c409556a6efd75cffe1dcbaa
[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 milliseconds.
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(opt.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 var res_json = null;
986 try {
987 res_json = res.json();
988 }
989 catch (err) {}
990
991 callback(res, res_json, res.duration);
992 });
993 };
994
995 return (Poll.add(fn, ival) ? fn : null);
996 },
997
998 /**
999 * Remove a polling request that has been previously added using `add()`.
1000 * This function is essentially a wrapper around
1001 * {@link LuCI.poll.remove LuCI.poll.remove()}.
1002 *
1003 * @instance
1004 * @memberof LuCI.request.poll
1005 * @param {function} entry
1006 * The poll function returned by {@link LuCI.request.poll#add add()}.
1007 *
1008 * @returns {boolean}
1009 * Returns `true` if any function has been removed, else `false`.
1010 */
1011 remove: function(entry) { return Poll.remove(entry) },
1012
1013 /**
1014 * Alias for {@link LuCI.poll.start LuCI.poll.start()}.
1015 *
1016 * @instance
1017 * @memberof LuCI.request.poll
1018 */
1019 start: function() { return Poll.start() },
1020
1021 /**
1022 * Alias for {@link LuCI.poll.stop LuCI.poll.stop()}.
1023 *
1024 * @instance
1025 * @memberof LuCI.request.poll
1026 */
1027 stop: function() { return Poll.stop() },
1028
1029 /**
1030 * Alias for {@link LuCI.poll.active LuCI.poll.active()}.
1031 *
1032 * @instance
1033 * @memberof LuCI.request.poll
1034 */
1035 active: function() { return Poll.active() }
1036 }
1037 });
1038
1039 /**
1040 * @class poll
1041 * @memberof LuCI
1042 * @hideconstructor
1043 * @classdesc
1044 *
1045 * The `Poll` class allows registering and unregistering poll actions,
1046 * as well as starting, stopping and querying the state of the polling
1047 * loop.
1048 */
1049 var Poll = Class.singleton(/** @lends LuCI.poll.prototype */ {
1050 __name__: 'LuCI.poll',
1051
1052 queue: [],
1053
1054 /**
1055 * Add a new operation to the polling loop. If the polling loop is not
1056 * already started at this point, it will be implicitely started.
1057 *
1058 * @instance
1059 * @memberof LuCI.poll
1060 * @param {function} fn
1061 * The function to invoke on each poll interval.
1062 *
1063 * @param {number} interval
1064 * The poll interval in seconds.
1065 *
1066 * @throws {TypeError}
1067 * Throws `TypeError` when an invalid interval was passed.
1068 *
1069 * @returns {boolean}
1070 * Returns `true` if the function has been added or `false` if it
1071 * already is registered.
1072 */
1073 add: function(fn, interval) {
1074 if (interval == null || interval <= 0)
1075 interval = env.pollinterval || null;
1076
1077 if (isNaN(interval) || typeof(fn) != 'function')
1078 throw new TypeError('Invalid argument to LuCI.poll.add()');
1079
1080 for (var i = 0; i < this.queue.length; i++)
1081 if (this.queue[i].fn === fn)
1082 return false;
1083
1084 var e = {
1085 r: true,
1086 i: interval >>> 0,
1087 fn: fn
1088 };
1089
1090 this.queue.push(e);
1091
1092 if (this.tick != null && !this.active())
1093 this.start();
1094
1095 return true;
1096 },
1097
1098 /**
1099 * Remove an operation from the polling loop. If no further operatons
1100 * are registered, the polling loop is implicitely stopped.
1101 *
1102 * @instance
1103 * @memberof LuCI.poll
1104 * @param {function} fn
1105 * The function to remove.
1106 *
1107 * @throws {TypeError}
1108 * Throws `TypeError` when the given argument isn't a function.
1109 *
1110 * @returns {boolean}
1111 * Returns `true` if the function has been removed or `false` if it
1112 * wasn't found.
1113 */
1114 remove: function(fn) {
1115 if (typeof(fn) != 'function')
1116 throw new TypeError('Invalid argument to LuCI.poll.remove()');
1117
1118 var len = this.queue.length;
1119
1120 for (var i = len; i > 0; i--)
1121 if (this.queue[i-1].fn === fn)
1122 this.queue.splice(i-1, 1);
1123
1124 if (!this.queue.length && this.stop())
1125 this.tick = 0;
1126
1127 return (this.queue.length != len);
1128 },
1129
1130 /**
1131 * (Re)start the polling loop. Dispatches a custom `poll-start` event
1132 * to the `document` object upon successful start.
1133 *
1134 * @instance
1135 * @memberof LuCI.poll
1136 * @returns {boolean}
1137 * Returns `true` if polling has been started (or if no functions
1138 * where registered) or `false` when the polling loop already runs.
1139 */
1140 start: function() {
1141 if (this.active())
1142 return false;
1143
1144 this.tick = 0;
1145
1146 if (this.queue.length) {
1147 this.timer = window.setInterval(this.step, 1000);
1148 this.step();
1149 document.dispatchEvent(new CustomEvent('poll-start'));
1150 }
1151
1152 return true;
1153 },
1154
1155 /**
1156 * Stop the polling loop. Dispatches a custom `poll-stop` event
1157 * to the `document` object upon successful stop.
1158 *
1159 * @instance
1160 * @memberof LuCI.poll
1161 * @returns {boolean}
1162 * Returns `true` if polling has been stopped or `false` if it din't
1163 * run to begin with.
1164 */
1165 stop: function() {
1166 if (!this.active())
1167 return false;
1168
1169 document.dispatchEvent(new CustomEvent('poll-stop'));
1170 window.clearInterval(this.timer);
1171 delete this.timer;
1172 delete this.tick;
1173 return true;
1174 },
1175
1176 /* private */
1177 step: function() {
1178 for (var i = 0, e = null; (e = Poll.queue[i]) != null; i++) {
1179 if ((Poll.tick % e.i) != 0)
1180 continue;
1181
1182 if (!e.r)
1183 continue;
1184
1185 e.r = false;
1186
1187 Promise.resolve(e.fn()).finally((function() { this.r = true }).bind(e));
1188 }
1189
1190 Poll.tick = (Poll.tick + 1) % Math.pow(2, 32);
1191 },
1192
1193 /**
1194 * Test whether the polling loop is running.
1195 *
1196 * @instance
1197 * @memberof LuCI.poll
1198 * @returns {boolean} - Returns `true` if polling is active, else `false`.
1199 */
1200 active: function() {
1201 return (this.timer != null);
1202 }
1203 });
1204
1205 /**
1206 * @class dom
1207 * @memberof LuCI
1208 * @hideconstructor
1209 * @classdesc
1210 *
1211 * The `dom` class provides convenience method for creating and
1212 * manipulating DOM elements.
1213 *
1214 * To import the class in views, use `'require dom'`, to import it in
1215 * external JavaScript, use `L.require("dom").then(...)`.
1216 */
1217 var DOM = Class.singleton(/** @lends LuCI.dom.prototype */ {
1218 __name__: 'LuCI.dom',
1219
1220 /**
1221 * Tests whether the given argument is a valid DOM `Node`.
1222 *
1223 * @instance
1224 * @memberof LuCI.dom
1225 * @param {*} e
1226 * The value to test.
1227 *
1228 * @returns {boolean}
1229 * Returns `true` if the value is a DOM `Node`, else `false`.
1230 */
1231 elem: function(e) {
1232 return (e != null && typeof(e) == 'object' && 'nodeType' in e);
1233 },
1234
1235 /**
1236 * Parses a given string as HTML and returns the first child node.
1237 *
1238 * @instance
1239 * @memberof LuCI.dom
1240 * @param {string} s
1241 * A string containing an HTML fragment to parse. Note that only
1242 * the first result of the resulting structure is returned, so an
1243 * input value of `<div>foo</div> <div>bar</div>` will only return
1244 * the first `div` element node.
1245 *
1246 * @returns {Node}
1247 * Returns the first DOM `Node` extracted from the HTML fragment or
1248 * `null` on parsing failures or if no element could be found.
1249 */
1250 parse: function(s) {
1251 var elem = null;
1252
1253 try {
1254 domParser = domParser || new DOMParser();
1255 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1256 }
1257 catch(e) {}
1258
1259 return elem;
1260 },
1261
1262 /**
1263 * Tests whether a given `Node` matches the given query selector.
1264 *
1265 * This function is a convenience wrapper around the standard
1266 * `Node.matches("selector")` function with the added benefit that
1267 * the `node` argument may be a non-`Node` value, in which case
1268 * this function simply returns `false`.
1269 *
1270 * @instance
1271 * @memberof LuCI.dom
1272 * @param {*} node
1273 * The `Node` argument to test the selector against.
1274 *
1275 * @param {string} [selector]
1276 * The query selector expression to test against the given node.
1277 *
1278 * @returns {boolean}
1279 * Returns `true` if the given node matches the specified selector
1280 * or `false` when the node argument is no valid DOM `Node` or the
1281 * selector didn't match.
1282 */
1283 matches: function(node, selector) {
1284 var m = this.elem(node) ? node.matches || node.msMatchesSelector : null;
1285 return m ? m.call(node, selector) : false;
1286 },
1287
1288 /**
1289 * Returns the closest parent node that matches the given query
1290 * selector expression.
1291 *
1292 * This function is a convenience wrapper around the standard
1293 * `Node.closest("selector")` function with the added benefit that
1294 * the `node` argument may be a non-`Node` value, in which case
1295 * this function simply returns `null`.
1296 *
1297 * @instance
1298 * @memberof LuCI.dom
1299 * @param {*} node
1300 * The `Node` argument to find the closest parent for.
1301 *
1302 * @param {string} [selector]
1303 * The query selector expression to test against each parent.
1304 *
1305 * @returns {Node|null}
1306 * Returns the closest parent node matching the selector or
1307 * `null` when the node argument is no valid DOM `Node` or the
1308 * selector didn't match any parent.
1309 */
1310 parent: function(node, selector) {
1311 if (this.elem(node) && node.closest)
1312 return node.closest(selector);
1313
1314 while (this.elem(node))
1315 if (this.matches(node, selector))
1316 return node;
1317 else
1318 node = node.parentNode;
1319
1320 return null;
1321 },
1322
1323 /**
1324 * Appends the given children data to the given node.
1325 *
1326 * @instance
1327 * @memberof LuCI.dom
1328 * @param {*} node
1329 * The `Node` argument to append the children to.
1330 *
1331 * @param {*} [children]
1332 * The childrens to append to the given node.
1333 *
1334 * When `children` is an array, then each item of the array
1335 * will be either appended as child element or text node,
1336 * depending on whether the item is a DOM `Node` instance or
1337 * some other non-`null` value. Non-`Node`, non-`null` values
1338 * will be converted to strings first before being passed as
1339 * argument to `createTextNode()`.
1340 *
1341 * When `children` is a function, it will be invoked with
1342 * the passed `node` argument as sole parameter and the `append`
1343 * function will be invoked again, with the given `node` argument
1344 * as first and the return value of the `children` function as
1345 * second parameter.
1346 *
1347 * When `children` is is a DOM `Node` instance, it will be
1348 * appended to the given `node`.
1349 *
1350 * When `children` is any other non-`null` value, it will be
1351 * converted to a string and appened to the `innerHTML` property
1352 * of the given `node`.
1353 *
1354 * @returns {Node|null}
1355 * Returns the last children `Node` appended to the node or `null`
1356 * if either the `node` argument was no valid DOM `node` or if the
1357 * `children` was `null` or didn't result in further DOM nodes.
1358 */
1359 append: function(node, children) {
1360 if (!this.elem(node))
1361 return null;
1362
1363 if (Array.isArray(children)) {
1364 for (var i = 0; i < children.length; i++)
1365 if (this.elem(children[i]))
1366 node.appendChild(children[i]);
1367 else if (children !== null && children !== undefined)
1368 node.appendChild(document.createTextNode('' + children[i]));
1369
1370 return node.lastChild;
1371 }
1372 else if (typeof(children) === 'function') {
1373 return this.append(node, children(node));
1374 }
1375 else if (this.elem(children)) {
1376 return node.appendChild(children);
1377 }
1378 else if (children !== null && children !== undefined) {
1379 node.innerHTML = '' + children;
1380 return node.lastChild;
1381 }
1382
1383 return null;
1384 },
1385
1386 /**
1387 * Replaces the content of the given node with the given children.
1388 *
1389 * This function first removes any children of the given DOM
1390 * `Node` and then adds the given given children following the
1391 * rules outlined below.
1392 *
1393 * @instance
1394 * @memberof LuCI.dom
1395 * @param {*} node
1396 * The `Node` argument to replace the children of.
1397 *
1398 * @param {*} [children]
1399 * The childrens to replace into the given node.
1400 *
1401 * When `children` is an array, then each item of the array
1402 * will be either appended as child element or text node,
1403 * depending on whether the item is a DOM `Node` instance or
1404 * some other non-`null` value. Non-`Node`, non-`null` values
1405 * will be converted to strings first before being passed as
1406 * argument to `createTextNode()`.
1407 *
1408 * When `children` is a function, it will be invoked with
1409 * the passed `node` argument as sole parameter and the `append`
1410 * function will be invoked again, with the given `node` argument
1411 * as first and the return value of the `children` function as
1412 * second parameter.
1413 *
1414 * When `children` is is a DOM `Node` instance, it will be
1415 * appended to the given `node`.
1416 *
1417 * When `children` is any other non-`null` value, it will be
1418 * converted to a string and appened to the `innerHTML` property
1419 * of the given `node`.
1420 *
1421 * @returns {Node|null}
1422 * Returns the last children `Node` appended to the node or `null`
1423 * if either the `node` argument was no valid DOM `node` or if the
1424 * `children` was `null` or didn't result in further DOM nodes.
1425 */
1426 content: function(node, children) {
1427 if (!this.elem(node))
1428 return null;
1429
1430 var dataNodes = node.querySelectorAll('[data-idref]');
1431
1432 for (var i = 0; i < dataNodes.length; i++)
1433 delete this.registry[dataNodes[i].getAttribute('data-idref')];
1434
1435 while (node.firstChild)
1436 node.removeChild(node.firstChild);
1437
1438 return this.append(node, children);
1439 },
1440
1441 /**
1442 * Sets attributes or registers event listeners on element nodes.
1443 *
1444 * @instance
1445 * @memberof LuCI.dom
1446 * @param {*} node
1447 * The `Node` argument to set the attributes or add the event
1448 * listeners for. When the given `node` value is not a valid
1449 * DOM `Node`, the function returns and does nothing.
1450 *
1451 * @param {string|Object<string, *>} key
1452 * Specifies either the attribute or event handler name to use,
1453 * or an object containing multiple key, value pairs which are
1454 * each added to the node as either attribute or event handler,
1455 * depending on the respective value.
1456 *
1457 * @param {*} [val]
1458 * Specifies the attribute value or event handler function to add.
1459 * If the `key` parameter is an `Object`, this parameter will be
1460 * ignored.
1461 *
1462 * When `val` is of type function, it will be registered as event
1463 * handler on the given `node` with the `key` parameter being the
1464 * event name.
1465 *
1466 * When `val` is of type object, it will be serialized as JSON and
1467 * added as attribute to the given `node`, using the given `key`
1468 * as attribute name.
1469 *
1470 * When `val` is of any other type, it will be added as attribute
1471 * to the given `node` as-is, with the underlying `setAttribute()`
1472 * call implicitely turning it into a string.
1473 */
1474 attr: function(node, key, val) {
1475 if (!this.elem(node))
1476 return null;
1477
1478 var attr = null;
1479
1480 if (typeof(key) === 'object' && key !== null)
1481 attr = key;
1482 else if (typeof(key) === 'string')
1483 attr = {}, attr[key] = val;
1484
1485 for (key in attr) {
1486 if (!attr.hasOwnProperty(key) || attr[key] == null)
1487 continue;
1488
1489 switch (typeof(attr[key])) {
1490 case 'function':
1491 node.addEventListener(key, attr[key]);
1492 break;
1493
1494 case 'object':
1495 node.setAttribute(key, JSON.stringify(attr[key]));
1496 break;
1497
1498 default:
1499 node.setAttribute(key, attr[key]);
1500 }
1501 }
1502 },
1503
1504 /**
1505 * Creates a new DOM `Node` from the given `html`, `attr` and
1506 * `data` parameters.
1507 *
1508 * This function has multiple signatures, it can be either invoked
1509 * in the form `create(html[, attr[, data]])` or in the form
1510 * `create(html[, data])`. The used variant is determined from the
1511 * type of the second argument.
1512 *
1513 * @instance
1514 * @memberof LuCI.dom
1515 * @param {*} html
1516 * Describes the node to create.
1517 *
1518 * When the value of `html` is of type array, a `DocumentFragment`
1519 * node is created and each item of the array is first converted
1520 * to a DOM `Node` by passing it through `create()` and then added
1521 * as child to the fragment.
1522 *
1523 * When the value of `html` is a DOM `Node` instance, no new
1524 * element will be created but the node will be used as-is.
1525 *
1526 * When the value of `html` is a string starting with `<`, it will
1527 * be passed to `dom.parse()` and the resulting value is used.
1528 *
1529 * When the value of `html` is any other string, it will be passed
1530 * to `document.createElement()` for creating a new DOM `Node` of
1531 * the given name.
1532 *
1533 * @param {Object<string, *>} [attr]
1534 * Specifies an Object of key, value pairs to set as attributes
1535 * or event handlers on the created node. Refer to
1536 * {@link LuCI.dom#attr dom.attr()} for details.
1537 *
1538 * @param {*} [data]
1539 * Specifies children to append to the newly created element.
1540 * Refer to {@link LuCI.dom#append dom.append()} for details.
1541 *
1542 * @throws {InvalidCharacterError}
1543 * Throws an `InvalidCharacterError` when the given `html`
1544 * argument contained malformed markup (such as not escaped
1545 * `&` characters in XHTML mode) or when the given node name
1546 * in `html` contains characters which are not legal in DOM
1547 * element names, such as spaces.
1548 *
1549 * @returns {Node}
1550 * Returns the newly created `Node`.
1551 */
1552 create: function() {
1553 var html = arguments[0],
1554 attr = arguments[1],
1555 data = arguments[2],
1556 elem;
1557
1558 if (!(attr instanceof Object) || Array.isArray(attr))
1559 data = attr, attr = null;
1560
1561 if (Array.isArray(html)) {
1562 elem = document.createDocumentFragment();
1563 for (var i = 0; i < html.length; i++)
1564 elem.appendChild(this.create(html[i]));
1565 }
1566 else if (this.elem(html)) {
1567 elem = html;
1568 }
1569 else if (html.charCodeAt(0) === 60) {
1570 elem = this.parse(html);
1571 }
1572 else {
1573 elem = document.createElement(html);
1574 }
1575
1576 if (!elem)
1577 return null;
1578
1579 this.attr(elem, attr);
1580 this.append(elem, data);
1581
1582 return elem;
1583 },
1584
1585 registry: {},
1586
1587 /**
1588 * Attaches or detaches arbitrary data to and from a DOM `Node`.
1589 *
1590 * This function is useful to attach non-string values or runtime
1591 * data that is not serializable to DOM nodes. To decouple data
1592 * from the DOM, values are not added directly to nodes, but
1593 * inserted into a registry instead which is then referenced by a
1594 * string key stored as `data-idref` attribute in the node.
1595 *
1596 * This function has multiple signatures and is sensitive to the
1597 * number of arguments passed to it.
1598 *
1599 * - `dom.data(node)` -
1600 * Fetches all data associated with the given node.
1601 * - `dom.data(node, key)` -
1602 * Fetches a specific key associated with the given node.
1603 * - `dom.data(node, key, val)` -
1604 * Sets a specific key to the given value associated with the
1605 * given node.
1606 * - `dom.data(node, null)` -
1607 * Clears any data associated with the node.
1608 * - `dom.data(node, key, null)` -
1609 * Clears the given key associated with the node.
1610 *
1611 * @instance
1612 * @memberof LuCI.dom
1613 * @param {Node} node
1614 * The DOM `Node` instance to set or retrieve the data for.
1615 *
1616 * @param {string|null} [key]
1617 * This is either a string specifying the key to retrieve, or
1618 * `null` to unset the entire node data.
1619 *
1620 * @param {*|null} [val]
1621 * This is either a non-`null` value to set for a given key or
1622 * `null` to remove the given `key` from the specified node.
1623 *
1624 * @returns {*}
1625 * Returns the get or set value, or `null` when no value could
1626 * be found.
1627 */
1628 data: function(node, key, val) {
1629 if (!node || !node.getAttribute)
1630 return null;
1631
1632 var id = node.getAttribute('data-idref');
1633
1634 /* clear all data */
1635 if (arguments.length > 1 && key == null) {
1636 if (id != null) {
1637 node.removeAttribute('data-idref');
1638 val = this.registry[id]
1639 delete this.registry[id];
1640 return val;
1641 }
1642
1643 return null;
1644 }
1645
1646 /* clear a key */
1647 else if (arguments.length > 2 && key != null && val == null) {
1648 if (id != null) {
1649 val = this.registry[id][key];
1650 delete this.registry[id][key];
1651 return val;
1652 }
1653
1654 return null;
1655 }
1656
1657 /* set a key */
1658 else if (arguments.length > 2 && key != null && val != null) {
1659 if (id == null) {
1660 do { id = Math.floor(Math.random() * 0xffffffff).toString(16) }
1661 while (this.registry.hasOwnProperty(id));
1662
1663 node.setAttribute('data-idref', id);
1664 this.registry[id] = {};
1665 }
1666
1667 return (this.registry[id][key] = val);
1668 }
1669
1670 /* get all data */
1671 else if (arguments.length == 1) {
1672 if (id != null)
1673 return this.registry[id];
1674
1675 return null;
1676 }
1677
1678 /* get a key */
1679 else if (arguments.length == 2) {
1680 if (id != null)
1681 return this.registry[id][key];
1682 }
1683
1684 return null;
1685 },
1686
1687 /**
1688 * Binds the given class instance ot the specified DOM `Node`.
1689 *
1690 * This function uses the `dom.data()` facility to attach the
1691 * passed instance of a Class to a node. This is needed for
1692 * complex widget elements or similar where the corresponding
1693 * class instance responsible for the element must be retrieved
1694 * from DOM nodes obtained by `querySelector()` or similar means.
1695 *
1696 * @instance
1697 * @memberof LuCI.dom
1698 * @param {Node} node
1699 * The DOM `Node` instance to bind the class to.
1700 *
1701 * @param {Class} inst
1702 * The Class instance to bind to the node.
1703 *
1704 * @throws {TypeError}
1705 * Throws a `TypeError` when the given instance argument isn't
1706 * a valid Class instance.
1707 *
1708 * @returns {Class}
1709 * Returns the bound class instance.
1710 */
1711 bindClassInstance: function(node, inst) {
1712 if (!(inst instanceof Class))
1713 LuCI.prototype.error('TypeError', 'Argument must be a class instance');
1714
1715 return this.data(node, '_class', inst);
1716 },
1717
1718 /**
1719 * Finds a bound class instance on the given node itself or the
1720 * first bound instance on its closest parent node.
1721 *
1722 * @instance
1723 * @memberof LuCI.dom
1724 * @param {Node} node
1725 * The DOM `Node` instance to start from.
1726 *
1727 * @returns {Class|null}
1728 * Returns the founds class instance if any or `null` if no bound
1729 * class could be found on the node itself or any of its parents.
1730 */
1731 findClassInstance: function(node) {
1732 var inst = null;
1733
1734 do {
1735 inst = this.data(node, '_class');
1736 node = node.parentNode;
1737 }
1738 while (!(inst instanceof Class) && node != null);
1739
1740 return inst;
1741 },
1742
1743 /**
1744 * Finds a bound class instance on the given node itself or the
1745 * first bound instance on its closest parent node and invokes
1746 * the specified method name on the found class instance.
1747 *
1748 * @instance
1749 * @memberof LuCI.dom
1750 * @param {Node} node
1751 * The DOM `Node` instance to start from.
1752 *
1753 * @param {string} method
1754 * The name of the method to invoke on the found class instance.
1755 *
1756 * @param {...*} params
1757 * Additional arguments to pass to the invoked method as-is.
1758 *
1759 * @returns {*|null}
1760 * Returns the return value of the invoked method if a class
1761 * instance and method has been found. Returns `null` if either
1762 * no bound class instance could be found, or if the found
1763 * instance didn't have the requested `method`.
1764 */
1765 callClassMethod: function(node, method /*, ... */) {
1766 var inst = this.findClassInstance(node);
1767
1768 if (inst == null || typeof(inst[method]) != 'function')
1769 return null;
1770
1771 return inst[method].apply(inst, inst.varargs(arguments, 2));
1772 },
1773
1774 /**
1775 * The ignore callback function is invoked by `isEmpty()` for each
1776 * child node to decide whether to ignore a child node or not.
1777 *
1778 * When this function returns `false`, the node passed to it is
1779 * ignored, else not.
1780 *
1781 * @callback LuCI.dom~ignoreCallbackFn
1782 * @param {Node} node
1783 * The child node to test.
1784 *
1785 * @returns {boolean}
1786 * Boolean indicating whether to ignore the node or not.
1787 */
1788
1789 /**
1790 * Tests whether a given DOM `Node` instance is empty or appears
1791 * empty.
1792 *
1793 * Any element child nodes which have the CSS class `hidden` set
1794 * or for which the optionally passed `ignoreFn` callback function
1795 * returns `false` are ignored.
1796 *
1797 * @instance
1798 * @memberof LuCI.dom
1799 * @param {Node} node
1800 * The DOM `Node` instance to test.
1801 *
1802 * @param {LuCI.dom~ignoreCallbackFn} [ignoreFn]
1803 * Specifies an optional function which is invoked for each child
1804 * node to decide whether the child node should be ignored or not.
1805 *
1806 * @returns {boolean}
1807 * Returns `true` if the node does not have any children or if
1808 * any children node either has a `hidden` CSS class or a `false`
1809 * result when testing it using the given `ignoreFn`.
1810 */
1811 isEmpty: function(node, ignoreFn) {
1812 for (var child = node.firstElementChild; child != null; child = child.nextElementSibling)
1813 if (!child.classList.contains('hidden') && (!ignoreFn || !ignoreFn(child)))
1814 return false;
1815
1816 return true;
1817 }
1818 });
1819
1820 /**
1821 * @class session
1822 * @memberof LuCI
1823 * @hideconstructor
1824 * @classdesc
1825 *
1826 * The `session` class provides various session related functionality.
1827 */
1828 var Session = Class.singleton(/** @lends LuCI.session.prototype */ {
1829 __name__: 'LuCI.session',
1830
1831 /**
1832 * Retrieve the current session ID.
1833 *
1834 * @returns {string}
1835 * Returns the current session ID.
1836 */
1837 getID: function() {
1838 return env.sessionid || '00000000000000000000000000000000';
1839 },
1840
1841 /**
1842 * Retrieve the current session token.
1843 *
1844 * @returns {string|null}
1845 * Returns the current session token or `null` if not logged in.
1846 */
1847 getToken: function() {
1848 return env.token || null;
1849 },
1850
1851 /**
1852 * Retrieve data from the local session storage.
1853 *
1854 * @param {string} [key]
1855 * The key to retrieve from the session data store. If omitted, all
1856 * session data will be returned.
1857 *
1858 * @returns {*}
1859 * Returns the stored session data or `null` if the given key wasn't
1860 * found.
1861 */
1862 getLocalData: function(key) {
1863 try {
1864 var sid = this.getID(),
1865 item = 'luci-session-store',
1866 data = JSON.parse(window.sessionStorage.getItem(item));
1867
1868 if (!LuCI.prototype.isObject(data) || !data.hasOwnProperty(sid)) {
1869 data = {};
1870 data[sid] = {};
1871 }
1872
1873 if (key != null)
1874 return data[sid].hasOwnProperty(key) ? data[sid][key] : null;
1875
1876 return data[sid];
1877 }
1878 catch (e) {
1879 return (key != null) ? null : {};
1880 }
1881 },
1882
1883 /**
1884 * Set data in the local session storage.
1885 *
1886 * @param {string} key
1887 * The key to set in the session data store.
1888 *
1889 * @param {*} value
1890 * The value to store. It will be internally converted to JSON before
1891 * being put in the session store.
1892 *
1893 * @returns {boolean}
1894 * Returns `true` if the data could be stored or `false` on error.
1895 */
1896 setLocalData: function(key, value) {
1897 if (key == null)
1898 return false;
1899
1900 try {
1901 var sid = this.getID(),
1902 item = 'luci-session-store',
1903 data = JSON.parse(window.sessionStorage.getItem(item));
1904
1905 if (!LuCI.prototype.isObject(data) || !data.hasOwnProperty(sid)) {
1906 data = {};
1907 data[sid] = {};
1908 }
1909
1910 if (value != null)
1911 data[sid][key] = value;
1912 else
1913 delete data[sid][key];
1914
1915 window.sessionStorage.setItem(item, JSON.stringify(data));
1916
1917 return true;
1918 }
1919 catch (e) {
1920 return false;
1921 }
1922 }
1923 });
1924
1925 /**
1926 * @class view
1927 * @memberof LuCI
1928 * @hideconstructor
1929 * @classdesc
1930 *
1931 * The `view` class forms the basis of views and provides a standard
1932 * set of methods to inherit from.
1933 */
1934 var View = Class.extend(/** @lends LuCI.view.prototype */ {
1935 __name__: 'LuCI.view',
1936
1937 __init__: function() {
1938 var vp = document.getElementById('view');
1939
1940 DOM.content(vp, E('div', { 'class': 'spinning' }, _('Loading view…')));
1941
1942 return Promise.resolve(this.load())
1943 .then(LuCI.prototype.bind(this.render, this))
1944 .then(LuCI.prototype.bind(function(nodes) {
1945 var vp = document.getElementById('view');
1946
1947 DOM.content(vp, nodes);
1948 DOM.append(vp, this.addFooter());
1949 }, this)).catch(LuCI.prototype.error);
1950 },
1951
1952 /**
1953 * The load function is invoked before the view is rendered.
1954 *
1955 * The invocation of this function is wrapped by
1956 * `Promise.resolve()` so it may return Promises if needed.
1957 *
1958 * The return value of the function (or the resolved values
1959 * of the promise returned by it) will be passed as first
1960 * argument to `render()`.
1961 *
1962 * This function is supposed to be overwritten by subclasses,
1963 * the default implementation does nothing.
1964 *
1965 * @instance
1966 * @abstract
1967 * @memberof LuCI.view
1968 *
1969 * @returns {*|Promise<*>}
1970 * May return any value or a Promise resolving to any value.
1971 */
1972 load: function() {},
1973
1974 /**
1975 * The render function is invoked after the
1976 * {@link LuCI.view#load load()} function and responsible
1977 * for setting up the view contents. It must return a DOM
1978 * `Node` or `DocumentFragment` holding the contents to
1979 * insert into the view area.
1980 *
1981 * The invocation of this function is wrapped by
1982 * `Promise.resolve()` so it may return Promises if needed.
1983 *
1984 * The return value of the function (or the resolved values
1985 * of the promise returned by it) will be inserted into the
1986 * main content area using
1987 * {@link LuCI.dom#append dom.append()}.
1988 *
1989 * This function is supposed to be overwritten by subclasses,
1990 * the default implementation does nothing.
1991 *
1992 * @instance
1993 * @abstract
1994 * @memberof LuCI.view
1995 * @param {*|null} load_results
1996 * This function will receive the return value of the
1997 * {@link LuCI.view#load view.load()} function as first
1998 * argument.
1999 *
2000 * @returns {Node|Promise<Node>}
2001 * Should return a DOM `Node` value or a `Promise` resolving
2002 * to a `Node` value.
2003 */
2004 render: function() {},
2005
2006 /**
2007 * The handleSave function is invoked when the user clicks
2008 * the `Save` button in the page action footer.
2009 *
2010 * The default implementation should be sufficient for most
2011 * views using {@link form#Map form.Map()} based forms - it
2012 * will iterate all forms present in the view and invoke
2013 * the {@link form#Map#save Map.save()} method on each form.
2014 *
2015 * Views not using `Map` instances or requiring other special
2016 * logic should overwrite `handleSave()` with a custom
2017 * implementation.
2018 *
2019 * To disable the `Save` page footer button, views extending
2020 * this base class should overwrite the `handleSave` function
2021 * with `null`.
2022 *
2023 * The invocation of this function is wrapped by
2024 * `Promise.resolve()` so it may return Promises if needed.
2025 *
2026 * @instance
2027 * @memberof LuCI.view
2028 * @param {Event} ev
2029 * The DOM event that triggered the function.
2030 *
2031 * @returns {*|Promise<*>}
2032 * Any return values of this function are discarded, but
2033 * passed through `Promise.resolve()` to ensure that any
2034 * returned promise runs to completion before the button
2035 * is reenabled.
2036 */
2037 handleSave: function(ev) {
2038 var tasks = [];
2039
2040 document.getElementById('maincontent')
2041 .querySelectorAll('.cbi-map').forEach(function(map) {
2042 tasks.push(DOM.callClassMethod(map, 'save'));
2043 });
2044
2045 return Promise.all(tasks);
2046 },
2047
2048 /**
2049 * The handleSaveApply function is invoked when the user clicks
2050 * the `Save & Apply` button in the page action footer.
2051 *
2052 * The default implementation should be sufficient for most
2053 * views using {@link form#Map form.Map()} based forms - it
2054 * will first invoke
2055 * {@link LuCI.view.handleSave view.handleSave()} and then
2056 * call {@link ui#changes#apply ui.changes.apply()} to start the
2057 * modal config apply and page reload flow.
2058 *
2059 * Views not using `Map` instances or requiring other special
2060 * logic should overwrite `handleSaveApply()` with a custom
2061 * implementation.
2062 *
2063 * To disable the `Save & Apply` page footer button, views
2064 * extending this base class should overwrite the
2065 * `handleSaveApply` function with `null`.
2066 *
2067 * The invocation of this function is wrapped by
2068 * `Promise.resolve()` so it may return Promises if needed.
2069 *
2070 * @instance
2071 * @memberof LuCI.view
2072 * @param {Event} ev
2073 * The DOM event that triggered the function.
2074 *
2075 * @returns {*|Promise<*>}
2076 * Any return values of this function are discarded, but
2077 * passed through `Promise.resolve()` to ensure that any
2078 * returned promise runs to completion before the button
2079 * is reenabled.
2080 */
2081 handleSaveApply: function(ev, mode) {
2082 return this.handleSave(ev).then(function() {
2083 classes.ui.changes.apply(mode == '0');
2084 });
2085 },
2086
2087 /**
2088 * The handleReset function is invoked when the user clicks
2089 * the `Reset` button in the page action footer.
2090 *
2091 * The default implementation should be sufficient for most
2092 * views using {@link form#Map form.Map()} based forms - it
2093 * will iterate all forms present in the view and invoke
2094 * the {@link form#Map#save Map.reset()} method on each form.
2095 *
2096 * Views not using `Map` instances or requiring other special
2097 * logic should overwrite `handleReset()` with a custom
2098 * implementation.
2099 *
2100 * To disable the `Reset` page footer button, views extending
2101 * this base class should overwrite the `handleReset` function
2102 * with `null`.
2103 *
2104 * The invocation of this function is wrapped by
2105 * `Promise.resolve()` so it may return Promises if needed.
2106 *
2107 * @instance
2108 * @memberof LuCI.view
2109 * @param {Event} ev
2110 * The DOM event that triggered the function.
2111 *
2112 * @returns {*|Promise<*>}
2113 * Any return values of this function are discarded, but
2114 * passed through `Promise.resolve()` to ensure that any
2115 * returned promise runs to completion before the button
2116 * is reenabled.
2117 */
2118 handleReset: function(ev) {
2119 var tasks = [];
2120
2121 document.getElementById('maincontent')
2122 .querySelectorAll('.cbi-map').forEach(function(map) {
2123 tasks.push(DOM.callClassMethod(map, 'reset'));
2124 });
2125
2126 return Promise.all(tasks);
2127 },
2128
2129 /**
2130 * Renders a standard page action footer if any of the
2131 * `handleSave()`, `handleSaveApply()` or `handleReset()`
2132 * functions are defined.
2133 *
2134 * The default implementation should be sufficient for most
2135 * views - it will render a standard page footer with action
2136 * buttons labeled `Save`, `Save & Apply` and `Reset`
2137 * triggering the `handleSave()`, `handleSaveApply()` and
2138 * `handleReset()` functions respectively.
2139 *
2140 * When any of these `handle*()` functions is overwritten
2141 * with `null` by a view extending this class, the
2142 * corresponding button will not be rendered.
2143 *
2144 * @instance
2145 * @memberof LuCI.view
2146 * @returns {DocumentFragment}
2147 * Returns a `DocumentFragment` containing the footer bar
2148 * with buttons for each corresponding `handle*()` action
2149 * or an empty `DocumentFragment` if all three `handle*()`
2150 * methods are overwritten with `null`.
2151 */
2152 addFooter: function() {
2153 var footer = E([]),
2154 vp = document.getElementById('view'),
2155 hasmap = false,
2156 readonly = true;
2157
2158 vp.querySelectorAll('.cbi-map').forEach(function(map) {
2159 var m = DOM.findClassInstance(map);
2160 if (m) {
2161 hasmap = true;
2162
2163 if (!m.readonly)
2164 readonly = false;
2165 }
2166 });
2167
2168 if (!hasmap)
2169 readonly = !LuCI.prototype.hasViewPermission();
2170
2171 var saveApplyBtn = this.handleSaveApply ? new classes.ui.ComboButton('0', {
2172 0: [ _('Save & Apply') ],
2173 1: [ _('Apply unchecked') ]
2174 }, {
2175 classes: {
2176 0: 'btn cbi-button cbi-button-apply important',
2177 1: 'btn cbi-button cbi-button-negative important'
2178 },
2179 click: classes.ui.createHandlerFn(this, 'handleSaveApply'),
2180 disabled: readonly || null
2181 }).render() : E([]);
2182
2183 if (this.handleSaveApply || this.handleSave || this.handleReset) {
2184 footer.appendChild(E('div', { 'class': 'cbi-page-actions control-group' }, [
2185 saveApplyBtn, ' ',
2186 this.handleSave ? E('button', {
2187 'class': 'cbi-button cbi-button-save',
2188 'click': classes.ui.createHandlerFn(this, 'handleSave'),
2189 'disabled': readonly || null
2190 }, [ _('Save') ]) : '', ' ',
2191 this.handleReset ? E('button', {
2192 'class': 'cbi-button cbi-button-reset',
2193 'click': classes.ui.createHandlerFn(this, 'handleReset'),
2194 'disabled': readonly || null
2195 }, [ _('Reset') ]) : ''
2196 ]));
2197 }
2198
2199 return footer;
2200 }
2201 });
2202
2203
2204 var dummyElem = null,
2205 domParser = null,
2206 originalCBIInit = null,
2207 rpcBaseURL = null,
2208 sysFeatures = null,
2209 preloadClasses = null;
2210
2211 /* "preload" builtin classes to make the available via require */
2212 var classes = {
2213 baseclass: Class,
2214 dom: DOM,
2215 poll: Poll,
2216 request: Request,
2217 session: Session,
2218 view: View
2219 };
2220
2221 var LuCI = Class.extend(/** @lends LuCI.prototype */ {
2222 __name__: 'LuCI',
2223 __init__: function(setenv) {
2224
2225 document.querySelectorAll('script[src*="/luci.js"]').forEach(function(s) {
2226 if (setenv.base_url == null || setenv.base_url == '') {
2227 var m = (s.getAttribute('src') || '').match(/^(.*)\/luci\.js(?:\?v=([^?]+))?$/);
2228 if (m) {
2229 setenv.base_url = m[1];
2230 setenv.resource_version = m[2];
2231 }
2232 }
2233 });
2234
2235 if (setenv.base_url == null)
2236 this.error('InternalError', 'Cannot find url of luci.js');
2237
2238 setenv.cgi_base = setenv.scriptname.replace(/\/[^\/]+$/, '');
2239
2240 Object.assign(env, setenv);
2241
2242 var domReady = new Promise(function(resolveFn, rejectFn) {
2243 document.addEventListener('DOMContentLoaded', resolveFn);
2244 });
2245
2246 Promise.all([
2247 domReady,
2248 this.require('ui'),
2249 this.require('rpc'),
2250 this.require('form'),
2251 this.probeRPCBaseURL()
2252 ]).then(this.setupDOM.bind(this)).catch(this.error);
2253
2254 originalCBIInit = window.cbi_init;
2255 window.cbi_init = function() {};
2256 },
2257
2258 /**
2259 * Captures the current stack trace and throws an error of the
2260 * specified type as a new exception. Also logs the exception as
2261 * error to the debug console if it is available.
2262 *
2263 * @instance
2264 * @memberof LuCI
2265 *
2266 * @param {Error|string} [type=Error]
2267 * Either a string specifying the type of the error to throw or an
2268 * existing `Error` instance to copy.
2269 *
2270 * @param {string} [fmt=Unspecified error]
2271 * A format string which is used to form the error message, together
2272 * with all subsequent optional arguments.
2273 *
2274 * @param {...*} [args]
2275 * Zero or more variable arguments to the supplied format string.
2276 *
2277 * @throws {Error}
2278 * Throws the created error object with the captured stack trace
2279 * appended to the message and the type set to the given type
2280 * argument or copied from the given error instance.
2281 */
2282 raise: function(type, fmt /*, ...*/) {
2283 var e = null,
2284 msg = fmt ? String.prototype.format.apply(fmt, this.varargs(arguments, 2)) : null,
2285 stack = null;
2286
2287 if (type instanceof Error) {
2288 e = type;
2289
2290 if (msg)
2291 e.message = msg + ': ' + e.message;
2292 }
2293 else {
2294 try { throw new Error('stacktrace') }
2295 catch (e2) { stack = (e2.stack || '').split(/\n/) }
2296
2297 e = new (window[type || 'Error'] || Error)(msg || 'Unspecified error');
2298 e.name = type || 'Error';
2299 }
2300
2301 stack = (stack || []).map(function(frame) {
2302 frame = frame.replace(/(.*?)@(.+):(\d+):(\d+)/g, 'at $1 ($2:$3:$4)').trim();
2303 return frame ? ' ' + frame : '';
2304 });
2305
2306 if (!/^ at /.test(stack[0]))
2307 stack.shift();
2308
2309 if (/\braise /.test(stack[0]))
2310 stack.shift();
2311
2312 if (/\berror /.test(stack[0]))
2313 stack.shift();
2314
2315 if (stack.length)
2316 e.message += '\n' + stack.join('\n');
2317
2318 if (window.console && console.debug)
2319 console.debug(e);
2320
2321 throw e;
2322 },
2323
2324 /**
2325 * A wrapper around {@link LuCI#raise raise()} which also renders
2326 * the error either as modal overlay when `ui.js` is already loaed
2327 * or directly into the view body.
2328 *
2329 * @instance
2330 * @memberof LuCI
2331 *
2332 * @param {Error|string} [type=Error]
2333 * Either a string specifying the type of the error to throw or an
2334 * existing `Error` instance to copy.
2335 *
2336 * @param {string} [fmt=Unspecified error]
2337 * A format string which is used to form the error message, together
2338 * with all subsequent optional arguments.
2339 *
2340 * @param {...*} [args]
2341 * Zero or more variable arguments to the supplied format string.
2342 *
2343 * @throws {Error}
2344 * Throws the created error object with the captured stack trace
2345 * appended to the message and the type set to the given type
2346 * argument or copied from the given error instance.
2347 */
2348 error: function(type, fmt /*, ...*/) {
2349 try {
2350 LuCI.prototype.raise.apply(LuCI.prototype,
2351 Array.prototype.slice.call(arguments));
2352 }
2353 catch (e) {
2354 if (!e.reported) {
2355 if (classes.ui)
2356 classes.ui.addNotification(e.name || _('Runtime error'),
2357 E('pre', {}, e.message), 'danger');
2358 else
2359 DOM.content(document.querySelector('#maincontent'),
2360 E('pre', { 'class': 'alert-message error' }, e.message));
2361
2362 e.reported = true;
2363 }
2364
2365 throw e;
2366 }
2367 },
2368
2369 /**
2370 * Return a bound function using the given `self` as `this` context
2371 * and any further arguments as parameters to the bound function.
2372 *
2373 * @instance
2374 * @memberof LuCI
2375 *
2376 * @param {function} fn
2377 * The function to bind.
2378 *
2379 * @param {*} self
2380 * The value to bind as `this` context to the specified function.
2381 *
2382 * @param {...*} [args]
2383 * Zero or more variable arguments which are bound to the function
2384 * as parameters.
2385 *
2386 * @returns {function}
2387 * Returns the bound function.
2388 */
2389 bind: function(fn, self /*, ... */) {
2390 return Function.prototype.bind.apply(fn, this.varargs(arguments, 2, self));
2391 },
2392
2393 /**
2394 * Load an additional LuCI JavaScript class and its dependencies,
2395 * instantiate it and return the resulting class instance. Each
2396 * class is only loaded once. Subsequent attempts to load the same
2397 * class will return the already instantiated class.
2398 *
2399 * @instance
2400 * @memberof LuCI
2401 *
2402 * @param {string} name
2403 * The name of the class to load in dotted notation. Dots will
2404 * be replaced by spaces and joined with the runtime-determined
2405 * base URL of LuCI.js to form an absolute URL to load the class
2406 * file from.
2407 *
2408 * @throws {DependencyError}
2409 * Throws a `DependencyError` when the class to load includes
2410 * circular dependencies.
2411 *
2412 * @throws {NetworkError}
2413 * Throws `NetworkError` when the underlying {@link LuCI.request}
2414 * call failed.
2415 *
2416 * @throws {SyntaxError}
2417 * Throws `SyntaxError` when the loaded class file code cannot
2418 * be interpreted by `eval`.
2419 *
2420 * @throws {TypeError}
2421 * Throws `TypeError` when the class file could be loaded and
2422 * interpreted, but when invoking its code did not yield a valid
2423 * class instance.
2424 *
2425 * @returns {Promise<LuCI.baseclass>}
2426 * Returns the instantiated class.
2427 */
2428 require: function(name, from) {
2429 var L = this, url = null, from = from || [];
2430
2431 /* Class already loaded */
2432 if (classes[name] != null) {
2433 /* Circular dependency */
2434 if (from.indexOf(name) != -1)
2435 LuCI.prototype.raise('DependencyError',
2436 'Circular dependency: class "%s" depends on "%s"',
2437 name, from.join('" which depends on "'));
2438
2439 return Promise.resolve(classes[name]);
2440 }
2441
2442 url = '%s/%s.js%s'.format(env.base_url, name.replace(/\./g, '/'), (env.resource_version ? '?v=' + env.resource_version : ''));
2443 from = [ name ].concat(from);
2444
2445 var compileClass = function(res) {
2446 if (!res.ok)
2447 LuCI.prototype.raise('NetworkError',
2448 'HTTP error %d while loading class file "%s"', res.status, url);
2449
2450 var source = res.text(),
2451 requirematch = /^require[ \t]+(\S+)(?:[ \t]+as[ \t]+([a-zA-Z_]\S*))?$/,
2452 strictmatch = /^use[ \t]+strict$/,
2453 depends = [],
2454 args = '';
2455
2456 /* find require statements in source */
2457 for (var i = 0, off = -1, prev = -1, quote = -1, comment = -1, esc = false; i < source.length; i++) {
2458 var chr = source.charCodeAt(i);
2459
2460 if (esc) {
2461 esc = false;
2462 }
2463 else if (comment != -1) {
2464 if ((comment == 47 && chr == 10) || (comment == 42 && prev == 42 && chr == 47))
2465 comment = -1;
2466 }
2467 else if ((chr == 42 || chr == 47) && prev == 47) {
2468 comment = chr;
2469 }
2470 else if (chr == 92) {
2471 esc = true;
2472 }
2473 else if (chr == quote) {
2474 var s = source.substring(off, i),
2475 m = requirematch.exec(s);
2476
2477 if (m) {
2478 var dep = m[1], as = m[2] || dep.replace(/[^a-zA-Z0-9_]/g, '_');
2479 depends.push(LuCI.prototype.require(dep, from));
2480 args += ', ' + as;
2481 }
2482 else if (!strictmatch.exec(s)) {
2483 break;
2484 }
2485
2486 off = -1;
2487 quote = -1;
2488 }
2489 else if (quote == -1 && (chr == 34 || chr == 39)) {
2490 off = i + 1;
2491 quote = chr;
2492 }
2493
2494 prev = chr;
2495 }
2496
2497 /* load dependencies and instantiate class */
2498 return Promise.all(depends).then(function(instances) {
2499 var _factory, _class;
2500
2501 try {
2502 _factory = eval(
2503 '(function(window, document, L%s) { %s })\n\n//# sourceURL=%s\n'
2504 .format(args, source, res.url));
2505 }
2506 catch (error) {
2507 LuCI.prototype.raise('SyntaxError', '%s\n in %s:%s',
2508 error.message, res.url, error.lineNumber || '?');
2509 }
2510
2511 _factory.displayName = toCamelCase(name + 'ClassFactory');
2512 _class = _factory.apply(_factory, [window, document, L].concat(instances));
2513
2514 if (!Class.isSubclass(_class))
2515 LuCI.prototype.error('TypeError', '"%s" factory yields invalid constructor', name);
2516
2517 if (_class.displayName == 'AnonymousClass')
2518 _class.displayName = toCamelCase(name + 'Class');
2519
2520 var ptr = Object.getPrototypeOf(L),
2521 parts = name.split(/\./),
2522 instance = new _class();
2523
2524 for (var i = 0; ptr && i < parts.length - 1; i++)
2525 ptr = ptr[parts[i]];
2526
2527 if (ptr)
2528 ptr[parts[i]] = instance;
2529
2530 classes[name] = instance;
2531
2532 return instance;
2533 });
2534 };
2535
2536 /* Request class file */
2537 classes[name] = Request.get(url, { cache: true }).then(compileClass);
2538
2539 return classes[name];
2540 },
2541
2542 /* DOM setup */
2543 probeRPCBaseURL: function() {
2544 if (rpcBaseURL == null)
2545 rpcBaseURL = Session.getLocalData('rpcBaseURL');
2546
2547 if (rpcBaseURL == null) {
2548 var msg = {
2549 jsonrpc: '2.0',
2550 id: 'init',
2551 method: 'list',
2552 params: undefined
2553 };
2554 var rpcFallbackURL = this.url('admin/ubus');
2555
2556 rpcBaseURL = Request.post(env.ubuspath, msg, { nobatch: true }).then(function(res) {
2557 return (rpcBaseURL = res.status == 200 ? env.ubuspath : rpcFallbackURL);
2558 }, function() {
2559 return (rpcBaseURL = rpcFallbackURL);
2560 }).then(function(url) {
2561 Session.setLocalData('rpcBaseURL', url);
2562 return url;
2563 });
2564 }
2565
2566 return Promise.resolve(rpcBaseURL);
2567 },
2568
2569 probeSystemFeatures: function() {
2570 if (sysFeatures == null)
2571 sysFeatures = Session.getLocalData('features');
2572
2573 if (!this.isObject(sysFeatures)) {
2574 sysFeatures = classes.rpc.declare({
2575 object: 'luci',
2576 method: 'getFeatures',
2577 expect: { '': {} }
2578 })().then(function(features) {
2579 Session.setLocalData('features', features);
2580 sysFeatures = features;
2581
2582 return features;
2583 });
2584 }
2585
2586 return Promise.resolve(sysFeatures);
2587 },
2588
2589 probePreloadClasses: function() {
2590 if (preloadClasses == null)
2591 preloadClasses = Session.getLocalData('preload');
2592
2593 if (!Array.isArray(preloadClasses)) {
2594 preloadClasses = this.resolveDefault(classes.rpc.declare({
2595 object: 'file',
2596 method: 'list',
2597 params: [ 'path' ],
2598 expect: { 'entries': [] }
2599 })(this.fspath(this.resource('preload'))), []).then(function(entries) {
2600 var classes = [];
2601
2602 for (var i = 0; i < entries.length; i++) {
2603 if (entries[i].type != 'file')
2604 continue;
2605
2606 var m = entries[i].name.match(/(.+)\.js$/);
2607
2608 if (m)
2609 classes.push('preload.%s'.format(m[1]));
2610 }
2611
2612 Session.setLocalData('preload', classes);
2613 preloadClasses = classes;
2614
2615 return classes;
2616 });
2617 }
2618
2619 return Promise.resolve(preloadClasses);
2620 },
2621
2622 /**
2623 * Test whether a particular system feature is available, such as
2624 * hostapd SAE support or an installed firewall. The features are
2625 * queried once at the beginning of the LuCI session and cached in
2626 * `SessionStorage` throughout the lifetime of the associated tab or
2627 * browser window.
2628 *
2629 * @instance
2630 * @memberof LuCI
2631 *
2632 * @param {string} feature
2633 * The feature to test. For detailed list of known feature flags,
2634 * see `/modules/luci-base/root/usr/libexec/rpcd/luci`.
2635 *
2636 * @param {string} [subfeature]
2637 * Some feature classes like `hostapd` provide sub-feature flags,
2638 * such as `sae` or `11w` support. The `subfeature` argument can
2639 * be used to query these.
2640 *
2641 * @return {boolean|null}
2642 * Return `true` if the queried feature (and sub-feature) is available
2643 * or `false` if the requested feature isn't present or known.
2644 * Return `null` when a sub-feature was queried for a feature which
2645 * has no sub-features.
2646 */
2647 hasSystemFeature: function() {
2648 var ft = sysFeatures[arguments[0]];
2649
2650 if (arguments.length == 2)
2651 return this.isObject(ft) ? ft[arguments[1]] : null;
2652
2653 return (ft != null && ft != false);
2654 },
2655
2656 /* private */
2657 notifySessionExpiry: function() {
2658 Poll.stop();
2659
2660 classes.ui.showModal(_('Session expired'), [
2661 E('div', { class: 'alert-message warning' },
2662 _('A new login is required since the authentication session expired.')),
2663 E('div', { class: 'right' },
2664 E('div', {
2665 class: 'btn primary',
2666 click: function() {
2667 var loc = window.location;
2668 window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
2669 }
2670 }, _('To login…')))
2671 ]);
2672
2673 LuCI.prototype.raise('SessionError', 'Login session is expired');
2674 },
2675
2676 /* private */
2677 setupDOM: function(res) {
2678 var domEv = res[0],
2679 uiClass = res[1],
2680 rpcClass = res[2],
2681 formClass = res[3],
2682 rpcBaseURL = res[4];
2683
2684 rpcClass.setBaseURL(rpcBaseURL);
2685
2686 rpcClass.addInterceptor(function(msg, req) {
2687 if (!LuCI.prototype.isObject(msg) ||
2688 !LuCI.prototype.isObject(msg.error) ||
2689 msg.error.code != -32002)
2690 return;
2691
2692 if (!LuCI.prototype.isObject(req) ||
2693 (req.object == 'session' && req.method == 'access'))
2694 return;
2695
2696 return rpcClass.declare({
2697 'object': 'session',
2698 'method': 'access',
2699 'params': [ 'scope', 'object', 'function' ],
2700 'expect': { access: true }
2701 })('uci', 'luci', 'read').catch(LuCI.prototype.notifySessionExpiry);
2702 });
2703
2704 Request.addInterceptor(function(res) {
2705 var isDenied = false;
2706
2707 if (res.status == 403 && res.headers.get('X-LuCI-Login-Required') == 'yes')
2708 isDenied = true;
2709
2710 if (!isDenied)
2711 return;
2712
2713 LuCI.prototype.notifySessionExpiry();
2714 });
2715
2716 document.addEventListener('poll-start', function(ev) {
2717 uiClass.showIndicator('poll-status', _('Refreshing'), function(ev) {
2718 Request.poll.active() ? Request.poll.stop() : Request.poll.start();
2719 });
2720 });
2721
2722 document.addEventListener('poll-stop', function(ev) {
2723 uiClass.showIndicator('poll-status', _('Paused'), null, 'inactive');
2724 });
2725
2726 return Promise.all([
2727 this.probeSystemFeatures(),
2728 this.probePreloadClasses()
2729 ]).finally(LuCI.prototype.bind(function() {
2730 var tasks = [];
2731
2732 if (Array.isArray(preloadClasses))
2733 for (var i = 0; i < preloadClasses.length; i++)
2734 tasks.push(this.require(preloadClasses[i]));
2735
2736 return Promise.all(tasks);
2737 }, this)).finally(this.initDOM);
2738 },
2739
2740 /* private */
2741 initDOM: function() {
2742 originalCBIInit();
2743 Poll.start();
2744 document.dispatchEvent(new CustomEvent('luci-loaded'));
2745 },
2746
2747 /**
2748 * The `env` object holds environment settings used by LuCI, such
2749 * as request timeouts, base URLs etc.
2750 *
2751 * @instance
2752 * @memberof LuCI
2753 */
2754 env: env,
2755
2756 /**
2757 * Construct an absolute filesystem path relative to the server
2758 * document root.
2759 *
2760 * @instance
2761 * @memberof LuCI
2762 *
2763 * @param {...string} [parts]
2764 * An array of parts to join into a path.
2765 *
2766 * @return {string}
2767 * Return the joined path.
2768 */
2769 fspath: function(/* ... */) {
2770 var path = env.documentroot;
2771
2772 for (var i = 0; i < arguments.length; i++)
2773 path += '/' + arguments[i];
2774
2775 var p = path.replace(/\/+$/, '').replace(/\/+/g, '/').split(/\//),
2776 res = [];
2777
2778 for (var i = 0; i < p.length; i++)
2779 if (p[i] == '..')
2780 res.pop();
2781 else if (p[i] != '.')
2782 res.push(p[i]);
2783
2784 return res.join('/');
2785 },
2786
2787 /**
2788 * Construct a relative URL path from the given prefix and parts.
2789 * The resulting URL is guaranteed to only contain the characters
2790 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2791 * as `/` for the path separator.
2792 *
2793 * @instance
2794 * @memberof LuCI
2795 *
2796 * @param {string} [prefix]
2797 * The prefix to join the given parts with. If the `prefix` is
2798 * omitted, it defaults to an empty string.
2799 *
2800 * @param {string[]} [parts]
2801 * An array of parts to join into an URL path. Parts may contain
2802 * slashes and any of the other characters mentioned above.
2803 *
2804 * @return {string}
2805 * Return the joined URL path.
2806 */
2807 path: function(prefix, parts) {
2808 var url = [ prefix || '' ];
2809
2810 for (var i = 0; i < parts.length; i++)
2811 if (/^(?:[a-zA-Z0-9_.%,;-]+\/)*[a-zA-Z0-9_.%,;-]+$/.test(parts[i]))
2812 url.push('/', parts[i]);
2813
2814 if (url.length === 1)
2815 url.push('/');
2816
2817 return url.join('');
2818 },
2819
2820 /**
2821 * Construct an URL pathrelative to the script path of the server
2822 * side LuCI application (usually `/cgi-bin/luci`).
2823 *
2824 * The resulting URL is guaranteed to only contain the characters
2825 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2826 * as `/` for the path separator.
2827 *
2828 * @instance
2829 * @memberof LuCI
2830 *
2831 * @param {string[]} [parts]
2832 * An array of parts to join into an URL path. Parts may contain
2833 * slashes and any of the other characters mentioned above.
2834 *
2835 * @return {string}
2836 * Returns the resulting URL path.
2837 */
2838 url: function() {
2839 return this.path(env.scriptname, arguments);
2840 },
2841
2842 /**
2843 * Construct an URL path relative to the global static resource path
2844 * of the LuCI ui (usually `/luci-static/resources`).
2845 *
2846 * The resulting URL is guaranteed to only contain the characters
2847 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2848 * as `/` for the path separator.
2849 *
2850 * @instance
2851 * @memberof LuCI
2852 *
2853 * @param {string[]} [parts]
2854 * An array of parts to join into an URL path. Parts may contain
2855 * slashes and any of the other characters mentioned above.
2856 *
2857 * @return {string}
2858 * Returns the resulting URL path.
2859 */
2860 resource: function() {
2861 return this.path(env.resource, arguments);
2862 },
2863
2864 /**
2865 * Construct an URL path relative to the media resource path of the
2866 * LuCI ui (usually `/luci-static/$theme_name`).
2867 *
2868 * The resulting URL is guaranteed to only contain the characters
2869 * `a-z`, `A-Z`, `0-9`, `_`, `.`, `%`, `,`, `;`, and `-` as well
2870 * as `/` for the path separator.
2871 *
2872 * @instance
2873 * @memberof LuCI
2874 *
2875 * @param {string[]} [parts]
2876 * An array of parts to join into an URL path. Parts may contain
2877 * slashes and any of the other characters mentioned above.
2878 *
2879 * @return {string}
2880 * Returns the resulting URL path.
2881 */
2882 media: function() {
2883 return this.path(env.media, arguments);
2884 },
2885
2886 /**
2887 * Return the complete URL path to the current view.
2888 *
2889 * @instance
2890 * @memberof LuCI
2891 *
2892 * @return {string}
2893 * Returns the URL path to the current view.
2894 */
2895 location: function() {
2896 return this.path(env.scriptname, env.requestpath);
2897 },
2898
2899
2900 /**
2901 * Tests whether the passed argument is a JavaScript object.
2902 * This function is meant to be an object counterpart to the
2903 * standard `Array.isArray()` function.
2904 *
2905 * @instance
2906 * @memberof LuCI
2907 *
2908 * @param {*} [val]
2909 * The value to test
2910 *
2911 * @return {boolean}
2912 * Returns `true` if the given value is of type object and
2913 * not `null`, else returns `false`.
2914 */
2915 isObject: function(val) {
2916 return (val != null && typeof(val) == 'object');
2917 },
2918
2919 /**
2920 * Return an array of sorted object keys, optionally sorted by
2921 * a different key or a different sorting mode.
2922 *
2923 * @instance
2924 * @memberof LuCI
2925 *
2926 * @param {object} obj
2927 * The object to extract the keys from. If the given value is
2928 * not an object, the function will return an empty array.
2929 *
2930 * @param {string} [key]
2931 * Specifies the key to order by. This is mainly useful for
2932 * nested objects of objects or objects of arrays when sorting
2933 * shall not be performed by the primary object keys but by
2934 * some other key pointing to a value within the nested values.
2935 *
2936 * @param {string} [sortmode]
2937 * May be either `addr` or `num` to override the natural
2938 * lexicographic sorting with a sorting suitable for IP/MAC style
2939 * addresses or numeric values respectively.
2940 *
2941 * @return {string[]}
2942 * Returns an array containing the sorted keys of the given object.
2943 */
2944 sortedKeys: function(obj, key, sortmode) {
2945 if (obj == null || typeof(obj) != 'object')
2946 return [];
2947
2948 return Object.keys(obj).map(function(e) {
2949 var v = (key != null) ? obj[e][key] : e;
2950
2951 switch (sortmode) {
2952 case 'addr':
2953 v = (v != null) ? v.replace(/(?:^|[.:])([0-9a-fA-F]{1,4})/g,
2954 function(m0, m1) { return ('000' + m1.toLowerCase()).substr(-4) }) : null;
2955 break;
2956
2957 case 'num':
2958 v = (v != null) ? +v : null;
2959 break;
2960 }
2961
2962 return [ e, v ];
2963 }).filter(function(e) {
2964 return (e[1] != null);
2965 }).sort(function(a, b) {
2966 if (a[1] < b[1])
2967 return -1;
2968 else if (a[1] > b[1])
2969 return 1;
2970 else
2971 return 0;
2972 }).map(function(e) {
2973 return e[0];
2974 });
2975 },
2976
2977 /**
2978 * Converts the given value to an array. If the given value is of
2979 * type array, it is returned as-is, values of type object are
2980 * returned as one-element array containing the object, empty
2981 * strings and `null` values are returned as empty array, all other
2982 * values are converted using `String()`, trimmed, split on white
2983 * space and returned as array.
2984 *
2985 * @instance
2986 * @memberof LuCI
2987 *
2988 * @param {*} val
2989 * The value to convert into an array.
2990 *
2991 * @return {Array<*>}
2992 * Returns the resulting array.
2993 */
2994 toArray: function(val) {
2995 if (val == null)
2996 return [];
2997 else if (Array.isArray(val))
2998 return val;
2999 else if (typeof(val) == 'object')
3000 return [ val ];
3001
3002 var s = String(val).trim();
3003
3004 if (s == '')
3005 return [];
3006
3007 return s.split(/\s+/);
3008 },
3009
3010 /**
3011 * Returns a promise resolving with either the given value or or with
3012 * the given default in case the input value is a rejecting promise.
3013 *
3014 * @instance
3015 * @memberof LuCI
3016 *
3017 * @param {*} value
3018 * The value to resolve the promise with.
3019 *
3020 * @param {*} defvalue
3021 * The default value to resolve the promise with in case the given
3022 * input value is a rejecting promise.
3023 *
3024 * @returns {Promise<*>}
3025 * Returns a new promise resolving either to the given input value or
3026 * to the given default value on error.
3027 */
3028 resolveDefault: function(value, defvalue) {
3029 return Promise.resolve(value).catch(function() { return defvalue });
3030 },
3031
3032 /**
3033 * The request callback function is invoked whenever an HTTP
3034 * reply to a request made using the `L.get()`, `L.post()` or
3035 * `L.poll()` function is timed out or received successfully.
3036 *
3037 * @instance
3038 * @memberof LuCI
3039 *
3040 * @callback LuCI.requestCallbackFn
3041 * @param {XMLHTTPRequest} xhr
3042 * The XMLHTTPRequest instance used to make the request.
3043 *
3044 * @param {*} data
3045 * The response JSON if the response could be parsed as such,
3046 * else `null`.
3047 *
3048 * @param {number} duration
3049 * The total duration of the request in milliseconds.
3050 */
3051
3052 /**
3053 * Issues a GET request to the given url and invokes the specified
3054 * callback function. The function is a wrapper around
3055 * {@link LuCI.request#request Request.request()}.
3056 *
3057 * @deprecated
3058 * @instance
3059 * @memberof LuCI
3060 *
3061 * @param {string} url
3062 * The URL to request.
3063 *
3064 * @param {Object<string, string>} [args]
3065 * Additional query string arguments to append to the URL.
3066 *
3067 * @param {LuCI.requestCallbackFn} cb
3068 * The callback function to invoke when the request finishes.
3069 *
3070 * @return {Promise<null>}
3071 * Returns a promise resolving to `null` when concluded.
3072 */
3073 get: function(url, args, cb) {
3074 return this.poll(null, url, args, cb, false);
3075 },
3076
3077 /**
3078 * Issues a POST request to the given url and invokes the specified
3079 * callback function. The function is a wrapper around
3080 * {@link LuCI.request#request Request.request()}. The request is
3081 * sent using `application/x-www-form-urlencoded` encoding and will
3082 * contain a field `token` with the current value of `LuCI.env.token`
3083 * by default.
3084 *
3085 * @deprecated
3086 * @instance
3087 * @memberof LuCI
3088 *
3089 * @param {string} url
3090 * The URL to request.
3091 *
3092 * @param {Object<string, string>} [args]
3093 * Additional post arguments to append to the request body.
3094 *
3095 * @param {LuCI.requestCallbackFn} cb
3096 * The callback function to invoke when the request finishes.
3097 *
3098 * @return {Promise<null>}
3099 * Returns a promise resolving to `null` when concluded.
3100 */
3101 post: function(url, args, cb) {
3102 return this.poll(null, url, args, cb, true);
3103 },
3104
3105 /**
3106 * Register a polling HTTP request that invokes the specified
3107 * callback function. The function is a wrapper around
3108 * {@link LuCI.request.poll#add Request.poll.add()}.
3109 *
3110 * @deprecated
3111 * @instance
3112 * @memberof LuCI
3113 *
3114 * @param {number} interval
3115 * The poll interval to use. If set to a value less than or equal
3116 * to `0`, it will default to the global poll interval configured
3117 * in `LuCI.env.pollinterval`.
3118 *
3119 * @param {string} url
3120 * The URL to request.
3121 *
3122 * @param {Object<string, string>} [args]
3123 * Specifies additional arguments for the request. For GET requests,
3124 * the arguments are appended to the URL as query string, for POST
3125 * requests, they'll be added to the request body.
3126 *
3127 * @param {LuCI.requestCallbackFn} cb
3128 * The callback function to invoke whenever a request finishes.
3129 *
3130 * @param {boolean} [post=false]
3131 * When set to `false` or not specified, poll requests will be made
3132 * using the GET method. When set to `true`, POST requests will be
3133 * issued. In case of POST requests, the request body will contain
3134 * an argument `token` with the current value of `LuCI.env.token` by
3135 * default, regardless of the parameters specified with `args`.
3136 *
3137 * @return {function}
3138 * Returns the internally created function that has been passed to
3139 * {@link LuCI.request.poll#add Request.poll.add()}. This value can
3140 * be passed to {@link LuCI.poll.remove Poll.remove()} to remove the
3141 * polling request.
3142 */
3143 poll: function(interval, url, args, cb, post) {
3144 if (interval !== null && interval <= 0)
3145 interval = env.pollinterval;
3146
3147 var data = post ? { token: env.token } : null,
3148 method = post ? 'POST' : 'GET';
3149
3150 if (!/^(?:\/|\S+:\/\/)/.test(url))
3151 url = this.url(url);
3152
3153 if (args != null)
3154 data = Object.assign(data || {}, args);
3155
3156 if (interval !== null)
3157 return Request.poll.add(interval, url, { method: method, query: data }, cb);
3158 else
3159 return Request.request(url, { method: method, query: data })
3160 .then(function(res) {
3161 var json = null;
3162 if (/^application\/json\b/.test(res.headers.get('Content-Type')))
3163 try { json = res.json() } catch(e) {}
3164 cb(res.xhr, json, res.duration);
3165 });
3166 },
3167
3168 /**
3169 * Check whether a view has sufficient permissions.
3170 *
3171 * @return {boolean|null}
3172 * Returns `null` if the current session has no permission at all to
3173 * load resources required by the view. Returns `false` if readonly
3174 * permissions are granted or `true` if at least one required ACL
3175 * group is granted with write permissions.
3176 */
3177 hasViewPermission: function() {
3178 if (!this.isObject(env.nodespec) || !env.nodespec.satisfied)
3179 return null;
3180
3181 return !env.nodespec.readonly;
3182 },
3183
3184 /**
3185 * Deprecated wrapper around {@link LuCI.poll.remove Poll.remove()}.
3186 *
3187 * @deprecated
3188 * @instance
3189 * @memberof LuCI
3190 *
3191 * @param {function} entry
3192 * The polling function to remove.
3193 *
3194 * @return {boolean}
3195 * Returns `true` when the function has been removed or `false` if
3196 * it could not be found.
3197 */
3198 stop: function(entry) { return Poll.remove(entry) },
3199
3200 /**
3201 * Deprecated wrapper around {@link LuCI.poll.stop Poll.stop()}.
3202 *
3203 * @deprecated
3204 * @instance
3205 * @memberof LuCI
3206 *
3207 * @return {boolean}
3208 * Returns `true` when the polling loop has been stopped or `false`
3209 * when it didn't run to begin with.
3210 */
3211 halt: function() { return Poll.stop() },
3212
3213 /**
3214 * Deprecated wrapper around {@link LuCI.poll.start Poll.start()}.
3215 *
3216 * @deprecated
3217 * @instance
3218 * @memberof LuCI
3219 *
3220 * @return {boolean}
3221 * Returns `true` when the polling loop has been started or `false`
3222 * when it was already running.
3223 */
3224 run: function() { return Poll.start() },
3225
3226 /**
3227 * Legacy `L.dom` class alias. New view code should use `'require dom';`
3228 * to request the `LuCI.dom` class.
3229 *
3230 * @instance
3231 * @memberof LuCI
3232 * @deprecated
3233 */
3234 dom: DOM,
3235
3236 /**
3237 * Legacy `L.view` class alias. New view code should use `'require view';`
3238 * to request the `LuCI.view` class.
3239 *
3240 * @instance
3241 * @memberof LuCI
3242 * @deprecated
3243 */
3244 view: View,
3245
3246 /**
3247 * Legacy `L.Poll` class alias. New view code should use `'require poll';`
3248 * to request the `LuCI.poll` class.
3249 *
3250 * @instance
3251 * @memberof LuCI
3252 * @deprecated
3253 */
3254 Poll: Poll,
3255
3256 /**
3257 * Legacy `L.Request` class alias. New view code should use `'require request';`
3258 * to request the `LuCI.request` class.
3259 *
3260 * @instance
3261 * @memberof LuCI
3262 * @deprecated
3263 */
3264 Request: Request,
3265
3266 /**
3267 * Legacy `L.Class` class alias. New view code should use `'require baseclass';`
3268 * to request the `LuCI.baseclass` class.
3269 *
3270 * @instance
3271 * @memberof LuCI
3272 * @deprecated
3273 */
3274 Class: Class
3275 });
3276
3277 /**
3278 * @class xhr
3279 * @memberof LuCI
3280 * @deprecated
3281 * @classdesc
3282 *
3283 * The `LuCI.xhr` class is a legacy compatibility shim for the
3284 * functionality formerly provided by `xhr.js`. It is registered as global
3285 * `window.XHR` symbol for compatibility with legacy code.
3286 *
3287 * New code should use {@link LuCI.request} instead to implement HTTP
3288 * request handling.
3289 */
3290 var XHR = Class.extend(/** @lends LuCI.xhr.prototype */ {
3291 __name__: 'LuCI.xhr',
3292 __init__: function() {
3293 if (window.console && console.debug)
3294 console.debug('Direct use XHR() is deprecated, please use L.Request instead');
3295 },
3296
3297 _response: function(cb, res, json, duration) {
3298 if (this.active)
3299 cb(res, json, duration);
3300 delete this.active;
3301 },
3302
3303 /**
3304 * This function is a legacy wrapper around
3305 * {@link LuCI#get LuCI.get()}.
3306 *
3307 * @instance
3308 * @deprecated
3309 * @memberof LuCI.xhr
3310 *
3311 * @param {string} url
3312 * The URL to request
3313 *
3314 * @param {Object} [data]
3315 * Additional query string data
3316 *
3317 * @param {LuCI.requestCallbackFn} [callback]
3318 * Callback function to invoke on completion
3319 *
3320 * @param {number} [timeout]
3321 * Request timeout to use
3322 *
3323 * @return {Promise<null>}
3324 */
3325 get: function(url, data, callback, timeout) {
3326 this.active = true;
3327 LuCI.prototype.get(url, data, this._response.bind(this, callback), timeout);
3328 },
3329
3330 /**
3331 * This function is a legacy wrapper around
3332 * {@link LuCI#post LuCI.post()}.
3333 *
3334 * @instance
3335 * @deprecated
3336 * @memberof LuCI.xhr
3337 *
3338 * @param {string} url
3339 * The URL to request
3340 *
3341 * @param {Object} [data]
3342 * Additional data to append to the request body.
3343 *
3344 * @param {LuCI.requestCallbackFn} [callback]
3345 * Callback function to invoke on completion
3346 *
3347 * @param {number} [timeout]
3348 * Request timeout to use
3349 *
3350 * @return {Promise<null>}
3351 */
3352 post: function(url, data, callback, timeout) {
3353 this.active = true;
3354 LuCI.prototype.post(url, data, this._response.bind(this, callback), timeout);
3355 },
3356
3357 /**
3358 * Cancels a running request.
3359 *
3360 * This function does not actually cancel the underlying
3361 * `XMLHTTPRequest` request but it sets a flag which prevents the
3362 * invocation of the callback function when the request eventually
3363 * finishes or timed out.
3364 *
3365 * @instance
3366 * @deprecated
3367 * @memberof LuCI.xhr
3368 */
3369 cancel: function() { delete this.active },
3370
3371 /**
3372 * Checks the running state of the request.
3373 *
3374 * @instance
3375 * @deprecated
3376 * @memberof LuCI.xhr
3377 *
3378 * @returns {boolean}
3379 * Returns `true` if the request is still running or `false` if it
3380 * already completed.
3381 */
3382 busy: function() { return (this.active === true) },
3383
3384 /**
3385 * Ignored for backwards compatibility.
3386 *
3387 * This function does nothing.
3388 *
3389 * @instance
3390 * @deprecated
3391 * @memberof LuCI.xhr
3392 */
3393 abort: function() {},
3394
3395 /**
3396 * Existing for backwards compatibility.
3397 *
3398 * This function simply throws an `InternalError` when invoked.
3399 *
3400 * @instance
3401 * @deprecated
3402 * @memberof LuCI.xhr
3403 *
3404 * @throws {InternalError}
3405 * Throws an `InternalError` with the message `Not implemented`
3406 * when invoked.
3407 */
3408 send_form: function() { LuCI.prototype.error('InternalError', 'Not implemented') },
3409 });
3410
3411 XHR.get = function() { return LuCI.prototype.get.apply(LuCI.prototype, arguments) };
3412 XHR.post = function() { return LuCI.prototype.post.apply(LuCI.prototype, arguments) };
3413 XHR.poll = function() { return LuCI.prototype.poll.apply(LuCI.prototype, arguments) };
3414 XHR.stop = Request.poll.remove.bind(Request.poll);
3415 XHR.halt = Request.poll.stop.bind(Request.poll);
3416 XHR.run = Request.poll.start.bind(Request.poll);
3417 XHR.running = Request.poll.active.bind(Request.poll);
3418
3419 window.XHR = XHR;
3420 window.LuCI = LuCI;
3421 })(window, document);