2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String.prototype.format = function()
15 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27 var a = b = [], numSubstitutions = 0, numMatches = 0;
29 while ((a = re.exec(str)) != null)
32 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33 var pPrecision = a[6], pType = a[7];
43 if (numSubstitutions < arguments.length)
45 var param = arguments[numSubstitutions++];
48 if (pPad && pPad.substr(0,1) == "'")
49 pad = leftpart.substr(1,1);
53 var justifyRight = true;
54 if (pJustify && pJustify === "-")
59 minLength = parseInt(pMinLength);
62 if (pPrecision && pType == 'f')
63 precision = parseInt(pPrecision.substring(1));
70 subst = (parseInt(param) || 0).toString(2);
74 subst = String.fromCharCode(parseInt(param) || 0);
78 subst = (parseInt(param) || 0);
82 subst = Math.abs(parseInt(param) || 0);
86 subst = (precision > -1)
87 ? ((parseFloat(param) || 0.0)).toFixed(precision)
88 : (parseFloat(param) || 0.0);
92 subst = (parseInt(param) || 0).toString(8);
100 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
104 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
108 subst = esc(param, html_esc);
112 subst = esc(param, quot_esc);
116 subst = String.serialize(param);
123 var ts = (param || 0);
126 tm = Math.floor(ts / 60);
131 th = Math.floor(tm / 60);
136 td = Math.floor(th / 24);
141 ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142 : '%dh %dm %ds'.format(th, tm, ts);
147 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
151 var val = parseFloat(param || 0);
152 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i = 0; (i < units.length) && (val > mf); i++)
157 subst = val.toFixed(pr) + ' ' + units[i];
161 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
163 if (minLength > 0 && pad.length > 0)
164 for (var i = 0; i < (minLength - subst.length); i++)
165 subst = justifyRight ? (pad + subst) : (subst + pad);
169 out += leftpart + subst;
170 str = str.substr(m.length);
180 var Class = function() { };
182 Class.extend = function(properties)
184 Class.initializing = true;
186 var prototype = new this();
187 var superprot = this.prototype;
189 Class.initializing = false;
191 $.extend(prototype, properties, {
192 callSuper: function() {
194 var meth = arguments[0];
196 if (typeof(superprot[meth]) != 'function')
199 for (var i = 1; i < arguments.length; i++)
200 args.push(arguments[i]);
202 return superprot[meth].apply(this, args);
208 this.options = arguments[0] || { };
210 if (!Class.initializing && typeof(this.init) == 'function')
211 this.init.apply(this, arguments);
214 _class.prototype = prototype;
215 _class.prototype.constructor = _class;
217 _class.extend = Class.extend;
222 this.defaults = function(obj, def)
225 if (typeof(obj[key]) == 'undefined')
231 this.isDeferred = function(x)
233 return (typeof(x) == 'object' &&
234 typeof(x.then) == 'function' &&
235 typeof(x.promise) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments[0]))
243 var d = $.Deferred();
244 d.resolve.apply(d, arguments);
253 plural: function(n) { return 0 + (n != 1) },
256 if (_luci2.i18n.loaded)
259 var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260 var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
262 for (var i = 0; i < langs.length; i++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
267 success: function(data) {
268 $.extend(_luci2.i18n.catalog, data);
270 var pe = _luci2.i18n.catalog[''];
273 delete _luci2.i18n.catalog[''];
275 var pf = new Function('n', 'return 0 + (' + pe + ')');
276 _luci2.i18n.plural = pf;
282 _luci2.i18n.loaded = true;
287 this.tr = function(msgid)
291 var msgstr = _luci2.i18n.catalog[msgid];
293 if (typeof(msgstr) == 'undefined')
295 else if (typeof(msgstr) == 'string')
301 this.trp = function(msgid, msgid_plural, count)
305 var msgstr = _luci2.i18n.catalog[msgid];
307 if (typeof(msgstr) == 'undefined')
308 return (count == 1) ? msgid : msgid_plural;
309 else if (typeof(msgstr) == 'string')
312 return msgstr[_luci2.i18n.plural(count)];
315 this.trc = function(msgctx, msgid)
319 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
321 if (typeof(msgstr) == 'undefined')
323 else if (typeof(msgstr) == 'string')
329 this.trcp = function(msgctx, msgid, msgid_plural, count)
333 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
335 if (typeof(msgstr) == 'undefined')
336 return (count == 1) ? msgid : msgid_plural;
337 else if (typeof(msgstr) == 'string')
340 return msgstr[_luci2.i18n.plural(count)];
343 this.setHash = function(key, value)
346 var data = this.getHash(undefined);
348 if (typeof(value) == 'undefined')
359 for (var i = 0; i < keys.length; i++)
364 h += keys[i] + ':' + data[keys[i]];
368 location.hash = '#' + h;
373 this.getHash = function(key)
376 var tuples = (location.hash || '#').substring(1).split(/,/);
378 for (var i = 0; i < tuples.length; i++)
380 var tuple = tuples[i].split(/:/);
381 if (tuple.length == 2)
382 data[tuple[0]] = tuple[1];
385 if (typeof(key) != 'undefined')
391 this.toArray = function(x)
401 var l = x.split(/\s+/);
402 for (var i = 0; i < l.length; i++)
411 for (var i = 0; i < x.length; i++)
415 else if ($.isPlainObject(x))
419 if (x.hasOwnProperty(k))
428 this.toObject = function(x)
438 var l = x.split(/\x+/);
439 for (var i = 0; i < l.length; i++)
448 for (var i = 0; i < x.length; i++)
452 else if ($.isPlainObject(x))
461 this.filterArray = function(array, item)
463 if (!$.isArray(array))
466 for (var i = 0; i < array.length; i++)
467 if (array[i] === item)
468 array.splice(i--, 1);
473 this.toClassName = function(str, suffix)
476 var l = str.split(/[\/.]/);
478 for (var i = 0; i < l.length; i++)
480 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
482 if (typeof(suffix) == 'string')
491 sid: '00000000000000000000000000000000'
500 _call: function(req, cb)
502 return $.ajax('/ubus', {
504 contentType: 'application/json',
505 data: JSON.stringify(req),
508 timeout: _luci2.globals.timeout,
513 _list_cb: function(msg)
515 var list = msg.result;
517 /* verify message frame */
518 if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
521 return $.Deferred().resolveWith(this, [ list ]);
524 _call_cb: function(msg)
527 var type = Object.prototype.toString;
528 var reqs = this._rpc_req;
530 if (!$.isArray(reqs))
536 for (var i = 0; i < msg.length; i++)
538 /* fetch related request info */
539 var req = _luci2.rpc._requests[reqs[i].id];
540 if (typeof(req) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
553 for (var key in req.expect)
555 if (typeof(ret) != 'undefined' && key != '')
558 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559 ret = req.expect[key];
566 if (typeof(req.filter) == 'function')
569 req.priv[1] = req.params;
570 ret = req.filter.apply(_luci2.rpc, req.priv);
573 /* store response data */
574 if (typeof(req.index) == 'number')
575 data[req.index] = ret;
579 /* delete request object */
580 delete _luci2.rpc._requests[reqs[i].id];
583 return $.Deferred().resolveWith(this, [ data ]);
589 for (var i = 0; i < arguments.length; i++)
590 params[i] = arguments[i];
596 params: (params.length > 0) ? params : undefined
599 return this._call(msg, this._list_cb);
604 if (!$.isArray(this._batch))
610 if (!$.isArray(this._batch))
611 return _luci2.deferrable([ ]);
613 var req = this._batch;
617 return this._call(req, this._call_cb);
620 declare: function(options)
625 /* build parameter object */
628 if ($.isArray(options.params))
629 for (p_off = 0; p_off < options.params.length; p_off++)
630 params[options.params[p_off]] = arguments[p_off];
632 /* all remaining arguments are private args */
633 var priv = [ undefined, undefined ];
634 for (; p_off < arguments.length; p_off++)
635 priv.push(arguments[p_off]);
637 /* store request info */
638 var req = _rpc._requests[_rpc._id] = {
639 expect: options.expect,
640 filter: options.filter,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc._batch))
662 req.index = _rpc._batch.push(msg) - 1;
663 return _luci2.deferrable(msg);
667 return _rpc._call(msg, _rpc._call_cb);
672 this.UCIContext = Class.extend({
686 _load: _luci2.rpc.declare({
689 params: [ 'config' ],
690 expect: { values: { } }
693 _order: _luci2.rpc.declare({
696 params: [ 'config', 'sections' ]
699 _add: _luci2.rpc.declare({
702 params: [ 'config', 'type', 'name', 'values' ],
703 expect: { section: '' }
706 _set: _luci2.rpc.declare({
709 params: [ 'config', 'section', 'values' ]
712 _delete: _luci2.rpc.declare({
715 params: [ 'config', 'section', 'options' ]
718 load: function(packages)
724 if (!$.isArray(packages))
725 packages = [ packages ];
729 for (var i = 0; i < packages.length; i++)
730 if (!seen[packages[i]])
732 pkgs.push(packages[i]);
733 seen[packages[i]] = true;
734 self._load(packages[i]);
737 return _luci2.rpc.flush().then(function(responses) {
738 for (var i = 0; i < responses.length; i++)
739 self.state.values[pkgs[i]] = responses[i];
745 unload: function(packages)
747 if (!$.isArray(packages))
748 packages = [ packages ];
750 for (var i = 0; i < packages.length; i++)
752 delete this.state.values[packages[i]];
753 delete this.state.creates[packages[i]];
754 delete this.state.changes[packages[i]];
755 delete this.state.deletes[packages[i]];
759 add: function(conf, type, name)
761 var c = this.state.creates;
762 var s = '.new.%d'.format(this.state.newid++);
772 '.index': 1000 + this.state.newid
778 remove: function(conf, sid)
780 var n = this.state.creates;
781 var c = this.state.changes;
782 var d = this.state.deletes;
784 /* requested deletion of a just created section */
785 if (sid.indexOf('.new.') == 0)
802 sections: function(conf, type, cb)
805 var v = this.state.values[conf];
806 var n = this.state.creates[conf];
807 var c = this.state.changes[conf];
808 var d = this.state.deletes[conf];
814 if (!d || d[s] !== true)
815 if (!type || v[s]['.type'] == type)
816 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
820 if (!type || n[s]['.type'] == type)
823 sa.sort(function(a, b) {
824 return a['.index'] - b['.index'];
827 for (var i = 0; i < sa.length; i++)
830 if (typeof(cb) == 'function')
831 for (var i = 0; i < sa.length; i++)
832 cb.call(this, sa[i], sa[i]['.name']);
837 get: function(conf, sid, opt)
839 var v = this.state.values;
840 var n = this.state.creates;
841 var c = this.state.changes;
842 var d = this.state.deletes;
844 if (typeof(sid) == 'undefined')
847 /* requested option in a just created section */
848 if (sid.indexOf('.new.') == 0)
853 if (typeof(opt) == 'undefined')
856 return n[conf][sid][opt];
859 /* requested an option value */
860 if (typeof(opt) != 'undefined')
862 /* check whether option was deleted */
863 if (d[conf] && d[conf][sid])
865 if (d[conf][sid] === true)
868 for (var i = 0; i < d[conf][sid].length; i++)
869 if (d[conf][sid][i] == opt)
873 /* check whether option was changed */
874 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
875 return c[conf][sid][opt];
877 /* return base value */
878 if (v[conf] && v[conf][sid])
879 return v[conf][sid][opt];
884 /* requested an entire section */
891 set: function(conf, sid, opt, val)
893 var n = this.state.creates;
894 var c = this.state.changes;
895 var d = this.state.deletes;
897 if (typeof(sid) == 'undefined' ||
898 typeof(opt) == 'undefined' ||
899 opt.charAt(0) == '.')
902 if (sid.indexOf('.new.') == 0)
904 if (n[conf] && n[conf][sid])
906 if (typeof(val) != 'undefined')
907 n[conf][sid][opt] = val;
909 delete n[conf][sid][opt];
912 else if (typeof(val) != 'undefined')
914 /* do not set within deleted section */
915 if (d[conf] && d[conf][sid] === true)
924 /* undelete option */
925 if (d[conf] && d[conf][sid])
926 d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
928 c[conf][sid][opt] = val;
938 if (d[conf][sid] !== true)
939 d[conf][sid].push(opt);
943 unset: function(conf, sid, opt)
945 return this.set(conf, sid, opt, undefined);
952 for (var pkg in this.state.values)
957 return this.load(pkgs);
962 var v = this.state.values;
963 var n = this.state.creates;
964 var r = this.state.reorder;
966 if ($.isEmptyObject(r))
967 return _luci2.deferrable();
972 gather all created and existing sections, sort them according
973 to their index value and issue an uci order call
988 o.sort(function(a, b) {
989 return (a['.index'] - b['.index']);
994 for (var i = 0; i < o.length; i++)
995 sids.push(o[i]['.name']);
997 this._order(c, sids);
1001 this.state.reorder = { };
1002 return _luci2.rpc.flush();
1005 swap: function(conf, sid1, sid2)
1007 var s1 = this.get(conf, sid1);
1008 var s2 = this.get(conf, sid2);
1009 var n1 = s1 ? s1['.index'] : NaN;
1010 var n2 = s2 ? s2['.index'] : NaN;
1012 if (isNaN(n1) || isNaN(n2))
1018 this.state.reorder[conf] = true;
1030 if (self.state.creates)
1031 for (var c in self.state.creates)
1032 for (var s in self.state.creates[c])
1039 for (var k in self.state.creates[c][s])
1042 r.type = self.state.creates[c][s][k];
1043 else if (k == '.create')
1044 r.name = self.state.creates[c][s][k];
1045 else if (k.charAt(0) != '.')
1046 r.values[k] = self.state.creates[c][s][k];
1049 snew.push(self.state.creates[c][s]);
1051 self._add(r.config, r.type, r.name, r.values);
1054 if (self.state.changes)
1055 for (var c in self.state.changes)
1056 for (var s in self.state.changes[c])
1057 self._set(c, s, self.state.changes[c][s]);
1059 if (self.state.deletes)
1060 for (var c in self.state.deletes)
1061 for (var s in self.state.deletes[c])
1063 var o = self.state.deletes[c][s];
1064 self._delete(c, s, (o === true) ? undefined : o);
1067 return _luci2.rpc.flush().then(function(responses) {
1069 array "snew" holds references to the created uci sections,
1070 use it to assign the returned names of the new sections
1072 for (var i = 0; i < snew.length; i++)
1073 snew[i]['.name'] = responses[i];
1075 return self._reorder();
1079 _apply: _luci2.rpc.declare({
1082 params: [ 'timeout', 'rollback' ]
1085 _confirm: _luci2.rpc.declare({
1090 apply: function(timeout)
1093 var date = new Date();
1094 var deferred = $.Deferred();
1096 if (typeof(timeout) != 'number' || timeout < 1)
1099 self._apply(timeout, true).then(function(rv) {
1102 deferred.rejectWith(self, [ rv ]);
1106 var try_deadline = date.getTime() + 1000 * timeout;
1107 var try_confirm = function()
1109 return self._confirm().then(function(rv) {
1112 if (date.getTime() < try_deadline)
1113 window.setTimeout(try_confirm, 250);
1115 deferred.rejectWith(self, [ rv ]);
1120 deferred.resolveWith(self, [ rv ]);
1124 window.setTimeout(try_confirm, 1000);
1130 changes: _luci2.rpc.declare({
1133 expect: { changes: { } }
1136 readable: function(conf)
1138 return _luci2.session.hasACL('uci', conf, 'read');
1141 writable: function(conf)
1143 return _luci2.session.hasACL('uci', conf, 'write');
1149 writable: function()
1151 return _luci2.session.access('ubus', 'uci', 'commit');
1154 add: _luci2.rpc.declare({
1157 params: [ 'config', 'type', 'name', 'values' ],
1158 expect: { section: '' }
1166 configs: _luci2.rpc.declare({
1169 expect: { configs: [ ] }
1172 _changes: _luci2.rpc.declare({
1175 params: [ 'config' ],
1176 expect: { changes: [ ] }
1179 changes: function(config)
1181 if (typeof(config) == 'string')
1182 return this._changes(config);
1185 return this.configs().then(function(configs) {
1187 configlist = configs;
1189 for (var i = 0; i < configs.length; i++)
1190 _luci2.uci._changes(configs[i]);
1192 return _luci2.rpc.flush();
1193 }).then(function(changes) {
1196 for (var i = 0; i < configlist.length; i++)
1197 if (changes[i].length)
1198 rv[configlist[i]] = changes[i];
1204 commit: _luci2.rpc.declare({
1207 params: [ 'config' ]
1210 _delete_one: _luci2.rpc.declare({
1213 params: [ 'config', 'section', 'option' ]
1216 _delete_multiple: _luci2.rpc.declare({
1219 params: [ 'config', 'section', 'options' ]
1222 'delete': function(config, section, option)
1224 if ($.isArray(option))
1225 return this._delete_multiple(config, section, option);
1227 return this._delete_one(config, section, option);
1230 delete_all: _luci2.rpc.declare({
1233 params: [ 'config', 'type', 'match' ]
1236 _foreach: _luci2.rpc.declare({
1239 params: [ 'config', 'type' ],
1240 expect: { values: { } }
1243 foreach: function(config, type, cb)
1245 return this._foreach(config, type).then(function(sections) {
1246 for (var s in sections)
1251 get: _luci2.rpc.declare({
1254 params: [ 'config', 'section', 'option' ],
1255 expect: { '': { } },
1256 filter: function(data, params) {
1257 if (typeof(params.option) == 'undefined')
1258 return data.values ? data.values['.type'] : undefined;
1264 get_all: _luci2.rpc.declare({
1267 params: [ 'config', 'section' ],
1268 expect: { values: { } },
1269 filter: function(data, params) {
1270 if (typeof(params.section) == 'string')
1271 data['.section'] = params.section;
1272 else if (typeof(params.config) == 'string')
1273 data['.package'] = params.config;
1278 get_first: function(config, type, option)
1280 return this._foreach(config, type).then(function(sections) {
1281 for (var s in sections)
1283 var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
1285 if (typeof(val) != 'undefined')
1293 section: _luci2.rpc.declare({
1296 params: [ 'config', 'type', 'name', 'values' ],
1297 expect: { section: '' }
1300 _set: _luci2.rpc.declare({
1303 params: [ 'config', 'section', 'values' ]
1306 set: function(config, section, option, value)
1308 if (typeof(value) == 'undefined' && typeof(option) == 'string')
1309 return this.section(config, section, option); /* option -> type */
1310 else if ($.isPlainObject(option))
1311 return this._set(config, section, option); /* option -> values */
1314 values[option] = value;
1316 return this._set(config, section, values);
1319 order: _luci2.rpc.declare({
1322 params: [ 'config', 'sections' ]
1327 listNetworkNames: function() {
1328 return _luci2.rpc.list('network.interface.*').then(function(list) {
1330 for (var name in list)
1331 if (name != 'network.interface.loopback')
1332 names.push(name.substring(18));
1338 listDeviceNames: _luci2.rpc.declare({
1339 object: 'network.device',
1341 expect: { '': { } },
1342 filter: function(data) {
1344 for (var name in data)
1352 getNetworkStatus: function()
1357 return this.listNetworkNames().then(function(names) {
1360 for (var i = 0; i < names.length; i++)
1361 _luci2.network.getInterfaceStatus(names[i]);
1363 return _luci2.rpc.flush();
1364 }).then(function(networks) {
1365 for (var i = 0; i < networks.length; i++)
1367 var net = nets[i] = networks[i];
1368 var dev = net.l3_device || net.l2_device;
1370 net.device = devs[dev] || (devs[dev] = { });
1375 for (var dev in devs)
1376 _luci2.network.getDeviceStatus(dev);
1378 return _luci2.rpc.flush();
1379 }).then(function(devices) {
1382 for (var i = 0; i < devices.length; i++)
1384 var brm = devices[i]['bridge-members'];
1385 delete devices[i]['bridge-members'];
1387 $.extend(devs[devices[i]['device']], devices[i]);
1392 devs[devices[i]['device']].subdevices = [ ];
1394 for (var j = 0; j < brm.length; j++)
1399 _luci2.network.getDeviceStatus(brm[j]);
1402 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
1406 return _luci2.rpc.flush();
1407 }).then(function(subdevices) {
1408 for (var i = 0; i < subdevices.length; i++)
1409 $.extend(devs[subdevices[i]['device']], subdevices[i]);
1413 for (var dev in devs)
1414 _luci2.wireless.getDeviceStatus(dev);
1416 return _luci2.rpc.flush();
1417 }).then(function(wifidevices) {
1418 for (var i = 0; i < wifidevices.length; i++)
1420 devs[wifidevices[i]['device']].wireless = wifidevices[i];
1422 nets.sort(function(a, b) {
1423 if (a['interface'] < b['interface'])
1425 else if (a['interface'] > b['interface'])
1435 findWanInterfaces: function(cb)
1437 return this.listNetworkNames().then(function(names) {
1440 for (var i = 0; i < names.length; i++)
1441 _luci2.network.getInterfaceStatus(names[i]);
1443 return _luci2.rpc.flush();
1444 }).then(function(interfaces) {
1445 var rv = [ undefined, undefined ];
1447 for (var i = 0; i < interfaces.length; i++)
1449 if (!interfaces[i].route)
1452 for (var j = 0; j < interfaces[i].route.length; j++)
1454 var rt = interfaces[i].route[j];
1456 if (typeof(rt.table) != 'undefined')
1459 if (rt.target == '0.0.0.0' && rt.mask == 0)
1460 rv[0] = interfaces[i];
1461 else if (rt.target == '::' && rt.mask == 0)
1462 rv[1] = interfaces[i];
1470 getDHCPLeases: _luci2.rpc.declare({
1471 object: 'luci2.network',
1472 method: 'dhcp_leases',
1473 expect: { leases: [ ] }
1476 getDHCPv6Leases: _luci2.rpc.declare({
1477 object: 'luci2.network',
1478 method: 'dhcp6_leases',
1479 expect: { leases: [ ] }
1482 getRoutes: _luci2.rpc.declare({
1483 object: 'luci2.network',
1485 expect: { routes: [ ] }
1488 getIPv6Routes: _luci2.rpc.declare({
1489 object: 'luci2.network',
1491 expect: { routes: [ ] }
1494 getARPTable: _luci2.rpc.declare({
1495 object: 'luci2.network',
1496 method: 'arp_table',
1497 expect: { entries: [ ] }
1500 getInterfaceStatus: _luci2.rpc.declare({
1501 object: 'network.interface',
1503 params: [ 'interface' ],
1504 expect: { '': { } },
1505 filter: function(data, params) {
1506 data['interface'] = params['interface'];
1507 data['l2_device'] = data['device'];
1508 delete data['device'];
1513 getDeviceStatus: _luci2.rpc.declare({
1514 object: 'network.device',
1517 expect: { '': { } },
1518 filter: function(data, params) {
1519 data['device'] = params['name'];
1524 getConntrackCount: _luci2.rpc.declare({
1525 object: 'luci2.network',
1526 method: 'conntrack_count',
1527 expect: { '': { count: 0, limit: 0 } }
1530 listSwitchNames: _luci2.rpc.declare({
1531 object: 'luci2.network',
1532 method: 'switch_list',
1533 expect: { switches: [ ] }
1536 getSwitchInfo: _luci2.rpc.declare({
1537 object: 'luci2.network',
1538 method: 'switch_info',
1539 params: [ 'switch' ],
1540 expect: { info: { } },
1541 filter: function(data, params) {
1542 data['attrs'] = data['switch'];
1543 data['vlan_attrs'] = data['vlan'];
1544 data['port_attrs'] = data['port'];
1545 data['switch'] = params['switch'];
1554 getSwitchStatus: _luci2.rpc.declare({
1555 object: 'luci2.network',
1556 method: 'switch_status',
1557 params: [ 'switch' ],
1558 expect: { ports: [ ] }
1562 runPing: _luci2.rpc.declare({
1563 object: 'luci2.network',
1566 expect: { '': { code: -1 } }
1569 runPing6: _luci2.rpc.declare({
1570 object: 'luci2.network',
1573 expect: { '': { code: -1 } }
1576 runTraceroute: _luci2.rpc.declare({
1577 object: 'luci2.network',
1578 method: 'traceroute',
1580 expect: { '': { code: -1 } }
1583 runTraceroute6: _luci2.rpc.declare({
1584 object: 'luci2.network',
1585 method: 'traceroute6',
1587 expect: { '': { code: -1 } }
1590 runNslookup: _luci2.rpc.declare({
1591 object: 'luci2.network',
1594 expect: { '': { code: -1 } }
1598 setUp: _luci2.rpc.declare({
1599 object: 'luci2.network',
1602 expect: { '': { code: -1 } }
1605 setDown: _luci2.rpc.declare({
1606 object: 'luci2.network',
1609 expect: { '': { code: -1 } }
1614 listDeviceNames: _luci2.rpc.declare({
1617 expect: { 'devices': [ ] },
1618 filter: function(data) {
1624 getDeviceStatus: _luci2.rpc.declare({
1627 params: [ 'device' ],
1628 expect: { '': { } },
1629 filter: function(data, params) {
1630 if (!$.isEmptyObject(data))
1632 data['device'] = params['device'];
1639 getAssocList: _luci2.rpc.declare({
1641 method: 'assoclist',
1642 params: [ 'device' ],
1643 expect: { results: [ ] },
1644 filter: function(data, params) {
1645 for (var i = 0; i < data.length; i++)
1646 data[i]['device'] = params['device'];
1648 data.sort(function(a, b) {
1649 if (a.bssid < b.bssid)
1651 else if (a.bssid > b.bssid)
1661 getWirelessStatus: function() {
1662 return this.listDeviceNames().then(function(names) {
1665 for (var i = 0; i < names.length; i++)
1666 _luci2.wireless.getDeviceStatus(names[i]);
1668 return _luci2.rpc.flush();
1669 }).then(function(networks) {
1673 'country', 'channel', 'frequency', 'frequency_offset',
1674 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1678 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1679 'signal', 'noise', 'bitrate', 'encryption'
1682 for (var i = 0; i < networks.length; i++)
1684 var phy = rv[networks[i].phy] || (
1685 rv[networks[i].phy] = { networks: [ ] }
1689 device: networks[i].device
1692 for (var j = 0; j < phy_attrs.length; j++)
1693 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1695 for (var j = 0; j < net_attrs.length; j++)
1696 net[net_attrs[j]] = networks[i][net_attrs[j]];
1698 phy.networks.push(net);
1705 getAssocLists: function()
1707 return this.listDeviceNames().then(function(names) {
1710 for (var i = 0; i < names.length; i++)
1711 _luci2.wireless.getAssocList(names[i]);
1713 return _luci2.rpc.flush();
1714 }).then(function(assoclists) {
1717 for (var i = 0; i < assoclists.length; i++)
1718 for (var j = 0; j < assoclists[i].length; j++)
1719 rv.push(assoclists[i][j]);
1725 formatEncryption: function(enc)
1727 var format_list = function(l, s)
1730 for (var i = 0; i < l.length; i++)
1731 rv.push(l[i].toUpperCase());
1732 return rv.join(s ? s : ', ');
1735 if (!enc || !enc.enabled)
1736 return _luci2.tr('None');
1740 if (enc.wep.length == 2)
1741 return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1742 else if (enc.wep[0] == 'shared')
1743 return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1745 return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1749 if (enc.wpa.length == 2)
1750 return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1751 format_list(enc.authentication, '/'),
1752 format_list(enc.ciphers, ', ')
1754 else if (enc.wpa[0] == 2)
1755 return 'WPA2 %s (%s)'.format(
1756 format_list(enc.authentication, '/'),
1757 format_list(enc.ciphers, ', ')
1760 return 'WPA %s (%s)'.format(
1761 format_list(enc.authentication, '/'),
1762 format_list(enc.ciphers, ', ')
1766 return _luci2.tr('Unknown');
1771 getZoneColor: function(zone)
1773 if ($.isPlainObject(zone))
1778 else if (zone == 'wan')
1781 for (var i = 0, hash = 0;
1783 hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1785 for (var i = 0, color = '#';
1787 color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1792 findZoneByNetwork: function(network)
1795 var zone = undefined;
1797 return _luci2.uci.foreach('firewall', 'zone', function(z) {
1798 if (!z.name || !z.network)
1801 if (!$.isArray(z.network))
1802 z.network = z.network.split(/\s+/);
1804 for (var i = 0; i < z.network.length; i++)
1806 if (z.network[i] == network)
1812 }).then(function() {
1814 zone.color = self.getZoneColor(zone);
1822 getSystemInfo: _luci2.rpc.declare({
1828 getBoardInfo: _luci2.rpc.declare({
1834 getDiskInfo: _luci2.rpc.declare({
1835 object: 'luci2.system',
1840 getInfo: function(cb)
1844 this.getSystemInfo();
1845 this.getBoardInfo();
1848 return _luci2.rpc.flush().then(function(info) {
1851 $.extend(rv, info[0]);
1852 $.extend(rv, info[1]);
1853 $.extend(rv, info[2]);
1859 getProcessList: _luci2.rpc.declare({
1860 object: 'luci2.system',
1861 method: 'process_list',
1862 expect: { processes: [ ] },
1863 filter: function(data) {
1864 data.sort(function(a, b) { return a.pid - b.pid });
1869 getSystemLog: _luci2.rpc.declare({
1870 object: 'luci2.system',
1875 getKernelLog: _luci2.rpc.declare({
1876 object: 'luci2.system',
1881 getZoneInfo: function(cb)
1883 return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1886 sendSignal: _luci2.rpc.declare({
1887 object: 'luci2.system',
1888 method: 'process_signal',
1889 params: [ 'pid', 'signal' ],
1890 filter: function(data) {
1895 initList: _luci2.rpc.declare({
1896 object: 'luci2.system',
1897 method: 'init_list',
1898 expect: { initscripts: [ ] },
1899 filter: function(data) {
1900 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1905 initEnabled: function(init, cb)
1907 return this.initList().then(function(list) {
1908 for (var i = 0; i < list.length; i++)
1909 if (list[i].name == init)
1910 return !!list[i].enabled;
1916 initRun: _luci2.rpc.declare({
1917 object: 'luci2.system',
1918 method: 'init_action',
1919 params: [ 'name', 'action' ],
1920 filter: function(data) {
1925 initStart: function(init, cb) { return _luci2.system.initRun(init, 'start', cb) },
1926 initStop: function(init, cb) { return _luci2.system.initRun(init, 'stop', cb) },
1927 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1928 initReload: function(init, cb) { return _luci2.system.initRun(init, 'reload', cb) },
1929 initEnable: function(init, cb) { return _luci2.system.initRun(init, 'enable', cb) },
1930 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1933 getRcLocal: _luci2.rpc.declare({
1934 object: 'luci2.system',
1935 method: 'rclocal_get',
1936 expect: { data: '' }
1939 setRcLocal: _luci2.rpc.declare({
1940 object: 'luci2.system',
1941 method: 'rclocal_set',
1946 getCrontab: _luci2.rpc.declare({
1947 object: 'luci2.system',
1948 method: 'crontab_get',
1949 expect: { data: '' }
1952 setCrontab: _luci2.rpc.declare({
1953 object: 'luci2.system',
1954 method: 'crontab_set',
1959 getSSHKeys: _luci2.rpc.declare({
1960 object: 'luci2.system',
1961 method: 'sshkeys_get',
1962 expect: { keys: [ ] }
1965 setSSHKeys: _luci2.rpc.declare({
1966 object: 'luci2.system',
1967 method: 'sshkeys_set',
1972 setPassword: _luci2.rpc.declare({
1973 object: 'luci2.system',
1974 method: 'password_set',
1975 params: [ 'user', 'password' ]
1979 listLEDs: _luci2.rpc.declare({
1980 object: 'luci2.system',
1982 expect: { leds: [ ] }
1985 listUSBDevices: _luci2.rpc.declare({
1986 object: 'luci2.system',
1988 expect: { devices: [ ] }
1992 testUpgrade: _luci2.rpc.declare({
1993 object: 'luci2.system',
1994 method: 'upgrade_test',
1998 startUpgrade: _luci2.rpc.declare({
1999 object: 'luci2.system',
2000 method: 'upgrade_start',
2004 cleanUpgrade: _luci2.rpc.declare({
2005 object: 'luci2.system',
2006 method: 'upgrade_clean'
2010 restoreBackup: _luci2.rpc.declare({
2011 object: 'luci2.system',
2012 method: 'backup_restore'
2015 cleanBackup: _luci2.rpc.declare({
2016 object: 'luci2.system',
2017 method: 'backup_clean'
2021 getBackupConfig: _luci2.rpc.declare({
2022 object: 'luci2.system',
2023 method: 'backup_config_get',
2024 expect: { config: '' }
2027 setBackupConfig: _luci2.rpc.declare({
2028 object: 'luci2.system',
2029 method: 'backup_config_set',
2034 listBackup: _luci2.rpc.declare({
2035 object: 'luci2.system',
2036 method: 'backup_list',
2037 expect: { files: [ ] }
2041 testReset: _luci2.rpc.declare({
2042 object: 'luci2.system',
2043 method: 'reset_test',
2044 expect: { supported: false }
2047 startReset: _luci2.rpc.declare({
2048 object: 'luci2.system',
2049 method: 'reset_start'
2053 performReboot: _luci2.rpc.declare({
2054 object: 'luci2.system',
2060 updateLists: _luci2.rpc.declare({
2061 object: 'luci2.opkg',
2066 _allPackages: _luci2.rpc.declare({
2067 object: 'luci2.opkg',
2069 params: [ 'offset', 'limit', 'pattern' ],
2073 _installedPackages: _luci2.rpc.declare({
2074 object: 'luci2.opkg',
2075 method: 'list_installed',
2076 params: [ 'offset', 'limit', 'pattern' ],
2080 _findPackages: _luci2.rpc.declare({
2081 object: 'luci2.opkg',
2083 params: [ 'offset', 'limit', 'pattern' ],
2087 _fetchPackages: function(action, offset, limit, pattern)
2091 return action(offset, limit, pattern).then(function(list) {
2092 if (!list.total || !list.packages)
2093 return { length: 0, total: 0 };
2095 packages.push.apply(packages, list.packages);
2096 packages.total = list.total;
2101 if (packages.length >= limit)
2106 for (var i = offset + packages.length; i < limit; i += 100)
2107 action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
2109 return _luci2.rpc.flush();
2110 }).then(function(lists) {
2111 for (var i = 0; i < lists.length; i++)
2113 if (!lists[i].total || !lists[i].packages)
2116 packages.push.apply(packages, lists[i].packages);
2117 packages.total = lists[i].total;
2124 listPackages: function(offset, limit, pattern)
2126 return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
2129 installedPackages: function(offset, limit, pattern)
2131 return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
2134 findPackages: function(offset, limit, pattern)
2136 return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
2139 installPackage: _luci2.rpc.declare({
2140 object: 'luci2.opkg',
2142 params: [ 'package' ],
2146 removePackage: _luci2.rpc.declare({
2147 object: 'luci2.opkg',
2149 params: [ 'package' ],
2153 getConfig: _luci2.rpc.declare({
2154 object: 'luci2.opkg',
2155 method: 'config_get',
2156 expect: { config: '' }
2159 setConfig: _luci2.rpc.declare({
2160 object: 'luci2.opkg',
2161 method: 'config_set',
2168 login: _luci2.rpc.declare({
2171 params: [ 'username', 'password' ],
2175 access: _luci2.rpc.declare({
2178 params: [ 'scope', 'object', 'function' ],
2179 expect: { access: false }
2184 return _luci2.session.access('ubus', 'session', 'access');
2187 startHeartbeat: function()
2189 this._hearbeatInterval = window.setInterval(function() {
2190 _luci2.session.isAlive().then(function(alive) {
2193 _luci2.session.stopHeartbeat();
2194 _luci2.ui.login(true);
2198 }, _luci2.globals.timeout * 2);
2201 stopHeartbeat: function()
2203 if (typeof(this._hearbeatInterval) != 'undefined')
2205 window.clearInterval(this._hearbeatInterval);
2206 delete this._hearbeatInterval;
2213 saveScrollTop: function()
2215 this._scroll_top = $(document).scrollTop();
2218 restoreScrollTop: function()
2220 if (typeof(this._scroll_top) == 'undefined')
2223 $(document).scrollTop(this._scroll_top);
2225 delete this._scroll_top;
2228 loading: function(enable)
2230 var win = $(window);
2231 var body = $('body');
2233 var state = _luci2.ui._loading || (_luci2.ui._loading = {
2235 .addClass('modal fade')
2236 .append($('<div />')
2237 .addClass('modal-dialog')
2238 .append($('<div />')
2239 .addClass('modal-content luci2-modal-loader')
2240 .append($('<div />')
2241 .addClass('modal-body')
2242 .text(_luci2.tr('Loading data…')))))
2250 state.modal.modal(enable ? 'show' : 'hide');
2253 dialog: function(title, content, options)
2255 var win = $(window);
2256 var body = $('body');
2258 var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
2259 dialog: $('<div />')
2260 .addClass('modal fade')
2261 .append($('<div />')
2262 .addClass('modal-dialog')
2263 .append($('<div />')
2264 .addClass('modal-content')
2265 .append($('<div />')
2266 .addClass('modal-header')
2268 .addClass('modal-title'))
2269 .append($('<div />')
2270 .addClass('modal-body'))
2271 .append($('<div />')
2272 .addClass('modal-footer')
2273 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2275 $(this).parents('div.modal').modal('hide');
2280 if (typeof(options) != 'object')
2283 if (title === false)
2285 state.dialog.modal('hide');
2290 var cnt = state.dialog.children().children().children('div.modal-body');
2291 var ftr = state.dialog.children().children().children('div.modal-footer');
2295 if (options.style == 'confirm')
2297 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
2298 .click(options.confirm || function() { _luci2.ui.dialog(false) }));
2300 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
2301 .click(options.cancel || function() { _luci2.ui.dialog(false) }));
2303 else if (options.style == 'close')
2305 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2306 .click(options.close || function() { _luci2.ui.dialog(false) }));
2308 else if (options.style == 'wait')
2310 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
2311 .attr('disabled', true));
2314 state.dialog.find('h4:first').text(title);
2315 state.dialog.modal('show');
2317 cnt.empty().append(content);
2320 upload: function(title, content, options)
2322 var state = _luci2.ui._upload || (_luci2.ui._upload = {
2324 .attr('method', 'post')
2325 .attr('action', '/cgi-bin/luci-upload')
2326 .attr('enctype', 'multipart/form-data')
2327 .attr('target', 'cbi-fileupload-frame')
2329 .append($('<input />')
2330 .attr('type', 'hidden')
2331 .attr('name', 'sessionid'))
2332 .append($('<input />')
2333 .attr('type', 'hidden')
2334 .attr('name', 'filename'))
2335 .append($('<input />')
2336 .attr('type', 'file')
2337 .attr('name', 'filedata')
2338 .addClass('cbi-input-file'))
2339 .append($('<div />')
2340 .css('width', '100%')
2341 .addClass('progress progress-striped active')
2342 .append($('<div />')
2343 .addClass('progress-bar')
2344 .css('width', '100%')))
2345 .append($('<iframe />')
2346 .addClass('pull-right')
2347 .attr('name', 'cbi-fileupload-frame')
2348 .css('width', '1px')
2349 .css('height', '1px')
2350 .css('visibility', 'hidden')),
2352 finish_cb: function(ev) {
2353 $(this).off('load');
2355 var body = (this.contentDocument || this.contentWindow.document).body;
2356 if (body.firstChild.tagName.toLowerCase() == 'pre')
2357 body = body.firstChild;
2361 json = $.parseJSON(body.innerHTML);
2364 message: _luci2.tr('Invalid server response received'),
2365 error: [ -1, _luci2.tr('Invalid data') ]
2371 L.ui.dialog(L.tr('File upload'), [
2372 $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
2373 $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
2374 $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
2375 ], { style: 'close' });
2377 else if (typeof(state.success_cb) == 'function')
2379 state.success_cb(json);
2383 confirm_cb: function() {
2384 var f = state.form.find('.cbi-input-file');
2385 var b = state.form.find('.progress');
2386 var p = state.form.find('p');
2391 state.form.find('iframe').on('load', state.finish_cb);
2392 state.form.submit();
2396 p.text(_luci2.tr('File upload in progress …'));
2398 state.form.parent().parent().find('button').prop('disabled', true);
2402 state.form.find('.progress').hide();
2403 state.form.find('.cbi-input-file').val('').show();
2404 state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
2406 state.form.find('[name=sessionid]').val(_luci2.globals.sid);
2407 state.form.find('[name=filename]').val(options.filename);
2409 state.success_cb = options.success;
2411 _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
2413 confirm: state.confirm_cb
2417 reconnect: function()
2419 var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
2420 var ports = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
2421 var address = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
2423 var interval, timeout;
2426 _luci2.tr('Waiting for device'), [
2427 $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
2429 .css('width', '100%')
2430 .addClass('progressbar')
2431 .addClass('intermediate')
2432 .append($('<div />')
2433 .css('width', '100%'))
2434 ], { style: 'wait' }
2437 for (var i = 0; i < protocols.length; i++)
2438 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
2440 //_luci2.network.getNetworkStatus(function(s) {
2441 // for (var i = 0; i < protocols.length; i++)
2443 // for (var j = 0; j < s.length; j++)
2445 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
2446 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
2448 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
2449 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
2452 //}).then(function() {
2453 images.on('load', function() {
2454 var url = this.getAttribute('url');
2455 _luci2.session.isAlive().then(function(access) {
2458 window.clearTimeout(timeout);
2459 window.clearInterval(interval);
2460 _luci2.ui.dialog(false);
2465 location.href = url;
2470 interval = window.setInterval(function() {
2471 images.each(function() {
2472 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
2476 timeout = window.setTimeout(function() {
2477 window.clearInterval(interval);
2481 _luci2.tr('Device not responding'),
2482 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2489 login: function(invalid)
2491 var state = _luci2.ui._login || (_luci2.ui._login = {
2494 .attr('method', 'post')
2496 .addClass('alert-message')
2497 .text(_luci2.tr('Wrong username or password given!')))
2499 .append($('<label />')
2500 .text(_luci2.tr('Username'))
2501 .append($('<br />'))
2502 .append($('<input />')
2503 .attr('type', 'text')
2504 .attr('name', 'username')
2505 .attr('value', 'root')
2506 .addClass('form-control')
2507 .keypress(function(ev) {
2508 if (ev.which == 10 || ev.which == 13)
2512 .append($('<label />')
2513 .text(_luci2.tr('Password'))
2514 .append($('<br />'))
2515 .append($('<input />')
2516 .attr('type', 'password')
2517 .attr('name', 'password')
2518 .addClass('form-control')
2519 .keypress(function(ev) {
2520 if (ev.which == 10 || ev.which == 13)
2524 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2526 response_cb: function(response) {
2527 if (!response.ubus_rpc_session)
2529 _luci2.ui.login(true);
2533 _luci2.globals.sid = response.ubus_rpc_session;
2534 _luci2.setHash('id', _luci2.globals.sid);
2535 _luci2.session.startHeartbeat();
2536 _luci2.ui.dialog(false);
2537 state.deferred.resolve();
2541 confirm_cb: function() {
2542 var u = state.form.find('[name=username]').val();
2543 var p = state.form.find('[name=password]').val();
2549 _luci2.tr('Logging in'), [
2550 $('<p />').text(_luci2.tr('Log in in progress …')),
2552 .css('width', '100%')
2553 .addClass('progressbar')
2554 .addClass('intermediate')
2555 .append($('<div />')
2556 .css('width', '100%'))
2557 ], { style: 'wait' }
2560 _luci2.globals.sid = '00000000000000000000000000000000';
2561 _luci2.session.login(u, p).then(state.response_cb);
2565 if (!state.deferred || state.deferred.state() != 'pending')
2566 state.deferred = $.Deferred();
2568 /* try to find sid from hash */
2569 var sid = _luci2.getHash('id');
2570 if (sid && sid.match(/^[a-f0-9]{32}$/))
2572 _luci2.globals.sid = sid;
2573 _luci2.session.isAlive().then(function(access) {
2576 _luci2.session.startHeartbeat();
2577 state.deferred.resolve();
2581 _luci2.setHash('id', undefined);
2586 return state.deferred;
2590 state.form.find('.alert-message').show();
2592 state.form.find('.alert-message').hide();
2594 _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2596 confirm: state.confirm_cb
2599 state.form.find('[name=password]').focus();
2601 return state.deferred;
2604 cryptPassword: _luci2.rpc.declare({
2608 expect: { crypt: '' }
2612 _acl_merge_scope: function(acl_scope, scope)
2614 if ($.isArray(scope))
2616 for (var i = 0; i < scope.length; i++)
2617 acl_scope[scope[i]] = true;
2619 else if ($.isPlainObject(scope))
2621 for (var object_name in scope)
2623 if (!$.isArray(scope[object_name]))
2626 var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2628 for (var i = 0; i < scope[object_name].length; i++)
2629 acl_object[scope[object_name][i]] = true;
2634 _acl_merge_permission: function(acl_perm, perm)
2636 if ($.isPlainObject(perm))
2638 for (var scope_name in perm)
2640 var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2641 this._acl_merge_scope(acl_scope, perm[scope_name]);
2646 _acl_merge_group: function(acl_group, group)
2648 if ($.isPlainObject(group))
2650 if (!acl_group.description)
2651 acl_group.description = group.description;
2655 var acl_perm = acl_group.read || (acl_group.read = { });
2656 this._acl_merge_permission(acl_perm, group.read);
2661 var acl_perm = acl_group.write || (acl_group.write = { });
2662 this._acl_merge_permission(acl_perm, group.write);