4e872188d0082c52a1b128273e10888e0066a593
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
1 /*
2         LuCI2 - OpenWrt Web Interface
3
4         Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
5
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
9
10                 http://www.apache.org/licenses/LICENSE-2.0
11 */
12
13 String.prototype.format = function()
14 {
15         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
16         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
17
18         function esc(s, r) {
19                 for( var i = 0; i < r.length; i += 2 )
20                         s = s.replace(r[i], r[i+1]);
21                 return s;
22         }
23
24         var str = this;
25         var out = '';
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;
28
29         while ((a = re.exec(str)) != null)
30         {
31                 var m = a[1];
32                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33                 var pPrecision = a[6], pType = a[7];
34
35                 numMatches++;
36
37                 if (pType == '%')
38                 {
39                         subst = '%';
40                 }
41                 else
42                 {
43                         if (numSubstitutions < arguments.length)
44                         {
45                                 var param = arguments[numSubstitutions++];
46
47                                 var pad = '';
48                                 if (pPad && pPad.substr(0,1) == "'")
49                                         pad = leftpart.substr(1,1);
50                                 else if (pPad)
51                                         pad = pPad;
52
53                                 var justifyRight = true;
54                                 if (pJustify && pJustify === "-")
55                                         justifyRight = false;
56
57                                 var minLength = -1;
58                                 if (pMinLength)
59                                         minLength = parseInt(pMinLength);
60
61                                 var precision = -1;
62                                 if (pPrecision && pType == 'f')
63                                         precision = parseInt(pPrecision.substring(1));
64
65                                 var subst = param;
66
67                                 switch(pType)
68                                 {
69                                         case 'b':
70                                                 subst = (parseInt(param) || 0).toString(2);
71                                                 break;
72
73                                         case 'c':
74                                                 subst = String.fromCharCode(parseInt(param) || 0);
75                                                 break;
76
77                                         case 'd':
78                                                 subst = (parseInt(param) || 0);
79                                                 break;
80
81                                         case 'u':
82                                                 subst = Math.abs(parseInt(param) || 0);
83                                                 break;
84
85                                         case 'f':
86                                                 subst = (precision > -1)
87                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
88                                                         : (parseFloat(param) || 0.0);
89                                                 break;
90
91                                         case 'o':
92                                                 subst = (parseInt(param) || 0).toString(8);
93                                                 break;
94
95                                         case 's':
96                                                 subst = param;
97                                                 break;
98
99                                         case 'x':
100                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
101                                                 break;
102
103                                         case 'X':
104                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
105                                                 break;
106
107                                         case 'h':
108                                                 subst = esc(param, html_esc);
109                                                 break;
110
111                                         case 'q':
112                                                 subst = esc(param, quot_esc);
113                                                 break;
114
115                                         case 'j':
116                                                 subst = String.serialize(param);
117                                                 break;
118
119                                         case 't':
120                                                 var td = 0;
121                                                 var th = 0;
122                                                 var tm = 0;
123                                                 var ts = (param || 0);
124
125                                                 if (ts > 60) {
126                                                         tm = Math.floor(ts / 60);
127                                                         ts = (ts % 60);
128                                                 }
129
130                                                 if (tm > 60) {
131                                                         th = Math.floor(tm / 60);
132                                                         tm = (tm % 60);
133                                                 }
134
135                                                 if (th > 24) {
136                                                         td = Math.floor(th / 24);
137                                                         th = (th % 24);
138                                                 }
139
140                                                 subst = (td > 0)
141                                                         ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142                                                         : '%dh %dm %ds'.format(th, tm, ts);
143
144                                                 break;
145
146                                         case 'm':
147                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
149
150                                                 var i = 0;
151                                                 var val = parseFloat(param || 0);
152                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
153
154                                                 for (i = 0; (i < units.length) && (val > mf); i++)
155                                                         val /= mf;
156
157                                                 subst = val.toFixed(pr) + ' ' + units[i];
158                                                 break;
159                                 }
160
161                                 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
162
163                                 if (minLength > 0 && pad.length > 0)
164                                         for (var i = 0; i < (minLength - subst.length); i++)
165                                                 subst = justifyRight ? (pad + subst) : (subst + pad);
166                         }
167                 }
168
169                 out += leftpart + subst;
170                 str = str.substr(m.length);
171         }
172
173         return out + str;
174 }
175
176 function LuCI2()
177 {
178         var _luci2 = this;
179
180         var Class = function() { };
181
182         Class.extend = function(properties)
183         {
184                 Class.initializing = true;
185
186                 var prototype = new this();
187                 var superprot = this.prototype;
188
189                 Class.initializing = false;
190
191                 $.extend(prototype, properties, {
192                         callSuper: function() {
193                                 var args = [ ];
194                                 var meth = arguments[0];
195
196                                 if (typeof(superprot[meth]) != 'function')
197                                         return undefined;
198
199                                 for (var i = 1; i < arguments.length; i++)
200                                         args.push(arguments[i]);
201
202                                 return superprot[meth].apply(this, args);
203                         }
204                 });
205
206                 function _class()
207                 {
208                         this.options = arguments[0] || { };
209
210                         if (!Class.initializing && typeof(this.init) == 'function')
211                                 this.init.apply(this, arguments);
212                 }
213
214                 _class.prototype = prototype;
215                 _class.prototype.constructor = _class;
216
217                 _class.extend = Class.extend;
218
219                 return _class;
220         };
221
222         this.defaults = function(obj, def)
223         {
224                 for (var key in def)
225                         if (typeof(obj[key]) == 'undefined')
226                                 obj[key] = def[key];
227
228                 return obj;
229         };
230
231         this.isDeferred = function(x)
232         {
233                 return (typeof(x) == 'object' &&
234                         typeof(x.then) == 'function' &&
235                         typeof(x.promise) == 'function');
236         };
237
238         this.deferrable = function()
239         {
240                 if (this.isDeferred(arguments[0]))
241                         return arguments[0];
242
243                 var d = $.Deferred();
244                     d.resolve.apply(d, arguments);
245
246                 return d.promise();
247         };
248
249         this.i18n = {
250
251                 loaded: false,
252                 catalog: { },
253                 plural:  function(n) { return 0 + (n != 1) },
254
255                 init: function() {
256                         if (_luci2.i18n.loaded)
257                                 return;
258
259                         var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260                         var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
261
262                         for (var i = 0; i < langs.length; i++)
263                                 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
264                                         async:    false,
265                                         cache:    true,
266                                         dataType: 'json',
267                                         success:  function(data) {
268                                                 $.extend(_luci2.i18n.catalog, data);
269
270                                                 var pe = _luci2.i18n.catalog[''];
271                                                 if (pe)
272                                                 {
273                                                         delete _luci2.i18n.catalog[''];
274                                                         try {
275                                                                 var pf = new Function('n', 'return 0 + (' + pe + ')');
276                                                                 _luci2.i18n.plural = pf;
277                                                         } catch (e) { };
278                                                 }
279                                         }
280                                 });
281
282                         _luci2.i18n.loaded = true;
283                 }
284
285         };
286
287         this.tr = function(msgid)
288         {
289                 _luci2.i18n.init();
290
291                 var msgstr = _luci2.i18n.catalog[msgid];
292
293                 if (typeof(msgstr) == 'undefined')
294                         return msgid;
295                 else if (typeof(msgstr) == 'string')
296                         return msgstr;
297                 else
298                         return msgstr[0];
299         };
300
301         this.trp = function(msgid, msgid_plural, count)
302         {
303                 _luci2.i18n.init();
304
305                 var msgstr = _luci2.i18n.catalog[msgid];
306
307                 if (typeof(msgstr) == 'undefined')
308                         return (count == 1) ? msgid : msgid_plural;
309                 else if (typeof(msgstr) == 'string')
310                         return msgstr;
311                 else
312                         return msgstr[_luci2.i18n.plural(count)];
313         };
314
315         this.trc = function(msgctx, msgid)
316         {
317                 _luci2.i18n.init();
318
319                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
320
321                 if (typeof(msgstr) == 'undefined')
322                         return msgid;
323                 else if (typeof(msgstr) == 'string')
324                         return msgstr;
325                 else
326                         return msgstr[0];
327         };
328
329         this.trcp = function(msgctx, msgid, msgid_plural, count)
330         {
331                 _luci2.i18n.init();
332
333                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
334
335                 if (typeof(msgstr) == 'undefined')
336                         return (count == 1) ? msgid : msgid_plural;
337                 else if (typeof(msgstr) == 'string')
338                         return msgstr;
339                 else
340                         return msgstr[_luci2.i18n.plural(count)];
341         };
342
343         this.setHash = function(key, value)
344         {
345                 var h = '';
346                 var data = this.getHash(undefined);
347
348                 if (typeof(value) == 'undefined')
349                         delete data[key];
350                 else
351                         data[key] = value;
352
353                 var keys = [ ];
354                 for (var k in data)
355                         keys.push(k);
356
357                 keys.sort();
358
359                 for (var i = 0; i < keys.length; i++)
360                 {
361                         if (i > 0)
362                                 h += ',';
363
364                         h += keys[i] + ':' + data[keys[i]];
365                 }
366
367                 if (h.length)
368                         location.hash = '#' + h;
369                 else
370                         location.hash = '';
371         };
372
373         this.getHash = function(key)
374         {
375                 var data = { };
376                 var tuples = (location.hash || '#').substring(1).split(/,/);
377
378                 for (var i = 0; i < tuples.length; i++)
379                 {
380                         var tuple = tuples[i].split(/:/);
381                         if (tuple.length == 2)
382                                 data[tuple[0]] = tuple[1];
383                 }
384
385                 if (typeof(key) != 'undefined')
386                         return data[key];
387
388                 return data;
389         };
390
391         this.toArray = function(x)
392         {
393                 switch (typeof(x))
394                 {
395                 case 'number':
396                 case 'boolean':
397                         return [ x ];
398
399                 case 'string':
400                         var r = [ ];
401                         var l = x.split(/\s+/);
402                         for (var i = 0; i < l.length; i++)
403                                 if (l[i].length > 0)
404                                         r.push(l[i]);
405                         return r;
406
407                 case 'object':
408                         if ($.isArray(x))
409                         {
410                                 var r = [ ];
411                                 for (var i = 0; i < x.length; i++)
412                                         r.push(x[i]);
413                                 return r;
414                         }
415                         else if ($.isPlainObject(x))
416                         {
417                                 var r = [ ];
418                                 for (var k in x)
419                                         if (x.hasOwnProperty(k))
420                                                 r.push(k);
421                                 return r.sort();
422                         }
423                 }
424
425                 return [ ];
426         };
427
428         this.toObject = function(x)
429         {
430                 switch (typeof(x))
431                 {
432                 case 'number':
433                 case 'boolean':
434                         return { x: true };
435
436                 case 'string':
437                         var r = { };
438                         var l = x.split(/\x+/);
439                         for (var i = 0; i < l.length; i++)
440                                 if (l[i].length > 0)
441                                         r[l[i]] = true;
442                         return r;
443
444                 case 'object':
445                         if ($.isArray(x))
446                         {
447                                 var r = { };
448                                 for (var i = 0; i < x.length; i++)
449                                         r[x[i]] = true;
450                                 return r;
451                         }
452                         else if ($.isPlainObject(x))
453                         {
454                                 return x;
455                         }
456                 }
457
458                 return { };
459         };
460
461         this.filterArray = function(array, item)
462         {
463                 if (!$.isArray(array))
464                         return [ ];
465
466                 for (var i = 0; i < array.length; i++)
467                         if (array[i] === item)
468                                 array.splice(i--, 1);
469
470                 return array;
471         };
472
473         this.toClassName = function(str, suffix)
474         {
475                 var n = '';
476                 var l = str.split(/[\/.]/);
477
478                 for (var i = 0; i < l.length; i++)
479                         if (l[i].length > 0)
480                                 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
481
482                 if (typeof(suffix) == 'string')
483                         n += suffix;
484
485                 return n;
486         };
487
488         this.globals = {
489                 timeout:  15000,
490                 resource: '/luci2',
491                 sid:      '00000000000000000000000000000000'
492         };
493
494         this.rpc = {
495
496                 _id: 1,
497                 _batch: undefined,
498                 _requests: { },
499
500                 _call: function(req, cb)
501                 {
502                         return $.ajax('/ubus', {
503                                 cache:       false,
504                                 contentType: 'application/json',
505                                 data:        JSON.stringify(req),
506                                 dataType:    'json',
507                                 type:        'POST',
508                                 timeout:     _luci2.globals.timeout,
509                                 _rpc_req:   req
510                         }).then(cb, cb);
511                 },
512
513                 _list_cb: function(msg)
514                 {
515                         var list = msg.result;
516
517                         /* verify message frame */
518                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
519                                 list = [ ];
520
521                         return $.Deferred().resolveWith(this, [ list ]);
522                 },
523
524                 _call_cb: function(msg)
525                 {
526                         var data = [ ];
527                         var type = Object.prototype.toString;
528                         var reqs = this._rpc_req;
529
530                         if (!$.isArray(reqs))
531                         {
532                                 msg = [ msg ];
533                                 reqs = [ reqs ];
534                         }
535
536                         for (var i = 0; i < msg.length; i++)
537                         {
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';
542
543                                 /* fetch response attribute and verify returned type */
544                                 var ret = undefined;
545
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];
550
551                                 if (req.expect)
552                                 {
553                                         for (var key in req.expect)
554                                         {
555                                                 if (typeof(ret) != 'undefined' && key != '')
556                                                         ret = ret[key];
557
558                                                 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559                                                         ret = req.expect[key];
560
561                                                 break;
562                                         }
563                                 }
564
565                                 /* apply filter */
566                                 if (typeof(req.filter) == 'function')
567                                 {
568                                         req.priv[0] = ret;
569                                         req.priv[1] = req.params;
570                                         ret = req.filter.apply(_luci2.rpc, req.priv);
571                                 }
572
573                                 /* store response data */
574                                 if (typeof(req.index) == 'number')
575                                         data[req.index] = ret;
576                                 else
577                                         data = ret;
578
579                                 /* delete request object */
580                                 delete _luci2.rpc._requests[reqs[i].id];
581                         }
582
583                         return $.Deferred().resolveWith(this, [ data ]);
584                 },
585
586                 list: function()
587                 {
588                         var params = [ ];
589                         for (var i = 0; i < arguments.length; i++)
590                                 params[i] = arguments[i];
591
592                         var msg = {
593                                 jsonrpc: '2.0',
594                                 id:      this._id++,
595                                 method:  'list',
596                                 params:  (params.length > 0) ? params : undefined
597                         };
598
599                         return this._call(msg, this._list_cb);
600                 },
601
602                 batch: function()
603                 {
604                         if (!$.isArray(this._batch))
605                                 this._batch = [ ];
606                 },
607
608                 flush: function()
609                 {
610                         if (!$.isArray(this._batch))
611                                 return _luci2.deferrable([ ]);
612
613                         var req = this._batch;
614                         delete this._batch;
615
616                         /* call rpc */
617                         return this._call(req, this._call_cb);
618                 },
619
620                 declare: function(options)
621                 {
622                         var _rpc = this;
623
624                         return function() {
625                                 /* build parameter object */
626                                 var p_off = 0;
627                                 var params = { };
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];
631
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]);
636
637                                 /* store request info */
638                                 var req = _rpc._requests[_rpc._id] = {
639                                         expect: options.expect,
640                                         filter: options.filter,
641                                         params: params,
642                                         priv:   priv
643                                 };
644
645                                 /* build message object */
646                                 var msg = {
647                                         jsonrpc: '2.0',
648                                         id:      _rpc._id++,
649                                         method:  'call',
650                                         params:  [
651                                                 _luci2.globals.sid,
652                                                 options.object,
653                                                 options.method,
654                                                 params
655                                         ]
656                                 };
657
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))
661                                 {
662                                         req.index = _rpc._batch.push(msg) - 1;
663                                         return _luci2.deferrable(msg);
664                                 }
665
666                                 /* call rpc */
667                                 return _rpc._call(msg, _rpc._call_cb);
668                         };
669                 }
670         };
671
672         this.uci = {
673
674                 writable: function()
675                 {
676                         return _luci2.session.access('ubus', 'uci', 'commit');
677                 },
678
679                 add: _luci2.rpc.declare({
680                         object: 'uci',
681                         method: 'add',
682                         params: [ 'config', 'type', 'name', 'values' ],
683                         expect: { section: '' }
684                 }),
685
686                 apply: function()
687                 {
688
689                 },
690
691                 configs: _luci2.rpc.declare({
692                         object: 'uci',
693                         method: 'configs',
694                         expect: { configs: [ ] }
695                 }),
696
697                 _changes: _luci2.rpc.declare({
698                         object: 'uci',
699                         method: 'changes',
700                         params: [ 'config' ],
701                         expect: { changes: [ ] }
702                 }),
703
704                 changes: function(config)
705                 {
706                         if (typeof(config) == 'string')
707                                 return this._changes(config);
708
709                         var configlist;
710                         return this.configs().then(function(configs) {
711                                 _luci2.rpc.batch();
712                                 configlist = configs;
713
714                                 for (var i = 0; i < configs.length; i++)
715                                         _luci2.uci._changes(configs[i]);
716
717                                 return _luci2.rpc.flush();
718                         }).then(function(changes) {
719                                 var rv = { };
720
721                                 for (var i = 0; i < configlist.length; i++)
722                                         if (changes[i].length)
723                                                 rv[configlist[i]] = changes[i];
724
725                                 return rv;
726                         });
727                 },
728
729                 commit: _luci2.rpc.declare({
730                         object: 'uci',
731                         method: 'commit',
732                         params: [ 'config' ]
733                 }),
734
735                 _delete_one: _luci2.rpc.declare({
736                         object: 'uci',
737                         method: 'delete',
738                         params: [ 'config', 'section', 'option' ]
739                 }),
740
741                 _delete_multiple: _luci2.rpc.declare({
742                         object: 'uci',
743                         method: 'delete',
744                         params: [ 'config', 'section', 'options' ]
745                 }),
746
747                 'delete': function(config, section, option)
748                 {
749                         if ($.isArray(option))
750                                 return this._delete_multiple(config, section, option);
751                         else
752                                 return this._delete_one(config, section, option);
753                 },
754
755                 delete_all: _luci2.rpc.declare({
756                         object: 'uci',
757                         method: 'delete',
758                         params: [ 'config', 'type', 'match' ]
759                 }),
760
761                 _foreach: _luci2.rpc.declare({
762                         object: 'uci',
763                         method: 'get',
764                         params: [ 'config', 'type' ],
765                         expect: { values: { } }
766                 }),
767
768                 foreach: function(config, type, cb)
769                 {
770                         return this._foreach(config, type).then(function(sections) {
771                                 for (var s in sections)
772                                         cb(sections[s]);
773                         });
774                 },
775
776                 get: _luci2.rpc.declare({
777                         object: 'uci',
778                         method: 'get',
779                         params: [ 'config', 'section', 'option' ],
780                         expect: { '': { } },
781                         filter: function(data, params) {
782                                 if (typeof(params.option) == 'undefined')
783                                         return data.values ? data.values['.type'] : undefined;
784                                 else
785                                         return data.value;
786                         }
787                 }),
788
789                 get_all: _luci2.rpc.declare({
790                         object: 'uci',
791                         method: 'get',
792                         params: [ 'config', 'section' ],
793                         expect: { values: { } },
794                         filter: function(data, params) {
795                                 if (typeof(params.section) == 'string')
796                                         data['.section'] = params.section;
797                                 else if (typeof(params.config) == 'string')
798                                         data['.package'] = params.config;
799                                 return data;
800                         }
801                 }),
802
803                 get_first: function(config, type, option)
804                 {
805                         return this._foreach(config, type).then(function(sections) {
806                                 for (var s in sections)
807                                 {
808                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
809
810                                         if (typeof(val) != 'undefined')
811                                                 return val;
812                                 }
813
814                                 return undefined;
815                         });
816                 },
817
818                 section: _luci2.rpc.declare({
819                         object: 'uci',
820                         method: 'add',
821                         params: [ 'config', 'type', 'name', 'values' ],
822                         expect: { section: '' }
823                 }),
824
825                 _set: _luci2.rpc.declare({
826                         object: 'uci',
827                         method: 'set',
828                         params: [ 'config', 'section', 'values' ]
829                 }),
830
831                 set: function(config, section, option, value)
832                 {
833                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
834                                 return this.section(config, section, option); /* option -> type */
835                         else if ($.isPlainObject(option))
836                                 return this._set(config, section, option); /* option -> values */
837
838                         var values = { };
839                             values[option] = value;
840
841                         return this._set(config, section, values);
842                 },
843
844                 order: _luci2.rpc.declare({
845                         object: 'uci',
846                         method: 'order',
847                         params: [ 'config', 'sections' ]
848                 })
849         };
850
851         this.network = {
852                 listNetworkNames: function() {
853                         return _luci2.rpc.list('network.interface.*').then(function(list) {
854                                 var names = [ ];
855                                 for (var name in list)
856                                         if (name != 'network.interface.loopback')
857                                                 names.push(name.substring(18));
858                                 names.sort();
859                                 return names;
860                         });
861                 },
862
863                 listDeviceNames: _luci2.rpc.declare({
864                         object: 'network.device',
865                         method: 'status',
866                         expect: { '': { } },
867                         filter: function(data) {
868                                 var names = [ ];
869                                 for (var name in data)
870                                         if (name != 'lo')
871                                                 names.push(name);
872                                 names.sort();
873                                 return names;
874                         }
875                 }),
876
877                 getNetworkStatus: function()
878                 {
879                         var nets = [ ];
880                         var devs = { };
881
882                         return this.listNetworkNames().then(function(names) {
883                                 _luci2.rpc.batch();
884
885                                 for (var i = 0; i < names.length; i++)
886                                         _luci2.network.getInterfaceStatus(names[i]);
887
888                                 return _luci2.rpc.flush();
889                         }).then(function(networks) {
890                                 for (var i = 0; i < networks.length; i++)
891                                 {
892                                         var net = nets[i] = networks[i];
893                                         var dev = net.l3_device || net.l2_device;
894                                         if (dev)
895                                                 net.device = devs[dev] || (devs[dev] = { });
896                                 }
897
898                                 _luci2.rpc.batch();
899
900                                 for (var dev in devs)
901                                         _luci2.network.getDeviceStatus(dev);
902
903                                 return _luci2.rpc.flush();
904                         }).then(function(devices) {
905                                 _luci2.rpc.batch();
906
907                                 for (var i = 0; i < devices.length; i++)
908                                 {
909                                         var brm = devices[i]['bridge-members'];
910                                         delete devices[i]['bridge-members'];
911
912                                         $.extend(devs[devices[i]['device']], devices[i]);
913
914                                         if (!brm)
915                                                 continue;
916
917                                         devs[devices[i]['device']].subdevices = [ ];
918
919                                         for (var j = 0; j < brm.length; j++)
920                                         {
921                                                 if (!devs[brm[j]])
922                                                 {
923                                                         devs[brm[j]] = { };
924                                                         _luci2.network.getDeviceStatus(brm[j]);
925                                                 }
926
927                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
928                                         }
929                                 }
930
931                                 return _luci2.rpc.flush();
932                         }).then(function(subdevices) {
933                                 for (var i = 0; i < subdevices.length; i++)
934                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
935
936                                 _luci2.rpc.batch();
937
938                                 for (var dev in devs)
939                                         _luci2.wireless.getDeviceStatus(dev);
940
941                                 return _luci2.rpc.flush();
942                         }).then(function(wifidevices) {
943                                 for (var i = 0; i < wifidevices.length; i++)
944                                         if (wifidevices[i])
945                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
946
947                                 nets.sort(function(a, b) {
948                                         if (a['interface'] < b['interface'])
949                                                 return -1;
950                                         else if (a['interface'] > b['interface'])
951                                                 return 1;
952                                         else
953                                                 return 0;
954                                 });
955
956                                 return nets;
957                         });
958                 },
959
960                 findWanInterfaces: function(cb)
961                 {
962                         return this.listNetworkNames().then(function(names) {
963                                 _luci2.rpc.batch();
964
965                                 for (var i = 0; i < names.length; i++)
966                                         _luci2.network.getInterfaceStatus(names[i]);
967
968                                 return _luci2.rpc.flush();
969                         }).then(function(interfaces) {
970                                 var rv = [ undefined, undefined ];
971
972                                 for (var i = 0; i < interfaces.length; i++)
973                                 {
974                                         if (!interfaces[i].route)
975                                                 continue;
976
977                                         for (var j = 0; j < interfaces[i].route.length; j++)
978                                         {
979                                                 var rt = interfaces[i].route[j];
980
981                                                 if (typeof(rt.table) != 'undefined')
982                                                         continue;
983
984                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
985                                                         rv[0] = interfaces[i];
986                                                 else if (rt.target == '::' && rt.mask == 0)
987                                                         rv[1] = interfaces[i];
988                                         }
989                                 }
990
991                                 return rv;
992                         });
993                 },
994
995                 getDHCPLeases: _luci2.rpc.declare({
996                         object: 'luci2.network',
997                         method: 'dhcp_leases',
998                         expect: { leases: [ ] }
999                 }),
1000
1001                 getDHCPv6Leases: _luci2.rpc.declare({
1002                         object: 'luci2.network',
1003                         method: 'dhcp6_leases',
1004                         expect: { leases: [ ] }
1005                 }),
1006
1007                 getRoutes: _luci2.rpc.declare({
1008                         object: 'luci2.network',
1009                         method: 'routes',
1010                         expect: { routes: [ ] }
1011                 }),
1012
1013                 getIPv6Routes: _luci2.rpc.declare({
1014                         object: 'luci2.network',
1015                         method: 'routes',
1016                         expect: { routes: [ ] }
1017                 }),
1018
1019                 getARPTable: _luci2.rpc.declare({
1020                         object: 'luci2.network',
1021                         method: 'arp_table',
1022                         expect: { entries: [ ] }
1023                 }),
1024
1025                 getInterfaceStatus: _luci2.rpc.declare({
1026                         object: 'network.interface',
1027                         method: 'status',
1028                         params: [ 'interface' ],
1029                         expect: { '': { } },
1030                         filter: function(data, params) {
1031                                 data['interface'] = params['interface'];
1032                                 data['l2_device'] = data['device'];
1033                                 delete data['device'];
1034                                 return data;
1035                         }
1036                 }),
1037
1038                 getDeviceStatus: _luci2.rpc.declare({
1039                         object: 'network.device',
1040                         method: 'status',
1041                         params: [ 'name' ],
1042                         expect: { '': { } },
1043                         filter: function(data, params) {
1044                                 data['device'] = params['name'];
1045                                 return data;
1046                         }
1047                 }),
1048
1049                 getConntrackCount: _luci2.rpc.declare({
1050                         object: 'luci2.network',
1051                         method: 'conntrack_count',
1052                         expect: { '': { count: 0, limit: 0 } }
1053                 }),
1054
1055                 listSwitchNames: _luci2.rpc.declare({
1056                         object: 'luci2.network',
1057                         method: 'switch_list',
1058                         expect: { switches: [ ] }
1059                 }),
1060
1061                 getSwitchInfo: _luci2.rpc.declare({
1062                         object: 'luci2.network',
1063                         method: 'switch_info',
1064                         params: [ 'switch' ],
1065                         expect: { info: { } },
1066                         filter: function(data, params) {
1067                                 data['attrs']      = data['switch'];
1068                                 data['vlan_attrs'] = data['vlan'];
1069                                 data['port_attrs'] = data['port'];
1070                                 data['switch']     = params['switch'];
1071
1072                                 delete data.vlan;
1073                                 delete data.port;
1074
1075                                 return data;
1076                         }
1077                 }),
1078
1079                 getSwitchStatus: _luci2.rpc.declare({
1080                         object: 'luci2.network',
1081                         method: 'switch_status',
1082                         params: [ 'switch' ],
1083                         expect: { ports: [ ] }
1084                 }),
1085
1086
1087                 runPing: _luci2.rpc.declare({
1088                         object: 'luci2.network',
1089                         method: 'ping',
1090                         params: [ 'data' ],
1091                         expect: { '': { code: -1 } }
1092                 }),
1093
1094                 runPing6: _luci2.rpc.declare({
1095                         object: 'luci2.network',
1096                         method: 'ping6',
1097                         params: [ 'data' ],
1098                         expect: { '': { code: -1 } }
1099                 }),
1100
1101                 runTraceroute: _luci2.rpc.declare({
1102                         object: 'luci2.network',
1103                         method: 'traceroute',
1104                         params: [ 'data' ],
1105                         expect: { '': { code: -1 } }
1106                 }),
1107
1108                 runTraceroute6: _luci2.rpc.declare({
1109                         object: 'luci2.network',
1110                         method: 'traceroute6',
1111                         params: [ 'data' ],
1112                         expect: { '': { code: -1 } }
1113                 }),
1114
1115                 runNslookup: _luci2.rpc.declare({
1116                         object: 'luci2.network',
1117                         method: 'nslookup',
1118                         params: [ 'data' ],
1119                         expect: { '': { code: -1 } }
1120                 }),
1121
1122
1123                 setUp: _luci2.rpc.declare({
1124                         object: 'luci2.network',
1125                         method: 'ifup',
1126                         params: [ 'data' ],
1127                         expect: { '': { code: -1 } }
1128                 }),
1129
1130                 setDown: _luci2.rpc.declare({
1131                         object: 'luci2.network',
1132                         method: 'ifdown',
1133                         params: [ 'data' ],
1134                         expect: { '': { code: -1 } }
1135                 })
1136         };
1137
1138         this.wireless = {
1139                 listDeviceNames: _luci2.rpc.declare({
1140                         object: 'iwinfo',
1141                         method: 'devices',
1142                         expect: { 'devices': [ ] },
1143                         filter: function(data) {
1144                                 data.sort();
1145                                 return data;
1146                         }
1147                 }),
1148
1149                 getDeviceStatus: _luci2.rpc.declare({
1150                         object: 'iwinfo',
1151                         method: 'info',
1152                         params: [ 'device' ],
1153                         expect: { '': { } },
1154                         filter: function(data, params) {
1155                                 if (!$.isEmptyObject(data))
1156                                 {
1157                                         data['device'] = params['device'];
1158                                         return data;
1159                                 }
1160                                 return undefined;
1161                         }
1162                 }),
1163
1164                 getAssocList: _luci2.rpc.declare({
1165                         object: 'iwinfo',
1166                         method: 'assoclist',
1167                         params: [ 'device' ],
1168                         expect: { results: [ ] },
1169                         filter: function(data, params) {
1170                                 for (var i = 0; i < data.length; i++)
1171                                         data[i]['device'] = params['device'];
1172
1173                                 data.sort(function(a, b) {
1174                                         if (a.bssid < b.bssid)
1175                                                 return -1;
1176                                         else if (a.bssid > b.bssid)
1177                                                 return 1;
1178                                         else
1179                                                 return 0;
1180                                 });
1181
1182                                 return data;
1183                         }
1184                 }),
1185
1186                 getWirelessStatus: function() {
1187                         return this.listDeviceNames().then(function(names) {
1188                                 _luci2.rpc.batch();
1189
1190                                 for (var i = 0; i < names.length; i++)
1191                                         _luci2.wireless.getDeviceStatus(names[i]);
1192
1193                                 return _luci2.rpc.flush();
1194                         }).then(function(networks) {
1195                                 var rv = { };
1196
1197                                 var phy_attrs = [
1198                                         'country', 'channel', 'frequency', 'frequency_offset',
1199                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1200                                 ];
1201
1202                                 var net_attrs = [
1203                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1204                                         'signal', 'noise', 'bitrate', 'encryption'
1205                                 ];
1206
1207                                 for (var i = 0; i < networks.length; i++)
1208                                 {
1209                                         var phy = rv[networks[i].phy] || (
1210                                                 rv[networks[i].phy] = { networks: [ ] }
1211                                         );
1212
1213                                         var net = {
1214                                                 device: networks[i].device
1215                                         };
1216
1217                                         for (var j = 0; j < phy_attrs.length; j++)
1218                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1219
1220                                         for (var j = 0; j < net_attrs.length; j++)
1221                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1222
1223                                         phy.networks.push(net);
1224                                 }
1225
1226                                 return rv;
1227                         });
1228                 },
1229
1230                 getAssocLists: function()
1231                 {
1232                         return this.listDeviceNames().then(function(names) {
1233                                 _luci2.rpc.batch();
1234
1235                                 for (var i = 0; i < names.length; i++)
1236                                         _luci2.wireless.getAssocList(names[i]);
1237
1238                                 return _luci2.rpc.flush();
1239                         }).then(function(assoclists) {
1240                                 var rv = [ ];
1241
1242                                 for (var i = 0; i < assoclists.length; i++)
1243                                         for (var j = 0; j < assoclists[i].length; j++)
1244                                                 rv.push(assoclists[i][j]);
1245
1246                                 return rv;
1247                         });
1248                 },
1249
1250                 formatEncryption: function(enc)
1251                 {
1252                         var format_list = function(l, s)
1253                         {
1254                                 var rv = [ ];
1255                                 for (var i = 0; i < l.length; i++)
1256                                         rv.push(l[i].toUpperCase());
1257                                 return rv.join(s ? s : ', ');
1258                         }
1259
1260                         if (!enc || !enc.enabled)
1261                                 return _luci2.tr('None');
1262
1263                         if (enc.wep)
1264                         {
1265                                 if (enc.wep.length == 2)
1266                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1267                                 else if (enc.wep[0] == 'shared')
1268                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1269                                 else
1270                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1271                         }
1272                         else if (enc.wpa)
1273                         {
1274                                 if (enc.wpa.length == 2)
1275                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1276                                                 format_list(enc.authentication, '/'),
1277                                                 format_list(enc.ciphers, ', ')
1278                                         );
1279                                 else if (enc.wpa[0] == 2)
1280                                         return 'WPA2 %s (%s)'.format(
1281                                                 format_list(enc.authentication, '/'),
1282                                                 format_list(enc.ciphers, ', ')
1283                                         );
1284                                 else
1285                                         return 'WPA %s (%s)'.format(
1286                                                 format_list(enc.authentication, '/'),
1287                                                 format_list(enc.ciphers, ', ')
1288                                         );
1289                         }
1290
1291                         return _luci2.tr('Unknown');
1292                 }
1293         };
1294
1295         this.firewall = {
1296                 getZoneColor: function(zone)
1297                 {
1298                         if ($.isPlainObject(zone))
1299                                 zone = zone.name;
1300
1301                         if (zone == 'lan')
1302                                 return '#90f090';
1303                         else if (zone == 'wan')
1304                                 return '#f09090';
1305
1306                         for (var i = 0, hash = 0;
1307                                  i < zone.length;
1308                                  hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1309
1310                         for (var i = 0, color = '#';
1311                                  i < 3;
1312                                  color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1313
1314                         return color;
1315                 },
1316
1317                 findZoneByNetwork: function(network)
1318                 {
1319                         var self = this;
1320                         var zone = undefined;
1321
1322                         return _luci2.uci.foreach('firewall', 'zone', function(z) {
1323                                 if (!z.name || !z.network)
1324                                         return;
1325
1326                                 if (!$.isArray(z.network))
1327                                         z.network = z.network.split(/\s+/);
1328
1329                                 for (var i = 0; i < z.network.length; i++)
1330                                 {
1331                                         if (z.network[i] == network)
1332                                         {
1333                                                 zone = z;
1334                                                 break;
1335                                         }
1336                                 }
1337                         }).then(function() {
1338                                 if (zone)
1339                                         zone.color = self.getZoneColor(zone);
1340
1341                                 return zone;
1342                         });
1343                 }
1344         };
1345
1346         this.system = {
1347                 getSystemInfo: _luci2.rpc.declare({
1348                         object: 'system',
1349                         method: 'info',
1350                         expect: { '': { } }
1351                 }),
1352
1353                 getBoardInfo: _luci2.rpc.declare({
1354                         object: 'system',
1355                         method: 'board',
1356                         expect: { '': { } }
1357                 }),
1358
1359                 getDiskInfo: _luci2.rpc.declare({
1360                         object: 'luci2.system',
1361                         method: 'diskfree',
1362                         expect: { '': { } }
1363                 }),
1364
1365                 getInfo: function(cb)
1366                 {
1367                         _luci2.rpc.batch();
1368
1369                         this.getSystemInfo();
1370                         this.getBoardInfo();
1371                         this.getDiskInfo();
1372
1373                         return _luci2.rpc.flush().then(function(info) {
1374                                 var rv = { };
1375
1376                                 $.extend(rv, info[0]);
1377                                 $.extend(rv, info[1]);
1378                                 $.extend(rv, info[2]);
1379
1380                                 return rv;
1381                         });
1382                 },
1383
1384                 getProcessList: _luci2.rpc.declare({
1385                         object: 'luci2.system',
1386                         method: 'process_list',
1387                         expect: { processes: [ ] },
1388                         filter: function(data) {
1389                                 data.sort(function(a, b) { return a.pid - b.pid });
1390                                 return data;
1391                         }
1392                 }),
1393
1394                 getSystemLog: _luci2.rpc.declare({
1395                         object: 'luci2.system',
1396                         method: 'syslog',
1397                         expect: { log: '' }
1398                 }),
1399
1400                 getKernelLog: _luci2.rpc.declare({
1401                         object: 'luci2.system',
1402                         method: 'dmesg',
1403                         expect: { log: '' }
1404                 }),
1405
1406                 getZoneInfo: function(cb)
1407                 {
1408                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1409                 },
1410
1411                 sendSignal: _luci2.rpc.declare({
1412                         object: 'luci2.system',
1413                         method: 'process_signal',
1414                         params: [ 'pid', 'signal' ],
1415                         filter: function(data) {
1416                                 return (data == 0);
1417                         }
1418                 }),
1419
1420                 initList: _luci2.rpc.declare({
1421                         object: 'luci2.system',
1422                         method: 'init_list',
1423                         expect: { initscripts: [ ] },
1424                         filter: function(data) {
1425                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1426                                 return data;
1427                         }
1428                 }),
1429
1430                 initEnabled: function(init, cb)
1431                 {
1432                         return this.initList().then(function(list) {
1433                                 for (var i = 0; i < list.length; i++)
1434                                         if (list[i].name == init)
1435                                                 return !!list[i].enabled;
1436
1437                                 return false;
1438                         });
1439                 },
1440
1441                 initRun: _luci2.rpc.declare({
1442                         object: 'luci2.system',
1443                         method: 'init_action',
1444                         params: [ 'name', 'action' ],
1445                         filter: function(data) {
1446                                 return (data == 0);
1447                         }
1448                 }),
1449
1450                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1451                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1452                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1453                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1454                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1455                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1456
1457
1458                 getRcLocal: _luci2.rpc.declare({
1459                         object: 'luci2.system',
1460                         method: 'rclocal_get',
1461                         expect: { data: '' }
1462                 }),
1463
1464                 setRcLocal: _luci2.rpc.declare({
1465                         object: 'luci2.system',
1466                         method: 'rclocal_set',
1467                         params: [ 'data' ]
1468                 }),
1469
1470
1471                 getCrontab: _luci2.rpc.declare({
1472                         object: 'luci2.system',
1473                         method: 'crontab_get',
1474                         expect: { data: '' }
1475                 }),
1476
1477                 setCrontab: _luci2.rpc.declare({
1478                         object: 'luci2.system',
1479                         method: 'crontab_set',
1480                         params: [ 'data' ]
1481                 }),
1482
1483
1484                 getSSHKeys: _luci2.rpc.declare({
1485                         object: 'luci2.system',
1486                         method: 'sshkeys_get',
1487                         expect: { keys: [ ] }
1488                 }),
1489
1490                 setSSHKeys: _luci2.rpc.declare({
1491                         object: 'luci2.system',
1492                         method: 'sshkeys_set',
1493                         params: [ 'keys' ]
1494                 }),
1495
1496
1497                 setPassword: _luci2.rpc.declare({
1498                         object: 'luci2.system',
1499                         method: 'password_set',
1500                         params: [ 'user', 'password' ]
1501                 }),
1502
1503
1504                 listLEDs: _luci2.rpc.declare({
1505                         object: 'luci2.system',
1506                         method: 'led_list',
1507                         expect: { leds: [ ] }
1508                 }),
1509
1510                 listUSBDevices: _luci2.rpc.declare({
1511                         object: 'luci2.system',
1512                         method: 'usb_list',
1513                         expect: { devices: [ ] }
1514                 }),
1515
1516
1517                 testUpgrade: _luci2.rpc.declare({
1518                         object: 'luci2.system',
1519                         method: 'upgrade_test',
1520                         expect: { '': { } }
1521                 }),
1522
1523                 startUpgrade: _luci2.rpc.declare({
1524                         object: 'luci2.system',
1525                         method: 'upgrade_start',
1526                         params: [ 'keep' ]
1527                 }),
1528
1529                 cleanUpgrade: _luci2.rpc.declare({
1530                         object: 'luci2.system',
1531                         method: 'upgrade_clean'
1532                 }),
1533
1534
1535                 restoreBackup: _luci2.rpc.declare({
1536                         object: 'luci2.system',
1537                         method: 'backup_restore'
1538                 }),
1539
1540                 cleanBackup: _luci2.rpc.declare({
1541                         object: 'luci2.system',
1542                         method: 'backup_clean'
1543                 }),
1544
1545
1546                 getBackupConfig: _luci2.rpc.declare({
1547                         object: 'luci2.system',
1548                         method: 'backup_config_get',
1549                         expect: { config: '' }
1550                 }),
1551
1552                 setBackupConfig: _luci2.rpc.declare({
1553                         object: 'luci2.system',
1554                         method: 'backup_config_set',
1555                         params: [ 'data' ]
1556                 }),
1557
1558
1559                 listBackup: _luci2.rpc.declare({
1560                         object: 'luci2.system',
1561                         method: 'backup_list',
1562                         expect: { files: [ ] }
1563                 }),
1564
1565
1566                 testReset: _luci2.rpc.declare({
1567                         object: 'luci2.system',
1568                         method: 'reset_test',
1569                         expect: { supported: false }
1570                 }),
1571
1572                 startReset: _luci2.rpc.declare({
1573                         object: 'luci2.system',
1574                         method: 'reset_start'
1575                 }),
1576
1577
1578                 performReboot: _luci2.rpc.declare({
1579                         object: 'luci2.system',
1580                         method: 'reboot'
1581                 })
1582         };
1583
1584         this.opkg = {
1585                 updateLists: _luci2.rpc.declare({
1586                         object: 'luci2.opkg',
1587                         method: 'update',
1588                         expect: { '': { } }
1589                 }),
1590
1591                 _allPackages: _luci2.rpc.declare({
1592                         object: 'luci2.opkg',
1593                         method: 'list',
1594                         params: [ 'offset', 'limit', 'pattern' ],
1595                         expect: { '': { } }
1596                 }),
1597
1598                 _installedPackages: _luci2.rpc.declare({
1599                         object: 'luci2.opkg',
1600                         method: 'list_installed',
1601                         params: [ 'offset', 'limit', 'pattern' ],
1602                         expect: { '': { } }
1603                 }),
1604
1605                 _findPackages: _luci2.rpc.declare({
1606                         object: 'luci2.opkg',
1607                         method: 'find',
1608                         params: [ 'offset', 'limit', 'pattern' ],
1609                         expect: { '': { } }
1610                 }),
1611
1612                 _fetchPackages: function(action, offset, limit, pattern)
1613                 {
1614                         var packages = [ ];
1615
1616                         return action(offset, limit, pattern).then(function(list) {
1617                                 if (!list.total || !list.packages)
1618                                         return { length: 0, total: 0 };
1619
1620                                 packages.push.apply(packages, list.packages);
1621                                 packages.total = list.total;
1622
1623                                 if (limit <= 0)
1624                                         limit = list.total;
1625
1626                                 if (packages.length >= limit)
1627                                         return packages;
1628
1629                                 _luci2.rpc.batch();
1630
1631                                 for (var i = offset + packages.length; i < limit; i += 100)
1632                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1633
1634                                 return _luci2.rpc.flush();
1635                         }).then(function(lists) {
1636                                 for (var i = 0; i < lists.length; i++)
1637                                 {
1638                                         if (!lists[i].total || !lists[i].packages)
1639                                                 continue;
1640
1641                                         packages.push.apply(packages, lists[i].packages);
1642                                         packages.total = lists[i].total;
1643                                 }
1644
1645                                 return packages;
1646                         });
1647                 },
1648
1649                 listPackages: function(offset, limit, pattern)
1650                 {
1651                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1652                 },
1653
1654                 installedPackages: function(offset, limit, pattern)
1655                 {
1656                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1657                 },
1658
1659                 findPackages: function(offset, limit, pattern)
1660                 {
1661                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1662                 },
1663
1664                 installPackage: _luci2.rpc.declare({
1665                         object: 'luci2.opkg',
1666                         method: 'install',
1667                         params: [ 'package' ],
1668                         expect: { '': { } }
1669                 }),
1670
1671                 removePackage: _luci2.rpc.declare({
1672                         object: 'luci2.opkg',
1673                         method: 'remove',
1674                         params: [ 'package' ],
1675                         expect: { '': { } }
1676                 }),
1677
1678                 getConfig: _luci2.rpc.declare({
1679                         object: 'luci2.opkg',
1680                         method: 'config_get',
1681                         expect: { config: '' }
1682                 }),
1683
1684                 setConfig: _luci2.rpc.declare({
1685                         object: 'luci2.opkg',
1686                         method: 'config_set',
1687                         params: [ 'data' ]
1688                 })
1689         };
1690
1691         this.session = {
1692
1693                 login: _luci2.rpc.declare({
1694                         object: 'session',
1695                         method: 'login',
1696                         params: [ 'username', 'password' ],
1697                         expect: { '': { } }
1698                 }),
1699
1700                 access: _luci2.rpc.declare({
1701                         object: 'session',
1702                         method: 'access',
1703                         params: [ 'scope', 'object', 'function' ],
1704                         expect: { access: false }
1705                 }),
1706
1707                 isAlive: function()
1708                 {
1709                         return _luci2.session.access('ubus', 'session', 'access');
1710                 },
1711
1712                 startHeartbeat: function()
1713                 {
1714                         this._hearbeatInterval = window.setInterval(function() {
1715                                 _luci2.session.isAlive().then(function(alive) {
1716                                         if (!alive)
1717                                         {
1718                                                 _luci2.session.stopHeartbeat();
1719                                                 _luci2.ui.login(true);
1720                                         }
1721
1722                                 });
1723                         }, _luci2.globals.timeout * 2);
1724                 },
1725
1726                 stopHeartbeat: function()
1727                 {
1728                         if (typeof(this._hearbeatInterval) != 'undefined')
1729                         {
1730                                 window.clearInterval(this._hearbeatInterval);
1731                                 delete this._hearbeatInterval;
1732                         }
1733                 }
1734         };
1735
1736         this.ui = {
1737
1738                 saveScrollTop: function()
1739                 {
1740                         this._scroll_top = $(document).scrollTop();
1741                 },
1742
1743                 restoreScrollTop: function()
1744                 {
1745                         if (typeof(this._scroll_top) == 'undefined')
1746                                 return;
1747
1748                         $(document).scrollTop(this._scroll_top);
1749
1750                         delete this._scroll_top;
1751                 },
1752
1753                 loading: function(enable)
1754                 {
1755                         var win = $(window);
1756                         var body = $('body');
1757
1758                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
1759                                 modal: $('<div />')
1760                                         .addClass('modal fade')
1761                                         .append($('<div />')
1762                                                 .addClass('modal-dialog')
1763                                                 .append($('<div />')
1764                                                         .addClass('modal-content luci2-modal-loader')
1765                                                         .append($('<div />')
1766                                                                 .addClass('modal-body')
1767                                                                 .text(_luci2.tr('Loading data…')))))
1768                                         .appendTo(body)
1769                                         .modal({
1770                                                 backdrop: 'static',
1771                                                 keyboard: false
1772                                         })
1773                         });
1774
1775                         state.modal.modal(enable ? 'show' : 'hide');
1776                 },
1777
1778                 dialog: function(title, content, options)
1779                 {
1780                         var win = $(window);
1781                         var body = $('body');
1782
1783                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1784                                 dialog: $('<div />')
1785                                         .addClass('modal fade')
1786                                         .append($('<div />')
1787                                                 .addClass('modal-dialog')
1788                                                 .append($('<div />')
1789                                                         .addClass('modal-content')
1790                                                         .append($('<div />')
1791                                                                 .addClass('modal-header')
1792                                                                 .append('<h4 />')
1793                                                                         .addClass('modal-title'))
1794                                                         .append($('<div />')
1795                                                                 .addClass('modal-body'))
1796                                                         .append($('<div />')
1797                                                                 .addClass('modal-footer')
1798                                                                 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1799                                                                         .click(function() {
1800                                                                                 $(this).parents('div.modal').modal('hide');
1801                                                                         })))))
1802                                         .appendTo(body)
1803                         });
1804
1805                         if (typeof(options) != 'object')
1806                                 options = { };
1807
1808                         if (title === false)
1809                         {
1810                                 state.dialog.modal('hide');
1811
1812                                 return;
1813                         }
1814
1815                         var cnt = state.dialog.children().children().children('div.modal-body');
1816                         var ftr = state.dialog.children().children().children('div.modal-footer');
1817
1818                         ftr.empty();
1819
1820                         if (options.style == 'confirm')
1821                         {
1822                                 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1823                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1824
1825                                 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1826                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1827                         }
1828                         else if (options.style == 'close')
1829                         {
1830                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1831                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1832                         }
1833                         else if (options.style == 'wait')
1834                         {
1835                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1836                                         .attr('disabled', true));
1837                         }
1838
1839                         state.dialog.find('h4:first').text(title);
1840                         state.dialog.modal('show');
1841
1842                         cnt.empty().append(content);
1843                 },
1844
1845                 upload: function(title, content, options)
1846                 {
1847                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
1848                                 form: $('<form />')
1849                                         .attr('method', 'post')
1850                                         .attr('action', '/cgi-bin/luci-upload')
1851                                         .attr('enctype', 'multipart/form-data')
1852                                         .attr('target', 'cbi-fileupload-frame')
1853                                         .append($('<p />'))
1854                                         .append($('<input />')
1855                                                 .attr('type', 'hidden')
1856                                                 .attr('name', 'sessionid'))
1857                                         .append($('<input />')
1858                                                 .attr('type', 'hidden')
1859                                                 .attr('name', 'filename'))
1860                                         .append($('<input />')
1861                                                 .attr('type', 'file')
1862                                                 .attr('name', 'filedata')
1863                                                 .addClass('cbi-input-file'))
1864                                         .append($('<div />')
1865                                                 .css('width', '100%')
1866                                                 .addClass('progress progress-striped active')
1867                                                 .append($('<div />')
1868                                                         .addClass('progress-bar')
1869                                                         .css('width', '100%')))
1870                                         .append($('<iframe />')
1871                                                 .addClass('pull-right')
1872                                                 .attr('name', 'cbi-fileupload-frame')
1873                                                 .css('width', '1px')
1874                                                 .css('height', '1px')
1875                                                 .css('visibility', 'hidden')),
1876
1877                                 finish_cb: function(ev) {
1878                                         $(this).off('load');
1879
1880                                         var body = (this.contentDocument || this.contentWindow.document).body;
1881                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1882                                                 body = body.firstChild;
1883
1884                                         var json;
1885                                         try {
1886                                                 json = $.parseJSON(body.innerHTML);
1887                                         } catch(e) {
1888                                                 json = {
1889                                                         message: _luci2.tr('Invalid server response received'),
1890                                                         error: [ -1, _luci2.tr('Invalid data') ]
1891                                                 };
1892                                         };
1893
1894                                         if (json.error)
1895                                         {
1896                                                 L.ui.dialog(L.tr('File upload'), [
1897                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1898                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1899                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1900                                                 ], { style: 'close' });
1901                                         }
1902                                         else if (typeof(state.success_cb) == 'function')
1903                                         {
1904                                                 state.success_cb(json);
1905                                         }
1906                                 },
1907
1908                                 confirm_cb: function() {
1909                                         var f = state.form.find('.cbi-input-file');
1910                                         var b = state.form.find('.progress');
1911                                         var p = state.form.find('p');
1912
1913                                         if (!f.val())
1914                                                 return;
1915
1916                                         state.form.find('iframe').on('load', state.finish_cb);
1917                                         state.form.submit();
1918
1919                                         f.hide();
1920                                         b.show();
1921                                         p.text(_luci2.tr('File upload in progress …'));
1922
1923                                         state.form.parent().parent().find('button').prop('disabled', true);
1924                                 }
1925                         });
1926
1927                         state.form.find('.progress').hide();
1928                         state.form.find('.cbi-input-file').val('').show();
1929                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1930
1931                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1932                         state.form.find('[name=filename]').val(options.filename);
1933
1934                         state.success_cb = options.success;
1935
1936                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1937                                 style: 'confirm',
1938                                 confirm: state.confirm_cb
1939                         });
1940                 },
1941
1942                 reconnect: function()
1943                 {
1944                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1945                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1946                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1947                         var images    = $();
1948                         var interval, timeout;
1949
1950                         _luci2.ui.dialog(
1951                                 _luci2.tr('Waiting for device'), [
1952                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1953                                         $('<div />')
1954                                                 .css('width', '100%')
1955                                                 .addClass('progressbar')
1956                                                 .addClass('intermediate')
1957                                                 .append($('<div />')
1958                                                         .css('width', '100%'))
1959                                 ], { style: 'wait' }
1960                         );
1961
1962                         for (var i = 0; i < protocols.length; i++)
1963                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1964
1965                         //_luci2.network.getNetworkStatus(function(s) {
1966                         //      for (var i = 0; i < protocols.length; i++)
1967                         //      {
1968                         //              for (var j = 0; j < s.length; j++)
1969                         //              {
1970                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1971                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1972                         //
1973                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1974                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1975                         //              }
1976                         //      }
1977                         //}).then(function() {
1978                                 images.on('load', function() {
1979                                         var url = this.getAttribute('url');
1980                                         _luci2.session.isAlive().then(function(access) {
1981                                                 if (access)
1982                                                 {
1983                                                         window.clearTimeout(timeout);
1984                                                         window.clearInterval(interval);
1985                                                         _luci2.ui.dialog(false);
1986                                                         images = null;
1987                                                 }
1988                                                 else
1989                                                 {
1990                                                         location.href = url;
1991                                                 }
1992                                         });
1993                                 });
1994
1995                                 interval = window.setInterval(function() {
1996                                         images.each(function() {
1997                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1998                                         });
1999                                 }, 5000);
2000
2001                                 timeout = window.setTimeout(function() {
2002                                         window.clearInterval(interval);
2003                                         images.off('load');
2004
2005                                         _luci2.ui.dialog(
2006                                                 _luci2.tr('Device not responding'),
2007                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2008                                                 { style: 'close' }
2009                                         );
2010                                 }, 180000);
2011                         //});
2012                 },
2013
2014                 login: function(invalid)
2015                 {
2016                         var state = _luci2.ui._login || (_luci2.ui._login = {
2017                                 form: $('<form />')
2018                                         .attr('target', '')
2019                                         .attr('method', 'post')
2020                                         .append($('<p />')
2021                                                 .addClass('alert-message')
2022                                                 .text(_luci2.tr('Wrong username or password given!')))
2023                                         .append($('<p />')
2024                                                 .append($('<label />')
2025                                                         .text(_luci2.tr('Username'))
2026                                                         .append($('<br />'))
2027                                                         .append($('<input />')
2028                                                                 .attr('type', 'text')
2029                                                                 .attr('name', 'username')
2030                                                                 .attr('value', 'root')
2031                                                                 .addClass('form-control')
2032                                                                 .keypress(function(ev) {
2033                                                                         if (ev.which == 10 || ev.which == 13)
2034                                                                                 state.confirm_cb();
2035                                                                 }))))
2036                                         .append($('<p />')
2037                                                 .append($('<label />')
2038                                                         .text(_luci2.tr('Password'))
2039                                                         .append($('<br />'))
2040                                                         .append($('<input />')
2041                                                                 .attr('type', 'password')
2042                                                                 .attr('name', 'password')
2043                                                                 .addClass('form-control')
2044                                                                 .keypress(function(ev) {
2045                                                                         if (ev.which == 10 || ev.which == 13)
2046                                                                                 state.confirm_cb();
2047                                                                 }))))
2048                                         .append($('<p />')
2049                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2050
2051                                 response_cb: function(response) {
2052                                         if (!response.ubus_rpc_session)
2053                                         {
2054                                                 _luci2.ui.login(true);
2055                                         }
2056                                         else
2057                                         {
2058                                                 _luci2.globals.sid = response.ubus_rpc_session;
2059                                                 _luci2.setHash('id', _luci2.globals.sid);
2060                                                 _luci2.session.startHeartbeat();
2061                                                 _luci2.ui.dialog(false);
2062                                                 state.deferred.resolve();
2063                                         }
2064                                 },
2065
2066                                 confirm_cb: function() {
2067                                         var u = state.form.find('[name=username]').val();
2068                                         var p = state.form.find('[name=password]').val();
2069
2070                                         if (!u)
2071                                                 return;
2072
2073                                         _luci2.ui.dialog(
2074                                                 _luci2.tr('Logging in'), [
2075                                                         $('<p />').text(_luci2.tr('Log in in progress …')),
2076                                                         $('<div />')
2077                                                                 .css('width', '100%')
2078                                                                 .addClass('progressbar')
2079                                                                 .addClass('intermediate')
2080                                                                 .append($('<div />')
2081                                                                         .css('width', '100%'))
2082                                                 ], { style: 'wait' }
2083                                         );
2084
2085                                         _luci2.globals.sid = '00000000000000000000000000000000';
2086                                         _luci2.session.login(u, p).then(state.response_cb);
2087                                 }
2088                         });
2089
2090                         if (!state.deferred || state.deferred.state() != 'pending')
2091                                 state.deferred = $.Deferred();
2092
2093                         /* try to find sid from hash */
2094                         var sid = _luci2.getHash('id');
2095                         if (sid && sid.match(/^[a-f0-9]{32}$/))
2096                         {
2097                                 _luci2.globals.sid = sid;
2098                                 _luci2.session.isAlive().then(function(access) {
2099                                         if (access)
2100                                         {
2101                                                 _luci2.session.startHeartbeat();
2102                                                 state.deferred.resolve();
2103                                         }
2104                                         else
2105                                         {
2106                                                 _luci2.setHash('id', undefined);
2107                                                 _luci2.ui.login();
2108                                         }
2109                                 });
2110
2111                                 return state.deferred;
2112                         }
2113
2114                         if (invalid)
2115                                 state.form.find('.alert-message').show();
2116                         else
2117                                 state.form.find('.alert-message').hide();
2118
2119                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2120                                 style: 'confirm',
2121                                 confirm: state.confirm_cb
2122                         });
2123
2124                         state.form.find('[name=password]').focus();
2125
2126                         return state.deferred;
2127                 },
2128
2129                 cryptPassword: _luci2.rpc.declare({
2130                         object: 'luci2.ui',
2131                         method: 'crypt',
2132                         params: [ 'data' ],
2133                         expect: { crypt: '' }
2134                 }),
2135
2136
2137                 _acl_merge_scope: function(acl_scope, scope)
2138                 {
2139                         if ($.isArray(scope))
2140                         {
2141                                 for (var i = 0; i < scope.length; i++)
2142                                         acl_scope[scope[i]] = true;
2143                         }
2144                         else if ($.isPlainObject(scope))
2145                         {
2146                                 for (var object_name in scope)
2147                                 {
2148                                         if (!$.isArray(scope[object_name]))
2149                                                 continue;
2150
2151                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2152
2153                                         for (var i = 0; i < scope[object_name].length; i++)
2154                                                 acl_object[scope[object_name][i]] = true;
2155                                 }
2156                         }
2157                 },
2158
2159                 _acl_merge_permission: function(acl_perm, perm)
2160                 {
2161                         if ($.isPlainObject(perm))
2162                         {
2163                                 for (var scope_name in perm)
2164                                 {
2165                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2166                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
2167                                 }
2168                         }
2169                 },
2170
2171                 _acl_merge_group: function(acl_group, group)
2172                 {
2173                         if ($.isPlainObject(group))
2174                         {
2175                                 if (!acl_group.description)
2176                                         acl_group.description = group.description;
2177
2178                                 if (group.read)
2179                                 {
2180                                         var acl_perm = acl_group.read || (acl_group.read = { });
2181                                         this._acl_merge_permission(acl_perm, group.read);
2182                                 }
2183
2184                                 if (group.write)
2185                                 {
2186                                         var acl_perm = acl_group.write || (acl_group.write = { });
2187                                         this._acl_merge_permission(acl_perm, group.write);
2188                                 }
2189                         }
2190                 },
2191
2192                 _acl_merge_tree: function(acl_tree, tree)
2193                 {
2194                         if ($.isPlainObject(tree))
2195                         {
2196                                 for (var group_name in tree)
2197                                 {
2198                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2199                                         this._acl_merge_group(acl_group, tree[group_name]);
2200                                 }
2201                         }
2202                 },
2203
2204                 listAvailableACLs: _luci2.rpc.declare({
2205                         object: 'luci2.ui',
2206                         method: 'acls',
2207                         expect: { acls: [ ] },
2208                         filter: function(trees) {
2209                                 var acl_tree = { };
2210                                 for (var i = 0; i < trees.length; i++)
2211                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2212                                 return acl_tree;
2213                         }
2214                 }),
2215
2216                 renderMainMenu: _luci2.rpc.declare({
2217                         object: 'luci2.ui',
2218                         method: 'menu',
2219                         expect: { menu: { } },
2220                         filter: function(entries) {
2221                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
2222                                 _luci2.globals.mainMenu.entries(entries);
2223
2224                                 $('#mainmenu')
2225                                         .empty()
2226                                         .append(_luci2.globals.mainMenu.render(0, 1));
2227                         }
2228                 }),
2229
2230                 renderViewMenu: function()
2231                 {
2232                         $('#viewmenu')
2233                                 .empty()
2234                                 .append(_luci2.globals.mainMenu.render(2, 900));
2235                 },
2236
2237                 renderView: function()
2238                 {
2239                         var node = arguments[0];
2240                         var name = node.view.split(/\//).join('.');
2241                         var args = [ ];
2242
2243                         for (var i = 1; i < arguments.length; i++)
2244                                 args.push(arguments[i]);
2245
2246                         if (_luci2.globals.currentView)
2247                                 _luci2.globals.currentView.finish();
2248
2249                         _luci2.ui.renderViewMenu();
2250
2251                         if (!_luci2._views)
2252                                 _luci2._views = { };
2253
2254                         _luci2.setHash('view', node.view);
2255
2256                         if (_luci2._views[name] instanceof _luci2.ui.view)
2257                         {
2258                                 _luci2.globals.currentView = _luci2._views[name];
2259                                 return _luci2._views[name].render.apply(_luci2._views[name], args);
2260                         }
2261
2262                         var url = _luci2.globals.resource + '/view/' + name + '.js';
2263
2264                         return $.ajax(url, {
2265                                 method: 'GET',
2266                                 cache: true,
2267                                 dataType: 'text'
2268                         }).then(function(data) {
2269                                 try {
2270                                         var viewConstructorSource = (
2271                                                 '(function(L, $) { ' +
2272                                                         'return %s' +
2273                                                 '})(_luci2, $);\n\n' +
2274                                                 '//@ sourceURL=%s'
2275                                         ).format(data, url);
2276
2277                                         var viewConstructor = eval(viewConstructorSource);
2278
2279                                         _luci2._views[name] = new viewConstructor({
2280                                                 name: name,
2281                                                 acls: node.write || { }
2282                                         });
2283
2284                                         _luci2.globals.currentView = _luci2._views[name];
2285                                         return _luci2._views[name].render.apply(_luci2._views[name], args);
2286                                 }
2287                                 catch(e) {
2288                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
2289                                 };
2290
2291                                 return $.Deferred().resolve();
2292                         });
2293                 },
2294
2295                 updateHostname: function()
2296                 {
2297                         return _luci2.system.getBoardInfo().then(function(info) {
2298                                 if (info.hostname)
2299                                         $('#hostname').text(info.hostname);
2300                         });
2301                 },
2302
2303                 updateChanges: function()
2304                 {
2305                         return _luci2.uci.changes().then(function(changes) {
2306                                 var n = 0;
2307                                 var html = '';
2308
2309                                 for (var config in changes)
2310                                 {
2311                                         var log = [ ];
2312
2313                                         for (var i = 0; i < changes[config].length; i++)
2314                                         {
2315                                                 var c = changes[config][i];
2316
2317                                                 switch (c[0])
2318                                                 {
2319                                                 case 'order':
2320                                                         break;
2321
2322                                                 case 'remove':
2323                                                         if (c.length < 3)
2324                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2325                                                         else
2326                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2327                                                         break;
2328
2329                                                 case 'rename':
2330                                                         if (c.length < 4)
2331                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2332                                                         else
2333                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2334                                                         break;
2335
2336                                                 case 'add':
2337                                                         log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2338                                                         break;
2339
2340                                                 case 'list-add':
2341                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2342                                                         break;
2343
2344                                                 case 'list-del':
2345                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2346                                                         break;
2347
2348                                                 case 'set':
2349                                                         if (c.length < 4)
2350                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2351                                                         else
2352                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2353                                                         break;
2354                                                 }
2355                                         }
2356
2357                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2358                                         n += changes[config].length;
2359                                 }
2360
2361                                 if (n > 0)
2362                                         $('#changes')
2363                                                 .empty()
2364                                                 .show()
2365                                                 .append($('<a />')
2366                                                         .attr('href', '#')
2367                                                         .addClass('label')
2368                                                         .addClass('notice')
2369                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2370                                                         .click(function(ev) {
2371                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2372                                                                 ev.preventDefault();
2373                                                         }));
2374                                 else
2375                                         $('#changes')
2376                                                 .hide();
2377                         });
2378                 },
2379
2380                 init: function()
2381                 {
2382                         _luci2.ui.loading(true);
2383
2384                         $.when(
2385                                 _luci2.ui.updateHostname(),
2386                                 _luci2.ui.updateChanges(),
2387                                 _luci2.ui.renderMainMenu()
2388                         ).then(function() {
2389                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2390                                         _luci2.ui.loading(false);
2391                                 })
2392                         });
2393                 },
2394
2395                 button: function(label, style, title)
2396                 {
2397                         style = style || 'default';
2398
2399                         return $('<button />')
2400                                 .attr('type', 'button')
2401                                 .attr('title', title ? title : '')
2402                                 .addClass('btn btn-' + style)
2403                                 .text(label);
2404                 }
2405         };
2406
2407         this.ui.AbstractWidget = Class.extend({
2408                 i18n: function(text) {
2409                         return text;
2410                 },
2411
2412                 label: function() {
2413                         var key = arguments[0];
2414                         var args = [ ];
2415
2416                         for (var i = 1; i < arguments.length; i++)
2417                                 args.push(arguments[i]);
2418
2419                         switch (typeof(this.options[key]))
2420                         {
2421                         case 'undefined':
2422                                 return '';
2423
2424                         case 'function':
2425                                 return this.options[key].apply(this, args);
2426
2427                         default:
2428                                 return ''.format.apply('' + this.options[key], args);
2429                         }
2430                 },
2431
2432                 toString: function() {
2433                         return $('<div />').append(this.render()).html();
2434                 },
2435
2436                 insertInto: function(id) {
2437                         return $(id).empty().append(this.render());
2438                 },
2439
2440                 appendTo: function(id) {
2441                         return $(id).append(this.render());
2442                 }
2443         });
2444
2445         this.ui.view = this.ui.AbstractWidget.extend({
2446                 _fetch_template: function()
2447                 {
2448                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2449                                 method: 'GET',
2450                                 cache: true,
2451                                 dataType: 'text',
2452                                 success: function(data) {
2453                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2454                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2455                                                 switch (p1)
2456                                                 {
2457                                                 case '#':
2458                                                         return '';
2459
2460                                                 case ':':
2461                                                         return _luci2.tr(p2);
2462
2463                                                 case '=':
2464                                                         return _luci2.globals[p2] || '';
2465
2466                                                 default:
2467                                                         return '(?' + match + ')';
2468                                                 }
2469                                         });
2470
2471                                         $('#maincontent').append(data);
2472                                 }
2473                         });
2474                 },
2475
2476                 execute: function()
2477                 {
2478                         throw "Not implemented";
2479                 },
2480
2481                 render: function()
2482                 {
2483                         var container = $('#maincontent');
2484
2485                         container.empty();
2486
2487                         if (this.title)
2488                                 container.append($('<h2 />').append(this.title));
2489
2490                         if (this.description)
2491                                 container.append($('<p />').append(this.description));
2492
2493                         var self = this;
2494                         var args = [ ];
2495
2496                         for (var i = 0; i < arguments.length; i++)
2497                                 args.push(arguments[i]);
2498
2499                         return this._fetch_template().then(function() {
2500                                 return _luci2.deferrable(self.execute.apply(self, args));
2501                         });
2502                 },
2503
2504                 repeat: function(func, interval)
2505                 {
2506                         var self = this;
2507
2508                         if (!self._timeouts)
2509                                 self._timeouts = [ ];
2510
2511                         var index = self._timeouts.length;
2512
2513                         if (typeof(interval) != 'number')
2514                                 interval = 5000;
2515
2516                         var setTimer, runTimer;
2517
2518                         setTimer = function() {
2519                                 if (self._timeouts)
2520                                         self._timeouts[index] = window.setTimeout(runTimer, interval);
2521                         };
2522
2523                         runTimer = function() {
2524                                 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2525                         };
2526
2527                         runTimer();
2528                 },
2529
2530                 finish: function()
2531                 {
2532                         if ($.isArray(this._timeouts))
2533                         {
2534                                 for (var i = 0; i < this._timeouts.length; i++)
2535                                         window.clearTimeout(this._timeouts[i]);
2536
2537                                 delete this._timeouts;
2538                         }
2539                 }
2540         });
2541
2542         this.ui.menu = this.ui.AbstractWidget.extend({
2543                 init: function() {
2544                         this._nodes = { };
2545                 },
2546
2547                 entries: function(entries)
2548                 {
2549                         for (var entry in entries)
2550                         {
2551                                 var path = entry.split(/\//);
2552                                 var node = this._nodes;
2553
2554                                 for (i = 0; i < path.length; i++)
2555                                 {
2556                                         if (!node.childs)
2557                                                 node.childs = { };
2558
2559                                         if (!node.childs[path[i]])
2560                                                 node.childs[path[i]] = { };
2561
2562                                         node = node.childs[path[i]];
2563                                 }
2564
2565                                 $.extend(node, entries[entry]);
2566                         }
2567                 },
2568
2569                 _indexcmp: function(a, b)
2570                 {
2571                         var x = a.index || 0;
2572                         var y = b.index || 0;
2573                         return (x - y);
2574                 },
2575
2576                 firstChildView: function(node)
2577                 {
2578                         if (node.view)
2579                                 return node;
2580
2581                         var nodes = [ ];
2582                         for (var child in (node.childs || { }))
2583                                 nodes.push(node.childs[child]);
2584
2585                         nodes.sort(this._indexcmp);
2586
2587                         for (var i = 0; i < nodes.length; i++)
2588                         {
2589                                 var child = this.firstChildView(nodes[i]);
2590                                 if (child)
2591                                 {
2592                                         for (var key in child)
2593                                                 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2594                                                         node[key] = child[key];
2595
2596                                         return node;
2597                                 }
2598                         }
2599
2600                         return undefined;
2601                 },
2602
2603                 _onclick: function(ev)
2604                 {
2605                         _luci2.ui.loading(true);
2606                         _luci2.ui.renderView(ev.data).then(function() {
2607                                 _luci2.ui.loading(false);
2608                         });
2609
2610                         ev.preventDefault();
2611                         this.blur();
2612                 },
2613
2614                 _render: function(childs, level, min, max)
2615                 {
2616                         var nodes = [ ];
2617                         for (var node in childs)
2618                         {
2619                                 var child = this.firstChildView(childs[node]);
2620                                 if (child)
2621                                         nodes.push(childs[node]);
2622                         }
2623
2624                         nodes.sort(this._indexcmp);
2625
2626                         var list = $('<ul />');
2627
2628                         if (level == 0)
2629                                 list.addClass('nav').addClass('navbar-nav');
2630                         else if (level == 1)
2631                                 list.addClass('dropdown-menu').addClass('navbar-inverse');
2632
2633                         for (var i = 0; i < nodes.length; i++)
2634                         {
2635                                 if (!_luci2.globals.defaultNode)
2636                                 {
2637                                         var v = _luci2.getHash('view');
2638                                         if (!v || v == nodes[i].view)
2639                                                 _luci2.globals.defaultNode = nodes[i];
2640                                 }
2641
2642                                 var item = $('<li />')
2643                                         .append($('<a />')
2644                                                 .attr('href', '#')
2645                                                 .text(_luci2.tr(nodes[i].title)))
2646                                         .appendTo(list);
2647
2648                                 if (nodes[i].childs && level < max)
2649                                 {
2650                                         item.addClass('dropdown');
2651
2652                                         item.find('a')
2653                                                 .addClass('dropdown-toggle')
2654                                                 .attr('data-toggle', 'dropdown')
2655                                                 .append('<b class="caret"></b>');
2656
2657                                         item.append(this._render(nodes[i].childs, level + 1));
2658                                 }
2659                                 else
2660                                 {
2661                                         item.find('a').click(nodes[i], this._onclick);
2662                                 }
2663                         }
2664
2665                         return list.get(0);
2666                 },
2667
2668                 render: function(min, max)
2669                 {
2670                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2671                         return this._render(top.childs, 0, min, max);
2672                 },
2673
2674                 getNode: function(path, max)
2675                 {
2676                         var p = path.split(/\//);
2677                         var n = this._nodes;
2678
2679                         if (typeof(max) == 'undefined')
2680                                 max = p.length;
2681
2682                         for (var i = 0; i < max; i++)
2683                         {
2684                                 if (!n.childs[p[i]])
2685                                         return undefined;
2686
2687                                 n = n.childs[p[i]];
2688                         }
2689
2690                         return n;
2691                 }
2692         });
2693
2694         this.ui.table = this.ui.AbstractWidget.extend({
2695                 init: function()
2696                 {
2697                         this._rows = [ ];
2698                 },
2699
2700                 row: function(values)
2701                 {
2702                         if ($.isArray(values))
2703                         {
2704                                 this._rows.push(values);
2705                         }
2706                         else if ($.isPlainObject(values))
2707                         {
2708                                 var v = [ ];
2709                                 for (var i = 0; i < this.options.columns.length; i++)
2710                                 {
2711                                         var col = this.options.columns[i];
2712
2713                                         if (typeof col.key == 'string')
2714                                                 v.push(values[col.key]);
2715                                         else
2716                                                 v.push(null);
2717                                 }
2718                                 this._rows.push(v);
2719                         }
2720                 },
2721
2722                 rows: function(rows)
2723                 {
2724                         for (var i = 0; i < rows.length; i++)
2725                                 this.row(rows[i]);
2726                 },
2727
2728                 render: function(id)
2729                 {
2730                         var fieldset = document.createElement('fieldset');
2731                                 fieldset.className = 'cbi-section';
2732
2733                         if (this.options.caption)
2734                         {
2735                                 var legend = document.createElement('legend');
2736                                 $(legend).append(this.options.caption);
2737                                 fieldset.appendChild(legend);
2738                         }
2739
2740                         var table = document.createElement('table');
2741                                 table.className = 'table table-condensed table-hover';
2742
2743                         var has_caption = false;
2744                         var has_description = false;
2745
2746                         for (var i = 0; i < this.options.columns.length; i++)
2747                                 if (this.options.columns[i].caption)
2748                                 {
2749                                         has_caption = true;
2750                                         break;
2751                                 }
2752                                 else if (this.options.columns[i].description)
2753                                 {
2754                                         has_description = true;
2755                                         break;
2756                                 }
2757
2758                         if (has_caption)
2759                         {
2760                                 var tr = table.insertRow(-1);
2761                                         tr.className = 'cbi-section-table-titles';
2762
2763                                 for (var i = 0; i < this.options.columns.length; i++)
2764                                 {
2765                                         var col = this.options.columns[i];
2766                                         var th = document.createElement('th');
2767                                                 th.className = 'cbi-section-table-cell';
2768
2769                                         tr.appendChild(th);
2770
2771                                         if (col.width)
2772                                                 th.style.width = col.width;
2773
2774                                         if (col.align)
2775                                                 th.style.textAlign = col.align;
2776
2777                                         if (col.caption)
2778                                                 $(th).append(col.caption);
2779                                 }
2780                         }
2781
2782                         if (has_description)
2783                         {
2784                                 var tr = table.insertRow(-1);
2785                                         tr.className = 'cbi-section-table-descr';
2786
2787                                 for (var i = 0; i < this.options.columns.length; i++)
2788                                 {
2789                                         var col = this.options.columns[i];
2790                                         var th = document.createElement('th');
2791                                                 th.className = 'cbi-section-table-cell';
2792
2793                                         tr.appendChild(th);
2794
2795                                         if (col.width)
2796                                                 th.style.width = col.width;
2797
2798                                         if (col.align)
2799                                                 th.style.textAlign = col.align;
2800
2801                                         if (col.description)
2802                                                 $(th).append(col.description);
2803                                 }
2804                         }
2805
2806                         if (this._rows.length == 0)
2807                         {
2808                                 if (this.options.placeholder)
2809                                 {
2810                                         var tr = table.insertRow(-1);
2811                                         var td = tr.insertCell(-1);
2812                                                 td.className = 'cbi-section-table-cell';
2813
2814                                         td.colSpan = this.options.columns.length;
2815                                         $(td).append(this.options.placeholder);
2816                                 }
2817                         }
2818                         else
2819                         {
2820                                 for (var i = 0; i < this._rows.length; i++)
2821                                 {
2822                                         var tr = table.insertRow(-1);
2823
2824                                         for (var j = 0; j < this.options.columns.length; j++)
2825                                         {
2826                                                 var col = this.options.columns[j];
2827                                                 var td = tr.insertCell(-1);
2828
2829                                                 var val = this._rows[i][j];
2830
2831                                                 if (typeof(val) == 'undefined')
2832                                                         val = col.placeholder;
2833
2834                                                 if (typeof(val) == 'undefined')
2835                                                         val = '';
2836
2837                                                 if (col.width)
2838                                                         td.style.width = col.width;
2839
2840                                                 if (col.align)
2841                                                         td.style.textAlign = col.align;
2842
2843                                                 if (typeof col.format == 'string')
2844                                                         $(td).append(col.format.format(val));
2845                                                 else if (typeof col.format == 'function')
2846                                                         $(td).append(col.format(val, i));
2847                                                 else
2848                                                         $(td).append(val);
2849                                         }
2850                                 }
2851                         }
2852
2853                         this._rows = [ ];
2854                         fieldset.appendChild(table);
2855
2856                         return fieldset;
2857                 }
2858         });
2859
2860         this.ui.progress = this.ui.AbstractWidget.extend({
2861                 render: function()
2862                 {
2863                         var vn = parseInt(this.options.value) || 0;
2864                         var mn = parseInt(this.options.max) || 100;
2865                         var pc = Math.floor((100 / mn) * vn);
2866
2867                         var text;
2868
2869                         if (typeof(this.options.format) == 'string')
2870                                 text = this.options.format.format(this.options.value, this.options.max, pc);
2871                         else if (typeof(this.options.format) == 'function')
2872                                 text = this.options.format(pc);
2873                         else
2874                                 text = '%.2f%%'.format(pc);
2875
2876                         return $('<div />')
2877                                 .addClass('progress')
2878                                 .append($('<div />')
2879                                         .addClass('progress-bar')
2880                                         .addClass('progress-bar-info')
2881                                         .css('width', pc + '%'))
2882                                 .append($('<small />')
2883                                         .text(text));
2884                 }
2885         });
2886
2887         this.ui.devicebadge = this.ui.AbstractWidget.extend({
2888                 render: function()
2889                 {
2890                         var l2dev = this.options.l2_device || this.options.device;
2891                         var l3dev = this.options.l3_device;
2892                         var dev = l3dev || l2dev || '?';
2893
2894                         var span = document.createElement('span');
2895                                 span.className = 'badge';
2896
2897                         if (typeof(this.options.signal) == 'number' ||
2898                                 typeof(this.options.noise) == 'number')
2899                         {
2900                                 var r = 'none';
2901                                 if (typeof(this.options.signal) != 'undefined' &&
2902                                         typeof(this.options.noise) != 'undefined')
2903                                 {
2904                                         var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2905                                         if (q < 1)
2906                                                 r = '0';
2907                                         else if (q < 2)
2908                                                 r = '0-25';
2909                                         else if (q < 3)
2910                                                 r = '25-50';
2911                                         else if (q < 4)
2912                                                 r = '50-75';
2913                                         else
2914                                                 r = '75-100';
2915                                 }
2916
2917                                 span.appendChild(document.createElement('img'));
2918                                 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2919
2920                                 if (r == 'none')
2921                                         span.title = _luci2.tr('No signal');
2922                                 else
2923                                         span.title = '%s: %d %s / %s: %d %s'.format(
2924                                                 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2925                                                 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2926                                         );
2927                         }
2928                         else
2929                         {
2930                                 var type = 'ethernet';
2931                                 var desc = _luci2.tr('Ethernet device');
2932
2933                                 if (l3dev != l2dev)
2934                                 {
2935                                         type = 'tunnel';
2936                                         desc = _luci2.tr('Tunnel interface');
2937                                 }
2938                                 else if (dev.indexOf('br-') == 0)
2939                                 {
2940                                         type = 'bridge';
2941                                         desc = _luci2.tr('Bridge');
2942                                 }
2943                                 else if (dev.indexOf('.') > 0)
2944                                 {
2945                                         type = 'vlan';
2946                                         desc = _luci2.tr('VLAN interface');
2947                                 }
2948                                 else if (dev.indexOf('wlan') == 0 ||
2949                                                  dev.indexOf('ath') == 0 ||
2950                                                  dev.indexOf('wl') == 0)
2951                                 {
2952                                         type = 'wifi';
2953                                         desc = _luci2.tr('Wireless Network');
2954                                 }
2955
2956                                 span.appendChild(document.createElement('img'));
2957                                 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2958                                 span.title = desc;
2959                         }
2960
2961                         $(span).append(' ');
2962                         $(span).append(dev);
2963
2964                         return span;
2965                 }
2966         });
2967
2968         var type = function(f, l)
2969         {