2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = Class.extend;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
373 this.getHash = function(key)
376 var tuples = (location.hash || '#').substring(1).split(/,/);
378 for (var i = 0; i < tuples.length; i++)
380 var tuple = tuples[i].split(/:/);
381 if (tuple.length == 2)
382 data[tuple[0]] = tuple[1];
385 if (typeof(key) != 'undefined')
391 this.toArray = function(x)
401 var l = x.split(/\s+/);
402 for (var i = 0; i < l.length; i++)
411 for (var i = 0; i < x.length; i++)
415 else if ($.isPlainObject(x))
419 if (x.hasOwnProperty(k))
428 this.toObject = function(x)
438 var l = x.split(/\x+/);
439 for (var i = 0; i < l.length; i++)
448 for (var i = 0; i < x.length; i++)
452 else if ($.isPlainObject(x))
461 this.filterArray = function(array, item)
463 if (!$.isArray(array))
466 for (var i = 0; i < array.length; i++)
467 if (array[i] === item)
468 array.splice(i--, 1);
473 this.toClassName = function(str, suffix)
476 var l = str.split(/[\/.]/);
478 for (var i = 0; i < l.length; i++)
480 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
482 if (typeof(suffix) == 'string')
491 sid: '00000000000000000000000000000000'
500 _call: function(req, cb)
502 return $.ajax('/ubus', {
504 contentType: 'application/json',
505 data: JSON.stringify(req),
508 timeout: _luci2.globals.timeout,
513 _list_cb: function(msg)
515 var list = msg.result;
517 /* verify message frame */
518 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
521 return $.Deferred().resolveWith(this, [ list ]);
524 _call_cb: function(msg)
527 var type = Object.prototype.toString;
528 var reqs = this._rpc_req;
530 if (!$.isArray(reqs))
536 for (var i = 0; i < msg.length; i++)
538 /* fetch related request info */
539 var req = _luci2.rpc._requests[reqs[i].id];
540 if (typeof(req) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
553 for (var key in req.expect)
555 if (typeof(ret) != 'undefined' && key != '')
558 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559 ret = req.expect[key];
566 if (typeof(req.filter) == 'function')
569 req.priv[1] = req.params;
570 ret = req.filter.apply(_luci2.rpc, req.priv);
573 /* store response data */
574 if (typeof(req.index) == 'number')
575 data[req.index] = ret;
579 /* delete request object */
580 delete _luci2.rpc._requests[reqs[i].id];
583 return $.Deferred().resolveWith(this, [ data ]);
589 for (var i = 0; i < arguments.length; i++)
590 params[i] = arguments[i];
596 params: (params.length > 0) ? params : undefined
599 return this._call(msg, this._list_cb);
604 if (!$.isArray(this._batch))
610 if (!$.isArray(this._batch))
611 return _luci2.deferrable([ ]);
613 var req = this._batch;
617 return this._call(req, this._call_cb);
620 declare: function(options)
625 /* build parameter object */
628 if ($.isArray(options.params))
629 for (p_off = 0; p_off < options.params.length; p_off++)
630 params[options.params[p_off]] = arguments[p_off];
632 /* all remaining arguments are private args */
633 var priv = [ undefined, undefined ];
634 for (; p_off < arguments.length; p_off++)
635 priv.push(arguments[p_off]);
637 /* store request info */
638 var req = _rpc._requests[_rpc._id] = {
639 expect: options.expect,
640 filter: options.filter,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc._batch))
662 req.index = _rpc._batch.push(msg) - 1;
663 return _luci2.deferrable(msg);
667 return _rpc._call(msg, _rpc._call_cb);
676 return _luci2.session.access('ubus', 'uci', 'commit');
679 add: _luci2.rpc.declare({
682 params: [ 'config', 'type', 'name', 'values' ],
683 expect: { section: '' }
691 configs: _luci2.rpc.declare({
694 expect: { configs: [ ] }
697 _changes: _luci2.rpc.declare({
700 params: [ 'config' ],
701 expect: { changes: [ ] }
704 changes: function(config)
706 if (typeof(config) == 'string')
707 return this._changes(config);
710 return this.configs().then(function(configs) {
712 configlist = configs;
714 for (var i = 0; i < configs.length; i++)
715 _luci2.uci._changes(configs[i]);
717 return _luci2.rpc.flush();
718 }).then(function(changes) {
721 for (var i = 0; i < configlist.length; i++)
722 if (changes[i].length)
723 rv[configlist[i]] = changes[i];
729 commit: _luci2.rpc.declare({
735 _delete_one: _luci2.rpc.declare({
738 params: [ 'config', 'section', 'option' ]
741 _delete_multiple: _luci2.rpc.declare({
744 params: [ 'config', 'section', 'options' ]
747 'delete': function(config, section, option)
749 if ($.isArray(option))
750 return this._delete_multiple(config, section, option);
752 return this._delete_one(config, section, option);
755 delete_all: _luci2.rpc.declare({
758 params: [ 'config', 'type', 'match' ]
761 _foreach: _luci2.rpc.declare({
764 params: [ 'config', 'type' ],
765 expect: { values: { } }
768 foreach: function(config, type, cb)
770 return this._foreach(config, type).then(function(sections) {
771 for (var s in sections)
776 get: _luci2.rpc.declare({
779 params: [ 'config', 'section', 'option' ],
781 filter: function(data, params) {
782 if (typeof(params.option) == 'undefined')
783 return data.values ? data.values['.type'] : undefined;
789 get_all: _luci2.rpc.declare({
792 params: [ 'config', 'section' ],
793 expect: { values: { } },
794 filter: function(data, params) {
795 if (typeof(params.section) == 'string')
796 data['.section'] = params.section;
797 else if (typeof(params.config) == 'string')
798 data['.package'] = params.config;
803 get_first: function(config, type, option)
805 return this._foreach(config, type).then(function(sections) {
806 for (var s in sections)
808 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
810 if (typeof(val) != 'undefined')
818 section: _luci2.rpc.declare({
821 params: [ 'config', 'type', 'name', 'values' ],
822 expect: { section: '' }
825 _set: _luci2.rpc.declare({
828 params: [ 'config', 'section', 'values' ]
831 set: function(config, section, option, value)
833 if (typeof(value) == 'undefined' && typeof(option) == 'string')
834 return this.section(config, section, option); /* option -> type */
835 else if ($.isPlainObject(option))
836 return this._set(config, section, option); /* option -> values */
839 values[option] = value;
841 return this._set(config, section, values);
844 order: _luci2.rpc.declare({
847 params: [ 'config', 'sections' ]
852 listNetworkNames: function() {
853 return _luci2.rpc.list('network.interface.*').then(function(list) {
855 for (var name in list)
856 if (name != 'network.interface.loopback')
857 names.push(name.substring(18));
863 listDeviceNames: _luci2.rpc.declare({
864 object: 'network.device',
867 filter: function(data) {
869 for (var name in data)
877 getNetworkStatus: function()
882 return this.listNetworkNames().then(function(names) {
885 for (var i = 0; i < names.length; i++)
886 _luci2.network.getInterfaceStatus(names[i]);
888 return _luci2.rpc.flush();
889 }).then(function(networks) {
890 for (var i = 0; i < networks.length; i++)
892 var net = nets[i] = networks[i];
893 var dev = net.l3_device || net.l2_device;
895 net.device = devs[dev] || (devs[dev] = { });
900 for (var dev in devs)
901 _luci2.network.getDeviceStatus(dev);
903 return _luci2.rpc.flush();
904 }).then(function(devices) {
907 for (var i = 0; i < devices.length; i++)
909 var brm = devices[i]['bridge-members'];
910 delete devices[i]['bridge-members'];
912 $.extend(devs[devices[i]['device']], devices[i]);
917 devs[devices[i]['device']].subdevices = [ ];
919 for (var j = 0; j < brm.length; j++)
924 _luci2.network.getDeviceStatus(brm[j]);
927 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
931 return _luci2.rpc.flush();
932 }).then(function(subdevices) {
933 for (var i = 0; i < subdevices.length; i++)
934 $.extend(devs[subdevices[i]['device']], subdevices[i]);
938 for (var dev in devs)
939 _luci2.wireless.getDeviceStatus(dev);
941 return _luci2.rpc.flush();
942 }).then(function(wifidevices) {
943 for (var i = 0; i < wifidevices.length; i++)
945 devs[wifidevices[i]['device']].wireless = wifidevices[i];
947 nets.sort(function(a, b) {
948 if (a['interface'] < b['interface'])
950 else if (a['interface'] > b['interface'])
960 findWanInterfaces: function(cb)
962 return this.listNetworkNames().then(function(names) {
965 for (var i = 0; i < names.length; i++)
966 _luci2.network.getInterfaceStatus(names[i]);
968 return _luci2.rpc.flush();
969 }).then(function(interfaces) {
970 var rv = [ undefined, undefined ];
972 for (var i = 0; i < interfaces.length; i++)
974 if (!interfaces[i].route)
977 for (var j = 0; j < interfaces[i].route.length; j++)
979 var rt = interfaces[i].route[j];
981 if (typeof(rt.table) != 'undefined')
984 if (rt.target == '0.0.0.0' && rt.mask == 0)
985 rv[0] = interfaces[i];
986 else if (rt.target == '::' && rt.mask == 0)
987 rv[1] = interfaces[i];
995 getDHCPLeases: _luci2.rpc.declare({
996 object: 'luci2.network',
997 method: 'dhcp_leases',
998 expect: { leases: [ ] }
1001 getDHCPv6Leases: _luci2.rpc.declare({
1002 object: 'luci2.network',
1003 method: 'dhcp6_leases',
1004 expect: { leases: [ ] }
1007 getRoutes: _luci2.rpc.declare({
1008 object: 'luci2.network',
1010 expect: { routes: [ ] }
1013 getIPv6Routes: _luci2.rpc.declare({
1014 object: 'luci2.network',
1016 expect: { routes: [ ] }
1019 getARPTable: _luci2.rpc.declare({
1020 object: 'luci2.network',
1021 method: 'arp_table',
1022 expect: { entries: [ ] }
1025 getInterfaceStatus: _luci2.rpc.declare({
1026 object: 'network.interface',
1028 params: [ 'interface' ],
1029 expect: { '': { } },
1030 filter: function(data, params) {
1031 data['interface'] = params['interface'];
1032 data['l2_device'] = data['device'];
1033 delete data['device'];
1038 getDeviceStatus: _luci2.rpc.declare({
1039 object: 'network.device',
1042 expect: { '': { } },
1043 filter: function(data, params) {
1044 data['device'] = params['name'];
1049 getConntrackCount: _luci2.rpc.declare({
1050 object: 'luci2.network',
1051 method: 'conntrack_count',
1052 expect: { '': { count: 0, limit: 0 } }
1055 listSwitchNames: _luci2.rpc.declare({
1056 object: 'luci2.network',
1057 method: 'switch_list',
1058 expect: { switches: [ ] }
1061 getSwitchInfo: _luci2.rpc.declare({
1062 object: 'luci2.network',
1063 method: 'switch_info',
1064 params: [ 'switch' ],
1065 expect: { info: { } },
1066 filter: function(data, params) {
1067 data['attrs'] = data['switch'];
1068 data['vlan_attrs'] = data['vlan'];
1069 data['port_attrs'] = data['port'];
1070 data['switch'] = params['switch'];
1079 getSwitchStatus: _luci2.rpc.declare({
1080 object: 'luci2.network',
1081 method: 'switch_status',
1082 params: [ 'switch' ],
1083 expect: { ports: [ ] }
1087 runPing: _luci2.rpc.declare({
1088 object: 'luci2.network',
1091 expect: { '': { code: -1 } }
1094 runPing6: _luci2.rpc.declare({
1095 object: 'luci2.network',
1098 expect: { '': { code: -1 } }
1101 runTraceroute: _luci2.rpc.declare({
1102 object: 'luci2.network',
1103 method: 'traceroute',
1105 expect: { '': { code: -1 } }
1108 runTraceroute6: _luci2.rpc.declare({
1109 object: 'luci2.network',
1110 method: 'traceroute6',
1112 expect: { '': { code: -1 } }
1115 runNslookup: _luci2.rpc.declare({
1116 object: 'luci2.network',
1119 expect: { '': { code: -1 } }
1123 setUp: _luci2.rpc.declare({
1124 object: 'luci2.network',
1127 expect: { '': { code: -1 } }
1130 setDown: _luci2.rpc.declare({
1131 object: 'luci2.network',
1134 expect: { '': { code: -1 } }
1139 listDeviceNames: _luci2.rpc.declare({
1142 expect: { 'devices': [ ] },
1143 filter: function(data) {
1149 getDeviceStatus: _luci2.rpc.declare({
1152 params: [ 'device' ],
1153 expect: { '': { } },
1154 filter: function(data, params) {
1155 if (!$.isEmptyObject(data))
1157 data['device'] = params['device'];
1164 getAssocList: _luci2.rpc.declare({
1166 method: 'assoclist',
1167 params: [ 'device' ],
1168 expect: { results: [ ] },
1169 filter: function(data, params) {
1170 for (var i = 0; i < data.length; i++)
1171 data[i]['device'] = params['device'];
1173 data.sort(function(a, b) {
1174 if (a.bssid < b.bssid)
1176 else if (a.bssid > b.bssid)
1186 getWirelessStatus: function() {
1187 return this.listDeviceNames().then(function(names) {
1190 for (var i = 0; i < names.length; i++)
1191 _luci2.wireless.getDeviceStatus(names[i]);
1193 return _luci2.rpc.flush();
1194 }).then(function(networks) {
1198 'country', 'channel', 'frequency', 'frequency_offset',
1199 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1203 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1204 'signal', 'noise', 'bitrate', 'encryption'
1207 for (var i = 0; i < networks.length; i++)
1209 var phy = rv[networks[i].phy] || (
1210 rv[networks[i].phy] = { networks: [ ] }
1214 device: networks[i].device
1217 for (var j = 0; j < phy_attrs.length; j++)
1218 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1220 for (var j = 0; j < net_attrs.length; j++)
1221 net[net_attrs[j]] = networks[i][net_attrs[j]];
1223 phy.networks.push(net);
1230 getAssocLists: function()
1232 return this.listDeviceNames().then(function(names) {
1235 for (var i = 0; i < names.length; i++)
1236 _luci2.wireless.getAssocList(names[i]);
1238 return _luci2.rpc.flush();
1239 }).then(function(assoclists) {
1242 for (var i = 0; i < assoclists.length; i++)
1243 for (var j = 0; j < assoclists[i].length; j++)
1244 rv.push(assoclists[i][j]);
1250 formatEncryption: function(enc)
1252 var format_list = function(l, s)
1255 for (var i = 0; i < l.length; i++)
1256 rv.push(l[i].toUpperCase());
1257 return rv.join(s ? s : ', ');
1260 if (!enc || !enc.enabled)
1261 return _luci2.tr('None');
1265 if (enc.wep.length == 2)
1266 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1267 else if (enc.wep[0] == 'shared')
1268 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1270 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1274 if (enc.wpa.length == 2)
1275 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1276 format_list(enc.authentication, '/'),
1277 format_list(enc.ciphers, ', ')
1279 else if (enc.wpa[0] == 2)
1280 return 'WPA2 %s (%s)'.format(
1281 format_list(enc.authentication, '/'),
1282 format_list(enc.ciphers, ', ')
1285 return 'WPA %s (%s)'.format(
1286 format_list(enc.authentication, '/'),
1287 format_list(enc.ciphers, ', ')
1291 return _luci2.tr('Unknown');
1296 getZoneColor: function(zone)
1298 if ($.isPlainObject(zone))
1303 else if (zone == 'wan')
1306 for (var i = 0, hash = 0;
1308 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1310 for (var i = 0, color = '#';
1312 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1317 findZoneByNetwork: function(network)
1320 var zone = undefined;
1322 return _luci2.uci.foreach('firewall', 'zone', function(z) {
1323 if (!z.name || !z.network)
1326 if (!$.isArray(z.network))
1327 z.network = z.network.split(/\s+/);
1329 for (var i = 0; i < z.network.length; i++)
1331 if (z.network[i] == network)
1337 }).then(function() {
1339 zone.color = self.getZoneColor(zone);
1347 getSystemInfo: _luci2.rpc.declare({
1353 getBoardInfo: _luci2.rpc.declare({
1359 getDiskInfo: _luci2.rpc.declare({
1360 object: 'luci2.system',
1365 getInfo: function(cb)
1369 this.getSystemInfo();
1370 this.getBoardInfo();
1373 return _luci2.rpc.flush().then(function(info) {
1376 $.extend(rv, info[0]);
1377 $.extend(rv, info[1]);
1378 $.extend(rv, info[2]);
1384 getProcessList: _luci2.rpc.declare({
1385 object: 'luci2.system',
1386 method: 'process_list',
1387 expect: { processes: [ ] },
1388 filter: function(data) {
1389 data.sort(function(a, b) { return a.pid - b.pid });
1394 getSystemLog: _luci2.rpc.declare({
1395 object: 'luci2.system',
1400 getKernelLog: _luci2.rpc.declare({
1401 object: 'luci2.system',
1406 getZoneInfo: function(cb)
1408 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1411 sendSignal: _luci2.rpc.declare({
1412 object: 'luci2.system',
1413 method: 'process_signal',
1414 params: [ 'pid', 'signal' ],
1415 filter: function(data) {
1420 initList: _luci2.rpc.declare({
1421 object: 'luci2.system',
1422 method: 'init_list',
1423 expect: { initscripts: [ ] },
1424 filter: function(data) {
1425 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1430 initEnabled: function(init, cb)
1432 return this.initList().then(function(list) {
1433 for (var i = 0; i < list.length; i++)
1434 if (list[i].name == init)
1435 return !!list[i].enabled;
1441 initRun: _luci2.rpc.declare({
1442 object: 'luci2.system',
1443 method: 'init_action',
1444 params: [ 'name', 'action' ],
1445 filter: function(data) {
1450 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1451 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1452 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1453 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1454 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1455 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1458 getRcLocal: _luci2.rpc.declare({
1459 object: 'luci2.system',
1460 method: 'rclocal_get',
1461 expect: { data: '' }
1464 setRcLocal: _luci2.rpc.declare({
1465 object: 'luci2.system',
1466 method: 'rclocal_set',
1471 getCrontab: _luci2.rpc.declare({
1472 object: 'luci2.system',
1473 method: 'crontab_get',
1474 expect: { data: '' }
1477 setCrontab: _luci2.rpc.declare({
1478 object: 'luci2.system',
1479 method: 'crontab_set',
1484 getSSHKeys: _luci2.rpc.declare({
1485 object: 'luci2.system',
1486 method: 'sshkeys_get',
1487 expect: { keys: [ ] }
1490 setSSHKeys: _luci2.rpc.declare({
1491 object: 'luci2.system',
1492 method: 'sshkeys_set',
1497 setPassword: _luci2.rpc.declare({
1498 object: 'luci2.system',
1499 method: 'password_set',
1500 params: [ 'user', 'password' ]
1504 listLEDs: _luci2.rpc.declare({
1505 object: 'luci2.system',
1507 expect: { leds: [ ] }
1510 listUSBDevices: _luci2.rpc.declare({
1511 object: 'luci2.system',
1513 expect: { devices: [ ] }
1517 testUpgrade: _luci2.rpc.declare({
1518 object: 'luci2.system',
1519 method: 'upgrade_test',
1523 startUpgrade: _luci2.rpc.declare({
1524 object: 'luci2.system',
1525 method: 'upgrade_start',
1529 cleanUpgrade: _luci2.rpc.declare({
1530 object: 'luci2.system',
1531 method: 'upgrade_clean'
1535 restoreBackup: _luci2.rpc.declare({
1536 object: 'luci2.system',
1537 method: 'backup_restore'
1540 cleanBackup: _luci2.rpc.declare({
1541 object: 'luci2.system',
1542 method: 'backup_clean'
1546 getBackupConfig: _luci2.rpc.declare({
1547 object: 'luci2.system',
1548 method: 'backup_config_get',
1549 expect: { config: '' }
1552 setBackupConfig: _luci2.rpc.declare({
1553 object: 'luci2.system',
1554 method: 'backup_config_set',
1559 listBackup: _luci2.rpc.declare({
1560 object: 'luci2.system',
1561 method: 'backup_list',
1562 expect: { files: [ ] }
1566 testReset: _luci2.rpc.declare({
1567 object: 'luci2.system',
1568 method: 'reset_test',
1569 expect: { supported: false }
1572 startReset: _luci2.rpc.declare({
1573 object: 'luci2.system',
1574 method: 'reset_start'
1578 performReboot: _luci2.rpc.declare({
1579 object: 'luci2.system',
1585 updateLists: _luci2.rpc.declare({
1586 object: 'luci2.opkg',
1591 _allPackages: _luci2.rpc.declare({
1592 object: 'luci2.opkg',
1594 params: [ 'offset', 'limit', 'pattern' ],
1598 _installedPackages: _luci2.rpc.declare({
1599 object: 'luci2.opkg',
1600 method: 'list_installed',
1601 params: [ 'offset', 'limit', 'pattern' ],
1605 _findPackages: _luci2.rpc.declare({
1606 object: 'luci2.opkg',
1608 params: [ 'offset', 'limit', 'pattern' ],
1612 _fetchPackages: function(action, offset, limit, pattern)
1616 return action(offset, limit, pattern).then(function(list) {
1617 if (!list.total || !list.packages)
1618 return { length: 0, total: 0 };
1620 packages.push.apply(packages, list.packages);
1621 packages.total = list.total;
1626 if (packages.length >= limit)
1631 for (var i = offset + packages.length; i < limit; i += 100)
1632 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1634 return _luci2.rpc.flush();
1635 }).then(function(lists) {
1636 for (var i = 0; i < lists.length; i++)
1638 if (!lists[i].total || !lists[i].packages)
1641 packages.push.apply(packages, lists[i].packages);
1642 packages.total = lists[i].total;
1649 listPackages: function(offset, limit, pattern)
1651 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1654 installedPackages: function(offset, limit, pattern)
1656 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1659 findPackages: function(offset, limit, pattern)
1661 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1664 installPackage: _luci2.rpc.declare({
1665 object: 'luci2.opkg',
1667 params: [ 'package' ],
1671 removePackage: _luci2.rpc.declare({
1672 object: 'luci2.opkg',
1674 params: [ 'package' ],
1678 getConfig: _luci2.rpc.declare({
1679 object: 'luci2.opkg',
1680 method: 'config_get',
1681 expect: { config: '' }
1684 setConfig: _luci2.rpc.declare({
1685 object: 'luci2.opkg',
1686 method: 'config_set',
1693 login: _luci2.rpc.declare({
1696 params: [ 'username', 'password' ],
1700 access: _luci2.rpc.declare({
1703 params: [ 'scope', 'object', 'function' ],
1704 expect: { access: false }
1709 return _luci2.session.access('ubus', 'session', 'access');
1712 startHeartbeat: function()
1714 this._hearbeatInterval = window.setInterval(function() {
1715 _luci2.session.isAlive().then(function(alive) {
1718 _luci2.session.stopHeartbeat();
1719 _luci2.ui.login(true);
1723 }, _luci2.globals.timeout * 2);
1726 stopHeartbeat: function()
1728 if (typeof(this._hearbeatInterval) != 'undefined')
1730 window.clearInterval(this._hearbeatInterval);
1731 delete this._hearbeatInterval;
1738 saveScrollTop: function()
1740 this._scroll_top = $(document).scrollTop();
1743 restoreScrollTop: function()
1745 if (typeof(this._scroll_top) == 'undefined')
1748 $(document).scrollTop(this._scroll_top);
1750 delete this._scroll_top;
1753 loading: function(enable)
1755 var win = $(window);
1756 var body = $('body');
1758 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1760 .addClass('modal fade')
1761 .append($('<div />')
1762 .addClass('modal-dialog')
1763 .append($('<div />')
1764 .addClass('modal-content luci2-modal-loader')
1765 .append($('<div />')
1766 .addClass('modal-body')
1767 .text(_luci2.tr('Loading data…')))))
1775 state.modal.modal(enable ? 'show' : 'hide');
1778 dialog: function(title, content, options)
1780 var win = $(window);
1781 var body = $('body');
1783 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1784 dialog: $('<div />')
1785 .addClass('modal fade')
1786 .append($('<div />')
1787 .addClass('modal-dialog')
1788 .append($('<div />')
1789 .addClass('modal-content')
1790 .append($('<div />')
1791 .addClass('modal-header')
1793 .addClass('modal-title'))
1794 .append($('<div />')
1795 .addClass('modal-body'))
1796 .append($('<div />')
1797 .addClass('modal-footer')
1798 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1800 $(this).parents('div.modal').modal('hide');
1805 if (typeof(options) != 'object')
1808 if (title === false)
1810 state.dialog.modal('hide');
1815 var cnt = state.dialog.children().children().children('div.modal-body');
1816 var ftr = state.dialog.children().children().children('div.modal-footer');
1820 if (options.style == 'confirm')
1822 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1823 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1825 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1826 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1828 else if (options.style == 'close')
1830 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1831 .click(options.close || function() { _luci2.ui.dialog(false) }));
1833 else if (options.style == 'wait')
1835 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1836 .attr('disabled', true));
1839 state.dialog.find('h4:first').text(title);
1840 state.dialog.modal('show');
1842 cnt.empty().append(content);
1845 upload: function(title, content, options)
1847 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1849 .attr('method', 'post')
1850 .attr('action', '/cgi-bin/luci-upload')
1851 .attr('enctype', 'multipart/form-data')
1852 .attr('target', 'cbi-fileupload-frame')
1854 .append($('<input />')
1855 .attr('type', 'hidden')
1856 .attr('name', 'sessionid'))
1857 .append($('<input />')
1858 .attr('type', 'hidden')
1859 .attr('name', 'filename'))
1860 .append($('<input />')
1861 .attr('type', 'file')
1862 .attr('name', 'filedata')
1863 .addClass('cbi-input-file'))
1864 .append($('<div />')
1865 .css('width', '100%')
1866 .addClass('progress progress-striped active')
1867 .append($('<div />')
1868 .addClass('progress-bar')
1869 .css('width', '100%')))
1870 .append($('<iframe />')
1871 .addClass('pull-right')
1872 .attr('name', 'cbi-fileupload-frame')
1873 .css('width', '1px')
1874 .css('height', '1px')
1875 .css('visibility', 'hidden')),
1877 finish_cb: function(ev) {
1878 $(this).off('load');
1880 var body = (this.contentDocument || this.contentWindow.document).body;
1881 if (body.firstChild.tagName.toLowerCase() == 'pre')
1882 body = body.firstChild;
1886 json = $.parseJSON(body.innerHTML);
1889 message: _luci2.tr('Invalid server response received'),
1890 error: [ -1, _luci2.tr('Invalid data') ]
1896 L.ui.dialog(L.tr('File upload'), [
1897 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1898 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1899 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1900 ], { style: 'close' });
1902 else if (typeof(state.success_cb) == 'function')
1904 state.success_cb(json);
1908 confirm_cb: function() {
1909 var f = state.form.find('.cbi-input-file');
1910 var b = state.form.find('.progress');
1911 var p = state.form.find('p');
1916 state.form.find('iframe').on('load', state.finish_cb);
1917 state.form.submit();
1921 p.text(_luci2.tr('File upload in progress …'));
1923 state.form.parent().parent().find('button').prop('disabled', true);
1927 state.form.find('.progress').hide();
1928 state.form.find('.cbi-input-file').val('').show();
1929 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1931 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1932 state.form.find('[name=filename]').val(options.filename);
1934 state.success_cb = options.success;
1936 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1938 confirm: state.confirm_cb
1942 reconnect: function()
1944 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1945 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1946 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1948 var interval, timeout;
1951 _luci2.tr('Waiting for device'), [
1952 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1954 .css('width', '100%')
1955 .addClass('progressbar')
1956 .addClass('intermediate')
1957 .append($('<div />')
1958 .css('width', '100%'))
1959 ], { style: 'wait' }
1962 for (var i = 0; i < protocols.length; i++)
1963 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1965 //_luci2.network.getNetworkStatus(function(s) {
1966 // for (var i = 0; i < protocols.length; i++)
1968 // for (var j = 0; j < s.length; j++)
1970 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1971 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1973 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1974 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1977 //}).then(function() {
1978 images.on('load', function() {
1979 var url = this.getAttribute('url');
1980 _luci2.session.isAlive().then(function(access) {
1983 window.clearTimeout(timeout);
1984 window.clearInterval(interval);
1985 _luci2.ui.dialog(false);
1990 location.href = url;
1995 interval = window.setInterval(function() {
1996 images.each(function() {
1997 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2001 timeout = window.setTimeout(function() {
2002 window.clearInterval(interval);
2006 _luci2.tr('Device not responding'),
2007 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2014 login: function(invalid)
2016 var state = _luci2.ui._login || (_luci2.ui._login = {
2019 .attr('method', 'post')
2021 .addClass('alert-message')
2022 .text(_luci2.tr('Wrong username or password given!')))
2024 .append($('<label />')
2025 .text(_luci2.tr('Username'))
2026 .append($('<br />'))
2027 .append($('<input />')
2028 .attr('type', 'text')
2029 .attr('name', 'username')
2030 .attr('value', 'root')
2031 .addClass('form-control')
2032 .keypress(function(ev) {
2033 if (ev.which == 10 || ev.which == 13)
2037 .append($('<label />')
2038 .text(_luci2.tr('Password'))
2039 .append($('<br />'))
2040 .append($('<input />')
2041 .attr('type', 'password')
2042 .attr('name', 'password')
2043 .addClass('form-control')
2044 .keypress(function(ev) {
2045 if (ev.which == 10 || ev.which == 13)
2049 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2051 response_cb: function(response) {
2052 if (!response.ubus_rpc_session)
2054 _luci2.ui.login(true);
2058 _luci2.globals.sid = response.ubus_rpc_session;
2059 _luci2.setHash('id', _luci2.globals.sid);
2060 _luci2.session.startHeartbeat();
2061 _luci2.ui.dialog(false);
2062 state.deferred.resolve();
2066 confirm_cb: function() {
2067 var u = state.form.find('[name=username]').val();
2068 var p = state.form.find('[name=password]').val();
2074 _luci2.tr('Logging in'), [
2075 $('<p />').text(_luci2.tr('Log in in progress …')),
2077 .css('width', '100%')
2078 .addClass('progressbar')
2079 .addClass('intermediate')
2080 .append($('<div />')
2081 .css('width', '100%'))
2082 ], { style: 'wait' }
2085 _luci2.globals.sid = '00000000000000000000000000000000';
2086 _luci2.session.login(u, p).then(state.response_cb);
2090 if (!state.deferred || state.deferred.state() != 'pending')
2091 state.deferred = $.Deferred();
2093 /* try to find sid from hash */
2094 var sid = _luci2.getHash('id');
2095 if (sid && sid.match(/^[a-f0-9]{32}$/))
2097 _luci2.globals.sid = sid;
2098 _luci2.session.isAlive().then(function(access) {
2101 _luci2.session.startHeartbeat();
2102 state.deferred.resolve();
2106 _luci2.setHash('id', undefined);
2111 return state.deferred;
2115 state.form.find('.alert-message').show();
2117 state.form.find('.alert-message').hide();
2119 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2121 confirm: state.confirm_cb
2124 state.form.find('[name=password]').focus();
2126 return state.deferred;
2129 cryptPassword: _luci2.rpc.declare({
2133 expect: { crypt: '' }
2137 _acl_merge_scope: function(acl_scope, scope)
2139 if ($.isArray(scope))
2141 for (var i = 0; i < scope.length; i++)
2142 acl_scope[scope[i]] = true;
2144 else if ($.isPlainObject(scope))
2146 for (var object_name in scope)
2148 if (!$.isArray(scope[object_name]))
2151 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2153 for (var i = 0; i < scope[object_name].length; i++)
2154 acl_object[scope[object_name][i]] = true;
2159 _acl_merge_permission: function(acl_perm, perm)
2161 if ($.isPlainObject(perm))
2163 for (var scope_name in perm)
2165 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2166 this._acl_merge_scope(acl_scope, perm[scope_name]);
2171 _acl_merge_group: function(acl_group, group)
2173 if ($.isPlainObject(group))
2175 if (!acl_group.description)
2176 acl_group.description = group.description;
2180 var acl_perm = acl_group.read || (acl_group.read = { });
2181 this._acl_merge_permission(acl_perm, group.read);
2186 var acl_perm = acl_group.write || (acl_group.write = { });
2187 this._acl_merge_permission(acl_perm, group.write);
2192 _acl_merge_tree: function(acl_tree, tree)
2194 if ($.isPlainObject(tree))
2196 for (var group_name in tree)
2198 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2199 this._acl_merge_group(acl_group, tree[group_name]);
2204 listAvailableACLs: _luci2.rpc.declare({
2207 expect: { acls: [ ] },
2208 filter: function(trees) {
2210 for (var i = 0; i < trees.length; i++)
2211 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2216 renderMainMenu: _luci2.rpc.declare({
2219 expect: { menu: { } },
2220 filter: function(entries) {
2221 _luci2.globals.mainMenu = new _luci2.ui.menu();
2222 _luci2.globals.mainMenu.entries(entries);
2226 .append(_luci2.globals.mainMenu.render(0, 1));
2230 renderViewMenu: function()
2234 .append(_luci2.globals.mainMenu.render(2, 900));
2237 renderView: function()
2239 var node = arguments[0];
2240 var name = node.view.split(/\//).join('.');
2243 for (var i = 1; i < arguments.length; i++)
2244 args.push(arguments[i]);
2246 if (_luci2.globals.currentView)
2247 _luci2.globals.currentView.finish();
2249 _luci2.ui.renderViewMenu();
2252 _luci2._views = { };
2254 _luci2.setHash('view', node.view);
2256 if (_luci2._views[name] instanceof _luci2.ui.view)
2258 _luci2.globals.currentView = _luci2._views[name];
2259 return _luci2._views[name].render.apply(_luci2._views[name], args);
2262 var url = _luci2.globals.resource + '/view/' + name + '.js';
2264 return $.ajax(url, {
2268 }).then(function(data) {
2270 var viewConstructorSource = (
2271 '(function(L, $) { ' +
2273 '})(_luci2, $);\n\n' +
2275 ).format(data, url);
2277 var viewConstructor = eval(viewConstructorSource);
2279 _luci2._views[name] = new viewConstructor({
2281 acls: node.write || { }
2284 _luci2.globals.currentView = _luci2._views[name];
2285 return _luci2._views[name].render.apply(_luci2._views[name], args);
2288 alert('Unable to instantiate view "%s": %s'.format(url, e));
2291 return $.Deferred().resolve();
2295 updateHostname: function()
2297 return _luci2.system.getBoardInfo().then(function(info) {
2299 $('#hostname').text(info.hostname);
2303 updateChanges: function()
2305 return _luci2.uci.changes().then(function(changes) {
2309 for (var config in changes)
2313 for (var i = 0; i < changes[config].length; i++)
2315 var c = changes[config][i];
2324 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2326 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2331 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2333 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2337 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2341 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2345 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2350 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2352 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2357 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2358 n += changes[config].length;
2369 .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2370 .click(function(ev) {
2371 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2372 ev.preventDefault();
2382 _luci2.ui.loading(true);
2385 _luci2.ui.updateHostname(),
2386 _luci2.ui.updateChanges(),
2387 _luci2.ui.renderMainMenu()
2389 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2390 _luci2.ui.loading(false);
2395 button: function(label, style, title)
2397 style = style || 'default';
2399 return $('<button />')
2400 .attr('type', 'button')
2401 .attr('title', title ? title : '')
2402 .addClass('btn btn-' + style)
2407 this.ui.AbstractWidget = Class.extend({
2408 i18n: function(text) {
2413 var key = arguments[0];
2416 for (var i = 1; i < arguments.length; i++)
2417 args.push(arguments[i]);
2419 switch (typeof(this.options[key]))
2425 return this.options[key].apply(this, args);
2428 return ''.format.apply('' + this.options[key], args);
2432 toString: function() {
2433 return $('<div />').append(this.render()).html();
2436 insertInto: function(id) {
2437 return $(id).empty().append(this.render());
2440 appendTo: function(id) {
2441 return $(id).append(this.render());
2445 this.ui.view = this.ui.AbstractWidget.extend({
2446 _fetch_template: function()
2448 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2452 success: function(data) {
2453 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2454 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2461 return _luci2.tr(p2);
2464 return _luci2.globals[p2] || '';
2467 return '(?' + match + ')';
2471 $('#maincontent').append(data);
2478 throw "Not implemented";
2483 var container = $('#maincontent');
2488 container.append($('<h2 />').append(this.title));
2490 if (this.description)
2491 container.append($('<p />').append(this.description));
2496 for (var i = 0; i < arguments.length; i++)
2497 args.push(arguments[i]);
2499 return this._fetch_template().then(function() {
2500 return _luci2.deferrable(self.execute.apply(self, args));
2504 repeat: function(func, interval)
2508 if (!self._timeouts)
2509 self._timeouts = [ ];
2511 var index = self._timeouts.length;
2513 if (typeof(interval) != 'number')
2516 var setTimer, runTimer;
2518 setTimer = function() {
2520 self._timeouts[index] = window.setTimeout(runTimer, interval);
2523 runTimer = function() {
2524 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2532 if ($.isArray(this._timeouts))
2534 for (var i = 0; i < this._timeouts.length; i++)
2535 window.clearTimeout(this._timeouts[i]);
2537 delete this._timeouts;
2542 this.ui.menu = this.ui.AbstractWidget.extend({
2547 entries: function(entries)
2549 for (var entry in entries)
2551 var path = entry.split(/\//);
2552 var node = this._nodes;
2554 for (i = 0; i < path.length; i++)
2559 if (!node.childs[path[i]])
2560 node.childs[path[i]] = { };
2562 node = node.childs[path[i]];
2565 $.extend(node, entries[entry]);
2569 _indexcmp: function(a, b)
2571 var x = a.index || 0;
2572 var y = b.index || 0;
2576 firstChildView: function(node)
2582 for (var child in (node.childs || { }))
2583 nodes.push(node.childs[child]);
2585 nodes.sort(this._indexcmp);
2587 for (var i = 0; i < nodes.length; i++)
2589 var child = this.firstChildView(nodes[i]);
2592 for (var key in child)
2593 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2594 node[key] = child[key];
2603 _onclick: function(ev)
2605 _luci2.ui.loading(true);
2606 _luci2.ui.renderView(ev.data).then(function() {
2607 _luci2.ui.loading(false);
2610 ev.preventDefault();
2614 _render: function(childs, level, min, max)
2617 for (var node in childs)
2619 var child = this.firstChildView(childs[node]);
2621 nodes.push(childs[node]);
2624 nodes.sort(this._indexcmp);
2626 var list = $('<ul />');
2629 list.addClass('nav').addClass('navbar-nav');
2630 else if (level == 1)
2631 list.addClass('dropdown-menu').addClass('navbar-inverse');
2633 for (var i = 0; i < nodes.length; i++)
2635 if (!_luci2.globals.defaultNode)
2637 var v = _luci2.getHash('view');
2638 if (!v || v == nodes[i].view)
2639 _luci2.globals.defaultNode = nodes[i];
2642 var item = $('<li />')
2645 .text(_luci2.tr(nodes[i].title)))