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')
394 sid: '00000000000000000000000000000000'
403 _call: function(req, cb)
405 return $.ajax('/ubus', {
407 contentType: 'application/json',
408 data: JSON.stringify(req),
411 timeout: _luci2.globals.timeout
415 _list_cb: function(msg)
417 /* verify message frame */
418 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
419 throw 'Invalid JSON response';
424 _call_cb: function(msg)
427 var type = Object.prototype.toString;
432 for (var i = 0; i < msg.length; i++)
434 /* verify message frame */
435 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
436 throw 'Invalid JSON response';
438 /* fetch related request info */
439 var req = _luci2.rpc._requests[msg[i].id];
440 if (typeof(req) != 'object')
441 throw 'No related request for JSON response';
443 /* fetch response attribute and verify returned type */
446 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
447 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
451 for (var key in req.expect)
453 if (typeof(ret) != 'undefined' && key != '')
456 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
457 ret = req.expect[key];
464 if (typeof(req.filter) == 'function')
467 req.priv[1] = req.params;
468 ret = req.filter.apply(_luci2.rpc, req.priv);
471 /* store response data */
472 if (typeof(req.index) == 'number')
473 data[req.index] = ret;
477 /* delete request object */
478 delete _luci2.rpc._requests[msg[i].id];
487 for (var i = 0; i < arguments.length; i++)
488 params[i] = arguments[i];
494 params: (params.length > 0) ? params : undefined
497 return this._call(msg, this._list_cb);
502 if (!$.isArray(this._batch))
508 if (!$.isArray(this._batch))
509 return _luci2.deferrable([ ]);
511 var req = this._batch;
515 return this._call(req, this._call_cb);
518 declare: function(options)
523 /* build parameter object */
526 if ($.isArray(options.params))
527 for (p_off = 0; p_off < options.params.length; p_off++)
528 params[options.params[p_off]] = arguments[p_off];
530 /* all remaining arguments are private args */
531 var priv = [ undefined, undefined ];
532 for (; p_off < arguments.length; p_off++)
533 priv.push(arguments[p_off]);
535 /* store request info */
536 var req = _rpc._requests[_rpc._id] = {
537 expect: options.expect,
538 filter: options.filter,
543 /* build message object */
556 /* when a batch is in progress then store index in request data
557 * and push message object onto the stack */
558 if ($.isArray(_rpc._batch))
560 req.index = _rpc._batch.push(msg) - 1;
561 return _luci2.deferrable(msg);
565 return _rpc._call(msg, _rpc._call_cb);
574 return _luci2.session.access('ubus', 'uci', 'commit');
577 add: _luci2.rpc.declare({
580 params: [ 'config', 'type', 'name', 'values' ],
581 expect: { section: '' }
589 configs: _luci2.rpc.declare({
592 expect: { configs: [ ] }
595 _changes: _luci2.rpc.declare({
598 params: [ 'config' ],
599 expect: { changes: [ ] }
602 changes: function(config)
604 if (typeof(config) == 'string')
605 return this._changes(config);
608 return this.configs().then(function(configs) {
610 configlist = configs;
612 for (var i = 0; i < configs.length; i++)
613 _luci2.uci._changes(configs[i]);
615 return _luci2.rpc.flush();
616 }).then(function(changes) {
619 for (var i = 0; i < configlist.length; i++)
620 if (changes[i].length)
621 rv[configlist[i]] = changes[i];
627 commit: _luci2.rpc.declare({
633 _delete_one: _luci2.rpc.declare({
636 params: [ 'config', 'section', 'option' ]
639 _delete_multiple: _luci2.rpc.declare({
642 params: [ 'config', 'section', 'options' ]
645 'delete': function(config, section, option)
647 if ($.isArray(option))
648 return this._delete_multiple(config, section, option);
650 return this._delete_one(config, section, option);
653 delete_all: _luci2.rpc.declare({
656 params: [ 'config', 'type', 'match' ]
659 _foreach: _luci2.rpc.declare({
662 params: [ 'config', 'type' ],
663 expect: { values: { } }
666 foreach: function(config, type, cb)
668 return this._foreach(config, type).then(function(sections) {
669 for (var s in sections)
674 get: _luci2.rpc.declare({
677 params: [ 'config', 'section', 'option' ],
679 filter: function(data, params) {
680 if (typeof(params.option) == 'undefined')
681 return data.values ? data.values['.type'] : undefined;
687 get_all: _luci2.rpc.declare({
690 params: [ 'config', 'section' ],
691 expect: { values: { } },
692 filter: function(data, params) {
693 if (typeof(params.section) == 'string')
694 data['.section'] = params.section;
695 else if (typeof(params.config) == 'string')
696 data['.package'] = params.config;
701 get_first: function(config, type, option)
703 return this._foreach(config, type).then(function(sections) {
704 for (var s in sections)
706 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
708 if (typeof(val) != 'undefined')
716 section: _luci2.rpc.declare({
719 params: [ 'config', 'type', 'name', 'values' ],
720 expect: { section: '' }
723 _set: _luci2.rpc.declare({
726 params: [ 'config', 'section', 'values' ]
729 set: function(config, section, option, value)
731 if (typeof(value) == 'undefined' && typeof(option) == 'string')
732 return this.section(config, section, option); /* option -> type */
733 else if ($.isPlainObject(option))
734 return this._set(config, section, option); /* option -> values */
737 values[option] = value;
739 return this._set(config, section, values);
742 order: _luci2.rpc.declare({
745 params: [ 'config', 'sections' ]
750 listNetworkNames: function() {
751 return _luci2.rpc.list('network.interface.*').then(function(list) {
753 for (var name in list)
754 if (name != 'network.interface.loopback')
755 names.push(name.substring(18));
761 listDeviceNames: _luci2.rpc.declare({
762 object: 'network.device',
765 filter: function(data) {
767 for (var name in data)
775 getNetworkStatus: function()
780 return this.listNetworkNames().then(function(names) {
783 for (var i = 0; i < names.length; i++)
784 _luci2.network.getInterfaceStatus(names[i]);
786 return _luci2.rpc.flush();
787 }).then(function(networks) {
788 for (var i = 0; i < networks.length; i++)
790 var net = nets[i] = networks[i];
791 var dev = net.l3_device || net.l2_device;
793 net.device = devs[dev] || (devs[dev] = { });
798 for (var dev in devs)
799 _luci2.network.getDeviceStatus(dev);
801 return _luci2.rpc.flush();
802 }).then(function(devices) {
805 for (var i = 0; i < devices.length; i++)
807 var brm = devices[i]['bridge-members'];
808 delete devices[i]['bridge-members'];
810 $.extend(devs[devices[i]['device']], devices[i]);
815 devs[devices[i]['device']].subdevices = [ ];
817 for (var j = 0; j < brm.length; j++)
822 _luci2.network.getDeviceStatus(brm[j]);
825 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
829 return _luci2.rpc.flush();
830 }).then(function(subdevices) {
831 for (var i = 0; i < subdevices.length; i++)
832 $.extend(devs[subdevices[i]['device']], subdevices[i]);
836 for (var dev in devs)
837 _luci2.wireless.getDeviceStatus(dev);
839 return _luci2.rpc.flush();
840 }).then(function(wifidevices) {
841 for (var i = 0; i < wifidevices.length; i++)
843 devs[wifidevices[i]['device']].wireless = wifidevices[i];
845 nets.sort(function(a, b) {
846 if (a['interface'] < b['interface'])
848 else if (a['interface'] > b['interface'])
858 findWanInterfaces: function(cb)
860 return this.listNetworkNames().then(function(names) {
863 for (var i = 0; i < names.length; i++)
864 _luci2.network.getInterfaceStatus(names[i]);
866 return _luci2.rpc.flush();
867 }).then(function(interfaces) {
868 var rv = [ undefined, undefined ];
870 for (var i = 0; i < interfaces.length; i++)
872 if (!interfaces[i].route)
875 for (var j = 0; j < interfaces[i].route.length; j++)
877 var rt = interfaces[i].route[j];
879 if (typeof(rt.table) != 'undefined')
882 if (rt.target == '0.0.0.0' && rt.mask == 0)
883 rv[0] = interfaces[i];
884 else if (rt.target == '::' && rt.mask == 0)
885 rv[1] = interfaces[i];
893 getDHCPLeases: _luci2.rpc.declare({
894 object: 'luci2.network',
895 method: 'dhcp_leases',
896 expect: { leases: [ ] }
899 getDHCPv6Leases: _luci2.rpc.declare({
900 object: 'luci2.network',
901 method: 'dhcp6_leases',
902 expect: { leases: [ ] }
905 getRoutes: _luci2.rpc.declare({
906 object: 'luci2.network',
908 expect: { routes: [ ] }
911 getIPv6Routes: _luci2.rpc.declare({
912 object: 'luci2.network',
914 expect: { routes: [ ] }
917 getARPTable: _luci2.rpc.declare({
918 object: 'luci2.network',
920 expect: { entries: [ ] }
923 getInterfaceStatus: _luci2.rpc.declare({
924 object: 'network.interface',
926 params: [ 'interface' ],
928 filter: function(data, params) {
929 data['interface'] = params['interface'];
930 data['l2_device'] = data['device'];
931 delete data['device'];
936 getDeviceStatus: _luci2.rpc.declare({
937 object: 'network.device',
941 filter: function(data, params) {
942 data['device'] = params['name'];
947 getConntrackCount: _luci2.rpc.declare({
948 object: 'luci2.network',
949 method: 'conntrack_count',
950 expect: { '': { count: 0, limit: 0 } }
953 listSwitchNames: _luci2.rpc.declare({
954 object: 'luci2.network',
955 method: 'switch_list',
956 expect: { switches: [ ] }
959 getSwitchInfo: _luci2.rpc.declare({
960 object: 'luci2.network',
961 method: 'switch_info',
962 params: [ 'switch' ],
963 expect: { info: { } },
964 filter: function(data, params) {
965 data['attrs'] = data['switch'];
966 data['vlan_attrs'] = data['vlan'];
967 data['port_attrs'] = data['port'];
968 data['switch'] = params['switch'];
977 getSwitchStatus: _luci2.rpc.declare({
978 object: 'luci2.network',
979 method: 'switch_status',
980 params: [ 'switch' ],
981 expect: { ports: [ ] }
985 runPing: _luci2.rpc.declare({
986 object: 'luci2.network',
989 expect: { '': { code: -1 } }
992 runPing6: _luci2.rpc.declare({
993 object: 'luci2.network',
996 expect: { '': { code: -1 } }
999 runTraceroute: _luci2.rpc.declare({
1000 object: 'luci2.network',
1001 method: 'traceroute',
1003 expect: { '': { code: -1 } }
1006 runTraceroute6: _luci2.rpc.declare({
1007 object: 'luci2.network',
1008 method: 'traceroute6',
1010 expect: { '': { code: -1 } }
1013 runNslookup: _luci2.rpc.declare({
1014 object: 'luci2.network',
1017 expect: { '': { code: -1 } }
1021 setUp: _luci2.rpc.declare({
1022 object: 'luci2.network',
1025 expect: { '': { code: -1 } }
1028 setDown: _luci2.rpc.declare({
1029 object: 'luci2.network',
1032 expect: { '': { code: -1 } }
1037 listDeviceNames: _luci2.rpc.declare({
1040 expect: { 'devices': [ ] },
1041 filter: function(data) {
1047 getDeviceStatus: _luci2.rpc.declare({
1050 params: [ 'device' ],
1051 expect: { '': { } },
1052 filter: function(data, params) {
1053 if (!$.isEmptyObject(data))
1055 data['device'] = params['device'];
1062 getAssocList: _luci2.rpc.declare({
1064 method: 'assoclist',
1065 params: [ 'device' ],
1066 expect: { results: [ ] },
1067 filter: function(data, params) {
1068 for (var i = 0; i < data.length; i++)
1069 data[i]['device'] = params['device'];
1071 data.sort(function(a, b) {
1072 if (a.bssid < b.bssid)
1074 else if (a.bssid > b.bssid)
1084 getWirelessStatus: function() {
1085 return this.listDeviceNames().then(function(names) {
1088 for (var i = 0; i < names.length; i++)
1089 _luci2.wireless.getDeviceStatus(names[i]);
1091 return _luci2.rpc.flush();
1092 }).then(function(networks) {
1096 'country', 'channel', 'frequency', 'frequency_offset',
1097 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1101 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1102 'signal', 'noise', 'bitrate', 'encryption'
1105 for (var i = 0; i < networks.length; i++)
1107 var phy = rv[networks[i].phy] || (
1108 rv[networks[i].phy] = { networks: [ ] }
1112 device: networks[i].device
1115 for (var j = 0; j < phy_attrs.length; j++)
1116 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1118 for (var j = 0; j < net_attrs.length; j++)
1119 net[net_attrs[j]] = networks[i][net_attrs[j]];
1121 phy.networks.push(net);
1128 getAssocLists: function()
1130 return this.listDeviceNames().then(function(names) {
1133 for (var i = 0; i < names.length; i++)
1134 _luci2.wireless.getAssocList(names[i]);
1136 return _luci2.rpc.flush();
1137 }).then(function(assoclists) {
1140 for (var i = 0; i < assoclists.length; i++)
1141 for (var j = 0; j < assoclists[i].length; j++)
1142 rv.push(assoclists[i][j]);
1148 formatEncryption: function(enc)
1150 var format_list = function(l, s)
1153 for (var i = 0; i < l.length; i++)
1154 rv.push(l[i].toUpperCase());
1155 return rv.join(s ? s : ', ');
1158 if (!enc || !enc.enabled)
1159 return _luci2.tr('None');
1163 if (enc.wep.length == 2)
1164 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1165 else if (enc.wep[0] == 'shared')
1166 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1168 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1172 if (enc.wpa.length == 2)
1173 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1174 format_list(enc.authentication, '/'),
1175 format_list(enc.ciphers, ', ')
1177 else if (enc.wpa[0] == 2)
1178 return 'WPA2 %s (%s)'.format(
1179 format_list(enc.authentication, '/'),
1180 format_list(enc.ciphers, ', ')
1183 return 'WPA %s (%s)'.format(
1184 format_list(enc.authentication, '/'),
1185 format_list(enc.ciphers, ', ')
1189 return _luci2.tr('Unknown');
1194 getZoneColor: function(zone)
1196 if ($.isPlainObject(zone))
1201 else if (zone == 'wan')
1204 for (var i = 0, hash = 0;
1206 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1208 for (var i = 0, color = '#';
1210 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1215 findZoneByNetwork: function(network)
1218 var zone = undefined;
1220 return _luci2.uci.foreach('firewall', 'zone', function(z) {
1221 if (!z.name || !z.network)
1224 if (!$.isArray(z.network))
1225 z.network = z.network.split(/\s+/);
1227 for (var i = 0; i < z.network.length; i++)
1229 if (z.network[i] == network)
1235 }).then(function() {
1237 zone.color = self.getZoneColor(zone);
1245 getSystemInfo: _luci2.rpc.declare({
1251 getBoardInfo: _luci2.rpc.declare({
1257 getDiskInfo: _luci2.rpc.declare({
1258 object: 'luci2.system',
1263 getInfo: function(cb)
1267 this.getSystemInfo();
1268 this.getBoardInfo();
1271 return _luci2.rpc.flush().then(function(info) {
1274 $.extend(rv, info[0]);
1275 $.extend(rv, info[1]);
1276 $.extend(rv, info[2]);
1282 getProcessList: _luci2.rpc.declare({
1283 object: 'luci2.system',
1284 method: 'process_list',
1285 expect: { processes: [ ] },
1286 filter: function(data) {
1287 data.sort(function(a, b) { return a.pid - b.pid });
1292 getSystemLog: _luci2.rpc.declare({
1293 object: 'luci2.system',
1298 getKernelLog: _luci2.rpc.declare({
1299 object: 'luci2.system',
1304 getZoneInfo: function(cb)
1306 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1309 sendSignal: _luci2.rpc.declare({
1310 object: 'luci2.system',
1311 method: 'process_signal',
1312 params: [ 'pid', 'signal' ],
1313 filter: function(data) {
1318 initList: _luci2.rpc.declare({
1319 object: 'luci2.system',
1320 method: 'init_list',
1321 expect: { initscripts: [ ] },
1322 filter: function(data) {
1323 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1328 initEnabled: function(init, cb)
1330 return this.initList().then(function(list) {
1331 for (var i = 0; i < list.length; i++)
1332 if (list[i].name == init)
1333 return !!list[i].enabled;
1339 initRun: _luci2.rpc.declare({
1340 object: 'luci2.system',
1341 method: 'init_action',
1342 params: [ 'name', 'action' ],
1343 filter: function(data) {
1348 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1349 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1350 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1351 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1352 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1353 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1356 getRcLocal: _luci2.rpc.declare({
1357 object: 'luci2.system',
1358 method: 'rclocal_get',
1359 expect: { data: '' }
1362 setRcLocal: _luci2.rpc.declare({
1363 object: 'luci2.system',
1364 method: 'rclocal_set',
1369 getCrontab: _luci2.rpc.declare({
1370 object: 'luci2.system',
1371 method: 'crontab_get',
1372 expect: { data: '' }
1375 setCrontab: _luci2.rpc.declare({
1376 object: 'luci2.system',
1377 method: 'crontab_set',
1382 getSSHKeys: _luci2.rpc.declare({
1383 object: 'luci2.system',
1384 method: 'sshkeys_get',
1385 expect: { keys: [ ] }
1388 setSSHKeys: _luci2.rpc.declare({
1389 object: 'luci2.system',
1390 method: 'sshkeys_set',
1395 setPassword: _luci2.rpc.declare({
1396 object: 'luci2.system',
1397 method: 'password_set',
1398 params: [ 'user', 'password' ]
1402 listLEDs: _luci2.rpc.declare({
1403 object: 'luci2.system',
1405 expect: { leds: [ ] }
1408 listUSBDevices: _luci2.rpc.declare({
1409 object: 'luci2.system',
1411 expect: { devices: [ ] }
1415 testUpgrade: _luci2.rpc.declare({
1416 object: 'luci2.system',
1417 method: 'upgrade_test',
1421 startUpgrade: _luci2.rpc.declare({
1422 object: 'luci2.system',
1423 method: 'upgrade_start',
1427 cleanUpgrade: _luci2.rpc.declare({
1428 object: 'luci2.system',
1429 method: 'upgrade_clean'
1433 restoreBackup: _luci2.rpc.declare({
1434 object: 'luci2.system',
1435 method: 'backup_restore'
1438 cleanBackup: _luci2.rpc.declare({
1439 object: 'luci2.system',
1440 method: 'backup_clean'
1444 getBackupConfig: _luci2.rpc.declare({
1445 object: 'luci2.system',
1446 method: 'backup_config_get',
1447 expect: { config: '' }
1450 setBackupConfig: _luci2.rpc.declare({
1451 object: 'luci2.system',
1452 method: 'backup_config_set',
1457 listBackup: _luci2.rpc.declare({
1458 object: 'luci2.system',
1459 method: 'backup_list',
1460 expect: { files: [ ] }
1464 testReset: _luci2.rpc.declare({
1465 object: 'luci2.system',
1466 method: 'reset_test',
1467 expect: { supported: false }
1470 startReset: _luci2.rpc.declare({
1471 object: 'luci2.system',
1472 method: 'reset_start'
1476 performReboot: _luci2.rpc.declare({
1477 object: 'luci2.system',
1483 updateLists: _luci2.rpc.declare({
1484 object: 'luci2.opkg',
1489 _allPackages: _luci2.rpc.declare({
1490 object: 'luci2.opkg',
1492 params: [ 'offset', 'limit', 'pattern' ],
1496 _installedPackages: _luci2.rpc.declare({
1497 object: 'luci2.opkg',
1498 method: 'list_installed',
1499 params: [ 'offset', 'limit', 'pattern' ],
1503 _findPackages: _luci2.rpc.declare({
1504 object: 'luci2.opkg',
1506 params: [ 'offset', 'limit', 'pattern' ],
1510 _fetchPackages: function(action, offset, limit, pattern)
1514 return action(offset, limit, pattern).then(function(list) {
1515 if (!list.total || !list.packages)
1516 return { length: 0, total: 0 };
1518 packages.push.apply(packages, list.packages);
1519 packages.total = list.total;
1524 if (packages.length >= limit)
1529 for (var i = offset + packages.length; i < limit; i += 100)
1530 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1532 return _luci2.rpc.flush();
1533 }).then(function(lists) {
1534 for (var i = 0; i < lists.length; i++)
1536 if (!lists[i].total || !lists[i].packages)
1539 packages.push.apply(packages, lists[i].packages);
1540 packages.total = lists[i].total;
1547 listPackages: function(offset, limit, pattern)
1549 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1552 installedPackages: function(offset, limit, pattern)
1554 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1557 findPackages: function(offset, limit, pattern)
1559 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1562 installPackage: _luci2.rpc.declare({
1563 object: 'luci2.opkg',
1565 params: [ 'package' ],
1569 removePackage: _luci2.rpc.declare({
1570 object: 'luci2.opkg',
1572 params: [ 'package' ],
1576 getConfig: _luci2.rpc.declare({
1577 object: 'luci2.opkg',
1578 method: 'config_get',
1579 expect: { config: '' }
1582 setConfig: _luci2.rpc.declare({
1583 object: 'luci2.opkg',
1584 method: 'config_set',
1591 login: _luci2.rpc.declare({
1594 params: [ 'username', 'password' ],
1598 access: _luci2.rpc.declare({
1601 params: [ 'scope', 'object', 'function' ],
1602 expect: { access: false }
1607 return _luci2.session.access('ubus', 'session', 'access');
1610 startHeartbeat: function()
1612 this._hearbeatInterval = window.setInterval(function() {
1613 _luci2.session.isAlive().then(function(alive) {
1616 _luci2.session.stopHeartbeat();
1617 _luci2.ui.login(true);
1621 }, _luci2.globals.timeout * 2);
1624 stopHeartbeat: function()
1626 if (typeof(this._hearbeatInterval) != 'undefined')
1628 window.clearInterval(this._hearbeatInterval);
1629 delete this._hearbeatInterval;
1636 saveScrollTop: function()
1638 this._scroll_top = $(document).scrollTop();
1641 restoreScrollTop: function()
1643 if (typeof(this._scroll_top) == 'undefined')
1646 $(document).scrollTop(this._scroll_top);
1648 delete this._scroll_top;
1651 loading: function(enable)
1653 var win = $(window);
1654 var body = $('body');
1656 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1658 .addClass('modal fade')
1659 .append($('<div />')
1660 .addClass('modal-dialog')
1661 .append($('<div />')
1662 .addClass('modal-content luci2-modal-loader')
1663 .append($('<div />')
1664 .addClass('modal-body')
1665 .text(_luci2.tr('Loading data…')))))
1673 state.modal.modal(enable ? 'show' : 'hide');
1676 dialog: function(title, content, options)
1678 var win = $(window);
1679 var body = $('body');
1681 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1682 dialog: $('<div />')
1683 .addClass('modal fade')
1684 .append($('<div />')
1685 .addClass('modal-dialog')
1686 .append($('<div />')
1687 .addClass('modal-content')
1688 .append($('<div />')
1689 .addClass('modal-header')
1691 .addClass('modal-title'))
1692 .append($('<div />')
1693 .addClass('modal-body'))
1694 .append($('<div />')
1695 .addClass('modal-footer')
1696 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1698 $(this).parents('div.modal').modal('hide');
1703 if (typeof(options) != 'object')
1706 if (title === false)
1708 state.dialog.modal('hide');
1713 var cnt = state.dialog.children().children().children('div.modal-body');
1714 var ftr = state.dialog.children().children().children('div.modal-footer');
1718 if (options.style == 'confirm')
1720 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1721 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1723 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1724 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1726 else if (options.style == 'close')
1728 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1729 .click(options.close || function() { _luci2.ui.dialog(false) }));
1731 else if (options.style == 'wait')
1733 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1734 .attr('disabled', true));
1737 state.dialog.find('h4:first').text(title);
1738 state.dialog.modal('show');
1740 cnt.empty().append(content);
1743 upload: function(title, content, options)
1745 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1747 .attr('method', 'post')
1748 .attr('action', '/cgi-bin/luci-upload')
1749 .attr('enctype', 'multipart/form-data')
1750 .attr('target', 'cbi-fileupload-frame')
1752 .append($('<input />')
1753 .attr('type', 'hidden')
1754 .attr('name', 'sessionid'))
1755 .append($('<input />')
1756 .attr('type', 'hidden')
1757 .attr('name', 'filename'))
1758 .append($('<input />')
1759 .attr('type', 'file')
1760 .attr('name', 'filedata')
1761 .addClass('cbi-input-file'))
1762 .append($('<div />')
1763 .css('width', '100%')
1764 .addClass('progress progress-striped active')
1765 .append($('<div />')
1766 .addClass('progress-bar')
1767 .css('width', '100%')))
1768 .append($('<iframe />')
1769 .addClass('pull-right')
1770 .attr('name', 'cbi-fileupload-frame')
1771 .css('width', '1px')
1772 .css('height', '1px')
1773 .css('visibility', 'hidden')),
1775 finish_cb: function(ev) {
1776 $(this).off('load');
1778 var body = (this.contentDocument || this.contentWindow.document).body;
1779 if (body.firstChild.tagName.toLowerCase() == 'pre')
1780 body = body.firstChild;
1784 json = $.parseJSON(body.innerHTML);
1787 message: _luci2.tr('Invalid server response received'),
1788 error: [ -1, _luci2.tr('Invalid data') ]
1794 L.ui.dialog(L.tr('File upload'), [
1795 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1796 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1797 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1798 ], { style: 'close' });
1800 else if (typeof(state.success_cb) == 'function')
1802 state.success_cb(json);
1806 confirm_cb: function() {
1807 var f = state.form.find('.cbi-input-file');
1808 var b = state.form.find('.progress');
1809 var p = state.form.find('p');
1814 state.form.find('iframe').on('load', state.finish_cb);
1815 state.form.submit();
1819 p.text(_luci2.tr('File upload in progress …'));
1821 state.form.parent().parent().find('button').prop('disabled', true);
1825 state.form.find('.progress').hide();
1826 state.form.find('.cbi-input-file').val('').show();
1827 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1829 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1830 state.form.find('[name=filename]').val(options.filename);
1832 state.success_cb = options.success;
1834 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1836 confirm: state.confirm_cb
1840 reconnect: function()
1842 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1843 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1844 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1846 var interval, timeout;
1849 _luci2.tr('Waiting for device'), [
1850 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1852 .css('width', '100%')
1853 .addClass('progressbar')
1854 .addClass('intermediate')
1855 .append($('<div />')
1856 .css('width', '100%'))
1857 ], { style: 'wait' }
1860 for (var i = 0; i < protocols.length; i++)
1861 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1863 //_luci2.network.getNetworkStatus(function(s) {
1864 // for (var i = 0; i < protocols.length; i++)
1866 // for (var j = 0; j < s.length; j++)
1868 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1869 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1871 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1872 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1875 //}).then(function() {
1876 images.on('load', function() {
1877 var url = this.getAttribute('url');
1878 _luci2.session.isAlive().then(function(access) {
1881 window.clearTimeout(timeout);
1882 window.clearInterval(interval);
1883 _luci2.ui.dialog(false);
1888 location.href = url;
1893 interval = window.setInterval(function() {
1894 images.each(function() {
1895 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1899 timeout = window.setTimeout(function() {
1900 window.clearInterval(interval);
1904 _luci2.tr('Device not responding'),
1905 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1912 login: function(invalid)
1914 var state = _luci2.ui._login || (_luci2.ui._login = {
1917 .attr('method', 'post')
1919 .addClass('alert-message')
1920 .text(_luci2.tr('Wrong username or password given!')))
1922 .append($('<label />')
1923 .text(_luci2.tr('Username'))
1924 .append($('<br />'))
1925 .append($('<input />')
1926 .attr('type', 'text')
1927 .attr('name', 'username')
1928 .attr('value', 'root')
1929 .addClass('form-control')
1930 .keypress(function(ev) {
1931 if (ev.which == 10 || ev.which == 13)
1935 .append($('<label />')
1936 .text(_luci2.tr('Password'))
1937 .append($('<br />'))
1938 .append($('<input />')
1939 .attr('type', 'password')
1940 .attr('name', 'password')
1941 .addClass('form-control')
1942 .keypress(function(ev) {
1943 if (ev.which == 10 || ev.which == 13)
1947 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1949 response_cb: function(response) {
1950 if (!response.ubus_rpc_session)
1952 _luci2.ui.login(true);
1956 _luci2.globals.sid = response.ubus_rpc_session;
1957 _luci2.setHash('id', _luci2.globals.sid);
1958 _luci2.session.startHeartbeat();
1959 _luci2.ui.dialog(false);
1960 state.deferred.resolve();
1964 confirm_cb: function() {
1965 var u = state.form.find('[name=username]').val();
1966 var p = state.form.find('[name=password]').val();
1972 _luci2.tr('Logging in'), [
1973 $('<p />').text(_luci2.tr('Log in in progress …')),
1975 .css('width', '100%')
1976 .addClass('progressbar')
1977 .addClass('intermediate')
1978 .append($('<div />')
1979 .css('width', '100%'))
1980 ], { style: 'wait' }
1983 _luci2.globals.sid = '00000000000000000000000000000000';
1984 _luci2.session.login(u, p).then(state.response_cb);
1988 if (!state.deferred || state.deferred.state() != 'pending')
1989 state.deferred = $.Deferred();
1991 /* try to find sid from hash */
1992 var sid = _luci2.getHash('id');
1993 if (sid && sid.match(/^[a-f0-9]{32}$/))
1995 _luci2.globals.sid = sid;
1996 _luci2.session.isAlive().then(function(access) {
1999 _luci2.session.startHeartbeat();
2000 state.deferred.resolve();
2004 _luci2.setHash('id', undefined);
2009 return state.deferred;
2013 state.form.find('.alert-message').show();
2015 state.form.find('.alert-message').hide();
2017 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2019 confirm: state.confirm_cb
2022 state.form.find('[name=password]').focus();
2024 return state.deferred;
2027 cryptPassword: _luci2.rpc.declare({
2031 expect: { crypt: '' }
2035 _acl_merge_scope: function(acl_scope, scope)
2037 if ($.isArray(scope))
2039 for (var i = 0; i < scope.length; i++)
2040 acl_scope[scope[i]] = true;
2042 else if ($.isPlainObject(scope))
2044 for (var object_name in scope)
2046 if (!$.isArray(scope[object_name]))
2049 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2051 for (var i = 0; i < scope[object_name].length; i++)
2052 acl_object[scope[object_name][i]] = true;
2057 _acl_merge_permission: function(acl_perm, perm)
2059 if ($.isPlainObject(perm))
2061 for (var scope_name in perm)
2063 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2064 this._acl_merge_scope(acl_scope, perm[scope_name]);
2069 _acl_merge_group: function(acl_group, group)
2071 if ($.isPlainObject(group))
2073 if (!acl_group.description)
2074 acl_group.description = group.description;
2078 var acl_perm = acl_group.read || (acl_group.read = { });
2079 this._acl_merge_permission(acl_perm, group.read);
2084 var acl_perm = acl_group.write || (acl_group.write = { });
2085 this._acl_merge_permission(acl_perm, group.write);
2090 _acl_merge_tree: function(acl_tree, tree)
2092 if ($.isPlainObject(tree))
2094 for (var group_name in tree)
2096 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2097 this._acl_merge_group(acl_group, tree[group_name]);
2102 listAvailableACLs: _luci2.rpc.declare({
2105 expect: { acls: [ ] },
2106 filter: function(trees) {
2108 for (var i = 0; i < trees.length; i++)
2109 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2114 renderMainMenu: _luci2.rpc.declare({
2117 expect: { menu: { } },
2118 filter: function(entries) {
2119 _luci2.globals.mainMenu = new _luci2.ui.menu();
2120 _luci2.globals.mainMenu.entries(entries);
2124 .append(_luci2.globals.mainMenu.render(0, 1));
2128 renderViewMenu: function()
2132 .append(_luci2.globals.mainMenu.render(2, 900));
2135 renderView: function()
2137 var node = arguments[0];
2138 var name = node.view.split(/\//).join('.');
2141 for (var i = 1; i < arguments.length; i++)
2142 args.push(arguments[i]);
2144 if (_luci2.globals.currentView)
2145 _luci2.globals.currentView.finish();
2147 _luci2.ui.renderViewMenu();
2150 _luci2._views = { };
2152 _luci2.setHash('view', node.view);
2154 if (_luci2._views[name] instanceof _luci2.ui.view)
2156 _luci2.globals.currentView = _luci2._views[name];
2157 return _luci2._views[name].render.apply(_luci2._views[name], args);
2160 var url = _luci2.globals.resource + '/view/' + name + '.js';
2162 return $.ajax(url, {
2166 }).then(function(data) {
2168 var viewConstructorSource = (
2169 '(function(L, $) { ' +
2171 '})(_luci2, $);\n\n' +
2173 ).format(data, url);
2175 var viewConstructor = eval(viewConstructorSource);
2177 _luci2._views[name] = new viewConstructor({
2179 acls: node.write || { }
2182 _luci2.globals.currentView = _luci2._views[name];
2183 return _luci2._views[name].render.apply(_luci2._views[name], args);
2186 alert('Unable to instantiate view "%s": %s'.format(url, e));
2189 return $.Deferred().resolve();
2193 updateHostname: function()
2195 return _luci2.system.getBoardInfo().then(function(info) {
2197 $('#hostname').text(info.hostname);
2201 updateChanges: function()
2203 return _luci2.uci.changes().then(function(changes) {
2207 for (var config in changes)
2211 for (var i = 0; i < changes[config].length; i++)
2213 var c = changes[config][i];
2222 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2224 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2229 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2231 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2235 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2239 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2243 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2248 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2250 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2255 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2256 n += changes[config].length;
2267 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2268 .click(function(ev) {
2269 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2270 ev.preventDefault();
2280 _luci2.ui.loading(true);
2283 _luci2.ui.updateHostname(),
2284 _luci2.ui.updateChanges(),
2285 _luci2.ui.renderMainMenu()
2287 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2288 _luci2.ui.loading(false);
2293 button: function(label, style, title)
2295 style = style || 'default';
2297 return $('<button />')
2298 .attr('type', 'button')
2299 .attr('title', title ? title : '')
2300 .addClass('btn btn-' + style)
2305 this.ui.AbstractWidget = Class.extend({
2306 i18n: function(text) {
2311 var key = arguments[0];
2314 for (var i = 1; i < arguments.length; i++)
2315 args.push(arguments[i]);
2317 switch (typeof(this.options[key]))
2323 return this.options[key].apply(this, args);
2326 return ''.format.apply('' + this.options[key], args);
2330 toString: function() {
2331 return $('<div />').append(this.render()).html();
2334 insertInto: function(id) {
2335 return $(id).empty().append(this.render());
2338 appendTo: function(id) {
2339 return $(id).append(this.render());
2343 this.ui.view = this.ui.AbstractWidget.extend({
2344 _fetch_template: function()
2346 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2350 success: function(data) {
2351 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2352 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2359 return _luci2.tr(p2);
2362 return _luci2.globals[p2] || '';
2365 return '(?' + match + ')';
2369 $('#maincontent').append(data);
2376 throw "Not implemented";
2381 var container = $('#maincontent');
2386 container.append($('<h2 />').append(this.title));
2388 if (this.description)
2389 container.append($('<p />').append(this.description));
2394 for (var i = 0; i < arguments.length; i++)
2395 args.push(arguments[i]);
2397 return this._fetch_template().then(function() {
2398 return _luci2.deferrable(self.execute.apply(self, args));
2402 repeat: function(func, interval)
2406 if (!self._timeouts)
2407 self._timeouts = [ ];
2409 var index = self._timeouts.length;
2411 if (typeof(interval) != 'number')
2414 var setTimer, runTimer;
2416 setTimer = function() {
2418 self._timeouts[index] = window.setTimeout(runTimer, interval);
2421 runTimer = function() {
2422 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2430 if ($.isArray(this._timeouts))
2432 for (var i = 0; i < this._timeouts.length; i++)
2433 window.clearTimeout(this._timeouts[i]);
2435 delete this._timeouts;
2440 this.ui.menu = this.ui.AbstractWidget.extend({
2445 entries: function(entries)
2447 for (var entry in entries)
2449 var path = entry.split(/\//);
2450 var node = this._nodes;
2452 for (i = 0; i < path.length; i++)
2457 if (!node.childs[path[i]])
2458 node.childs[path[i]] = { };
2460 node = node.childs[path[i]];
2463 $.extend(node, entries[entry]);
2467 _indexcmp: function(a, b)
2469 var x = a.index || 0;
2470 var y = b.index || 0;
2474 firstChildView: function(node)
2480 for (var child in (node.childs || { }))
2481 nodes.push(node.childs[child]);
2483 nodes.sort(this._indexcmp);
2485 for (var i = 0; i < nodes.length; i++)
2487 var child = this.firstChildView(nodes[i]);
2490 for (var key in child)
2491 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2492 node[key] = child[key];
2501 _onclick: function(ev)
2503 _luci2.ui.loading(true);
2504 _luci2.ui.renderView(ev.data).then(function() {
2505 _luci2.ui.loading(false);
2508 ev.preventDefault();
2512 _render: function(childs, level, min, max)
2515 for (var node in childs)
2517 var child = this.firstChildView(childs[node]);
2519 nodes.push(childs[node]);
2522 nodes.sort(this._indexcmp);
2524 var list = $('<ul />');
2527 list.addClass('nav').addClass('navbar-nav');
2528 else if (level == 1)
2529 list.addClass('dropdown-menu').addClass('navbar-inverse');
2531 for (var i = 0; i < nodes.length; i++)
2533 if (!_luci2.globals.defaultNode)
2535 var v = _luci2.getHash('view');
2536 if (!v || v == nodes[i].view)
2537 _luci2.globals.defaultNode = nodes[i];
2540 var item = $('<li />')
2543 .text(_luci2.tr(nodes[i].title)))
2546 if (nodes[i].childs && level < max)
2548 item.addClass('dropdown');
2551 .addClass('dropdown-toggle')
2552 .attr('data-toggle', 'dropdown')
2553 .append('<b class="caret"></b>');
2555 item.append(this._render(nodes[i].childs, level + 1));
2559 item.find('a').click(nodes[i], this._onclick);
2566 render: function(min, max)
2568 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2569 return this._render(top.childs, 0, min, max);
2572 getNode: function(path, max)
2574 var p = path.split(/\//);
2575 var n = this._nodes;
2577 if (typeof(max) == 'undefined')
2580 for (var i = 0; i < max; i++)
2582 if (!n.childs[p[i]])
2592 this.ui.table = this.ui.AbstractWidget.extend({
2598 row: function(values)
2600 if ($.isArray(values))
2602 this._rows.push(values);
2604 else if ($.isPlainObject(values))
2607 for (var i = 0; i < this.options.columns.length; i++)
2609 var col = this.options.columns[i];
2611 if (typeof col.key == 'string')
2612 v.push(values[col.key]);
2620 rows: function(rows)
2622 for (var i = 0; i < rows.length; i++)
2626 render: function(id)
2628 var fieldset = document.createElement('fieldset');
2629 fieldset.className = 'cbi-section';
2631 if (this.options.caption)
2633 var legend = document.createElement('legend');
2634 $(legend).append(this.options.caption);
2635 fieldset.appendChild(legend);
2638 var table = document.createElement('table');
2639 table.className = 'table table-condensed table-hover';
2641 var has_caption = false;
2642 var has_description = false;
2644 for (var i = 0; i < this.options.columns.length; i++)