6c7db677418081ed9582c9fcf8da1835dd56d3af
[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                         }).then(cb);
510                 },
511
512                 _list_cb: function(msg)
513                 {
514                         /* verify message frame */
515                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
516                                 throw 'Invalid JSON response';
517
518                         return msg.result;
519                 },
520
521                 _call_cb: function(msg)
522                 {
523                         var data = [ ];
524                         var type = Object.prototype.toString;
525
526                         if (!$.isArray(msg))
527                                 msg = [ msg ];
528
529                         for (var i = 0; i < msg.length; i++)
530                         {
531                                 /* verify message frame */
532                                 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
533                                         throw 'Invalid JSON response';
534
535                                 /* fetch related request info */
536                                 var req = _luci2.rpc._requests[msg[i].id];
537                                 if (typeof(req) != 'object')
538                                         throw 'No related request for JSON response';
539
540                                 /* fetch response attribute and verify returned type */
541                                 var ret = undefined;
542
543                                 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
544                                         ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
545
546                                 if (req.expect)
547                                 {
548                                         for (var key in req.expect)
549                                         {
550                                                 if (typeof(ret) != 'undefined' && key != '')
551                                                         ret = ret[key];
552
553                                                 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
554                                                         ret = req.expect[key];
555
556                                                 break;
557                                         }
558                                 }
559
560                                 /* apply filter */
561                                 if (typeof(req.filter) == 'function')
562                                 {
563                                         req.priv[0] = ret;
564                                         req.priv[1] = req.params;
565                                         ret = req.filter.apply(_luci2.rpc, req.priv);
566                                 }
567
568                                 /* store response data */
569                                 if (typeof(req.index) == 'number')
570                                         data[req.index] = ret;
571                                 else
572                                         data = ret;
573
574                                 /* delete request object */
575                                 delete _luci2.rpc._requests[msg[i].id];
576                         }
577
578                         return data;
579                 },
580
581                 list: function()
582                 {
583                         var params = [ ];
584                         for (var i = 0; i < arguments.length; i++)
585                                 params[i] = arguments[i];
586
587                         var msg = {
588                                 jsonrpc: '2.0',
589                                 id:      this._id++,
590                                 method:  'list',
591                                 params:  (params.length > 0) ? params : undefined
592                         };
593
594                         return this._call(msg, this._list_cb);
595                 },
596
597                 batch: function()
598                 {
599                         if (!$.isArray(this._batch))
600                                 this._batch = [ ];
601                 },
602
603                 flush: function()
604                 {
605                         if (!$.isArray(this._batch))
606                                 return _luci2.deferrable([ ]);
607
608                         var req = this._batch;
609                         delete this._batch;
610
611                         /* call rpc */
612                         return this._call(req, this._call_cb);
613                 },
614
615                 declare: function(options)
616                 {
617                         var _rpc = this;
618
619                         return function() {
620                                 /* build parameter object */
621                                 var p_off = 0;
622                                 var params = { };
623                                 if ($.isArray(options.params))
624                                         for (p_off = 0; p_off < options.params.length; p_off++)
625                                                 params[options.params[p_off]] = arguments[p_off];
626
627                                 /* all remaining arguments are private args */
628                                 var priv = [ undefined, undefined ];
629                                 for (; p_off < arguments.length; p_off++)
630                                         priv.push(arguments[p_off]);
631
632                                 /* store request info */
633                                 var req = _rpc._requests[_rpc._id] = {
634                                         expect: options.expect,
635                                         filter: options.filter,
636                                         params: params,
637                                         priv:   priv
638                                 };
639
640                                 /* build message object */
641                                 var msg = {
642                                         jsonrpc: '2.0',
643                                         id:      _rpc._id++,
644                                         method:  'call',
645                                         params:  [
646                                                 _luci2.globals.sid,
647                                                 options.object,
648                                                 options.method,
649                                                 params
650                                         ]
651                                 };
652
653                                 /* when a batch is in progress then store index in request data
654                                  * and push message object onto the stack */
655                                 if ($.isArray(_rpc._batch))
656                                 {
657                                         req.index = _rpc._batch.push(msg) - 1;
658                                         return _luci2.deferrable(msg);
659                                 }
660
661                                 /* call rpc */
662                                 return _rpc._call(msg, _rpc._call_cb);
663                         };
664                 }
665         };
666
667         this.uci = {
668
669                 writable: function()
670                 {
671                         return _luci2.session.access('ubus', 'uci', 'commit');
672                 },
673
674                 add: _luci2.rpc.declare({
675                         object: 'uci',
676                         method: 'add',
677                         params: [ 'config', 'type', 'name', 'values' ],
678                         expect: { section: '' }
679                 }),
680
681                 apply: function()
682                 {
683
684                 },
685
686                 configs: _luci2.rpc.declare({
687                         object: 'uci',
688                         method: 'configs',
689                         expect: { configs: [ ] }
690                 }),
691
692                 _changes: _luci2.rpc.declare({
693                         object: 'uci',
694                         method: 'changes',
695                         params: [ 'config' ],
696                         expect: { changes: [ ] }
697                 }),
698
699                 changes: function(config)
700                 {
701                         if (typeof(config) == 'string')
702                                 return this._changes(config);
703
704                         var configlist;
705                         return this.configs().then(function(configs) {
706                                 _luci2.rpc.batch();
707                                 configlist = configs;
708
709                                 for (var i = 0; i < configs.length; i++)
710                                         _luci2.uci._changes(configs[i]);
711
712                                 return _luci2.rpc.flush();
713                         }).then(function(changes) {
714                                 var rv = { };
715
716                                 for (var i = 0; i < configlist.length; i++)
717                                         if (changes[i].length)
718                                                 rv[configlist[i]] = changes[i];
719
720                                 return rv;
721                         });
722                 },
723
724                 commit: _luci2.rpc.declare({
725                         object: 'uci',
726                         method: 'commit',
727                         params: [ 'config' ]
728                 }),
729
730                 _delete_one: _luci2.rpc.declare({
731                         object: 'uci',
732                         method: 'delete',
733                         params: [ 'config', 'section', 'option' ]
734                 }),
735
736                 _delete_multiple: _luci2.rpc.declare({
737                         object: 'uci',
738                         method: 'delete',
739                         params: [ 'config', 'section', 'options' ]
740                 }),
741
742                 'delete': function(config, section, option)
743                 {
744                         if ($.isArray(option))
745                                 return this._delete_multiple(config, section, option);
746                         else
747                                 return this._delete_one(config, section, option);
748                 },
749
750                 delete_all: _luci2.rpc.declare({
751                         object: 'uci',
752                         method: 'delete',
753                         params: [ 'config', 'type', 'match' ]
754                 }),
755
756                 _foreach: _luci2.rpc.declare({
757                         object: 'uci',
758                         method: 'get',
759                         params: [ 'config', 'type' ],
760                         expect: { values: { } }
761                 }),
762
763                 foreach: function(config, type, cb)
764                 {
765                         return this._foreach(config, type).then(function(sections) {
766                                 for (var s in sections)
767                                         cb(sections[s]);
768                         });
769                 },
770
771                 get: _luci2.rpc.declare({
772                         object: 'uci',
773                         method: 'get',
774                         params: [ 'config', 'section', 'option' ],
775                         expect: { '': { } },
776                         filter: function(data, params) {
777                                 if (typeof(params.option) == 'undefined')
778                                         return data.values ? data.values['.type'] : undefined;
779                                 else
780                                         return data.value;
781                         }
782                 }),
783
784                 get_all: _luci2.rpc.declare({
785                         object: 'uci',
786                         method: 'get',
787                         params: [ 'config', 'section' ],
788                         expect: { values: { } },
789                         filter: function(data, params) {
790                                 if (typeof(params.section) == 'string')
791                                         data['.section'] = params.section;
792                                 else if (typeof(params.config) == 'string')
793                                         data['.package'] = params.config;
794                                 return data;
795                         }
796                 }),
797
798                 get_first: function(config, type, option)
799                 {
800                         return this._foreach(config, type).then(function(sections) {
801                                 for (var s in sections)
802                                 {
803                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
804
805                                         if (typeof(val) != 'undefined')
806                                                 return val;
807                                 }
808
809                                 return undefined;
810                         });
811                 },
812
813                 section: _luci2.rpc.declare({
814                         object: 'uci',
815                         method: 'add',
816                         params: [ 'config', 'type', 'name', 'values' ],
817                         expect: { section: '' }
818                 }),
819
820                 _set: _luci2.rpc.declare({
821                         object: 'uci',
822                         method: 'set',
823                         params: [ 'config', 'section', 'values' ]
824                 }),
825
826                 set: function(config, section, option, value)
827                 {
828                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
829                                 return this.section(config, section, option); /* option -> type */
830                         else if ($.isPlainObject(option))
831                                 return this._set(config, section, option); /* option -> values */
832
833                         var values = { };
834                             values[option] = value;
835
836                         return this._set(config, section, values);
837                 },
838
839                 order: _luci2.rpc.declare({
840                         object: 'uci',
841                         method: 'order',
842                         params: [ 'config', 'sections' ]
843                 })
844         };
845
846         this.network = {
847                 listNetworkNames: function() {
848                         return _luci2.rpc.list('network.interface.*').then(function(list) {
849                                 var names = [ ];
850                                 for (var name in list)
851                                         if (name != 'network.interface.loopback')
852                                                 names.push(name.substring(18));
853                                 names.sort();
854                                 return names;
855                         });
856                 },
857
858                 listDeviceNames: _luci2.rpc.declare({
859                         object: 'network.device',
860                         method: 'status',
861                         expect: { '': { } },
862                         filter: function(data) {
863                                 var names = [ ];
864                                 for (var name in data)
865                                         if (name != 'lo')
866                                                 names.push(name);
867                                 names.sort();
868                                 return names;
869                         }
870                 }),
871
872                 getNetworkStatus: function()
873                 {
874                         var nets = [ ];
875                         var devs = { };
876
877                         return this.listNetworkNames().then(function(names) {
878                                 _luci2.rpc.batch();
879
880                                 for (var i = 0; i < names.length; i++)
881                                         _luci2.network.getInterfaceStatus(names[i]);
882
883                                 return _luci2.rpc.flush();
884                         }).then(function(networks) {
885                                 for (var i = 0; i < networks.length; i++)
886                                 {
887                                         var net = nets[i] = networks[i];
888                                         var dev = net.l3_device || net.l2_device;
889                                         if (dev)
890                                                 net.device = devs[dev] || (devs[dev] = { });
891                                 }
892
893                                 _luci2.rpc.batch();
894
895                                 for (var dev in devs)
896                                         _luci2.network.getDeviceStatus(dev);
897
898                                 return _luci2.rpc.flush();
899                         }).then(function(devices) {
900                                 _luci2.rpc.batch();
901
902                                 for (var i = 0; i < devices.length; i++)
903                                 {
904                                         var brm = devices[i]['bridge-members'];
905                                         delete devices[i]['bridge-members'];
906
907                                         $.extend(devs[devices[i]['device']], devices[i]);
908
909                                         if (!brm)
910                                                 continue;
911
912                                         devs[devices[i]['device']].subdevices = [ ];
913
914                                         for (var j = 0; j < brm.length; j++)
915                                         {
916                                                 if (!devs[brm[j]])
917                                                 {
918                                                         devs[brm[j]] = { };
919                                                         _luci2.network.getDeviceStatus(brm[j]);
920                                                 }
921
922                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
923                                         }
924                                 }
925
926                                 return _luci2.rpc.flush();
927                         }).then(function(subdevices) {
928                                 for (var i = 0; i < subdevices.length; i++)
929                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
930
931                                 _luci2.rpc.batch();
932
933                                 for (var dev in devs)
934                                         _luci2.wireless.getDeviceStatus(dev);
935
936                                 return _luci2.rpc.flush();
937                         }).then(function(wifidevices) {
938                                 for (var i = 0; i < wifidevices.length; i++)
939                                         if (wifidevices[i])
940                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
941
942                                 nets.sort(function(a, b) {
943                                         if (a['interface'] < b['interface'])
944                                                 return -1;
945                                         else if (a['interface'] > b['interface'])
946                                                 return 1;
947                                         else
948                                                 return 0;
949                                 });
950
951                                 return nets;
952                         });
953                 },
954
955                 findWanInterfaces: function(cb)
956                 {
957                         return this.listNetworkNames().then(function(names) {
958                                 _luci2.rpc.batch();
959
960                                 for (var i = 0; i < names.length; i++)
961                                         _luci2.network.getInterfaceStatus(names[i]);
962
963                                 return _luci2.rpc.flush();
964                         }).then(function(interfaces) {
965                                 var rv = [ undefined, undefined ];
966
967                                 for (var i = 0; i < interfaces.length; i++)
968                                 {
969                                         if (!interfaces[i].route)
970                                                 continue;
971
972                                         for (var j = 0; j < interfaces[i].route.length; j++)
973                                         {
974                                                 var rt = interfaces[i].route[j];
975
976                                                 if (typeof(rt.table) != 'undefined')
977                                                         continue;
978
979                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
980                                                         rv[0] = interfaces[i];
981                                                 else if (rt.target == '::' && rt.mask == 0)
982                                                         rv[1] = interfaces[i];
983                                         }
984                                 }
985
986                                 return rv;
987                         });
988                 },
989
990                 getDHCPLeases: _luci2.rpc.declare({
991                         object: 'luci2.network',
992                         method: 'dhcp_leases',
993                         expect: { leases: [ ] }
994                 }),
995
996                 getDHCPv6Leases: _luci2.rpc.declare({
997                         object: 'luci2.network',
998                         method: 'dhcp6_leases',
999                         expect: { leases: [ ] }
1000                 }),
1001
1002                 getRoutes: _luci2.rpc.declare({
1003                         object: 'luci2.network',
1004                         method: 'routes',
1005                         expect: { routes: [ ] }
1006                 }),
1007
1008                 getIPv6Routes: _luci2.rpc.declare({
1009                         object: 'luci2.network',
1010                         method: 'routes',
1011                         expect: { routes: [ ] }
1012                 }),
1013
1014                 getARPTable: _luci2.rpc.declare({
1015                         object: 'luci2.network',
1016                         method: 'arp_table',
1017                         expect: { entries: [ ] }
1018                 }),
1019
1020                 getInterfaceStatus: _luci2.rpc.declare({
1021                         object: 'network.interface',
1022                         method: 'status',
1023                         params: [ 'interface' ],
1024                         expect: { '': { } },
1025                         filter: function(data, params) {
1026                                 data['interface'] = params['interface'];
1027                                 data['l2_device'] = data['device'];
1028                                 delete data['device'];
1029                                 return data;
1030                         }
1031                 }),
1032
1033                 getDeviceStatus: _luci2.rpc.declare({
1034                         object: 'network.device',
1035                         method: 'status',
1036                         params: [ 'name' ],
1037                         expect: { '': { } },
1038                         filter: function(data, params) {
1039                                 data['device'] = params['name'];
1040                                 return data;
1041                         }
1042                 }),
1043
1044                 getConntrackCount: _luci2.rpc.declare({
1045                         object: 'luci2.network',
1046                         method: 'conntrack_count',
1047                         expect: { '': { count: 0, limit: 0 } }
1048                 }),
1049
1050                 listSwitchNames: _luci2.rpc.declare({
1051                         object: 'luci2.network',
1052                         method: 'switch_list',
1053                         expect: { switches: [ ] }
1054                 }),
1055
1056                 getSwitchInfo: _luci2.rpc.declare({
1057                         object: 'luci2.network',
1058                         method: 'switch_info',
1059                         params: [ 'switch' ],
1060                         expect: { info: { } },
1061                         filter: function(data, params) {
1062                                 data['attrs']      = data['switch'];
1063                                 data['vlan_attrs'] = data['vlan'];
1064                                 data['port_attrs'] = data['port'];
1065                                 data['switch']     = params['switch'];
1066
1067                                 delete data.vlan;
1068                                 delete data.port;
1069
1070                                 return data;
1071                         }
1072                 }),
1073
1074                 getSwitchStatus: _luci2.rpc.declare({
1075                         object: 'luci2.network',
1076                         method: 'switch_status',
1077                         params: [ 'switch' ],
1078                         expect: { ports: [ ] }
1079                 }),
1080
1081
1082                 runPing: _luci2.rpc.declare({
1083                         object: 'luci2.network',
1084                         method: 'ping',
1085                         params: [ 'data' ],
1086                         expect: { '': { code: -1 } }
1087                 }),
1088
1089                 runPing6: _luci2.rpc.declare({
1090                         object: 'luci2.network',
1091                         method: 'ping6',
1092                         params: [ 'data' ],
1093                         expect: { '': { code: -1 } }
1094                 }),
1095
1096                 runTraceroute: _luci2.rpc.declare({
1097                         object: 'luci2.network',
1098                         method: 'traceroute',
1099                         params: [ 'data' ],
1100                         expect: { '': { code: -1 } }
1101                 }),
1102
1103                 runTraceroute6: _luci2.rpc.declare({
1104                         object: 'luci2.network',
1105                         method: 'traceroute6',
1106                         params: [ 'data' ],
1107                         expect: { '': { code: -1 } }
1108                 }),
1109
1110                 runNslookup: _luci2.rpc.declare({
1111                         object: 'luci2.network',
1112                         method: 'nslookup',
1113                         params: [ 'data' ],
1114                         expect: { '': { code: -1 } }
1115                 }),
1116
1117
1118                 setUp: _luci2.rpc.declare({
1119                         object: 'luci2.network',
1120                         method: 'ifup',
1121                         params: [ 'data' ],
1122                         expect: { '': { code: -1 } }
1123                 }),
1124
1125                 setDown: _luci2.rpc.declare({
1126                         object: 'luci2.network',
1127                         method: 'ifdown',
1128                         params: [ 'data' ],
1129                         expect: { '': { code: -1 } }
1130                 })
1131         };
1132
1133         this.wireless = {
1134                 listDeviceNames: _luci2.rpc.declare({
1135                         object: 'iwinfo',
1136                         method: 'devices',
1137                         expect: { 'devices': [ ] },
1138                         filter: function(data) {
1139                                 data.sort();
1140                                 return data;
1141                         }
1142                 }),
1143
1144                 getDeviceStatus: _luci2.rpc.declare({
1145                         object: 'iwinfo',
1146                         method: 'info',
1147                         params: [ 'device' ],
1148                         expect: { '': { } },
1149                         filter: function(data, params) {
1150                                 if (!$.isEmptyObject(data))
1151                                 {
1152                                         data['device'] = params['device'];
1153                                         return data;
1154                                 }
1155                                 return undefined;
1156                         }
1157                 }),
1158
1159                 getAssocList: _luci2.rpc.declare({
1160                         object: 'iwinfo',
1161                         method: 'assoclist',
1162                         params: [ 'device' ],
1163                         expect: { results: [ ] },
1164                         filter: function(data, params) {
1165                                 for (var i = 0; i < data.length; i++)
1166                                         data[i]['device'] = params['device'];
1167
1168                                 data.sort(function(a, b) {
1169                                         if (a.bssid < b.bssid)
1170                                                 return -1;
1171                                         else if (a.bssid > b.bssid)
1172                                                 return 1;
1173                                         else
1174                                                 return 0;
1175                                 });
1176
1177                                 return data;
1178                         }
1179                 }),
1180
1181                 getWirelessStatus: function() {
1182                         return this.listDeviceNames().then(function(names) {
1183                                 _luci2.rpc.batch();
1184
1185                                 for (var i = 0; i < names.length; i++)
1186                                         _luci2.wireless.getDeviceStatus(names[i]);
1187
1188                                 return _luci2.rpc.flush();
1189                         }).then(function(networks) {
1190                                 var rv = { };
1191
1192                                 var phy_attrs = [
1193                                         'country', 'channel', 'frequency', 'frequency_offset',
1194                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1195                                 ];
1196
1197                                 var net_attrs = [
1198                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1199                                         'signal', 'noise', 'bitrate', 'encryption'
1200                                 ];
1201
1202                                 for (var i = 0; i < networks.length; i++)
1203                                 {
1204                                         var phy = rv[networks[i].phy] || (
1205                                                 rv[networks[i].phy] = { networks: [ ] }
1206                                         );
1207
1208                                         var net = {
1209                                                 device: networks[i].device
1210                                         };
1211
1212                                         for (var j = 0; j < phy_attrs.length; j++)
1213                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1214
1215                                         for (var j = 0; j < net_attrs.length; j++)
1216                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1217
1218                                         phy.networks.push(net);
1219                                 }
1220
1221                                 return rv;
1222                         });
1223                 },
1224
1225                 getAssocLists: function()
1226                 {
1227                         return this.listDeviceNames().then(function(names) {
1228                                 _luci2.rpc.batch();
1229
1230                                 for (var i = 0; i < names.length; i++)
1231                                         _luci2.wireless.getAssocList(names[i]);
1232
1233                                 return _luci2.rpc.flush();
1234                         }).then(function(assoclists) {
1235                                 var rv = [ ];
1236
1237                                 for (var i = 0; i < assoclists.length; i++)
1238                                         for (var j = 0; j < assoclists[i].length; j++)
1239                                                 rv.push(assoclists[i][j]);
1240
1241                                 return rv;
1242                         });
1243                 },
1244
1245                 formatEncryption: function(enc)
1246                 {
1247                         var format_list = function(l, s)
1248                         {
1249                                 var rv = [ ];
1250                                 for (var i = 0; i < l.length; i++)
1251                                         rv.push(l[i].toUpperCase());
1252                                 return rv.join(s ? s : ', ');
1253                         }
1254
1255                         if (!enc || !enc.enabled)
1256                                 return _luci2.tr('None');
1257
1258                         if (enc.wep)
1259                         {
1260                                 if (enc.wep.length == 2)
1261                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1262                                 else if (enc.wep[0] == 'shared')
1263                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1264                                 else
1265                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1266                         }
1267                         else if (enc.wpa)
1268                         {
1269                                 if (enc.wpa.length == 2)
1270                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1271                                                 format_list(enc.authentication, '/'),
1272                                                 format_list(enc.ciphers, ', ')
1273                                         );
1274                                 else if (enc.wpa[0] == 2)
1275                                         return 'WPA2 %s (%s)'.format(
1276                                                 format_list(enc.authentication, '/'),
1277                                                 format_list(enc.ciphers, ', ')
1278                                         );
1279                                 else
1280                                         return 'WPA %s (%s)'.format(
1281                                                 format_list(enc.authentication, '/'),
1282                                                 format_list(enc.ciphers, ', ')
1283                                         );
1284                         }
1285
1286                         return _luci2.tr('Unknown');
1287                 }
1288         };
1289
1290         this.firewall = {
1291                 getZoneColor: function(zone)
1292                 {
1293                         if ($.isPlainObject(zone))
1294                                 zone = zone.name;
1295
1296                         if (zone == 'lan')
1297                                 return '#90f090';
1298                         else if (zone == 'wan')
1299                                 return '#f09090';
1300
1301                         for (var i = 0, hash = 0;
1302                                  i < zone.length;
1303                                  hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1304
1305                         for (var i = 0, color = '#';
1306                                  i < 3;
1307                                  color += ('00' + ((hash >> i++ * 8) & 0xFF).tozoneing(16)).slice(-2));
1308
1309                         return color;
1310                 },
1311
1312                 findZoneByNetwork: function(network)
1313                 {
1314                         var self = this;
1315                         var zone = undefined;
1316
1317                         return _luci2.uci.foreach('firewall', 'zone', function(z) {
1318                                 if (!z.name || !z.network)
1319                                         return;
1320
1321                                 if (!$.isArray(z.network))
1322                                         z.network = z.network.split(/\s+/);
1323
1324                                 for (var i = 0; i < z.network.length; i++)
1325                                 {
1326                                         if (z.network[i] == network)
1327                                         {
1328                                                 zone = z;
1329                                                 break;
1330                                         }
1331                                 }
1332                         }).then(function() {
1333                                 if (zone)
1334                                         zone.color = self.getZoneColor(zone);
1335
1336                                 return zone;
1337                         });
1338                 }
1339         };
1340
1341         this.system = {
1342                 getSystemInfo: _luci2.rpc.declare({
1343                         object: 'system',
1344                         method: 'info',
1345                         expect: { '': { } }
1346                 }),
1347
1348                 getBoardInfo: _luci2.rpc.declare({
1349                         object: 'system',
1350                         method: 'board',
1351                         expect: { '': { } }
1352                 }),
1353
1354                 getDiskInfo: _luci2.rpc.declare({
1355                         object: 'luci2.system',
1356                         method: 'diskfree',
1357                         expect: { '': { } }
1358                 }),
1359
1360                 getInfo: function(cb)
1361                 {
1362                         _luci2.rpc.batch();
1363
1364                         this.getSystemInfo();
1365                         this.getBoardInfo();
1366                         this.getDiskInfo();
1367
1368                         return _luci2.rpc.flush().then(function(info) {
1369                                 var rv = { };
1370
1371                                 $.extend(rv, info[0]);
1372                                 $.extend(rv, info[1]);
1373                                 $.extend(rv, info[2]);
1374
1375                                 return rv;
1376                         });
1377                 },
1378
1379                 getProcessList: _luci2.rpc.declare({
1380                         object: 'luci2.system',
1381                         method: 'process_list',
1382                         expect: { processes: [ ] },
1383                         filter: function(data) {
1384                                 data.sort(function(a, b) { return a.pid - b.pid });
1385                                 return data;
1386                         }
1387                 }),
1388
1389                 getSystemLog: _luci2.rpc.declare({
1390                         object: 'luci2.system',
1391                         method: 'syslog',
1392                         expect: { log: '' }
1393                 }),
1394
1395                 getKernelLog: _luci2.rpc.declare({
1396                         object: 'luci2.system',
1397                         method: 'dmesg',
1398                         expect: { log: '' }
1399                 }),
1400
1401                 getZoneInfo: function(cb)
1402                 {
1403                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1404                 },
1405
1406                 sendSignal: _luci2.rpc.declare({
1407                         object: 'luci2.system',
1408                         method: 'process_signal',
1409                         params: [ 'pid', 'signal' ],
1410                         filter: function(data) {
1411                                 return (data == 0);
1412                         }
1413                 }),
1414
1415                 initList: _luci2.rpc.declare({
1416                         object: 'luci2.system',
1417                         method: 'init_list',
1418                         expect: { initscripts: [ ] },
1419                         filter: function(data) {
1420                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1421                                 return data;
1422                         }
1423                 }),
1424
1425                 initEnabled: function(init, cb)
1426                 {
1427                         return this.initList().then(function(list) {
1428                                 for (var i = 0; i < list.length; i++)
1429                                         if (list[i].name == init)
1430                                                 return !!list[i].enabled;
1431
1432                                 return false;
1433                         });
1434                 },
1435
1436                 initRun: _luci2.rpc.declare({
1437                         object: 'luci2.system',
1438                         method: 'init_action',
1439                         params: [ 'name', 'action' ],
1440                         filter: function(data) {
1441                                 return (data == 0);
1442                         }
1443                 }),
1444
1445                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1446                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1447                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1448                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1449                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1450                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1451
1452
1453                 getRcLocal: _luci2.rpc.declare({
1454                         object: 'luci2.system',
1455                         method: 'rclocal_get',
1456                         expect: { data: '' }
1457                 }),
1458
1459                 setRcLocal: _luci2.rpc.declare({
1460                         object: 'luci2.system',
1461                         method: 'rclocal_set',
1462                         params: [ 'data' ]
1463                 }),
1464
1465
1466                 getCrontab: _luci2.rpc.declare({
1467                         object: 'luci2.system',
1468                         method: 'crontab_get',
1469                         expect: { data: '' }
1470                 }),
1471
1472                 setCrontab: _luci2.rpc.declare({
1473                         object: 'luci2.system',
1474                         method: 'crontab_set',
1475                         params: [ 'data' ]
1476                 }),
1477
1478
1479                 getSSHKeys: _luci2.rpc.declare({
1480                         object: 'luci2.system',
1481                         method: 'sshkeys_get',
1482                         expect: { keys: [ ] }
1483                 }),
1484
1485                 setSSHKeys: _luci2.rpc.declare({
1486                         object: 'luci2.system',
1487                         method: 'sshkeys_set',
1488                         params: [ 'keys' ]
1489                 }),
1490
1491
1492                 setPassword: _luci2.rpc.declare({
1493                         object: 'luci2.system',
1494                         method: 'password_set',
1495                         params: [ 'user', 'password' ]
1496                 }),
1497
1498
1499                 listLEDs: _luci2.rpc.declare({
1500                         object: 'luci2.system',
1501                         method: 'led_list',
1502                         expect: { leds: [ ] }
1503                 }),
1504
1505                 listUSBDevices: _luci2.rpc.declare({
1506                         object: 'luci2.system',
1507                         method: 'usb_list',
1508                         expect: { devices: [ ] }
1509                 }),
1510
1511
1512                 testUpgrade: _luci2.rpc.declare({
1513                         object: 'luci2.system',
1514                         method: 'upgrade_test',
1515                         expect: { '': { } }
1516                 }),
1517
1518                 startUpgrade: _luci2.rpc.declare({
1519                         object: 'luci2.system',
1520                         method: 'upgrade_start',
1521                         params: [ 'keep' ]
1522                 }),
1523
1524                 cleanUpgrade: _luci2.rpc.declare({
1525                         object: 'luci2.system',
1526                         method: 'upgrade_clean'
1527                 }),
1528
1529
1530                 restoreBackup: _luci2.rpc.declare({
1531                         object: 'luci2.system',
1532                         method: 'backup_restore'
1533                 }),
1534
1535                 cleanBackup: _luci2.rpc.declare({
1536                         object: 'luci2.system',
1537                         method: 'backup_clean'
1538                 }),
1539
1540
1541                 getBackupConfig: _luci2.rpc.declare({
1542                         object: 'luci2.system',
1543                         method: 'backup_config_get',
1544                         expect: { config: '' }
1545                 }),
1546
1547                 setBackupConfig: _luci2.rpc.declare({
1548                         object: 'luci2.system',
1549                         method: 'backup_config_set',
1550                         params: [ 'data' ]
1551                 }),
1552
1553
1554                 listBackup: _luci2.rpc.declare({
1555                         object: 'luci2.system',
1556                         method: 'backup_list',
1557                         expect: { files: [ ] }
1558                 }),
1559
1560
1561                 testReset: _luci2.rpc.declare({
1562                         object: 'luci2.system',
1563                         method: 'reset_test',
1564                         expect: { supported: false }
1565                 }),
1566
1567                 startReset: _luci2.rpc.declare({
1568                         object: 'luci2.system',
1569                         method: 'reset_start'
1570                 }),
1571
1572
1573                 performReboot: _luci2.rpc.declare({
1574                         object: 'luci2.system',
1575                         method: 'reboot'
1576                 })
1577         };
1578
1579         this.opkg = {
1580                 updateLists: _luci2.rpc.declare({
1581                         object: 'luci2.opkg',
1582                         method: 'update',
1583                         expect: { '': { } }
1584                 }),
1585
1586                 _allPackages: _luci2.rpc.declare({
1587                         object: 'luci2.opkg',
1588                         method: 'list',
1589                         params: [ 'offset', 'limit', 'pattern' ],
1590                         expect: { '': { } }
1591                 }),
1592
1593                 _installedPackages: _luci2.rpc.declare({
1594                         object: 'luci2.opkg',
1595                         method: 'list_installed',
1596                         params: [ 'offset', 'limit', 'pattern' ],
1597                         expect: { '': { } }
1598                 }),
1599
1600                 _findPackages: _luci2.rpc.declare({
1601                         object: 'luci2.opkg',
1602                         method: 'find',
1603                         params: [ 'offset', 'limit', 'pattern' ],
1604                         expect: { '': { } }
1605                 }),
1606
1607                 _fetchPackages: function(action, offset, limit, pattern)
1608                 {
1609                         var packages = [ ];
1610
1611                         return action(offset, limit, pattern).then(function(list) {
1612                                 if (!list.total || !list.packages)
1613                                         return { length: 0, total: 0 };
1614
1615                                 packages.push.apply(packages, list.packages);
1616                                 packages.total = list.total;
1617
1618                                 if (limit <= 0)
1619                                         limit = list.total;
1620
1621                                 if (packages.length >= limit)
1622                                         return packages;
1623
1624                                 _luci2.rpc.batch();
1625
1626                                 for (var i = offset + packages.length; i < limit; i += 100)
1627                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1628
1629                                 return _luci2.rpc.flush();
1630                         }).then(function(lists) {
1631                                 for (var i = 0; i < lists.length; i++)
1632                                 {
1633                                         if (!lists[i].total || !lists[i].packages)
1634                                                 continue;
1635
1636                                         packages.push.apply(packages, lists[i].packages);
1637                                         packages.total = lists[i].total;
1638                                 }
1639
1640                                 return packages;
1641                         });
1642                 },
1643
1644                 listPackages: function(offset, limit, pattern)
1645                 {
1646                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1647                 },
1648
1649                 installedPackages: function(offset, limit, pattern)
1650                 {
1651                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1652                 },
1653
1654                 findPackages: function(offset, limit, pattern)
1655                 {
1656                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1657                 },
1658
1659                 installPackage: _luci2.rpc.declare({
1660                         object: 'luci2.opkg',
1661                         method: 'install',
1662                         params: [ 'package' ],
1663                         expect: { '': { } }
1664                 }),
1665
1666                 removePackage: _luci2.rpc.declare({
1667                         object: 'luci2.opkg',
1668                         method: 'remove',
1669                         params: [ 'package' ],
1670                         expect: { '': { } }
1671                 }),
1672
1673                 getConfig: _luci2.rpc.declare({
1674                         object: 'luci2.opkg',
1675                         method: 'config_get',
1676                         expect: { config: '' }
1677                 }),
1678
1679                 setConfig: _luci2.rpc.declare({
1680                         object: 'luci2.opkg',
1681                         method: 'config_set',
1682                         params: [ 'data' ]
1683                 })
1684         };
1685
1686         this.session = {
1687
1688                 login: _luci2.rpc.declare({
1689                         object: 'session',
1690                         method: 'login',
1691                         params: [ 'username', 'password' ],
1692                         expect: { '': { } }
1693                 }),
1694
1695                 access: _luci2.rpc.declare({
1696                         object: 'session',
1697                         method: 'access',
1698                         params: [ 'scope', 'object', 'function' ],
1699                         expect: { access: false }
1700                 }),
1701
1702                 isAlive: function()
1703                 {
1704                         return _luci2.session.access('ubus', 'session', 'access');
1705                 },
1706
1707                 startHeartbeat: function()
1708                 {
1709                         this._hearbeatInterval = window.setInterval(function() {
1710                                 _luci2.session.isAlive().then(function(alive) {
1711                                         if (!alive)
1712                                         {
1713                                                 _luci2.session.stopHeartbeat();
1714                                                 _luci2.ui.login(true);
1715                                         }
1716
1717                                 });
1718                         }, _luci2.globals.timeout * 2);
1719                 },
1720
1721                 stopHeartbeat: function()
1722                 {
1723                         if (typeof(this._hearbeatInterval) != 'undefined')
1724                         {
1725                                 window.clearInterval(this._hearbeatInterval);
1726                                 delete this._hearbeatInterval;
1727                         }
1728                 }
1729         };
1730
1731         this.ui = {
1732
1733                 saveScrollTop: function()
1734                 {
1735                         this._scroll_top = $(document).scrollTop();
1736                 },
1737
1738                 restoreScrollTop: function()
1739                 {
1740                         if (typeof(this._scroll_top) == 'undefined')
1741                                 return;
1742
1743                         $(document).scrollTop(this._scroll_top);
1744
1745                         delete this._scroll_top;
1746                 },
1747
1748                 loading: function(enable)
1749                 {
1750                         var win = $(window);
1751                         var body = $('body');
1752
1753                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
1754                                 modal: $('<div />')
1755                                         .addClass('modal fade')
1756                                         .append($('<div />')
1757                                                 .addClass('modal-dialog')
1758                                                 .append($('<div />')
1759                                                         .addClass('modal-content luci2-modal-loader')
1760                                                         .append($('<div />')
1761                                                                 .addClass('modal-body')
1762                                                                 .text(_luci2.tr('Loading data…')))))
1763                                         .appendTo(body)
1764                                         .modal({
1765                                                 backdrop: 'static',
1766                                                 keyboard: false
1767                                         })
1768                         });
1769
1770                         state.modal.modal(enable ? 'show' : 'hide');
1771                 },
1772
1773                 dialog: function(title, content, options)
1774                 {
1775                         var win = $(window);
1776                         var body = $('body');
1777
1778                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1779                                 dialog: $('<div />')
1780                                         .addClass('modal fade')
1781                                         .append($('<div />')
1782                                                 .addClass('modal-dialog')
1783                                                 .append($('<div />')
1784                                                         .addClass('modal-content')
1785                                                         .append($('<div />')
1786                                                                 .addClass('modal-header')
1787                                                                 .append('<h4 />')
1788                                                                         .addClass('modal-title'))
1789                                                         .append($('<div />')
1790                                                                 .addClass('modal-body'))
1791                                                         .append($('<div />')
1792                                                                 .addClass('modal-footer')
1793                                                                 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1794                                                                         .click(function() {
1795                                                                                 $(this).parents('div.modal').modal('hide');
1796                                                                         })))))
1797                                         .appendTo(body)
1798                         });
1799
1800                         if (typeof(options) != 'object')
1801                                 options = { };
1802
1803                         if (title === false)
1804                         {
1805                                 state.dialog.modal('hide');
1806
1807                                 return;
1808                         }
1809
1810                         var cnt = state.dialog.children().children().children('div.modal-body');
1811                         var ftr = state.dialog.children().children().children('div.modal-footer');
1812
1813                         ftr.empty();
1814
1815                         if (options.style == 'confirm')
1816                         {
1817                                 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
1818                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1819
1820                                 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
1821                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1822                         }
1823                         else if (options.style == 'close')
1824                         {
1825                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1826                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1827                         }
1828                         else if (options.style == 'wait')
1829                         {
1830                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
1831                                         .attr('disabled', true));
1832                         }
1833
1834                         state.dialog.find('h4:first').text(title);
1835                         state.dialog.modal('show');
1836
1837                         cnt.empty().append(content);
1838                 },
1839
1840                 upload: function(title, content, options)
1841                 {
1842                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
1843                                 form: $('<form />')
1844                                         .attr('method', 'post')
1845                                         .attr('action', '/cgi-bin/luci-upload')
1846                                         .attr('enctype', 'multipart/form-data')
1847                                         .attr('target', 'cbi-fileupload-frame')
1848                                         .append($('<p />'))
1849                                         .append($('<input />')
1850                                                 .attr('type', 'hidden')
1851                                                 .attr('name', 'sessionid'))
1852                                         .append($('<input />')
1853                                                 .attr('type', 'hidden')
1854                                                 .attr('name', 'filename'))
1855                                         .append($('<input />')
1856                                                 .attr('type', 'file')
1857                                                 .attr('name', 'filedata')
1858                                                 .addClass('cbi-input-file'))
1859                                         .append($('<div />')
1860                                                 .css('width', '100%')
1861                                                 .addClass('progress progress-striped active')
1862                                                 .append($('<div />')
1863                                                         .addClass('progress-bar')
1864                                                         .css('width', '100%')))
1865                                         .append($('<iframe />')
1866                                                 .addClass('pull-right')
1867                                                 .attr('name', 'cbi-fileupload-frame')
1868                                                 .css('width', '1px')
1869                                                 .css('height', '1px')
1870                                                 .css('visibility', 'hidden')),
1871
1872                                 finish_cb: function(ev) {
1873                                         $(this).off('load');
1874
1875                                         var body = (this.contentDocument || this.contentWindow.document).body;
1876                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1877                                                 body = body.firstChild;
1878
1879                                         var json;
1880                                         try {
1881                                                 json = $.parseJSON(body.innerHTML);
1882                                         } catch(e) {
1883                                                 json = {
1884                                                         message: _luci2.tr('Invalid server response received'),
1885                                                         error: [ -1, _luci2.tr('Invalid data') ]
1886                                                 };
1887                                         };
1888
1889                                         if (json.error)
1890                                         {
1891                                                 L.ui.dialog(L.tr('File upload'), [
1892                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1893                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1894                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1895                                                 ], { style: 'close' });
1896                                         }
1897                                         else if (typeof(state.success_cb) == 'function')
1898                                         {
1899                                                 state.success_cb(json);
1900                                         }
1901                                 },
1902
1903                                 confirm_cb: function() {
1904                                         var f = state.form.find('.cbi-input-file');
1905                                         var b = state.form.find('.progress');
1906                                         var p = state.form.find('p');
1907
1908                                         if (!f.val())
1909                                                 return;
1910
1911                                         state.form.find('iframe').on('load', state.finish_cb);
1912                                         state.form.submit();
1913
1914                                         f.hide();
1915                                         b.show();
1916                                         p.text(_luci2.tr('File upload in progress …'));
1917
1918                                         state.form.parent().parent().find('button').prop('disabled', true);
1919                                 }
1920                         });
1921
1922                         state.form.find('.progress').hide();
1923                         state.form.find('.cbi-input-file').val('').show();
1924                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1925
1926                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1927                         state.form.find('[name=filename]').val(options.filename);
1928
1929                         state.success_cb = options.success;
1930
1931                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1932                                 style: 'confirm',
1933                                 confirm: state.confirm_cb
1934                         });
1935                 },
1936
1937                 reconnect: function()
1938                 {
1939                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1940                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1941                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1942                         var images    = $();
1943                         var interval, timeout;
1944
1945                         _luci2.ui.dialog(
1946                                 _luci2.tr('Waiting for device'), [
1947                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring …')),
1948                                         $('<div />')
1949                                                 .css('width', '100%')
1950                                                 .addClass('progressbar')
1951                                                 .addClass('intermediate')
1952                                                 .append($('<div />')
1953                                                         .css('width', '100%'))
1954                                 ], { style: 'wait' }
1955                         );
1956
1957                         for (var i = 0; i < protocols.length; i++)
1958                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1959
1960                         //_luci2.network.getNetworkStatus(function(s) {
1961                         //      for (var i = 0; i < protocols.length; i++)
1962                         //      {
1963                         //              for (var j = 0; j < s.length; j++)
1964                         //              {
1965                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1966                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1967                         //
1968                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1969                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1970                         //              }
1971                         //      }
1972                         //}).then(function() {
1973                                 images.on('load', function() {
1974                                         var url = this.getAttribute('url');
1975                                         _luci2.session.isAlive().then(function(access) {
1976                                                 if (access)
1977                                                 {
1978                                                         window.clearTimeout(timeout);
1979                                                         window.clearInterval(interval);
1980                                                         _luci2.ui.dialog(false);
1981                                                         images = null;
1982                                                 }
1983                                                 else
1984                                                 {
1985                                                         location.href = url;
1986                                                 }
1987                                         });
1988                                 });
1989
1990                                 interval = window.setInterval(function() {
1991                                         images.each(function() {
1992                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1993                                         });
1994                                 }, 5000);
1995
1996                                 timeout = window.setTimeout(function() {
1997                                         window.clearInterval(interval);
1998                                         images.off('load');
1999
2000                                         _luci2.ui.dialog(
2001                                                 _luci2.tr('Device not responding'),
2002                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
2003                                                 { style: 'close' }
2004                                         );
2005                                 }, 180000);
2006                         //});
2007                 },
2008
2009                 login: function(invalid)
2010                 {
2011                         var state = _luci2.ui._login || (_luci2.ui._login = {
2012                                 form: $('<form />')
2013                                         .attr('target', '')
2014                                         .attr('method', 'post')
2015                                         .append($('<p />')
2016                                                 .addClass('alert-message')
2017                                                 .text(_luci2.tr('Wrong username or password given!')))
2018                                         .append($('<p />')
2019                                                 .append($('<label />')
2020                                                         .text(_luci2.tr('Username'))
2021                                                         .append($('<br />'))
2022                                                         .append($('<input />')
2023                                                                 .attr('type', 'text')
2024                                                                 .attr('name', 'username')
2025                                                                 .attr('value', 'root')
2026                                                                 .addClass('form-control')
2027                                                                 .keypress(function(ev) {
2028                                                                         if (ev.which == 10 || ev.which == 13)
2029                                                                                 state.confirm_cb();
2030                                                                 }))))
2031                                         .append($('<p />')
2032                                                 .append($('<label />')
2033                                                         .text(_luci2.tr('Password'))
2034                                                         .append($('<br />'))
2035                                                         .append($('<input />')
2036                                                                 .attr('type', 'password')
2037                                                                 .attr('name', 'password')
2038                                                                 .addClass('form-control')
2039                                                                 .keypress(function(ev) {
2040                                                                         if (ev.which == 10 || ev.which == 13)
2041                                                                                 state.confirm_cb();
2042                                                                 }))))
2043                                         .append($('<p />')
2044                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
2045
2046                                 response_cb: function(response) {
2047                                         if (!response.ubus_rpc_session)
2048                                         {
2049                                                 _luci2.ui.login(true);
2050                                         }
2051                                         else
2052                                         {
2053                                                 _luci2.globals.sid = response.ubus_rpc_session;
2054                                                 _luci2.setHash('id', _luci2.globals.sid);
2055                                                 _luci2.session.startHeartbeat();
2056                                                 _luci2.ui.dialog(false);
2057                                                 state.deferred.resolve();
2058                                         }
2059                                 },
2060
2061                                 confirm_cb: function() {
2062                                         var u = state.form.find('[name=username]').val();
2063                                         var p = state.form.find('[name=password]').val();
2064
2065                                         if (!u)
2066                                                 return;
2067
2068                                         _luci2.ui.dialog(
2069                                                 _luci2.tr('Logging in'), [
2070                                                         $('<p />').text(_luci2.tr('Log in in progress …')),
2071                                                         $('<div />')
2072                                                                 .css('width', '100%')
2073                                                                 .addClass('progressbar')
2074                                                                 .addClass('intermediate')
2075                                                                 .append($('<div />')
2076                                                                         .css('width', '100%'))
2077                                                 ], { style: 'wait' }
2078                                         );
2079
2080                                         _luci2.globals.sid = '00000000000000000000000000000000';
2081                                         _luci2.session.login(u, p).then(state.response_cb);
2082                                 }
2083                         });
2084
2085                         if (!state.deferred || state.deferred.state() != 'pending')
2086                                 state.deferred = $.Deferred();
2087
2088                         /* try to find sid from hash */
2089                         var sid = _luci2.getHash('id');
2090                         if (sid && sid.match(/^[a-f0-9]{32}$/))
2091                         {
2092                                 _luci2.globals.sid = sid;
2093                                 _luci2.session.isAlive().then(function(access) {
2094                                         if (access)
2095                                         {
2096                                                 _luci2.session.startHeartbeat();
2097                                                 state.deferred.resolve();
2098                                         }
2099                                         else
2100                                         {
2101                                                 _luci2.setHash('id', undefined);
2102                                                 _luci2.ui.login();
2103                                         }
2104                                 });
2105
2106                                 return state.deferred;
2107                         }
2108
2109                         if (invalid)
2110                                 state.form.find('.alert-message').show();
2111                         else
2112                                 state.form.find('.alert-message').hide();
2113
2114                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
2115                                 style: 'confirm',
2116                                 confirm: state.confirm_cb
2117                         });
2118
2119                         state.form.find('[name=password]').focus();
2120
2121                         return state.deferred;
2122                 },
2123
2124                 cryptPassword: _luci2.rpc.declare({
2125                         object: 'luci2.ui',
2126                         method: 'crypt',
2127                         params: [ 'data' ],
2128                         expect: { crypt: '' }
2129                 }),
2130
2131
2132                 _acl_merge_scope: function(acl_scope, scope)
2133                 {
2134                         if ($.isArray(scope))
2135                         {
2136                                 for (var i = 0; i < scope.length; i++)
2137                                         acl_scope[scope[i]] = true;
2138                         }
2139                         else if ($.isPlainObject(scope))
2140                         {
2141                                 for (var object_name in scope)
2142                                 {
2143                                         if (!$.isArray(scope[object_name]))
2144                                                 continue;
2145
2146                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2147
2148                                         for (var i = 0; i < scope[object_name].length; i++)
2149                                                 acl_object[scope[object_name][i]] = true;
2150                                 }
2151                         }
2152                 },
2153
2154                 _acl_merge_permission: function(acl_perm, perm)
2155                 {
2156                         if ($.isPlainObject(perm))
2157                         {
2158                                 for (var scope_name in perm)
2159                                 {
2160                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2161                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
2162                                 }
2163                         }
2164                 },
2165
2166                 _acl_merge_group: function(acl_group, group)
2167                 {
2168                         if ($.isPlainObject(group))
2169                         {
2170                                 if (!acl_group.description)
2171                                         acl_group.description = group.description;
2172
2173                                 if (group.read)
2174                                 {
2175                                         var acl_perm = acl_group.read || (acl_group.read = { });
2176                                         this._acl_merge_permission(acl_perm, group.read);
2177                                 }
2178
2179                                 if (group.write)
2180                                 {
2181                                         var acl_perm = acl_group.write || (acl_group.write = { });
2182                                         this._acl_merge_permission(acl_perm, group.write);
2183                                 }
2184                         }
2185                 },
2186
2187                 _acl_merge_tree: function(acl_tree, tree)
2188                 {
2189                         if ($.isPlainObject(tree))
2190                         {
2191                                 for (var group_name in tree)
2192                                 {
2193                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2194                                         this._acl_merge_group(acl_group, tree[group_name]);
2195                                 }
2196                         }
2197                 },
2198
2199                 listAvailableACLs: _luci2.rpc.declare({
2200                         object: 'luci2.ui',
2201                         method: 'acls',
2202                         expect: { acls: [ ] },
2203                         filter: function(trees) {
2204                                 var acl_tree = { };
2205                                 for (var i = 0; i < trees.length; i++)
2206                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2207                                 return acl_tree;
2208                         }
2209                 }),
2210
2211                 renderMainMenu: _luci2.rpc.declare({
2212                         object: 'luci2.ui',
2213                         method: 'menu',
2214                         expect: { menu: { } },
2215                         filter: function(entries) {
2216                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
2217                                 _luci2.globals.mainMenu.entries(entries);
2218
2219                                 $('#mainmenu')
2220                                         .empty()
2221                                         .append(_luci2.globals.mainMenu.render(0, 1));
2222                         }
2223                 }),
2224
2225                 renderViewMenu: function()
2226                 {
2227                         $('#viewmenu')
2228                                 .empty()
2229                                 .append(_luci2.globals.mainMenu.render(2, 900));
2230                 },
2231
2232                 renderView: function()
2233                 {
2234                         var node = arguments[0];
2235                         var name = node.view.split(/\//).join('.');
2236                         var args = [ ];
2237
2238                         for (var i = 1; i < arguments.length; i++)
2239                                 args.push(arguments[i]);
2240
2241                         if (_luci2.globals.currentView)
2242                                 _luci2.globals.currentView.finish();
2243
2244                         _luci2.ui.renderViewMenu();
2245
2246                         if (!_luci2._views)
2247                                 _luci2._views = { };
2248
2249                         _luci2.setHash('view', node.view);
2250
2251                         if (_luci2._views[name] instanceof _luci2.ui.view)
2252                         {
2253                                 _luci2.globals.currentView = _luci2._views[name];
2254                                 return _luci2._views[name].render.apply(_luci2._views[name], args);
2255                         }
2256
2257                         var url = _luci2.globals.resource + '/view/' + name + '.js';
2258
2259                         return $.ajax(url, {
2260                                 method: 'GET',
2261                                 cache: true,
2262                                 dataType: 'text'
2263                         }).then(function(data) {
2264                                 try {
2265                                         var viewConstructorSource = (
2266                                                 '(function(L, $) { ' +
2267                                                         'return %s' +
2268                                                 '})(_luci2, $);\n\n' +
2269                                                 '//@ sourceURL=%s'
2270                                         ).format(data, url);
2271
2272                                         var viewConstructor = eval(viewConstructorSource);
2273
2274                                         _luci2._views[name] = new viewConstructor({
2275                                                 name: name,
2276                                                 acls: node.write || { }
2277                                         });
2278
2279                                         _luci2.globals.currentView = _luci2._views[name];
2280                                         return _luci2._views[name].render.apply(_luci2._views[name], args);
2281                                 }
2282                                 catch(e) {
2283                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
2284                                 };
2285
2286                                 return $.Deferred().resolve();
2287                         });
2288                 },
2289
2290                 updateHostname: function()
2291                 {
2292                         return _luci2.system.getBoardInfo().then(function(info) {
2293                                 if (info.hostname)
2294                                         $('#hostname').text(info.hostname);
2295                         });
2296                 },
2297
2298                 updateChanges: function()
2299                 {
2300                         return _luci2.uci.changes().then(function(changes) {
2301                                 var n = 0;
2302                                 var html = '';
2303
2304                                 for (var config in changes)
2305                                 {
2306                                         var log = [ ];
2307
2308                                         for (var i = 0; i < changes[config].length; i++)
2309                                         {
2310                                                 var c = changes[config][i];
2311
2312                                                 switch (c[0])
2313                                                 {
2314                                                 case 'order':
2315                                                         break;
2316
2317                                                 case 'remove':
2318                                                         if (c.length < 3)
2319                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2320                                                         else
2321                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2322                                                         break;
2323
2324                                                 case 'rename':
2325                                                         if (c.length < 4)
2326                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2327                                                         else
2328                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2329                                                         break;
2330
2331                                                 case 'add':
2332                                                         log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2333                                                         break;
2334
2335                                                 case 'list-add':
2336                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2337                                                         break;
2338
2339                                                 case 'list-del':
2340                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2341                                                         break;
2342
2343                                                 case 'set':
2344                                                         if (c.length < 4)
2345                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2346                                                         else
2347                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2348                                                         break;
2349                                                 }
2350                                         }
2351
2352                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2353                                         n += changes[config].length;
2354                                 }
2355
2356                                 if (n > 0)
2357                                         $('#changes')
2358                                                 .empty()
2359                                                 .show()
2360                                                 .append($('<a />')
2361                                                         .attr('href', '#')
2362                                                         .addClass('label')
2363                                                         .addClass('notice')
2364                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2365                                                         .click(function(ev) {
2366                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2367                                                                 ev.preventDefault();
2368                                                         }));
2369                                 else
2370                                         $('#changes')
2371                                                 .hide();
2372                         });
2373                 },
2374
2375                 init: function()
2376                 {
2377                         _luci2.ui.loading(true);
2378
2379                         $.when(
2380                                 _luci2.ui.updateHostname(),
2381                                 _luci2.ui.updateChanges(),
2382                                 _luci2.ui.renderMainMenu()
2383                         ).then(function() {
2384                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2385                                         _luci2.ui.loading(false);
2386                                 })
2387                         });
2388                 },
2389
2390                 button: function(label, style, title)
2391                 {
2392                         style = style || 'default';
2393
2394                         return $('<button />')
2395                                 .attr('type', 'button')
2396                                 .attr('title', title ? title : '')
2397                                 .addClass('btn btn-' + style)
2398                                 .text(label);
2399                 }
2400         };
2401
2402         this.ui.AbstractWidget = Class.extend({
2403                 i18n: function(text) {
2404                         return text;
2405                 },
2406
2407                 label: function() {
2408                         var key = arguments[0];
2409                         var args = [ ];
2410
2411                         for (var i = 1; i < arguments.length; i++)
2412                                 args.push(arguments[i]);
2413
2414                         switch (typeof(this.options[key]))
2415                         {
2416                         case 'undefined':
2417                                 return '';
2418
2419                         case 'function':
2420                                 return this.options[key].apply(this, args);
2421
2422                         default:
2423                                 return ''.format.apply('' + this.options[key], args);
2424                         }
2425                 },
2426
2427                 toString: function() {
2428                         return $('<div />').append(this.render()).html();
2429                 },
2430
2431                 insertInto: function(id) {
2432                         return $(id).empty().append(this.render());
2433                 },
2434
2435                 appendTo: function(id) {
2436                         return $(id).append(this.render());
2437                 }
2438         });
2439
2440         this.ui.view = this.ui.AbstractWidget.extend({
2441                 _fetch_template: function()
2442                 {
2443                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2444                                 method: 'GET',
2445                                 cache: true,
2446                                 dataType: 'text',
2447                                 success: function(data) {
2448                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2449                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2450                                                 switch (p1)
2451                                                 {
2452                                                 case '#':
2453                                                         return '';
2454
2455                                                 case ':':
2456                                                         return _luci2.tr(p2);
2457
2458                                                 case '=':
2459                                                         return _luci2.globals[p2] || '';
2460
2461                                                 default:
2462                                                         return '(?' + match + ')';
2463                                                 }
2464                                         });
2465
2466                                         $('#maincontent').append(data);
2467                                 }
2468                         });
2469                 },
2470
2471                 execute: function()
2472                 {
2473                         throw "Not implemented";
2474                 },
2475
2476                 render: function()
2477                 {
2478                         var container = $('#maincontent');
2479
2480                         container.empty();
2481
2482                         if (this.title)
2483                                 container.append($('<h2 />').append(this.title));
2484
2485                         if (this.description)
2486                                 container.append($('<p />').append(this.description));
2487
2488                         var self = this;
2489                         var args = [ ];
2490
2491                         for (var i = 0; i < arguments.length; i++)
2492                                 args.push(arguments[i]);
2493
2494                         return this._fetch_template().then(function() {
2495                                 return _luci2.deferrable(self.execute.apply(self, args));
2496                         });
2497                 },
2498
2499                 repeat: function(func, interval)
2500                 {
2501                         var self = this;
2502
2503                         if (!self._timeouts)
2504                                 self._timeouts = [ ];
2505
2506                         var index = self._timeouts.length;
2507
2508                         if (typeof(interval) != 'number')
2509                                 interval = 5000;
2510
2511                         var setTimer, runTimer;
2512
2513                         setTimer = function() {
2514                                 if (self._timeouts)
2515                                         self._timeouts[index] = window.setTimeout(runTimer, interval);
2516                         };
2517
2518                         runTimer = function() {
2519                                 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
2520                         };
2521
2522                         runTimer();
2523                 },
2524
2525                 finish: function()
2526                 {
2527                         if ($.isArray(this._timeouts))
2528                         {
2529                                 for (var i = 0; i < this._timeouts.length; i++)
2530                                         window.clearTimeout(this._timeouts[i]);
2531
2532                                 delete this._timeouts;
2533                         }
2534                 }
2535         });
2536
2537         this.ui.menu = this.ui.AbstractWidget.extend({
2538                 init: function() {
2539                         this._nodes = { };
2540                 },
2541
2542                 entries: function(entries)
2543                 {
2544                         for (var entry in entries)
2545                         {
2546                                 var path = entry.split(/\//);
2547                                 var node = this._nodes;
2548
2549                                 for (i = 0; i < path.length; i++)
2550                                 {
2551                                         if (!node.childs)
2552                                                 node.childs = { };
2553
2554                                         if (!node.childs[path[i]])
2555                                                 node.childs[path[i]] = { };
2556
2557                                         node = node.childs[path[i]];
2558                                 }
2559
2560                                 $.extend(node, entries[entry]);
2561                         }
2562                 },
2563
2564                 _indexcmp: function(a, b)
2565                 {
2566                         var x = a.index || 0;
2567                         var y = b.index || 0;
2568                         return (x - y);
2569                 },
2570
2571                 firstChildView: function(node)
2572                 {
2573                         if (node.view)
2574                                 return node;
2575
2576                         var nodes = [ ];
2577                         for (var child in (node.childs || { }))
2578                                 nodes.push(node.childs[child]);
2579
2580                         nodes.sort(this._indexcmp);
2581
2582                         for (var i = 0; i < nodes.length; i++)
2583                         {
2584                                 var child = this.firstChildView(nodes[i]);
2585                                 if (child)
2586                                 {
2587                                         for (var key in child)
2588                                                 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2589                                                         node[key] = child[key];
2590
2591                                         return node;
2592                                 }
2593                         }
2594
2595                         return undefined;
2596                 },
2597
2598                 _onclick: function(ev)
2599                 {
2600                         _luci2.ui.loading(true);
2601                         _luci2.ui.renderView(ev.data).then(function() {
2602                                 _luci2.ui.loading(false);
2603                         });
2604
2605                         ev.preventDefault();
2606                         this.blur();
2607                 },
2608
2609                 _render: function(childs, level, min, max)
2610                 {
2611                         var nodes = [ ];
2612                         for (var node in childs)
2613                         {
2614                                 var child = this.firstChildView(childs[node]);
2615                                 if (child)
2616                                         nodes.push(childs[node]);
2617                         }
2618
2619                         nodes.sort(this._indexcmp);
2620
2621                         var list = $('<ul />');
2622
2623                         if (level == 0)
2624                                 list.addClass('nav').addClass('navbar-nav');
2625                         else if (level == 1)
2626                                 list.addClass('dropdown-menu').addClass('navbar-inverse');
2627
2628                         for (var i = 0; i < nodes.length; i++)
2629                         {
2630                                 if (!_luci2.globals.defaultNode)
2631                                 {
2632                                         var v = _luci2.getHash('view');
2633                                         if (!v || v == nodes[i].view)
2634                                                 _luci2.globals.defaultNode = nodes[i];
2635                                 }
2636
2637                                 var item = $('<li />')
2638                                         .append($('<a />')
2639                                                 .attr('href', '#')
2640                                                 .text(_luci2.tr(nodes[i].title)))
2641                                         .appendTo(list);
2642
2643                                 if (nodes[i].childs && level < max)
2644                                 {
2645                                         item.addClass('dropdown');
2646
2647                                         item.find('a')
2648                                                 .addClass('dropdown-toggle')
2649                                                 .attr('data-toggle', 'dropdown')