function LuCI2()
{
- var _luci2 = this;
+ var L = this;
var Class = function() { };
plural: function(n) { return 0 + (n != 1) },
init: function() {
- if (_luci2.i18n.loaded)
+ if (L.i18n.loaded)
return;
var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
for (var i = 0; i < langs.length; i++)
- $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
+ $.ajax('%s/i18n/base.%s.json'.format(L.globals.resource, langs[i]), {
async: false,
cache: true,
dataType: 'json',
success: function(data) {
- $.extend(_luci2.i18n.catalog, data);
+ $.extend(L.i18n.catalog, data);
- var pe = _luci2.i18n.catalog[''];
+ var pe = L.i18n.catalog[''];
if (pe)
{
- delete _luci2.i18n.catalog[''];
+ delete L.i18n.catalog[''];
try {
var pf = new Function('n', 'return 0 + (' + pe + ')');
- _luci2.i18n.plural = pf;
+ L.i18n.plural = pf;
} catch (e) { };
}
}
});
- _luci2.i18n.loaded = true;
+ L.i18n.loaded = true;
}
};
this.tr = function(msgid)
{
- _luci2.i18n.init();
+ L.i18n.init();
- var msgstr = _luci2.i18n.catalog[msgid];
+ var msgstr = L.i18n.catalog[msgid];
if (typeof(msgstr) == 'undefined')
return msgid;
this.trp = function(msgid, msgid_plural, count)
{
- _luci2.i18n.init();
+ L.i18n.init();
- var msgstr = _luci2.i18n.catalog[msgid];
+ var msgstr = L.i18n.catalog[msgid];
if (typeof(msgstr) == 'undefined')
return (count == 1) ? msgid : msgid_plural;
else if (typeof(msgstr) == 'string')
return msgstr;
else
- return msgstr[_luci2.i18n.plural(count)];
+ return msgstr[L.i18n.plural(count)];
};
this.trc = function(msgctx, msgid)
{
- _luci2.i18n.init();
+ L.i18n.init();
- var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
+ var msgstr = L.i18n.catalog[msgid + '\u0004' + msgctx];
if (typeof(msgstr) == 'undefined')
return msgid;
this.trcp = function(msgctx, msgid, msgid_plural, count)
{
- _luci2.i18n.init();
+ L.i18n.init();
- var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
+ var msgstr = L.i18n.catalog[msgid + '\u0004' + msgctx];
if (typeof(msgstr) == 'undefined')
return (count == 1) ? msgid : msgid_plural;
else if (typeof(msgstr) == 'string')
return msgstr;
else
- return msgstr[_luci2.i18n.plural(count)];
+ return msgstr[L.i18n.plural(count)];
};
this.setHash = function(key, value)
return n;
};
+ this.toColor = function(str)
+ {
+ if (typeof(str) != 'string' || str.length == 0)
+ return '#CCCCCC';
+
+ if (str == 'wan')
+ return '#F09090';
+ else if (str == 'lan')
+ return '#90F090';
+
+ var i = 0, hash = 0;
+
+ while (i < str.length)
+ hash = str.charCodeAt(i++) + ((hash << 5) - hash);
+
+ var r = (hash & 0xFF) % 128;
+ var g = ((hash >> 8) & 0xFF) % 128;
+
+ var min = 0;
+ var max = 128;
+
+ if ((r + g) < 128)
+ min = 128 - r - g;
+ else
+ max = 255 - r - g;
+
+ var b = min + (((hash >> 16) & 0xFF) % (max - min));
+
+ return '#%02X%02X%02X'.format(0xFF - r, 0xFF - g, 0xFF - b);
+ };
+
+ this.parseIPv4 = function(str)
+ {
+ if ((typeof(str) != 'string' && !(str instanceof String)) ||
+ !str.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/))
+ return undefined;
+
+ var num = [ ];
+ var parts = str.split(/\./);
+
+ for (var i = 0; i < parts.length; i++)
+ {
+ var n = parseInt(parts[i], 10);
+ if (isNaN(n) || n > 255)
+ return undefined;
+
+ num.push(n);
+ }
+
+ return num;
+ };
+
+ this.parseIPv6 = function(str)
+ {
+ if ((typeof(str) != 'string' && !(str instanceof String)) ||
+ !str.match(/^[a-fA-F0-9:]+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/))
+ return undefined;
+
+ var parts = str.split(/::/);
+ if (parts.length == 0 || parts.length > 2)
+ return undefined;
+
+ var lnum = [ ];
+ if (parts[0].length > 0)
+ {
+ var left = parts[0].split(/:/);
+ for (var i = 0; i < left.length; i++)
+ {
+ var n = parseInt(left[i], 16);
+ if (isNaN(n))
+ return undefined;
+
+ lnum.push((n / 256) >> 0);
+ lnum.push(n % 256);
+ }
+ }
+
+ var rnum = [ ];
+ if (parts.length > 1 && parts[1].length > 0)
+ {
+ var right = parts[1].split(/:/);
+
+ for (var i = 0; i < right.length; i++)
+ {
+ if (right[i].indexOf('.') > 0)
+ {
+ var addr = L.parseIPv4(right[i]);
+ if (!addr)
+ return undefined;
+
+ rnum.push.apply(rnum, addr);
+ continue;
+ }
+
+ var n = parseInt(right[i], 16);
+ if (isNaN(n))
+ return undefined;
+
+ rnum.push((n / 256) >> 0);
+ rnum.push(n % 256);
+ }
+ }
+
+ if (rnum.length > 0 && (lnum.length + rnum.length) > 15)
+ return undefined;
+
+ var num = [ ];
+
+ num.push.apply(num, lnum);
+
+ for (var i = 0; i < (16 - lnum.length - rnum.length); i++)
+ num.push(0);
+
+ num.push.apply(num, rnum);
+
+ if (num.length > 16)
+ return undefined;
+
+ return num;
+ };
+
+ this.isNetmask = function(addr)
+ {
+ if (!$.isArray(addr))
+ return false;
+
+ var c;
+
+ for (c = 0; (c < addr.length) && (addr[c] == 255); c++);
+
+ if (c == addr.length)
+ return true;
+
+ if ((addr[c] == 254) || (addr[c] == 252) || (addr[c] == 248) ||
+ (addr[c] == 240) || (addr[c] == 224) || (addr[c] == 192) ||
+ (addr[c] == 128) || (addr[c] == 0))
+ {
+ for (c++; (c < addr.length) && (addr[c] == 0); c++);
+
+ if (c == addr.length)
+ return true;
+ }
+
+ return false;
+ };
+
this.globals = {
timeout: 15000,
resource: '/luci2',
data: JSON.stringify(req),
dataType: 'json',
type: 'POST',
- timeout: _luci2.globals.timeout
- }).then(cb);
+ timeout: L.globals.timeout,
+ _rpc_req: req
+ }).then(cb, cb);
},
_list_cb: function(msg)
{
+ var list = msg.result;
+
/* verify message frame */
- if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
- throw 'Invalid JSON response';
+ if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
+ list = [ ];
- return msg.result;
+ return $.Deferred().resolveWith(this, [ list ]);
},
_call_cb: function(msg)
{
var data = [ ];
var type = Object.prototype.toString;
+ var reqs = this._rpc_req;
- if (!$.isArray(msg))
+ if (!$.isArray(reqs))
+ {
msg = [ msg ];
+ reqs = [ reqs ];
+ }
for (var i = 0; i < msg.length; i++)
{
- /* verify message frame */
- if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
- throw 'Invalid JSON response';
-
/* fetch related request info */
- var req = _luci2.rpc._requests[msg[i].id];
+ var req = L.rpc._requests[reqs[i].id];
if (typeof(req) != 'object')
throw 'No related request for JSON response';
/* fetch response attribute and verify returned type */
var ret = undefined;
- if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
- ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
+ /* verify message frame */
+ if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
+ if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
+ ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
if (req.expect)
{
{
req.priv[0] = ret;
req.priv[1] = req.params;
- ret = req.filter.apply(_luci2.rpc, req.priv);
+ ret = req.filter.apply(L.rpc, req.priv);
}
/* store response data */
data = ret;
/* delete request object */
- delete _luci2.rpc._requests[msg[i].id];
+ delete L.rpc._requests[reqs[i].id];
}
- return data;
+ return $.Deferred().resolveWith(this, [ data ]);
},
list: function()
flush: function()
{
if (!$.isArray(this._batch))
- return _luci2.deferrable([ ]);
+ return L.deferrable([ ]);
var req = this._batch;
delete this._batch;
id: _rpc._id++,
method: 'call',
params: [
- _luci2.globals.sid,
+ L.globals.sid,
options.object,
options.method,
params
if ($.isArray(_rpc._batch))
{
req.index = _rpc._batch.push(msg) - 1;
- return _luci2.deferrable(msg);
+ return L.deferrable(msg);
}
/* call rpc */
}
};
- this.uci = {
-
- writable: function()
- {
- return _luci2.session.access('ubus', 'uci', 'commit');
- },
-
- add: _luci2.rpc.declare({
- object: 'uci',
- method: 'add',
- params: [ 'config', 'type', 'name', 'values' ],
- expect: { section: '' }
- }),
+ this.UCIContext = Class.extend({
- apply: function()
+ init: function()
{
-
+ this.state = {
+ newidx: 0,
+ values: { },
+ creates: { },
+ changes: { },
+ deletes: { },
+ reorder: { }
+ };
},
- configs: _luci2.rpc.declare({
+ _load: L.rpc.declare({
object: 'uci',
- method: 'configs',
- expect: { configs: [ ] }
+ method: 'get',
+ params: [ 'config' ],
+ expect: { values: { } }
}),
- _changes: _luci2.rpc.declare({
+ _order: L.rpc.declare({
object: 'uci',
- method: 'changes',
- params: [ 'config' ],
- expect: { changes: [ ] }
+ method: 'order',
+ params: [ 'config', 'sections' ]
}),
- changes: function(config)
- {
- if (typeof(config) == 'string')
- return this._changes(config);
-
- var configlist;
- return this.configs().then(function(configs) {
- _luci2.rpc.batch();
- configlist = configs;
-
- for (var i = 0; i < configs.length; i++)
- _luci2.uci._changes(configs[i]);
-
- return _luci2.rpc.flush();
- }).then(function(changes) {
- var rv = { };
-
- for (var i = 0; i < configlist.length; i++)
- if (changes[i].length)
- rv[configlist[i]] = changes[i];
-
- return rv;
- });
- },
-
- commit: _luci2.rpc.declare({
+ _add: L.rpc.declare({
object: 'uci',
- method: 'commit',
- params: [ 'config' ]
+ method: 'add',
+ params: [ 'config', 'type', 'name', 'values' ],
+ expect: { section: '' }
}),
- _delete_one: _luci2.rpc.declare({
+ _set: L.rpc.declare({
object: 'uci',
- method: 'delete',
- params: [ 'config', 'section', 'option' ]
+ method: 'set',
+ params: [ 'config', 'section', 'values' ]
}),
- _delete_multiple: _luci2.rpc.declare({
+ _delete: L.rpc.declare({
object: 'uci',
method: 'delete',
params: [ 'config', 'section', 'options' ]
}),
- 'delete': function(config, section, option)
+ _newid: function(conf)
{
- if ($.isArray(option))
- return this._delete_multiple(config, section, option);
- else
- return this._delete_one(config, section, option);
- },
+ var v = this.state.values;
+ var n = this.state.creates;
+ var sid;
- delete_all: _luci2.rpc.declare({
- object: 'uci',
- method: 'delete',
- params: [ 'config', 'type', 'match' ]
- }),
+ do {
+ sid = "new%06x".format(Math.random() * 0xFFFFFF);
+ } while ((n[conf] && n[conf][sid]) || (v[conf] && v[conf][sid]));
- _foreach: _luci2.rpc.declare({
- object: 'uci',
- method: 'get',
- params: [ 'config', 'type' ],
- expect: { values: { } }
- }),
+ return sid;
+ },
- foreach: function(config, type, cb)
+ load: function(packages)
{
- return this._foreach(config, type).then(function(sections) {
- for (var s in sections)
- cb(sections[s]);
- });
- },
+ var self = this;
+ var seen = { };
+ var pkgs = [ ];
- get: _luci2.rpc.declare({
- object: 'uci',
- method: 'get',
- params: [ 'config', 'section', 'option' ],
- expect: { '': { } },
- filter: function(data, params) {
- if (typeof(params.option) == 'undefined')
- return data.values ? data.values['.type'] : undefined;
- else
- return data.value;
- }
- }),
+ if (!$.isArray(packages))
+ packages = [ packages ];
- get_all: _luci2.rpc.declare({
- object: 'uci',
- method: 'get',
- params: [ 'config', 'section' ],
- expect: { values: { } },
- filter: function(data, params) {
- if (typeof(params.section) == 'string')
- data['.section'] = params.section;
- else if (typeof(params.config) == 'string')
- data['.package'] = params.config;
- return data;
- }
- }),
+ L.rpc.batch();
- get_first: function(config, type, option)
- {
- return this._foreach(config, type).then(function(sections) {
- for (var s in sections)
+ for (var i = 0; i < packages.length; i++)
+ if (!seen[packages[i]] && !self.state.values[packages[i]])
{
- var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
-
- if (typeof(val) != 'undefined')
- return val;
+ pkgs.push(packages[i]);
+ seen[packages[i]] = true;
+ self._load(packages[i]);
}
- return undefined;
+ return L.rpc.flush().then(function(responses) {
+ for (var i = 0; i < responses.length; i++)
+ self.state.values[pkgs[i]] = responses[i];
+
+ return pkgs;
});
},
- section: _luci2.rpc.declare({
- object: 'uci',
- method: 'add',
- params: [ 'config', 'type', 'name', 'values' ],
- expect: { section: '' }
- }),
+ unload: function(packages)
+ {
+ if (!$.isArray(packages))
+ packages = [ packages ];
- _set: _luci2.rpc.declare({
- object: 'uci',
- method: 'set',
- params: [ 'config', 'section', 'values' ]
- }),
+ for (var i = 0; i < packages.length; i++)
+ {
+ delete this.state.values[packages[i]];
+ delete this.state.creates[packages[i]];
+ delete this.state.changes[packages[i]];
+ delete this.state.deletes[packages[i]];
+ }
+ },
- set: function(config, section, option, value)
+ add: function(conf, type, name)
{
- if (typeof(value) == 'undefined' && typeof(option) == 'string')
- return this.section(config, section, option); /* option -> type */
- else if ($.isPlainObject(option))
- return this._set(config, section, option); /* option -> values */
+ var n = this.state.creates;
+ var sid = this._newid(conf);
+
+ if (!n[conf])
+ n[conf] = { };
- var values = { };
- values[option] = value;
+ n[conf][sid] = {
+ '.type': type,
+ '.name': sid,
+ '.create': name,
+ '.anonymous': !name,
+ '.index': 1000 + this.state.newidx++
+ };
- return this._set(config, section, values);
+ return sid;
},
- order: _luci2.rpc.declare({
- object: 'uci',
- method: 'order',
- params: [ 'config', 'sections' ]
- })
- };
+ remove: function(conf, sid)
+ {
+ var n = this.state.creates;
+ var c = this.state.changes;
+ var d = this.state.deletes;
- this.network = {
- listNetworkNames: function() {
- return _luci2.rpc.list('network.interface.*').then(function(list) {
- var names = [ ];
- for (var name in list)
- if (name != 'network.interface.loopback')
- names.push(name.substring(18));
- names.sort();
- return names;
- });
- },
+ /* requested deletion of a just created section */
+ if (n[conf] && n[conf][sid])
+ {
+ delete n[conf][sid];
+ }
+ else
+ {
+ if (c[conf])
+ delete c[conf][sid];
- listDeviceNames: _luci2.rpc.declare({
- object: 'network.device',
- method: 'status',
- expect: { '': { } },
- filter: function(data) {
- var names = [ ];
- for (var name in data)
- if (name != 'lo')
- names.push(name);
- names.sort();
- return names;
+ if (!d[conf])
+ d[conf] = { };
+
+ d[conf][sid] = true;
}
- }),
+ },
- getNetworkStatus: function()
+ sections: function(conf, type, cb)
{
- var nets = [ ];
- var devs = { };
-
- return this.listNetworkNames().then(function(names) {
- _luci2.rpc.batch();
+ var sa = [ ];
+ var v = this.state.values[conf];
+ var n = this.state.creates[conf];
+ var c = this.state.changes[conf];
+ var d = this.state.deletes[conf];
- for (var i = 0; i < names.length; i++)
- _luci2.network.getInterfaceStatus(names[i]);
+ if (!v)
+ return sa;
- return _luci2.rpc.flush();
- }).then(function(networks) {
- for (var i = 0; i < networks.length; i++)
- {
- var net = nets[i] = networks[i];
- var dev = net.l3_device || net.l2_device;
- if (dev)
- net.device = devs[dev] || (devs[dev] = { });
- }
+ for (var s in v)
+ if (!d || d[s] !== true)
+ if (!type || v[s]['.type'] == type)
+ sa.push($.extend({ }, v[s], c ? c[s] : undefined));
- _luci2.rpc.batch();
+ if (n)
+ for (var s in n)
+ if (!type || n[s]['.type'] == type)
+ sa.push(n[s]);
- for (var dev in devs)
- _luci2.network.getDeviceStatus(dev);
+ sa.sort(function(a, b) {
+ return a['.index'] - b['.index'];
+ });
- return _luci2.rpc.flush();
- }).then(function(devices) {
- _luci2.rpc.batch();
+ for (var i = 0; i < sa.length; i++)
+ sa[i]['.index'] = i;
- for (var i = 0; i < devices.length; i++)
- {
- var brm = devices[i]['bridge-members'];
- delete devices[i]['bridge-members'];
+ if (typeof(cb) == 'function')
+ for (var i = 0; i < sa.length; i++)
+ cb.call(this, sa[i], sa[i]['.name']);
- $.extend(devs[devices[i]['device']], devices[i]);
+ return sa;
+ },
- if (!brm)
- continue;
+ get: function(conf, sid, opt)
+ {
+ var v = this.state.values;
+ var n = this.state.creates;
+ var c = this.state.changes;
+ var d = this.state.deletes;
- devs[devices[i]['device']].subdevices = [ ];
+ if (typeof(sid) == 'undefined')
+ return undefined;
- for (var j = 0; j < brm.length; j++)
- {
- if (!devs[brm[j]])
- {
- devs[brm[j]] = { };
- _luci2.network.getDeviceStatus(brm[j]);
- }
+ /* requested option in a just created section */
+ if (n[conf] && n[conf][sid])
+ {
+ if (!n[conf])
+ return undefined;
- devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
- }
- }
+ if (typeof(opt) == 'undefined')
+ return n[conf][sid];
- return _luci2.rpc.flush();
- }).then(function(subdevices) {
- for (var i = 0; i < subdevices.length; i++)
- $.extend(devs[subdevices[i]['device']], subdevices[i]);
+ return n[conf][sid][opt];
+ }
- _luci2.rpc.batch();
+ /* requested an option value */
+ if (typeof(opt) != 'undefined')
+ {
+ /* check whether option was deleted */
+ if (d[conf] && d[conf][sid])
+ {
+ if (d[conf][sid] === true)
+ return undefined;
- for (var dev in devs)
- _luci2.wireless.getDeviceStatus(dev);
+ for (var i = 0; i < d[conf][sid].length; i++)
+ if (d[conf][sid][i] == opt)
+ return undefined;
+ }
- return _luci2.rpc.flush();
- }).then(function(wifidevices) {
- for (var i = 0; i < wifidevices.length; i++)
- if (wifidevices[i])
- devs[wifidevices[i]['device']].wireless = wifidevices[i];
+ /* check whether option was changed */
+ if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
+ return c[conf][sid][opt];
- nets.sort(function(a, b) {
- if (a['interface'] < b['interface'])
- return -1;
- else if (a['interface'] > b['interface'])
- return 1;
- else
- return 0;
- });
+ /* return base value */
+ if (v[conf] && v[conf][sid])
+ return v[conf][sid][opt];
- return nets;
- });
- },
+ return undefined;
+ }
- findWanInterfaces: function(cb)
+ /* requested an entire section */
+ if (v[conf])
+ return v[conf][sid];
+
+ return undefined;
+ },
+
+ set: function(conf, sid, opt, val)
{
- return this.listNetworkNames().then(function(names) {
- _luci2.rpc.batch();
+ var v = this.state.values;
+ var n = this.state.creates;
+ var c = this.state.changes;
+ var d = this.state.deletes;
- for (var i = 0; i < names.length; i++)
- _luci2.network.getInterfaceStatus(names[i]);
+ if (typeof(sid) == 'undefined' ||
+ typeof(opt) == 'undefined' ||
+ opt.charAt(0) == '.')
+ return;
+
+ if (n[conf] && n[conf][sid])
+ {
+ if (typeof(val) != 'undefined')
+ n[conf][sid][opt] = val;
+ else
+ delete n[conf][sid][opt];
+ }
+ else if (typeof(val) != 'undefined')
+ {
+ /* do not set within deleted section */
+ if (d[conf] && d[conf][sid] === true)
+ return;
+
+ /* only set in existing sections */
+ if (!v[conf] || !v[conf][sid])
+ return;
+
+ if (!c[conf])
+ c[conf] = { };
+
+ if (!c[conf][sid])
+ c[conf][sid] = { };
+
+ /* undelete option */
+ if (d[conf] && d[conf][sid])
+ d[conf][sid] = L.filterArray(d[conf][sid], opt);
+
+ c[conf][sid][opt] = val;
+ }
+ else
+ {
+ /* only delete in existing sections */
+ if (!v[conf] || !v[conf][sid])
+ return;
- return _luci2.rpc.flush();
- }).then(function(interfaces) {
- var rv = [ undefined, undefined ];
+ if (!d[conf])
+ d[conf] = { };
+
+ if (!d[conf][sid])
+ d[conf][sid] = [ ];
+
+ if (d[conf][sid] !== true)
+ d[conf][sid].push(opt);
+ }
+ },
+
+ unset: function(conf, sid, opt)
+ {
+ return this.set(conf, sid, opt, undefined);
+ },
+
+ _reload: function()
+ {
+ var pkgs = [ ];
+
+ for (var pkg in this.state.values)
+ pkgs.push(pkg);
+
+ this.init();
+
+ return this.load(pkgs);
+ },
+
+ _reorder: function()
+ {
+ var v = this.state.values;
+ var n = this.state.creates;
+ var r = this.state.reorder;
+
+ if ($.isEmptyObject(r))
+ return L.deferrable();
+
+ L.rpc.batch();
+
+ /*
+ gather all created and existing sections, sort them according
+ to their index value and issue an uci order call
+ */
+ for (var c in r)
+ {
+ var o = [ ];
- for (var i = 0; i < interfaces.length; i++)
+ if (n[c])
+ for (var s in n[c])
+ o.push(n[c][s]);
+
+ for (var s in v[c])
+ o.push(v[c][s]);
+
+ if (o.length > 0)
{
- if (!interfaces[i].route)
- continue;
+ o.sort(function(a, b) {
+ return (a['.index'] - b['.index']);
+ });
- for (var j = 0; j < interfaces[i].route.length; j++)
- {
- var rt = interfaces[i].route[j];
+ var sids = [ ];
- if (typeof(rt.table) != 'undefined')
- continue;
+ for (var i = 0; i < o.length; i++)
+ sids.push(o[i]['.name']);
- if (rt.target == '0.0.0.0' && rt.mask == 0)
- rv[0] = interfaces[i];
- else if (rt.target == '::' && rt.mask == 0)
- rv[1] = interfaces[i];
- }
+ this._order(c, sids);
}
+ }
- return rv;
- });
+ this.state.reorder = { };
+ return L.rpc.flush();
},
- getDHCPLeases: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'dhcp_leases',
- expect: { leases: [ ] }
- }),
+ swap: function(conf, sid1, sid2)
+ {
+ var s1 = this.get(conf, sid1);
+ var s2 = this.get(conf, sid2);
+ var n1 = s1 ? s1['.index'] : NaN;
+ var n2 = s2 ? s2['.index'] : NaN;
- getDHCPv6Leases: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'dhcp6_leases',
- expect: { leases: [ ] }
- }),
+ if (isNaN(n1) || isNaN(n2))
+ return false;
- getRoutes: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'routes',
- expect: { routes: [ ] }
- }),
+ s1['.index'] = n2;
+ s2['.index'] = n1;
- getIPv6Routes: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'routes',
- expect: { routes: [ ] }
- }),
+ this.state.reorder[conf] = true;
- getARPTable: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'arp_table',
- expect: { entries: [ ] }
- }),
+ return true;
+ },
- getInterfaceStatus: _luci2.rpc.declare({
- object: 'network.interface',
- method: 'status',
- params: [ 'interface' ],
- expect: { '': { } },
- filter: function(data, params) {
- data['interface'] = params['interface'];
- data['l2_device'] = data['device'];
- delete data['device'];
- return data;
- }
- }),
+ save: function()
+ {
+ L.rpc.batch();
- getDeviceStatus: _luci2.rpc.declare({
- object: 'network.device',
- method: 'status',
- params: [ 'name' ],
- expect: { '': { } },
- filter: function(data, params) {
- data['device'] = params['name'];
- return data;
- }
- }),
+ var v = this.state.values;
+ var n = this.state.creates;
+ var c = this.state.changes;
+ var d = this.state.deletes;
- getConntrackCount: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'conntrack_count',
- expect: { '': { count: 0, limit: 0 } }
- }),
+ var self = this;
+ var snew = [ ];
+ var pkgs = { };
- listSwitchNames: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'switch_list',
- expect: { switches: [ ] }
- }),
+ if (n)
+ for (var conf in n)
+ {
+ for (var sid in n[conf])
+ {
+ var r = {
+ config: conf,
+ values: { }
+ };
- getSwitchInfo: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'switch_info',
- params: [ 'switch' ],
- expect: { info: { } },
- filter: function(data, params) {
- data['attrs'] = data['switch'];
- data['vlan_attrs'] = data['vlan'];
- data['port_attrs'] = data['port'];
- data['switch'] = params['switch'];
+ for (var k in n[conf][sid])
+ {
+ if (k == '.type')
+ r.type = n[conf][sid][k];
+ else if (k == '.create')
+ r.name = n[conf][sid][k];
+ else if (k.charAt(0) != '.')
+ r.values[k] = n[conf][sid][k];
+ }
- delete data.vlan;
- delete data.port;
+ snew.push(n[conf][sid]);
- return data;
- }
- }),
+ self._add(r.config, r.type, r.name, r.values);
+ }
- getSwitchStatus: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'switch_status',
- params: [ 'switch' ],
- expect: { ports: [ ] }
- }),
+ pkgs[conf] = true;
+ }
+ if (c)
+ for (var conf in c)
+ {
+ for (var sid in c[conf])
+ self._set(conf, sid, c[conf][sid]);
- runPing: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'ping',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
- }),
+ pkgs[conf] = true;
+ }
- runPing6: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'ping6',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
- }),
+ if (d)
+ for (var conf in d)
+ {
+ for (var sid in d[conf])
+ {
+ var o = d[conf][sid];
+ self._delete(conf, sid, (o === true) ? undefined : o);
+ }
- runTraceroute: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'traceroute',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
- }),
+ pkgs[conf] = true;
+ }
- runTraceroute6: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'traceroute6',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
+ return L.rpc.flush().then(function(responses) {
+ /*
+ array "snew" holds references to the created uci sections,
+ use it to assign the returned names of the new sections
+ */
+ for (var i = 0; i < snew.length; i++)
+ snew[i]['.name'] = responses[i];
+
+ return self._reorder();
+ }).then(function() {
+ pkgs = L.toArray(pkgs);
+
+ self.unload(pkgs);
+
+ return self.load(pkgs);
+ });
+ },
+
+ _apply: L.rpc.declare({
+ object: 'uci',
+ method: 'apply',
+ params: [ 'timeout', 'rollback' ]
}),
- runNslookup: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'nslookup',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
+ _confirm: L.rpc.declare({
+ object: 'uci',
+ method: 'confirm'
}),
+ apply: function(timeout)
+ {
+ var self = this;
+ var date = new Date();
+ var deferred = $.Deferred();
- setUp: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'ifup',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
+ if (typeof(timeout) != 'number' || timeout < 1)
+ timeout = 10;
+
+ self._apply(timeout, true).then(function(rv) {
+ if (rv != 0)
+ {
+ deferred.rejectWith(self, [ rv ]);
+ return;
+ }
+
+ var try_deadline = date.getTime() + 1000 * timeout;
+ var try_confirm = function()
+ {
+ return self._confirm().then(function(rv) {
+ if (rv != 0)
+ {
+ if (date.getTime() < try_deadline)
+ window.setTimeout(try_confirm, 250);
+ else
+ deferred.rejectWith(self, [ rv ]);
+
+ return;
+ }
+
+ deferred.resolveWith(self, [ rv ]);
+ });
+ };
+
+ window.setTimeout(try_confirm, 1000);
+ });
+
+ return deferred;
+ },
+
+ changes: L.rpc.declare({
+ object: 'uci',
+ method: 'changes',
+ expect: { changes: { } }
}),
- setDown: _luci2.rpc.declare({
- object: 'luci2.network',
- method: 'ifdown',
- params: [ 'data' ],
- expect: { '': { code: -1 } }
- })
- };
+ readable: function(conf)
+ {
+ return L.session.hasACL('uci', conf, 'read');
+ },
+
+ writable: function(conf)
+ {
+ return L.session.hasACL('uci', conf, 'write');
+ }
+ });
+
+ this.uci = new this.UCIContext();
this.wireless = {
- listDeviceNames: _luci2.rpc.declare({
+ listDeviceNames: L.rpc.declare({
object: 'iwinfo',
method: 'devices',
expect: { 'devices': [ ] },
}
}),
- getDeviceStatus: _luci2.rpc.declare({
+ getDeviceStatus: L.rpc.declare({
object: 'iwinfo',
method: 'info',
params: [ 'device' ],
}
}),
- getAssocList: _luci2.rpc.declare({
+ getAssocList: L.rpc.declare({
object: 'iwinfo',
method: 'assoclist',
params: [ 'device' ],
getWirelessStatus: function() {
return this.listDeviceNames().then(function(names) {
- _luci2.rpc.batch();
+ L.rpc.batch();
for (var i = 0; i < names.length; i++)
- _luci2.wireless.getDeviceStatus(names[i]);
+ L.wireless.getDeviceStatus(names[i]);
- return _luci2.rpc.flush();
+ return L.rpc.flush();
}).then(function(networks) {
var rv = { };
getAssocLists: function()
{
return this.listDeviceNames().then(function(names) {
- _luci2.rpc.batch();
+ L.rpc.batch();
for (var i = 0; i < names.length; i++)
- _luci2.wireless.getAssocList(names[i]);
+ L.wireless.getAssocList(names[i]);
- return _luci2.rpc.flush();
+ return L.rpc.flush();
}).then(function(assoclists) {
var rv = [ ];
}
if (!enc || !enc.enabled)
- return _luci2.tr('None');
+ return L.tr('None');
if (enc.wep)
{
if (enc.wep.length == 2)
- return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
+ return L.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
else if (enc.wep[0] == 'shared')
- return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
+ return L.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
else
- return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
+ return L.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
}
else if (enc.wpa)
{
if (enc.wpa.length == 2)
- return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
+ return L.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
format_list(enc.authentication, '/'),
format_list(enc.ciphers, ', ')
);
);
}
- return _luci2.tr('Unknown');
- }
- };
+ return L.tr('Unknown');
+ }
+ };
+
+ this.firewall = {
+ getZoneColor: function(zone)
+ {
+ if ($.isPlainObject(zone))
+ zone = zone.name;
+
+ if (zone == 'lan')
+ return '#90f090';
+ else if (zone == 'wan')
+ return '#f09090';
+
+ for (var i = 0, hash = 0;
+ i < zone.length;
+ hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
+
+ for (var i = 0, color = '#';
+ i < 3;
+ color += ('00' + ((hash >> i++ * 8) & 0xFF).tostring(16)).slice(-2));
+
+ return color;
+ },
+
+ findZoneByNetwork: function(network)
+ {
+ var self = this;
+ var zone = undefined;
+
+ return L.uci.sections('firewall', 'zone', function(z) {
+ if (!z.name || !z.network)
+ return;
+
+ if (!$.isArray(z.network))
+ z.network = z.network.split(/\s+/);
+
+ for (var i = 0; i < z.network.length; i++)
+ {
+ if (z.network[i] == network)
+ {
+ zone = z;
+ break;
+ }
+ }
+ }).then(function() {
+ if (zone)
+ zone.color = self.getZoneColor(zone);
+
+ return zone;
+ });
+ }
+ };
+
+ this.NetworkModel = {
+ _device_blacklist: [
+ /^gre[0-9]+$/,
+ /^gretap[0-9]+$/,
+ /^ifb[0-9]+$/,
+ /^ip6tnl[0-9]+$/,
+ /^sit[0-9]+$/,
+ /^wlan[0-9]+\.sta[0-9]+$/
+ ],
+
+ _cache_functions: [
+ 'protolist', 0, L.rpc.declare({
+ object: 'network',
+ method: 'get_proto_handlers',
+ expect: { '': { } }
+ }),
+ 'ifstate', 1, L.rpc.declare({
+ object: 'network.interface',
+ method: 'dump',
+ expect: { 'interface': [ ] }
+ }),
+ 'devstate', 2, L.rpc.declare({
+ object: 'network.device',
+ method: 'status',
+ expect: { '': { } }
+ }),
+ 'wifistate', 0, L.rpc.declare({
+ object: 'network.wireless',
+ method: 'status',
+ expect: { '': { } }
+ }),
+ 'bwstate', 2, L.rpc.declare({
+ object: 'luci2.network.bwmon',
+ method: 'statistics',
+ expect: { 'statistics': { } }
+ }),
+ 'devlist', 2, L.rpc.declare({
+ object: 'luci2.network',
+ method: 'device_list',
+ expect: { 'devices': [ ] }
+ }),
+ 'swlist', 0, L.rpc.declare({
+ object: 'luci2.network',
+ method: 'switch_list',
+ expect: { 'switches': [ ] }
+ })
+ ],
+
+ _fetch_protocol: function(proto)
+ {
+ var url = L.globals.resource + '/proto/' + proto + '.js';
+ var self = L.NetworkModel;
+
+ var def = $.Deferred();
+
+ $.ajax(url, {
+ method: 'GET',
+ cache: true,
+ dataType: 'text'
+ }).then(function(data) {
+ try {
+ var protoConstructorSource = (
+ '(function(L, $) { ' +
+ 'return %s' +
+ '})(L, $);\n\n' +
+ '//@ sourceURL=%s'
+ ).format(data, url);
+
+ var protoClass = eval(protoConstructorSource);
+
+ self._protos[proto] = new protoClass();
+ }
+ catch(e) {
+ alert('Unable to instantiate proto "%s": %s'.format(url, e));
+ };
+
+ def.resolve();
+ }).fail(function() {
+ def.resolve();
+ });
+
+ return def;
+ },
+
+ _fetch_protocols: function()
+ {
+ var self = L.NetworkModel;
+ var deferreds = [
+ self._fetch_protocol('none')
+ ];
+
+ for (var proto in self._cache.protolist)
+ deferreds.push(self._fetch_protocol(proto));
+
+ return $.when.apply($, deferreds);
+ },
+
+ _fetch_swstate: L.rpc.declare({
+ object: 'luci2.network',
+ method: 'switch_info',
+ params: [ 'switch' ],
+ expect: { 'info': { } }
+ }),
+
+ _fetch_swstate_cb: function(responses) {
+ var self = L.NetworkModel;
+ var swlist = self._cache.swlist;
+ var swstate = self._cache.swstate = { };
+
+ for (var i = 0; i < responses.length; i++)
+ swstate[swlist[i]] = responses[i];
+ },
+
+ _fetch_cache_cb: function(level)
+ {
+ var self = L.NetworkModel;
+ var name = '_fetch_cache_cb_' + level;
+
+ return self[name] || (
+ self[name] = function(responses)
+ {
+ for (var i = 0; i < self._cache_functions.length; i += 3)
+ if (!level || self._cache_functions[i + 1] == level)
+ self._cache[self._cache_functions[i]] = responses.shift();
+
+ if (!level)
+ {
+ L.rpc.batch();
+
+ for (var i = 0; i < self._cache.swlist.length; i++)
+ self._fetch_swstate(self._cache.swlist[i]);
+
+ return L.rpc.flush().then(self._fetch_swstate_cb);
+ }
+
+ return L.deferrable();
+ }
+ );
+ },
+
+ _fetch_cache: function(level)
+ {
+ var self = L.NetworkModel;
+
+ return L.uci.load(['network', 'wireless']).then(function() {
+ L.rpc.batch();
+
+ for (var i = 0; i < self._cache_functions.length; i += 3)
+ if (!level || self._cache_functions[i + 1] == level)
+ self._cache_functions[i + 2]();
+
+ return L.rpc.flush().then(self._fetch_cache_cb(level || 0));
+ });
+ },
+
+ _get: function(pkg, sid, key)
+ {
+ return L.uci.get(pkg, sid, key);
+ },
+
+ _set: function(pkg, sid, key, val)
+ {
+ return L.uci.set(pkg, sid, key, val);
+ },
+
+ _is_blacklisted: function(dev)
+ {
+ for (var i = 0; i < this._device_blacklist.length; i++)
+ if (dev.match(this._device_blacklist[i]))
+ return true;
+
+ return false;
+ },
+
+ _sort_devices: function(a, b)
+ {
+ if (a.options.kind < b.options.kind)
+ return -1;
+ else if (a.options.kind > b.options.kind)
+ return 1;
+
+ if (a.options.name < b.options.name)
+ return -1;
+ else if (a.options.name > b.options.name)
+ return 1;
+
+ return 0;
+ },
+
+ _get_dev: function(ifname)
+ {
+ var alias = (ifname.charAt(0) == '@');
+ return this._devs[ifname] || (
+ this._devs[ifname] = {
+ ifname: ifname,
+ kind: alias ? 'alias' : 'ethernet',
+ type: alias ? 0 : 1,
+ up: false,
+ changed: { }
+ }
+ );
+ },
+
+ _get_iface: function(name)
+ {
+ return this._ifaces[name] || (
+ this._ifaces[name] = {
+ name: name,
+ proto: this._protos.none,
+ changed: { }
+ }
+ );
+ },
+
+ _parse_devices: function()
+ {
+ var self = L.NetworkModel;
+ var wificount = { };
+
+ for (var ifname in self._cache.devstate)
+ {
+ if (self._is_blacklisted(ifname))
+ continue;
+
+ var dev = self._cache.devstate[ifname];
+ var entry = self._get_dev(ifname);
+
+ entry.up = dev.up;
+
+ switch (dev.type)
+ {
+ case 'IP tunnel':
+ entry.kind = 'tunnel';
+ break;
+
+ case 'Bridge':
+ entry.kind = 'bridge';
+ //entry.ports = dev['bridge-members'].sort();
+ break;
+ }
+ }
+
+ for (var i = 0; i < self._cache.devlist.length; i++)
+ {
+ var dev = self._cache.devlist[i];
+
+ if (self._is_blacklisted(dev.device))
+ continue;
+
+ var entry = self._get_dev(dev.device);
+
+ entry.up = dev.is_up;
+ entry.type = dev.type;
+
+ switch (dev.type)
+ {
+ case 1: /* Ethernet */
+ if (dev.is_bridge)
+ entry.kind = 'bridge';
+ else if (dev.is_tuntap)
+ entry.kind = 'tunnel';
+ else if (dev.is_wireless)
+ entry.kind = 'wifi';
+ break;
+
+ case 512: /* PPP */
+ case 768: /* IP-IP Tunnel */
+ case 769: /* IP6-IP6 Tunnel */
+ case 776: /* IPv6-in-IPv4 */
+ case 778: /* GRE over IP */
+ entry.kind = 'tunnel';
+ break;
+ }
+ }
+
+ var net = L.uci.sections('network');
+ for (var i = 0; i < net.length; i++)
+ {
+ var s = net[i];
+ var sid = s['.name'];
+
+ if (s['.type'] == 'device' && s.name)
+ {
+ var entry = self._get_dev(s.name);
+
+ switch (s.type)
+ {
+ case 'macvlan':
+ case 'tunnel':
+ entry.kind = 'tunnel';
+ break;
+ }
+
+ entry.sid = sid;
+ }
+ else if (s['.type'] == 'interface' && !s['.anonymous'] && s.ifname)
+ {
+ var ifnames = L.toArray(s.ifname);
+
+ for (var j = 0; j < ifnames.length; j++)
+ self._get_dev(ifnames[j]);
+
+ if (s['.name'] != 'loopback')
+ {
+ var entry = self._get_dev('@%s'.format(s['.name']));
+
+ entry.type = 0;
+ entry.kind = 'alias';
+ entry.sid = sid;
+ }
+ }
+ else if (s['.type'] == 'switch_vlan' && s.device)
+ {
+ var sw = self._cache.swstate[s.device];
+ var vid = parseInt(s.vid || s.vlan);
+ var ports = L.toArray(s.ports);
+
+ if (!sw || !ports.length || isNaN(vid))
+ continue;
+
+ var ifname = undefined;
+
+ for (var j = 0; j < ports.length; j++)
+ {
+ var port = parseInt(ports[j]);
+ var tag = (ports[j].replace(/[^tu]/g, '') == 't');
+
+ if (port == sw.cpu_port)
+ {
+ // XXX: need a way to map switch to netdev
+ if (tag)
+ ifname = 'eth0.%d'.format(vid);
+ else
+ ifname = 'eth0';
+
+ break;
+ }
+ }
+
+ if (!ifname)
+ continue;
+
+ var entry = self._get_dev(ifname);
+
+ entry.kind = 'vlan';
+ entry.sid = sid;
+ entry.vsw = sw;
+ entry.vid = vid;
+ }
+ }
+
+ var wifi = L.uci.sections('wireless');
+ for (var i = 0; i < wifi.length; i++)
+ {
+ var s = wifi[i];
+ var sid = s['.name'];
+
+ if (s['.type'] == 'wifi-iface' && s.device)
+ {
+ var r = parseInt(s.device.replace(/^[^0-9]+/, ''));
+ var n = wificount[s.device] = (wificount[s.device] || 0) + 1;
+ var id = 'radio%d.network%d'.format(r, n);
+ var ifname = id;
+
+ if (self._cache.wifistate[s.device])
+ {
+ var ifcs = self._cache.wifistate[s.device].interfaces;
+ for (var ifc in ifcs)
+ {
+ if (ifcs[ifc].section == sid)
+ {
+ ifname = ifcs[ifc].ifname;
+ break;
+ }
+ }
+ }
+
+ var entry = self._get_dev(ifname);
+
+ entry.kind = 'wifi';
+ entry.sid = sid;
+ entry.wid = id;
+ entry.wdev = s.device;
+ entry.wmode = s.mode;
+ entry.wssid = s.ssid;
+ entry.wbssid = s.bssid;
+ }
+ }
+
+ for (var i = 0; i < net.length; i++)
+ {
+ var s = net[i];
+ var sid = s['.name'];
+
+ if (s['.type'] == 'interface' && !s['.anonymous'] && s.type == 'bridge')
+ {
+ var ifnames = L.toArray(s.ifname);
+
+ for (var ifname in self._devs)
+ {
+ var dev = self._devs[ifname];
+
+ if (dev.kind != 'wifi')
+ continue;
+
+ var wnets = L.toArray(L.uci.get('wireless', dev.sid, 'network'));
+ if ($.inArray(sid, wnets) > -1)
+ ifnames.push(ifname);
+ }
+
+ entry = self._get_dev('br-%s'.format(s['.name']));
+ entry.type = 1;
+ entry.kind = 'bridge';
+ entry.sid = sid;
+ entry.ports = ifnames.sort();
+ }
+ }
+ },
+
+ _parse_interfaces: function()
+ {
+ var self = L.NetworkModel;
+ var net = L.uci.sections('network');
+
+ for (var i = 0; i < net.length; i++)
+ {
+ var s = net[i];
+ var sid = s['.name'];
+
+ if (s['.type'] == 'interface' && !s['.anonymous'] && s.proto)
+ {
+ var entry = self._get_iface(s['.name']);
+ var proto = self._protos[s.proto] || self._protos.none;
+
+ var l3dev = undefined;
+ var l2dev = undefined;
+
+ var ifnames = L.toArray(s.ifname);
+
+ for (var ifname in self._devs)
+ {
+ var dev = self._devs[ifname];
+
+ if (dev.kind != 'wifi')
+ continue;
+
+ var wnets = L.toArray(L.uci.get('wireless', dev.sid, 'network'));
+ if ($.inArray(entry.name, wnets) > -1)
+ ifnames.push(ifname);
+ }
+
+ if (proto.virtual)
+ l3dev = '%s-%s'.format(s.proto, entry.name);
+ else if (s.type == 'bridge')
+ l3dev = 'br-%s'.format(entry.name);
+ else
+ l3dev = ifnames[0];
+
+ if (!proto.virtual && s.type == 'bridge')
+ l2dev = 'br-%s'.format(entry.name);
+ else if (!proto.virtual)
+ l2dev = ifnames[0];
+
+ entry.proto = proto;
+ entry.sid = sid;
+ entry.l3dev = l3dev;
+ entry.l2dev = l2dev;
+ }
+ }
+
+ for (var i = 0; i < self._cache.ifstate.length; i++)
+ {
+ var iface = self._cache.ifstate[i];
+ var entry = self._get_iface(iface['interface']);
+ var proto = self._protos[iface.proto] || self._protos.none;
+
+ /* this is a virtual interface, either deleted from config but
+ not applied yet or set up from external tools (6rd) */
+ if (!entry.sid)
+ {
+ entry.proto = proto;
+ entry.l2dev = iface.device;
+ entry.l3dev = iface.l3_device;
+ }
+ }
+ },
+
+ init: function()
+ {
+ var self = this;
+
+ if (self._cache)
+ return L.deferrable();
+
+ self._cache = { };
+ self._devs = { };
+ self._ifaces = { };
+ self._protos = { };
+
+ return self._fetch_cache()
+ .then(self._fetch_protocols)
+ .then(self._parse_devices)
+ .then(self._parse_interfaces);
+ },
+
+ update: function()
+ {
+ delete this._cache;
+ return this.init();
+ },
+
+ refreshInterfaceStatus: function()
+ {
+ return this._fetch_cache(1).then(this._parse_interfaces);
+ },
+
+ refreshDeviceStatus: function()
+ {
+ return this._fetch_cache(2).then(this._parse_devices);
+ },
+
+ refreshStatus: function()
+ {
+ return this._fetch_cache(1)
+ .then(this._fetch_cache(2))
+ .then(this._parse_devices)
+ .then(this._parse_interfaces);
+ },
+
+ getDevices: function()
+ {
+ var devs = [ ];
+
+ for (var ifname in this._devs)
+ if (ifname != 'lo')
+ devs.push(new L.NetworkModel.Device(this._devs[ifname]));
+
+ return devs.sort(this._sort_devices);
+ },
+
+ getDeviceByInterface: function(iface)
+ {
+ if (iface instanceof L.NetworkModel.Interface)
+ iface = iface.name();
+
+ if (this._ifaces[iface])
+ return this.getDevice(this._ifaces[iface].l3dev) ||
+ this.getDevice(this._ifaces[iface].l2dev);
+
+ return undefined;
+ },
+
+ getDevice: function(ifname)
+ {
+ if (this._devs[ifname])
+ return new L.NetworkModel.Device(this._devs[ifname]);
+
+ return undefined;
+ },
+
+ createDevice: function(name)
+ {
+ return new L.NetworkModel.Device(this._get_dev(name));
+ },
+
+ getInterfaces: function()
+ {
+ var ifaces = [ ];
+
+ for (var name in this._ifaces)
+ if (name != 'loopback')
+ ifaces.push(this.getInterface(name));
+
+ ifaces.sort(function(a, b) {
+ if (a.name() < b.name())
+ return -1;
+ else if (a.name() > b.name())
+ return 1;
+ else
+ return 0;
+ });
+
+ return ifaces;
+ },
+
+ getInterfacesByDevice: function(dev)
+ {
+ var ifaces = [ ];
+
+ if (dev instanceof L.NetworkModel.Device)
+ dev = dev.name();
+
+ for (var name in this._ifaces)
+ {
+ var iface = this._ifaces[name];
+ if (iface.l2dev == dev || iface.l3dev == dev)
+ ifaces.push(this.getInterface(name));
+ }
+
+ ifaces.sort(function(a, b) {
+ if (a.name() < b.name())
+ return -1;
+ else if (a.name() > b.name())
+ return 1;
+ else
+ return 0;
+ });
+
+ return ifaces;
+ },
+
+ getInterface: function(iface)
+ {
+ if (this._ifaces[iface])
+ return new L.NetworkModel.Interface(this._ifaces[iface]);
+
+ return undefined;
+ },
+
+ getProtocols: function()
+ {
+ var rv = [ ];
+
+ for (var proto in this._protos)
+ {
+ var pr = this._protos[proto];
+
+ rv.push({
+ name: proto,
+ description: pr.description,
+ virtual: pr.virtual,
+ tunnel: pr.tunnel
+ });
+ }
+
+ return rv.sort(function(a, b) {
+ if (a.name < b.name)
+ return -1;
+ else if (a.name > b.name)
+ return 1;
+ else
+ return 0;
+ });
+ },
+
+ _find_wan: function(ipaddr)
+ {
+ for (var i = 0; i < this._cache.ifstate.length; i++)
+ {
+ var ifstate = this._cache.ifstate[i];
+
+ if (!ifstate.route)
+ continue;
+
+ for (var j = 0; j < ifstate.route.length; j++)
+ if (ifstate.route[j].mask == 0 &&
+ ifstate.route[j].target == ipaddr &&
+ typeof(ifstate.route[j].table) == 'undefined')
+ {
+ return this.getInterface(ifstate['interface']);
+ }
+ }
+
+ return undefined;
+ },
+
+ findWAN: function()
+ {
+ return this._find_wan('0.0.0.0');
+ },
+
+ findWAN6: function()
+ {
+ return this._find_wan('::');
+ },
+
+ resolveAlias: function(ifname)
+ {
+ if (ifname instanceof L.NetworkModel.Device)
+ ifname = ifname.name();
+
+ var dev = this._devs[ifname];
+ var seen = { };
+
+ while (dev && dev.kind == 'alias')
+ {
+ // loop
+ if (seen[dev.ifname])
+ return undefined;
+
+ var ifc = this._ifaces[dev.sid];
+
+ seen[dev.ifname] = true;
+ dev = ifc ? this._devs[ifc.l3dev] : undefined;
+ }
+
+ return dev ? this.getDevice(dev.ifname) : undefined;
+ }
+ };
+
+ this.NetworkModel.Device = Class.extend({
+ _wifi_modes: {
+ ap: L.tr('Master'),
+ sta: L.tr('Client'),
+ adhoc: L.tr('Ad-Hoc'),
+ monitor: L.tr('Monitor'),
+ wds: L.tr('Static WDS')
+ },
+
+ _status: function(key)
+ {
+ var s = L.NetworkModel._cache.devstate[this.options.ifname];
+
+ if (s)
+ return key ? s[key] : s;
+
+ return undefined;
+ },
+
+ get: function(key)
+ {
+ var sid = this.options.sid;
+ var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
+ return L.NetworkModel._get(pkg, sid, key);
+ },
+
+ set: function(key, val)
+ {
+ var sid = this.options.sid;
+ var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
+ return L.NetworkModel._set(pkg, sid, key, val);
+ },
+
+ init: function()
+ {
+ if (typeof(this.options.type) == 'undefined')
+ this.options.type = 1;
+
+ if (typeof(this.options.kind) == 'undefined')
+ this.options.kind = 'ethernet';
+
+ if (typeof(this.options.networks) == 'undefined')
+ this.options.networks = [ ];
+ },
+
+ name: function()
+ {
+ return this.options.ifname;
+ },
+
+ description: function()
+ {
+ switch (this.options.kind)
+ {
+ case 'alias':
+ return L.tr('Alias for network "%s"').format(this.options.ifname.substring(1));
+
+ case 'bridge':
+ return L.tr('Network bridge');
+
+ case 'ethernet':
+ return L.tr('Network device');
+
+ case 'tunnel':
+ switch (this.options.type)
+ {
+ case 1: /* tuntap */
+ return L.tr('TAP device');
+
+ case 512: /* PPP */
+ return L.tr('PPP tunnel');
+
+ case 768: /* IP-IP Tunnel */
+ return L.tr('IP-in-IP tunnel');
+
+ case 769: /* IP6-IP6 Tunnel */
+ return L.tr('IPv6-in-IPv6 tunnel');
+
+ case 776: /* IPv6-in-IPv4 */
+ return L.tr('IPv6-over-IPv4 tunnel');
+ break;
+
+ case 778: /* GRE over IP */
+ return L.tr('GRE-over-IP tunnel');
+
+ default:
+ return L.tr('Tunnel device');
+ }
+
+ case 'vlan':
+ return L.tr('VLAN %d on %s').format(this.options.vid, this.options.vsw.model);
+
+ case 'wifi':
+ var o = this.options;
+ return L.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
+ o.wmode ? this._wifi_modes[o.wmode] : L.tr('Unknown mode'),
+ o.wssid || '?', o.wdev
+ );
+ }
+
+ return L.tr('Unknown device');
+ },
+
+ icon: function(up)
+ {
+ var kind = this.options.kind;
+
+ if (kind == 'alias')
+ kind = 'ethernet';
+
+ if (typeof(up) == 'undefined')
+ up = this.isUp();
+
+ return L.globals.resource + '/icons/%s%s.png'.format(kind, up ? '' : '_disabled');
+ },
+
+ isUp: function()
+ {
+ var l = L.NetworkModel._cache.devlist;
+
+ for (var i = 0; i < l.length; i++)
+ if (l[i].device == this.options.ifname)
+ return (l[i].is_up === true);
+
+ return false;
+ },
+
+ isAlias: function()
+ {
+ return (this.options.kind == 'alias');
+ },
+
+ isBridge: function()
+ {
+ return (this.options.kind == 'bridge');
+ },
+
+ isBridgeable: function()
+ {
+ return (this.options.type == 1 && this.options.kind != 'bridge');
+ },
+
+ isWireless: function()
+ {
+ return (this.options.kind == 'wifi');
+ },
+
+ isInNetwork: function(net)
+ {
+ if (!(net instanceof L.NetworkModel.Interface))
+ net = L.NetworkModel.getInterface(net);
+
+ if (net)
+ {
+ if (net.options.l3dev == this.options.ifname ||
+ net.options.l2dev == this.options.ifname)
+ return true;
+
+ var dev = L.NetworkModel._devs[net.options.l2dev];
+ if (dev && dev.kind == 'bridge' && dev.ports)
+ return ($.inArray(this.options.ifname, dev.ports) > -1);
+ }
+
+ return false;
+ },
+
+ getMTU: function()
+ {
+ var dev = L.NetworkModel._cache.devstate[this.options.ifname];
+ if (dev && !isNaN(dev.mtu))
+ return dev.mtu;
+
+ return undefined;
+ },
+
+ getMACAddress: function()
+ {
+ if (this.options.type != 1)
+ return undefined;
+
+ var dev = L.NetworkModel._cache.devstate[this.options.ifname];
+ if (dev && dev.macaddr)
+ return dev.macaddr.toUpperCase();
+
+ return undefined;
+ },
+
+ getInterfaces: function()
+ {
+ return L.NetworkModel.getInterfacesByDevice(this.options.name);
+ },
+
+ getStatistics: function()
+ {
+ var s = this._status('statistics') || { };
+ return {
+ rx_bytes: (s.rx_bytes || 0),
+ tx_bytes: (s.tx_bytes || 0),
+ rx_packets: (s.rx_packets || 0),
+ tx_packets: (s.tx_packets || 0)
+ };
+ },
+
+ getTrafficHistory: function()
+ {
+ var def = new Array(120);
+
+ for (var i = 0; i < 120; i++)
+ def[i] = 0;
+
+ var h = L.NetworkModel._cache.bwstate[this.options.ifname] || { };
+ return {
+ rx_bytes: (h.rx_bytes || def),
+ tx_bytes: (h.tx_bytes || def),
+ rx_packets: (h.rx_packets || def),
+ tx_packets: (h.tx_packets || def)
+ };
+ },
+
+ removeFromInterface: function(iface)
+ {
+ if (!(iface instanceof L.NetworkModel.Interface))
+ iface = L.NetworkModel.getInterface(iface);
+
+ if (!iface)
+ return;
+
+ var ifnames = L.toArray(iface.get('ifname'));
+ if ($.inArray(this.options.ifname, ifnames) > -1)
+ iface.set('ifname', L.filterArray(ifnames, this.options.ifname));
+
+ if (this.options.kind != 'wifi')
+ return;
+
+ var networks = L.toArray(this.get('network'));
+ if ($.inArray(iface.name(), networks) > -1)
+ this.set('network', L.filterArray(networks, iface.name()));
+ },
+
+ attachToInterface: function(iface)
+ {
+ if (!(iface instanceof L.NetworkModel.Interface))
+ iface = L.NetworkModel.getInterface(iface);
+
+ if (!iface)
+ return;
+
+ if (this.options.kind != 'wifi')
+ {
+ var ifnames = L.toArray(iface.get('ifname'));
+ if ($.inArray(this.options.ifname, ifnames) < 0)
+ {
+ ifnames.push(this.options.ifname);
+ iface.set('ifname', (ifnames.length > 1) ? ifnames : ifnames[0]);
+ }
+ }
+ else
+ {
+ var networks = L.toArray(this.get('network'));
+ if ($.inArray(iface.name(), networks) < 0)
+ {
+ networks.push(iface.name());
+ this.set('network', (networks.length > 1) ? networks : networks[0]);
+ }
+ }
+ }
+ });
+
+ this.NetworkModel.Interface = Class.extend({
+ _status: function(key)
+ {
+ var s = L.NetworkModel._cache.ifstate;
+
+ for (var i = 0; i < s.length; i++)
+ if (s[i]['interface'] == this.options.name)
+ return key ? s[i][key] : s[i];
+
+ return undefined;
+ },
+
+ get: function(key)
+ {
+ return L.NetworkModel._get('network', this.options.name, key);
+ },
+
+ set: function(key, val)
+ {
+ return L.NetworkModel._set('network', this.options.name, key, val);
+ },
+
+ name: function()
+ {
+ return this.options.name;
+ },
+
+ protocol: function()
+ {
+ return (this.get('proto') || 'none');
+ },
+
+ isUp: function()
+ {
+ return (this._status('up') === true);
+ },
+
+ isVirtual: function()
+ {
+ return (typeof(this.options.sid) != 'string');
+ },
+
+ getProtocol: function()
+ {
+ var prname = this.get('proto') || 'none';
+ return L.NetworkModel._protos[prname] || L.NetworkModel._protos.none;
+ },
+
+ getUptime: function()
+ {
+ var uptime = this._status('uptime');
+ return isNaN(uptime) ? 0 : uptime;
+ },
+
+ getDevice: function(resolveAlias)
+ {
+ if (this.options.l3dev)
+ return L.NetworkModel.getDevice(this.options.l3dev);
+
+ return undefined;
+ },
+
+ getPhysdev: function()
+ {
+ if (this.options.l2dev)
+ return L.NetworkModel.getDevice(this.options.l2dev);
+
+ return undefined;
+ },
+
+ getSubdevices: function()
+ {
+ var rv = [ ];
+ var dev = this.options.l2dev ?
+ L.NetworkModel._devs[this.options.l2dev] : undefined;
+
+ if (dev && dev.kind == 'bridge' && dev.ports && dev.ports.length)
+ for (var i = 0; i < dev.ports.length; i++)
+ rv.push(L.NetworkModel.getDevice(dev.ports[i]));
+
+ return rv;
+ },
+
+ getIPv4Addrs: function(mask)
+ {
+ var rv = [ ];
+ var addrs = this._status('ipv4-address');
+
+ if (addrs)
+ for (var i = 0; i < addrs.length; i++)
+ if (!mask)
+ rv.push(addrs[i].address);
+ else
+ rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
+
+ return rv;
+ },
+
+ getIPv6Addrs: function(mask)
+ {
+ var rv = [ ];
+ var addrs;
+
+ addrs = this._status('ipv6-address');
+
+ if (addrs)
+ for (var i = 0; i < addrs.length; i++)
+ if (!mask)
+ rv.push(addrs[i].address);
+ else
+ rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
+
+ addrs = this._status('ipv6-prefix-assignment');
+
+ if (addrs)
+ for (var i = 0; i < addrs.length; i++)
+ if (!mask)
+ rv.push('%s1'.format(addrs[i].address));
+ else
+ rv.push('%s1/%d'.format(addrs[i].address, addrs[i].mask));
+
+ return rv;
+ },
+
+ getDNSAddrs: function()
+ {
+ var rv = [ ];
+ var addrs = this._status('dns-server');
+
+ if (addrs)
+ for (var i = 0; i < addrs.length; i++)
+ rv.push(addrs[i]);
+
+ return rv;
+ },
+
+ getIPv4DNS: function()
+ {
+ var rv = [ ];
+ var dns = this._status('dns-server');
+
+ if (dns)
+ for (var i = 0; i < dns.length; i++)
+ if (dns[i].indexOf(':') == -1)
+ rv.push(dns[i]);
+
+ return rv;
+ },
+
+ getIPv6DNS: function()
+ {
+ var rv = [ ];
+ var dns = this._status('dns-server');
+
+ if (dns)
+ for (var i = 0; i < dns.length; i++)
+ if (dns[i].indexOf(':') > -1)
+ rv.push(dns[i]);
+
+ return rv;
+ },
+
+ getIPv4Gateway: function()
+ {
+ var rt = this._status('route');
+
+ if (rt)
+ for (var i = 0; i < rt.length; i++)
+ if (rt[i].target == '0.0.0.0' && rt[i].mask == 0)
+ return rt[i].nexthop;
+
+ return undefined;
+ },
+
+ getIPv6Gateway: function()
+ {
+ var rt = this._status('route');
+
+ if (rt)
+ for (var i = 0; i < rt.length; i++)
+ if (rt[i].target == '::' && rt[i].mask == 0)
+ return rt[i].nexthop;
+
+ return undefined;
+ },
+
+ getStatistics: function()
+ {
+ var dev = this.getDevice() || new L.NetworkModel.Device({});
+ return dev.getStatistics();
+ },
+
+ getTrafficHistory: function()
+ {
+ var dev = this.getDevice() || new L.NetworkModel.Device({});
+ return dev.getTrafficHistory();
+ },
+
+ setDevices: function(devs)
+ {
+ var dev = this.getPhysdev();
+ var old_devs = [ ];
+ var changed = false;
+
+ if (dev && dev.isBridge())
+ old_devs = this.getSubdevices();
+ else if (dev)
+ old_devs = [ dev ];
+
+ if (old_devs.length != devs.length)
+ changed = true;
+ else
+ for (var i = 0; i < old_devs.length; i++)
+ {
+ var dev = devs[i];
+
+ if (dev instanceof L.NetworkModel.Device)
+ dev = dev.name();
+
+ if (!dev || old_devs[i].name() != dev)
+ {
+ changed = true;
+ break;
+ }
+ }
+
+ if (changed)
+ {
+ for (var i = 0; i < old_devs.length; i++)
+ old_devs[i].removeFromInterface(this);
+
+ for (var i = 0; i < devs.length; i++)
+ {
+ var dev = devs[i];
+
+ if (!(dev instanceof L.NetworkModel.Device))
+ dev = L.NetworkModel.getDevice(dev);
+
+ if (dev)
+ dev.attachToInterface(this);
+ }
+ }
+ },
+
+ changeProtocol: function(proto)
+ {
+ var pr = L.NetworkModel._protos[proto];
+
+ if (!pr)
+ return;
+
+ for (var opt in (this.get() || { }))
+ {
+ switch (opt)
+ {
+ case 'type':
+ case 'ifname':
+ case 'macaddr':
+ if (pr.virtual)
+ this.set(opt, undefined);
+ break;
+
+ case 'auto':
+ case 'mtu':
+ break;
+
+ case 'proto':
+ this.set(opt, pr.protocol);
+ break;
+
+ default:
+ this.set(opt, undefined);
+ break;
+ }
+ }
+ },
+
+ createForm: function(mapwidget)
+ {
+ var self = this;
+ var proto = self.getProtocol();
+ var device = self.getDevice();
+
+ if (!mapwidget)
+ mapwidget = L.cbi.Map;
+
+ var map = new mapwidget('network', {
+ caption: L.tr('Configure "%s"').format(self.name())
+ });
+
+ var section = map.section(L.cbi.SingleSection, self.name(), {
+ anonymous: true
+ });
+
+ section.tab({
+ id: 'general',
+ caption: L.tr('General Settings')
+ });
+
+ section.tab({
+ id: 'advanced',
+ caption: L.tr('Advanced Settings')
+ });
+
+ section.tab({
+ id: 'ipv6',
+ caption: L.tr('IPv6')
+ });
+
+ section.tab({
+ id: 'physical',
+ caption: L.tr('Physical Settings')
+ });
+
+
+ section.taboption('general', L.cbi.CheckboxValue, 'auto', {
+ caption: L.tr('Start on boot'),
+ optional: true,
+ initial: true
+ });
+
+ var pr = section.taboption('general', L.cbi.ListValue, 'proto', {
+ caption: L.tr('Protocol')
+ });
- this.firewall = {
- getZoneColor: function(zone)
- {
- if ($.isPlainObject(zone))
- zone = zone.name;
+ pr.ucivalue = function(sid) {
+ return self.get('proto') || 'none';
+ };
- if (zone == 'lan')
- return '#90f090';
- else if (zone == 'wan')
- return '#f09090';
+ var ok = section.taboption('general', L.cbi.ButtonValue, '_confirm', {
+ caption: L.tr('Really switch?'),
+ description: L.tr('Changing the protocol will clear all configuration for this interface!'),
+ text: L.tr('Change protocol')
+ });
- for (var i = 0, hash = 0;
- i < zone.length;
- hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
+ ok.on('click', function(ev) {
+ self.changeProtocol(pr.formvalue(ev.data.sid));
+ self.createForm(mapwidget).show();
+ });
- for (var i = 0, color = '#';
- i < 3;
- color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
+ var protos = L.NetworkModel.getProtocols();
- return color;
- },
+ for (var i = 0; i < protos.length; i++)
+ pr.value(protos[i].name, protos[i].description);
- findZoneByNetwork: function(network)
- {
- var self = this;
- var zone = undefined;
+ proto.populateForm(section, self);
- return _luci2.uci.foreach('firewall', 'zone', function(z) {
- if (!z.name || !z.network)
- return;
+ if (!proto.virtual)
+ {
+ var br = section.taboption('physical', L.cbi.CheckboxValue, 'type', {
+ caption: L.tr('Network bridge'),
+ description: L.tr('Merges multiple devices into one logical bridge'),
+ optional: true,
+ enabled: 'bridge',
+ disabled: '',
+ initial: ''
+ });
- if (!$.isArray(z.network))
- z.network = z.network.split(/\s+/);
+ section.taboption('physical', L.cbi.DeviceList, '__iface_multi', {
+ caption: L.tr('Devices'),
+ multiple: true,
+ bridges: false
+ }).depends('type', true);
+
+ section.taboption('physical', L.cbi.DeviceList, '__iface_single', {
+ caption: L.tr('Device'),
+ multiple: false,
+ bridges: true
+ }).depends('type', false);
+
+ var mac = section.taboption('physical', L.cbi.InputValue, 'macaddr', {
+ caption: L.tr('Override MAC'),
+ optional: true,
+ placeholder: device ? device.getMACAddress() : undefined,
+ datatype: 'macaddr'
+ })
- for (var i = 0; i < z.network.length; i++)
+ mac.ucivalue = function(sid)
{
- if (z.network[i] == network)
- {
- zone = z;
- break;
- }
- }
- }).then(function() {
- if (zone)
- zone.color = self.getZoneColor(zone);
+ if (device)
+ return device.get('macaddr');
- return zone;
+ return this.callSuper('ucivalue', sid);
+ };
+
+ mac.save = function(sid)
+ {
+ if (!this.changed(sid))
+ return false;
+
+ if (device)
+ device.set('macaddr', this.formvalue(sid));
+ else
+ this.callSuper('set', sid);
+
+ return true;
+ };
+ }
+
+ section.taboption('physical', L.cbi.InputValue, 'mtu', {
+ caption: L.tr('Override MTU'),
+ optional: true,
+ placeholder: device ? device.getMTU() : undefined,
+ datatype: 'range(1, 9000)'
});
+
+ section.taboption('physical', L.cbi.InputValue, 'metric', {
+ caption: L.tr('Override Metric'),
+ optional: true,
+ placeholder: 0,
+ datatype: 'uinteger'
+ });
+
+ for (var field in section.fields)
+ {
+ switch (field)
+ {
+ case 'proto':
+ break;
+
+ case '_confirm':
+ for (var i = 0; i < protos.length; i++)
+ if (protos[i].name != (this.get('proto') || 'none'))
+ section.fields[field].depends('proto', protos[i].name);
+ break;
+
+ default:
+ section.fields[field].depends('proto', this.get('proto') || 'none', true);
+ break;
+ }
+ }
+
+ return map;
}
- };
+ });
+
+ this.NetworkModel.Protocol = this.NetworkModel.Interface.extend({
+ description: '__unknown__',
+ tunnel: false,
+ virtual: false,
+
+ populateForm: function(section, iface)
+ {
+
+ }
+ });
this.system = {
- getSystemInfo: _luci2.rpc.declare({
+ getSystemInfo: L.rpc.declare({
object: 'system',
method: 'info',
expect: { '': { } }
}),
- getBoardInfo: _luci2.rpc.declare({
+ getBoardInfo: L.rpc.declare({
object: 'system',
method: 'board',
expect: { '': { } }
}),
- getDiskInfo: _luci2.rpc.declare({
+ getDiskInfo: L.rpc.declare({
object: 'luci2.system',
method: 'diskfree',
expect: { '': { } }
getInfo: function(cb)
{
- _luci2.rpc.batch();
+ L.rpc.batch();
this.getSystemInfo();
this.getBoardInfo();
this.getDiskInfo();
- return _luci2.rpc.flush().then(function(info) {
+ return L.rpc.flush().then(function(info) {
var rv = { };
$.extend(rv, info[0]);
});
},
- getProcessList: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'process_list',
- expect: { processes: [ ] },
- filter: function(data) {
- data.sort(function(a, b) { return a.pid - b.pid });
- return data;
- }
- }),
-
- getSystemLog: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'syslog',
- expect: { log: '' }
- }),
-
- getKernelLog: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'dmesg',
- expect: { log: '' }
- }),
-
- getZoneInfo: function(cb)
- {
- return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
- },
-
- sendSignal: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'process_signal',
- params: [ 'pid', 'signal' ],
- filter: function(data) {
- return (data == 0);
- }
- }),
- initList: _luci2.rpc.declare({
+ initList: L.rpc.declare({
object: 'luci2.system',
method: 'init_list',
expect: { initscripts: [ ] },
});
},
- initRun: _luci2.rpc.declare({
+ initRun: L.rpc.declare({
object: 'luci2.system',
method: 'init_action',
params: [ 'name', 'action' ],
}
}),
- initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
- initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
- initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
- initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
- initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
- initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
-
-
- getRcLocal: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'rclocal_get',
- expect: { data: '' }
- }),
-
- setRcLocal: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'rclocal_set',
- params: [ 'data' ]
- }),
-
-
- getCrontab: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'crontab_get',
- expect: { data: '' }
- }),
-
- setCrontab: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'crontab_set',
- params: [ 'data' ]
- }),
-
-
- getSSHKeys: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'sshkeys_get',
- expect: { keys: [ ] }
- }),
-
- setSSHKeys: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'sshkeys_set',
- params: [ 'keys' ]
- }),
-
-
- setPassword: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'password_set',
- params: [ 'user', 'password' ]
- }),
-
-
- listLEDs: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'led_list',
- expect: { leds: [ ] }
- }),
-
- listUSBDevices: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'usb_list',
- expect: { devices: [ ] }
- }),
-
-
- testUpgrade: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'upgrade_test',
- expect: { '': { } }
- }),
-
- startUpgrade: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'upgrade_start',
- params: [ 'keep' ]
- }),
-
- cleanUpgrade: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'upgrade_clean'
- }),
-
-
- restoreBackup: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'backup_restore'
- }),
-
- cleanBackup: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'backup_clean'
- }),
-
-
- getBackupConfig: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'backup_config_get',
- expect: { config: '' }
- }),
-
- setBackupConfig: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'backup_config_set',
- params: [ 'data' ]
- }),
-
-
- listBackup: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'backup_list',
- expect: { files: [ ] }
- }),
-
-
- testReset: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'reset_test',
- expect: { supported: false }
- }),
-
- startReset: _luci2.rpc.declare({
- object: 'luci2.system',
- method: 'reset_start'
- }),
+ initStart: function(init, cb) { return L.system.initRun(init, 'start', cb) },
+ initStop: function(init, cb) { return L.system.initRun(init, 'stop', cb) },
+ initRestart: function(init, cb) { return L.system.initRun(init, 'restart', cb) },
+ initReload: function(init, cb) { return L.system.initRun(init, 'reload', cb) },
+ initEnable: function(init, cb) { return L.system.initRun(init, 'enable', cb) },
+ initDisable: function(init, cb) { return L.system.initRun(init, 'disable', cb) },
- performReboot: _luci2.rpc.declare({
+ performReboot: L.rpc.declare({
object: 'luci2.system',
method: 'reboot'
})
};
- this.opkg = {
- updateLists: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'update',
- expect: { '': { } }
- }),
-
- _allPackages: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'list',
- params: [ 'offset', 'limit', 'pattern' ],
- expect: { '': { } }
- }),
-
- _installedPackages: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'list_installed',
- params: [ 'offset', 'limit', 'pattern' ],
- expect: { '': { } }
- }),
-
- _findPackages: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'find',
- params: [ 'offset', 'limit', 'pattern' ],
- expect: { '': { } }
- }),
-
- _fetchPackages: function(action, offset, limit, pattern)
- {
- var packages = [ ];
-
- return action(offset, limit, pattern).then(function(list) {
- if (!list.total || !list.packages)
- return { length: 0, total: 0 };
-
- packages.push.apply(packages, list.packages);
- packages.total = list.total;
-
- if (limit <= 0)
- limit = list.total;
-
- if (packages.length >= limit)
- return packages;
-
- _luci2.rpc.batch();
-
- for (var i = offset + packages.length; i < limit; i += 100)
- action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
-
- return _luci2.rpc.flush();
- }).then(function(lists) {
- for (var i = 0; i < lists.length; i++)
- {
- if (!lists[i].total || !lists[i].packages)
- continue;
-
- packages.push.apply(packages, lists[i].packages);
- packages.total = lists[i].total;
- }
-
- return packages;
- });
- },
-
- listPackages: function(offset, limit, pattern)
- {
- return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
- },
-
- installedPackages: function(offset, limit, pattern)
- {
- return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
- },
-
- findPackages: function(offset, limit, pattern)
- {
- return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
- },
-
- installPackage: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'install',
- params: [ 'package' ],
- expect: { '': { } }
- }),
-
- removePackage: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'remove',
- params: [ 'package' ],
- expect: { '': { } }
- }),
-
- getConfig: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'config_get',
- expect: { config: '' }
- }),
-
- setConfig: _luci2.rpc.declare({
- object: 'luci2.opkg',
- method: 'config_set',
- params: [ 'data' ]
- })
- };
-
this.session = {
- login: _luci2.rpc.declare({
+ login: L.rpc.declare({
object: 'session',
method: 'login',
params: [ 'username', 'password' ],
expect: { '': { } }
}),
- access: _luci2.rpc.declare({
+ access: L.rpc.declare({
object: 'session',
method: 'access',
params: [ 'scope', 'object', 'function' ],
isAlive: function()
{
- return _luci2.session.access('ubus', 'session', 'access');
+ return L.session.access('ubus', 'session', 'access');
},
startHeartbeat: function()
{
this._hearbeatInterval = window.setInterval(function() {
- _luci2.session.isAlive().then(function(alive) {
+ L.session.isAlive().then(function(alive) {
if (!alive)
{
- _luci2.session.stopHeartbeat();
- _luci2.ui.login(true);
+ L.session.stopHeartbeat();
+ L.ui.login(true);
}
});
- }, _luci2.globals.timeout * 2);
+ }, L.globals.timeout * 2);
},
stopHeartbeat: function()
window.clearInterval(this._hearbeatInterval);
delete this._hearbeatInterval;
}
+ },
+
+
+ _acls: { },
+
+ _fetch_acls: L.rpc.declare({
+ object: 'session',
+ method: 'access',
+ expect: { '': { } }
+ }),
+
+ _fetch_acls_cb: function(acls)
+ {
+ L.session._acls = acls;
+ },
+
+ updateACLs: function()
+ {
+ return L.session._fetch_acls()
+ .then(L.session._fetch_acls_cb);
+ },
+
+ hasACL: function(scope, object, func)
+ {
+ var acls = L.session._acls;
+
+ if (typeof(func) == 'undefined')
+ return (acls && acls[scope] && acls[scope][object]);
+
+ if (acls && acls[scope] && acls[scope][object])
+ for (var i = 0; i < acls[scope][object].length; i++)
+ if (acls[scope][object][i] == func)
+ return true;
+
+ return false;
}
};
var win = $(window);
var body = $('body');
- var state = _luci2.ui._loading || (_luci2.ui._loading = {
+ var state = L.ui._loading || (L.ui._loading = {
modal: $('<div />')
+ .css('z-index', 2000)
.addClass('modal fade')
.append($('<div />')
.addClass('modal-dialog')
.addClass('modal-content luci2-modal-loader')
.append($('<div />')
.addClass('modal-body')
- .text(_luci2.tr('Loading data…')))))
+ .text(L.tr('Loading data…')))))
.appendTo(body)
.modal({
backdrop: 'static',
var win = $(window);
var body = $('body');
- var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
+ var state = L.ui._dialog || (L.ui._dialog = {
dialog: $('<div />')
.addClass('modal fade')
.append($('<div />')
.addClass('modal-body'))
.append($('<div />')
.addClass('modal-footer')
- .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
+ .append(L.ui.button(L.tr('Close'), 'primary')
.click(function() {
$(this).parents('div.modal').modal('hide');
})))))
{
state.dialog.modal('hide');
- return;
+ return state.dialog;
}
var cnt = state.dialog.children().children().children('div.modal-body');
var ftr = state.dialog.children().children().children('div.modal-footer');
- ftr.empty();
+ ftr.empty().show();
if (options.style == 'confirm')
{
- ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
- .click(options.confirm || function() { _luci2.ui.dialog(false) }));
+ ftr.append(L.ui.button(L.tr('Ok'), 'primary')
+ .click(options.confirm || function() { L.ui.dialog(false) }));
- ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
- .click(options.cancel || function() { _luci2.ui.dialog(false) }));
+ ftr.append(L.ui.button(L.tr('Cancel'), 'default')
+ .click(options.cancel || function() { L.ui.dialog(false) }));
}
else if (options.style == 'close')
{
- ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
- .click(options.close || function() { _luci2.ui.dialog(false) }));
+ ftr.append(L.ui.button(L.tr('Close'), 'primary')
+ .click(options.close || function() { L.ui.dialog(false) }));
}
else if (options.style == 'wait')
{
- ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
+ ftr.append(L.ui.button(L.tr('Close'), 'primary')
.attr('disabled', true));
}
+ if (options.wide)
+ {
+ state.dialog.addClass('wide');
+ }
+ else
+ {
+ state.dialog.removeClass('wide');
+ }
+
state.dialog.find('h4:first').text(title);
state.dialog.modal('show');
cnt.empty().append(content);
+
+ return state.dialog;
},
upload: function(title, content, options)
{
- var state = _luci2.ui._upload || (_luci2.ui._upload = {
+ var state = L.ui._upload || (L.ui._upload = {
form: $('<form />')
.attr('method', 'post')
.attr('action', '/cgi-bin/luci-upload')
json = $.parseJSON(body.innerHTML);
} catch(e) {
json = {
- message: _luci2.tr('Invalid server response received'),
- error: [ -1, _luci2.tr('Invalid data') ]
+ message: L.tr('Invalid server response received'),
+ error: [ -1, L.tr('Invalid data') ]
};
};
if (json.error)
{
L.ui.dialog(L.tr('File upload'), [
- $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
+ $('<p />').text(L.tr('The file upload failed with the server response below:')),
$('<pre />').addClass('alert-message').text(json.message || json.error[1]),
- $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
+ $('<p />').text(L.tr('In case of network problems try uploading the file again.'))
], { style: 'close' });
}
else if (typeof(state.success_cb) == 'function')
f.hide();
b.show();
- p.text(_luci2.tr('File upload in progress …'));
+ p.text(L.tr('File upload in progress …'));
state.form.parent().parent().find('button').prop('disabled', true);
}
state.form.find('.progress').hide();
state.form.find('.cbi-input-file').val('').show();
- state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
+ state.form.find('p').text(content || L.tr('Select the file to upload and press "%s" to proceed.').format(L.tr('Ok')));
- state.form.find('[name=sessionid]').val(_luci2.globals.sid);
+ state.form.find('[name=sessionid]').val(L.globals.sid);
state.form.find('[name=filename]').val(options.filename);
state.success_cb = options.success;
- _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
+ L.ui.dialog(title || L.tr('File upload'), state.form, {
style: 'confirm',
confirm: state.confirm_cb
});
var images = $();
var interval, timeout;
- _luci2.ui.dialog(
- _luci2.tr('Waiting for device'), [
- $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
+ L.ui.dialog(
+ L.tr('Waiting for device'), [
+ $('<p />').text(L.tr('Please stand by while the device is reconfiguring …')),
$('<div />')
.css('width', '100%')
.addClass('progressbar')
for (var i = 0; i < protocols.length; i++)
images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
- //_luci2.network.getNetworkStatus(function(s) {
+ //L.network.getNetworkStatus(function(s) {
// for (var i = 0; i < protocols.length; i++)
// {
// for (var j = 0; j < s.length; j++)
//}).then(function() {
images.on('load', function() {
var url = this.getAttribute('url');
- _luci2.session.isAlive().then(function(access) {
+ L.session.isAlive().then(function(access) {
if (access)
{
window.clearTimeout(timeout);
window.clearInterval(interval);
- _luci2.ui.dialog(false);
+ L.ui.dialog(false);
images = null;
}
else
interval = window.setInterval(function() {
images.each(function() {
- this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
+ this.setAttribute('src', this.getAttribute('url') + L.globals.resource + '/icons/loading.gif?r=' + Math.random());
});
}, 5000);
window.clearInterval(interval);
images.off('load');
- _luci2.ui.dialog(
- _luci2.tr('Device not responding'),
- _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
+ L.ui.dialog(
+ L.tr('Device not responding'),
+ L.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
{ style: 'close' }
);
}, 180000);
login: function(invalid)
{
- var state = _luci2.ui._login || (_luci2.ui._login = {
+ var state = L.ui._login || (L.ui._login = {
form: $('<form />')
.attr('target', '')
.attr('method', 'post')
.append($('<p />')
.addClass('alert-message')
- .text(_luci2.tr('Wrong username or password given!')))
+ .text(L.tr('Wrong username or password given!')))
.append($('<p />')
.append($('<label />')
- .text(_luci2.tr('Username'))
+ .text(L.tr('Username'))
.append($('<br />'))
.append($('<input />')
.attr('type', 'text')
}))))
.append($('<p />')
.append($('<label />')
- .text(_luci2.tr('Password'))
+ .text(L.tr('Password'))
.append($('<br />'))
.append($('<input />')
.attr('type', 'password')
state.confirm_cb();
}))))
.append($('<p />')
- .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
+ .text(L.tr('Enter your username and password above, then click "%s" to proceed.').format(L.tr('Ok')))),
response_cb: function(response) {
if (!response.ubus_rpc_session)
{
- _luci2.ui.login(true);
+ L.ui.login(true);
}
else
{
- _luci2.globals.sid = response.ubus_rpc_session;
- _luci2.setHash('id', _luci2.globals.sid);
- _luci2.session.startHeartbeat();
- _luci2.ui.dialog(false);
+ L.globals.sid = response.ubus_rpc_session;
+ L.setHash('id', L.globals.sid);
+ L.session.startHeartbeat();
+ L.ui.dialog(false);
state.deferred.resolve();
}
},
if (!u)
return;
- _luci2.ui.dialog(
- _luci2.tr('Logging in'), [
- $('<p />').text(_luci2.tr('Log in in progress …')),
+ L.ui.dialog(
+ L.tr('Logging in'), [
+ $('<p />').text(L.tr('Log in in progress …')),
$('<div />')
.css('width', '100%')
.addClass('progressbar')
], { style: 'wait' }
);
- _luci2.globals.sid = '00000000000000000000000000000000';
- _luci2.session.login(u, p).then(state.response_cb);
+ L.globals.sid = '00000000000000000000000000000000';
+ L.session.login(u, p).then(state.response_cb);
}
});
state.deferred = $.Deferred();
/* try to find sid from hash */
- var sid = _luci2.getHash('id');
+ var sid = L.getHash('id');
if (sid && sid.match(/^[a-f0-9]{32}$/))
{
- _luci2.globals.sid = sid;
- _luci2.session.isAlive().then(function(access) {
+ L.globals.sid = sid;
+ L.session.isAlive().then(function(access) {
if (access)
{
- _luci2.session.startHeartbeat();
+ L.session.startHeartbeat();
state.deferred.resolve();
}
else
{
- _luci2.setHash('id', undefined);
- _luci2.ui.login();
+ L.setHash('id', undefined);
+ L.ui.login();
}
});
else
state.form.find('.alert-message').hide();
- _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
+ L.ui.dialog(L.tr('Authorization Required'), state.form, {
style: 'confirm',
confirm: state.confirm_cb
});
return state.deferred;
},
- cryptPassword: _luci2.rpc.declare({
+ cryptPassword: L.rpc.declare({
object: 'luci2.ui',
method: 'crypt',
params: [ 'data' ],
}
},
- listAvailableACLs: _luci2.rpc.declare({
+ listAvailableACLs: L.rpc.declare({
object: 'luci2.ui',
method: 'acls',
expect: { acls: [ ] },
filter: function(trees) {
var acl_tree = { };
for (var i = 0; i < trees.length; i++)
- _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
+ L.ui._acl_merge_tree(acl_tree, trees[i]);
return acl_tree;
}
}),
- renderMainMenu: _luci2.rpc.declare({
+ _render_change_indicator: function()
+ {
+ return $('<ul />')
+ .addClass('nav navbar-nav navbar-right')
+ .append($('<li />')
+ .append($('<a />')
+ .attr('id', 'changes')
+ .attr('href', '#')
+ .append($('<span />')
+ .addClass('label label-info'))));
+ },
+
+ renderMainMenu: L.rpc.declare({
object: 'luci2.ui',
method: 'menu',
expect: { menu: { } },
filter: function(entries) {
- _luci2.globals.mainMenu = new _luci2.ui.menu();
- _luci2.globals.mainMenu.entries(entries);
+ L.globals.mainMenu = new L.ui.menu();
+ L.globals.mainMenu.entries(entries);
$('#mainmenu')
.empty()
- .append(_luci2.globals.mainMenu.render(0, 1));
+ .append(L.globals.mainMenu.render(0, 1))
+ .append(L.ui._render_change_indicator());
}
}),
{
$('#viewmenu')
.empty()
- .append(_luci2.globals.mainMenu.render(2, 900));
+ .append(L.globals.mainMenu.render(2, 900));
},
renderView: function()
{
- var node = arguments[0];
- var name = node.view.split(/\//).join('.');
- var args = [ ];
+ var node = arguments[0];
+ var name = node.view.split(/\//).join('.');
+ var cname = L.toClassName(name);
+ var views = L.views || (L.views = { });
+ var args = [ ];
for (var i = 1; i < arguments.length; i++)
args.push(arguments[i]);
- if (_luci2.globals.currentView)
- _luci2.globals.currentView.finish();
-
- _luci2.ui.renderViewMenu();
-
- if (!_luci2._views)
- _luci2._views = { };
+ if (L.globals.currentView)
+ L.globals.currentView.finish();
- _luci2.setHash('view', node.view);
+ L.ui.renderViewMenu();
+ L.setHash('view', node.view);
- if (_luci2._views[name] instanceof _luci2.ui.view)
+ if (views[cname] instanceof L.ui.view)
{
- _luci2.globals.currentView = _luci2._views[name];
- return _luci2._views[name].render.apply(_luci2._views[name], args);
+ L.globals.currentView = views[cname];
+ return views[cname].render.apply(views[cname], args);
}
- var url = _luci2.globals.resource + '/view/' + name + '.js';
+ var url = L.globals.resource + '/view/' + name + '.js';
return $.ajax(url, {
method: 'GET',
var viewConstructorSource = (
'(function(L, $) { ' +
'return %s' +
- '})(_luci2, $);\n\n' +
+ '})(L, $);\n\n' +
'//@ sourceURL=%s'
).format(data, url);
var viewConstructor = eval(viewConstructorSource);
- _luci2._views[name] = new viewConstructor({
+ views[cname] = new viewConstructor({
name: name,
acls: node.write || { }
});
- _luci2.globals.currentView = _luci2._views[name];
- return _luci2._views[name].render.apply(_luci2._views[name], args);
+ L.globals.currentView = views[cname];
+ return views[cname].render.apply(views[cname], args);
}
catch(e) {
alert('Unable to instantiate view "%s": %s'.format(url, e));
});
},
+ changeView: function()
+ {
+ var name = L.getHash('view');
+ var node = L.globals.defaultNode;
+
+ if (name && L.globals.mainMenu)
+ node = L.globals.mainMenu.getNode(name);
+
+ if (node)
+ {
+ L.ui.loading(true);
+ L.ui.renderView(node).then(function() {
+ L.ui.loading(false);
+ });
+ }
+ },
+
updateHostname: function()
{
- return _luci2.system.getBoardInfo().then(function(info) {
+ return L.system.getBoardInfo().then(function(info) {
if (info.hostname)
$('#hostname').text(info.hostname);
});
updateChanges: function()
{
- return _luci2.uci.changes().then(function(changes) {
+ return L.uci.changes().then(function(changes) {
var n = 0;
var html = '';
switch (c[0])
{
case 'order':
+ log.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
break;
case 'remove':
if (n > 0)
$('#changes')
- .empty()
- .show()
- .append($('<a />')
- .attr('href', '#')
- .addClass('label')
- .addClass('notice')
- .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
- .click(function(ev) {
- _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
- ev.preventDefault();
- }));
+ .click(function(ev) {
+ L.ui.dialog(L.tr('Staged configuration changes'), html, {
+ style: 'confirm',
+ confirm: function() {
+ L.uci.apply().then(
+ function(code) { alert('Success with code ' + code); },
+ function(code) { alert('Error with code ' + code); }
+ );
+ }
+ });
+ ev.preventDefault();
+ })
+ .children('span')
+ .show()
+ .text(L.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n));
else
- $('#changes')
- .hide();
+ $('#changes').children('span').hide();
});
},
init: function()
{
- _luci2.ui.loading(true);
+ L.ui.loading(true);
$.when(
- _luci2.ui.updateHostname(),
- _luci2.ui.updateChanges(),
- _luci2.ui.renderMainMenu()
+ L.session.updateACLs(),
+ L.ui.updateHostname(),
+ L.ui.updateChanges(),
+ L.ui.renderMainMenu(),
+ L.NetworkModel.init()
).then(function() {
- _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
- _luci2.ui.loading(false);
- })
+ L.ui.renderView(L.globals.defaultNode).then(function() {
+ L.ui.loading(false);
+ });
+
+ $(window).on('hashchange', function() {
+ L.ui.changeView();
+ });
});
},
appendTo: function(id) {
return $(id).append(this.render());
+ },
+
+ on: function(evname, evfunc)
+ {
+ var evnames = L.toArray(evname);
+
+ if (!this.events)
+ this.events = { };
+
+ for (var i = 0; i < evnames.length; i++)
+ this.events[evnames[i]] = evfunc;
+
+ return this;
+ },
+
+ trigger: function(evname, evdata)
+ {
+ if (this.events)
+ {
+ var evnames = L.toArray(evname);
+
+ for (var i = 0; i < evnames.length; i++)
+ if (this.events[evnames[i]])
+ this.events[evnames[i]].call(this, evdata);
+ }
+
+ return this;
}
});
this.ui.view = this.ui.AbstractWidget.extend({
_fetch_template: function()
{
- return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
+ return $.ajax(L.globals.resource + '/template/' + this.options.name + '.htm', {
method: 'GET',
cache: true,
dataType: 'text',
return '';
case ':':
- return _luci2.tr(p2);
+ return L.tr(p2);
case '=':
- return _luci2.globals[p2] || '';
+ return L.globals[p2] || '';
default:
return '(?' + match + ')';
args.push(arguments[i]);
return this._fetch_template().then(function() {
- return _luci2.deferrable(self.execute.apply(self, args));
+ return L.deferrable(self.execute.apply(self, args));
});
},
};
runTimer = function() {
- _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
+ L.deferrable(func.call(self)).then(setTimer, setTimer);
};
runTimer();
_onclick: function(ev)
{
- _luci2.ui.loading(true);
- _luci2.ui.renderView(ev.data).then(function() {
- _luci2.ui.loading(false);
- });
+ L.setHash('view', ev.data);
ev.preventDefault();
this.blur();
for (var i = 0; i < nodes.length; i++)
{
- if (!_luci2.globals.defaultNode)
+ if (!L.globals.defaultNode)
{
- var v = _luci2.getHash('view');
+ var v = L.getHash('view');
if (!v || v == nodes[i].view)
- _luci2.globals.defaultNode = nodes[i];
+ L.globals.defaultNode = nodes[i];
}
var item = $('<li />')
.append($('<a />')
.attr('href', '#')
- .text(_luci2.tr(nodes[i].title)))
+ .text(L.tr(nodes[i].title)))
.appendTo(list);
if (nodes[i].childs && level < max)
}
else
{
- item.find('a').click(nodes[i], this._onclick);
+ item.find('a').click(nodes[i].view, this._onclick);
}
}
render: function(min, max)
{
- var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
+ var top = min ? this.getNode(L.globals.defaultNode.view, min) : this._nodes;
return this._render(top.childs, 0, min, max);
},
}
span.appendChild(document.createElement('img'));
- span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
+ span.lastChild.src = L.globals.resource + '/icons/signal-' + r + '.png';
if (r == 'none')
- span.title = _luci2.tr('No signal');
+ span.title = L.tr('No signal');
else
span.title = '%s: %d %s / %s: %d %s'.format(
- _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
- _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
+ L.tr('Signal'), this.options.signal, L.tr('dBm'),
+ L.tr('Noise'), this.options.noise, L.tr('dBm')
);
}
else
{
var type = 'ethernet';
- var desc = _luci2.tr('Ethernet device');
+ var desc = L.tr('Ethernet device');
if (l3dev != l2dev)
{
type = 'tunnel';
- desc = _luci2.tr('Tunnel interface');
+ desc = L.tr('Tunnel interface');
}
else if (dev.indexOf('br-') == 0)
{
type = 'bridge';
- desc = _luci2.tr('Bridge');
+ desc = L.tr('Bridge');
}
else if (dev.indexOf('.') > 0)
{
type = 'vlan';
- desc = _luci2.tr('VLAN interface');
+ desc = L.tr('VLAN interface');
}
else if (dev.indexOf('wlan') == 0 ||
dev.indexOf('ath') == 0 ||
dev.indexOf('wl') == 0)
{
type = 'wifi';
- desc = _luci2.tr('Wireless Network');
+ desc = L.tr('Wireless Network');
}
span.appendChild(document.createElement('img'));
- span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
+ span.lastChild.src = L.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
span.title = desc;
}
validation: {
i18n: function(msg)
{
- _luci2.cbi.validation.message = _luci2.tr(msg);
+ L.cbi.validation.message = L.tr(msg);
},
compile: function(code)
var pos = 0;
var esc = false;
var depth = 0;
- var types = _luci2.cbi.validation.types;
+ var types = L.cbi.validation.types;
var stack = [ ];
code += ',';
throw "Syntax error, argument list follows non-function";
stack[stack.length-1] =
- _luci2.cbi.validation.compile(code.substring(pos, i));
+ L.cbi.validation.compile(code.substring(pos, i));
pos = i+1;
}
msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
}
- validation.message = msgs.join( _luci2.tr(' - or - '));
+ validation.message = msgs.join( L.tr(' - or - '));
return false;
},
this.dependencies = [ ];
this.rdependency = { };
- this.options = _luci2.defaults(options, {
+ this.options = L.defaults(options, {
placeholder: '',
datatype: 'string',
optional: false,
return i.top;
},
+ active: function(sid)
+ {
+ return (this.instance[sid] && !this.instance[sid].disabled);
+ },
+
ucipath: function(sid)
{
return {
return this.choices[i][1];
}
else if (v === true)
- return _luci2.tr('yes');
+ return L.tr('yes');
else if (v === false)
- return _luci2.tr('no');
+ return L.tr('no');
else if ($.isArray(v))
return v.join(', ');
d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
- d.inst.error.text(_luci2.tr('Field must not be empty')).show();
+ d.inst.error.text(L.tr('Field must not be empty')).show();
rv = false;
}
else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
}
if (rv)
+ {
for (var field in d.self.rdependency)
d.self.rdependency[field].toggle(d.sid);
+ d.self.section.tabtoggle(d.sid);
+ }
+
return rv;
},
validator: function(sid, elem, multi)
{
+ var evdata = {
+ self: this,
+ sid: sid,
+ elem: elem,
+ multi: multi,
+ inst: this.instance[sid],
+ opt: this.options.optional
+ };
+
+ if (this.events)
+ for (var evname in this.events)
+ elem.on(evname, evdata, this.events[evname]);
+
if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
return elem;
if (typeof(this.options.datatype) == 'string')
{
try {
- vstack = _luci2.cbi.validation.compile(this.options.datatype);
+ evdata.vstack = L.cbi.validation.compile(this.options.datatype);
} catch(e) { };
}
else if (typeof(this.options.datatype) == 'function')
{
var vfunc = this.options.datatype;
- vstack = [ function(elem) {
+ evdata.vstack = [ function(elem) {
var rv = vfunc(this, elem);
if (rv !== true)
validation.message = rv;
}, [ elem ] ];
}
- var evdata = {
- self: this,
- sid: sid,
- elem: elem,
- multi: multi,
- vstack: vstack,
- inst: this.instance[sid],
- opt: this.options.optional
- };
-
if (elem.prop('tagName') == 'SELECT')
{
elem.change(evdata, this._ev_validate);
return (i.disabled || i.error.text() == '');
},
- depends: function(d, v)
+ depends: function(d, v, add)
{
var dep;
{
if (typeof(d[i]) == 'string')
dep[d[i]] = true;
- else if (d[i] instanceof _luci2.cbi.AbstractValue)
+ else if (d[i] instanceof L.cbi.AbstractValue)
dep[d[i].name] = true;
}
}
- else if (d instanceof _luci2.cbi.AbstractValue)
+ else if (d instanceof L.cbi.AbstractValue)
{
dep = { };
dep[d.name] = (typeof(v) == 'undefined') ? true : v;
if ($.isEmptyObject(dep))
return this;
- this.dependencies.push(dep);
+ if (!add || !this.dependencies.length)
+ this.dependencies.push(dep);
+ else
+ for (var i = 0; i < this.dependencies.length; i++)
+ $.extend(this.dependencies[i], dep);
return this;
},
break;
}
}
- else if (typeof(cmp) == 'string')
+ else if (typeof(cmp) == 'string' || typeof(cmp) == 'number')
{
if (val != cmp)
{
var t = $('<span />')
.addClass('input-group-btn')
- .append(_luci2.ui.button(_luci2.tr('Reveal'), 'default')
+ .append(L.ui.button(L.tr('Reveal'), 'default')
.click(function(ev) {
var b = $(this);
var i = b.parent().prev();
var t = i.attr('type');
- b.text(t == 'password' ? _luci2.tr('Hide') : _luci2.tr('Reveal'));
+ b.text(t == 'password' ? L.tr('Hide') : L.tr('Reveal'));
i.attr('type', (t == 'password') ? 'text' : 'password');
b = i = t = null;
}));
var s = $('<select />')
.addClass('form-control');
- if (this.options.optional)
+ if (this.options.optional && !this.has_empty)
$('<option />')
.attr('value', '')
- .text(_luci2.tr('-- Please choose --'))
+ .text(L.tr('-- Please choose --'))
.appendTo(s);
if (this.choices)
if (!this.choices)
this.choices = [ ];
+ if (k == '')
+ this.has_empty = true;
+
this.choices.push([k, v || k]);
return this;
}
{
ev.data.select.hide();
ev.data.input.show().focus();
-
- var v = ev.data.input.val();
- ev.data.input.val(' ');
- ev.data.input.val(v);
+ ev.data.input.val('');
}
else if (self.options.optional && s.selectedIndex == 0)
{
{
ev.data.input.val(ev.data.select.val());
}
+
+ ev.stopPropagation();
},
_blur: function(ev)
ev.data.select.empty();
- if (self.options.optional)
+ if (self.options.optional && !self.has_empty)
$('<option />')
.attr('value', '')
- .text(_luci2.tr('-- please choose --'))
+ .text(L.tr('-- please choose --'))
.appendTo(ev.data.select);
if (self.choices)
$('<option />')
.attr('value', ' ')
- .text(_luci2.tr('-- custom --'))
+ .text(L.tr('-- custom --'))
.appendTo(ev.data.select);
ev.data.input.hide();
- ev.data.select.val(val).show().focus();
+ ev.data.select.val(val).show().blur();
},
_enter: function(ev)
.attr('id', this.id(sid));
var t = $('<input />')
+ .addClass('form-control')
.attr('type', 'text')
.hide()
.appendTo(d);
var s = $('<select />')
+ .addClass('form-control')
.appendTo(d);
var evdata = {
self: this,
- input: this.validator(sid, t),
- select: this.validator(sid, s)
+ input: t,
+ select: s
};
s.change(evdata, this._change);
t.val(this.ucivalue(sid));
t.blur();
+ this.validator(sid, t);
+ this.validator(sid, s);
+
return d;
},
if (!this.choices)
this.choices = [ ];
+ if (k == '')
+ this.has_empty = true;
+
this.choices.push([k, v || k]);
return this;
},
var btn;
if (evdata.remove)
- btn = _luci2.ui.button('–', 'danger').click(evdata, this._btnclick);
+ btn = L.ui.button('–', 'danger').click(evdata, this._btnclick);
else
- btn = _luci2.ui.button('+', 'success').click(evdata, this._btnclick);
+ btn = L.ui.button('+', 'success').click(evdata, this._btnclick);
if (this.choices)
{
formvalue: function(sid)
{
var rv = [ ];
- var fields = $('#' + this.id(sid) + ' > input');
+ var fields = $('#' + this.id(sid) + ' input');
for (var i = 0; i < fields.length; i++)
if (typeof(fields[i].value) == 'string' && fields[i].value.length)
}
});
- this.cbi.NetworkList = this.cbi.AbstractValue.extend({
- load: function(sid)
+ this.cbi.ButtonValue = this.cbi.AbstractValue.extend({
+ widget: function(sid)
{
- var self = this;
+ this.options.optional = true;
- if (!self.interfaces)
- {
- self.interfaces = [ ];
- return _luci2.network.getNetworkStatus().then(function(ifaces) {
- self.interfaces = ifaces;
- self = null;
- });
- }
+ var btn = $('<button />')
+ .addClass('btn btn-default')
+ .attr('id', this.id(sid))
+ .attr('type', 'button')
+ .text(this.label('text'));
- return undefined;
+ return this.validator(sid, btn);
+ }
+ });
+
+ this.cbi.NetworkList = this.cbi.AbstractValue.extend({
+ load: function(sid)
+ {
+ return L.NetworkModel.init();
},
_device_icon: function(dev)
{
- var type = 'ethernet';
- var desc = _luci2.tr('Ethernet device');
-
- if (dev.type == 'IP tunnel')
- {
- type = 'tunnel';
- desc = _luci2.tr('Tunnel interface');
- }
- else if (dev['bridge-members'])
- {
- type = 'bridge';
- desc = _luci2.tr('Bridge');
- }
- else if (dev.wireless)
- {
- type = 'wifi';
- desc = _luci2.tr('Wireless Network');
- }
- else if (dev.device.indexOf('.') > 0)
- {
- type = 'vlan';
- desc = _luci2.tr('VLAN interface');
- }
-
return $('<img />')
- .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
- .attr('title', '%s (%s)'.format(desc, dev.device));
+ .attr('src', dev.icon())
+ .attr('title', '%s (%s)'.format(dev.description(), dev.name() || '?'));
},
widget: function(sid)
for (var i = 0; i < value.length; i++)
check[value[i]] = true;
- if (this.interfaces)
- {
- for (var i = 0; i < this.interfaces.length; i++)
- {
- var iface = this.interfaces[i];
- var badge = $('<span />')
- .addClass('badge')
- .text('%s: '.format(iface['interface']));
+ var interfaces = L.NetworkModel.getInterfaces();
- if (iface.device && iface.device.subdevices)
- for (var j = 0; j < iface.device.subdevices.length; j++)
- badge.append(this._device_icon(iface.device.subdevices[j]));
- else if (iface.device)
- badge.append(this._device_icon(iface.device));
- else
- badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
+ for (var i = 0; i < interfaces.length; i++)
+ {
+ var iface = interfaces[i];
+ var badge = $('<span />')
+ .addClass('badge')
+ .text('%s: '.format(iface.name()));
+
+ var dev = iface.getDevice();
+ var subdevs = iface.getSubdevices();
+
+ if (subdevs.length)
+ for (var j = 0; j < subdevs.length; j++)
+ badge.append(this._device_icon(subdevs[j]));
+ else if (dev)
+ badge.append(this._device_icon(dev));
+ else
+ badge.append($('<em />').text(L.tr('(No devices attached)')));
- $('<li />')
- .append($('<label />')
- .addClass(itype + ' inline')
- .append($('<input />')
- .attr('name', itype + id)
- .attr('type', itype)
- .attr('value', iface['interface'])
- .prop('checked', !!check[iface['interface']]))
- .append(badge))
- .appendTo(ul);
- }
+ $('<li />')
+ .append($('<label />')
+ .addClass(itype + ' inline')
+ .append($('<input />')
+ .attr('name', itype + id)
+ .attr('type', itype)
+ .attr('value', iface.name())
+ .prop('checked', !!check[iface.name()]))
+ .append(badge))
+ .appendTo(ul);
}
if (!this.options.multiple)
.attr('name', itype + id)
.attr('type', itype)
.attr('value', '')
- .prop('checked', !value))
- .append(_luci2.tr('unspecified')))
+ .prop('checked', $.isEmptyObject(check)))
+ .append(L.tr('unspecified')))
.appendTo(ul);
}
}
});
+ this.cbi.DeviceList = this.cbi.NetworkList.extend({
+ _ev_focus: function(ev)
+ {
+ var self = ev.data.self;
+ var input = $(this);
+
+ input.parent().prev().prop('checked', true);
+ },
+
+ _ev_blur: function(ev)
+ {
+ ev.which = 10;
+ ev.data.self._ev_keydown.call(this, ev);
+ },
+
+ _ev_keydown: function(ev)
+ {
+ if (ev.which != 10 && ev.which != 13)
+ return;
+
+ var sid = ev.data.sid;
+ var self = ev.data.self;
+ var input = $(this);
+ var ifnames = L.toArray(input.val());
+
+ if (!ifnames.length)
+ return;
+
+ L.NetworkModel.createDevice(ifnames[0]);
+
+ self._redraw(sid, $('#' + self.id(sid)), ifnames[0]);
+ },
+
+ load: function(sid)
+ {
+ return L.NetworkModel.init();
+ },
+
+ _redraw: function(sid, ul, sel)
+ {
+ var id = ul.attr('id');
+ var devs = L.NetworkModel.getDevices();
+ var iface = L.NetworkModel.getInterface(sid);
+ var itype = this.options.multiple ? 'checkbox' : 'radio';
+ var check = { };
+
+ if (!sel)
+ {
+ for (var i = 0; i < devs.length; i++)
+ if (devs[i].isInNetwork(iface))
+ check[devs[i].name()] = true;
+ }
+ else
+ {
+ if (this.options.multiple)
+ check = L.toObject(this.formvalue(sid));
+
+ check[sel] = true;
+ }
+
+ ul.empty();
+
+ for (var i = 0; i < devs.length; i++)
+ {
+ var dev = devs[i];
+
+ if (dev.isBridge() && this.options.bridges === false)
+ continue;
+
+ if (!dev.isBridgeable() && this.options.multiple)
+ continue;
+
+ var badge = $('<span />')
+ .addClass('badge')
+ .append($('<img />').attr('src', dev.icon()))
+ .append(' %s: %s'.format(dev.name(), dev.description()));
+
+ //var ifcs = dev.getInterfaces();
+ //if (ifcs.length)
+ //{
+ // for (var j = 0; j < ifcs.length; j++)
+ // badge.append((j ? ', ' : ' (') + ifcs[j].name());
+ //
+ // badge.append(')');
+ //}
+
+ $('<li />')
+ .append($('<label />')
+ .addClass(itype + ' inline')
+ .append($('<input />')
+ .attr('name', itype + id)
+ .attr('type', itype)
+ .attr('value', dev.name())
+ .prop('checked', !!check[dev.name()]))
+ .append(badge))
+ .appendTo(ul);
+ }
+
+
+ $('<li />')
+ .append($('<label />')
+ .attr('for', 'custom' + id)
+ .addClass(itype + ' inline')
+ .append($('<input />')
+ .attr('name', itype + id)
+ .attr('type', itype)
+ .attr('value', ''))
+ .append($('<span />')
+ .addClass('badge')
+ .append($('<input />')
+ .attr('id', 'custom' + id)
+ .attr('type', 'text')
+ .attr('placeholder', L.tr('Custom device …'))
+ .on('focus', { self: this, sid: sid }, this._ev_focus)
+ .on('blur', { self: this, sid: sid }, this._ev_blur)
+ .on('keydown', { self: this, sid: sid }, this._ev_keydown))))
+ .appendTo(ul);
+
+ if (!this.options.multiple)
+ {
+ $('<li />')
+ .append($('<label />')
+ .addClass(itype + ' inline text-muted')
+ .append($('<input />')
+ .attr('name', itype + id)
+ .attr('type', itype)
+ .attr('value', '')
+ .prop('checked', $.isEmptyObject(check)))
+ .append(L.tr('unspecified')))
+ .appendTo(ul);
+ }
+ },
+
+ widget: function(sid)
+ {
+ var id = this.id(sid);
+ var ul = $('<ul />')
+ .attr('id', id)
+ .addClass('list-unstyled');
+
+ this._redraw(sid, ul);
+
+ return ul;
+ },
+
+ save: function(sid)
+ {
+ if (this.instance[sid].disabled)
+ return;
+
+ var ifnames = this.formvalue(sid);
+ //if (!ifnames)
+ // return;
+
+ var iface = L.NetworkModel.getInterface(sid);
+ if (!iface)
+ return;
+
+ iface.setDevices($.isArray(ifnames) ? ifnames : [ ifnames ]);
+ }
+ });
+
this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
id: function()
var w = widget ? new widget(name, options) : null;
- if (!(w instanceof _luci2.cbi.AbstractValue))
+ if (!(w instanceof L.cbi.AbstractValue))
throw 'Widget must be an instance of AbstractValue';
w.section = this;
return w;
},
+ tabtoggle: function(sid)
+ {
+ for (var i = 0; i < this.tabs.length; i++)
+ {
+ var tab = this.tabs[i];
+ var elem = $('#' + this.id('nodetab', sid, tab.id));
+ var empty = true;
+
+ for (var j = 0; j < tab.fields.length; j++)
+ {
+ if (tab.fields[j].active(sid))
+ {
+ empty = false;
+ break;
+ }
+ }
+
+ if (empty && elem.is(':visible'))
+ elem.fadeOut();
+ else if (!empty)
+ elem.fadeIn();
+ }
+ },
+
ucipackages: function(pkg)
{
for (var i = 0; i < this.tabs.length; i++)
if (inval > 0)
stbadge.show()
.text(inval)
- .attr('title', _luci2.trp('1 Error', '%d Errors', inval).format(inval));
+ .attr('title', L.trp('1 Error', '%d Errors', inval).format(inval));
else
stbadge.hide();
if (invals > 0)
badge.show()
.text(invals)
- .attr('title', _luci2.trp('1 Error', '%d Errors', invals).format(invals));
+ .attr('title', L.trp('1 Error', '%d Errors', invals).format(invals));
else
badge.hide();
validate: function()
{
- this.error_count = 0;
-
+ var errors = 0;
var as = this.sections();
for (var i = 0; i < as.length; i++)
var invals = this.validate_section(as[i]['.name']);
if (invals > 0)
- this.error_count += invals;
+ errors += invals;
}
var badge = $('#' + this.id('sectiontab')).children('span:first');
- if (this.error_count > 0)
+ if (errors > 0)
badge.show()
- .text(this.error_count)
- .attr('title', _luci2.trp('1 Error', '%d Errors', this.error_count).format(this.error_count));
+ .text(errors)
+ .attr('title', L.trp('1 Error', '%d Errors', errors).format(errors));
else
badge.hide();
- return (this.error_count == 0);
+ return (errors == 0);
}
});
this.options = options;
this.tabs = [ ];
this.fields = { };
- this.error_count = 0;
this.active_panel = 0;
this.active_tab = { };
},
sections: function(cb)
{
- var s1 = this.map.ucisections(this.map.uci_package);
+ var s1 = L.uci.sections(this.map.uci_package);
var s2 = [ ];
for (var i = 0; i < s1.length; i++)
if (typeof(cb) == 'function')
for (var i = 0; i < s2.length; i++)
- cb.apply(this, [ s2[i] ]);
+ cb.call(this, s2[i]);
return s2;
},
add: function(name)
{
- this.map.add(this.map.uci_package, this.uci_type, name);
+ return this.map.add(this.map.uci_package, this.uci_type, name);
},
remove: function(sid)
{
- this.map.remove(this.map.uci_package, sid);
+ return this.map.remove(this.map.uci_package, sid);
},
_ev_add: function(ev)
if (addb.prop('disabled') || name === '')
return;
- _luci2.ui.saveScrollTop();
+ L.ui.saveScrollTop();
self.active_panel = -1;
self.map.save();
- self.add(name);
+
+ ev.data.sid = self.add(name);
+ ev.data.type = self.uci_type;
+ ev.data.name = name;
+
+ self.trigger('add', ev);
+
self.map.redraw();
- _luci2.ui.restoreScrollTop();
+ L.ui.restoreScrollTop();
},
_ev_remove: function(ev)
var self = ev.data.self;
var sid = ev.data.sid;
- _luci2.ui.saveScrollTop();
+ L.ui.saveScrollTop();
+
+ self.trigger('remove', ev);
self.map.save();
self.remove(sid);
self.map.redraw();
- _luci2.ui.restoreScrollTop();
+ L.ui.restoreScrollTop();
ev.stopPropagation();
},
var addb = text.next();
var errt = addb.next();
var name = text.val();
- var used = false;
if (!/^[a-zA-Z0-9_]*$/.test(name))
{
- errt.text(_luci2.tr('Invalid section name')).show();
+ errt.text(L.tr('Invalid section name')).show();
text.addClass('error');
addb.prop('disabled', true);
return false;
}
- for (var sid in self.map.uci.values[self.map.uci_package])
- if (sid == name)
- {
- used = true;
- break;
- }
-
- for (var sid in self.map.uci.creates[self.map.uci_package])
- if (sid == name)
- {
- used = true;
- break;
- }
-
- if (used)
+ if (L.uci.get(self.map.uci_package, name))
{
- errt.text(_luci2.tr('Name already used')).show();
+ errt.text(L.tr('Name already used')).show();
text.addClass('error');
addb.prop('disabled', true);
return false;
if (new_idx >= 0 && new_idx < s.length)
{
- var tmp = s[cur_idx]['.index'];
-
- s[cur_idx]['.index'] = s[new_idx]['.index'];
- s[new_idx]['.index'] = tmp;
-
- if (self.active_panel == cur_idx)
- self.active_panel = new_idx;
- else if (self.active_panel == new_idx)
- self.active_panel = cur_idx;
-
- self.map.uci.reorder = true;
+ L.uci.swap(self.map.uci_package, s[cur_idx]['.name'], s[new_idx]['.name']);
self.map.save();
self.map.redraw();
for (var i = 0; i < this.options.teasers.length; i++)
{
var f = this.options.teasers[i];
- if (f instanceof _luci2.cbi.AbstractValue)
+ if (f instanceof L.cbi.AbstractValue)
tf.push(f);
- else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
+ else if (typeof(f) == 'string' && this.fields[f] instanceof L.cbi.AbstractValue)
tf.push(this.fields[f]);
}
}
if (!this.options.addremove)
return null;
- var text = _luci2.tr('Add section');
- var ttip = _luci2.tr('Create new section...');
+ var text = L.tr('Add section');
+ var ttip = L.tr('Create new section...');
if ($.isArray(this.options.add_caption))
text = this.options.add_caption[0], ttip = this.options.add_caption[1];
.appendTo(add);
$('<img />')
- .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
+ .attr('src', L.globals.resource + '/icons/cbi/add.gif')
.attr('title', text)
.addClass('cbi-button')
.click({ self: this }, this._ev_add)
}
else
{
- _luci2.ui.button(text, 'success', ttip)
+ L.ui.button(text, 'success', ttip)
.click({ self: this }, this._ev_add)
.appendTo(add);
}
if (!this.options.addremove)
return null;
- var text = _luci2.tr('Remove');
- var ttip = _luci2.tr('Remove this section');
+ var text = L.tr('Remove');
+ var ttip = L.tr('Remove this section');
if ($.isArray(this.options.remove_caption))
text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
else if (typeof(this.options.remove_caption) == 'string')
text = this.options.remove_caption, ttip = '';
- return _luci2.ui.button(text, 'danger', ttip)
+ return L.ui.button(text, 'danger', ttip)
.click({ self: this, sid: sid, index: index }, this._ev_remove);
},
if (!this.options.sortable)
return null;
- var b1 = _luci2.ui.button('↑', 'info', _luci2.tr('Move up'))
+ var b1 = L.ui.button('↑', 'info', L.tr('Move up'))
.click({ self: this, index: index, up: true }, this._ev_sort);
- var b2 = _luci2.ui.button('↓', 'info', _luci2.tr('Move down'))
+ var b2 = L.ui.button('↓', 'info', L.tr('Move down'))
.click({ self: this, index: index, up: false }, this._ev_sort);
return b1.add(b2);
if (cur == tab_index)
tabh.addClass('active');
+ if (!tab.fields.length)
+ tabh.hide();
+
return tabh;
},
{
body.append($('<li />')
.addClass('list-group-item text-muted')
- .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.')))
+ .text(this.label('placeholder') || L.tr('There are no entries defined yet.')))
}
for (var i = 0; i < s.length; i++)
.append($('<td />')
.addClass('text-muted')
.attr('colspan', cols)
- .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.'))));
+ .text(this.label('placeholder') || L.tr('There are no entries defined yet.'))));
}
for (var i = 0; i < s.length; i++)
sections: function(cb)
{
var sa = [ ];
- var pkg = this.map.uci.values[this.map.uci_package];
+ var sl = L.uci.sections(this.map.uci_package);
- for (var s in pkg)
- if (pkg[s]['.name'] == this.uci_type)
+ for (var i = 0; i < sl.length; i++)
+ if (sl[i]['.name'] == this.uci_type)
{
- sa.push(pkg[s]);
+ sa.push(sl[i]);
break;
}
if (typeof(cb) == 'function' && sa.length > 0)
- cb.apply(this, [ sa[0] ]);
+ cb.call(this, sa[0]);
return sa;
}
});
+ this.cbi.SingleSection = this.cbi.NamedSection.extend({
+ render: function()
+ {
+ this.instance = { };
+ this.instance[this.uci_type] = { tabs: [ ] };
+
+ return this._render_section_body(this.uci_type, 0);
+ }
+ });
+
this.cbi.DummySection = this.cbi.TypedSection.extend({
sections: function(cb)
{
this.uci_package = uci_package;
this.sections = [ ];
- this.options = _luci2.defaults(options, {
+ this.options = L.defaults(options, {
save: function() { },
- prepare: function() {
- return _luci2.uci.writable(function(writable) {
- self.options.readonly = !writable;
- });
- }
+ prepare: function() { }
});
},
- _load_cb: function(packages)
+ _load_cb: function()
{
- for (var i = 0; i < packages.length; i++)
- {
- this.uci.values[packages[i]['.package']] = packages[i];
- delete packages[i]['.package'];
- }
-
- var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
+ var deferreds = [ L.deferrable(this.options.prepare()) ];
for (var i = 0; i < this.sections.length; i++)
{
for (var j = 0; j < s.length; j++)
{
var rv = this.sections[i].fields[f].load(s[j]['.name']);
- if (_luci2.isDeferred(rv))
+ if (L.isDeferred(rv))
deferreds.push(rv);
}
}
load: function()
{
var self = this;
-
- this.uci = {
- newid: 0,
- values: { },
- creates: { },
- changes: { },
- deletes: { },
- reorder: false
- };
-
var packages = { };
for (var i = 0; i < this.sections.length; i++)
this.sections[i].ucipackages(packages);
- packages[this.uci_package] = true;
+ packages[this.uci_package] = true;
+
+ for (var pkg in packages)
+ if (!L.uci.writable(pkg))
+ this.options.readonly = true;
+
+ return L.uci.load(L.toArray(packages)).then(function() {
+ return self._load_cb();
+ });
+ },
+
+ _ev_tab: function(ev)
+ {
+ var self = ev.data.self;
+
+ self.validate();
+ self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
+ },
- _luci2.rpc.batch();
+ _ev_apply: function(ev)
+ {
+ var self = ev.data.self;
- for (var pkg in packages)
- _luci2.uci.get_all(pkg);
+ self.trigger('apply', ev);
+ },
- return _luci2.rpc.flush().then(function(packages) {
- return self._load_cb(packages);
+ _ev_save: function(ev)
+ {
+ var self = ev.data.self;
+
+ self.send().then(function() {
+ self.trigger('save', ev);
});
},
- _ev_tab: function(ev)
+ _ev_reset: function(ev)
{
var self = ev.data.self;
- self.validate();
- self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
+ self.trigger('reset', ev);
+ self.reset();
},
_render_tab_head: function(tab_index)
return body;
},
+ _render_footer: function()
+ {
+ var evdata = {
+ self: this
+ };
+
+ return $('<div />')
+ .addClass('panel panel-default panel-body text-right')
+ .append($('<div />')
+ .addClass('btn-group')
+ .append(L.ui.button(L.tr('Save & Apply'), 'primary')
+ .click(evdata, this._ev_apply))
+ .append(L.ui.button(L.tr('Save'), 'default')
+ .click(evdata, this._ev_save))
+ .append(L.ui.button(L.tr('Reset'), 'default')
+ .click(evdata, this._ev_reset)));
+ },
+
render: function()
{
var map = $('<form />');
map.append(this._render_body());
if (this.options.pageaction !== false)
- {
- map.append($('<div />')
- .addClass('panel panel-default panel-body text-right')
- .append($('<div />')
- .addClass('btn-group')
- .append(_luci2.ui.button(_luci2.tr('Save & Apply'), 'primary')
- .click({ self: this }, function(ev) { }))
- .append(_luci2.ui.button(_luci2.tr('Save'), 'default')
- .click({ self: this }, function(ev) { ev.data.self.send(); }))
- .append(_luci2.ui.button(_luci2.tr('Reset'), 'default')
- .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); }))));
- }
+ map.append(this._render_footer());
return map;
},
{
var w = widget ? new widget(uci_type, options) : null;
- if (!(w instanceof _luci2.cbi.AbstractSection))
+ if (!(w instanceof L.cbi.AbstractSection))
throw 'Widget must be an instance of AbstractSection';
w.map = this;
add: function(conf, type, name)
{
- var c = this.uci.creates;
- var s = '.new.%d'.format(this.uci.newid++);
-
- if (!c[conf])
- c[conf] = { };
-
- c[conf][s] = {
- '.type': type,
- '.name': s,
- '.create': name,
- '.anonymous': !name,
- '.index': 1000 + this.uci.newid
- };
-
- return s;
+ return L.uci.add(conf, type, name);
},
remove: function(conf, sid)
{
- var n = this.uci.creates;
- var c = this.uci.changes;
- var d = this.uci.deletes;
-
- /* requested deletion of a just created section */
- if (sid.indexOf('.new.') == 0)
- {
- if (n[conf])
- delete n[conf][sid];
- }
- else
- {
- if (c[conf])
- delete c[conf][sid];
-
- if (!d[conf])
- d[conf] = { };
-
- d[conf][sid] = true;
- }
- },
-
- ucisections: function(conf, cb)
- {
- var sa = [ ];
- var pkg = this.uci.values[conf];
- var crt = this.uci.creates[conf];
- var del = this.uci.deletes[conf];
-
- if (!pkg)
- return sa;
-
- for (var s in pkg)
- if (!del || del[s] !== true)
- sa.push(pkg[s]);
-
- if (crt)
- for (var s in crt)
- sa.push(crt[s]);
-
- sa.sort(function(a, b) {
- return a['.index'] - b['.index'];
- });
-
- for (var i = 0; i < sa.length; i++)
- sa[i]['.index'] = i;
-
- if (typeof(cb) == 'function')
- for (var i = 0; i < sa.length; i++)
- cb.apply(this, [ sa[i] ]);
-
- return sa;
+ return L.uci.remove(conf, sid);
},
get: function(conf, sid, opt)
{
- var v = this.uci.values;
- var n = this.uci.creates;
- var c = this.uci.changes;
- var d = this.uci.deletes;
-
- /* requested option in a just created section */
- if (sid.indexOf('.new.') == 0)
- {
- if (!n[conf])
- return undefined;
-
- if (typeof(opt) == 'undefined')
- return (n[conf][sid] || { });
-
- return n[conf][sid][opt];
- }
-
- /* requested an option value */
- if (typeof(opt) != 'undefined')
- {
- /* check whether option was deleted */
- if (d[conf] && d[conf][sid])
- {
- if (d[conf][sid] === true)
- return undefined;
-
- for (var i = 0; i < d[conf][sid].length; i++)
- if (d[conf][sid][i] == opt)
- return undefined;
- }
-
- /* check whether option was changed */
- if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
- return c[conf][sid][opt];
-
- /* return base value */
- if (v[conf] && v[conf][sid])
- return v[conf][sid][opt];
-
- return undefined;
- }
-
- /* requested an entire section */
- if (v[conf])
- return (v[conf][sid] || { });
-
- return undefined;
+ return L.uci.get(conf, sid, opt);
},
set: function(conf, sid, opt, val)
{
- var n = this.uci.creates;
- var c = this.uci.changes;
- var d = this.uci.deletes;
-
- if (sid.indexOf('.new.') == 0)
- {
- if (n[conf] && n[conf][sid])
- {
- if (typeof(val) != 'undefined')
- n[conf][sid][opt] = val;
- else
- delete n[conf][sid][opt];
- }
- }
- else if (typeof(val) != 'undefined')
- {
- if (!c[conf])
- c[conf] = { };
-
- if (!c[conf][sid])
- c[conf][sid] = { };
-
- c[conf][sid][opt] = val;
- }
- else
- {
- if (!d[conf])
- d[conf] = { };
-
- if (!d[conf][sid])
- d[conf][sid] = [ ];
-
- d[conf][sid].push(opt);
- }
+ return L.uci.set(conf, sid, opt, val);
},
validate: function()
save: function()
{
- if (this.options.readonly)
- return _luci2.deferrable();
+ var self = this;
- var deferreds = [ _luci2.deferrable(this.options.save()) ];
+ if (self.options.readonly)
+ return L.deferrable();
- for (var i = 0; i < this.sections.length; i++)
+ var deferreds = [ ];
+
+ for (var i = 0; i < self.sections.length; i++)
{
- if (this.sections[i].options.readonly)
+ if (self.sections[i].options.readonly)
continue;
- for (var f in this.sections[i].fields)
+ for (var f in self.sections[i].fields)
{
- if (typeof(this.sections[i].fields[f].save) != 'function')
+ if (typeof(self.sections[i].fields[f].save) != 'function')
continue;
- var s = this.sections[i].sections();
+ var s = self.sections[i].sections();
for (var j = 0; j < s.length; j++)
{
- var rv = this.sections[i].fields[f].save(s[j]['.name']);
- if (_luci2.isDeferred(rv))
+ var rv = self.sections[i].fields[f].save(s[j]['.name']);
+ if (L.isDeferred(rv))
deferreds.push(rv);
}
}
}
- return $.when.apply($, deferreds);
+ return $.when.apply($, deferreds).then(function() {
+ return L.deferrable(self.options.save());
+ });
},
- _send_uci_reorder: function()
+ send: function()
{
- if (!this.uci.reorder)
- return _luci2.deferrable();
-
- _luci2.rpc.batch();
+ if (!this.validate())
+ return L.deferrable();
- /*
- gather all created and existing sections, sort them according
- to their index value and issue an uci order call
- */
- for (var c in this.uci.values)
- {
- var o = [ ];
+ var self = this;
- if (this.uci.creates && this.uci.creates[c])
- for (var s in this.uci.creates[c])
- o.push(this.uci.creates[c][s]);
+ L.ui.saveScrollTop();
+ L.ui.loading(true);
- for (var s in this.uci.values[c])
- o.push(this.uci.values[c][s]);
+ return this.save().then(function() {
+ return L.uci.save();
+ }).then(function() {
+ return L.ui.updateChanges();
+ }).then(function() {
+ return self.load();
+ }).then(function() {
+ self.redraw();
+ self = null;
- if (o.length > 0)
- {
- o.sort(function(a, b) {
- return (a['.index'] - b['.index']);
- });
+ L.ui.loading(false);
+ L.ui.restoreScrollTop();
+ });
+ },
- var sids = [ ];
+ revert: function()
+ {
+ var packages = { };
- for (var i = 0; i < o.length; i++)
- sids.push(o[i]['.name']);
+ for (var i = 0; i < this.sections.length; i++)
+ this.sections[i].ucipackages(packages);
- _luci2.uci.order(c, sids);
- }
- }
+ packages[this.uci_package] = true;
- return _luci2.rpc.flush();
+ L.uci.unload(L.toArray(packages));
},
- _send_uci: function()
+ reset: function()
{
- _luci2.rpc.batch();
-
var self = this;
- var snew = [ ];
- if (this.uci.creates)
- for (var c in this.uci.creates)
- for (var s in this.uci.creates[c])
- {
- var r = {
- config: c,
- values: { }
- };
+ self.revert();
- for (var k in this.uci.creates[c][s])
- {
- if (k == '.type')
- r.type = this.uci.creates[c][s][k];
- else if (k == '.create')
- r.name = this.uci.creates[c][s][k];
- else if (k.charAt(0) != '.')
- r.values[k] = this.uci.creates[c][s][k];
- }
+ return self.insertInto(self.target);
+ },
- snew.push(this.uci.creates[c][s]);
+ insertInto: function(id)
+ {
+ var self = this;
+ self.target = $(id);
- _luci2.uci.add(r.config, r.type, r.name, r.values);
- }
+ L.ui.loading(true);
+ self.target.hide();
- if (this.uci.changes)
- for (var c in this.uci.changes)
- for (var s in this.uci.changes[c])
- _luci2.uci.set(c, s, this.uci.changes[c][s]);
+ return self.load().then(function() {
+ self.target.empty().append(self.render());
+ self.finish();
+ self.target.show();
+ self = null;
+ L.ui.loading(false);
+ });
+ }
+ });
- if (this.uci.deletes)
- for (var c in this.uci.deletes)
- for (var s in this.uci.deletes[c])
- {
- var o = this.uci.deletes[c][s];
- _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
- }
+ this.cbi.Modal = this.cbi.Map.extend({
+ _ev_apply: function(ev)
+ {
+ var self = ev.data.self;
- return _luci2.rpc.flush().then(function(responses) {
- /*
- array "snew" holds references to the created uci sections,
- use it to assign the returned names of the new sections
- */
- for (var i = 0; i < snew.length; i++)
- snew[i]['.name'] = responses[i];
+ self.trigger('apply', ev);
+ },
+
+ _ev_save: function(ev)
+ {
+ var self = ev.data.self;
- return self._send_uci_reorder();
+ self.send().then(function() {
+ self.trigger('save', ev);
+ self.close();
});
},
- send: function()
+ _ev_reset: function(ev)
{
- if (!this.validate())
- return _luci2.deferrable();
+ var self = ev.data.self;
- var self = this;
+ self.trigger('close', ev);
+ self.revert();
+ self.close();
+ },
- _luci2.ui.saveScrollTop();
- _luci2.ui.loading(true);
+ _render_footer: function()
+ {
+ var evdata = {
+ self: this
+ };
- return this.save().then(function() {
- return self._send_uci();
- }).then(function() {
- return _luci2.ui.updateChanges();
- }).then(function() {
- return self.load();
- }).then(function() {
- self.redraw();
- self = null;
+ return $('<div />')
+ .addClass('btn-group')
+ .append(L.ui.button(L.tr('Save & Apply'), 'primary')
+ .click(evdata, this._ev_apply))
+ .append(L.ui.button(L.tr('Save'), 'default')
+ .click(evdata, this._ev_save))
+ .append(L.ui.button(L.tr('Cancel'), 'default')
+ .click(evdata, this._ev_reset));
+ },
- _luci2.ui.loading(false);
- _luci2.ui.restoreScrollTop();
- });
+ render: function()
+ {
+ var modal = L.ui.dialog(this.label('caption'), null, { wide: true });
+ var map = $('<form />');
+
+ var desc = this.label('description');
+ if (desc)
+ map.append($('<p />').text(desc));
+
+ map.append(this._render_body());
+
+ modal.find('.modal-body').append(map);
+ modal.find('.modal-footer').append(this._render_footer());
+
+ return modal;
},
- insertInto: function(id)
+ redraw: function()
+ {
+ this.render();
+ this.finish();
+ },
+
+ show: function()
{
var self = this;
- self.target = $(id);
- _luci2.ui.loading(true);
- self.target.hide();
+ L.ui.loading(true);
return self.load().then(function() {
- self.target.empty().append(self.render());
+ self.render();
self.finish();
- self.target.show();
- self = null;
- _luci2.ui.loading(false);
+
+ L.ui.loading(false);
});
+ },
+
+ close: function()
+ {
+ L.ui.dialog(false);
}
});
};