2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013-2014 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);
176 if (!window.location.origin)
177 window.location.origin = '%s//%s%s'.format(
178 window.location.protocol,
179 window.location.hostname,
180 (window.location.port ? ':' + window.location.port : '')
187 var Class = function() { };
189 Class.extend = function(properties)
191 Class.initializing = true;
193 var prototype = new this();
194 var superprot = this.prototype;
196 Class.initializing = false;
198 $.extend(prototype, properties, {
199 callSuper: function() {
201 var meth = arguments[0];
203 if (typeof(superprot[meth]) != 'function')
206 for (var i = 1; i < arguments.length; i++)
207 args.push(arguments[i]);
209 return superprot[meth].apply(this, args);
215 this.options = arguments[0] || { };
217 if (!Class.initializing && typeof(this.init) == 'function')
218 this.init.apply(this, arguments);
221 _class.prototype = prototype;
222 _class.prototype.constructor = _class;
224 _class.extend = Class.extend;
229 this.defaults = function(obj, def)
232 if (typeof(obj[key]) == 'undefined')
238 this.isDeferred = function(x)
240 return (typeof(x) == 'object' &&
241 typeof(x.then) == 'function' &&
242 typeof(x.promise) == 'function');
245 this.deferrable = function()
247 if (this.isDeferred(arguments[0]))
250 var d = $.Deferred();
251 d.resolve.apply(d, arguments);
260 plural: function(n) { return 0 + (n != 1) },
266 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
267 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
269 for (var i = 0; i < langs.length; i++)
270 $.ajax('%s/i18n/base.%s.json'.format(L.globals.resource, langs[i]), {
274 success: function(data) {
275 $.extend(L.i18n.catalog, data);
277 var pe = L.i18n.catalog[''];
280 delete L.i18n.catalog[''];
282 var pf = new Function('n', 'return 0 + (' + pe + ')');
289 L.i18n.loaded = true;
294 this.tr = function(msgid)
298 var msgstr = L.i18n.catalog[msgid];
300 if (typeof(msgstr) == 'undefined')
302 else if (typeof(msgstr) == 'string')
308 this.trp = function(msgid, msgid_plural, count)
312 var msgstr = L.i18n.catalog[msgid];
314 if (typeof(msgstr) == 'undefined')
315 return (count == 1) ? msgid : msgid_plural;
316 else if (typeof(msgstr) == 'string')
319 return msgstr[L.i18n.plural(count)];
322 this.trc = function(msgctx, msgid)
326 var msgstr = L.i18n.catalog[msgid + '\u0004' + msgctx];
328 if (typeof(msgstr) == 'undefined')
330 else if (typeof(msgstr) == 'string')
336 this.trcp = function(msgctx, msgid, msgid_plural, count)
340 var msgstr = L.i18n.catalog[msgid + '\u0004' + msgctx];
342 if (typeof(msgstr) == 'undefined')
343 return (count == 1) ? msgid : msgid_plural;
344 else if (typeof(msgstr) == 'string')
347 return msgstr[L.i18n.plural(count)];
350 this.setHash = function(key, value)
353 var data = this.getHash(undefined);
355 if (typeof(value) == 'undefined')
366 for (var i = 0; i < keys.length; i++)
371 h += keys[i] + ':' + data[keys[i]];
375 location.hash = '#' + h;
380 this.getHash = function(key)
383 var tuples = (location.hash || '#').substring(1).split(/,/);
385 for (var i = 0; i < tuples.length; i++)
387 var tuple = tuples[i].split(/:/);
388 if (tuple.length == 2)
389 data[tuple[0]] = tuple[1];
392 if (typeof(key) != 'undefined')
398 this.toArray = function(x)
408 var l = x.split(/\s+/);
409 for (var i = 0; i < l.length; i++)
418 for (var i = 0; i < x.length; i++)
422 else if ($.isPlainObject(x))
426 if (x.hasOwnProperty(k))
435 this.toObject = function(x)
445 var l = x.split(/\x+/);
446 for (var i = 0; i < l.length; i++)
455 for (var i = 0; i < x.length; i++)
459 else if ($.isPlainObject(x))
468 this.filterArray = function(array, item)
470 if (!$.isArray(array))
473 for (var i = 0; i < array.length; i++)
474 if (array[i] === item)
475 array.splice(i--, 1);
480 this.toClassName = function(str, suffix)
483 var l = str.split(/[\/.]/);
485 for (var i = 0; i < l.length; i++)
487 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
489 if (typeof(suffix) == 'string')
495 this.toColor = function(str)
497 if (typeof(str) != 'string' || str.length == 0)
502 else if (str == 'lan')
507 while (i < str.length)
508 hash = str.charCodeAt(i++) + ((hash << 5) - hash);
510 var r = (hash & 0xFF) % 128;
511 var g = ((hash >> 8) & 0xFF) % 128;
521 var b = min + (((hash >> 16) & 0xFF) % (max - min));
523 return '#%02X%02X%02X'.format(0xFF - r, 0xFF - g, 0xFF - b);
526 this.parseIPv4 = function(str)
528 if ((typeof(str) != 'string' && !(str instanceof String)) ||
529 !str.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/))
533 var parts = str.split(/\./);
535 for (var i = 0; i < parts.length; i++)
537 var n = parseInt(parts[i], 10);
538 if (isNaN(n) || n > 255)
547 this.parseIPv6 = function(str)
549 if ((typeof(str) != 'string' && !(str instanceof String)) ||
550 !str.match(/^[a-fA-F0-9:]+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/))
553 var parts = str.split(/::/);
554 if (parts.length == 0 || parts.length > 2)
558 if (parts[0].length > 0)
560 var left = parts[0].split(/:/);
561 for (var i = 0; i < left.length; i++)
563 var n = parseInt(left[i], 16);
567 lnum.push((n / 256) >> 0);
573 if (parts.length > 1 && parts[1].length > 0)
575 var right = parts[1].split(/:/);
577 for (var i = 0; i < right.length; i++)
579 if (right[i].indexOf('.') > 0)
581 var addr = L.parseIPv4(right[i]);
585 rnum.push.apply(rnum, addr);
589 var n = parseInt(right[i], 16);
593 rnum.push((n / 256) >> 0);
598 if (rnum.length > 0 && (lnum.length + rnum.length) > 15)
603 num.push.apply(num, lnum);
605 for (var i = 0; i < (16 - lnum.length - rnum.length); i++)
608 num.push.apply(num, rnum);
616 this.isNetmask = function(addr)
618 if (!$.isArray(addr))
623 for (c = 0; (c < addr.length) && (addr[c] == 255); c++);
625 if (c == addr.length)
628 if ((addr[c] == 254) || (addr[c] == 252) || (addr[c] == 248) ||
629 (addr[c] == 240) || (addr[c] == 224) || (addr[c] == 192) ||
630 (addr[c] == 128) || (addr[c] == 0))
632 for (c++; (c < addr.length) && (addr[c] == 0); c++);
634 if (c == addr.length)
644 sid: '00000000000000000000000000000000'
653 _call: function(req, cb)
655 return $.ajax('/ubus', {
657 contentType: 'application/json',
658 data: JSON.stringify(req),
661 timeout: L.globals.timeout,
666 _list_cb: function(msg)
668 var list = msg.result;
670 /* verify message frame */
671 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
674 return $.Deferred().resolveWith(this, [ list ]);
677 _call_cb: function(msg)
680 var type = Object.prototype.toString;
681 var reqs = this._rpc_req;
683 if (!$.isArray(reqs))
689 for (var i = 0; i < msg.length; i++)
691 /* fetch related request info */
692 var req = L.rpc._requests[reqs[i].id];
693 if (typeof(req) != 'object')
694 throw 'No related request for JSON response';
696 /* fetch response attribute and verify returned type */
699 /* verify message frame */
700 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
701 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
702 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
706 for (var key in req.expect)
708 if (typeof(ret) != 'undefined' && key != '')
711 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
712 ret = req.expect[key];
719 if (typeof(req.filter) == 'function')
722 req.priv[1] = req.params;
723 ret = req.filter.apply(L.rpc, req.priv);
726 /* store response data */
727 if (typeof(req.index) == 'number')
728 data[req.index] = ret;
732 /* delete request object */
733 delete L.rpc._requests[reqs[i].id];
736 return $.Deferred().resolveWith(this, [ data ]);
742 for (var i = 0; i < arguments.length; i++)
743 params[i] = arguments[i];
749 params: (params.length > 0) ? params : undefined
752 return this._call(msg, this._list_cb);
757 if (!$.isArray(this._batch))
763 if (!$.isArray(this._batch))
764 return L.deferrable([ ]);
766 var req = this._batch;
770 return this._call(req, this._call_cb);
773 declare: function(options)
778 /* build parameter object */
781 if ($.isArray(options.params))
782 for (p_off = 0; p_off < options.params.length; p_off++)
783 params[options.params[p_off]] = arguments[p_off];
785 /* all remaining arguments are private args */
786 var priv = [ undefined, undefined ];
787 for (; p_off < arguments.length; p_off++)
788 priv.push(arguments[p_off]);
790 /* store request info */
791 var req = _rpc._requests[_rpc._id] = {
792 expect: options.expect,
793 filter: options.filter,
798 /* build message object */
811 /* when a batch is in progress then store index in request data
812 * and push message object onto the stack */
813 if ($.isArray(_rpc._batch))
815 req.index = _rpc._batch.push(msg) - 1;
816 return L.deferrable(msg);
820 return _rpc._call(msg, _rpc._call_cb);
825 this.UCIContext = Class.extend({
839 callLoad: L.rpc.declare({
842 params: [ 'config' ],
843 expect: { values: { } }
846 callOrder: L.rpc.declare({
849 params: [ 'config', 'sections' ]
852 callAdd: L.rpc.declare({
855 params: [ 'config', 'type', 'name', 'values' ],
856 expect: { section: '' }
859 callSet: L.rpc.declare({
862 params: [ 'config', 'section', 'values' ]
865 callDelete: L.rpc.declare({
868 params: [ 'config', 'section', 'options' ]
871 callApply: L.rpc.declare({
874 params: [ 'timeout', 'rollback' ]
877 callConfirm: L.rpc.declare({
882 createSID: function(conf)
884 var v = this.state.values;
885 var n = this.state.creates;
889 sid = "new%06x".format(Math.random() * 0xFFFFFF);
890 } while ((n[conf] && n[conf][sid]) || (v[conf] && v[conf][sid]));
895 reorderSections: function()
897 var v = this.state.values;
898 var n = this.state.creates;
899 var r = this.state.reorder;
901 if ($.isEmptyObject(r))
902 return L.deferrable();
907 gather all created and existing sections, sort them according
908 to their index value and issue an uci order call
923 o.sort(function(a, b) {
924 return (a['.index'] - b['.index']);
929 for (var i = 0; i < o.length; i++)
930 sids.push(o[i]['.name']);
932 this.callOrder(c, sids);
936 this.state.reorder = { };
937 return L.rpc.flush();
940 load: function(packages)
946 if (!$.isArray(packages))
947 packages = [ packages ];
951 for (var i = 0; i < packages.length; i++)
952 if (!seen[packages[i]] && !self.state.values[packages[i]])
954 pkgs.push(packages[i]);
955 seen[packages[i]] = true;
956 self.callLoad(packages[i]);
959 return L.rpc.flush().then(function(responses) {
960 for (var i = 0; i < responses.length; i++)
961 self.state.values[pkgs[i]] = responses[i];
967 unload: function(packages)
969 if (!$.isArray(packages))
970 packages = [ packages ];
972 for (var i = 0; i < packages.length; i++)
974 delete this.state.values[packages[i]];
975 delete this.state.creates[packages[i]];
976 delete this.state.changes[packages[i]];
977 delete this.state.deletes[packages[i]];
981 add: function(conf, type, name)
983 var n = this.state.creates;
984 var sid = name || this.createSID(conf);
994 '.index': 1000 + this.state.newidx++
1000 remove: function(conf, sid)
1002 var n = this.state.creates;
1003 var c = this.state.changes;
1004 var d = this.state.deletes;
1006 /* requested deletion of a just created section */
1007 if (n[conf] && n[conf][sid])
1009 delete n[conf][sid];
1014 delete c[conf][sid];
1019 d[conf][sid] = true;
1023 sections: function(conf, type, cb)
1026 var v = this.state.values[conf];
1027 var n = this.state.creates[conf];
1028 var c = this.state.changes[conf];
1029 var d = this.state.deletes[conf];
1035 if (!d || d[s] !== true)
1036 if (!type || v[s]['.type'] == type)
1037 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
1041 if (!type || n[s]['.type'] == type)
1044 sa.sort(function(a, b) {
1045 return a['.index'] - b['.index'];
1048 for (var i = 0; i < sa.length; i++)
1049 sa[i]['.index'] = i;
1051 if (typeof(cb) == 'function')
1052 for (var i = 0; i < sa.length; i++)
1053 cb.call(this, sa[i], sa[i]['.name']);
1058 get: function(conf, sid, opt)
1060 var v = this.state.values;
1061 var n = this.state.creates;
1062 var c = this.state.changes;
1063 var d = this.state.deletes;
1065 if (typeof(sid) == 'undefined')
1068 /* requested option in a just created section */
1069 if (n[conf] && n[conf][sid])
1074 if (typeof(opt) == 'undefined')
1075 return n[conf][sid];
1077 return n[conf][sid][opt];
1080 /* requested an option value */
1081 if (typeof(opt) != 'undefined')
1083 /* check whether option was deleted */
1084 if (d[conf] && d[conf][sid])
1086 if (d[conf][sid] === true)
1089 for (var i = 0; i < d[conf][sid].length; i++)
1090 if (d[conf][sid][i] == opt)
1094 /* check whether option was changed */
1095 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
1096 return c[conf][sid][opt];
1098 /* return base value */
1099 if (v[conf] && v[conf][sid])
1100 return v[conf][sid][opt];
1105 /* requested an entire section */
1107 return v[conf][sid];
1112 set: function(conf, sid, opt, val)
1114 var v = this.state.values;
1115 var n = this.state.creates;
1116 var c = this.state.changes;
1117 var d = this.state.deletes;
1119 if (typeof(sid) == 'undefined' ||
1120 typeof(opt) == 'undefined' ||
1121 opt.charAt(0) == '.')
1124 if (n[conf] && n[conf][sid])
1126 if (typeof(val) != 'undefined')
1127 n[conf][sid][opt] = val;
1129 delete n[conf][sid][opt];
1131 else if (typeof(val) != 'undefined')
1133 /* do not set within deleted section */
1134 if (d[conf] && d[conf][sid] === true)
1137 /* only set in existing sections */
1138 if (!v[conf] || !v[conf][sid])
1147 /* undelete option */
1148 if (d[conf] && d[conf][sid])
1149 d[conf][sid] = L.filterArray(d[conf][sid], opt);
1151 c[conf][sid][opt] = val;
1155 /* only delete in existing sections */
1156 if (!v[conf] || !v[conf][sid])
1165 if (d[conf][sid] !== true)
1166 d[conf][sid].push(opt);
1170 unset: function(conf, sid, opt)
1172 return this.set(conf, sid, opt, undefined);
1175 get_first: function(conf, type, opt)
1177 var sid = undefined;
1179 L.uci.sections(conf, type, function(s) {
1180 if (typeof(sid) != 'string')
1184 return this.get(conf, sid, opt);
1187 set_first: function(conf, type, opt, val)
1189 var sid = undefined;
1191 L.uci.sections(conf, type, function(s) {
1192 if (typeof(sid) != 'string')
1196 return this.set(conf, sid, opt, val);
1199 unset_first: function(conf, type, opt)
1201 return this.set_first(conf, type, opt, undefined);
1204 swap: function(conf, sid1, sid2)
1206 var s1 = this.get(conf, sid1);
1207 var s2 = this.get(conf, sid2);
1208 var n1 = s1 ? s1['.index'] : NaN;
1209 var n2 = s2 ? s2['.index'] : NaN;
1211 if (isNaN(n1) || isNaN(n2))
1217 this.state.reorder[conf] = true;
1226 var v = this.state.values;
1227 var n = this.state.creates;
1228 var c = this.state.changes;
1229 var d = this.state.deletes;
1238 for (var sid in n[conf])
1245 for (var k in n[conf][sid])
1248 r.type = n[conf][sid][k];
1249 else if (k == '.create')
1250 r.name = n[conf][sid][k];
1251 else if (k.charAt(0) != '.')
1252 r.values[k] = n[conf][sid][k];
1255 snew.push(n[conf][sid]);
1257 self.callAdd(r.config, r.type, r.name, r.values);
1266 for (var sid in c[conf])
1267 self.callSet(conf, sid, c[conf][sid]);
1275 for (var sid in d[conf])
1277 var o = d[conf][sid];
1278 self.callDelete(conf, sid, (o === true) ? undefined : o);
1284 return L.rpc.flush().then(function(responses) {
1286 array "snew" holds references to the created uci sections,
1287 use it to assign the returned names of the new sections
1289 for (var i = 0; i < snew.length; i++)
1290 snew[i]['.name'] = responses[i];
1292 return self.reorderSections();
1293 }).then(function() {
1294 pkgs = L.toArray(pkgs);
1298 return self.load(pkgs);
1302 apply: function(timeout)
1305 var date = new Date();
1306 var deferred = $.Deferred();
1308 if (typeof(timeout) != 'number' || timeout < 1)
1311 self.callApply(timeout, true).then(function(rv) {
1314 deferred.rejectWith(self, [ rv ]);
1318 var try_deadline = date.getTime() + 1000 * timeout;
1319 var try_confirm = function()
1321 return self.callConfirm().then(function(rv) {
1324 if (date.getTime() < try_deadline)
1325 window.setTimeout(try_confirm, 250);
1327 deferred.rejectWith(self, [ rv ]);
1332 deferred.resolveWith(self, [ rv ]);
1336 window.setTimeout(try_confirm, 1000);
1342 changes: L.rpc.declare({
1345 expect: { changes: { } }
1348 readable: function(conf)
1350 return L.session.hasACL('uci', conf, 'read');
1353 writable: function(conf)
1355 return L.session.hasACL('uci', conf, 'write');
1359 this.uci = new this.UCIContext();
1362 listDeviceNames: L.rpc.declare({
1365 expect: { 'devices': [ ] },
1366 filter: function(data) {
1372 getDeviceStatus: L.rpc.declare({
1375 params: [ 'device' ],
1376 expect: { '': { } },
1377 filter: function(data, params) {
1378 if (!$.isEmptyObject(data))
1380 data['device'] = params['device'];
1387 getAssocList: L.rpc.declare({
1389 method: 'assoclist',
1390 params: [ 'device' ],
1391 expect: { results: [ ] },
1392 filter: function(data, params) {
1393 for (var i = 0; i < data.length; i++)
1394 data[i]['device'] = params['device'];
1396 data.sort(function(a, b) {
1397 if (a.bssid < b.bssid)
1399 else if (a.bssid > b.bssid)
1409 getWirelessStatus: function() {
1410 return this.listDeviceNames().then(function(names) {
1413 for (var i = 0; i < names.length; i++)
1414 L.wireless.getDeviceStatus(names[i]);
1416 return L.rpc.flush();
1417 }).then(function(networks) {
1421 'country', 'channel', 'frequency', 'frequency_offset',
1422 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1426 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1427 'signal', 'noise', 'bitrate', 'encryption'
1430 for (var i = 0; i < networks.length; i++)
1432 var phy = rv[networks[i].phy] || (
1433 rv[networks[i].phy] = { networks: [ ] }
1437 device: networks[i].device
1440 for (var j = 0; j < phy_attrs.length; j++)
1441 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1443 for (var j = 0; j < net_attrs.length; j++)
1444 net[net_attrs[j]] = networks[i][net_attrs[j]];
1446 phy.networks.push(net);
1453 getAssocLists: function()
1455 return this.listDeviceNames().then(function(names) {
1458 for (var i = 0; i < names.length; i++)
1459 L.wireless.getAssocList(names[i]);
1461 return L.rpc.flush();
1462 }).then(function(assoclists) {
1465 for (var i = 0; i < assoclists.length; i++)
1466 for (var j = 0; j < assoclists[i].length; j++)
1467 rv.push(assoclists[i][j]);
1473 formatEncryption: function(enc)
1475 var format_list = function(l, s)
1478 for (var i = 0; i < l.length; i++)
1479 rv.push(l[i].toUpperCase());
1480 return rv.join(s ? s : ', ');
1483 if (!enc || !enc.enabled)
1484 return L.tr('None');
1488 if (enc.wep.length == 2)
1489 return L.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1490 else if (enc.wep[0] == 'shared')
1491 return L.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1493 return L.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1497 if (enc.wpa.length == 2)
1498 return L.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1499 format_list(enc.authentication, '/'),
1500 format_list(enc.ciphers, ', ')
1502 else if (enc.wpa[0] == 2)
1503 return 'WPA2 %s (%s)'.format(
1504 format_list(enc.authentication, '/'),
1505 format_list(enc.ciphers, ', ')
1508 return 'WPA %s (%s)'.format(
1509 format_list(enc.authentication, '/'),
1510 format_list(enc.ciphers, ', ')
1514 return L.tr('Unknown');
1519 getZoneColor: function(zone)
1521 if ($.isPlainObject(zone))
1526 else if (zone == 'wan')
1529 for (var i = 0, hash = 0;
1531 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1533 for (var i = 0, color = '#';
1535 color += ('00' + ((hash >> i++ * 8) & 0xFF).tostring(16)).slice(-2));
1540 findZoneByNetwork: function(network)
1543 var zone = undefined;
1545 return L.uci.sections('firewall', 'zone', function(z) {
1546 if (!z.name || !z.network)
1549 if (!$.isArray(z.network))
1550 z.network = z.network.split(/\s+/);
1552 for (var i = 0; i < z.network.length; i++)
1554 if (z.network[i] == network)
1560 }).then(function() {
1562 zone.color = self.getZoneColor(zone);
1569 this.NetworkModel = {
1576 /^wlan[0-9]+\.sta[0-9]+$/
1579 rpcCacheFunctions: [
1580 'protolist', 0, L.rpc.declare({
1582 method: 'get_proto_handlers',
1585 'ifstate', 1, L.rpc.declare({
1586 object: 'network.interface',
1588 expect: { 'interface': [ ] }
1590 'devstate', 2, L.rpc.declare({
1591 object: 'network.device',
1595 'wifistate', 0, L.rpc.declare({
1596 object: 'network.wireless',
1600 'bwstate', 2, L.rpc.declare({
1601 object: 'luci2.network.bwmon',
1602 method: 'statistics',
1603 expect: { 'statistics': { } }
1605 'devlist', 2, L.rpc.declare({
1606 object: 'luci2.network',
1607 method: 'device_list',
1608 expect: { 'devices': [ ] }
1610 'swlist', 0, L.rpc.declare({
1611 object: 'luci2.network',
1612 method: 'switch_list',
1613 expect: { 'switches': [ ] }
1617 loadProtocolHandler: function(proto)
1619 var url = L.globals.resource + '/proto/' + proto + '.js';
1620 var self = L.NetworkModel;
1622 var def = $.Deferred();
1628 }).then(function(data) {
1630 var protoConstructorSource = (
1631 '(function(L, $) { ' +
1635 ).format(data, url);
1637 var protoClass = eval(protoConstructorSource);
1639 self.protocolHandlers[proto] = new protoClass();
1642 alert('Unable to instantiate proto "%s": %s'.format(url, e));
1646 }).fail(function() {
1653 loadProtocolHandlers: function()
1655 var self = L.NetworkModel;
1657 self.loadProtocolHandler('none')
1660 for (var proto in self.rpcCache.protolist)
1661 deferreds.push(self.loadProtocolHandler(proto));
1663 return $.when.apply($, deferreds);
1666 callSwitchInfo: L.rpc.declare({
1667 object: 'luci2.network',
1668 method: 'switch_info',
1669 params: [ 'switch' ],
1670 expect: { 'info': { } }
1673 callSwitchInfoCallback: function(responses) {
1674 var self = L.NetworkModel;
1675 var swlist = self.rpcCache.swlist;
1676 var swstate = self.rpcCache.swstate = { };
1678 for (var i = 0; i < responses.length; i++)
1679 swstate[swlist[i]] = responses[i];
1682 loadCacheCallback: function(level)
1684 var self = L.NetworkModel;
1685 var name = '_fetch_cache_cb_' + level;
1687 return self[name] || (
1688 self[name] = function(responses)
1690 for (var i = 0; i < self.rpcCacheFunctions.length; i += 3)
1691 if (!level || self.rpcCacheFunctions[i + 1] == level)
1692 self.rpcCache[self.rpcCacheFunctions[i]] = responses.shift();
1698 for (var i = 0; i < self.rpcCache.swlist.length; i++)
1699 self.callSwitchInfo(self.rpcCache.swlist[i]);
1701 return L.rpc.flush().then(self.callSwitchInfoCallback);
1704 return L.deferrable();
1709 loadCache: function(level)
1711 var self = L.NetworkModel;
1713 return L.uci.load(['network', 'wireless']).then(function() {
1716 for (var i = 0; i < self.rpcCacheFunctions.length; i += 3)
1717 if (!level || self.rpcCacheFunctions[i + 1] == level)
1718 self.rpcCacheFunctions[i + 2]();
1720 return L.rpc.flush().then(self.loadCacheCallback(level || 0));
1724 isBlacklistedDevice: function(dev)
1726 for (var i = 0; i < this.deviceBlacklist.length; i++)
1727 if (dev.match(this.deviceBlacklist[i]))
1733 sortDevicesCallback: function(a, b)
1735 if (a.options.kind < b.options.kind)
1737 else if (a.options.kind > b.options.kind)
1740 if (a.options.name < b.options.name)
1742 else if (a.options.name > b.options.name)
1748 getDeviceObject: function(ifname)
1750 var alias = (ifname.charAt(0) == '@');
1751 return this.deviceObjects[ifname] || (
1752 this.deviceObjects[ifname] = {
1754 kind: alias ? 'alias' : 'ethernet',
1755 type: alias ? 0 : 1,
1762 getInterfaceObject: function(name)
1764 return this.interfaceObjects[name] || (
1765 this.interfaceObjects[name] = {
1767 proto: this.protocolHandlers.none,
1773 loadDevicesCallback: function()
1775 var self = L.NetworkModel;
1776 var wificount = { };
1778 for (var ifname in self.rpcCache.devstate)
1780 if (self.isBlacklistedDevice(ifname))
1783 var dev = self.rpcCache.devstate[ifname];
1784 var entry = self.getDeviceObject(ifname);
1791 entry.kind = 'tunnel';
1795 entry.kind = 'bridge';
1796 //entry.ports = dev['bridge-members'].sort();
1801 for (var i = 0; i < self.rpcCache.devlist.length; i++)
1803 var dev = self.rpcCache.devlist[i];
1805 if (self.isBlacklistedDevice(dev.device))
1808 var entry = self.getDeviceObject(dev.device);
1810 entry.up = dev.is_up;
1811 entry.type = dev.type;
1815 case 1: /* Ethernet */
1817 entry.kind = 'bridge';
1818 else if (dev.is_tuntap)
1819 entry.kind = 'tunnel';
1820 else if (dev.is_wireless)
1821 entry.kind = 'wifi';
1825 case 768: /* IP-IP Tunnel */
1826 case 769: /* IP6-IP6 Tunnel */
1827 case 776: /* IPv6-in-IPv4 */
1828 case 778: /* GRE over IP */
1829 entry.kind = 'tunnel';
1834 var net = L.uci.sections('network');
1835 for (var i = 0; i < net.length; i++)
1838 var sid = s['.name'];
1840 if (s['.type'] == 'device' && s.name)
1842 var entry = self.getDeviceObject(s.name);
1848 entry.kind = 'tunnel';
1854 else if (s['.type'] == 'interface' && !s['.anonymous'] && s.ifname)
1856 var ifnames = L.toArray(s.ifname);
1858 for (var j = 0; j < ifnames.length; j++)
1859 self.getDeviceObject(ifnames[j]);
1861 if (s['.name'] != 'loopback')
1863 var entry = self.getDeviceObject('@%s'.format(s['.name']));
1866 entry.kind = 'alias';
1870 else if (s['.type'] == 'switch_vlan' && s.device)
1872 var sw = self.rpcCache.swstate[s.device];
1873 var vid = parseInt(s.vid || s.vlan);
1874 var ports = L.toArray(s.ports);
1876 if (!sw || !ports.length || isNaN(vid))
1879 var ifname = undefined;
1881 for (var j = 0; j < ports.length; j++)
1883 var port = parseInt(ports[j]);
1884 var tag = (ports[j].replace(/[^tu]/g, '') == 't');
1886 if (port == sw.cpu_port)
1888 // XXX: need a way to map switch to netdev
1890 ifname = 'eth0.%d'.format(vid);
1901 var entry = self.getDeviceObject(ifname);
1903 entry.kind = 'vlan';
1910 var wifi = L.uci.sections('wireless');
1911 for (var i = 0; i < wifi.length; i++)
1914 var sid = s['.name'];
1916 if (s['.type'] == 'wifi-iface' && s.device)
1918 var r = parseInt(s.device.replace(/^[^0-9]+/, ''));
1919 var n = wificount[s.device] = (wificount[s.device] || 0) + 1;
1920 var id = 'radio%d.network%d'.format(r, n);
1923 if (self.rpcCache.wifistate[s.device])
1925 var ifcs = self.rpcCache.wifistate[s.device].interfaces;
1926 for (var ifc in ifcs)
1928 if (ifcs[ifc].section == sid && ifcs[ifc].ifname)
1930 ifname = ifcs[ifc].ifname;
1936 var entry = self.getDeviceObject(ifname);
1938 entry.kind = 'wifi';
1941 entry.wdev = s.device;
1942 entry.wmode = s.mode;
1943 entry.wssid = s.ssid;
1944 entry.wbssid = s.bssid;
1948 for (var i = 0; i < net.length; i++)
1951 var sid = s['.name'];
1953 if (s['.type'] == 'interface' && !s['.anonymous'] && s.type == 'bridge')
1955 var ifnames = L.toArray(s.ifname);
1957 for (var ifname in self.deviceObjects)
1959 var dev = self.deviceObjects[ifname];
1961 if (dev.kind != 'wifi')
1964 var wnets = L.toArray(L.uci.get('wireless', dev.sid, 'network'));
1965 if ($.inArray(sid, wnets) > -1)
1966 ifnames.push(ifname);
1969 entry = self.getDeviceObject('br-%s'.format(s['.name']));
1971 entry.kind = 'bridge';
1973 entry.ports = ifnames.sort();
1978 loadInterfacesCallback: function()
1980 var self = L.NetworkModel;
1981 var net = L.uci.sections('network');
1983 for (var i = 0; i < net.length; i++)
1986 var sid = s['.name'];
1988 if (s['.type'] == 'interface' && !s['.anonymous'] && s.proto)
1990 var entry = self.getInterfaceObject(s['.name']);
1991 var proto = self.protocolHandlers[s.proto] || self.protocolHandlers.none;
1993 var l3dev = undefined;
1994 var l2dev = undefined;
1996 var ifnames = L.toArray(s.ifname);
1998 for (var ifname in self.deviceObjects)
2000 var dev = self.deviceObjects[ifname];
2002 if (dev.kind != 'wifi')
2005 var wnets = L.toArray(L.uci.get('wireless', dev.sid, 'network'));
2006 if ($.inArray(entry.name, wnets) > -1)
2007 ifnames.push(ifname);
2011 l3dev = '%s-%s'.format(s.proto, entry.name);
2012 else if (s.type == 'bridge')
2013 l3dev = 'br-%s'.format(entry.name);
2017 if (!proto.virtual && s.type == 'bridge')
2018 l2dev = 'br-%s'.format(entry.name);
2019 else if (!proto.virtual)
2022 entry.proto = proto;
2024 entry.l3dev = l3dev;
2025 entry.l2dev = l2dev;
2029 for (var i = 0; i < self.rpcCache.ifstate.length; i++)
2031 var iface = self.rpcCache.ifstate[i];
2032 var entry = self.getInterfaceObject(iface['interface']);
2033 var proto = self.protocolHandlers[iface.proto] || self.protocolHandlers.none;
2035 /* this is a virtual interface, either deleted from config but
2036 not applied yet or set up from external tools (6rd) */
2039 entry.proto = proto;
2040 entry.l2dev = iface.device;
2041 entry.l3dev = iface.l3_device;
2051 return L.deferrable();
2053 self.rpcCache = { };
2054 self.deviceObjects = { };
2055 self.interfaceObjects = { };
2056 self.protocolHandlers = { };
2058 return self.loadCache()
2059 .then(self.loadProtocolHandlers)
2060 .then(self.loadDevicesCallback)
2061 .then(self.loadInterfacesCallback);
2066 delete this.rpcCache;
2070 refreshInterfaceStatus: function()
2072 return this.loadCache(1).then(this.loadInterfacesCallback);
2075 refreshDeviceStatus: function()
2077 return this.loadCache(2).then(this.loadDevicesCallback);
2080 refreshStatus: function()
2082 return this.loadCache(1)
2083 .then(this.loadCache(2))
2084 .then(this.loadDevicesCallback)
2085 .then(this.loadInterfacesCallback);
2088 getDevices: function()
2092 for (var ifname in this.deviceObjects)
2094 devs.push(new L.NetworkModel.Device(this.deviceObjects[ifname]));
2096 return devs.sort(this.sortDevicesCallback);
2099 getDeviceByInterface: function(iface)
2101 if (iface instanceof L.NetworkModel.Interface)
2102 iface = iface.name();
2104 if (this.interfaceObjects[iface])
2105 return this.getDevice(this.interfaceObjects[iface].l3dev) ||
2106 this.getDevice(this.interfaceObjects[iface].l2dev);
2111 getDevice: function(ifname)
2113 if (this.deviceObjects[ifname])
2114 return new L.NetworkModel.Device(this.deviceObjects[ifname]);
2119 createDevice: function(name)
2121 return new L.NetworkModel.Device(this.getDeviceObject(name));
2124 getInterfaces: function()
2128 for (var name in this.interfaceObjects)
2129 if (name != 'loopback')
2130 ifaces.push(this.getInterface(name));
2132 ifaces.sort(function(a, b) {
2133 if (a.name() < b.name())
2135 else if (a.name() > b.name())
2144 getInterfacesByDevice: function(dev)
2148 if (dev instanceof L.NetworkModel.Device)
2151 for (var name in this.interfaceObjects)
2153 var iface = this.interfaceObjects[name];
2154 if (iface.l2dev == dev || iface.l3dev == dev)
2155 ifaces.push(this.getInterface(name));
2158 ifaces.sort(function(a, b) {
2159 if (a.name() < b.name())
2161 else if (a.name() > b.name())
2170 getInterface: function(iface)
2172 if (this.interfaceObjects[iface])
2173 return new L.NetworkModel.Interface(this.interfaceObjects[iface]);
2178 getProtocols: function()
2182 for (var proto in this.protocolHandlers)
2184 var pr = this.protocolHandlers[proto];
2188 description: pr.description,
2189 virtual: pr.virtual,
2194 return rv.sort(function(a, b) {
2195 if (a.name < b.name)
2197 else if (a.name > b.name)
2204 findWANByAddr: function(ipaddr)
2206 for (var i = 0; i < this.rpcCache.ifstate.length; i++)
2208 var ifstate = this.rpcCache.ifstate[i];
2213 for (var j = 0; j < ifstate.route.length; j++)
2214 if (ifstate.route[j].mask == 0 &&
2215 ifstate.route[j].target == ipaddr &&
2216 typeof(ifstate.route[j].table) == 'undefined')
2218 return this.getInterface(ifstate['interface']);
2227 return this.findWANByAddr('0.0.0.0');
2230 findWAN6: function()
2232 return this.findWANByAddr('::');
2235 resolveAlias: function(ifname)
2237 if (ifname instanceof L.NetworkModel.Device)
2238 ifname = ifname.name();
2240 var dev = this.deviceObjects[ifname];
2243 while (dev && dev.kind == 'alias')
2246 if (seen[dev.ifname])
2249 var ifc = this.interfaceObjects[dev.sid];
2251 seen[dev.ifname] = true;
2252 dev = ifc ? this.deviceObjects[ifc.l3dev] : undefined;
2255 return dev ? this.getDevice(dev.ifname) : undefined;
2259 this.NetworkModel.Device = Class.extend({
2262 sta: L.tr('Client'),
2263 adhoc: L.tr('Ad-Hoc'),
2264 monitor: L.tr('Monitor'),
2265 wds: L.tr('Static WDS')
2268 getStatus: function(key)
2270 var s = L.NetworkModel.rpcCache.devstate[this.options.ifname];
2273 return key ? s[key] : s;
2280 var sid = this.options.sid;
2281 var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
2282 return L.uci.get(pkg, sid, key);
2285 set: function(key, val)
2287 var sid = this.options.sid;
2288 var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
2289 return L.uci.set(pkg, sid, key, val);
2294 if (typeof(this.options.type) == 'undefined')
2295 this.options.type = 1;
2297 if (typeof(this.options.kind) == 'undefined')
2298 this.options.kind = 'ethernet';
2300 if (typeof(this.options.networks) == 'undefined')
2301 this.options.networks = [ ];
2306 return this.options.ifname;
2309 description: function()
2311 switch (this.options.kind)
2314 return L.tr('Alias for network "%s"').format(this.options.ifname.substring(1));
2317 return L.tr('Network bridge');
2320 return L.tr('Network device');
2323 switch (this.options.type)
2325 case 1: /* tuntap */
2326 return L.tr('TAP device');
2329 return L.tr('PPP tunnel');
2331 case 768: /* IP-IP Tunnel */
2332 return L.tr('IP-in-IP tunnel');
2334 case 769: /* IP6-IP6 Tunnel */
2335 return L.tr('IPv6-in-IPv6 tunnel');
2337 case 776: /* IPv6-in-IPv4 */
2338 return L.tr('IPv6-over-IPv4 tunnel');
2341 case 778: /* GRE over IP */
2342 return L.tr('GRE-over-IP tunnel');
2345 return L.tr('Tunnel device');
2349 return L.tr('VLAN %d on %s').format(this.options.vid, this.options.vsw.model);
2352 var o = this.options;
2353 return L.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2354 o.wmode ? this.wifiModeStrings[o.wmode] : L.tr('Unknown mode'),
2355 o.wssid || '?', o.wdev
2359 return L.tr('Unknown device');
2364 var kind = this.options.kind;
2366 if (kind == 'alias')
2369 if (typeof(up) == 'undefined')
2372 return L.globals.resource + '/icons/%s%s.png'.format(kind, up ? '' : '_disabled');
2377 var l = L.NetworkModel.rpcCache.devlist;
2379 for (var i = 0; i < l.length; i++)
2380 if (l[i].device == this.options.ifname)
2381 return (l[i].is_up === true);
2388 return (this.options.kind == 'alias');
2391 isBridge: function()
2393 return (this.options.kind == 'bridge');
2396 isBridgeable: function()
2398 return (this.options.type == 1 && this.options.kind != 'bridge');
2401 isWireless: function()
2403 return (this.options.kind == 'wifi');
2406 isInNetwork: function(net)
2408 if (!(net instanceof L.NetworkModel.Interface))
2409 net = L.NetworkModel.getInterface(net);
2413 if (net.options.l3dev == this.options.ifname ||
2414 net.options.l2dev == this.options.ifname)
2417 var dev = L.NetworkModel.deviceObjects[net.options.l2dev];
2418 if (dev && dev.kind == 'bridge' && dev.ports)
2419 return ($.inArray(this.options.ifname, dev.ports) > -1);
2427 var dev = L.NetworkModel.rpcCache.devstate[this.options.ifname];
2428 if (dev && !isNaN(dev.mtu))
2434 getMACAddress: function()
2436 if (this.options.type != 1)
2439 var dev = L.NetworkModel.rpcCache.devstate[this.options.ifname];
2440 if (dev && dev.macaddr)
2441 return dev.macaddr.toUpperCase();
2446 getInterfaces: function()
2448 return L.NetworkModel.getInterfacesByDevice(this.options.name);
2451 getStatistics: function()
2453 var s = this.getStatus('statistics') || { };
2455 rx_bytes: (s.rx_bytes || 0),
2456 tx_bytes: (s.tx_bytes || 0),
2457 rx_packets: (s.rx_packets || 0),
2458 tx_packets: (s.tx_packets || 0)
2462 getTrafficHistory: function()
2464 var def = new Array(120);
2466 for (var i = 0; i < 120; i++)
2469 var h = L.NetworkModel.rpcCache.bwstate[this.options.ifname] || { };
2471 rx_bytes: (h.rx_bytes || def),
2472 tx_bytes: (h.tx_bytes || def),
2473 rx_packets: (h.rx_packets || def),
2474 tx_packets: (h.tx_packets || def)
2478 removeFromInterface: function(iface)
2480 if (!(iface instanceof L.NetworkModel.Interface))
2481 iface = L.NetworkModel.getInterface(iface);
2486 var ifnames = L.toArray(iface.get('ifname'));
2487 if ($.inArray(this.options.ifname, ifnames) > -1)
2488 iface.set('ifname', L.filterArray(ifnames, this.options.ifname));
2490 if (this.options.kind != 'wifi')
2493 var networks = L.toArray(this.get('network'));
2494 if ($.inArray(iface.name(), networks) > -1)
2495 this.set('network', L.filterArray(networks, iface.name()));
2498 attachToInterface: function(iface)
2500 if (!(iface instanceof L.NetworkModel.Interface))
2501 iface = L.NetworkModel.getInterface(iface);
2506 if (this.options.kind != 'wifi')
2508 var ifnames = L.toArray(iface.get('ifname'));
2509 if ($.inArray(this.options.ifname, ifnames) < 0)
2511 ifnames.push(this.options.ifname);
2512 iface.set('ifname', (ifnames.length > 1) ? ifnames : ifnames[0]);
2517 var networks = L.toArray(this.get('network'));
2518 if ($.inArray(iface.name(), networks) < 0)
2520 networks.push(iface.name());
2521 this.set('network', (networks.length > 1) ? networks : networks[0]);
2527 this.NetworkModel.Interface = Class.extend({
2528 getStatus: function(key)
2530 var s = L.NetworkModel.rpcCache.ifstate;
2532 for (var i = 0; i < s.length; i++)
2533 if (s[i]['interface'] == this.options.name)
2534 return key ? s[i][key] : s[i];
2541 return L.uci.get('network', this.options.name, key);
2544 set: function(key, val)
2546 return L.uci.set('network', this.options.name, key, val);
2551 return this.options.name;
2554 protocol: function()
2556 return (this.get('proto') || 'none');
2561 return (this.getStatus('up') === true);
2564 isVirtual: function()
2566 return (typeof(this.options.sid) != 'string');
2569 getProtocol: function()
2571 var prname = this.get('proto') || 'none';
2572 return L.NetworkModel.protocolHandlers[prname] || L.NetworkModel.protocolHandlers.none;
2575 getUptime: function()
2577 var uptime = this.getStatus('uptime');
2578 return isNaN(uptime) ? 0 : uptime;
2581 getDevice: function(resolveAlias)
2583 if (this.options.l3dev)
2584 return L.NetworkModel.getDevice(this.options.l3dev);
2589 getPhysdev: function()
2591 if (this.options.l2dev)
2592 return L.NetworkModel.getDevice(this.options.l2dev);
2597 getSubdevices: function()
2600 var dev = this.options.l2dev ?
2601 L.NetworkModel.deviceObjects[this.options.l2dev] : undefined;
2603 if (dev && dev.kind == 'bridge' && dev.ports && dev.ports.length)
2604 for (var i = 0; i < dev.ports.length; i++)
2605 rv.push(L.NetworkModel.getDevice(dev.ports[i]));
2610 getIPv4Addrs: function(mask)
2613 var addrs = this.getStatus('ipv4-address');
2616 for (var i = 0; i < addrs.length; i++)
2618 rv.push(addrs[i].address);
2620 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2625 getIPv6Addrs: function(mask)
2630 addrs = this.getStatus('ipv6-address');
2633 for (var i = 0; i < addrs.length; i++)
2635 rv.push(addrs[i].address);
2637 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2639 addrs = this.getStatus('ipv6-prefix-assignment');
2642 for (var i = 0; i < addrs.length; i++)
2644 rv.push('%s1'.format(addrs[i].address));
2646 rv.push('%s1/%d'.format(addrs[i].address, addrs[i].mask));
2651 getDNSAddrs: function()
2654 var addrs = this.getStatus('dns-server');
2657 for (var i = 0; i < addrs.length; i++)
2663 getIPv4DNS: function()
2666 var dns = this.getStatus('dns-server');
2669 for (var i = 0; i < dns.length; i++)
2670 if (dns[i].indexOf(':') == -1)
2676 getIPv6DNS: function()
2679 var dns = this.getStatus('dns-server');
2682 for (var i = 0; i < dns.length; i++)
2683 if (dns[i].indexOf(':') > -1)
2689 getIPv4Gateway: function()
2691 var rt = this.getStatus('route');
2694 for (var i = 0; i < rt.length; i++)
2695 if (rt[i].target == '0.0.0.0' && rt[i].mask == 0)
2696 return rt[i].nexthop;
2701 getIPv6Gateway: function()
2703 var rt = this.getStatus('route');
2706 for (var i = 0; i < rt.length; i++)
2707 if (rt[i].target == '::' && rt[i].mask == 0)
2708 return rt[i].nexthop;
2713 getStatistics: function()
2715 var dev = this.getDevice() || new L.NetworkModel.Device({});
2716 return dev.getStatistics();
2719 getTrafficHistory: function()
2721 var dev = this.getDevice() || new L.NetworkModel.Device({});
2722 return dev.getTrafficHistory();
2725 renderBadge: function()
2727 var badge = $('<span />')
2729 .text('%s: '.format(this.name()));
2731 var dev = this.getDevice();
2732 var subdevs = this.getSubdevices();
2735 for (var j = 0; j < subdevs.length; j++)
2736 badge.append($('<img />')
2737 .attr('src', subdevs[j].icon())
2738 .attr('title', '%s (%s)'.format(subdevs[j].description(), subdevs[j].name() || '?')));
2740 badge.append($('<img />')
2741 .attr('src', dev.icon())
2742 .attr('title', '%s (%s)'.format(dev.description(), dev.name() || '?')));
2744 badge.append($('<em />').text(L.tr('(No devices attached)')));
2749 setDevices: function(devs)
2751 var dev = this.getPhysdev();
2753 var changed = false;
2755 if (dev && dev.isBridge())
2756 old_devs = this.getSubdevices();
2760 if (old_devs.length != devs.length)
2763 for (var i = 0; i < old_devs.length; i++)
2767 if (dev instanceof L.NetworkModel.Device)
2770 if (!dev || old_devs[i].name() != dev)
2779 for (var i = 0; i < old_devs.length; i++)
2780 old_devs[i].removeFromInterface(this);
2782 for (var i = 0; i < devs.length; i++)
2786 if (!(dev instanceof L.NetworkModel.Device))
2787 dev = L.NetworkModel.getDevice(dev);
2790 dev.attachToInterface(this);
2795 changeProtocol: function(proto)
2797 var pr = L.NetworkModel.protocolHandlers[proto];
2802 for (var opt in (this.get() || { }))
2810 this.set(opt, undefined);
2818 this.set(opt, pr.protocol);
2822 this.set(opt, undefined);
2828 createForm: function(mapwidget)
2831 var proto = self.getProtocol();
2832 var device = self.getDevice();
2835 mapwidget = L.cbi.Map;
2837 var map = new mapwidget('network', {
2838 caption: L.tr('Configure "%s"').format(self.name())
2841 var section = map.section(L.cbi.SingleSection, self.name(), {
2847 caption: L.tr('General Settings')
2852 caption: L.tr('Advanced Settings')
2857 caption: L.tr('IPv6')
2862 caption: L.tr('Physical Settings')
2866 section.taboption('general', L.cbi.CheckboxValue, 'auto', {
2867 caption: L.tr('Start on boot'),
2872 var pr = section.taboption('general', L.cbi.ListValue, 'proto', {
2873 caption: L.tr('Protocol')
2876 pr.ucivalue = function(sid) {
2877 return self.get('proto') || 'none';
2880 var ok = section.taboption('general', L.cbi.ButtonValue, '_confirm', {
2881 caption: L.tr('Really switch?'),
2882 description: L.tr('Changing the protocol will clear all configuration for this interface!'),
2883 text: L.tr('Change protocol')
2886 ok.on('click', function(ev) {
2887 self.changeProtocol(pr.formvalue(ev.data.sid));
2888 self.createForm(mapwidget).show();
2891 var protos = L.NetworkModel.getProtocols();
2893 for (var i = 0; i < protos.length; i++)
2894 pr.value(protos[i].name, protos[i].description);
2896 proto.populateForm(section, self);
2900 var br = section.taboption('physical', L.cbi.CheckboxValue, 'type', {
2901 caption: L.tr('Network bridge'),
2902 description: L.tr('Merges multiple devices into one logical bridge'),
2909 section.taboption('physical', L.cbi.DeviceList, '__iface_multi', {
2910 caption: L.tr('Devices'),
2913 }).depends('type', true);
2915 section.taboption('physical', L.cbi.DeviceList, '__iface_single', {
2916 caption: L.tr('Device'),
2919 }).depends('type', false);
2921 var mac = section.taboption('physical', L.cbi.InputValue, 'macaddr', {
2922 caption: L.tr('Override MAC'),
2924 placeholder: device ? device.getMACAddress() : undefined,
2928 mac.ucivalue = function(sid)
2931 return device.get('macaddr');
2933 return this.callSuper('ucivalue', sid);
2936 mac.save = function(sid)
2938 if (!this.changed(sid))
2942 device.set('macaddr', this.formvalue(sid));
2944 this.callSuper('set', sid);
2950 section.taboption('physical', L.cbi.InputValue, 'mtu', {
2951 caption: L.tr('Override MTU'),
2953 placeholder: device ? device.getMTU() : undefined,
2954 datatype: 'range(1, 9000)'
2957 section.taboption('physical', L.cbi.InputValue, 'metric', {
2958 caption: L.tr('Override Metric'),
2961 datatype: 'uinteger'
2964 for (var field in section.fields)
2972 for (var i = 0; i < protos.length; i++)
2973 if (protos[i].name != (this.get('proto') || 'none'))
2974 section.fields[field].depends('proto', protos[i].name);
2978 section.fields[field].depends('proto', this.get('proto') || 'none', true);
2987 this.NetworkModel.Protocol = this.NetworkModel.Interface.extend({
2988 description: '__unknown__',
2992 populateForm: function(section, iface)
2999 getSystemInfo: L.rpc.declare({
3005 getBoardInfo: L.rpc.declare({
3011 getDiskInfo: L.rpc.declare({
3012 object: 'luci2.system',
3017 getInfo: function(cb)
3021 this.getSystemInfo();
3022 this.getBoardInfo();
3025 return L.rpc.flush().then(function(info) {
3028 $.extend(rv, info[0]);
3029 $.extend(rv, info[1]);
3030 $.extend(rv, info[2]);
3037 initList: L.rpc.declare({
3038 object: 'luci2.system',
3039 method: 'init_list',
3040 expect: { initscripts: [ ] },
3041 filter: function(data) {
3042 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
3047 initEnabled: function(init, cb)
3049 return this.initList().then(function(list) {
3050 for (var i = 0; i < list.length; i++)
3051 if (list[i].name == init)
3052 return !!list[i].enabled;
3058 initRun: L.rpc.declare({
3059 object: 'luci2.system',
3060 method: 'init_action',
3061 params: [ 'name', 'action' ],
3062 filter: function(data) {
3067 initStart: function(init, cb) { return L.system.initRun(init, 'start', cb) },
3068 initStop: function(init, cb) { return L.system.initRun(init, 'stop', cb) },
3069 initRestart: function(init, cb) { return L.system.initRun(init, 'restart', cb) },
3070 initReload: function(init, cb) { return L.system.initRun(init, 'reload', cb) },
3071 initEnable: function(init, cb) { return L.system.initRun(init, 'enable', cb) },
3072 initDisable: function(init, cb) { return L.system.initRun(init, 'disable', cb) },
3075 performReboot: L.rpc.declare({
3076 object: 'luci2.system',
3083 login: L.rpc.declare({
3086 params: [ 'username', 'password' ],
3090 access: L.rpc.declare({
3093 params: [ 'scope', 'object', 'function' ],
3094 expect: { access: false }
3099 return L.session.access('ubus', 'session', 'access');
3102 startHeartbeat: function()
3104 this._hearbeatInterval = window.setInterval(function() {
3105 L.session.isAlive().then(function(alive) {
3108 L.session.stopHeartbeat();
3113 }, L.globals.timeout * 2);
3116 stopHeartbeat: function()
3118 if (typeof(this._hearbeatInterval) != 'undefined')
3120 window.clearInterval(this._hearbeatInterval);
3121 delete this._hearbeatInterval;
3128 callAccess: L.rpc.declare({
3134 callAccessCallback: function(acls)
3136 L.session.aclCache = acls;
3139 updateACLs: function()
3141 return L.session.callAccess()
3142 .then(L.session.callAccessCallback);
3145 hasACL: function(scope, object, func)
3147 var acls = L.session.aclCache;
3149 if (typeof(func) == 'undefined')
3150 return (acls && acls[scope] && acls[scope][object]);
3152 if (acls && acls[scope] && acls[scope][object])
3153 for (var i = 0; i < acls[scope][object].length; i++)
3154 if (acls[scope][object][i] == func)
3163 saveScrollTop: function()
3165 this._scroll_top = $(document).scrollTop();
3168 restoreScrollTop: function()
3170 if (typeof(this._scroll_top) == 'undefined')
3173 $(document).scrollTop(this._scroll_top);
3175 delete this._scroll_top;
3178 loading: function(enable)
3180 var win = $(window);
3181 var body = $('body');
3183 var state = L.ui._loading || (L.ui._loading = {
3185 .css('z-index', 2000)
3186 .addClass('modal fade')
3187 .append($('<div />')
3188 .addClass('modal-dialog')
3189 .append($('<div />')
3190 .addClass('modal-content luci2-modal-loader')
3191 .append($('<div />')
3192 .addClass('modal-body')
3193 .text(L.tr('Loading data…')))))
3201 state.modal.modal(enable ? 'show' : 'hide');
3204 dialog: function(title, content, options)
3206 var win = $(window);
3207 var body = $('body');
3209 var state = L.ui._dialog || (L.ui._dialog = {
3210 dialog: $('<div />')
3211 .addClass('modal fade')
3212 .append($('<div />')
3213 .addClass('modal-dialog')
3214 .append($('<div />')
3215 .addClass('modal-content')
3216 .append($('<div />')
3217 .addClass('modal-header')
3219 .addClass('modal-title'))
3220 .append($('<div />')
3221 .addClass('modal-body'))
3222 .append($('<div />')
3223 .addClass('modal-footer')
3224 .append(L.ui.button(L.tr('Close'), 'primary')
3226 $(this).parents('div.modal').modal('hide');
3231 if (typeof(options) != 'object')
3234 if (title === false)
3236 state.dialog.modal('hide');
3238 return state.dialog;
3241 var cnt = state.dialog.children().children().children('div.modal-body');
3242 var ftr = state.dialog.children().children().children('div.modal-footer');
3246 if (options.style == 'confirm')
3248 ftr.append(L.ui.button(L.tr('Ok'), 'primary')
3249 .click(options.confirm || function() { L.ui.dialog(false) }));
3251 ftr.append(L.ui.button(L.tr('Cancel'), 'default')
3252 .click(options.cancel || function() { L.ui.dialog(false) }));
3254 else if (options.style == 'close')
3256 ftr.append(L.ui.button(L.tr('Close'), 'primary')
3257 .click(options.close || function() { L.ui.dialog(false) }));
3259 else if (options.style == 'wait')
3261 ftr.append(L.ui.button(L.tr('Close'), 'primary')
3262 .attr('disabled', true));
3267 state.dialog.addClass('wide');
3271 state.dialog.removeClass('wide');
3274 state.dialog.find('h4:first').text(title);
3275 state.dialog.modal('show');
3277 cnt.empty().append(content);
3279 return state.dialog;
3282 upload: function(title, content, options)
3284 var state = L.ui._upload || (L.ui._upload = {
3286 .attr('method', 'post')
3287 .attr('action', '/cgi-bin/luci-upload')
3288 .attr('enctype', 'multipart/form-data')
3289 .attr('target', 'cbi-fileupload-frame')
3291 .append($('<input />')
3292 .attr('type', 'hidden')
3293 .attr('name', 'sessionid'))
3294 .append($('<input />')
3295 .attr('type', 'hidden')
3296 .attr('name', 'filename'))
3297 .append($('<input />')
3298 .attr('type', 'file')
3299 .attr('name', 'filedata')
3300 .addClass('cbi-input-file'))
3301 .append($('<div />')
3302 .css('width', '100%')
3303 .addClass('progress progress-striped active')
3304 .append($('<div />')
3305 .addClass('progress-bar')
3306 .css('width', '100%')))
3307 .append($('<iframe />')
3308 .addClass('pull-right')
3309 .attr('name', 'cbi-fileupload-frame')
3310 .css('width', '1px')
3311 .css('height', '1px')
3312 .css('visibility', 'hidden')),
3314 finish_cb: function(ev) {
3315 $(this).off('load');
3317 var body = (this.contentDocument || this.contentWindow.document).body;
3318 if (body.firstChild.tagName.toLowerCase() == 'pre')
3319 body = body.firstChild;
3323 json = $.parseJSON(body.innerHTML);
3326 message: L.tr('Invalid server response received'),
3327 error: [ -1, L.tr('Invalid data') ]
3333 L.ui.dialog(L.tr('File upload'), [
3334 $('<p />').text(L.tr('The file upload failed with the server response below:')),
3335 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
3336 $('<p />').text(L.tr('In case of network problems try uploading the file again.'))
3337 ], { style: 'close' });
3339 else if (typeof(state.success_cb) == 'function')
3341 state.success_cb(json);
3345 confirm_cb: function() {
3346 var f = state.form.find('.cbi-input-file');
3347 var b = state.form.find('.progress');
3348 var p = state.form.find('p');
3353 state.form.find('iframe').on('load', state.finish_cb);
3354 state.form.submit();
3358 p.text(L.tr('File upload in progress …'));
3360 state.form.parent().parent().find('button').prop('disabled', true);
3364 state.form.find('.progress').hide();
3365 state.form.find('.cbi-input-file').val('').show();
3366 state.form.find('p').text(content || L.tr('Select the file to upload and press "%s" to proceed.').format(L.tr('Ok')));
3368 state.form.find('[name=sessionid]').val(L.globals.sid);
3369 state.form.find('[name=filename]').val(options.filename);
3371 state.success_cb = options.success;
3373 L.ui.dialog(title || L.tr('File upload'), state.form, {
3375 confirm: state.confirm_cb
3379 reconnect: function()
3381 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3382 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
3383 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
3385 var interval, timeout;
3388 L.tr('Waiting for device'), [
3389 $('<p />').text(L.tr('Please stand by while the device is reconfiguring …')),
3391 .css('width', '100%')
3392 .addClass('progressbar')
3393 .addClass('intermediate')
3394 .append($('<div />')
3395 .css('width', '100%'))
3396 ], { style: 'wait' }
3399 for (var i = 0; i < protocols.length; i++)
3400 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
3402 //L.network.getNetworkStatus(function(s) {
3403 // for (var i = 0; i < protocols.length; i++)
3405 // for (var j = 0; j < s.length; j++)
3407 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3408 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3410 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3411 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3414 //}).then(function() {
3415 images.on('load', function() {
3416 var url = this.getAttribute('url');
3417 L.session.isAlive().then(function(access) {
3420 window.clearTimeout(timeout);
3421 window.clearInterval(interval);
3427 location.href = url;
3432 interval = window.setInterval(function() {
3433 images.each(function() {
3434 this.setAttribute('src', this.getAttribute('url') + L.globals.resource + '/icons/loading.gif?r=' + Math.random());
3438 timeout = window.setTimeout(function() {
3439 window.clearInterval(interval);
3443 L.tr('Device not responding'),
3444 L.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3451 login: function(invalid)
3453 var state = L.ui._login || (L.ui._login = {
3456 .attr('method', 'post')
3458 .addClass('alert-message')
3459 .text(L.tr('Wrong username or password given!')))
3461 .append($('<label />')
3462 .text(L.tr('Username'))
3463 .append($('<br />'))
3464 .append($('<input />')
3465 .attr('type', 'text')
3466 .attr('name', 'username')
3467 .attr('value', 'root')
3468 .addClass('form-control')
3469 .keypress(function(ev) {
3470 if (ev.which == 10 || ev.which == 13)
3474 .append($('<label />')
3475 .text(L.tr('Password'))
3476 .append($('<br />'))
3477 .append($('<input />')
3478 .attr('type', 'password')
3479 .attr('name', 'password')
3480 .addClass('form-control')
3481 .keypress(function(ev) {
3482 if (ev.which == 10 || ev.which == 13)
3486 .text(L.tr('Enter your username and password above, then click "%s" to proceed.').format(L.tr('Ok')))),
3488 response_cb: function(response) {
3489 if (!response.ubus_rpc_session)
3495 L.globals.sid = response.ubus_rpc_session;
3496 L.setHash('id', L.globals.sid);
3497 L.session.startHeartbeat();
3499 state.deferred.resolve();
3503 confirm_cb: function() {
3504 var u = state.form.find('[name=username]').val();
3505 var p = state.form.find('[name=password]').val();
3511 L.tr('Logging in'), [
3512 $('<p />').text(L.tr('Log in in progress …')),
3514 .css('width', '100%')
3515 .addClass('progressbar')
3516 .addClass('intermediate')
3517 .append($('<div />')
3518 .css('width', '100%'))
3519 ], { style: 'wait' }
3522 L.globals.sid = '00000000000000000000000000000000';
3523 L.session.login(u, p).then(state.response_cb);
3527 if (!state.deferred || state.deferred.state() != 'pending')
3528 state.deferred = $.Deferred();
3530 /* try to find sid from hash */
3531 var sid = L.getHash('id');
3532 if (sid && sid.match(/^[a-f0-9]{32}$/))
3534 L.globals.sid = sid;
3535 L.session.isAlive().then(function(access) {
3538 L.session.startHeartbeat();
3539 state.deferred.resolve();
3543 L.setHash('id', undefined);
3548 return state.deferred;
3552 state.form.find('.alert-message').show();
3554 state.form.find('.alert-message').hide();
3556 L.ui.dialog(L.tr('Authorization Required'), state.form, {
3558 confirm: state.confirm_cb
3561 state.form.find('[name=password]').focus();
3563 return state.deferred;
3566 cryptPassword: L.rpc.declare({
3570 expect: { crypt: '' }
3574 mergeACLScope: function(acl_scope, scope)
3576 if ($.isArray(scope))
3578 for (var i = 0; i < scope.length; i++)
3579 acl_scope[scope[i]] = true;
3581 else if ($.isPlainObject(scope))
3583 for (var object_name in scope)
3585 if (!$.isArray(scope[object_name]))
3588 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
3590 for (var i = 0; i < scope[object_name].length; i++)
3591 acl_object[scope[object_name][i]] = true;
3596 mergeACLPermission: function(acl_perm, perm)
3598 if ($.isPlainObject(perm))
3600 for (var scope_name in perm)
3602 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
3603 L.ui.mergeACLScope(acl_scope, perm[scope_name]);
3608 mergeACLGroup: function(acl_group, group)
3610 if ($.isPlainObject(group))
3612 if (!acl_group.description)
3613 acl_group.description = group.description;
3617 var acl_perm = acl_group.read || (acl_group.read = { });
3618 L.ui.mergeACLPermission(acl_perm, group.read);
3623 var acl_perm = acl_group.write || (acl_group.write = { });
3624 L.ui.mergeACLPermission(acl_perm, group.write);
3629 callACLsCallback: function(trees)
3633 for (var i = 0; i < trees.length; i++)
3635 if (!$.isPlainObject(trees[i]))
3638 for (var group_name in trees[i])
3640 var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
3641 L.ui.mergeACLGroup(acl_group, trees[i][group_name]);
3648 callACLs: L.rpc.declare({
3651 expect: { acls: [ ] }
3654 getAvailableACLs: function()
3656 return this.callACLs().then(this.callACLsCallback);
3659 renderChangeIndicator: function()
3662 .addClass('nav navbar-nav navbar-right')
3665 .attr('id', 'changes')
3667 .append($('<span />')
3668 .addClass('label label-info'))));
3671 callMenuCallback: function(entries)
3673 L.globals.mainMenu = new L.ui.menu();
3674 L.globals.mainMenu.entries(entries);
3678 .append(L.globals.mainMenu.render(0, 1))
3679 .append(L.ui.renderChangeIndicator());
3682 callMenu: L.rpc.declare({
3685 expect: { menu: { } }
3688 renderMainMenu: function()
3690 return this.callMenu().then(this.callMenuCallback);
3693 renderViewMenu: function()
3697 .append(L.globals.mainMenu.render(2, 900));
3700 renderView: function()
3702 var node = arguments[0];
3703 var name = node.view.split(/\//).join('.');
3704 var cname = L.toClassName(name);
3705 var views = L.views || (L.views = { });
3708 for (var i = 1; i < arguments.length; i++)
3709 args.push(arguments[i]);
3711 if (L.globals.currentView)
3712 L.globals.currentView.finish();
3714 L.ui.renderViewMenu();
3715 L.setHash('view', node.view);
3717 if (views[cname] instanceof L.ui.view)
3719 L.globals.currentView = views[cname];
3720 return views[cname].render.apply(views[cname], args);
3723 var url = L.globals.resource + '/view/' + name + '.js';
3725 return $.ajax(url, {
3729 }).then(function(data) {
3731 var viewConstructorSource = (
3732 '(function(L, $) { ' +
3736 ).format(data, url);
3738 var viewConstructor = eval(viewConstructorSource);
3740 views[cname] = new viewConstructor({
3742 acls: node.write || { }
3745 L.globals.currentView = views[cname];
3746 return views[cname].render.apply(views[cname], args);
3749 alert('Unable to instantiate view "%s": %s'.format(url, e));
3752 return $.Deferred().resolve();
3756 changeView: function()
3758 var name = L.getHash('view');
3759 var node = L.globals.defaultNode;
3761 if (name && L.globals.mainMenu)
3762 node = L.globals.mainMenu.getNode(name);
3767 L.ui.renderView(node).then(function() {
3768 L.ui.loading(false);
3773 updateHostname: function()
3775 return L.system.getBoardInfo().then(function(info) {
3777 $('#hostname').text(info.hostname);
3781 updateChanges: function()
3783 return L.uci.changes().then(function(changes) {
3787 for (var config in changes)
3791 for (var i = 0; i < changes[config].length; i++)
3793 var c = changes[config][i];
3798 log.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
3803 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
3805 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
3810 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
3812 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
3816 log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
3820 log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
3824 log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
3829 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
3831 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
3836 html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
3837 n += changes[config].length;
3842 .click(function(ev) {
3843 L.ui.dialog(L.tr('Staged configuration changes'), html, {
3845 confirm: function() {
3847 function(code) { alert('Success with code ' + code); },
3848 function(code) { alert('Error with code ' + code); }
3852 ev.preventDefault();
3856 .text(L.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n));
3858 $('#changes').children('span').hide();
3867 L.session.updateACLs(),
3868 L.ui.updateHostname(),
3869 L.ui.updateChanges(),
3870 L.ui.renderMainMenu(),
3871 L.NetworkModel.init()
3873 L.ui.renderView(L.globals.defaultNode).then(function() {
3874 L.ui.loading(false);
3877 $(window).on('hashchange', function() {
3883 button: function(label, style, title)
3885 style = style || 'default';
3887 return $('<button />')
3888 .attr('type', 'button')
3889 .attr('title', title ? title : '')
3890 .addClass('btn btn-' + style)
3895 this.ui.AbstractWidget = Class.extend({
3896 i18n: function(text) {
3901 var key = arguments[0];
3904 for (var i = 1; i < arguments.length; i++)
3905 args.push(arguments[i]);
3907 switch (typeof(this.options[key]))
3913 return this.options[key].apply(this, args);
3916 return ''.format.apply('' + this.options[key], args);
3920 toString: function() {
3921 return $('<div />').append(this.render()).html();
3924 insertInto: function(id) {
3925 return $(id).empty().append(this.render());
3928 appendTo: function(id) {
3929 return $(id).append(this.render());
3932 on: function(evname, evfunc)
3934 var evnames = L.toArray(evname);
3939 for (var i = 0; i < evnames.length; i++)
3940 this.events[evnames[i]] = evfunc;
3945 trigger: function(evname, evdata)
3949 var evnames = L.toArray(evname);
3951 for (var i = 0; i < evnames.length; i++)
3952 if (this.events[evnames[i]])
3953 this.events[evnames[i]].call(this, evdata);
3960 this.ui.view = this.ui.AbstractWidget.extend({
3961 _fetch_template: function()
3963 return $.ajax(L.globals.resource + '/template/' + this.options.name + '.htm', {
3967 success: function(data) {
3968 data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
3969 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
3979 return L.globals[p2] || '';
3982 return '(?' + match + ')';
3986 $('#maincontent').append(data);
3993 throw "Not implemented";
3998 var container = $('#maincontent');
4003 container.append($('<h2 />').append(this.title));
4005 if (this.description)
4006 container.append($('<p />').append(this.description));
4011 for (var i = 0; i < arguments.length; i++)
4012 args.push(arguments[i]);
4014 return this._fetch_template().then(function() {
4015 return L.deferrable(self.execute.apply(self, args));
4019 repeat: function(func, interval)
4023 if (!self._timeouts)
4024 self._timeouts = [ ];
4026 var index = self._timeouts.length;
4028 if (typeof(interval) != 'number')
4031 var setTimer, runTimer;
4033 setTimer = function() {
4035 self._timeouts[index] = window.setTimeout(runTimer, interval);
4038 runTimer = function() {
4039 L.deferrable(func.call(self)).then(setTimer, setTimer);
4047 if ($.isArray(this._timeouts))
4049 for (var i = 0; i < this._timeouts.length; i++)
4050 window.clearTimeout(this._timeouts[i]);
4052 delete this._timeouts;
4057 this.ui.menu = this.ui.AbstractWidget.extend({
4062 entries: function(entries)
4064 for (var entry in entries)
4066 var path = entry.split(/\//);
4067 var node = this._nodes;
4069 for (i = 0; i < path.length; i++)
4074 if (!node.childs[path[i]])
4075 node.childs[path[i]] = { };
4077 node = node.childs[path[i]];
4080 $.extend(node, entries[entry]);
4084 sortNodesCallback: function(a, b)
4086 var x = a.index || 0;
4087 var y = b.index || 0;
4091 firstChildView: function(node)
4097 for (var child in (node.childs || { }))
4098 nodes.push(node.childs[child]);
4100 nodes.sort(this.sortNodesCallback);
4102 for (var i = 0; i < nodes.length; i++)
4104 var child = this.firstChildView(nodes[i]);
4107 for (var key in child)
4108 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
4109 node[key] = child[key];
4118 handleClick: function(ev)
4120 L.setHash('view', ev.data);
4122 ev.preventDefault();
4126 renderNodes: function(childs, level, min, max)
4129 for (var node in childs)
4131 var child = this.firstChildView(childs[node]);
4133 nodes.push(childs[node]);
4136 nodes.sort(this.sortNodesCallback);
4138 var list = $('<ul />');
4141 list.addClass('nav').addClass('navbar-nav');
4142 else if (level == 1)
4143 list.addClass('dropdown-menu').addClass('navbar-inverse');
4145 for (var i = 0; i < nodes.length; i++)
4147 if (!L.globals.defaultNode)
4149 var v = L.getHash('view');
4150 if (!v || v == nodes[i].view)
4151 L.globals.defaultNode = nodes[i];
4154 var item = $('<li />')
4157 .text(L.tr(nodes[i].title)))
4160 if (nodes[i].childs && level < max)
4162 item.addClass('dropdown');
4165 .addClass('dropdown-toggle')
4166 .attr('data-toggle', 'dropdown')
4167 .append('<b class="caret"></b>');
4169 item.append(this.renderNodes(nodes[i].childs, level + 1));
4173 item.find('a').click(nodes[i].view, this.handleClick);
4180 render: function(min, max)
4182 var top = min ? this.getNode(L.globals.defaultNode.view, min) : this._nodes;
4183 return this.renderNodes(top.childs, 0, min, max);
4186 getNode: function(path, max)
4188 var p = path.split(/\//);
4189 var n = this._nodes;
4191 if (typeof(max) == 'undefined')
4194 for (var i = 0; i < max; i++)
4196 if (!n.childs[p[i]])
4206 this.ui.table = this.ui.AbstractWidget.extend({
4212 row: function(values)
4214 if ($.isArray(values))
4216 this._rows.push(values);
4218 else if ($.isPlainObject(values))
4221 for (var i = 0; i < this.options.columns.length; i++)
4223 var col = this.options.columns[i];
4225 if (typeof col.key == 'string')
4226 v.push(values[col.key]);
4234 rows: function(rows)
4236 for (var i = 0; i < rows.length; i++)
4240 render: function(id)
4242 var fieldset = document.createElement('fieldset');
4243 fieldset.className = 'cbi-section';
4245 if (this.options.caption)
4247 var legend = document.createElement('legend');
4248 $(legend).append(this.options.caption);
4249 fieldset.appendChild(legend);
4252 var table = document.createElement('table');
4253 table.className = 'table table-condensed table-hover';
4255 var has_caption = false;
4256 var has_description = false;
4258 for (var i = 0; i < this.options.columns.length; i++)
4259 if (this.options.columns[i].caption)
4264 else if (this.options.columns[i].description)
4266 has_description = true;
4272 var tr = table.insertRow(-1);
4273 tr.className = 'cbi-section-table-titles';
4275 for (var i = 0; i < this.options.columns.length; i++)
4277 var col = this.options.columns[i];
4278 var th = document.createElement('th');
4279 th.className = 'cbi-section-table-cell';
4284 th.style.width = col.width;
4287 th.style.textAlign = col.align;
4290 $(th).append(col.caption);
4294 if (has_description)
4296 var tr = table.insertRow(-1);
4297 tr.className = 'cbi-section-table-descr';
4299 for (var i = 0; i < this.options.columns.length; i++)
4301 var col = this.options.columns[i];
4302 var th = document.createElement('th');
4303 th.className = 'cbi-section-table-cell';
4308 th.style.width = col.width;
4311 th.style.textAlign = col.align;
4313 if (col.description)
4314 $(th).append(col.description);
4318 if (this._rows.length == 0)
4320 if (this.options.placeholder)
4322 var tr = table.insertRow(-1);
4323 var td = tr.insertCell(-1);
4324 td.className = 'cbi-section-table-cell';
4326 td.colSpan = this.options.columns.length;
4327 $(td).append(this.options.placeholder);
4332 for (var i = 0; i < this._rows.length; i++)
4334 var tr = table.insertRow(-1);
4336 for (var j = 0; j < this.options.columns.length; j++)
4338 var col = this.options.columns[j];
4339 var td = tr.insertCell(-1);
4341 var val = this._rows[i][j];
4343 if (typeof(val) == 'undefined')
4344 val = col.placeholder;
4346 if (typeof(val) == 'undefined')
4350 td.style.width = col.width;
4353 td.style.textAlign = col.align;
4355 if (typeof col.format == 'string')
4356 $(td).append(col.format.format(val));
4357 else if (typeof col.format == 'function')
4358 $(td).append(col.format(val, i));
4366 fieldset.appendChild(table);
4372 this.ui.progress = this.ui.AbstractWidget.extend({
4375 var vn = parseInt(this.options.value) || 0;
4376 var mn = parseInt(this.options.max) || 100;
4377 var pc = Math.floor((100 / mn) * vn);
4381 if (typeof(this.options.format) == 'string')
4382 text = this.options.format.format(this.options.value, this.options.max, pc);
4383 else if (typeof(this.options.format) == 'function')
4384 text = this.options.format(pc);
4386 text = '%.2f%%'.format(pc);
4389 .addClass('progress')
4390 .append($('<div />')
4391 .addClass('progress-bar')
4392 .addClass('progress-bar-info')
4393 .css('width', pc + '%'))
4394 .append($('<small />')
4399 this.ui.devicebadge = this.ui.AbstractWidget.extend({
4402 var l2dev = this.options.l2_device || this.options.device;
4403 var l3dev = this.options.l3_device;
4404 var dev = l3dev || l2dev || '?';
4406 var span = document.createElement('span');
4407 span.className = 'badge';
4409 if (typeof(this.options.signal) == 'number' ||
4410 typeof(this.options.noise) == 'number')
4413 if (typeof(this.options.signal) != 'undefined' &&
4414 typeof(this.options.noise) != 'undefined')
4416 var q = (-1 * (this.options.noise - this.options.signal)) / 5;
4429 span.appendChild(document.createElement('img'));
4430 span.lastChild.src = L.globals.resource + '/icons/signal-' + r + '.png';
4433 span.title = L.tr('No signal');
4435 span.title = '%s: %d %s / %s: %d %s'.format(
4436 L.tr('Signal'), this.options.signal, L.tr('dBm'),
4437 L.tr('Noise'), this.options.noise, L.tr('dBm')
4442 var type = 'ethernet';
4443 var desc = L.tr('Ethernet device');
4448 desc = L.tr('Tunnel interface');
4450 else if (dev.indexOf('br-') == 0)
4453 desc = L.tr('Bridge');
4455 else if (dev.indexOf('.') > 0)
4458 desc = L.tr('VLAN interface');
4460 else if (dev.indexOf('wlan') == 0 ||
4461 dev.indexOf('ath') == 0 ||
4462 dev.indexOf('wl') == 0)
4465 desc = L.tr('Wireless Network');
4468 span.appendChild(document.createElement('img'));
4469 span.lastChild.src = L.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
4473 $(span).append(' ');
4474 $(span).append(dev);
4480 var type = function(f, l)
4490 L.cbi.validation.message = L.tr(msg);
4493 compile: function(code)
4498 var types = L.cbi.validation.types;
4503 for (var i = 0; i < code.length; i++)
4511 switch (code.charCodeAt(i))
4523 var label = code.substring(pos, i);
4524 label = label.replace(/\\(.)/g, '$1');
4525 label = label.replace(/^[ \t]+/g, '');
4526 label = label.replace(/[ \t]+$/g, '');
4528 if (label && !isNaN(label))
4530 stack.push(parseFloat(label));
4532 else if (label.match(/^(['"]).*\1$/))
4534 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
4536 else if (typeof types[label] == 'function')
4538 stack.push(types[label]);
4543 throw "Syntax error, unhandled token '"+label+"'";
4548 depth += (code.charCodeAt(i) == 40);
4554 if (typeof stack[stack.length-2] != 'function')
4555 throw "Syntax error, argument list follows non-function";
4557 stack[stack.length-1] =
4558 L.cbi.validation.compile(code.substring(pos, i));
4571 var validation = this.cbi.validation;
4573 validation.types = {
4574 'integer': function()
4576 if (this.match(/^-?[0-9]+$/) != null)
4579 validation.i18n('Must be a valid integer');
4583 'uinteger': function()
4585 if (validation.types['integer'].apply(this) && (this >= 0))
4588 validation.i18n('Must be a positive integer');
4594 if (!isNaN(parseFloat(this)))
4597 validation.i18n('Must be a valid number');
4601 'ufloat': function()
4603 if (validation.types['float'].apply(this) && (this >= 0))
4606 validation.i18n('Must be a positive number');
4610 'ipaddr': function()
4612 if (L.parseIPv4(this) || L.parseIPv6(this))
4615 validation.i18n('Must be a valid IP address');
4619 'ip4addr': function()
4621 if (L.parseIPv4(this))
4624 validation.i18n('Must be a valid IPv4 address');
4628 'ip6addr': function()
4630 if (L.parseIPv6(this))
4633 validation.i18n('Must be a valid IPv6 address');
4637 'netmask4': function()
4639 if (L.isNetmask(L.parseIPv4(this)))
4642 validation.i18n('Must be a valid IPv4 netmask');
4646 'netmask6': function()
4648 if (L.isNetmask(L.parseIPv6(this)))
4651 validation.i18n('Must be a valid IPv6 netmask6');
4657 if (this.match(/^([0-9.]+)\/(\d{1,2})$/))
4658 if (RegExp.$2 <= 32 && L.parseIPv4(RegExp.$1))
4661 validation.i18n('Must be a valid IPv4 prefix');
4667 if (this.match(/^([a-fA-F0-9:.]+)\/(\d{1,3})$/))
4668 if (RegExp.$2 <= 128 && L.parseIPv6(RegExp.$1))
4671 validation.i18n('Must be a valid IPv6 prefix');
4675 'ipmask4': function()
4677 if (this.match(/^([0-9.]+)\/([0-9.]+)$/))
4679 var addr = RegExp.$1, mask = RegExp.$2;
4680 if (L.parseIPv4(addr) && L.isNetmask(L.parseIPv4(mask)))
4684 validation.i18n('Must be a valid IPv4 address/netmask pair');
4688 'ipmask6': function()
4690 if (this.match(/^([a-fA-F0-9:.]+)\/([a-fA-F0-9:.]+)$/))
4692 var addr = RegExp.$1, mask = RegExp.$2;
4693 if (L.parseIPv6(addr) && L.isNetmask(L.parseIPv6(mask)))
4697 validation.i18n('Must be a valid IPv6 address/netmask pair');
4703 if (validation.types['integer'].apply(this) &&
4704 (this >= 0) && (this <= 65535))
4707 validation.i18n('Must be a valid port number');
4711 'portrange': function()
4713 if (this.match(/^(\d+)-(\d+)$/))
4718 if (validation.types['port'].apply(p1) &&
4719 validation.types['port'].apply(p2) &&
4720 (parseInt(p1) <= parseInt(p2)))
4723 else if (validation.types['port'].apply(this))
4728 validation.i18n('Must be a valid port range');
4732 'macaddr': function()
4734 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4737 validation.i18n('Must be a valid MAC address');
4743 if (validation.types['hostname'].apply(this) ||
4744 validation.types['ipaddr'].apply(this))
4747 validation.i18n('Must be a valid hostname or IP address');
4751 'hostname': function()
4753 if ((this.length <= 253) &&
4754 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4755 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4756 this.match(/[^0-9.]/)))))
4759 validation.i18n('Must be a valid host name');
4763 'network': function()
4765 if (validation.types['uciname'].apply(this) ||
4766 validation.types['host'].apply(this))
4769 validation.i18n('Must be a valid network name');
4773 'wpakey': function()
4777 if ((v.length == 64)
4778 ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
4779 : ((v.length >= 8) && (v.length <= 63)))
4782 validation.i18n('Must be a valid WPA key');
4786 'wepkey': function()
4790 if (v.substr(0,2) == 's:')
4793 if (((v.length == 10) || (v.length == 26))
4794 ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
4795 : ((v.length == 5) || (v.length == 13)))
4798 validation.i18n('Must be a valid WEP key');
4802 'uciname': function()
4804 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4807 validation.i18n('Must be a valid UCI identifier');
4811 'range': function(min, max)
4813 var val = parseFloat(this);
4815 if (validation.types['integer'].apply(this) &&
4816 !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
4819 validation.i18n('Must be a number between %d and %d');
4823 'min': function(min)
4825 var val = parseFloat(this);
4827 if (validation.types['integer'].apply(this) &&
4828 !isNaN(min) && !isNaN(val) && (val >= min))
4831 validation.i18n('Must be a number greater or equal to %d');
4835 'max': function(max)
4837 var val = parseFloat(this);
4839 if (validation.types['integer'].apply(this) &&
4840 !isNaN(max) && !isNaN(val) && (val <= max))
4843 validation.i18n('Must be a number lower or equal to %d');
4847 'rangelength': function(min, max)
4849 var val = '' + this;
4851 if (!isNaN(min) && !isNaN(max) &&
4852 (val.length >= min) && (val.length <= max))
4855 validation.i18n('Must be between %d and %d characters');
4859 'minlength': function(min)
4861 var val = '' + this;
4863 if (!isNaN(min) && (val.length >= min))
4866 validation.i18n('Must be at least %d characters');
4870 'maxlength': function(max)
4872 var val = '' + this;
4874 if (!isNaN(max) && (val.length <= max))
4877 validation.i18n('Must be at most %d characters');
4885 for (var i = 0; i < arguments.length; i += 2)
4887 delete validation.message;
4889 if (typeof(arguments[i]) != 'function')
4891 if (arguments[i] == this)
4895 else if (arguments[i].apply(this, arguments[i+1]))
4900 if (validation.message)
4901 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
4904 validation.message = msgs.join( L.tr(' - or - '));
4912 for (var i = 0; i < arguments.length; i += 2)
4914 delete validation.message;
4916 if (typeof arguments[i] != 'function')
4918 if (arguments[i] != this)
4922 else if (!arguments[i].apply(this, arguments[i+1]))
4927 if (validation.message)
4928 msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
4931 validation.message = msgs.join(', ');
4937 return validation.types['or'].apply(
4938 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
4941 'list': function(subvalidator, subargs)
4943 if (typeof subvalidator != 'function')
4946 var tokens = this.match(/[^ \t]+/g);
4947 for (var i = 0; i < tokens.length; i++)
4948 if (!subvalidator.apply(tokens[i], subargs))
4954 'phonedigit': function()
4956 if (this.match(/^[0-9\*#!\.]+$/) != null)
4959 validation.i18n('Must be a valid phone number digit');
4963 'string': function()
4970 this.cbi.AbstractValue = this.ui.AbstractWidget.extend({
4971 init: function(name, options)
4974 this.instance = { };
4975 this.dependencies = [ ];
4976 this.rdependency = { };
4978 this.options = L.defaults(options, {
4988 return this.ownerSection.id('field', sid || '__unknown__', this.name);
4991 render: function(sid, condensed)
4993 var i = this.instance[sid] = { };
4995 i.top = $('<div />')
4996 .addClass('luci2-field');
5000 i.top.addClass('form-group');
5002 if (typeof(this.options.caption) == 'string')
5004 .addClass('col-lg-2 control-label')
5005 .attr('for', this.id(sid))
5006 .text(this.options.caption)
5010 i.error = $('<div />')
5012 .addClass('luci2-field-error label label-danger');
5014 i.widget = $('<div />')
5015 .addClass('luci2-field-widget')
5016 .append(this.widget(sid))
5022 i.widget.addClass('col-lg-5');
5025 .addClass('col-lg-5')
5026 .text((typeof(this.options.description) == 'string') ? this.options.description : '')
5033 active: function(sid)
5035 return (this.instance[sid] && !this.instance[sid].disabled);
5038 ucipath: function(sid)
5041 config: (this.options.uci_package || this.ownerMap.uci_package),
5042 section: (this.options.uci_section || sid),
5043 option: (this.options.uci_option || this.name)
5047 ucivalue: function(sid)
5049 var uci = this.ucipath(sid);
5050 var val = this.ownerMap.get(uci.config, uci.section, uci.option);
5052 if (typeof(val) == 'undefined')
5053 return this.options.initial;
5058 formvalue: function(sid)
5060 var v = $('#' + this.id(sid)).val();
5061 return (v === '') ? undefined : v;
5064 textvalue: function(sid)
5066 var v = this.formvalue(sid);
5068 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
5069 v = this.ucivalue(sid);
5071 if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
5072 v = this.options.placeholder;
5074 if (typeof(v) == 'undefined' || v === '')
5077 if (typeof(v) == 'string' && $.isArray(this.choices))
5079 for (var i = 0; i < this.choices.length; i++)
5080 if (v === this.choices[i][0])
5081 return this.choices[i][1];
5083 else if (v === true)
5085 else if (v === false)
5087 else if ($.isArray(v))
5088 return v.join(', ');
5093 changed: function(sid)
5095 var a = this.ucivalue(sid);
5096 var b = this.formvalue(sid);
5098 if (typeof(a) != typeof(b))
5103 if (a.length != b.length)
5106 for (var i = 0; i < a.length; i++)
5112 else if ($.isPlainObject(a))
5119 if (!(k in a) || a[k] !== b[k])
5130 var uci = this.ucipath(sid);
5132 if (this.instance[sid].disabled)
5134 if (!this.options.keep)
5135 return this.ownerMap.set(uci.config, uci.section, uci.option, undefined);
5140 var chg = this.changed(sid);
5141 var val = this.formvalue(sid);
5144 this.ownerMap.set(uci.config, uci.section, uci.option, val);
5149 findSectionID: function($elem)
5151 return this.ownerSection.findParentSectionIDs($elem)[0];
5154 setError: function($elem, msg, msgargs)
5156 var $field = $elem.parents('.luci2-field:first');
5157 var $error = $field.find('.luci2-field-error:first');
5159 if (typeof(msg) == 'string' && msg.length > 0)
5161 $field.addClass('luci2-form-error');
5162 $elem.parent().addClass('has-error');
5164 $error.text(msg.format.apply(msg, msgargs)).show();
5165 $field.trigger('validate');
5171 $elem.parent().removeClass('has-error');
5173 var $other_errors = $field.find('.has-error');
5174 if ($other_errors.length == 0)
5176 $field.removeClass('luci2-form-error');
5177 $error.text('').hide();
5178 $field.trigger('validate');
5187 handleValidate: function(ev)
5189 var $elem = $(this);
5193 var val = $elem.val();
5194 var vstack = d.vstack;
5196 if (vstack && typeof(vstack[0]) == 'function')
5198 delete validation.message;
5200 if ((val.length == 0 && !d.opt))
5202 rv = d.self.setError($elem, L.tr('Field must not be empty'));
5204 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
5206 rv = d.self.setError($elem, validation.message, vstack[1]);
5210 rv = d.self.setError($elem);
5216 var sid = d.self.findSectionID($elem);
5218 for (var field in d.self.rdependency)
5220 d.self.rdependency[field].toggle(sid);
5221 d.self.rdependency[field].validate(sid);
5224 d.self.ownerSection.tabtoggle(sid);
5230 attachEvents: function(sid, elem)
5234 opt: this.options.optional
5238 for (var evname in this.events)
5239 elem.on(evname, evdata, this.events[evname]);
5241 if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
5245 if (typeof(this.options.datatype) == 'string')
5248 evdata.vstack = L.cbi.validation.compile(this.options.datatype);
5251 else if (typeof(this.options.datatype) == 'function')
5253 var vfunc = this.options.datatype;
5254 evdata.vstack = [ function(elem) {
5255 var rv = vfunc(this, elem);
5257 validation.message = rv;
5258 return (rv === true);
5262 if (elem.prop('tagName') == 'SELECT')
5264 elem.change(evdata, this.handleValidate);
5266 else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
5268 elem.click(evdata, this.handleValidate);
5269 elem.blur(evdata, this.handleValidate);
5273 elem.keyup(evdata, this.handleValidate);
5274 elem.blur(evdata, this.handleValidate);
5277 elem.addClass('luci2-field-validate')
5278 .on('validate', evdata, this.handleValidate);
5283 validate: function(sid)
5285 var i = this.instance[sid];
5287 i.widget.find('.luci2-field-validate').trigger('validate');
5289 return (i.disabled || i.error.text() == '');
5292 depends: function(d, v, add)
5299 for (var i = 0; i < d.length; i++)
5301 if (typeof(d[i]) == 'string')
5303 else if (d[i] instanceof L.cbi.AbstractValue)
5304 dep[d[i].name] = true;
5307 else if (d instanceof L.cbi.AbstractValue)
5310 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
5312 else if (typeof(d) == 'object')
5316 else if (typeof(d) == 'string')
5319 dep[d] = (typeof(v) == 'undefined') ? true : v;
5322 if (!dep || $.isEmptyObject(dep))
5325 for (var field in dep)
5327 var f = this.ownerSection.fields[field];
5329 f.rdependency[this.name] = this;
5334 if ($.isEmptyObject(dep))
5337 if (!add || !this.dependencies.length)
5338 this.dependencies.push(dep);
5340 for (var i = 0; i < this.dependencies.length; i++)
5341 $.extend(this.dependencies[i], dep);
5346 toggle: function(sid)
5348 var d = this.dependencies;
5349 var i = this.instance[sid];
5354 for (var n = 0; n < d.length; n++)
5358 for (var field in d[n])
5360 var val = this.ownerSection.fields[field].formvalue(sid);
5361 var cmp = d[n][field];
5363 if (typeof(cmp) == 'boolean')
5365 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
5371 else if (typeof(cmp) == 'string' || typeof(cmp) == 'number')
5379 else if (typeof(cmp) == 'function')
5387 else if (cmp instanceof RegExp)
5402 i.top.removeClass('luci2-field-disabled');
5413 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
5414 i.top.addClass('luci2-field-disabled');
5421 this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
5422 widget: function(sid)
5424 var o = this.options;
5426 if (typeof(o.enabled) == 'undefined') o.enabled = '1';
5427 if (typeof(o.disabled) == 'undefined') o.disabled = '0';
5429 var i = $('<input />')
5430 .attr('id', this.id(sid))
5431 .attr('type', 'checkbox')
5432 .prop('checked', this.ucivalue(sid));
5435 .addClass('checkbox')
5436 .append(this.attachEvents(sid, i));
5439 ucivalue: function(sid)
5441 var v = this.callSuper('ucivalue', sid);
5443 if (typeof(v) == 'boolean')
5446 return (v == this.options.enabled);
5449 formvalue: function(sid)
5451 var v = $('#' + this.id(sid)).prop('checked');
5453 if (typeof(v) == 'undefined')
5454 return !!this.options.initial;
5461 var uci = this.ucipath(sid);
5463 if (this.instance[sid].disabled)
5465 if (!this.options.keep)
5466 return this.ownerMap.set(uci.config, uci.section, uci.option, undefined);
5471 var chg = this.changed(sid);
5472 var val = this.formvalue(sid);
5476 if (this.options.optional && val == this.options.initial)
5477 this.ownerMap.set(uci.config, uci.section, uci.option, undefined);
5479 this.ownerMap.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
5486 this.cbi.InputValue = this.cbi.AbstractValue.extend({
5487 widget: function(sid)
5489 var i = $('<input />')
5490 .addClass('form-control')
5491 .attr('id', this.id(sid))
5492 .attr('type', 'text')
5493 .attr('placeholder', this.options.placeholder)
5494 .val(this.ucivalue(sid));
5496 return this.attachEvents(sid, i);
5500 this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
5501 widget: function(sid)
5503 var i = $('<input />')
5504 .addClass('form-control')
5505 .attr('id', this.id(sid))
5506 .attr('type', 'password')
5507 .attr('placeholder', this.options.placeholder)
5508 .val(this.ucivalue(sid));
5510 var t = $('<span />')
5511 .addClass('input-group-btn')
5512 .append(L.ui.button(L.tr('Reveal'), 'default')
5513 .click(function(ev) {
5515 var i = b.parent().prev();
5516 var t = i.attr('type');
5517 b.text(t == 'password' ? L.tr('Hide') : L.tr('Reveal'));
5518 i.attr('type', (t == 'password') ? 'text' : 'password');
5522 this.attachEvents(sid, i);
5525 .addClass('input-group')
5531 this.cbi.ListValue = this.cbi.AbstractValue.extend({
5532 widget: function(sid)
5534 var s = $('<select />')
5535 .addClass('form-control');
5537 if (this.options.optional && !this.has_empty)
5540 .text(L.tr('-- Please choose --'))
5544 for (var i = 0; i < this.choices.length; i++)
5546 .attr('value', this.choices[i][0])
5547 .text(this.choices[i][1])
5550 s.attr('id', this.id(sid)).val(this.ucivalue(sid));
5552 return this.attachEvents(sid, s);
5555 value: function(k, v)
5561 this.has_empty = true;
5563 this.choices.push([k, v || k]);
5568 this.cbi.MultiValue = this.cbi.ListValue.extend({
5569 widget: function(sid)
5571 var v = this.ucivalue(sid);
5572 var t = $('<div />').attr('id', this.id(sid));
5575 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
5578 for (var i = 0; i < v.length; i++)
5582 for (var i = 0; i < this.choices.length; i++)
5585 .addClass('checkbox')
5586 .append($('<input />')
5587 .attr('type', 'checkbox')
5588 .attr('value', this.choices[i][0])
5589 .prop('checked', s[this.choices[i][0]]))
5590 .append(this.choices[i][1])
5597 formvalue: function(sid)
5600 var fields = $('#' + this.id(sid) + ' > label > input');
5602 for (var i = 0; i < fields.length; i++)
5603 if (fields[i].checked)
5604 rv.push(fields[i].getAttribute('value'));
5609 textvalue: function(sid)
5611 var v = this.formvalue(sid);
5615 for (var i = 0; i < this.choices.length; i++)
5616 c[this.choices[i][0]] = this.choices[i][1];
5620 for (var i = 0; i < v.length; i++)
5621 t.push(c[v[i]] || v[i]);
5623 return t.join(', ');
5627 this.cbi.ComboBox = this.cbi.AbstractValue.extend({
5628 _change: function(ev)
5631 var self = ev.data.self;
5633 if (s.selectedIndex == (s.options.length - 1))
5635 ev.data.select.hide();
5636 ev.data.input.show().focus();
5637 ev.data.input.val('');
5639 else if (self.options.optional && s.selectedIndex == 0)
5641 ev.data.input.val('');
5645 ev.data.input.val(ev.data.select.val());
5648 ev.stopPropagation();
5654 var val = this.value;
5655 var self = ev.data.self;
5657 ev.data.select.empty();
5659 if (self.options.optional && !self.has_empty)
5662 .text(L.tr('-- please choose --'))
5663 .appendTo(ev.data.select);
5666 for (var i = 0; i < self.choices.length; i++)
5668 if (self.choices[i][0] == val)
5672 .attr('value', self.choices[i][0])
5673 .text(self.choices[i][1])
5674 .appendTo(ev.data.select);
5677 if (!seen && val != '')
5681 .appendTo(ev.data.select);
5685 .text(L.tr('-- custom --'))
5686 .appendTo(ev.data.select);
5688 ev.data.input.hide();
5689 ev.data.select.val(val).show().blur();
5692 _enter: function(ev)
5697 ev.preventDefault();
5698 ev.data.self._blur(ev);
5702 widget: function(sid)
5704 var d = $('<div />')
5705 .attr('id', this.id(sid));
5707 var t = $('<input />')
5708 .addClass('form-control')
5709 .attr('type', 'text')
5713 var s = $('<select />')
5714 .addClass('form-control')
5723 s.change(evdata, this._change);
5724 t.blur(evdata, this._blur);
5725 t.keydown(evdata, this._enter);
5727 t.val(this.ucivalue(sid));
5730 this.attachEvents(sid, t);
5731 this.attachEvents(sid, s);
5736 value: function(k, v)
5742 this.has_empty = true;
5744 this.choices.push([k, v || k]);
5748 formvalue: function(sid)
5750 var v = $('#' + this.id(sid)).children('input').val();
5751 return (v == '') ? undefined : v;
5755 this.cbi.DynamicList = this.cbi.ComboBox.extend({
5756 _redraw: function(focus, add, del, s)
5758 var v = s.values || [ ];
5761 $(s.parent).children('div.input-group').children('input').each(function(i) {
5763 v.push(this.value || '');
5766 $(s.parent).empty();
5771 v.splice(focus, 0, '');
5773 else if (v.length == 0)
5779 for (var i = 0; i < v.length; i++)
5786 remove: ((i+1) < v.length)
5791 btn = L.ui.button('–', 'danger').click(evdata, this._btnclick);
5793 btn = L.ui.button('+', 'success').click(evdata, this._btnclick);
5797 var txt = $('<input />')
5798 .addClass('form-control')
5799 .attr('type', 'text')
5802 var sel = $('<select />')
5803 .addClass('form-control');
5806 .addClass('input-group')
5809 .append($('<span />')
5810 .addClass('input-group-btn')
5812 .appendTo(s.parent);
5814 evdata.input = this.attachEvents(s.sid, txt);
5815 evdata.select = this.attachEvents(s.sid, sel);
5817 sel.change(evdata, this._change);
5818 txt.blur(evdata, this._blur);
5819 txt.keydown(evdata, this._keydown);
5824 if (i == focus || -(i+1) == focus)
5831 var f = $('<input />')
5832 .attr('type', 'text')
5834 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
5835 .addClass('form-control')
5836 .keydown(evdata, this._keydown)
5837 .keypress(evdata, this._keypress)
5841 .addClass('input-group')
5843 .append($('<span />')
5844 .addClass('input-group-btn')
5846 .appendTo(s.parent);
5852 else if (-(i+1) == focus)
5856 /* force cursor to end */
5862 evdata.input = this.attachEvents(s.sid, f);
5873 _keypress: function(ev)
5877 /* backspace, delete */
5880 if (ev.data.input.val() == '')
5882 ev.preventDefault();
5888 /* enter, arrow up, arrow down */
5892 ev.preventDefault();
5899 _keydown: function(ev)
5901 var input = ev.data.input;
5905 /* backspace, delete */
5908 if (input.val().length == 0)
5910 ev.preventDefault();
5912 var index = ev.data.index;
5918 ev.data.self._redraw(focus, -1, index, ev.data);
5926 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
5931 var prev = input.parent().prevAll('div.input-group:first').children('input');
5932 if (prev.is(':visible'))
5935 prev.next('select').focus();
5940 var next = input.parent().nextAll('div.input-group:first').children('input');
5941 if (next.is(':visible'))
5944 next.next('select').focus();
5951 _btnclick: function(ev)
5953 if (!this.getAttribute('disabled'))
5957 var index = ev.data.index;
5958 ev.data.self._redraw(-index, -1, index, ev.data);
5962 ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
5969 widget: function(sid)
5971 this.options.optional = true;
5973 var v = this.ucivalue(sid);
5976 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
5978 var d = $('<div />')
5979 .attr('id', this.id(sid))
5980 .addClass('cbi-input-dynlist');
5982 this._redraw(NaN, -1, -1, {
5992 ucivalue: function(sid)
5994 var v = this.callSuper('ucivalue', sid);
5997 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
6002 formvalue: function(sid)
6005 var fields = $('#' + this.id(sid) + ' input');
6007 for (var i = 0; i < fields.length; i++)
6008 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
6009 rv.push(fields[i].value);
6015 this.cbi.DummyValue = this.cbi.AbstractValue.extend({
6016 widget: function(sid)
6019 .addClass('form-control-static')
6020 .attr('id', this.id(sid))
6021 .html(this.ucivalue(sid) || this.label('placeholder'));
6024 formvalue: function(sid)
6026 return this.ucivalue(sid);
6030 this.cbi.ButtonValue = this.cbi.AbstractValue.extend({
6031 widget: function(sid)
6033 this.options.optional = true;
6035 var btn = $('<button />')
6036 .addClass('btn btn-default')
6037 .attr('id', this.id(sid))
6038 .attr('type', 'button')
6039 .text(this.label('text'));
6041 return this.attachEvents(sid, btn);
6045 this.cbi.NetworkList = this.cbi.AbstractValue.extend({
6048 return L.NetworkModel.init();
6051 _device_icon: function(dev)
6054 .attr('src', dev.icon())
6055 .attr('title', '%s (%s)'.format(dev.description(), dev.name() || '?'));
6058 widget: function(sid)
6060 var id = this.id(sid);
6061 var ul = $('<ul />')
6063 .addClass('list-unstyled');
6065 var itype = this.options.multiple ? 'checkbox' : 'radio';
6066 var value = this.ucivalue(sid);
6069 if (!this.options.multiple)
6070 check[value] = true;
6072 for (var i = 0; i < value.length; i++)
6073 check[value[i]] = true;
6075 var interfaces = L.NetworkModel.getInterfaces();
6077 for (var i = 0; i < interfaces.length; i++)
6079 var iface = interfaces[i];
6082 .append($('<label />')
6083 .addClass(itype + ' inline')
6084 .append(this.attachEvents(sid, $('<input />')
6085 .attr('name', itype + id)
6086 .attr('type', itype)
6087 .attr('value', iface.name())
6088 .prop('checked', !!check[iface.name()])))
6089 .append(iface.renderBadge()))
6093 if (!this.options.multiple)
6096 .append($('<label />')
6097 .addClass(itype + ' inline text-muted')
6098 .append(this.attachEvents(sid, $('<input />')
6099 .attr('name', itype + id)
6100 .attr('type', itype)
6102 .prop('checked', $.isEmptyObject(check))))
6103 .append(L.tr('unspecified')))
6110 ucivalue: function(sid)
6112 var v = this.callSuper('ucivalue', sid);
6114 if (!this.options.multiple)
6120 else if (typeof(v) == 'string')
6123 return v ? v[0] : undefined;
6130 if (typeof(v) == 'string')
6131 v = v.match(/\S+/g);
6137 formvalue: function(sid)
6139 var inputs = $('#' + this.id(sid) + ' input');
6141 if (!this.options.multiple)
6143 for (var i = 0; i < inputs.length; i++)
6144 if (inputs[i].checked && inputs[i].value !== '')
6145 return inputs[i].value;
6152 for (var i = 0; i < inputs.length; i++)
6153 if (inputs[i].checked)
6154 rv.push(inputs[i].value);
6156 return rv.length ? rv : undefined;
6160 this.cbi.DeviceList = this.cbi.NetworkList.extend({
6161 handleFocus: function(ev)
6163 var self = ev.data.self;
6164 var input = $(this);
6166 input.parent().prev().prop('checked', true);
6169 handleBlur: function(ev)
6172 ev.data.self.handleKeydown.call(this, ev);
6175 handleKeydown: function(ev)
6177 if (ev.which != 10 && ev.which != 13)
6180 var sid = ev.data.sid;
6181 var self = ev.data.self;
6182 var input = $(this);
6183 var ifnames = L.toArray(input.val());
6185 if (!ifnames.length)
6188 L.NetworkModel.createDevice(ifnames[0]);
6190 self._redraw(sid, $('#' + self.id(sid)), ifnames[0]);
6195 return L.NetworkModel.init();
6198 _redraw: function(sid, ul, sel)
6200 var id = ul.attr('id');
6201 var devs = L.NetworkModel.getDevices();
6202 var iface = L.NetworkModel.getInterface(sid);
6203 var itype = this.options.multiple ? 'checkbox' : 'radio';
6208 for (var i = 0; i < devs.length; i++)
6209 if (devs[i].isInNetwork(iface))
6210 check[devs[i].name()] = true;
6214 if (this.options.multiple)
6215 check = L.toObject(this.formvalue(sid));
6222 for (var i = 0; i < devs.length; i++)
6226 if (dev.isBridge() && this.options.bridges === false)
6229 if (!dev.isBridgeable() && this.options.multiple)
6232 var badge = $('<span />')
6234 .append($('<img />').attr('src', dev.icon()))
6235 .append(' %s: %s'.format(dev.name(), dev.description()));
6237 //var ifcs = dev.getInterfaces();
6240 // for (var j = 0; j < ifcs.length; j++)
6241 // badge.append((j ? ', ' : ' (') + ifcs[j].name());
6243 // badge.append(')');
6247 .append($('<label />')
6248 .addClass(itype + ' inline')
6249 .append($('<input />')
6250 .attr('name', itype + id)
6251 .attr('type', itype)
6252 .attr('value', dev.name())
6253 .prop('checked', !!check[dev.name()]))
6260 .append($('<label />')
6261 .attr('for', 'custom' + id)
6262 .addClass(itype + ' inline')
6263 .append($('<input />')
6264 .attr('name', itype + id)
6265 .attr('type', itype)
6267 .append($('<span />')
6269 .append($('<input />')
6270 .attr('id', 'custom' + id)
6271 .attr('type', 'text')
6272 .attr('placeholder', L.tr('Custom device …'))
6273 .on('focus', { self: this, sid: sid }, this.handleFocus)
6274 .on('blur', { self: this, sid: sid }, this.handleBlur)
6275 .on('keydown', { self: this, sid: sid }, this.handleKeydown))))
6278 if (!this.options.multiple)
6281 .append($('<label />')
6282 .addClass(itype + ' inline text-muted')
6283 .append($('<input />')
6284 .attr('name', itype + id)
6285 .attr('type', itype)
6287 .prop('checked', $.isEmptyObject(check)))
6288 .append(L.tr('unspecified')))
6293 widget: function(sid)
6295 var id = this.id(sid);
6296 var ul = $('<ul />')
6298 .addClass('list-unstyled');
6300 this._redraw(sid, ul);
6307 if (this.instance[sid].disabled)
6310 var ifnames = this.formvalue(sid);
6314 var iface = L.NetworkModel.getInterface(sid);
6318 iface.setDevices($.isArray(ifnames) ? ifnames : [ ifnames ]);
6323 this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
6326 var s = [ arguments[0], this.ownerMap.uci_package, this.uci_type ];
6328 for (var i = 1; i < arguments.length && typeof(arguments[i]) == 'string'; i++)
6329 s.push(arguments[i].replace(/\./g, '_'));
6334 option: function(widget, name, options)
6336 if (this.tabs.length == 0)
6337 this.tab({ id: '__default__', selected: true });
6339 return this.taboption('__default__', widget, name, options);
6342 tab: function(options)
6344 if (options.selected)
6345 this.tabs.selected = this.tabs.length;
6349 caption: options.caption,
6350 description: options.description,
6356 taboption: function(tabid, widget, name, options)
6359 for (var i = 0; i < this.tabs.length; i++)
6361 if (this.tabs[i].id == tabid)
6369 throw 'Cannot append to unknown tab ' + tabid;
6371 var w = widget ? new widget(name, options) : null;
6373 if (!(w instanceof L.cbi.AbstractValue))
6374 throw 'Widget must be an instance of AbstractValue';
6376 w.ownerSection = this;
6377 w.ownerMap = this.ownerMap;
6379 this.fields[name] = w;
6385 tabtoggle: function(sid)
6387 for (var i = 0; i < this.tabs.length; i++)
6389 var tab = this.tabs[i];
6390 var elem = $('#' + this.id('nodetab', sid, tab.id));
6393 for (var j = 0; j < tab.fields.length; j++)
6395 if (tab.fields[j].active(sid))
6402 if (empty && elem.is(':visible'))
6409 validate: function(parent_sid)
6411 var s = this.getUCISections(parent_sid);
6414 for (var i = 0; i < s.length; i++)
6416 var $item = $('#' + this.id('sectionitem', s[i]['.name']));
6418 $item.find('.luci2-field-validate').trigger('validate');
6419 n += $item.find('.luci2-field.luci2-form-error').not('.luci2-field-disabled').length;
6425 load: function(parent_sid)
6427 var deferreds = [ ];
6429 var s = this.getUCISections(parent_sid);
6430 for (var i = 0; i < s.length; i++)
6432 for (var f in this.fields)
6434 if (typeof(this.fields[f].load) != 'function')
6437 var rv = this.fields[f].load(s[i]['.name']);
6438 if (L.isDeferred(rv))
6442 for (var j = 0; j < this.subsections.length; j++)
6444 var rv = this.subsections[j].load(s[i]['.name']);
6445 deferreds.push.apply(deferreds, rv);
6452 save: function(parent_sid)
6454 var deferreds = [ ];
6455 var s = this.getUCISections(parent_sid);
6457 for (i = 0; i < s.length; i++)
6459 if (!this.options.readonly)
6461 for (var f in this.fields)
6463 if (typeof(this.fields[f].save) != 'function')
6466 var rv = this.fields[f].save(s[i]['.name']);
6467 if (L.isDeferred(rv))
6472 for (var j = 0; j < this.subsections.length; j++)
6474 var rv = this.subsections[j].save(s[i]['.name']);
6475 deferreds.push.apply(deferreds, rv);
6482 teaser: function(sid)
6484 var tf = this.teaser_fields;
6488 tf = this.teaser_fields = [ ];
6490 if ($.isArray(this.options.teasers))
6492 for (var i = 0; i < this.options.teasers.length; i++)
6494 var f = this.options.teasers[i];
6495 if (f instanceof L.cbi.AbstractValue)
6497 else if (typeof(f) == 'string' && this.fields[f] instanceof L.cbi.AbstractValue)
6498 tf.push(this.fields[f]);
6503 for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
6504 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
6505 tf.push(this.tabs[i].fields[j]);
6511 for (var i = 0; i < tf.length; i++)
6513 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
6516 var n = tf[i].options.caption || tf[i].name;
6517 var v = tf[i].textvalue(sid);
6519 if (typeof(v) == 'undefined')
6522 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
6528 findAdditionalUCIPackages: function()
6532 for (var i = 0; i < this.tabs.length; i++)
6533 for (var j = 0; j < this.tabs[i].fields.length; j++)
6534 if (this.tabs[i].fields[j].options.uci_package)
6535 packages.push(this.tabs[i].fields[j].options.uci_package);
6540 findParentSectionIDs: function($elem)
6543 var $parents = $elem.parents('.luci2-section-item');
6545 for (var i = 0; i < $parents.length; i++)
6546 rv.push($parents[i].getAttribute('data-luci2-sid'));
6552 this.cbi.TypedSection = this.cbi.AbstractSection.extend({
6553 init: function(uci_type, options)
6555 this.uci_type = uci_type;
6556 this.options = options;
6559 this.subsections = [ ];
6560 this.active_panel = { };
6561 this.active_tab = { };
6563 this.instance = { };
6566 filter: function(section, parent_sid)
6571 sort: function(section1, section2)
6576 subsection: function(widget, uci_type, options)
6578 var w = widget ? new widget(uci_type, options) : null;
6580 if (!(w instanceof L.cbi.AbstractSection))
6581 throw 'Widget must be an instance of AbstractSection';
6583 w.ownerSection = this;
6584 w.ownerMap = this.ownerMap;
6585 w.index = this.subsections.length;
6587 this.subsections.push(w);
6591 getUCISections: function(parent_sid)
6593 var s1 = L.uci.sections(this.ownerMap.uci_package);
6596 for (var i = 0; i < s1.length; i++)
6597 if (s1[i]['.type'] == this.uci_type)
6598 if (this.filter(s1[i], parent_sid))
6606 add: function(name, parent_sid)
6608 return this.ownerMap.add(this.ownerMap.uci_package, this.uci_type, name);
6611 remove: function(sid, parent_sid)
6613 return this.ownerMap.remove(this.ownerMap.uci_package, sid);
6616 handleAdd: function(ev)
6619 var name = undefined;
6620 var self = ev.data.self;
6621 var sid = self.findParentSectionIDs(addb)[0];
6623 if (addb.prev().prop('nodeName') == 'INPUT')
6624 name = addb.prev().val();
6626 if (addb.prop('disabled') || name === '')
6629 L.ui.saveScrollTop();
6631 self.setPanelIndex(sid, -1);
6632 self.ownerMap.save();
6634 ev.data.sid = self.add(name, sid);
6635 ev.data.type = self.uci_type;
6636 ev.data.name = name;
6638 self.trigger('add', ev);
6640 self.ownerMap.redraw();
6642 L.ui.restoreScrollTop();
6645 handleRemove: function(ev)
6647 var self = ev.data.self;
6648 var sids = self.findParentSectionIDs($(this));
6652 L.ui.saveScrollTop();
6655 ev.parent_sid = sids[1];
6657 self.trigger('remove', ev);
6659 self.ownerMap.save();
6660 self.remove(ev.sid, ev.parent_sid);
6661 self.ownerMap.redraw();
6663 L.ui.restoreScrollTop();
6666 ev.stopPropagation();
6669 handleSID: function(ev)
6671 var self = ev.data.self;
6673 var addb = text.next();
6674 var errt = addb.next();
6675 var name = text.val();
6677 if (!/^[a-zA-Z0-9_]*$/.test(name))
6679 errt.text(L.tr('Invalid section name')).show();
6680 text.addClass('error');
6681 addb.prop('disabled', true);
6685 if (L.uci.get(self.ownerMap.uci_package, name))
6687 errt.text(L.tr('Name already used')).show();
6688 text.addClass('error');
6689 addb.prop('disabled', true);
6693 errt.text('').hide();
6694 text.removeClass('error');
6695 addb.prop('disabled', false);
6699 handleTab: function(ev)
6701 var self = ev.data.self;
6703 var sid = self.findParentSectionIDs($tab)[0];
6705 self.active_tab[sid] = $tab.parent().index();
6708 handleTabValidate: function(ev)
6710 var $pane = $(ev.delegateTarget);
6711 var $badge = $pane.parent()
6712 .children('.nav-tabs')
6714 .eq($pane.index() - 1) // item #1 is the <ul>
6715 .find('.badge:first');
6717 var err_count = $pane.find('.luci2-field.luci2-form-error').not('.luci2-field-disabled').length;
6721 .attr('title', L.trp('1 Error', '%d Errors', err_count).format(err_count))
6727 handlePanelValidate: function(ev)
6729 var $elem = $(this);
6731 .prevAll('.luci2-section-header:first')
6732 .children('.luci2-section-teaser')
6733 .find('.badge:first');
6735 var err_count = $elem.find('.luci2-field.luci2-form-error').not('.luci2-field-disabled').length;
6739 .attr('title', L.trp('1 Error', '%d Errors', err_count).format(err_count))
6745 handlePanelCollapse: function(ev)
6747 var self = ev.data.self;
6749 var $items = $(ev.delegateTarget).children('.luci2-section-item');
6751 var $this_panel = $(ev.target);
6752 var $this_teaser = $this_panel.prevAll('.luci2-section-header:first').children('.luci2-section-teaser');
6754 var $prev_panel = $items.children('.luci2-section-panel.in');
6755 var $prev_teaser = $prev_panel.prevAll('.luci2-section-header:first').children('.luci2-section-teaser');
6757 var sids = self.findParentSectionIDs($prev_panel);
6759 self.setPanelIndex(sids[1], $this_panel.parent().index());
6763 .addClass('collapse');
6767 .children('span:last')
6769 .append(self.teaser(sids[0]));
6774 ev.stopPropagation();
6777 handleSort: function(ev)
6779 var self = ev.data.self;
6781 var $item = $(this).parents('.luci2-section-item:first');
6782 var $next = ev.data.up ? $item.prev() : $item.next();
6784 if ($item.length && $next.length)
6786 var cur_sid = $item.attr('data-luci2-sid');
6787 var new_sid = $next.attr('data-luci2-sid');
6789 L.uci.swap(self.ownerMap.uci_package, cur_sid, new_sid);
6791 self.ownerMap.save();
6792 self.ownerMap.redraw();
6795 ev.stopPropagation();
6798 getPanelIndex: function(parent_sid)
6800 return (this.active_panel[parent_sid || '__top__'] || 0);
6803 setPanelIndex: function(parent_sid, new_index)
6805 if (typeof(new_index) == 'number')
6806 this.active_panel[parent_sid || '__top__'] = new_index;
6809 renderAdd: function()
6811 if (!this.options.addremove)
6814 var text = L.tr('Add section');
6815 var ttip = L.tr('Create new section...');
6817 if ($.isArray(this.options.add_caption))
6818 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
6819 else if (typeof(this.options.add_caption) == 'string')
6820 text = this.options.add_caption, ttip = '';
6822 var add = $('<div />');
6824 if (this.options.anonymous === false)
6827 .addClass('cbi-input-text')
6828 .attr('type', 'text')
6829 .attr('placeholder', ttip)
6830 .blur({ self: this }, this.handleSID)
6831 .keyup({ self: this }, this.handleSID)
6835 .attr('src', L.globals.resource + '/icons/cbi/add.gif')
6836 .attr('title', text)
6837 .addClass('cbi-button')
6838 .click({ self: this }, this.handleAdd)
6842 .addClass('cbi-value-error')
6848 L.ui.button(text, 'success', ttip)
6849 .click({ self: this }, this.handleAdd)
6856 renderRemove: function(index)
6858 if (!this.options.addremove)
6861 var text = L.tr('Remove');
6862 var ttip = L.tr('Remove this section');
6864 if ($.isArray(this.options.remove_caption))
6865 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
6866 else if (typeof(this.options.remove_caption) == 'string')
6867 text = this.options.remove_caption, ttip = '';
6869 return L.ui.button(text, 'danger', ttip)
6870 .click({ self: this, index: index }, this.handleRemove);
6873 renderSort: function(index)
6875 if (!this.options.sortable)
6878 var b1 = L.ui.button('↑', 'info', L.tr('Move up'))
6879 .click({ self: this, index: index, up: true }, this.handleSort);
6881 var b2 = L.ui.button('↓', 'info', L.tr('Move down'))
6882 .click({ self: this, index: index, up: false }, this.handleSort);
6887 renderCaption: function()
6890 .addClass('panel-title')
6891 .append(this.label('caption') || this.uci_type);
6894 renderDescription: function()
6896 var text = this.label('description');
6900 .addClass('luci2-section-description')
6906 renderTeaser: function(sid, index)
6908 if (this.options.collabsible || this.ownerMap.options.collabsible)
6911 .attr('id', this.id('teaser', sid))
6912 .addClass('luci2-section-teaser well well-sm')
6913 .append($('<span />')
6915 .append($('<span />'));
6921 renderHead: function(condensed)
6927 .addClass('panel-heading')
6928 .append(this.renderCaption())
6929 .append(this.renderDescription());
6932 renderTabDescription: function(sid, index, tab_index)
6934 var tab = this.tabs[tab_index];
6936 if (typeof(tab.description) == 'string')
6939 .addClass('cbi-tab-descr')
6940 .text(tab.description);
6946 renderTabHead: function(sid, index, tab_index)
6948 var tab = this.tabs[tab_index];
6949 var cur = this.active_tab[sid] || 0;
6951 var tabh = $('<li />')
6953 .attr('id', this.id('nodetab', sid, tab.id))
6954 .attr('href', '#' + this.id('node', sid, tab.id))
6955 .attr('data-toggle', 'tab')
6956 .text((tab.caption ? tab.caption.format(tab.id) : tab.id) + ' ')
6957 .append($('<span />')
6959 .on('shown.bs.tab', { self: this, sid: sid }, this.handleTab));
6961 if (cur == tab_index)
6962 tabh.addClass('active');
6964 if (!tab.fields.length)
6970 renderTabBody: function(sid, index, tab_index)
6972 var tab = this.tabs[tab_index];
6973 var cur = this.active_tab[sid] || 0;
6975 var tabb = $('<div />')
6976 .addClass('tab-pane')
6977 .attr('id', this.id('node', sid, tab.id))
6978 .append(this.renderTabDescription(sid, index, tab_index))
6979 .on('validate', this.handleTabValidate);
6981 if (cur == tab_index)
6982 tabb.addClass('active');
6984 for (var i = 0; i < tab.fields.length; i++)
6985 tabb.append(tab.fields[i].render(sid));
6990 renderPanelHead: function(sid, index, parent_sid)
6992 var head = $('<div />')
6993 .addClass('luci2-section-header')
6994 .append(this.renderTeaser(sid, index))
6995 .append($('<div />')
6996 .addClass('btn-group')
6997 .append(this.renderSort(index))
6998 .append(this.renderRemove(index)));
7000 if (this.options.collabsible)
7002 head.attr('data-toggle', 'collapse')
7003 .attr('data-parent', this.id('sectiongroup', parent_sid))
7004 .attr('data-target', '#' + this.id('panel', sid));
7010 renderPanelBody: function(sid, index, parent_sid)
7012 var body = $('<div />')
7013 .attr('id', this.id('panel', sid))
7014 .addClass('luci2-section-panel')
7015 .on('validate', this.handlePanelValidate);
7017 if (this.options.collabsible || this.ownerMap.options.collabsible)
7019 body.addClass('panel-collapse collapse');
7021 if (index == this.getPanelIndex(parent_sid))
7022 body.addClass('in');
7025 var tab_heads = $('<ul />')
7026 .addClass('nav nav-tabs');
7028 var tab_bodies = $('<div />')
7029 .addClass('form-horizontal tab-content')
7032 for (var j = 0; j < this.tabs.length; j++)
7034 tab_heads.append(this.renderTabHead(sid, index, j));
7035 tab_bodies.append(this.renderTabBody(sid, index, j));
7038 body.append(tab_bodies);
7040 if (this.tabs.length <= 1)
7043 for (var i = 0; i < this.subsections.length; i++)
7044 body.append(this.subsections[i].render(false, sid));
7049 renderBody: function(condensed, parent_sid)
7051 var s = this.getUCISections(parent_sid);
7052 var n = this.getPanelIndex(parent_sid);
7055 this.setPanelIndex(parent_sid, n + s.length);
7056 else if (n >= s.length)
7057 this.setPanelIndex(parent_sid, s.length - 1);
7059 var body = $('<ul />')
7060 .addClass('luci2-section-group list-group');
7062 if (this.options.collabsible)
7064 body.attr('id', this.id('sectiongroup', parent_sid))
7065 .on('show.bs.collapse', { self: this }, this.handlePanelCollapse);
7070 body.append($('<li />')
7071 .addClass('list-group-item text-muted')
7072 .text(this.label('placeholder') || L.tr('There are no entries defined yet.')))
7075 for (var i = 0; i < s.length; i++)
7077 var sid = s[i]['.name'];
7078 var inst = this.instance[sid] = { tabs: [ ] };
7080 body.append($('<li />')
7081 .addClass('luci2-section-item list-group-item')
7082 .attr('id', this.id('sectionitem', sid))
7083 .attr('data-luci2-sid', sid)
7084 .append(this.renderPanelHead(sid, i, parent_sid))
7085 .append(this.renderPanelBody(sid, i, parent_sid)));
7091 render: function(condensed, parent_sid)
7093 this.instance = { };
7095 var panel = $('<div />')
7096 .addClass('panel panel-default')
7097 .append(this.renderHead(condensed))
7098 .append(this.renderBody(condensed, parent_sid));
7100 if (this.options.addremove)
7101 panel.append($('<div />')
7102 .addClass('panel-footer')
7103 .append(this.renderAdd()));
7108 finish: function(parent_sid)
7110 var s = this.getUCISections(parent_sid);
7112 for (var i = 0; i < s.length; i++)
7114 var sid = s[i]['.name'];
7116 if (i != this.getPanelIndex(parent_sid))
7117 $('#' + this.id('teaser', sid)).children('span:last')
7118 .append(this.teaser(sid));
7120 $('#' + this.id('teaser', sid))
7123 for (var j = 0; j < this.subsections.length; j++)
7124 this.subsections[j].finish(sid);
7129 this.cbi.TableSection = this.cbi.TypedSection.extend({
7130 renderTableHead: function()
7132 var thead = $('<thead />')
7134 .addClass('cbi-section-table-titles'));
7136 for (var j = 0; j < this.tabs[0].fields.length; j++)
7137 thead.children().append($('<th />')
7138 .addClass('cbi-section-table-cell')
7139 .css('width', this.tabs[0].fields[j].options.width || '')
7140 .append(this.tabs[0].fields[j].label('caption')));
7142 if (this.options.addremove !== false || this.options.sortable)
7143 thead.children().append($('<th />')
7144 .addClass('cbi-section-table-cell')
7150 renderTableRow: function(sid, index)
7152 var row = $('<tr />')
7153 .addClass('luci2-section-item')
7154 .attr('id', this.id('sectionitem', sid))
7155 .attr('data-luci2-sid', sid);
7157 for (var j = 0; j < this.tabs[0].fields.length; j++)
7159 row.append($('<td />')
7160 .css('width', this.tabs[0].fields[j].options.width || '')
7161 .append(this.tabs[0].fields[j].render(sid, true)));
7164 if (this.options.addremove !== false || this.options.sortable)
7166 row.append($('<td />')
7168 .addClass('text-right')
7169 .append($('<div />')
7170 .addClass('btn-group')
7171 .append(this.renderSort(index))
7172 .append(this.renderRemove(index))));
7178 renderTableBody: function(parent_sid)
7180 var s = this.getUCISections(parent_sid);
7182 var tbody = $('<tbody />');
7186 var cols = this.tabs[0].fields.length;
7188 if (this.options.addremove !== false || this.options.sortable)
7191 tbody.append($('<tr />')
7193 .addClass('text-muted')
7194 .attr('colspan', cols)
7195 .text(this.label('placeholder') || L.tr('There are no entries defined yet.'))));
7198 for (var i = 0; i < s.length; i++)
7200 var sid = s[i]['.name'];
7201 var inst = this.instance[sid] = { tabs: [ ] };
7203 tbody.append(this.renderTableRow(sid, i));
7209 renderBody: function(condensed, parent_sid)
7211 return $('<table />')
7212 .addClass('table table-condensed table-hover')
7213 .append(this.renderTableHead())
7214 .append(this.renderTableBody(parent_sid));
7218 this.cbi.NamedSection = this.cbi.TypedSection.extend({
7219 getUCISections: function(cb)
7222 var sl = L.uci.sections(this.ownerMap.uci_package);
7224 for (var i = 0; i < sl.length; i++)
7225 if (sl[i]['.name'] == this.uci_type)
7231 if (typeof(cb) == 'function' && sa.length > 0)
7232 cb.call(this, sa[0]);
7238 this.cbi.SingleSection = this.cbi.NamedSection.extend({
7241 this.instance = { };
7242 this.instance[this.uci_type] = { tabs: [ ] };
7245 .addClass('luci2-section-item')
7246 .attr('id', this.id('sectionitem', this.uci_type))
7247 .attr('data-luci2-sid', this.uci_type)
7248 .append(this.renderPanelBody(this.uci_type, 0));
7252 this.cbi.DummySection = this.cbi.TypedSection.extend({
7253 getUCISections: function(cb)
7255 if (typeof(cb) == 'function')
7256 cb.apply(this, [ { '.name': this.uci_type } ]);
7258 return [ { '.name': this.uci_type } ];
7262 this.cbi.Map = this.ui.AbstractWidget.extend({
7263 init: function(uci_package, options)
7267 this.uci_package = uci_package;
7268 this.sections = [ ];
7269 this.options = L.defaults(options, {
7270 save: function() { },
7271 prepare: function() { }
7275 loadCallback: function()
7277 var deferreds = [ L.deferrable(this.options.prepare()) ];
7279 for (var i = 0; i < this.sections.length; i++)
7281 var rv = this.sections[i].load();
7282 deferreds.push.apply(deferreds, rv);
7285 return $.when.apply($, deferreds);
7291 var packages = [ this.uci_package ];
7293 for (var i = 0; i < this.sections.length; i++)
7294 packages.push.apply(packages, this.sections[i].findAdditionalUCIPackages());
7296 for (var i = 0; i < packages.length; i++)
7297 if (!L.uci.writable(packages[i]))
7299 this.options.readonly = true;
7303 return L.uci.load(packages).then(function() {
7304 return self.loadCallback();
7308 handleTab: function(ev)
7310 ev.data.self.active_tab = $(ev.target).parent().index();
7313 handleApply: function(ev)
7315 var self = ev.data.self;
7317 self.trigger('apply', ev);
7320 handleSave: function(ev)
7322 var self = ev.data.self;
7324 self.send().then(function() {
7325 self.trigger('save', ev);
7329 handleReset: function(ev)
7331 var self = ev.data.self;
7333 self.trigger('reset', ev);
7337 renderTabHead: function(tab_index)
7339 var section = this.sections[tab_index];
7340 var cur = this.active_tab || 0;
7342 var tabh = $('<li />')
7344 .attr('id', section.id('sectiontab'))
7345 .attr('href', '#' + section.id('section'))
7346 .attr('data-toggle', 'tab')
7347 .text(section.label('caption') + ' ')
7348 .append($('<span />')
7350 .on('shown.bs.tab', { self: this }, this.handleTab));
7352 if (cur == tab_index)
7353 tabh.addClass('active');
7358 renderTabBody: function(tab_index)
7360 var section = this.sections[tab_index];
7361 var desc = section.label('description');
7362 var cur = this.active_tab || 0;
7364 var tabb = $('<div />')
7365 .addClass('tab-pane')
7366 .attr('id', section.id('section'));
7368 if (cur == tab_index)
7369 tabb.addClass('active');
7372 tabb.append($('<p />')
7375 var s = section.render(this.options.tabbed);
7377 if (this.options.readonly || section.options.readonly)
7378 s.find('input, select, button, img.cbi-button').attr('disabled', true);
7385 renderBody: function()
7387 var tabs = $('<ul />')
7388 .addClass('nav nav-tabs');
7390 var body = $('<div />')
7393 for (var i = 0; i < this.sections.length; i++)
7395 tabs.append(this.renderTabHead(i));
7396 body.append(this.renderTabBody(i));
7399 if (this.options.tabbed)
7400 body.addClass('tab-content');
7407 renderFooter: function()
7414 .addClass('panel panel-default panel-body text-right')
7415 .append($('<div />')
7416 .addClass('btn-group')
7417 .append(L.ui.button(L.tr('Save & Apply'), 'primary')
7418 .click(evdata, this.handleApply))
7419 .append(L.ui.button(L.tr('Save'), 'default')
7420 .click(evdata, this.handleSave))
7421 .append(L.ui.button(L.tr('Reset'), 'default')
7422 .click(evdata, this.handleReset)));
7427 var map = $('<form />');
7429 if (typeof(this.options.caption) == 'string')
7430 map.append($('<h2 />')
7431 .text(this.options.caption));
7433 if (typeof(this.options.description) == 'string')
7434 map.append($('<p />')
7435 .text(this.options.description));
7437 map.append(this.renderBody());
7439 if (this.options.pageaction !== false)
7440 map.append(this.renderFooter());
7447 for (var i = 0; i < this.sections.length; i++)
7448 this.sections[i].finish();
7455 this.target.hide().empty().append(this.render());
7460 section: function(widget, uci_type, options)
7462 var w = widget ? new widget(uci_type, options) : null;
7464 if (!(w instanceof L.cbi.AbstractSection))
7465 throw 'Widget must be an instance of AbstractSection';
7468 w.index = this.sections.length;
7470 this.sections.push(w);
7474 add: function(conf, type, name)
7476 return L.uci.add(conf, type, name);
7479 remove: function(conf, sid)
7481 return L.uci.remove(conf, sid);
7484 get: function(conf, sid, opt)
7486 return L.uci.get(conf, sid, opt);
7489 set: function(conf, sid, opt, val)
7491 return L.uci.set(conf, sid, opt, val);
7494 validate: function()
7498 for (var i = 0; i < this.sections.length; i++)
7500 if (!this.sections[i].validate())
7511 if (self.options.readonly)
7512 return L.deferrable();
7514 var deferreds = [ ];
7516 for (var i = 0; i < self.sections.length; i++)
7518 var rv = self.sections[i].save();
7519 deferreds.push.apply(deferreds, rv);
7522 return $.when.apply($, deferreds).then(function() {
7523 return L.deferrable(self.options.save());
7529 if (!this.validate())
7530 return L.deferrable();
7534 L.ui.saveScrollTop();
7537 return this.save().then(function() {
7538 return L.uci.save();
7539 }).then(function() {
7540 return L.ui.updateChanges();
7541 }).then(function() {
7543 }).then(function() {
7547 L.ui.loading(false);
7548 L.ui.restoreScrollTop();
7554 var packages = [ this.uci_package ];
7556 for (var i = 0; i < this.sections.length; i++)
7557 packages.push.apply(packages, this.sections[i].findAdditionalUCIPackages());
7559 L.uci.unload(packages);
7568 return self.insertInto(self.target);
7571 insertInto: function(id)
7574 self.target = $(id);
7579 return self.load().then(function() {
7580 self.target.empty().append(self.render());
7584 L.ui.loading(false);
7589 this.cbi.Modal = this.cbi.Map.extend({
7590 handleApply: function(ev)
7592 var self = ev.data.self;
7594 self.trigger('apply', ev);
7597 handleSave: function(ev)
7599 var self = ev.data.self;
7601 self.send().then(function() {
7602 self.trigger('save', ev);
7607 handleReset: function(ev)
7609 var self = ev.data.self;
7611 self.trigger('close', ev);
7616 renderFooter: function()
7623 .addClass('btn-group')
7624 .append(L.ui.button(L.tr('Save & Apply'), 'primary')
7625 .click(evdata, this.handleApply))
7626 .append(L.ui.button(L.tr('Save'), 'default')
7627 .click(evdata, this.handleSave))
7628 .append(L.ui.button(L.tr('Cancel'), 'default')
7629 .click(evdata, this.handleReset));
7634 var modal = L.ui.dialog(this.label('caption'), null, { wide: true });
7635 var map = $('<form />');
7637 var desc = this.label('description');
7639 map.append($('<p />').text(desc));
7641 map.append(this.renderBody());
7643 modal.find('.modal-body').append(map);
7644 modal.find('.modal-footer').append(this.renderFooter());
7661 return self.load().then(function() {
7665 L.ui.loading(false);