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
512 _list_cb: function(msg)
514 /* verify message frame */
515 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
516 throw 'Invalid JSON response';
521 _call_cb: function(msg)
524 var type = Object.prototype.toString;
529 for (var i = 0; i < msg.length; i++)
531 /* verify message frame */
532 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
533 throw 'Invalid JSON response';
535 /* fetch related request info */
536 var req = _luci2.rpc._requests[msg[i].id];
537 if (typeof(req) != 'object')
538 throw 'No related request for JSON response';
540 /* fetch response attribute and verify returned type */
543 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
544 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
548 for (var key in req.expect)
550 if (typeof(ret) != 'undefined' && key != '')
553 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
554 ret = req.expect[key];
561 if (typeof(req.filter) == 'function')
564 req.priv[1] = req.params;
565 ret = req.filter.apply(_luci2.rpc, req.priv);
568 /* store response data */
569 if (typeof(req.index) == 'number')
570 data[req.index] = ret;
574 /* delete request object */
575 delete _luci2.rpc._requests[msg[i].id];
584 for (var i = 0; i < arguments.length; i++)
585 params[i] = arguments[i];
591 params: (params.length > 0) ? params : undefined
594 return this._call(msg, this._list_cb);
599 if (!$.isArray(this._batch))
605 if (!$.isArray(this._batch))
606 return _luci2.deferrable([ ]);
608 var req = this._batch;
612 return this._call(req, this._call_cb);
615 declare: function(options)
620 /* build parameter object */
623 if ($.isArray(options.params))
624 for (p_off = 0; p_off < options.params.length; p_off++)
625 params[options.params[p_off]] = arguments[p_off];
627 /* all remaining arguments are private args */
628 var priv = [ undefined, undefined ];
629 for (; p_off < arguments.length; p_off++)
630 priv.push(arguments[p_off]);
632 /* store request info */
633 var req = _rpc._requests[_rpc._id] = {
634 expect: options.expect,
635 filter: options.filter,
640 /* build message object */
653 /* when a batch is in progress then store index in request data
654 * and push message object onto the stack */
655 if ($.isArray(_rpc._batch))
657 req.index = _rpc._batch.push(msg) - 1;
658 return _luci2.deferrable(msg);
662 return _rpc._call(msg, _rpc._call_cb);
671 return _luci2.session.access('ubus', 'uci', 'commit');
674 add: _luci2.rpc.declare({
677 params: [ 'config', 'type', 'name', 'values' ],
678 expect: { section: '' }
686 configs: _luci2.rpc.declare({
689 expect: { configs: [ ] }
692 _changes: _luci2.rpc.declare({
695 params: [ 'config' ],
696 expect: { changes: [ ] }
699 changes: function(config)
701 if (typeof(config) == 'string')
702 return this._changes(config);
705 return this.configs().then(function(configs) {
707 configlist = configs;
709 for (var i = 0; i < configs.length; i++)
710 _luci2.uci._changes(configs[i]);
712 return _luci2.rpc.flush();
713 }).then(function(changes) {
716 for (var i = 0; i < configlist.length; i++)
717 if (changes[i].length)
718 rv[configlist[i]] = changes[i];
724 commit: _luci2.rpc.declare({
730 _delete_one: _luci2.rpc.declare({
733 params: [ 'config', 'section', 'option' ]
736 _delete_multiple: _luci2.rpc.declare({
739 params: [ 'config', 'section', 'options' ]
742 'delete': function(config, section, option)
744 if ($.isArray(option))
745 return this._delete_multiple(config, section, option);
747 return this._delete_one(config, section, option);
750 delete_all: _luci2.rpc.declare({
753 params: [ 'config', 'type', 'match' ]
756 _foreach: _luci2.rpc.declare({
759 params: [ 'config', 'type' ],
760 expect: { values: { } }
763 foreach: function(config, type, cb)
765 return this._foreach(config, type).then(function(sections) {
766 for (var s in sections)
771 get: _luci2.rpc.declare({
774 params: [ 'config', 'section', 'option' ],
776 filter: function(data, params) {
777 if (typeof(params.option) == 'undefined')
778 return data.values ? data.values['.type'] : undefined;
784 get_all: _luci2.rpc.declare({
787 params: [ 'config', 'section' ],
788 expect: { values: { } },
789 filter: function(data, params) {
790 if (typeof(params.section) == 'string')
791 data['.section'] = params.section;
792 else if (typeof(params.config) == 'string')
793 data['.package'] = params.config;
798 get_first: function(config, type, option)
800 return this._foreach(config, type).then(function(sections) {
801 for (var s in sections)
803 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
805 if (typeof(val) != 'undefined')
813 section: _luci2.rpc.declare({
816 params: [ 'config', 'type', 'name', 'values' ],
817 expect: { section: '' }
820 _set: _luci2.rpc.declare({
823 params: [ 'config', 'section', 'values' ]
826 set: function(config, section, option, value)
828 if (typeof(value) == 'undefined' && typeof(option) == 'string')
829 return this.section(config, section, option); /* option -> type */
830 else if ($.isPlainObject(option))
831 return this._set(config, section, option); /* option -> values */
834 values[option] = value;
836 return this._set(config, section, values);
839 order: _luci2.rpc.declare({
842 params: [ 'config', 'sections' ]
847 listNetworkNames: function() {
848 return _luci2.rpc.list('network.interface.*').then(function(list) {
850 for (var name in list)
851 if (name != 'network.interface.loopback')
852 names.push(name.substring(18));
858 listDeviceNames: _luci2.rpc.declare({
859 object: 'network.device',
862 filter: function(data) {
864 for (var name in data)
872 getNetworkStatus: function()
877 return this.listNetworkNames().then(function(names) {
880 for (var i = 0; i < names.length; i++)
881 _luci2.network.getInterfaceStatus(names[i]);
883 return _luci2.rpc.flush();
884 }).then(function(networks) {
885 for (var i = 0; i < networks.length; i++)
887 var net = nets[i] = networks[i];
888 var dev = net.l3_device || net.l2_device;
890 net.device = devs[dev] || (devs[dev] = { });
895 for (var dev in devs)
896 _luci2.network.getDeviceStatus(dev);
898 return _luci2.rpc.flush();
899 }).then(function(devices) {
902 for (var i = 0; i < devices.length; i++)
904 var brm = devices[i]['bridge-members'];
905 delete devices[i]['bridge-members'];
907 $.extend(devs[devices[i]['device']], devices[i]);
912 devs[devices[i]['device']].subdevices = [ ];
914 for (var j = 0; j < brm.length; j++)
919 _luci2.network.getDeviceStatus(brm[j]);
922 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
926 return _luci2.rpc.flush();
927 }).then(function(subdevices) {
928 for (var i = 0; i < subdevices.length; i++)
929 $.extend(devs[subdevices[i]['device']], subdevices[i]);
933 for (var dev in devs)
934 _luci2.wireless.getDeviceStatus(dev);
936 return _luci2.rpc.flush();
937 }).then(function(wifidevices) {
938 for (var i = 0; i < wifidevices.length; i++)
940 devs[wifidevices[i]['device']].wireless = wifidevices[i];
942 nets.sort(function(a, b) {
943 if (a['interface'] < b['interface'])
945 else if (a['interface'] > b['interface'])
955 findWanInterfaces: function(cb)
957 return this.listNetworkNames().then(function(names) {
960 for (var i = 0; i < names.length; i++)
961 _luci2.network.getInterfaceStatus(names[i]);
963 return _luci2.rpc.flush();
964 }).then(function(interfaces) {
965 var rv = [ undefined, undefined ];
967 for (var i = 0; i < interfaces.length; i++)
969 if (!interfaces[i].route)
972 for (var j = 0; j < interfaces[i].route.length; j++)
974 var rt = interfaces[i].route[j];
976 if (typeof(rt.table) != 'undefined')
979 if (rt.target == '0.0.0.0' && rt.mask == 0)
980 rv[0] = interfaces[i];
981 else if (rt.target == '::' && rt.mask == 0)
982 rv[1] = interfaces[i];
990 getDHCPLeases: _luci2.rpc.declare({
991 object: 'luci2.network',
992 method: 'dhcp_leases',
993 expect: { leases: [ ] }
996 getDHCPv6Leases: _luci2.rpc.declare({
997 object: 'luci2.network',
998 method: 'dhcp6_leases',
999 expect: { leases: [ ] }
1002 getRoutes: _luci2.rpc.declare({
1003 object: 'luci2.network',
1005 expect: { routes: [ ] }
1008 getIPv6Routes: _luci2.rpc.declare({
1009 object: 'luci2.network',
1011 expect: { routes: [ ] }
1014 getARPTable: _luci2.rpc.declare({
1015 object: 'luci2.network',
1016 method: 'arp_table',
1017 expect: { entries: [ ] }
1020 getInterfaceStatus: _luci2.rpc.declare({
1021 object: 'network.interface',
1023 params: [ 'interface' ],
1024 expect: { '': { } },
1025 filter: function(data, params) {
1026 data['interface'] = params['interface'];
1027 data['l2_device'] = data['device'];
1028 delete data['device'];
1033 getDeviceStatus: _luci2.rpc.declare({
1034 object: 'network.device',
1037 expect: { '': { } },
1038 filter: function(data, params) {
1039 data['device'] = params['name'];
1044 getConntrackCount: _luci2.rpc.declare({
1045 object: 'luci2.network',
1046 method: 'conntrack_count',
1047 expect: { '': { count: 0, limit: 0 } }
1050 listSwitchNames: _luci2.rpc.declare({
1051 object: 'luci2.network',
1052 method: 'switch_list',
1053 expect: { switches: [ ] }
1056 getSwitchInfo: _luci2.rpc.declare({
1057 object: 'luci2.network',
1058 method: 'switch_info',
1059 params: [ 'switch' ],
1060 expect: { info: { } },
1061 filter: function(data, params) {
1062 data['attrs'] = data['switch'];
1063 data['vlan_attrs'] = data['vlan'];
1064 data['port_attrs'] = data['port'];
1065 data['switch'] = params['switch'];
1074 getSwitchStatus: _luci2.rpc.declare({
1075 object: 'luci2.network',
1076 method: 'switch_status',
1077 params: [ 'switch' ],
1078 expect: { ports: [ ] }
1082 runPing: _luci2.rpc.declare({
1083 object: 'luci2.network',
1086 expect: { '': { code: -1 } }
1089 runPing6: _luci2.rpc.declare({
1090 object: 'luci2.network',
1093 expect: { '': { code: -1 } }
1096 runTraceroute: _luci2.rpc.declare({
1097 object: 'luci2.network',
1098 method: 'traceroute',
1100 expect: { '': { code: -1 } }
1103 runTraceroute6: _luci2.rpc.declare({
1104 object: 'luci2.network',
1105 method: 'traceroute6',
1107 expect: { '': { code: -1 } }
1110 runNslookup: _luci2.rpc.declare({
1111 object: 'luci2.network',
1114 expect: { '': { code: -1 } }
1118 setUp: _luci2.rpc.declare({
1119 object: 'luci2.network',
1122 expect: { '': { code: -1 } }
1125 setDown: _luci2.rpc.declare({
1126 object: 'luci2.network',
1129 expect: { '': { code: -1 } }
1134 listDeviceNames: _luci2.rpc.declare({
1137 expect: { 'devices': [ ] },
1138 filter: function(data) {
1144 getDeviceStatus: _luci2.rpc.declare({
1147 params: [ 'device' ],
1148 expect: { '': { } },
1149 filter: function(data, params) {
1150 if (!$.isEmptyObject(data))
1152 data['device'] = params['device'];
1159 getAssocList: _luci2.rpc.declare({
1161 method: 'assoclist',
1162 params: [ 'device' ],
1163 expect: { results: [ ] },
1164 filter: function(data, params) {
1165 for (var i = 0; i < data.length; i++)
1166 data[i]['device'] = params['device'];
1168 data.sort(function(a, b) {
1169 if (a.bssid < b.bssid)
1171 else if (a.bssid > b.bssid)
1181 getWirelessStatus: function() {
1182 return this.listDeviceNames().then(function(names) {
1185 for (var i = 0; i < names.length; i++)
1186 _luci2.wireless.getDeviceStatus(names[i]);
1188 return _luci2.rpc.flush();
1189 }).then(function(networks) {
1193 'country', 'channel', 'frequency', 'frequency_offset',
1194 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1198 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1199 'signal', 'noise', 'bitrate', 'encryption'
1202 for (var i = 0; i < networks.length; i++)
1204 var phy = rv[networks[i].phy] || (
1205 rv[networks[i].phy] = { networks: [ ] }
1209 device: networks[i].device
1212 for (var j = 0; j < phy_attrs.length; j++)
1213 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1215 for (var j = 0; j < net_attrs.length; j++)
1216 net[net_attrs[j]] = networks[i][net_attrs[j]];
1218 phy.networks.push(net);
1225 getAssocLists: function()
1227 return this.listDeviceNames().then(function(names) {
1230 for (var i = 0; i < names.length; i++)
1231 _luci2.wireless.getAssocList(names[i]);
1233 return _luci2.rpc.flush();
1234 }).then(function(assoclists) {
1237 for (var i = 0; i < assoclists.length; i++)
1238 for (var j = 0; j < assoclists[i].length; j++)
1239 rv.push(assoclists[i][j]);
1245 formatEncryption: function(enc)
1247 var format_list = function(l, s)
1250 for (var i = 0; i < l.length; i++)
1251 rv.push(l[i].toUpperCase());
1252 return rv.join(s ? s : ', ');
1255 if (!enc || !enc.enabled)
1256 return _luci2.tr('None');
1260 if (enc.wep.length == 2)
1261 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1262 else if (enc.wep[0] == 'shared')
1263 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1265 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1269 if (enc.wpa.length == 2)
1270 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1271 format_list(enc.authentication, '/'),
1272 format_list(enc.ciphers, ', ')
1274 else if (enc.wpa[0] == 2)
1275 return 'WPA2 %s (%s)'.format(
1276 format_list(enc.authentication, '/'),
1277 format_list(enc.ciphers, ', ')
1280 return 'WPA %s (%s)'.format(
1281 format_list(enc.authentication, '/'),
1282 format_list(enc.ciphers, ', ')
1286 return _luci2.tr('Unknown');
1291 getZoneColor: function(zone)
1293 if ($.isPlainObject(zone))
1298 else if (zone == 'wan')
1301 for (var i = 0, hash = 0;
1303 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1305 for (var i = 0, color = '#';
1307 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1312 findZoneByNetwork: function(network)
1315 var zone = undefined;
1317 return _luci2.uci.foreach('firewall', 'zone', function(z) {
1318 if (!z.name || !z.network)
1321 if (!$.isArray(z.network))
1322 z.network = z.network.split(/\s+/);
1324 for (var i = 0; i < z.network.length; i++)
1326 if (z.network[i] == network)
1332 }).then(function() {
1334 zone.color = self.getZoneColor(zone);
1342 getSystemInfo: _luci2.rpc.declare({
1348 getBoardInfo: _luci2.rpc.declare({
1354 getDiskInfo: _luci2.rpc.declare({
1355 object: 'luci2.system',
1360 getInfo: function(cb)
1364 this.getSystemInfo();
1365 this.getBoardInfo();
1368 return _luci2.rpc.flush().then(function(info) {
1371 $.extend(rv, info[0]);
1372 $.extend(rv, info[1]);
1373 $.extend(rv, info[2]);
1379 getProcessList: _luci2.rpc.declare({
1380 object: 'luci2.system',
1381 method: 'process_list',
1382 expect: { processes: [ ] },
1383 filter: function(data) {
1384 data.sort(function(a, b) { return a.pid - b.pid });
1389 getSystemLog: _luci2.rpc.declare({
1390 object: 'luci2.system',
1395 getKernelLog: _luci2.rpc.declare({
1396 object: 'luci2.system',
1401 getZoneInfo: function(cb)
1403 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1406 sendSignal: _luci2.rpc.declare({
1407 object: 'luci2.system',
1408 method: 'process_signal',
1409 params: [ 'pid', 'signal' ],
1410 filter: function(data) {
1415 initList: _luci2.rpc.declare({
1416 object: 'luci2.system',
1417 method: 'init_list',
1418 expect: { initscripts: [ ] },
1419 filter: function(data) {
1420 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1425 initEnabled: function(init, cb)
1427 return this.initList().then(function(list) {
1428 for (var i = 0; i < list.length; i++)
1429 if (list[i].name == init)
1430 return !!list[i].enabled;
1436 initRun: _luci2.rpc.declare({
1437 object: 'luci2.system',
1438 method: 'init_action',
1439 params: [ 'name', 'action' ],
1440 filter: function(data) {
1445 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1446 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1447 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1448 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1449 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1450 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1453 getRcLocal: _luci2.rpc.declare({
1454 object: 'luci2.system',
1455 method: 'rclocal_get',
1456 expect: { data: '' }
1459 setRcLocal: _luci2.rpc.declare({
1460 object: 'luci2.system',
1461 method: 'rclocal_set',
1466 getCrontab: _luci2.rpc.declare({
1467 object: 'luci2.system',
1468 method: 'crontab_get',
1469 expect: { data: '' }
1472 setCrontab: _luci2.rpc.declare({
1473 object: 'luci2.system',
1474 method: 'crontab_set',
1479 getSSHKeys: _luci2.rpc.declare({
1480 object: 'luci2.system',
1481 method: 'sshkeys_get',
1482 expect: { keys: [ ] }
1485 setSSHKeys: _luci2.rpc.declare({
1486 object: 'luci2.system',
1487 method: 'sshkeys_set',
1492 setPassword: _luci2.rpc.declare({
1493 object: 'luci2.system',
1494 method: 'password_set',
1495 params: [ 'user', 'password' ]
1499 listLEDs: _luci2.rpc.declare({
1500 object: 'luci2.system',
1502 expect: { leds: [ ] }
1505 listUSBDevices: _luci2.rpc.declare({
1506 object: 'luci2.system',
1508 expect: { devices: [ ] }
1512 testUpgrade: _luci2.rpc.declare({
1513 object: 'luci2.system',
1514 method: 'upgrade_test',
1518 startUpgrade: _luci2.rpc.declare({
1519 object: 'luci2.system',
1520 method: 'upgrade_start',
1524 cleanUpgrade: _luci2.rpc.declare({
1525 object: 'luci2.system',
1526 method: 'upgrade_clean'
1530 restoreBackup: _luci2.rpc.declare({
1531 object: 'luci2.system',
1532 method: 'backup_restore'
1535 cleanBackup: _luci2.rpc.declare({
1536 object: 'luci2.system',
1537 method: 'backup_clean'
1541 getBackupConfig: _luci2.rpc.declare({
1542 object: 'luci2.system',
1543 method: 'backup_config_get',
1544 expect: { config: '' }
1547 setBackupConfig: _luci2.rpc.declare({
1548 object: 'luci2.system',
1549 method: 'backup_config_set',
1554 listBackup: _luci2.rpc.declare({
1555 object: 'luci2.system',
1556 method: 'backup_list',
1557 expect: { files: [ ] }
1561 testReset: _luci2.rpc.declare({
1562 object: 'luci2.system',
1563 method: 'reset_test',
1564 expect: { supported: false }
1567 startReset: _luci2.rpc.declare({
1568 object: 'luci2.system',
1569 method: 'reset_start'
1573 performReboot: _luci2.rpc.declare({
1574 object: 'luci2.system',
1580 updateLists: _luci2.rpc.declare({
1581 object: 'luci2.opkg',
1586 _allPackages: _luci2.rpc.declare({
1587 object: 'luci2.opkg',
1589 params: [ 'offset', 'limit', 'pattern' ],
1593 _installedPackages: _luci2.rpc.declare({
1594 object: 'luci2.opkg',
1595 method: 'list_installed',
1596 params: [ 'offset', 'limit', 'pattern' ],
1600 _findPackages: _luci2.rpc.declare({
1601 object: 'luci2.opkg',
1603 params: [ 'offset', 'limit', 'pattern' ],
1607 _fetchPackages: function(action, offset, limit, pattern)
1611 return action(offset, limit, pattern).then(function(list) {
1612 if (!list.total || !list.packages)
1613 return { length: 0, total: 0 };
1615 packages.push.apply(packages, list.packages);
1616 packages.total = list.total;
1621 if (packages.length >= limit)
1626 for (var i = offset + packages.length; i < limit; i += 100)
1627 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1629 return _luci2.rpc.flush();
1630 }).then(function(lists) {
1631 for (var i = 0; i < lists.length; i++)
1633 if (!lists[i].total || !lists[i].packages)
1636 packages.push.apply(packages, lists[i].packages);
1637 packages.total = lists[i].total;
1644 listPackages: function(offset, limit, pattern)
1646 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1649 installedPackages: function(offset, limit, pattern)
1651 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1654 findPackages: function(offset, limit, pattern)
1656 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1659 installPackage: _luci2.rpc.declare({
1660 object: 'luci2.opkg',
1662 params: [ 'package' ],
1666 removePackage: _luci2.rpc.declare({
1667 object: 'luci2.opkg',
1669 params: [ 'package' ],
1673 getConfig: _luci2.rpc.declare({
1674 object: 'luci2.opkg',
1675 method: 'config_get',
1676 expect: { config: '' }
1679 setConfig: _luci2.rpc.declare({
1680 object: 'luci2.opkg',
1681 method: 'config_set',
1688 login: _luci2.rpc.declare({
1691 params: [ 'username', 'password' ],
1695 access: _luci2.rpc.declare({
1698 params: [ 'scope', 'object', 'function' ],
1699 expect: { access: false }
1704 return _luci2.session.access('ubus', 'session', 'access');
1707 startHeartbeat: function()
1709 this._hearbeatInterval = window.setInterval(function() {
1710 _luci2.session.isAlive().then(function(alive) {
1713 _luci2.session.stopHeartbeat();
1714 _luci2.ui.login(true);
1718 }, _luci2.globals.timeout * 2);
1721 stopHeartbeat: function()
1723 if (typeof(this._hearbeatInterval) != 'undefined')
1725 window.clearInterval(this._hearbeatInterval);
1726 delete this._hearbeatInterval;
1733 saveScrollTop: function()
1735 this._scroll_top = $(document).scrollTop();
1738 restoreScrollTop: function()
1740 if (typeof(this._scroll_top) == 'undefined')
1743 $(document).scrollTop(this._scroll_top);
1745 delete this._scroll_top;
1748 loading: function(enable)
1750 var win = $(window);
1751 var body = $('body');
1753 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1755 .addClass('modal fade')
1756 .append($('<div />')
1757 .addClass('modal-dialog')
1758 .append($('<div />')
1759 .addClass('modal-content luci2-modal-loader')
1760 .append($('<div />')
1761 .addClass('modal-body')
1762 .text(_luci2.tr('Loading data…')))))
1770 state.modal.modal(enable ? 'show' : 'hide');
1773 dialog: function(title, content, options)
1775 var win = $(window);
1776 var body = $('body');
1778 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1779 dialog: $('<div />')
1780 .addClass('modal fade')
1781 .append($('<div />')
1782 .addClass('modal-dialog')
1783 .append($('<div />')
1784 .addClass('modal-content')
1785 .append($('<div />')
1786 .addClass('modal-header')
1788 .addClass('modal-title'))
1789 .append($('<div />')
1790 .addClass('modal-body'))
1791 .append($('<div />')
1792 .addClass('modal-footer')
1793 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1795 $(this).parents('div.modal').modal('hide');
1800 if (typeof(options) != 'object')
1803 if (title === false)
1805 state.dialog.modal('hide');
1810 var cnt = state.dialog.children().children().children('div.modal-body');
1811 var ftr = state.dialog.children().children().children('div.modal-footer');
1815 if (options.style == 'confirm')
1817 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1818 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1820 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1821 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1823 else if (options.style == 'close')
1825 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1826 .click(options.close || function() { _luci2.ui.dialog(false) }));
1828 else if (options.style == 'wait')
1830 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1831 .attr('disabled', true));
1834 state.dialog.find('h4:first').text(title);
1835 state.dialog.modal('show');
1837 cnt.empty().append(content);
1840 upload: function(title, content, options)
1842 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1844 .attr('method', 'post')
1845 .attr('action', '/cgi-bin/luci-upload')
1846 .attr('enctype', 'multipart/form-data')
1847 .attr('target', 'cbi-fileupload-frame')
1849 .append($('<input />')
1850 .attr('type', 'hidden')
1851 .attr('name', 'sessionid'))
1852 .append($('<input />')
1853 .attr('type', 'hidden')
1854 .attr('name', 'filename'))
1855 .append($('<input />')
1856 .attr('type', 'file')
1857 .attr('name', 'filedata')
1858 .addClass('cbi-input-file'))
1859 .append($('<div />')
1860 .css('width', '100%')
1861 .addClass('progress progress-striped active')
1862 .append($('<div />')
1863 .addClass('progress-bar')
1864 .css('width', '100%')))
1865 .append($('<iframe />')
1866 .addClass('pull-right')
1867 .attr('name', 'cbi-fileupload-frame')
1868 .css('width', '1px')
1869 .css('height', '1px')
1870 .css('visibility', 'hidden')),
1872 finish_cb: function(ev) {
1873 $(this).off('load');
1875 var body = (this.contentDocument || this.contentWindow.document).body;
1876 if (body.firstChild.tagName.toLowerCase() == 'pre')
1877 body = body.firstChild;
1881 json = $.parseJSON(body.innerHTML);
1884 message: _luci2.tr('Invalid server response received'),
1885 error: [ -1, _luci2.tr('Invalid data') ]
1891 L.ui.dialog(L.tr('File upload'), [
1892 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1893 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1894 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1895 ], { style: 'close' });
1897 else if (typeof(state.success_cb) == 'function')
1899 state.success_cb(json);
1903 confirm_cb: function() {
1904 var f = state.form.find('.cbi-input-file');
1905 var b = state.form.find('.progress');
1906 var p = state.form.find('p');
1911 state.form.find('iframe').on('load', state.finish_cb);
1912 state.form.submit();
1916 p.text(_luci2.tr('File upload in progress …'));
1918 state.form.parent().parent().find('button').prop('disabled', true);
1922 state.form.find('.progress').hide();
1923 state.form.find('.cbi-input-file').val('').show();
1924 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1926 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1927 state.form.find('[name=filename]').val(options.filename);
1929 state.success_cb = options.success;
1931 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1933 confirm: state.confirm_cb
1937 reconnect: function()
1939 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1940 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1941 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1943 var interval, timeout;
1946 _luci2.tr('Waiting for device'), [
1947 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1949 .css('width', '100%')
1950 .addClass('progressbar')
1951 .addClass('intermediate')
1952 .append($('<div />')
1953 .css('width', '100%'))
1954 ], { style: 'wait' }
1957 for (var i = 0; i < protocols.length; i++)
1958 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1960 //_luci2.network.getNetworkStatus(function(s) {
1961 // for (var i = 0; i < protocols.length; i++)
1963 // for (var j = 0; j < s.length; j++)
1965 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1966 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1968 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1969 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1972 //}).then(function() {
1973 images.on('load', function() {
1974 var url = this.getAttribute('url');
1975 _luci2.session.isAlive().then(function(access) {
1978 window.clearTimeout(timeout);
1979 window.clearInterval(interval);
1980 _luci2.ui.dialog(false);
1985 location.href = url;
1990 interval = window.setInterval(function() {
1991 images.each(function() {
1992 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1996 timeout = window.setTimeout(function() {
1997 window.clearInterval(interval);
2001 _luci2.tr('Device not responding'),
2002 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2009 login: function(invalid)
2011 var state = _luci2.ui._login || (_luci2.ui._login = {
2014 .attr('method', 'post')
2016 .addClass('alert-message')
2017 .text(_luci2.tr('Wrong username or password given!')))
2019 .append($('<label />')
2020 .text(_luci2.tr('Username'))
2021 .append($('<br />'))
2022 .append($('<input />')
2023 .attr('type', 'text')
2024 .attr('name', 'username')
2025 .attr('value', 'root')
2026 .addClass('form-control')
2027 .keypress(function(ev) {
2028 if (ev.which == 10 || ev.which == 13)
2032 .append($('<label />')
2033 .text(_luci2.tr('Password'))
2034 .append($('<br />'))
2035 .append($('<input />')
2036 .attr('type', 'password')
2037 .attr('name', 'password')
2038 .addClass('form-control')
2039 .keypress(function(ev) {
2040 if (ev.which == 10 || ev.which == 13)
2044 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2046 response_cb: function(response) {
2047 if (!response.ubus_rpc_session)
2049 _luci2.ui.login(true);
2053 _luci2.globals.sid = response.ubus_rpc_session;
2054 _luci2.setHash('id', _luci2.globals.sid);
2055 _luci2.session.startHeartbeat();
2056 _luci2.ui.dialog(false);
2057 state.deferred.resolve();
2061 confirm_cb: function() {
2062 var u = state.form.find('[name=username]').val();
2063 var p = state.form.find('[name=password]').val();
2069 _luci2.tr('Logging in'), [
2070 $('<p />').text(_luci2.tr('Log in in progress …')),
2072 .css('width', '100%')
2073 .addClass('progressbar')
2074 .addClass('intermediate')
2075 .append($('<div />')
2076 .css('width', '100%'))
2077 ], { style: 'wait' }
2080 _luci2.globals.sid = '00000000000000000000000000000000';
2081 _luci2.session.login(u, p).then(state.response_cb);
2085 if (!state.deferred || state.deferred.state() != 'pending')
2086 state.deferred = $.Deferred();
2088 /* try to find sid from hash */
2089 var sid = _luci2.getHash('id');
2090 if (sid && sid.match(/^[a-f0-9]{32}$/))
2092 _luci2.globals.sid = sid;
2093 _luci2.session.isAlive().then(function(access) {
2096 _luci2.session.startHeartbeat();
2097 state.deferred.resolve();
2101 _luci2.setHash('id', undefined);
2106 return state.deferred;
2110 state.form.find('.alert-message').show();
2112 state.form.find('.alert-message').hide();
2114 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2116 confirm: state.confirm_cb
2119 state.form.find('[name=password]').focus();
2121 return state.deferred;
2124 cryptPassword: _luci2.rpc.declare({
2128 expect: { crypt: '' }
2132 _acl_merge_scope: function(acl_scope, scope)
2134 if ($.isArray(scope))
2136 for (var i = 0; i < scope.length; i++)
2137 acl_scope[scope[i]] = true;
2139 else if ($.isPlainObject(scope))
2141 for (var object_name in scope)
2143 if (!$.isArray(scope[object_name]))
2146 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2148 for (var i = 0; i < scope[object_name].length; i++)
2149 acl_object[scope[object_name][i]] = true;
2154 _acl_merge_permission: function(acl_perm, perm)
2156 if ($.isPlainObject(perm))
2158 for (var scope_name in perm)
2160 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2161 this._acl_merge_scope(acl_scope, perm[scope_name]);
2166 _acl_merge_group: function(acl_group, group)
2168 if ($.isPlainObject(group))
2170 if (!acl_group.description)
2171 acl_group.description = group.description;
2175 var acl_perm = acl_group.read || (acl_group.read = { });
2176 this._acl_merge_permission(acl_perm, group.read);
2181 var acl_perm = acl_group.write || (acl_group.write = { });
2182 this._acl_merge_permission(acl_perm, group.write);
2187 _acl_merge_tree: function(acl_tree, tree)
2189 if ($.isPlainObject(tree))
2191 for (var group_name in tree)
2193 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2194 this._acl_merge_group(acl_group, tree[group_name]);
2199 listAvailableACLs: _luci2.rpc.declare({
2202 expect: { acls: [ ] },
2203 filter: function(trees) {
2205 for (var i = 0; i < trees.length; i++)
2206 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2211 renderMainMenu: _luci2.rpc.declare({
2214 expect: { menu: { } },
2215 filter: function(entries) {
2216 _luci2.globals.mainMenu = new _luci2.ui.menu();
2217 _luci2.globals.mainMenu.entries(entries);
2221 .append(_luci2.globals.mainMenu.render(0, 1));
2225 renderViewMenu: function()
2229 .append(_luci2.globals.mainMenu.render(2, 900));
2232 renderView: function()
2234 var node = arguments[0];
2235 var name = node.view.split(/\//).join('.');
2238 for (var i = 1; i < arguments.length; i++)
2239 args.push(arguments[i]);
2241 if (_luci2.globals.currentView)
2242 _luci2.globals.currentView.finish();
2244 _luci2.ui.renderViewMenu();
2247 _luci2._views = { };
2249 _luci2.setHash('view', node.view);
2251 if (_luci2._views[name] instanceof _luci2.ui.view)
2253 _luci2.globals.currentView = _luci2._views[name];
2254 return _luci2._views[name].render.apply(_luci2._views[name], args);
2257 var url = _luci2.globals.resource + '/view/' + name + '.js';
2259 return $.ajax(url, {
2263 }).then(function(data) {
2265 var viewConstructorSource = (
2266 '(function(L, $) { ' +
2268 '})(_luci2, $);\n\n' +
2270 ).format(data, url);
2272 var viewConstructor = eval(viewConstructorSource);
2274 _luci2._views[name] = new viewConstructor({
2276 acls: node.write || { }
2279 _luci2.globals.currentView = _luci2._views[name];
2280 return _luci2._views[name].render.apply(_luci2._views[name], args);
2283 alert('Unable to instantiate view "%s": %s'.format(url, e));
2286 return $.Deferred().resolve();
2290 updateHostname: function()
2292 return _luci2.system.getBoardInfo().then(function(info) {
2294 $('#hostname').text(info.hostname);
2298 updateChanges: function()
2300 return _luci2.uci.changes().then(function(changes) {
2304 for (var config in changes)
2308 for (var i = 0; i < changes[config].length; i++)
2310 var c = changes[config][i];
2319 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2321 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2326 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2328 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2332 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2336 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2340 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2345 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2347 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2352 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2353 n += changes[config].length;
2364 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2365 .click(function(ev) {
2366 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2367 ev.preventDefault();
2377 _luci2.ui.loading(true);
2380 _luci2.ui.updateHostname(),
2381 _luci2.ui.updateChanges(),
2382 _luci2.ui.renderMainMenu()
2384 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2385 _luci2.ui.loading(false);
2390 button: function(label, style, title)
2392 style = style || 'default';
2394 return $('<button />')
2395 .attr('type', 'button')
2396 .attr('title', title ? title : '')
2397 .addClass('btn btn-' + style)
2402 this.ui.AbstractWidget = Class.extend({
2403 i18n: function(text) {
2408 var key = arguments[0];
2411 for (var i = 1; i < arguments.length; i++)
2412 args.push(arguments[i]);
2414 switch (typeof(this.options[key]))
2420 return this.options[key].apply(this, args);
2423 return ''.format.apply('' + this.options[key], args);
2427 toString: function() {
2428 return $('<div />').append(this.render()).html();
2431 insertInto: function(id) {
2432 return $(id).empty().append(this.render());
2435 appendTo: function(id) {
2436 return $(id).append(this.render());
2440 this.ui.view = this.ui.AbstractWidget.extend({
2441 _fetch_template: function()
2443 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2447 success: function(data) {
2448 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2449 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2456 return _luci2.tr(p2);
2459 return _luci2.globals[p2] || '';
2462 return '(?' + match + ')';
2466 $('#maincontent').append(data);
2473 throw "Not implemented";
2478 var container = $('#maincontent');
2483 container.append($('<h2 />').append(this.title));
2485 if (this.description)
2486 container.append($('<p />').append(this.description));
2491 for (var i = 0; i < arguments.length; i++)
2492 args.push(arguments[i]);
2494 return this._fetch_template().then(function() {
2495 return _luci2.deferrable(self.execute.apply(self, args));
2499 repeat: function(func, interval)
2503 if (!self._timeouts)
2504 self._timeouts = [ ];
2506 var index = self._timeouts.length;
2508 if (typeof(interval) != 'number')
2511 var setTimer, runTimer;
2513 setTimer = function() {
2515 self._timeouts[index] = window.setTimeout(runTimer, interval);
2518 runTimer = function() {
2519 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2527 if ($.isArray(this._timeouts))
2529 for (var i = 0; i < this._timeouts.length; i++)
2530 window.clearTimeout(this._timeouts[i]);
2532 delete this._timeouts;
2537 this.ui.menu = this.ui.AbstractWidget.extend({
2542 entries: function(entries)
2544 for (var entry in entries)
2546 var path = entry.split(/\//);
2547 var node = this._nodes;
2549 for (i = 0; i < path.length; i++)
2554 if (!node.childs[path[i]])
2555 node.childs[path[i]] = { };
2557 node = node.childs[path[i]];
2560 $.extend(node, entries[entry]);
2564 _indexcmp: function(a, b)
2566 var x = a.index || 0;
2567 var y = b.index || 0;
2571 firstChildView: function(node)
2577 for (var child in (node.childs || { }))
2578 nodes.push(node.childs[child]);
2580 nodes.sort(this._indexcmp);
2582 for (var i = 0; i < nodes.length; i++)
2584 var child = this.firstChildView(nodes[i]);
2587 for (var key in child)
2588 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2589 node[key] = child[key];
2598 _onclick: function(ev)
2600 _luci2.ui.loading(true);
2601 _luci2.ui.renderView(ev.data).then(function() {
2602 _luci2.ui.loading(false);
2605 ev.preventDefault();
2609 _render: function(childs, level, min, max)
2612 for (var node in childs)
2614 var child = this.firstChildView(childs[node]);
2616 nodes.push(childs[node]);
2619 nodes.sort(this._indexcmp);
2621 var list = $('<ul />');
2624 list.addClass('nav').addClass('navbar-nav');
2625 else if (level == 1)
2626 list.addClass('dropdown-menu').addClass('navbar-inverse');
2628 for (var i = 0; i < nodes.length; i++)
2630 if (!_luci2.globals.defaultNode)
2632 var v = _luci2.getHash('view');
2633 if (!v || v == nodes[i].view)
2634 _luci2.globals.defaultNode = nodes[i];
2637 var item = $('<li />')
2640 .text(_luci2.tr(nodes[i].title)))
2643 if (nodes[i].childs && level < max)
2645 item.addClass('dropdown');