2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = Class.extend;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
373 this.getHash = function(key)
376 var tuples = (location.hash || '#').substring(1).split(/,/);
378 for (var i = 0; i < tuples.length; i++)
380 var tuple = tuples[i].split(/:/);
381 if (tuple.length == 2)
382 data[tuple[0]] = tuple[1];
385 if (typeof(key) != 'undefined')
391 this.toArray = function(x)
401 var l = x.split(/\s+/);
402 for (var i = 0; i < l.length; i++)
411 for (var i = 0; i < x.length; i++)
415 else if ($.isPlainObject(x))
419 if (x.hasOwnProperty(k))
428 this.toObject = function(x)
438 var l = x.split(/\x+/);
439 for (var i = 0; i < l.length; i++)
448 for (var i = 0; i < x.length; i++)
452 else if ($.isPlainObject(x))
461 this.filterArray = function(array, item)
463 if (!$.isArray(array))
466 for (var i = 0; i < array.length; i++)
467 if (array[i] === item)
468 array.splice(i--, 1);
473 this.toClassName = function(str, suffix)
476 var l = str.split(/[\/.]/);
478 for (var i = 0; i < l.length; i++)
480 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
482 if (typeof(suffix) == 'string')
491 sid: '00000000000000000000000000000000'
500 _call: function(req, cb)
502 return $.ajax('/ubus', {
504 contentType: 'application/json',
505 data: JSON.stringify(req),
508 timeout: _luci2.globals.timeout,
513 _list_cb: function(msg)
515 var list = msg.result;
517 /* verify message frame */
518 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
521 return $.Deferred().resolveWith(this, [ list ]);
524 _call_cb: function(msg)
527 var type = Object.prototype.toString;
528 var reqs = this._rpc_req;
530 if (!$.isArray(reqs))
536 for (var i = 0; i < msg.length; i++)
538 /* fetch related request info */
539 var req = _luci2.rpc._requests[reqs[i].id];
540 if (typeof(req) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
553 for (var key in req.expect)
555 if (typeof(ret) != 'undefined' && key != '')
558 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559 ret = req.expect[key];
566 if (typeof(req.filter) == 'function')
569 req.priv[1] = req.params;
570 ret = req.filter.apply(_luci2.rpc, req.priv);
573 /* store response data */
574 if (typeof(req.index) == 'number')
575 data[req.index] = ret;
579 /* delete request object */
580 delete _luci2.rpc._requests[reqs[i].id];
583 return $.Deferred().resolveWith(this, [ data ]);
589 for (var i = 0; i < arguments.length; i++)
590 params[i] = arguments[i];
596 params: (params.length > 0) ? params : undefined
599 return this._call(msg, this._list_cb);
604 if (!$.isArray(this._batch))
610 if (!$.isArray(this._batch))
611 return _luci2.deferrable([ ]);
613 var req = this._batch;
617 return this._call(req, this._call_cb);
620 declare: function(options)
625 /* build parameter object */
628 if ($.isArray(options.params))
629 for (p_off = 0; p_off < options.params.length; p_off++)
630 params[options.params[p_off]] = arguments[p_off];
632 /* all remaining arguments are private args */
633 var priv = [ undefined, undefined ];
634 for (; p_off < arguments.length; p_off++)
635 priv.push(arguments[p_off]);
637 /* store request info */
638 var req = _rpc._requests[_rpc._id] = {
639 expect: options.expect,
640 filter: options.filter,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc._batch))
662 req.index = _rpc._batch.push(msg) - 1;
663 return _luci2.deferrable(msg);
667 return _rpc._call(msg, _rpc._call_cb);
672 this.UCIContext = Class.extend({
686 _load: _luci2.rpc.declare({
689 params: [ 'config' ],
690 expect: { values: { } }
693 _order: _luci2.rpc.declare({
696 params: [ 'config', 'sections' ]
699 _add: _luci2.rpc.declare({
702 params: [ 'config', 'type', 'name', 'values' ],
703 expect: { section: '' }
706 _set: _luci2.rpc.declare({
709 params: [ 'config', 'section', 'values' ]
712 _delete: _luci2.rpc.declare({
715 params: [ 'config', 'section', 'options' ]
718 load: function(packages)
724 if (!$.isArray(packages))
725 packages = [ packages ];
729 for (var i = 0; i < packages.length; i++)
730 if (!seen[packages[i]])
732 pkgs.push(packages[i]);
733 seen[packages[i]] = true;
734 self._load(packages[i]);
737 return _luci2.rpc.flush().then(function(responses) {
738 for (var i = 0; i < responses.length; i++)
739 self.state.values[pkgs[i]] = responses[i];
745 unload: function(packages)
747 if (!$.isArray(packages))
748 packages = [ packages ];
750 for (var i = 0; i < packages.length; i++)
752 delete this.state.values[packages[i]];
753 delete this.state.creates[packages[i]];
754 delete this.state.changes[packages[i]];
755 delete this.state.deletes[packages[i]];
759 add: function(conf, type, name)
761 var c = this.state.creates;
762 var s = '.new.%d'.format(this.state.newid++);
772 '.index': 1000 + this.state.newid
778 remove: function(conf, sid)
780 var n = this.state.creates;
781 var c = this.state.changes;
782 var d = this.state.deletes;
784 /* requested deletion of a just created section */
785 if (sid.indexOf('.new.') == 0)
802 sections: function(conf, type, cb)
805 var v = this.state.values[conf];
806 var n = this.state.creates[conf];
807 var c = this.state.changes[conf];
808 var d = this.state.deletes[conf];
814 if (!d || d[s] !== true)
815 if (!type || v[s]['.type'] == type)
816 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
820 if (!type || n[s]['.type'] == type)
823 sa.sort(function(a, b) {
824 return a['.index'] - b['.index'];
827 for (var i = 0; i < sa.length; i++)
830 if (typeof(cb) == 'function')
831 for (var i = 0; i < sa.length; i++)
832 cb.call(this, sa[i], sa[i]['.name']);
837 get: function(conf, sid, opt)
839 var v = this.state.values;
840 var n = this.state.creates;
841 var c = this.state.changes;
842 var d = this.state.deletes;
844 if (typeof(sid) == 'undefined')
847 /* requested option in a just created section */
848 if (sid.indexOf('.new.') == 0)
853 if (typeof(opt) == 'undefined')
856 return n[conf][sid][opt];
859 /* requested an option value */
860 if (typeof(opt) != 'undefined')
862 /* check whether option was deleted */
863 if (d[conf] && d[conf][sid])
865 if (d[conf][sid] === true)
868 for (var i = 0; i < d[conf][sid].length; i++)
869 if (d[conf][sid][i] == opt)
873 /* check whether option was changed */
874 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
875 return c[conf][sid][opt];
877 /* return base value */
878 if (v[conf] && v[conf][sid])
879 return v[conf][sid][opt];
884 /* requested an entire section */
891 set: function(conf, sid, opt, val)
893 var n = this.state.creates;
894 var c = this.state.changes;
895 var d = this.state.deletes;
897 if (typeof(sid) == 'undefined' ||
898 typeof(opt) == 'undefined' ||
899 opt.charAt(0) == '.')
902 if (sid.indexOf('.new.') == 0)
904 if (n[conf] && n[conf][sid])
906 if (typeof(val) != 'undefined')
907 n[conf][sid][opt] = val;
909 delete n[conf][sid][opt];
912 else if (typeof(val) != 'undefined')
914 /* do not set within deleted section */
915 if (d[conf] && d[conf][sid] === true)
924 /* undelete option */
925 if (d[conf] && d[conf][sid])
926 d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
928 c[conf][sid][opt] = val;
938 if (d[conf][sid] !== true)
939 d[conf][sid].push(opt);
943 unset: function(conf, sid, opt)
945 return this.set(conf, sid, opt, undefined);
952 for (var pkg in this.state.values)
957 return this.load(pkgs);
962 var v = this.state.values;
963 var n = this.state.creates;
964 var r = this.state.reorder;
966 if ($.isEmptyObject(r))
967 return _luci2.deferrable();
972 gather all created and existing sections, sort them according
973 to their index value and issue an uci order call
988 o.sort(function(a, b) {
989 return (a['.index'] - b['.index']);
994 for (var i = 0; i < o.length; i++)
995 sids.push(o[i]['.name']);
997 this._order(c, sids);
1001 this.state.reorder = { };
1002 return _luci2.rpc.flush();
1005 swap: function(conf, sid1, sid2)
1007 var s1 = this.get(conf, sid1);
1008 var s2 = this.get(conf, sid2);
1009 var n1 = s1 ? s1['.index'] : NaN;
1010 var n2 = s2 ? s2['.index'] : NaN;
1012 if (isNaN(n1) || isNaN(n2))
1018 this.state.reorder[conf] = true;
1030 if (self.state.creates)
1031 for (var c in self.state.creates)
1032 for (var s in self.state.creates[c])
1039 for (var k in self.state.creates[c][s])
1042 r.type = self.state.creates[c][s][k];
1043 else if (k == '.create')
1044 r.name = self.state.creates[c][s][k];
1045 else if (k.charAt(0) != '.')
1046 r.values[k] = self.state.creates[c][s][k];
1049 snew.push(self.state.creates[c][s]);
1051 self._add(r.config, r.type, r.name, r.values);
1054 if (self.state.changes)
1055 for (var c in self.state.changes)
1056 for (var s in self.state.changes[c])
1057 self._set(c, s, self.state.changes[c][s]);
1059 if (self.state.deletes)
1060 for (var c in self.state.deletes)
1061 for (var s in self.state.deletes[c])
1063 var o = self.state.deletes[c][s];
1064 self._delete(c, s, (o === true) ? undefined : o);
1067 return _luci2.rpc.flush().then(function(responses) {
1069 array "snew" holds references to the created uci sections,
1070 use it to assign the returned names of the new sections
1072 for (var i = 0; i < snew.length; i++)
1073 snew[i]['.name'] = responses[i];
1075 return self._reorder();
1079 _apply: _luci2.rpc.declare({
1082 params: [ 'timeout', 'rollback' ]
1085 _confirm: _luci2.rpc.declare({
1090 apply: function(timeout)
1093 var date = new Date();
1094 var deferred = $.Deferred();
1096 if (typeof(timeout) != 'number' || timeout < 1)
1099 self._apply(timeout, true).then(function(rv) {
1102 deferred.rejectWith(self, [ rv ]);
1106 var try_deadline = date.getTime() + 1000 * timeout;
1107 var try_confirm = function()
1109 return self._confirm().then(function(rv) {
1112 if (date.getTime() < try_deadline)
1113 window.setTimeout(try_confirm, 250);
1115 deferred.rejectWith(self, [ rv ]);
1120 deferred.resolveWith(self, [ rv ]);
1124 window.setTimeout(try_confirm, 1000);
1130 changes: _luci2.rpc.declare({
1133 expect: { changes: { } }
1136 readable: function(conf)
1138 return _luci2.session.hasACL('uci', conf, 'read');
1141 writable: function(conf)
1143 return _luci2.session.hasACL('uci', conf, 'write');
1147 this.uci = new this.UCIContext();
1150 listDeviceNames: _luci2.rpc.declare({
1153 expect: { 'devices': [ ] },
1154 filter: function(data) {
1160 getDeviceStatus: _luci2.rpc.declare({
1163 params: [ 'device' ],
1164 expect: { '': { } },
1165 filter: function(data, params) {
1166 if (!$.isEmptyObject(data))
1168 data['device'] = params['device'];
1175 getAssocList: _luci2.rpc.declare({
1177 method: 'assoclist',
1178 params: [ 'device' ],
1179 expect: { results: [ ] },
1180 filter: function(data, params) {
1181 for (var i = 0; i < data.length; i++)
1182 data[i]['device'] = params['device'];
1184 data.sort(function(a, b) {
1185 if (a.bssid < b.bssid)
1187 else if (a.bssid > b.bssid)
1197 getWirelessStatus: function() {
1198 return this.listDeviceNames().then(function(names) {
1201 for (var i = 0; i < names.length; i++)
1202 _luci2.wireless.getDeviceStatus(names[i]);
1204 return _luci2.rpc.flush();
1205 }).then(function(networks) {
1209 'country', 'channel', 'frequency', 'frequency_offset',
1210 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1214 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1215 'signal', 'noise', 'bitrate', 'encryption'
1218 for (var i = 0; i < networks.length; i++)
1220 var phy = rv[networks[i].phy] || (
1221 rv[networks[i].phy] = { networks: [ ] }
1225 device: networks[i].device
1228 for (var j = 0; j < phy_attrs.length; j++)
1229 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1231 for (var j = 0; j < net_attrs.length; j++)
1232 net[net_attrs[j]] = networks[i][net_attrs[j]];
1234 phy.networks.push(net);
1241 getAssocLists: function()
1243 return this.listDeviceNames().then(function(names) {
1246 for (var i = 0; i < names.length; i++)
1247 _luci2.wireless.getAssocList(names[i]);
1249 return _luci2.rpc.flush();
1250 }).then(function(assoclists) {
1253 for (var i = 0; i < assoclists.length; i++)
1254 for (var j = 0; j < assoclists[i].length; j++)
1255 rv.push(assoclists[i][j]);
1261 formatEncryption: function(enc)
1263 var format_list = function(l, s)
1266 for (var i = 0; i < l.length; i++)
1267 rv.push(l[i].toUpperCase());
1268 return rv.join(s ? s : ', ');
1271 if (!enc || !enc.enabled)
1272 return _luci2.tr('None');
1276 if (enc.wep.length == 2)
1277 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1278 else if (enc.wep[0] == 'shared')
1279 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1281 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1285 if (enc.wpa.length == 2)
1286 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1287 format_list(enc.authentication, '/'),
1288 format_list(enc.ciphers, ', ')
1290 else if (enc.wpa[0] == 2)
1291 return 'WPA2 %s (%s)'.format(
1292 format_list(enc.authentication, '/'),
1293 format_list(enc.ciphers, ', ')
1296 return 'WPA %s (%s)'.format(
1297 format_list(enc.authentication, '/'),
1298 format_list(enc.ciphers, ', ')
1302 return _luci2.tr('Unknown');
1307 getZoneColor: function(zone)
1309 if ($.isPlainObject(zone))
1314 else if (zone == 'wan')
1317 for (var i = 0, hash = 0;
1319 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1321 for (var i = 0, color = '#';
1323 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1328 findZoneByNetwork: function(network)
1331 var zone = undefined;
1333 return _luci2.uci.sections('firewall', 'zone', function(z) {
1334 if (!z.name || !z.network)
1337 if (!$.isArray(z.network))
1338 z.network = z.network.split(/\s+/);
1340 for (var i = 0; i < z.network.length; i++)
1342 if (z.network[i] == network)
1348 }).then(function() {
1350 zone.color = self.getZoneColor(zone);
1358 getSystemInfo: _luci2.rpc.declare({
1364 getBoardInfo: _luci2.rpc.declare({
1370 getDiskInfo: _luci2.rpc.declare({
1371 object: 'luci2.system',
1376 getInfo: function(cb)
1380 this.getSystemInfo();
1381 this.getBoardInfo();
1384 return _luci2.rpc.flush().then(function(info) {
1387 $.extend(rv, info[0]);
1388 $.extend(rv, info[1]);
1389 $.extend(rv, info[2]);
1395 getProcessList: _luci2.rpc.declare({
1396 object: 'luci2.system',
1397 method: 'process_list',
1398 expect: { processes: [ ] },
1399 filter: function(data) {
1400 data.sort(function(a, b) { return a.pid - b.pid });
1405 getSystemLog: _luci2.rpc.declare({
1406 object: 'luci2.system',
1411 getKernelLog: _luci2.rpc.declare({
1412 object: 'luci2.system',
1417 getZoneInfo: function(cb)
1419 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1422 sendSignal: _luci2.rpc.declare({
1423 object: 'luci2.system',
1424 method: 'process_signal',
1425 params: [ 'pid', 'signal' ],
1426 filter: function(data) {
1431 initList: _luci2.rpc.declare({
1432 object: 'luci2.system',
1433 method: 'init_list',
1434 expect: { initscripts: [ ] },
1435 filter: function(data) {
1436 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1441 initEnabled: function(init, cb)
1443 return this.initList().then(function(list) {
1444 for (var i = 0; i < list.length; i++)
1445 if (list[i].name == init)
1446 return !!list[i].enabled;
1452 initRun: _luci2.rpc.declare({
1453 object: 'luci2.system',
1454 method: 'init_action',
1455 params: [ 'name', 'action' ],
1456 filter: function(data) {
1461 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1462 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1463 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1464 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1465 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1466 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1469 getRcLocal: _luci2.rpc.declare({
1470 object: 'luci2.system',
1471 method: 'rclocal_get',
1472 expect: { data: '' }
1475 setRcLocal: _luci2.rpc.declare({
1476 object: 'luci2.system',
1477 method: 'rclocal_set',
1482 getCrontab: _luci2.rpc.declare({
1483 object: 'luci2.system',
1484 method: 'crontab_get',
1485 expect: { data: '' }
1488 setCrontab: _luci2.rpc.declare({
1489 object: 'luci2.system',
1490 method: 'crontab_set',
1495 getSSHKeys: _luci2.rpc.declare({
1496 object: 'luci2.system',
1497 method: 'sshkeys_get',
1498 expect: { keys: [ ] }
1501 setSSHKeys: _luci2.rpc.declare({
1502 object: 'luci2.system',
1503 method: 'sshkeys_set',
1508 setPassword: _luci2.rpc.declare({
1509 object: 'luci2.system',
1510 method: 'password_set',
1511 params: [ 'user', 'password' ]
1515 listLEDs: _luci2.rpc.declare({
1516 object: 'luci2.system',
1518 expect: { leds: [ ] }
1521 listUSBDevices: _luci2.rpc.declare({
1522 object: 'luci2.system',
1524 expect: { devices: [ ] }
1528 testUpgrade: _luci2.rpc.declare({
1529 object: 'luci2.system',
1530 method: 'upgrade_test',
1534 startUpgrade: _luci2.rpc.declare({
1535 object: 'luci2.system',
1536 method: 'upgrade_start',
1540 cleanUpgrade: _luci2.rpc.declare({
1541 object: 'luci2.system',
1542 method: 'upgrade_clean'
1546 restoreBackup: _luci2.rpc.declare({
1547 object: 'luci2.system',
1548 method: 'backup_restore'
1551 cleanBackup: _luci2.rpc.declare({
1552 object: 'luci2.system',
1553 method: 'backup_clean'
1557 getBackupConfig: _luci2.rpc.declare({
1558 object: 'luci2.system',
1559 method: 'backup_config_get',
1560 expect: { config: '' }
1563 setBackupConfig: _luci2.rpc.declare({
1564 object: 'luci2.system',
1565 method: 'backup_config_set',
1570 listBackup: _luci2.rpc.declare({
1571 object: 'luci2.system',
1572 method: 'backup_list',
1573 expect: { files: [ ] }
1577 testReset: _luci2.rpc.declare({
1578 object: 'luci2.system',
1579 method: 'reset_test',
1580 expect: { supported: false }
1583 startReset: _luci2.rpc.declare({
1584 object: 'luci2.system',
1585 method: 'reset_start'
1589 performReboot: _luci2.rpc.declare({
1590 object: 'luci2.system',
1596 updateLists: _luci2.rpc.declare({
1597 object: 'luci2.opkg',
1602 _allPackages: _luci2.rpc.declare({
1603 object: 'luci2.opkg',
1605 params: [ 'offset', 'limit', 'pattern' ],
1609 _installedPackages: _luci2.rpc.declare({
1610 object: 'luci2.opkg',
1611 method: 'list_installed',
1612 params: [ 'offset', 'limit', 'pattern' ],
1616 _findPackages: _luci2.rpc.declare({
1617 object: 'luci2.opkg',
1619 params: [ 'offset', 'limit', 'pattern' ],
1623 _fetchPackages: function(action, offset, limit, pattern)
1627 return action(offset, limit, pattern).then(function(list) {
1628 if (!list.total || !list.packages)
1629 return { length: 0, total: 0 };
1631 packages.push.apply(packages, list.packages);
1632 packages.total = list.total;
1637 if (packages.length >= limit)
1642 for (var i = offset + packages.length; i < limit; i += 100)
1643 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1645 return _luci2.rpc.flush();
1646 }).then(function(lists) {
1647 for (var i = 0; i < lists.length; i++)
1649 if (!lists[i].total || !lists[i].packages)
1652 packages.push.apply(packages, lists[i].packages);
1653 packages.total = lists[i].total;
1660 listPackages: function(offset, limit, pattern)
1662 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1665 installedPackages: function(offset, limit, pattern)
1667 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1670 findPackages: function(offset, limit, pattern)
1672 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1675 installPackage: _luci2.rpc.declare({
1676 object: 'luci2.opkg',
1678 params: [ 'package' ],
1682 removePackage: _luci2.rpc.declare({
1683 object: 'luci2.opkg',
1685 params: [ 'package' ],
1689 getConfig: _luci2.rpc.declare({
1690 object: 'luci2.opkg',
1691 method: 'config_get',
1692 expect: { config: '' }
1695 setConfig: _luci2.rpc.declare({
1696 object: 'luci2.opkg',
1697 method: 'config_set',
1704 login: _luci2.rpc.declare({
1707 params: [ 'username', 'password' ],
1711 access: _luci2.rpc.declare({
1714 params: [ 'scope', 'object', 'function' ],
1715 expect: { access: false }
1720 return _luci2.session.access('ubus', 'session', 'access');
1723 startHeartbeat: function()
1725 this._hearbeatInterval = window.setInterval(function() {
1726 _luci2.session.isAlive().then(function(alive) {
1729 _luci2.session.stopHeartbeat();
1730 _luci2.ui.login(true);
1734 }, _luci2.globals.timeout * 2);
1737 stopHeartbeat: function()
1739 if (typeof(this._hearbeatInterval) != 'undefined')
1741 window.clearInterval(this._hearbeatInterval);
1742 delete this._hearbeatInterval;
1749 _fetch_acls: _luci2.rpc.declare({
1755 _fetch_acls_cb: function(acls)
1757 _luci2.session._acls = acls;
1760 updateACLs: function()
1762 return _luci2.session._fetch_acls()
1763 .then(_luci2.session._fetch_acls_cb);
1766 hasACL: function(scope, object, func)
1768 var acls = _luci2.session._acls;
1770 if (typeof(func) == 'undefined')
1771 return (acls && acls[scope] && acls[scope][object]);
1773 if (acls && acls[scope] && acls[scope][object])
1774 for (var i = 0; i < acls[scope][object].length; i++)
1775 if (acls[scope][object][i] == func)
1784 saveScrollTop: function()
1786 this._scroll_top = $(document).scrollTop();
1789 restoreScrollTop: function()
1791 if (typeof(this._scroll_top) == 'undefined')
1794 $(document).scrollTop(this._scroll_top);
1796 delete this._scroll_top;
1799 loading: function(enable)
1801 var win = $(window);
1802 var body = $('body');
1804 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1806 .addClass('modal fade')
1807 .append($('<div />')
1808 .addClass('modal-dialog')
1809 .append($('<div />')
1810 .addClass('modal-content luci2-modal-loader')
1811 .append($('<div />')
1812 .addClass('modal-body')
1813 .text(_luci2.tr('Loading data…')))))
1821 state.modal.modal(enable ? 'show' : 'hide');
1824 dialog: function(title, content, options)
1826 var win = $(window);
1827 var body = $('body');
1829 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1830 dialog: $('<div />')
1831 .addClass('modal fade')
1832 .append($('<div />')
1833 .addClass('modal-dialog')
1834 .append($('<div />')
1835 .addClass('modal-content')
1836 .append($('<div />')
1837 .addClass('modal-header')
1839 .addClass('modal-title'))
1840 .append($('<div />')
1841 .addClass('modal-body'))
1842 .append($('<div />')
1843 .addClass('modal-footer')
1844 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1846 $(this).parents('div.modal').modal('hide');
1851 if (typeof(options) != 'object')
1854 if (title === false)
1856 state.dialog.modal('hide');
1861 var cnt = state.dialog.children().children().children('div.modal-body');
1862 var ftr = state.dialog.children().children().children('div.modal-footer');
1866 if (options.style == 'confirm')
1868 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1869 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1871 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1872 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1874 else if (options.style == 'close')
1876 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1877 .click(options.close || function() { _luci2.ui.dialog(false) }));
1879 else if (options.style == 'wait')
1881 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1882 .attr('disabled', true));
1885 state.dialog.find('h4:first').text(title);
1886 state.dialog.modal('show');
1888 cnt.empty().append(content);
1891 upload: function(title, content, options)
1893 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1895 .attr('method', 'post')
1896 .attr('action', '/cgi-bin/luci-upload')
1897 .attr('enctype', 'multipart/form-data')
1898 .attr('target', 'cbi-fileupload-frame')
1900 .append($('<input />')
1901 .attr('type', 'hidden')
1902 .attr('name', 'sessionid'))
1903 .append($('<input />')
1904 .attr('type', 'hidden')
1905 .attr('name', 'filename'))
1906 .append($('<input />')
1907 .attr('type', 'file')
1908 .attr('name', 'filedata')
1909 .addClass('cbi-input-file'))
1910 .append($('<div />')
1911 .css('width', '100%')
1912 .addClass('progress progress-striped active')
1913 .append($('<div />')
1914 .addClass('progress-bar')
1915 .css('width', '100%')))
1916 .append($('<iframe />')
1917 .addClass('pull-right')
1918 .attr('name', 'cbi-fileupload-frame')
1919 .css('width', '1px')
1920 .css('height', '1px')
1921 .css('visibility', 'hidden')),
1923 finish_cb: function(ev) {
1924 $(this).off('load');
1926 var body = (this.contentDocument || this.contentWindow.document).body;
1927 if (body.firstChild.tagName.toLowerCase() == 'pre')
1928 body = body.firstChild;
1932 json = $.parseJSON(body.innerHTML);
1935 message: _luci2.tr('Invalid server response received'),
1936 error: [ -1, _luci2.tr('Invalid data') ]
1942 L.ui.dialog(L.tr('File upload'), [
1943 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1944 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1945 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1946 ], { style: 'close' });
1948 else if (typeof(state.success_cb) == 'function')
1950 state.success_cb(json);
1954 confirm_cb: function() {
1955 var f = state.form.find('.cbi-input-file');
1956 var b = state.form.find('.progress');
1957 var p = state.form.find('p');
1962 state.form.find('iframe').on('load', state.finish_cb);
1963 state.form.submit();
1967 p.text(_luci2.tr('File upload in progress …'));
1969 state.form.parent().parent().find('button').prop('disabled', true);
1973 state.form.find('.progress').hide();
1974 state.form.find('.cbi-input-file').val('').show();
1975 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1977 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1978 state.form.find('[name=filename]').val(options.filename);
1980 state.success_cb = options.success;
1982 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1984 confirm: state.confirm_cb
1988 reconnect: function()
1990 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1991 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1992 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1994 var interval, timeout;
1997 _luci2.tr('Waiting for device'), [
1998 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
2000 .css('width', '100%')
2001 .addClass('progressbar')
2002 .addClass('intermediate')
2003 .append($('<div />')
2004 .css('width', '100%'))
2005 ], { style: 'wait' }
2008 for (var i = 0; i < protocols.length; i++)
2009 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
2011 //_luci2.network.getNetworkStatus(function(s) {
2012 // for (var i = 0; i < protocols.length; i++)
2014 // for (var j = 0; j < s.length; j++)
2016 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2017 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2019 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2020 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2023 //}).then(function() {
2024 images.on('load', function() {
2025 var url = this.getAttribute('url');
2026 _luci2.session.isAlive().then(function(access) {
2029 window.clearTimeout(timeout);
2030 window.clearInterval(interval);
2031 _luci2.ui.dialog(false);
2036 location.href = url;
2041 interval = window.setInterval(function() {
2042 images.each(function() {
2043 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2047 timeout = window.setTimeout(function() {
2048 window.clearInterval(interval);
2052 _luci2.tr('Device not responding'),
2053 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2060 login: function(invalid)
2062 var state = _luci2.ui._login || (_luci2.ui._login = {
2065 .attr('method', 'post')
2067 .addClass('alert-message')
2068 .text(_luci2.tr('Wrong username or password given!')))
2070 .append($('<label />')
2071 .text(_luci2.tr('Username'))
2072 .append($('<br />'))
2073 .append($('<input />')
2074 .attr('type', 'text')
2075 .attr('name', 'username')
2076 .attr('value', 'root')
2077 .addClass('form-control')
2078 .keypress(function(ev) {
2079 if (ev.which == 10 || ev.which == 13)
2083 .append($('<label />')
2084 .text(_luci2.tr('Password'))
2085 .append($('<br />'))
2086 .append($('<input />')
2087 .attr('type', 'password')
2088 .attr('name', 'password')
2089 .addClass('form-control')
2090 .keypress(function(ev) {
2091 if (ev.which == 10 || ev.which == 13)
2095 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2097 response_cb: function(response) {
2098 if (!response.ubus_rpc_session)
2100 _luci2.ui.login(true);
2104 _luci2.globals.sid = response.ubus_rpc_session;
2105 _luci2.setHash('id', _luci2.globals.sid);
2106 _luci2.session.startHeartbeat();
2107 _luci2.ui.dialog(false);
2108 state.deferred.resolve();
2112 confirm_cb: function() {
2113 var u = state.form.find('[name=username]').val();
2114 var p = state.form.find('[name=password]').val();
2120 _luci2.tr('Logging in'), [
2121 $('<p />').text(_luci2.tr('Log in in progress …')),
2123 .css('width', '100%')
2124 .addClass('progressbar')
2125 .addClass('intermediate')
2126 .append($('<div />')
2127 .css('width', '100%'))
2128 ], { style: 'wait' }
2131 _luci2.globals.sid = '00000000000000000000000000000000';
2132 _luci2.session.login(u, p).then(state.response_cb);
2136 if (!state.deferred || state.deferred.state() != 'pending')
2137 state.deferred = $.Deferred();
2139 /* try to find sid from hash */
2140 var sid = _luci2.getHash('id');
2141 if (sid && sid.match(/^[a-f0-9]{32}$/))
2143 _luci2.globals.sid = sid;
2144 _luci2.session.isAlive().then(function(access) {
2147 _luci2.session.startHeartbeat();
2148 state.deferred.resolve();
2152 _luci2.setHash('id', undefined);
2157 return state.deferred;
2161 state.form.find('.alert-message').show();
2163 state.form.find('.alert-message').hide();
2165 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2167 confirm: state.confirm_cb
2170 state.form.find('[name=password]').focus();
2172 return state.deferred;
2175 cryptPassword: _luci2.rpc.declare({
2179 expect: { crypt: '' }
2183 _acl_merge_scope: function(acl_scope, scope)
2185 if ($.isArray(scope))
2187 for (var i = 0; i < scope.length; i++)
2188 acl_scope[scope[i]] = true;
2190 else if ($.isPlainObject(scope))
2192 for (var object_name in scope)
2194 if (!$.isArray(scope[object_name]))
2197 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2199 for (var i = 0; i < scope[object_name].length; i++)
2200 acl_object[scope[object_name][i]] = true;
2205 _acl_merge_permission: function(acl_perm, perm)
2207 if ($.isPlainObject(perm))
2209 for (var scope_name in perm)
2211 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2212 this._acl_merge_scope(acl_scope, perm[scope_name]);
2217 _acl_merge_group: function(acl_group, group)
2219 if ($.isPlainObject(group))
2221 if (!acl_group.description)
2222 acl_group.description = group.description;
2226 var acl_perm = acl_group.read || (acl_group.read = { });
2227 this._acl_merge_permission(acl_perm, group.read);
2232 var acl_perm = acl_group.write || (acl_group.write = { });
2233 this._acl_merge_permission(acl_perm, group.write);
2238 _acl_merge_tree: function(acl_tree, tree)
2240 if ($.isPlainObject(tree))
2242 for (var group_name in tree)
2244 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2245 this._acl_merge_group(acl_group, tree[group_name]);
2250 listAvailableACLs: _luci2.rpc.declare({
2253 expect: { acls: [ ] },
2254 filter: function(trees) {
2256 for (var i = 0; i < trees.length; i++)
2257 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2262 renderMainMenu: _luci2.rpc.declare({
2265 expect: { menu: { } },
2266 filter: function(entries) {
2267 _luci2.globals.mainMenu = new _luci2.ui.menu();
2268 _luci2.globals.mainMenu.entries(entries);
2272 .append(_luci2.globals.mainMenu.render(0, 1));
2276 renderViewMenu: function()
2280 .append(_luci2.globals.mainMenu.render(2, 900));
2283 renderView: function()
2285 var node = arguments[0];
2286 var name = node.view.split(/\//).join('.');
2289 for (var i = 1; i < arguments.length; i++)
2290 args.push(arguments[i]);
2292 if (_luci2.globals.currentView)
2293 _luci2.globals.currentView.finish();
2295 _luci2.ui.renderViewMenu();
2298 _luci2._views = { };
2300 _luci2.setHash('view', node.view);
2302 if (_luci2._views[name] instanceof _luci2.ui.view)
2304 _luci2.globals.currentView = _luci2._views[name];
2305 return _luci2._views[name].render.apply(_luci2._views[name], args);
2308 var url = _luci2.globals.resource + '/view/' + name + '.js';
2310 return $.ajax(url, {
2314 }).then(function(data) {
2316 var viewConstructorSource = (
2317 '(function(L, $) { ' +
2319 '})(_luci2, $);\n\n' +
2321 ).format(data, url);
2323 var viewConstructor = eval(viewConstructorSource);
2325 _luci2._views[name] = new viewConstructor({
2327 acls: node.write || { }
2330 _luci2.globals.currentView = _luci2._views[name];
2331 return _luci2._views[name].render.apply(_luci2._views[name], args);
2334 alert('Unable to instantiate view "%s": %s'.format(url, e));
2337 return $.Deferred().resolve();
2341 updateHostname: function()
2343 return _luci2.system.getBoardInfo().then(function(info) {
2345 $('#hostname').text(info.hostname);
2349 updateChanges: function()
2351 return _luci2.uci.changes().then(function(changes) {
2355 for (var config in changes)
2359 for (var i = 0; i < changes[config].length; i++)
2361 var c = changes[config][i];
2370 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2372 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2377 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2379 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2383 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2387 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2391 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2396 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2398 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2403 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2404 n += changes[config].length;
2415 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2416 .click(function(ev) {
2417 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2418 ev.preventDefault();
2428 _luci2.ui.loading(true);
2431 _luci2.ui.updateHostname(),
2432 _luci2.ui.updateChanges(),
2433 _luci2.ui.renderMainMenu()
2435 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2436 _luci2.ui.loading(false);
2441 button: function(label, style, title)
2443 style = style || 'default';
2445 return $('<button />')
2446 .attr('type', 'button')
2447 .attr('title', title ? title : '')
2448 .addClass('btn btn-' + style)
2453 this.ui.AbstractWidget = Class.extend({
2454 i18n: function(text) {
2459 var key = arguments[0];
2462 for (var i = 1; i < arguments.length; i++)
2463 args.push(arguments[i]);
2465 switch (typeof(this.options[key]))
2471 return this.options[key].apply(this, args);
2474 return ''.format.apply('' + this.options[key], args);
2478 toString: function() {
2479 return $('<div />').append(this.render()).html();
2482 insertInto: function(id) {
2483 return $(id).empty().append(this.render());
2486 appendTo: function(id) {
2487 return $(id).append(this.render());
2491 this.ui.view = this.ui.AbstractWidget.extend({
2492 _fetch_template: function()
2494 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2498 success: function(data) {
2499 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2500 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2507 return _luci2.tr(p2);
2510 return _luci2.globals[p2] || '';
2513 return '(?' + match + ')';
2517 $('#maincontent').append(data);
2524 throw "Not implemented";
2529 var container = $('#maincontent');
2534 container.append($('<h2 />').append(this.title));
2536 if (this.description)
2537 container.append($('<p />').append(this.description));
2542 for (var i = 0; i < arguments.length; i++)
2543 args.push(arguments[i]);
2545 return this._fetch_template().then(function() {
2546 return _luci2.deferrable(self.execute.apply(self, args));
2550 repeat: function(func, interval)
2554 if (!self._timeouts)
2555 self._timeouts = [ ];
2557 var index = self._timeouts.length;
2559 if (typeof(interval) != 'number')
2562 var setTimer, runTimer;
2564 setTimer = function() {
2566 self._timeouts[index] = window.setTimeout(runTimer, interval);
2569 runTimer = function() {
2570 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2578 if ($.isArray(this._timeouts))
2580 for (var i = 0; i < this._timeouts.length; i++)
2581 window.clearTimeout(this._timeouts[i]);
2583 delete this._timeouts;
2588 this.ui.menu = this.ui.AbstractWidget.extend({
2593 entries: function(entries)
2595 for (var entry in entries)
2597 var path = entry.split(/\//);
2598 var node = this._nodes;
2600 for (i = 0; i < path.length; i++)
2605 if (!node.childs[path[i]])
2606 node.childs[path[i]] = { };
2608 node = node.childs[path[i]];
2611 $.extend(node, entries[entry]);
2615 _indexcmp: function(a, b)
2617 var x = a.index || 0;
2618 var y = b.index || 0;
2622 firstChildView: function(node)
2628 for (var child in (node.childs || { }))
2629 nodes.push(node.childs[child]);
2631 nodes.sort(this._indexcmp);
2633 for (var i = 0; i < nodes.length; i++)
2635 var child = this.firstChildView(nodes[i]);
2638 for (var key in child)
2639 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2640 node[key] = child[key];