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 = arguments.callee;
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;
371 this.getHash = function(key)
374 var tuples = (location.hash || '#').substring(1).split(/,/);
376 for (var i = 0; i < tuples.length; i++)
378 var tuple = tuples[i].split(/:/);
379 if (tuple.length == 2)
380 data[tuple[0]] = tuple[1];
383 if (typeof(key) != 'undefined')
392 sid: '00000000000000000000000000000000'
401 _call: function(req, cb)
403 return $.ajax('/ubus', {
405 contentType: 'application/json',
406 data: JSON.stringify(req),
409 timeout: _luci2.globals.timeout
413 _list_cb: function(msg)
415 /* verify message frame */
416 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417 throw 'Invalid JSON response';
422 _call_cb: function(msg)
425 var type = Object.prototype.toString;
430 for (var i = 0; i < msg.length; i++)
432 /* verify message frame */
433 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434 throw 'Invalid JSON response';
436 /* fetch related request info */
437 var req = _luci2.rpc._requests[msg[i].id];
438 if (typeof(req) != 'object')
439 throw 'No related request for JSON response';
441 /* fetch response attribute and verify returned type */
444 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
449 for (var key in req.expect)
451 if (typeof(ret) != 'undefined' && key != '')
454 if (type.call(ret) != type.call(req.expect[key]))
455 ret = req.expect[key];
462 if (typeof(req.filter) == 'function')
465 req.priv[1] = req.params;
466 ret = req.filter.apply(_luci2.rpc, req.priv);
469 /* store response data */
470 if (typeof(req.index) == 'number')
471 data[req.index] = ret;
475 /* delete request object */
476 delete _luci2.rpc._requests[msg[i].id];
485 for (var i = 0; i < arguments.length; i++)
486 params[i] = arguments[i];
492 params: (params.length > 0) ? params : undefined
495 return this._call(msg, this._list_cb);
500 if (!$.isArray(this._batch))
506 if (!$.isArray(this._batch))
507 return _luci2.deferrable([ ]);
509 var req = this._batch;
513 return this._call(req, this._call_cb);
516 declare: function(options)
521 /* build parameter object */
524 if ($.isArray(options.params))
525 for (p_off = 0; p_off < options.params.length; p_off++)
526 params[options.params[p_off]] = arguments[p_off];
528 /* all remaining arguments are private args */
529 var priv = [ undefined, undefined ];
530 for (; p_off < arguments.length; p_off++)
531 priv.push(arguments[p_off]);
533 /* store request info */
534 var req = _rpc._requests[_rpc._id] = {
535 expect: options.expect,
536 filter: options.filter,
541 /* build message object */
554 /* when a batch is in progress then store index in request data
555 * and push message object onto the stack */
556 if ($.isArray(_rpc._batch))
558 req.index = _rpc._batch.push(msg) - 1;
559 return _luci2.deferrable(msg);
563 return _rpc._call(msg, _rpc._call_cb);
572 return _luci2.session.access('ubus', 'uci', 'commit');
575 add: _luci2.rpc.declare({
578 params: [ 'config', 'type', 'name', 'values' ],
579 expect: { section: '' }
587 changes: _luci2.rpc.declare({
590 params: [ 'config' ],
591 expect: { changes: [ ] }
594 commit: _luci2.rpc.declare({
600 _delete_one: _luci2.rpc.declare({
603 params: [ 'config', 'section', 'option' ]
606 _delete_multiple: _luci2.rpc.declare({
609 params: [ 'config', 'section', 'options' ]
612 'delete': function(config, section, option)
614 if ($.isArray(option))
615 return this._delete_multiple(config, section, option);
617 return this._delete_one(config, section, option);
620 delete_all: _luci2.rpc.declare({
623 params: [ 'config', 'type', 'match' ]
626 _foreach: _luci2.rpc.declare({
629 params: [ 'config', 'type' ],
630 expect: { values: { } }
633 foreach: function(config, type, cb)
635 return this._foreach(config, type).then(function(sections) {
636 for (var s in sections)
641 get: _luci2.rpc.declare({
644 params: [ 'config', 'section', 'option' ],
646 filter: function(data, params) {
647 if (typeof(params.option) == 'undefined')
648 return data.values ? data.values['.type'] : undefined;
654 get_all: _luci2.rpc.declare({
657 params: [ 'config', 'section' ],
658 expect: { values: { } },
659 filter: function(data, params) {
660 if (typeof(params.section) == 'string')
661 data['.section'] = params.section;
662 else if (typeof(params.config) == 'string')
663 data['.package'] = params.config;
668 get_first: function(config, type, option)
670 return this._foreach(config, type).then(function(sections) {
671 for (var s in sections)
673 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
675 if (typeof(val) != 'undefined')
683 section: _luci2.rpc.declare({
686 params: [ 'config', 'type', 'name', 'values' ],
687 expect: { section: '' }
690 _set: _luci2.rpc.declare({
693 params: [ 'config', 'section', 'values' ]
696 set: function(config, section, option, value)
698 if (typeof(value) == 'undefined' && typeof(option) == 'string')
699 return this.section(config, section, option); /* option -> type */
700 else if ($.isPlainObject(option))
701 return this._set(config, section, option); /* option -> values */
704 values[option] = value;
706 return this._set(config, section, values);
709 order: _luci2.rpc.declare({
712 params: [ 'config', 'sections' ]
717 listNetworkNames: function() {
718 return _luci2.rpc.list('network.interface.*').then(function(list) {
720 for (var name in list)
721 if (name != 'network.interface.loopback')
722 names.push(name.substring(18));
728 listDeviceNames: _luci2.rpc.declare({
729 object: 'network.device',
732 filter: function(data) {
734 for (var name in data)
742 getNetworkStatus: function()
747 return this.listNetworkNames().then(function(names) {
750 for (var i = 0; i < names.length; i++)
751 _luci2.network.getInterfaceStatus(names[i]);
753 return _luci2.rpc.flush();
754 }).then(function(networks) {
755 for (var i = 0; i < networks.length; i++)
757 var net = nets[i] = networks[i];
758 var dev = net.l3_device || net.l2_device;
760 net.device = devs[dev] = { };
765 for (var dev in devs)
766 _luci2.network.listDeviceNamestatus(dev);
768 return _luci2.rpc.flush();
769 }).then(function(devices) {
772 for (var i = 0; i < devices.length; i++)
774 var brm = devices[i]['bridge-members'];
775 delete devices[i]['bridge-members'];
777 $.extend(devs[devices[i]['device']], devices[i]);
782 devs[devices[i]['device']].subdevices = [ ];
784 for (var j = 0; j < brm.length; j++)
789 _luci2.network.listDeviceNamestatus(brm[j]);
792 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
796 return _luci2.rpc.flush();
797 }).then(function(subdevices) {
798 for (var i = 0; i < subdevices.length; i++)
799 $.extend(devs[subdevices[i]['device']], subdevices[i]);
803 for (var dev in devs)
804 _luci2.wireless.getDeviceStatus(dev);
806 return _luci2.rpc.flush();
807 }).then(function(wifidevices) {
808 for (var i = 0; i < wifidevices.length; i++)
810 devs[wifidevices[i]['device']].wireless = wifidevices[i];
812 nets.sort(function(a, b) {
813 if (a['interface'] < b['interface'])
815 else if (a['interface'] > b['interface'])
825 findWanInterfaces: function(cb)
827 return this.listNetworkNames().then(function(names) {
830 for (var i = 0; i < names.length; i++)
831 _luci2.network.getInterfaceStatus(names[i]);
833 return _luci2.rpc.flush();
834 }).then(function(interfaces) {
835 var rv = [ undefined, undefined ];
837 for (var i = 0; i < interfaces.length; i++)
839 for (var j = 0; j < interfaces[i].route.length; j++)
841 var rt = interfaces[i].route[j];
843 if (typeof(rt.table) != 'undefined')
846 if (rt.target == '0.0.0.0' && rt.mask == 0)
847 rv[0] = interfaces[i];
848 else if (rt.target == '::' && rt.mask == 0)
849 rv[1] = interfaces[i];
857 getDHCPLeases: _luci2.rpc.declare({
858 object: 'luci2.network',
859 method: 'dhcp_leases',
860 expect: { leases: [ ] }
863 getDHCPv6Leases: _luci2.rpc.declare({
864 object: 'luci2.network',
865 method: 'dhcp6_leases',
866 expect: { leases: [ ] }
869 getRoutes: _luci2.rpc.declare({
870 object: 'luci2.network',
872 expect: { routes: [ ] }
875 getIPv6Routes: _luci2.rpc.declare({
876 object: 'luci2.network',
878 expect: { routes: [ ] }
881 getARPTable: _luci2.rpc.declare({
882 object: 'luci2.network',
884 expect: { entries: [ ] }
887 getInterfaceStatus: _luci2.rpc.declare({
888 object: 'network.interface',
890 params: [ 'interface' ],
892 filter: function(data, params) {
893 data['interface'] = params['interface'];
894 data['l2_device'] = data['device'];
895 delete data['device'];
900 listDeviceNamestatus: _luci2.rpc.declare({
901 object: 'network.device',
905 filter: function(data, params) {
906 data['device'] = params['name'];
911 getConntrackCount: _luci2.rpc.declare({
912 object: 'luci2.network',
913 method: 'conntrack_count',
914 expect: { '': { count: 0, limit: 0 } }
919 listDeviceNames: _luci2.rpc.declare({
922 expect: { 'devices': [ ] },
923 filter: function(data) {
929 getDeviceStatus: _luci2.rpc.declare({
932 params: [ 'device' ],
934 filter: function(data, params) {
935 if (!$.isEmptyObject(data))
937 data['device'] = params['device'];
944 getAssocList: _luci2.rpc.declare({
947 params: [ 'device' ],
948 expect: { results: [ ] },
949 filter: function(data, params) {
950 for (var i = 0; i < data.length; i++)
951 data[i]['device'] = params['device'];
953 data.sort(function(a, b) {
954 if (a.bssid < b.bssid)
956 else if (a.bssid > b.bssid)
966 getWirelessStatus: function() {
967 return this.listDeviceNames().then(function(names) {
970 for (var i = 0; i < names.length; i++)
971 _luci2.wireless.getDeviceStatus(names[i]);
973 return _luci2.rpc.flush();
974 }).then(function(networks) {
978 'country', 'channel', 'frequency', 'frequency_offset',
979 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
983 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
984 'signal', 'noise', 'bitrate', 'encryption'
987 for (var i = 0; i < networks.length; i++)
989 var phy = rv[networks[i].phy] || (
990 rv[networks[i].phy] = { networks: [ ] }
994 device: networks[i].device
997 for (var j = 0; j < phy_attrs.length; j++)
998 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1000 for (var j = 0; j < net_attrs.length; j++)
1001 net[net_attrs[j]] = networks[i][net_attrs[j]];
1003 phy.networks.push(net);
1010 getAssocLists: function()
1012 return this.listDeviceNames().then(function(names) {
1015 for (var i = 0; i < names.length; i++)
1016 _luci2.wireless.getAssocList(names[i]);
1018 return _luci2.rpc.flush();
1019 }).then(function(assoclists) {
1022 for (var i = 0; i < assoclists.length; i++)
1023 for (var j = 0; j < assoclists[i].length; j++)
1024 rv.push(assoclists[i][j]);
1030 formatEncryption: function(enc)
1032 var format_list = function(l, s)
1035 for (var i = 0; i < l.length; i++)
1036 rv.push(l[i].toUpperCase());
1037 return rv.join(s ? s : ', ');
1040 if (!enc || !enc.enabled)
1041 return _luci2.tr('None');
1045 if (enc.wep.length == 2)
1046 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1047 else if (enc.wep[0] == 'shared')
1048 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1050 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1054 if (enc.wpa.length == 2)
1055 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1056 format_list(enc.authentication, '/'),
1057 format_list(enc.ciphers, ', ')
1059 else if (enc.wpa[0] == 2)
1060 return 'WPA2 %s (%s)'.format(
1061 format_list(enc.authentication, '/'),
1062 format_list(enc.ciphers, ', ')
1065 return 'WPA %s (%s)'.format(
1066 format_list(enc.authentication, '/'),
1067 format_list(enc.ciphers, ', ')
1071 return _luci2.tr('Unknown');
1076 getSystemInfo: _luci2.rpc.declare({
1082 getBoardInfo: _luci2.rpc.declare({
1088 getDiskInfo: _luci2.rpc.declare({
1089 object: 'luci2.system',
1094 getInfo: function(cb)
1098 this.getSystemInfo();
1099 this.getBoardInfo();
1102 return _luci2.rpc.flush().then(function(info) {
1105 $.extend(rv, info[0]);
1106 $.extend(rv, info[1]);
1107 $.extend(rv, info[2]);
1113 getProcessList: _luci2.rpc.declare({
1114 object: 'luci2.system',
1115 method: 'process_list',
1116 expect: { processes: [ ] },
1117 filter: function(data) {
1118 data.sort(function(a, b) { return a.pid - b.pid });
1123 getSystemLog: _luci2.rpc.declare({
1124 object: 'luci2.system',
1129 getKernelLog: _luci2.rpc.declare({
1130 object: 'luci2.system',
1135 getZoneInfo: function(cb)
1137 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1140 sendSignal: _luci2.rpc.declare({
1141 object: 'luci2.system',
1142 method: 'process_signal',
1143 params: [ 'pid', 'signal' ],
1144 filter: function(data) {
1149 initList: _luci2.rpc.declare({
1150 object: 'luci2.system',
1151 method: 'init_list',
1152 expect: { initscripts: [ ] },
1153 filter: function(data) {
1154 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1159 initEnabled: function(init, cb)
1161 return this.initList().then(function(list) {
1162 for (var i = 0; i < list.length; i++)
1163 if (list[i].name == init)
1164 return !!list[i].enabled;
1170 initRun: _luci2.rpc.declare({
1171 object: 'luci2.system',
1172 method: 'init_action',
1173 params: [ 'name', 'action' ],
1174 filter: function(data) {
1179 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1180 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1181 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1182 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1183 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1184 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1187 getRcLocal: _luci2.rpc.declare({
1188 object: 'luci2.system',
1189 method: 'rclocal_get',
1190 expect: { data: '' }
1193 setRcLocal: _luci2.rpc.declare({
1194 object: 'luci2.system',
1195 method: 'rclocal_set',
1200 getCrontab: _luci2.rpc.declare({
1201 object: 'luci2.system',
1202 method: 'crontab_get',
1203 expect: { data: '' }
1206 setCrontab: _luci2.rpc.declare({
1207 object: 'luci2.system',
1208 method: 'crontab_set',
1213 getSSHKeys: _luci2.rpc.declare({
1214 object: 'luci2.system',
1215 method: 'sshkeys_get',
1216 expect: { keys: [ ] }
1219 setSSHKeys: _luci2.rpc.declare({
1220 object: 'luci2.system',
1221 method: 'sshkeys_set',
1226 setPassword: _luci2.rpc.declare({
1227 object: 'luci2.system',
1228 method: 'password_set',
1229 params: [ 'user', 'password' ]
1233 listLEDs: _luci2.rpc.declare({
1234 object: 'luci2.system',
1236 expect: { leds: [ ] }
1239 listUSBDevices: _luci2.rpc.declare({
1240 object: 'luci2.system',
1242 expect: { devices: [ ] }
1246 testUpgrade: _luci2.rpc.declare({
1247 object: 'luci2.system',
1248 method: 'upgrade_test',
1252 startUpgrade: _luci2.rpc.declare({
1253 object: 'luci2.system',
1254 method: 'upgrade_start',
1258 cleanUpgrade: _luci2.rpc.declare({
1259 object: 'luci2.system',
1260 method: 'upgrade_clean'
1264 restoreBackup: _luci2.rpc.declare({
1265 object: 'luci2.system',
1266 method: 'backup_restore'
1269 cleanBackup: _luci2.rpc.declare({
1270 object: 'luci2.system',
1271 method: 'backup_clean'
1275 getBackupConfig: _luci2.rpc.declare({
1276 object: 'luci2.system',
1277 method: 'backup_config_get',
1278 expect: { config: '' }
1281 setBackupConfig: _luci2.rpc.declare({
1282 object: 'luci2.system',
1283 method: 'backup_config_set',
1288 listBackup: _luci2.rpc.declare({
1289 object: 'luci2.system',
1290 method: 'backup_list',
1291 expect: { files: [ ] }
1295 performReboot: _luci2.rpc.declare({
1296 object: 'luci2.system',
1302 updateLists: _luci2.rpc.declare({
1303 object: 'luci2.opkg',
1308 _allPackages: _luci2.rpc.declare({
1309 object: 'luci2.opkg',
1311 params: [ 'offset', 'limit', 'pattern' ],
1315 _installedPackages: _luci2.rpc.declare({
1316 object: 'luci2.opkg',
1317 method: 'list_installed',
1318 params: [ 'offset', 'limit', 'pattern' ],
1322 _findPackages: _luci2.rpc.declare({
1323 object: 'luci2.opkg',
1325 params: [ 'offset', 'limit', 'pattern' ],
1329 _fetchPackages: function(action, offset, limit, pattern)
1333 return action(offset, limit, pattern).then(function(list) {
1334 if (!list.total || !list.packages)
1335 return { length: 0, total: 0 };
1337 packages.push.apply(packages, list.packages);
1338 packages.total = list.total;
1343 if (packages.length >= limit)
1348 for (var i = offset + packages.length; i < limit; i += 100)
1349 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1351 return _luci2.rpc.flush();
1352 }).then(function(lists) {
1353 for (var i = 0; i < lists.length; i++)
1355 if (!lists[i].total || !lists[i].packages)
1358 packages.push.apply(packages, lists[i].packages);
1359 packages.total = lists[i].total;
1366 listPackages: function(offset, limit, pattern)
1368 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1371 installedPackages: function(offset, limit, pattern)
1373 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1376 findPackages: function(offset, limit, pattern)
1378 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1381 installPackage: _luci2.rpc.declare({
1382 object: 'luci2.opkg',
1384 params: [ 'package' ],
1388 removePackage: _luci2.rpc.declare({
1389 object: 'luci2.opkg',
1391 params: [ 'package' ],
1395 getConfig: _luci2.rpc.declare({
1396 object: 'luci2.opkg',
1397 method: 'config_get',
1398 expect: { config: '' }
1401 setConfig: _luci2.rpc.declare({
1402 object: 'luci2.opkg',
1403 method: 'config_set',
1410 login: _luci2.rpc.declare({
1413 params: [ 'username', 'password' ],
1417 access: _luci2.rpc.declare({
1420 params: [ 'scope', 'object', 'function' ],
1421 expect: { access: false }
1426 return _luci2.session.access('ubus', 'session', 'access');
1429 startHeartbeat: function()
1431 this._hearbeatInterval = window.setInterval(function() {
1432 _luci2.session.isAlive().then(function(alive) {
1435 _luci2.session.stopHeartbeat();
1436 _luci2.ui.login(true);
1440 }, _luci2.globals.timeout * 2);
1443 stopHeartbeat: function()
1445 if (typeof(this._hearbeatInterval) != 'undefined')
1447 window.clearInterval(this._hearbeatInterval);
1448 delete this._hearbeatInterval;
1455 saveScrollTop: function()
1457 this._scroll_top = $(document).scrollTop();
1460 restoreScrollTop: function()
1462 if (typeof(this._scroll_top) == 'undefined')
1465 $(document).scrollTop(this._scroll_top);
1467 delete this._scroll_top;
1470 loading: function(enable)
1472 var win = $(window);
1473 var body = $('body');
1475 var state = _luci2.ui._loading || (_luci2.ui._loading = {
1477 .addClass('cbi-modal-loader')
1478 .append($('<div />').text(_luci2.tr('Loading data...')))
1484 body.css('overflow', 'hidden');
1485 body.css('padding', 0);
1486 body.css('width', win.width());
1487 body.css('height', win.height());
1488 state.modal.css('width', win.width());
1489 state.modal.css('height', win.height());
1495 body.css('overflow', '');
1496 body.css('padding', '');
1497 body.css('width', '');
1498 body.css('height', '');
1502 dialog: function(title, content, options)
1504 var win = $(window);
1505 var body = $('body');
1507 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1508 dialog: $('<div />')
1509 .addClass('cbi-modal-dialog')
1510 .append($('<div />')
1511 .append($('<div />')
1512 .addClass('cbi-modal-dialog-header'))
1513 .append($('<div />')
1514 .addClass('cbi-modal-dialog-body'))
1515 .append($('<div />')
1516 .addClass('cbi-modal-dialog-footer')
1517 .append($('<button />')
1518 .addClass('cbi-button')
1519 .text(_luci2.tr('Close'))
1522 .css('overflow', '')
1527 $(this).parent().parent().parent().hide();
1532 if (typeof(options) != 'object')
1535 if (title === false)
1538 .css('overflow', '')
1543 state.dialog.hide();
1548 var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1549 var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1553 if (options.style == 'confirm')
1555 ftr.append($('<button />')
1556 .addClass('cbi-button')
1557 .text(_luci2.tr('Ok'))
1558 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1560 ftr.append($('<button />')
1561 .addClass('cbi-button')
1562 .text(_luci2.tr('Cancel'))
1563 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1565 else if (options.style == 'close')
1567 ftr.append($('<button />')
1568 .addClass('cbi-button')
1569 .text(_luci2.tr('Close'))
1570 .click(options.close || function() { _luci2.ui.dialog(false) }));
1572 else if (options.style == 'wait')
1574 ftr.append($('<button />')
1575 .addClass('cbi-button')
1576 .text(_luci2.tr('Close'))
1577 .attr('disabled', true));
1580 state.dialog.find('div.cbi-modal-dialog-header').text(title);
1581 state.dialog.show();
1584 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1588 state.dialog.children()
1589 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1591 body.css('overflow', 'hidden');
1592 body.css('padding', 0);
1593 body.css('width', win.width());
1594 body.css('height', win.height());
1595 state.dialog.css('width', win.width());
1596 state.dialog.css('height', win.height());
1599 upload: function(title, content, options)
1601 var state = _luci2.ui._upload || (_luci2.ui._upload = {
1603 .attr('method', 'post')
1604 .attr('action', '/cgi-bin/luci-upload')
1605 .attr('enctype', 'multipart/form-data')
1606 .attr('target', 'cbi-fileupload-frame')
1608 .append($('<input />')
1609 .attr('type', 'hidden')
1610 .attr('name', 'sessionid'))
1611 .append($('<input />')
1612 .attr('type', 'hidden')
1613 .attr('name', 'filename'))
1614 .append($('<input />')
1615 .attr('type', 'file')
1616 .attr('name', 'filedata')
1617 .addClass('cbi-input-file'))
1618 .append($('<div />')
1619 .css('width', '100%')
1620 .addClass('progressbar')
1621 .addClass('intermediate')
1622 .append($('<div />')
1623 .css('width', '100%')))
1624 .append($('<iframe />')
1625 .attr('name', 'cbi-fileupload-frame')
1626 .css('width', '1px')
1627 .css('height', '1px')
1628 .css('visibility', 'hidden')),
1630 finish_cb: function(ev) {
1631 $(this).off('load');
1633 var body = (this.contentDocument || this.contentWindow.document).body;
1634 if (body.firstChild.tagName.toLowerCase() == 'pre')
1635 body = body.firstChild;
1639 json = $.parseJSON(body.innerHTML);
1642 message: _luci2.tr('Invalid server response received'),
1643 error: [ -1, _luci2.tr('Invalid data') ]
1649 L.ui.dialog(L.tr('File upload'), [
1650 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1651 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1652 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1653 ], { style: 'close' });
1655 else if (typeof(state.success_cb) == 'function')
1657 state.success_cb(json);
1661 confirm_cb: function() {
1662 var f = state.form.find('.cbi-input-file');
1663 var b = state.form.find('.progressbar');
1664 var p = state.form.find('p');
1669 state.form.find('iframe').on('load', state.finish_cb);
1670 state.form.submit();
1674 p.text(_luci2.tr('File upload in progress …'));
1676 state.form.parent().parent().find('button').prop('disabled', true);
1680 state.form.find('.progressbar').hide();
1681 state.form.find('.cbi-input-file').val('').show();
1682 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1684 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1685 state.form.find('[name=filename]').val(options.filename);
1687 state.success_cb = options.success;
1689 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1691 confirm: state.confirm_cb
1695 reconnect: function()
1697 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1698 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1699 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1701 var interval, timeout;
1704 _luci2.tr('Waiting for device'), [
1705 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1707 .css('width', '100%')
1708 .addClass('progressbar')
1709 .addClass('intermediate')
1710 .append($('<div />')
1711 .css('width', '100%'))
1712 ], { style: 'wait' }
1715 for (var i = 0; i < protocols.length; i++)
1716 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1718 //_luci2.network.getNetworkStatus(function(s) {
1719 // for (var i = 0; i < protocols.length; i++)
1721 // for (var j = 0; j < s.length; j++)
1723 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1724 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1726 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1727 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1730 //}).then(function() {
1731 images.on('load', function() {
1732 var url = this.getAttribute('url');
1733 _luci2.session.isAlive().then(function(access) {
1736 window.clearTimeout(timeout);
1737 window.clearInterval(interval);
1738 _luci2.ui.dialog(false);
1743 location.href = url;
1748 interval = window.setInterval(function() {
1749 images.each(function() {
1750 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1754 timeout = window.setTimeout(function() {
1755 window.clearInterval(interval);
1759 _luci2.tr('Device not responding'),
1760 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1767 login: function(invalid)
1769 var state = _luci2.ui._login || (_luci2.ui._login = {
1772 .attr('method', 'post')
1774 .addClass('alert-message')
1775 .text(_luci2.tr('Wrong username or password given!')))
1777 .append($('<label />')
1778 .text(_luci2.tr('Username'))
1779 .append($('<br />'))
1780 .append($('<input />')
1781 .attr('type', 'text')
1782 .attr('name', 'username')
1783 .attr('value', 'root')
1784 .addClass('cbi-input-text')
1785 .keypress(function(ev) {
1786 if (ev.which == 10 || ev.which == 13)
1790 .append($('<label />')
1791 .text(_luci2.tr('Password'))
1792 .append($('<br />'))
1793 .append($('<input />')
1794 .attr('type', 'password')
1795 .attr('name', 'password')
1796 .addClass('cbi-input-password')
1797 .keypress(function(ev) {
1798 if (ev.which == 10 || ev.which == 13)
1802 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1804 response_cb: function(response) {
1805 if (!response.ubus_rpc_session)
1807 _luci2.ui.login(true);
1811 _luci2.globals.sid = response.ubus_rpc_session;
1812 _luci2.setHash('id', _luci2.globals.sid);
1813 _luci2.session.startHeartbeat();
1814 _luci2.ui.dialog(false);
1815 state.deferred.resolve();
1819 confirm_cb: function() {
1820 var u = state.form.find('[name=username]').val();
1821 var p = state.form.find('[name=password]').val();
1827 _luci2.tr('Logging in'), [
1828 $('<p />').text(_luci2.tr('Log in in progress …')),
1830 .css('width', '100%')
1831 .addClass('progressbar')
1832 .addClass('intermediate')
1833 .append($('<div />')
1834 .css('width', '100%'))
1835 ], { style: 'wait' }
1838 _luci2.globals.sid = '00000000000000000000000000000000';
1839 _luci2.session.login(u, p).then(state.response_cb);
1843 if (!state.deferred || state.deferred.state() != 'pending')
1844 state.deferred = $.Deferred();
1846 /* try to find sid from hash */
1847 var sid = _luci2.getHash('id');
1848 if (sid && sid.match(/^[a-f0-9]{32}$/))
1850 _luci2.globals.sid = sid;
1851 _luci2.session.isAlive().then(function(access) {
1854 _luci2.session.startHeartbeat();
1855 state.deferred.resolve();
1859 _luci2.setHash('id', undefined);
1864 return state.deferred;
1868 state.form.find('.alert-message').show();
1870 state.form.find('.alert-message').hide();
1872 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1874 confirm: state.confirm_cb
1877 state.form.find('[name=password]').focus();
1879 return state.deferred;
1882 cryptPassword: _luci2.rpc.declare({
1886 expect: { crypt: '' }
1890 _acl_merge_scope: function(acl_scope, scope)
1892 if ($.isArray(scope))
1894 for (var i = 0; i < scope.length; i++)
1895 acl_scope[scope[i]] = true;
1897 else if ($.isPlainObject(scope))
1899 for (var object_name in scope)
1901 if (!$.isArray(scope[object_name]))
1904 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1906 for (var i = 0; i < scope[object_name].length; i++)
1907 acl_object[scope[object_name][i]] = true;
1912 _acl_merge_permission: function(acl_perm, perm)
1914 if ($.isPlainObject(perm))
1916 for (var scope_name in perm)
1918 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1919 this._acl_merge_scope(acl_scope, perm[scope_name]);
1924 _acl_merge_group: function(acl_group, group)
1926 if ($.isPlainObject(group))
1928 if (!acl_group.description)
1929 acl_group.description = group.description;
1933 var acl_perm = acl_group.read || (acl_group.read = { });
1934 this._acl_merge_permission(acl_perm, group.read);
1939 var acl_perm = acl_group.write || (acl_group.write = { });
1940 this._acl_merge_permission(acl_perm, group.write);
1945 _acl_merge_tree: function(acl_tree, tree)
1947 if ($.isPlainObject(tree))
1949 for (var group_name in tree)
1951 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1952 this._acl_merge_group(acl_group, tree[group_name]);
1957 listAvailableACLs: _luci2.rpc.declare({
1960 expect: { acls: [ ] },
1961 filter: function(trees) {
1963 for (var i = 0; i < trees.length; i++)
1964 _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
1969 renderMainMenu: _luci2.rpc.declare({
1972 expect: { menu: { } },
1973 filter: function(entries) {
1974 _luci2.globals.mainMenu = new _luci2.ui.menu();
1975 _luci2.globals.mainMenu.entries(entries);
1979 .append(_luci2.globals.mainMenu.render(0, 1));
1983 renderViewMenu: function()
1987 .append(_luci2.globals.mainMenu.render(2, 900));
1990 renderView: function(node)
1992 var name = node.view.split(/\//).join('.');
1994 _luci2.ui.renderViewMenu();
1997 _luci2._views = { };
1999 _luci2.setHash('view', node.view);
2001 if (_luci2._views[name] instanceof _luci2.ui.view)
2002 return _luci2._views[name].render();
2004 var url = _luci2.globals.resource + '/view/' + name + '.js';
2006 return $.ajax(url, {
2010 }).then(function(data) {
2012 var viewConstructorSource = (
2013 '(function(L, $) {\n' +
2015 '})(_luci2, $);\n\n' +
2017 ).format(data, url);
2019 var viewConstructor = eval(viewConstructorSource);
2021 _luci2._views[name] = new viewConstructor({
2023 acls: node.write || { }
2026 return _luci2._views[name].render();
2029 alert('Unable to instantiate view "%s": %s'.format(url, e));
2032 return $.Deferred().resolve();
2036 updateHostname: function()
2038 return _luci2.system.getBoardInfo().then(function(info) {
2040 $('#hostname').text(info.hostname);
2046 _luci2.ui.loading(true);
2049 _luci2.ui.updateHostname(),
2050 _luci2.ui.renderMainMenu()
2052 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2053 _luci2.ui.loading(false);
2059 var AbstractWidget = Class.extend({
2060 i18n: function(text) {
2064 toString: function() {
2065 var x = document.createElement('div');
2066 x.appendChild(this.render());
2071 insertInto: function(id) {
2072 return $(id).empty().append(this.render());
2076 this.ui.view = AbstractWidget.extend({
2077 _fetch_template: function()
2079 return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2083 success: function(data) {
2084 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2085 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2092 return _luci2.tr(p2);
2095 return _luci2.globals[p2] || '';
2098 return '(?' + match + ')';
2102 $('#maincontent').append(data);
2109 throw "Not implemented";
2114 var container = $('#maincontent');
2119 container.append($('<h2 />').append(this.title));
2121 if (this.description)
2122 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2125 return this._fetch_template().then(function() {
2126 return _luci2.deferrable(self.execute());
2131 this.ui.menu = AbstractWidget.extend({
2136 entries: function(entries)
2138 for (var entry in entries)
2140 var path = entry.split(/\//);
2141 var node = this._nodes;
2143 for (i = 0; i < path.length; i++)
2148 if (!node.childs[path[i]])
2149 node.childs[path[i]] = { };
2151 node = node.childs[path[i]];
2154 $.extend(node, entries[entry]);
2158 _indexcmp: function(a, b)
2160 var x = a.index || 0;
2161 var y = b.index || 0;
2165 firstChildView: function(node)
2171 for (var child in (node.childs || { }))
2172 nodes.push(node.childs[child]);
2174 nodes.sort(this._indexcmp);
2176 for (var i = 0; i < nodes.length; i++)
2178 var child = this.firstChildView(nodes[i]);
2181 $.extend(node, child);
2189 _onclick: function(ev)
2191 _luci2.ui.loading(true);
2192 _luci2.ui.renderView(ev.data).then(function() {
2193 _luci2.ui.loading(false);
2196 ev.preventDefault();
2200 _render: function(childs, level, min, max)
2203 for (var node in childs)
2205 var child = this.firstChildView(childs[node]);
2207 nodes.push(childs[node]);
2210 nodes.sort(this._indexcmp);
2212 var list = $('<ul />');
2215 list.addClass('nav');
2216 else if (level == 1)
2217 list.addClass('dropdown-menu');
2219 for (var i = 0; i < nodes.length; i++)
2221 if (!_luci2.globals.defaultNode)
2223 var v = _luci2.getHash('view');
2224 if (!v || v == nodes[i].view)
2225 _luci2.globals.defaultNode = nodes[i];
2228 var item = $('<li />')
2231 .text(_luci2.tr(nodes[i].title))
2232 .click(nodes[i], this._onclick))
2235 if (nodes[i].childs && level < max)
2237 item.addClass('dropdown');
2238 item.find('a').addClass('menu');
2239 item.append(this._render(nodes[i].childs, level + 1));
2246 render: function(min, max)
2248 var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2249 return this._render(top.childs, 0, min, max);
2252 getNode: function(path, max)
2254 var p = path.split(/\//);
2255 var n = this._nodes;
2257 if (typeof(max) == 'undefined')
2260 for (var i = 0; i < max; i++)
2262 if (!n.childs[p[i]])
2272 this.ui.table = AbstractWidget.extend({
2278 row: function(values)
2280 if ($.isArray(values))
2282 this._rows.push(values);
2284 else if ($.isPlainObject(values))
2287 for (var i = 0; i < this.options.columns.length; i++)
2289 var col = this.options.columns[i];
2291 if (typeof col.key == 'string')
2292 v.push(values[col.key]);
2300 rows: function(rows)
2302 for (var i = 0; i < rows.length; i++)
2306 render: function(id)
2308 var fieldset = document.createElement('fieldset');
2309 fieldset.className = 'cbi-section';
2311 if (this.options.caption)
2313 var legend = document.createElement('legend');
2314 $(legend).append(this.options.caption);
2315 fieldset.appendChild(legend);
2318 var table = document.createElement('table');
2319 table.className = 'cbi-section-table';
2321 var has_caption = false;
2322 var has_description = false;
2324 for (var i = 0; i < this.options.columns.length; i++)
2325 if (this.options.columns[i].caption)
2330 else if (this.options.columns[i].description)
2332 has_description = true;
2338 var tr = table.insertRow(-1);
2339 tr.className = 'cbi-section-table-titles';
2341 for (var i = 0; i < this.options.columns.length; i++)
2343 var col = this.options.columns[i];
2344 var th = document.createElement('th');
2345 th.className = 'cbi-section-table-cell';
2350 th.style.width = col.width;
2353 th.style.textAlign = col.align;
2356 $(th).append(col.caption);
2360 if (has_description)
2362 var tr = table.insertRow(-1);
2363 tr.className = 'cbi-section-table-descr';
2365 for (var i = 0; i < this.options.columns.length; i++)
2367 var col = this.options.columns[i];
2368 var th = document.createElement('th');
2369 th.className = 'cbi-section-table-cell';
2374 th.style.width = col.width;
2377 th.style.textAlign = col.align;
2379 if (col.description)
2380 $(th).append(col.description);
2384 if (this._rows.length == 0)
2386 if (this.options.placeholder)
2388 var tr = table.insertRow(-1);
2389 var td = tr.insertCell(-1);
2390 td.className = 'cbi-section-table-cell';
2392 td.colSpan = this.options.columns.length;
2393 $(td).append(this.options.placeholder);
2398 for (var i = 0; i < this._rows.length; i++)
2400 var tr = table.insertRow(-1);
2402 for (var j = 0; j < this.options.columns.length; j++)
2404 var col = this.options.columns[j];
2405 var td = tr.insertCell(-1);
2407 var val = this._rows[i][j];
2409 if (typeof(val) == 'undefined')
2410 val = col.placeholder;
2412 if (typeof(val) == 'undefined')
2416 td.style.width = col.width;
2419 td.style.textAlign = col.align;
2421 if (typeof col.format == 'string')
2422 $(td).append(col.format.format(val));
2423 else if (typeof col.format == 'function')
2424 $(td).append(col.format(val, i));
2432 fieldset.appendChild(table);
2438 this.ui.progress = AbstractWidget.extend({
2441 var vn = parseInt(this.options.value) || 0;
2442 var mn = parseInt(this.options.max) || 100;
2443 var pc = Math.floor((100 / mn) * vn);
2445 var bar = document.createElement('div');
2446 bar.className = 'progressbar';
2448 bar.appendChild(document.createElement('div'));
2449 bar.lastChild.appendChild(document.createElement('div'));
2450 bar.lastChild.style.width = pc + '%';
2452 if (typeof(this.options.format) == 'string')
2453 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2454 else if (typeof(this.options.format) == 'function')
2455 $(bar.lastChild.lastChild).append(this.options.format(pc));
2457 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2463 this.ui.devicebadge = AbstractWidget.extend({
2466 var dev = this.options.l3_device || this.options.device || '?';
2468 var span = document.createElement('span');
2469 span.className = 'ifacebadge';
2471 if (typeof(this.options.signal) == 'number' ||
2472 typeof(this.options.noise) == 'number')
2475 if (typeof(this.options.signal) != 'undefined' &&
2476 typeof(this.options.noise) != 'undefined')
2478 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2491 span.appendChild(document.createElement('img'));
2492 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2495 span.title = _luci2.tr('No signal');
2497 span.title = '%s: %d %s / %s: %d %s'.format(
2498 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2499 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2504 var type = 'ethernet';
2505 var desc = _luci2.tr('Ethernet device');
2507 if (this.options.l3_device != this.options.device)
2510 desc = _luci2.tr('Tunnel interface');
2512 else if (dev.indexOf('br-') == 0)
2515 desc = _luci2.tr('Bridge');
2517 else if (dev.indexOf('.') > 0)
2520 desc = _luci2.tr('VLAN interface');
2522 else if (dev.indexOf('wlan') == 0 ||
2523 dev.indexOf('ath') == 0 ||
2524 dev.indexOf('wl') == 0)
2527 desc = _luci2.tr('Wireless Network');
2530 span.appendChild(document.createElement('img'));
2531 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2535 $(span).append(' ');
2536 $(span).append(dev);
2542 var type = function(f, l)
2552 _luci2.cbi.validation.message = _luci2.tr(msg);
2555 compile: function(code)
2560 var types = _luci2.cbi.validation.types;
2565 for (var i = 0; i < code.length; i++)
2573 switch (code.charCodeAt(i))
2585 var label = code.substring(pos, i);
2586 label = label.replace(/\\(.)/g, '$1');
2587 label = label.replace(/^[ \t]+/g, '');
2588 label = label.replace(/[ \t]+$/g, '');
2590 if (label && !isNaN(label))
2592 stack.push(parseFloat(label));
2594 else if (label.match(/^(['"]).*\1$/))
2596 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2598 else if (typeof types[label] == 'function')
2600 stack.push(types[label]);
2605 throw "Syntax error, unhandled token '"+label+"'";
2610 depth += (code.charCodeAt(i) == 40);
2616 if (typeof stack[stack.length-2] != 'function')
2617 throw "Syntax error, argument list follows non-function";
2619 stack[stack.length-1] =
2620 arguments.callee(code.substring(pos, i));
2633 var validation = this.cbi.validation;
2635 validation.types = {
2636 'integer': function()
2638 if (this.match(/^-?[0-9]+$/) != null)
2641 validation.i18n('Must be a valid integer');
2645 'uinteger': function()
2647 if (validation.types['integer'].apply(this) && (this >= 0))
2650 validation.i18n('Must be a positive integer');
2656 if (!isNaN(parseFloat(this)))
2659 validation.i18n('Must be a valid number');
2663 'ufloat': function()
2665 if (validation.types['float'].apply(this) && (this >= 0))
2668 validation.i18n('Must be a positive number');
2672 'ipaddr': function()
2674 if (validation.types['ip4addr'].apply(this) ||
2675 validation.types['ip6addr'].apply(this))
2678 validation.i18n('Must be a valid IP address');
2682 'ip4addr': function()
2684 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2686 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2687 (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2688 (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2689 (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2690 ((RegExp.$6.indexOf('.') < 0)
2691 ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2692 : (validation.types['ip4addr'].apply(RegExp.$6))))
2696 validation.i18n('Must be a valid IPv4 address');
2700 'ip6addr': function()
2702 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2704 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2706 var addr = RegExp.$1;
2713 if (addr.indexOf('.') > 0)
2715 var off = addr.lastIndexOf(':');
2717 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2719 validation.i18n('Must be a valid IPv6 address');
2723 addr = addr.substr(0, off) + ':0:0';
2726 if (addr.indexOf('::') >= 0)
2731 for (var i = 1; i < (addr.length-1); i++)
2732 if (addr.charAt(i) == ':')
2737 validation.i18n('Must be a valid IPv6 address');
2741 for (var i = 0; i < (7 - colons); i++)
2744 if (addr.match(/^(.*?)::(.*?)$/))
2745 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2746 (RegExp.$2 ? ':' + RegExp.$2 : '');
2749 if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2752 validation.i18n('Must be a valid IPv6 address');
2762 if (validation.types['integer'].apply(this) &&
2763 (this >= 0) && (this <= 65535))
2766 validation.i18n('Must be a valid port number');
2770 'portrange': function()
2772 if (this.match(/^(\d+)-(\d+)$/))
2777 if (validation.types['port'].apply(p1) &&
2778 validation.types['port'].apply(p2) &&
2779 (parseInt(p1) <= parseInt(p2)))
2782 else if (validation.types['port'].apply(this))
2787 validation.i18n('Must be a valid port range');
2791 'macaddr': function()
2793 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2796 validation.i18n('Must be a valid MAC address');
2802 if (validation.types['hostname'].apply(this) ||
2803 validation.types['ipaddr'].apply(this))
2806 validation.i18n('Must be a valid hostname or IP address');
2810 'hostname': function()
2812 if ((this.length <= 253) &&
2813 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2814 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2815 this.match(/[^0-9.]/)))))
2818 validation.i18n('Must be a valid host name');
2822 'network': function()
2824 if (validation.types['uciname'].apply(this) ||
2825 validation.types['host'].apply(this))
2828 validation.i18n('Must be a valid network name');
2832 'wpakey': function()
2836 if ((v.length == 64)
2837 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2838 : ((v.length >= 8) && (v.length <= 63)))
2841 validation.i18n('Must be a valid WPA key');
2845 'wepkey': function()
2849 if (v.substr(0,2) == 's:')
2852 if (((v.length == 10) || (v.length == 26))
2853 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2854 : ((v.length == 5) || (v.length == 13)))
2857 validation.i18n('Must be a valid WEP key');
2861 'uciname': function()
2863 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2866 validation.i18n('Must be a valid UCI identifier');
2870 'range': function(min, max)
2872 var val = parseFloat(this);
2874 if (validation.types['integer'].apply(this) &&
2875 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2878 validation.i18n('Must be a number between %d and %d');
2882 'min': function(min)
2884 var val = parseFloat(this);
2886 if (validation.types['integer'].apply(this) &&
2887 !isNaN(min) && !isNaN(val) && (val >= min))
2890 validation.i18n('Must be a number greater or equal to %d');
2894 'max': function(max)
2896 var val = parseFloat(this);
2898 if (validation.types['integer'].apply(this) &&
2899 !isNaN(max) && !isNaN(val) && (val <= max))
2902 validation.i18n('Must be a number lower or equal to %d');
2906 'rangelength': function(min, max)
2908 var val = '' + this;
2910 if (!isNaN(min) && !isNaN(max) &&
2911 (val.length >= min) && (val.length <= max))
2914 validation.i18n('Must be between %d and %d characters');
2918 'minlength': function(min)
2920 var val = '' + this;
2922 if (!isNaN(min) && (val.length >= min))
2925 validation.i18n('Must be at least %d characters');
2929 'maxlength': function(max)
2931 var val = '' + this;
2933 if (!isNaN(max) && (val.length <= max))
2936 validation.i18n('Must be at most %d characters');
2944 for (var i = 0; i < arguments.length; i += 2)