2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String
.prototype.format = function()
15 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g
, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
27 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
29 while ((a
= re
.exec(str
)) != null)
32 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
33 var pPrecision
= a
[6], pType
= a
[7];
43 if (numSubstitutions
< arguments
.length
)
45 var param
= arguments
[numSubstitutions
++];
48 if (pPad
&& pPad
.substr(0,1) == "'")
49 pad
= leftpart
.substr(1,1);
53 var justifyRight
= true;
54 if (pJustify
&& pJustify
=== "-")
59 minLength
= parseInt(pMinLength
);
62 if (pPrecision
&& pType
== 'f')
63 precision
= parseInt(pPrecision
.substring(1));
70 subst
= (parseInt(param
) || 0).toString(2);
74 subst
= String
.fromCharCode(parseInt(param
) || 0);
78 subst
= (parseInt(param
) || 0);
82 subst
= Math
.abs(parseInt(param
) || 0);
86 subst
= (precision
> -1)
87 ? ((parseFloat(param
) || 0.0)).toFixed(precision
)
88 : (parseFloat(param
) || 0.0);
92 subst
= (parseInt(param
) || 0).toString(8);
100 subst
= ('' + (parseInt(param
) || 0).toString(16)).toLowerCase();
104 subst
= ('' + (parseInt(param
) || 0).toString(16)).toUpperCase();
108 subst
= esc(param
, html_esc
);
112 subst
= esc(param
, quot_esc
);
116 subst
= String
.serialize(param
);
123 var ts
= (param
|| 0);
126 tm
= Math
.floor(ts
/ 60);
131 th
= Math
.floor(tm
/ 60);
136 td
= Math
.floor(th
/ 24);
141 ? '%dd %dh %dm %ds'.format(td
, th
, tm
, ts
)
142 : '%dh %dm %ds'.format(th
, tm
, ts
);
147 var mf
= pMinLength
? parseInt(pMinLength
) : 1000;
148 var pr
= pPrecision
? Math
.floor(10*parseFloat('0'+pPrecision
)) : 2;
151 var val
= parseFloat(param
|| 0);
152 var units
= [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
157 subst
= val
.toFixed(pr
) + ' ' + units
[i
];
161 subst
= (typeof(subst
) == 'undefined') ? '' : subst
.toString();
163 if (minLength
> 0 && pad
.length
> 0)
164 for (var i
= 0; i
< (minLength
- subst
.length
); i
++)
165 subst
= justifyRight
? (pad
+ subst
) : (subst
+ pad
);
169 out
+= leftpart
+ subst
;
170 str
= str
.substr(m
.length
);
180 var Class = function() { };
182 Class
.extend = function(properties
)
184 Class
.initializing
= true;
186 var prototype = new this();
187 var superprot
= this.prototype;
189 Class
.initializing
= false;
191 $.extend(prototype, properties
, {
192 callSuper: function() {
194 var meth
= arguments
[0];
196 if (typeof(superprot
[meth
]) != 'function')
199 for (var i
= 1; i
< arguments
.length
; i
++)
200 args
.push(arguments
[i
]);
202 return superprot
[meth
].apply(this, args
);
208 this.options
= arguments
[0] || { };
210 if (!Class
.initializing
&& typeof(this.init
) == 'function')
211 this.init
.apply(this, arguments
);
214 _class
.prototype = prototype;
215 _class
.prototype.constructor = _class
;
217 _class
.extend
= Class
.extend
;
222 this.defaults = function(obj
, def
)
225 if (typeof(obj
[key
]) == 'undefined')
231 this.isDeferred = function(x
)
233 return (typeof(x
) == 'object' &&
234 typeof(x
.then
) == 'function' &&
235 typeof(x
.promise
) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments
[0]))
243 var d
= $.Deferred();
244 d
.resolve
.apply(d
, arguments
);
253 plural: function(n
) { return 0 + (n
!= 1) },
256 if (_luci2
.i18n
.loaded
)
259 var lang
= (navigator
.userLanguage
|| navigator
.language
|| 'en').toLowerCase();
260 var langs
= (lang
.indexOf('-') > -1) ? [ lang
, lang
.split(/-/)[0] ] : [ lang
];
262 for (var i
= 0; i
< langs
.length
; i
++)
263 $.ajax('%s/i18n/base.%s.json'.format(_luci2
.globals
.resource
, langs
[i
]), {
267 success: function(data
) {
268 $.extend(_luci2
.i18n
.catalog
, data
);
270 var pe
= _luci2
.i18n
.catalog
[''];
273 delete _luci2
.i18n
.catalog
[''];
275 var pf
= new Function('n', 'return 0 + (' + pe
+ ')');
276 _luci2
.i18n
.plural
= pf
;
282 _luci2
.i18n
.loaded
= true;
287 this.tr = function(msgid
)
291 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
293 if (typeof(msgstr
) == 'undefined')
295 else if (typeof(msgstr
) == 'string')
301 this.trp = function(msgid
, msgid_plural
, count
)
305 var msgstr
= _luci2
.i18n
.catalog
[msgid
];
307 if (typeof(msgstr
) == 'undefined')
308 return (count
== 1) ? msgid
: msgid_plural
;
309 else if (typeof(msgstr
) == 'string')
312 return msgstr
[_luci2
.i18n
.plural(count
)];
315 this.trc = function(msgctx
, msgid
)
319 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
321 if (typeof(msgstr
) == 'undefined')
323 else if (typeof(msgstr
) == 'string')
329 this.trcp = function(msgctx
, msgid
, msgid_plural
, count
)
333 var msgstr
= _luci2
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
335 if (typeof(msgstr
) == 'undefined')
336 return (count
== 1) ? msgid
: msgid_plural
;
337 else if (typeof(msgstr
) == 'string')
340 return msgstr
[_luci2
.i18n
.plural(count
)];
343 this.setHash = function(key
, value
)
346 var data
= this.getHash(undefined);
348 if (typeof(value
) == 'undefined')
359 for (var i
= 0; i
< keys
.length
; i
++)
364 h
+= keys
[i
] + ':' + data
[keys
[i
]];
368 location
.hash
= '#' + h
;
373 this.getHash = function(key
)
376 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
378 for (var i
= 0; i
< tuples
.length
; i
++)
380 var tuple
= tuples
[i
].split(/:/);
381 if (tuple
.length
== 2)
382 data
[tuple
[0]] = tuple
[1];
385 if (typeof(key
) != 'undefined')
391 this.toArray = function(x
)
401 var l
= x
.split(/\s+/);
402 for (var i
= 0; i
< l
.length
; i
++)
411 for (var i
= 0; i
< x
.length
; i
++)
415 else if ($.isPlainObject(x
))
419 if (x
.hasOwnProperty(k
))
428 this.toObject = function(x
)
438 var l
= x
.split(/\x+/);
439 for (var i
= 0; i
< l
.length
; i
++)
448 for (var i
= 0; i
< x
.length
; i
++)
452 else if ($.isPlainObject(x
))
461 this.filterArray = function(array
, item
)
463 if (!$.isArray(array
))
466 for (var i
= 0; i
< array
.length
; i
++)
467 if (array
[i
] === item
)
468 array
.splice(i
--, 1);
473 this.toClassName = function(str
, suffix
)
476 var l
= str
.split(/[\/.]/);
478 for (var i
= 0; i
< l
.length
; i
++)
480 n
+= l
[i
].charAt(0).toUpperCase() + l
[i
].substr(1).toLowerCase();
482 if (typeof(suffix
) == 'string')
491 sid
: '00000000000000000000000000000000'
500 _call: function(req
, cb
)
502 return $.ajax('/ubus', {
504 contentType
: 'application/json',
505 data
: JSON
.stringify(req
),
508 timeout
: _luci2
.globals
.timeout
,
513 _list_cb: function(msg
)
515 var list
= msg
.result
;
517 /* verify message frame */
518 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
|| !$.isArray(list
))
521 return $.Deferred().resolveWith(this, [ list
]);
524 _call_cb: function(msg
)
527 var type
= Object
.prototype.toString
;
528 var reqs
= this._rpc_req
;
530 if (!$.isArray(reqs
))
536 for (var i
= 0; i
< msg
.length
; i
++)
538 /* fetch related request info */
539 var req
= _luci2
.rpc
._requests
[reqs
[i
].id
];
540 if (typeof(req
) != 'object')
541 throw 'No related request for JSON response';
543 /* fetch response attribute and verify returned type */
546 /* verify message frame */
547 if (typeof(msg
[i
]) == 'object' && msg
[i
].jsonrpc
== '2.0')
548 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
549 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
553 for (var key
in req
.expect
)
555 if (typeof(ret
) != 'undefined' && key
!= '')
558 if (typeof(ret
) == 'undefined' || type
.call(ret
) != type
.call(req
.expect
[key
]))
559 ret
= req
.expect
[key
];
566 if (typeof(req
.filter
) == 'function')
569 req
.priv
[1] = req
.params
;
570 ret
= req
.filter
.apply(_luci2
.rpc
, req
.priv
);
573 /* store response data */
574 if (typeof(req
.index
) == 'number')
575 data
[req
.index
] = ret
;
579 /* delete request object */
580 delete _luci2
.rpc
._requests
[reqs
[i
].id
];
583 return $.Deferred().resolveWith(this, [ data
]);
589 for (var i
= 0; i
< arguments
.length
; i
++)
590 params
[i
] = arguments
[i
];
596 params
: (params
.length
> 0) ? params
: undefined
599 return this._call(msg
, this._list_cb
);
604 if (!$.isArray(this._batch
))
610 if (!$.isArray(this._batch
))
611 return _luci2
.deferrable([ ]);
613 var req
= this._batch
;
617 return this._call(req
, this._call_cb
);
620 declare: function(options
)
625 /* build parameter object */
628 if ($.isArray(options
.params
))
629 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
630 params
[options
.params
[p_off
]] = arguments
[p_off
];
632 /* all remaining arguments are private args */
633 var priv
= [ undefined, undefined ];
634 for (; p_off
< arguments
.length
; p_off
++)
635 priv
.push(arguments
[p_off
]);
637 /* store request info */
638 var req
= _rpc
._requests
[_rpc
._id
] = {
639 expect
: options
.expect
,
640 filter
: options
.filter
,
645 /* build message object */
658 /* when a batch is in progress then store index in request data
659 * and push message object onto the stack */
660 if ($.isArray(_rpc
._batch
))
662 req
.index
= _rpc
._batch
.push(msg
) - 1;
663 return _luci2
.deferrable(msg
);
667 return _rpc
._call(msg
, _rpc
._call_cb
);
672 this.UCIContext
= Class
.extend({
686 _load
: _luci2
.rpc
.declare({
689 params
: [ 'config' ],
690 expect
: { values
: { } }
693 _order
: _luci2
.rpc
.declare({
696 params
: [ 'config', 'sections' ]
699 _add
: _luci2
.rpc
.declare({
702 params
: [ 'config', 'type', 'name', 'values' ],
703 expect
: { section
: '' }
706 _set
: _luci2
.rpc
.declare({
709 params
: [ 'config', 'section', 'values' ]
712 _delete
: _luci2
.rpc
.declare({
715 params
: [ 'config', 'section', 'options' ]
718 load: function(packages
)
724 if (!$.isArray(packages
))
725 packages
= [ packages
];
729 for (var i
= 0; i
< packages
.length
; i
++)
730 if (!seen
[packages
[i
]])
732 pkgs
.push(packages
[i
]);
733 seen
[packages
[i
]] = true;
734 self
._load(packages
[i
]);
737 return _luci2
.rpc
.flush().then(function(responses
) {
738 for (var i
= 0; i
< responses
.length
; i
++)
739 self
.state
.values
[pkgs
[i
]] = responses
[i
];
745 unload: function(packages
)
747 if (!$.isArray(packages
))
748 packages
= [ packages
];
750 for (var i
= 0; i
< packages
.length
; i
++)
752 delete this.state
.values
[packages
[i
]];
753 delete this.state
.creates
[packages
[i
]];
754 delete this.state
.changes
[packages
[i
]];
755 delete this.state
.deletes
[packages
[i
]];
759 add: function(conf
, type
, name
)
761 var c
= this.state
.creates
;
762 var s
= '.new.%d'.format(this.state
.newid
++);
772 '.index': 1000 + this.state
.newid
778 remove: function(conf
, sid
)
780 var n
= this.state
.creates
;
781 var c
= this.state
.changes
;
782 var d
= this.state
.deletes
;
784 /* requested deletion of a just created section */
785 if (sid
.indexOf('.new.') == 0)
802 sections: function(conf
, type
, cb
)
805 var v
= this.state
.values
[conf
];
806 var n
= this.state
.creates
[conf
];
807 var c
= this.state
.changes
[conf
];
808 var d
= this.state
.deletes
[conf
];
814 if (!d
|| d
[s
] !== true)
815 if (!type
|| v
[s
]['.type'] == type
)
816 sa
.push($.extend({ }, v
[s
], c
? c
[s
] : undefined));
820 if (!type
|| n
[s
]['.type'] == type
)
823 sa
.sort(function(a
, b
) {
824 return a
['.index'] - b
['.index'];
827 for (var i
= 0; i
< sa
.length
; i
++)
830 if (typeof(cb
) == 'function')
831 for (var i
= 0; i
< sa
.length
; i
++)
832 cb
.call(this, sa
[i
], sa
[i
]['.name']);
837 get: function(conf
, sid
, opt
)
839 var v
= this.state
.values
;
840 var n
= this.state
.creates
;
841 var c
= this.state
.changes
;
842 var d
= this.state
.deletes
;
844 if (typeof(sid
) == 'undefined')
847 /* requested option in a just created section */
848 if (sid
.indexOf('.new.') == 0)
853 if (typeof(opt
) == 'undefined')
856 return n
[conf
][sid
][opt
];
859 /* requested an option value */
860 if (typeof(opt
) != 'undefined')
862 /* check whether option was deleted */
863 if (d
[conf
] && d
[conf
][sid
])
865 if (d
[conf
][sid
] === true)
868 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
869 if (d
[conf
][sid
][i
] == opt
)
873 /* check whether option was changed */
874 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
875 return c
[conf
][sid
][opt
];
877 /* return base value */
878 if (v
[conf
] && v
[conf
][sid
])
879 return v
[conf
][sid
][opt
];
884 /* requested an entire section */
891 set: function(conf
, sid
, opt
, val
)
893 var n
= this.state
.creates
;
894 var c
= this.state
.changes
;
895 var d
= this.state
.deletes
;
897 if (typeof(sid
) == 'undefined' ||
898 typeof(opt
) == 'undefined' ||
899 opt
.charAt(0) == '.')
902 if (sid
.indexOf('.new.') == 0)
904 if (n
[conf
] && n
[conf
][sid
])
906 if (typeof(val
) != 'undefined')
907 n
[conf
][sid
][opt
] = val
;
909 delete n
[conf
][sid
][opt
];
912 else if (typeof(val
) != 'undefined')
914 /* do not set within deleted section */
915 if (d
[conf
] && d
[conf
][sid
] === true)
924 /* undelete option */
925 if (d
[conf
] && d
[conf
][sid
])
926 d
[conf
][sid
] = _luci2
.filterArray(d
[conf
][sid
], opt
);
928 c
[conf
][sid
][opt
] = val
;
938 if (d
[conf
][sid
] !== true)
939 d
[conf
][sid
].push(opt
);
943 unset: function(conf
, sid
, opt
)
945 return this.set(conf
, sid
, opt
, undefined);
952 for (var pkg
in this.state
.values
)
957 return this.load(pkgs
);
962 var v
= this.state
.values
;
963 var n
= this.state
.creates
;
964 var r
= this.state
.reorder
;
966 if ($.isEmptyObject(r
))
967 return _luci2
.deferrable();
972 gather all created and existing sections, sort them according
973 to their index value and issue an uci order call
988 o
.sort(function(a
, b
) {
989 return (a
['.index'] - b
['.index']);
994 for (var i
= 0; i
< o
.length
; i
++)
995 sids
.push(o
[i
]['.name']);
997 this._order(c
, sids
);
1001 this.state
.reorder
= { };
1002 return _luci2
.rpc
.flush();
1005 swap: function(conf
, sid1
, sid2
)
1007 var s1
= this.get(conf
, sid1
);
1008 var s2
= this.get(conf
, sid2
);
1009 var n1
= s1
? s1
['.index'] : NaN
;
1010 var n2
= s2
? s2
['.index'] : NaN
;
1012 if (isNaN(n1
) || isNaN(n2
))
1018 this.state
.reorder
[conf
] = true;
1030 if (self
.state
.creates
)
1031 for (var c
in self
.state
.creates
)
1032 for (var s
in self
.state
.creates
[c
])
1039 for (var k
in self
.state
.creates
[c
][s
])
1042 r
.type
= self
.state
.creates
[c
][s
][k
];
1043 else if (k
== '.create')
1044 r
.name
= self
.state
.creates
[c
][s
][k
];
1045 else if (k
.charAt(0) != '.')
1046 r
.values
[k
] = self
.state
.creates
[c
][s
][k
];
1049 snew
.push(self
.state
.creates
[c
][s
]);
1051 self
._add(r
.config
, r
.type
, r
.name
, r
.values
);
1054 if (self
.state
.changes
)
1055 for (var c
in self
.state
.changes
)
1056 for (var s
in self
.state
.changes
[c
])
1057 self
._set(c
, s
, self
.state
.changes
[c
][s
]);
1059 if (self
.state
.deletes
)
1060 for (var c
in self
.state
.deletes
)
1061 for (var s
in self
.state
.deletes
[c
])
1063 var o
= self
.state
.deletes
[c
][s
];
1064 self
._delete(c
, s
, (o
=== true) ? undefined : o
);
1067 return _luci2
.rpc
.flush().then(function(responses
) {
1069 array "snew" holds references to the created uci sections,
1070 use it to assign the returned names of the new sections
1072 for (var i
= 0; i
< snew
.length
; i
++)
1073 snew
[i
]['.name'] = responses
[i
];
1075 return self
._reorder();
1079 _apply
: _luci2
.rpc
.declare({
1082 params
: [ 'timeout', 'rollback' ]
1085 _confirm
: _luci2
.rpc
.declare({
1090 apply: function(timeout
)
1093 var date
= new Date();
1094 var deferred
= $.Deferred();
1096 if (typeof(timeout
) != 'number' || timeout
< 1)
1099 self
._apply(timeout
, true).then(function(rv
) {
1102 deferred
.rejectWith(self
, [ rv
]);
1106 var try_deadline
= date
.getTime() + 1000 * timeout
;
1107 var try_confirm = function()
1109 return self
._confirm().then(function(rv
) {
1112 if (date
.getTime() < try_deadline
)
1113 window
.setTimeout(try_confirm
, 250);
1115 deferred
.rejectWith(self
, [ rv
]);
1120 deferred
.resolveWith(self
, [ rv
]);
1124 window
.setTimeout(try_confirm
, 1000);
1130 changes
: _luci2
.rpc
.declare({
1133 expect
: { changes
: { } }
1136 readable: function(conf
)
1138 return _luci2
.session
.hasACL('uci', conf
, 'read');
1141 writable: function(conf
)
1143 return _luci2
.session
.hasACL('uci', conf
, 'write');
1147 this.uci
= new this.UCIContext();
1150 listDeviceNames
: _luci2
.rpc
.declare({
1153 expect
: { 'devices': [ ] },
1154 filter: function(data
) {
1160 getDeviceStatus
: _luci2
.rpc
.declare({
1163 params
: [ 'device' ],
1164 expect
: { '': { } },
1165 filter: function(data
, params
) {
1166 if (!$.isEmptyObject(data
))
1168 data
['device'] = params
['device'];
1175 getAssocList
: _luci2
.rpc
.declare({
1177 method
: 'assoclist',
1178 params
: [ 'device' ],
1179 expect
: { results
: [ ] },
1180 filter: function(data
, params
) {
1181 for (var i
= 0; i
< data
.length
; i
++)
1182 data
[i
]['device'] = params
['device'];
1184 data
.sort(function(a
, b
) {
1185 if (a
.bssid
< b
.bssid
)
1187 else if (a
.bssid
> b
.bssid
)
1197 getWirelessStatus: function() {
1198 return this.listDeviceNames().then(function(names
) {
1201 for (var i
= 0; i
< names
.length
; i
++)
1202 _luci2
.wireless
.getDeviceStatus(names
[i
]);
1204 return _luci2
.rpc
.flush();
1205 }).then(function(networks
) {
1209 'country', 'channel', 'frequency', 'frequency_offset',
1210 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1214 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1215 'signal', 'noise', 'bitrate', 'encryption'
1218 for (var i
= 0; i
< networks
.length
; i
++)
1220 var phy
= rv
[networks
[i
].phy
] || (
1221 rv
[networks
[i
].phy
] = { networks
: [ ] }
1225 device
: networks
[i
].device
1228 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1229 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1231 for (var j
= 0; j
< net_attrs
.length
; j
++)
1232 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1234 phy
.networks
.push(net
);
1241 getAssocLists: function()
1243 return this.listDeviceNames().then(function(names
) {
1246 for (var i
= 0; i
< names
.length
; i
++)
1247 _luci2
.wireless
.getAssocList(names
[i
]);
1249 return _luci2
.rpc
.flush();
1250 }).then(function(assoclists
) {
1253 for (var i
= 0; i
< assoclists
.length
; i
++)
1254 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1255 rv
.push(assoclists
[i
][j
]);
1261 formatEncryption: function(enc
)
1263 var format_list = function(l
, s
)
1266 for (var i
= 0; i
< l
.length
; i
++)
1267 rv
.push(l
[i
].toUpperCase());
1268 return rv
.join(s
? s
: ', ');
1271 if (!enc
|| !enc
.enabled
)
1272 return _luci2
.tr('None');
1276 if (enc
.wep
.length
== 2)
1277 return _luci2
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1278 else if (enc
.wep
[0] == 'shared')
1279 return _luci2
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1281 return _luci2
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1285 if (enc
.wpa
.length
== 2)
1286 return _luci2
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1287 format_list(enc
.authentication
, '/'),
1288 format_list(enc
.ciphers
, ', ')
1290 else if (enc
.wpa
[0] == 2)
1291 return 'WPA2 %s (%s)'.format(
1292 format_list(enc
.authentication
, '/'),
1293 format_list(enc
.ciphers
, ', ')
1296 return 'WPA %s (%s)'.format(
1297 format_list(enc
.authentication
, '/'),
1298 format_list(enc
.ciphers
, ', ')
1302 return _luci2
.tr('Unknown');
1307 getZoneColor: function(zone
)
1309 if ($.isPlainObject(zone
))
1314 else if (zone
== 'wan')
1317 for (var i
= 0, hash
= 0;
1319 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1321 for (var i
= 0, color
= '#';
1323 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tostring(16)).slice(-2));
1328 findZoneByNetwork: function(network
)
1331 var zone
= undefined;
1333 return _luci2
.uci
.sections('firewall', 'zone', function(z
) {
1334 if (!z
.name
|| !z
.network
)
1337 if (!$.isArray(z
.network
))
1338 z
.network
= z
.network
.split(/\s+/);
1340 for (var i
= 0; i
< z
.network
.length
; i
++)
1342 if (z
.network
[i
] == network
)
1348 }).then(function() {
1350 zone
.color
= self
.getZoneColor(zone
);
1357 this.NetworkModel
= {
1358 _device_blacklist
: [
1364 /^wlan[0-9]+\.sta[0-9]+$/
1368 'protolist', 0, _luci2
.rpc
.declare({
1370 method
: 'get_proto_handlers',
1373 'ifstate', 1, _luci2
.rpc
.declare({
1374 object
: 'network.interface',
1376 expect
: { 'interface': [ ] }
1378 'devstate', 2, _luci2
.rpc
.declare({
1379 object
: 'network.device',
1383 'wifistate', 0, _luci2
.rpc
.declare({
1384 object
: 'network.wireless',
1388 'bwstate', 2, _luci2
.rpc
.declare({
1389 object
: 'luci2.network.bwmon',
1390 method
: 'statistics',
1391 expect
: { 'statistics': { } }
1393 'devlist', 2, _luci2
.rpc
.declare({
1394 object
: 'luci2.network',
1395 method
: 'device_list',
1396 expect
: { 'devices': [ ] }
1398 'swlist', 0, _luci2
.rpc
.declare({
1399 object
: 'luci2.network',
1400 method
: 'switch_list',
1401 expect
: { 'switches': [ ] }
1405 _fetch_protocol: function(proto
)
1407 var url
= _luci2
.globals
.resource
+ '/proto/' + proto
+ '.js';
1408 var self
= _luci2
.NetworkModel
;
1410 var def
= $.Deferred();
1416 }).then(function(data
) {
1418 var protoConstructorSource
= (
1419 '(function(L, $) { ' +
1421 '})(_luci2, $);\n\n' +
1423 ).format(data
, url
);
1425 var protoClass
= eval(protoConstructorSource
);
1427 self
._protos
[proto
] = new protoClass();
1430 alert('Unable to instantiate proto "%s": %s'.format(url
, e
));
1434 }).fail(function() {
1441 _fetch_protocols: function()
1443 var self
= _luci2
.NetworkModel
;
1444 var deferreds
= [ ];
1446 for (var proto
in self
._cache
.protolist
)
1447 deferreds
.push(self
._fetch_protocol(proto
));
1449 return $.when
.apply($, deferreds
);
1452 _fetch_swstate
: _luci2
.rpc
.declare({
1453 object
: 'luci2.network',
1454 method
: 'switch_info',
1455 params
: [ 'switch' ],
1456 expect
: { 'info': { } }
1459 _fetch_swstate_cb: function(responses
) {
1460 var self
= _luci2
.NetworkModel
;
1461 var swlist
= self
._cache
.swlist
;
1462 var swstate
= self
._cache
.swstate
= { };
1464 for (var i
= 0; i
< responses
.length
; i
++)
1465 swstate
[swlist
[i
]] = responses
[i
];
1468 _fetch_cache_cb: function(level
)
1470 var self
= _luci2
.NetworkModel
;
1471 var name
= '_fetch_cache_cb_' + level
;
1473 return self
[name
] || (
1474 self
[name
] = function(responses
)
1476 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1477 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1478 self
._cache
[self
._cache_functions
[i
]] = responses
.shift();
1484 for (var i
= 0; i
< self
._cache
.swlist
.length
; i
++)
1485 self
._fetch_swstate(self
._cache
.swlist
[i
]);
1487 return _luci2
.rpc
.flush().then(self
._fetch_swstate_cb
);
1490 return _luci2
.deferrable();
1495 _fetch_cache: function(level
)
1497 var self
= _luci2
.NetworkModel
;
1499 return _luci2
.uci
.load(['network', 'wireless']).then(function() {
1502 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1503 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1504 self
._cache_functions
[i
+ 2]();
1506 return _luci2
.rpc
.flush().then(self
._fetch_cache_cb(level
|| 0));
1510 _get: function(pkg
, sid
, key
)
1512 return _luci2
.uci
.get(pkg
, sid
, key
);
1515 _set: function(pkg
, sid
, key
, val
)
1517 return _luci2
.uci
.set(pkg
, sid
, key
, val
);
1520 _is_blacklisted: function(dev
)
1522 for (var i
= 0; i
< this._device_blacklist
.length
; i
++)
1523 if (dev
.match(this._device_blacklist
[i
]))
1529 _sort_devices: function(a
, b
)
1531 if (a
.options
.kind
< b
.options
.kind
)
1533 else if (a
.options
.kind
> b
.options
.kind
)
1536 if (a
.options
.name
< b
.options
.name
)
1538 else if (a
.options
.name
> b
.options
.name
)
1544 _get_dev: function(ifname
)
1546 var alias
= (ifname
.charAt(0) == '@');
1547 return this._devs
[ifname
] || (
1548 this._devs
[ifname
] = {
1550 kind
: alias
? 'alias' : 'ethernet',
1551 type
: alias
? 0 : 1,
1558 _get_iface: function(name
)
1560 return this._ifaces
[name
] || (
1561 this._ifaces
[name
] = {
1563 proto
: this._protos
.none
,
1569 _parse_devices: function()
1571 var self
= _luci2
.NetworkModel
;
1572 var wificount
= { };
1574 for (var ifname
in self
._cache
.devstate
)
1576 if (self
._is_blacklisted(ifname
))
1579 var dev
= self
._cache
.devstate
[ifname
];
1580 var entry
= self
._get_dev(ifname
);
1587 entry
.kind
= 'tunnel';
1591 entry
.kind
= 'bridge';
1592 //entry.ports = dev['bridge-members'].sort();
1597 for (var i
= 0; i
< self
._cache
.devlist
.length
; i
++)
1599 var dev
= self
._cache
.devlist
[i
];
1601 if (self
._is_blacklisted(dev
.device
))
1604 var entry
= self
._get_dev(dev
.device
);
1606 entry
.up
= dev
.is_up
;
1607 entry
.type
= dev
.type
;
1611 case 1: /* Ethernet */
1613 entry
.kind
= 'bridge';
1614 else if (dev
.is_tuntap
)
1615 entry
.kind
= 'tunnel';
1616 else if (dev
.is_wireless
)
1617 entry
.kind
= 'wifi';
1621 case 768: /* IP-IP Tunnel */
1622 case 769: /* IP6-IP6 Tunnel */
1623 case 776: /* IPv6-in-IPv4 */
1624 case 778: /* GRE over IP */
1625 entry
.kind
= 'tunnel';
1630 var net
= _luci2
.uci
.sections('network');
1631 for (var i
= 0; i
< net
.length
; i
++)
1634 var sid
= s
['.name'];
1636 if (s
['.type'] == 'device' && s
.name
)
1638 var entry
= self
._get_dev(s
.name
);
1644 entry
.kind
= 'tunnel';
1650 else if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.ifname
)
1652 var ifnames
= _luci2
.toArray(s
.ifname
);
1654 for (var j
= 0; j
< ifnames
.length
; j
++)
1655 self
._get_dev(ifnames
[j
]);
1657 if (s
['.name'] != 'loopback')
1659 var entry
= self
._get_dev('@%s'.format(s
['.name']));
1662 entry
.kind
= 'alias';
1666 else if (s
['.type'] == 'switch_vlan' && s
.device
)
1668 var sw
= self
._cache
.swstate
[s
.device
];
1669 var vid
= parseInt(s
.vid
|| s
.vlan
);
1670 var ports
= _luci2
.toArray(s
.ports
);
1672 if (!sw
|| !ports
.length
|| isNaN(vid
))
1675 var ifname
= undefined;
1677 for (var j
= 0; j
< ports
.length
; j
++)
1679 var port
= parseInt(ports
[j
]);
1680 var tag
= (ports
[j
].replace(/[^tu]/g, '') == 't');
1682 if (port
== sw
.cpu_port
)
1684 // XXX: need a way to map switch to netdev
1686 ifname
= 'eth0.%d'.format(vid
);
1697 var entry
= self
._get_dev(ifname
);
1699 entry
.kind
= 'vlan';
1706 var wifi
= _luci2
.uci
.sections('wireless');
1707 for (var i
= 0; i
< wifi
.length
; i
++)
1710 var sid
= s
['.name'];
1712 if (s
['.type'] == 'wifi-iface' && s
.device
)
1714 var r
= parseInt(s
.device
.replace(/^[^0-9]+/, ''));
1715 var n
= wificount
[s
.device
] = (wificount
[s
.device
] || 0) + 1;
1716 var id
= 'radio%d.network%d'.format(r
, n
);
1719 if (self
._cache
.wifistate
[s
.device
])
1721 var ifcs
= self
._cache
.wifistate
[s
.device
].interfaces
;
1722 for (var ifc
in ifcs
)
1724 if (ifcs
[ifc
].section
== sid
)
1726 ifname
= ifcs
[ifc
].ifname
;
1732 var entry
= self
._get_dev(ifname
);
1734 entry
.kind
= 'wifi';
1737 entry
.wdev
= s
.device
;
1738 entry
.wmode
= s
.mode
;
1739 entry
.wssid
= s
.ssid
;
1740 entry
.wbssid
= s
.bssid
;
1744 for (var i
= 0; i
< net
.length
; i
++)
1747 var sid
= s
['.name'];
1749 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.type
== 'bridge')
1751 var ifnames
= _luci2
.toArray(s
.ifname
);
1753 for (var ifname
in self
._devs
)
1755 var dev
= self
._devs
[ifname
];
1757 if (dev
.kind
!= 'wifi')
1760 var wnets
= _luci2
.toArray(_luci2
.uci
.get('wireless', dev
.sid
, 'network'));
1761 if ($.inArray(sid
, wnets
) > -1)
1762 ifnames
.push(ifname
);
1765 entry
= self
._get_dev('br-%s'.format(s
['.name']));
1767 entry
.kind
= 'bridge';
1769 entry
.ports
= ifnames
.sort();
1774 _parse_interfaces: function()
1776 var self
= _luci2
.NetworkModel
;
1777 var net
= _luci2
.uci
.sections('network');
1779 for (var i
= 0; i
< net
.length
; i
++)
1782 var sid
= s
['.name'];
1784 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.proto
)
1786 var entry
= self
._get_iface(s
['.name']);
1787 var proto
= self
._protos
[s
.proto
] || self
._protos
.none
;
1789 var l3dev
= undefined;
1790 var l2dev
= undefined;
1792 var ifnames
= _luci2
.toArray(s
.ifname
);
1794 for (var ifname
in self
._devs
)
1796 var dev
= self
._devs
[ifname
];
1798 if (dev
.kind
!= 'wifi')
1801 var wnets
= _luci2
.toArray(_luci2
.uci
.get('wireless', dev
.sid
, 'network'));
1802 if ($.inArray(entry
.name
, wnets
) > -1)
1803 ifnames
.push(ifname
);
1807 l3dev
= '%s-%s'.format(s
.proto
, entry
.name
);
1808 else if (s
.type
== 'bridge')
1809 l3dev
= 'br-%s'.format(entry
.name
);
1813 if (!proto
.virtual
&& s
.type
== 'bridge')
1814 l2dev
= 'br-%s'.format(entry
.name
);
1815 else if (!proto
.virtual
)
1818 entry
.proto
= proto
;
1820 entry
.l3dev
= l3dev
;
1821 entry
.l2dev
= l2dev
;
1825 for (var i
= 0; i
< self
._cache
.ifstate
.length
; i
++)
1827 var iface
= self
._cache
.ifstate
[i
];
1828 var entry
= self
._get_iface(iface
['interface']);
1829 var proto
= self
._protos
[iface
.proto
] || self
._protos
.none
;
1831 /* this is a virtual interface, either deleted from config but
1832 not applied yet or set up from external tools (6rd) */
1835 entry
.proto
= proto
;
1836 entry
.l2dev
= iface
.device
;
1837 entry
.l3dev
= iface
.l3_device
;
1847 return _luci2
.deferrable();
1854 return self
._fetch_cache()
1855 .then(self
._fetch_protocols
)
1856 .then(self
._parse_devices
)
1857 .then(self
._parse_interfaces
);
1866 refreshInterfaceStatus: function()
1868 return this._fetch_cache(1).then(this._parse_interfaces
);
1871 refreshDeviceStatus: function()
1873 return this._fetch_cache(2).then(this._parse_devices
);
1876 refreshStatus: function()
1878 return this._fetch_cache(1)
1879 .then(this._fetch_cache(2))
1880 .then(this._parse_devices
)
1881 .then(this._parse_interfaces
);
1884 getDevices: function()
1888 for (var ifname
in this._devs
)
1890 devs
.push(new _luci2
.NetworkModel
.Device(this._devs
[ifname
]));
1892 return devs
.sort(this._sort_devices
);
1895 getDeviceByInterface: function(iface
)
1897 if (iface
instanceof _luci2
.NetworkModel
.Interface
)
1898 iface
= iface
.name();
1900 if (this._ifaces
[iface
])
1901 return this.getDevice(this._ifaces
[iface
].l3dev
) ||
1902 this.getDevice(this._ifaces
[iface
].l2dev
);
1907 getDevice: function(ifname
)
1909 if (this._devs
[ifname
])
1910 return new _luci2
.NetworkModel
.Device(this._devs
[ifname
]);
1915 createDevice: function(name
)
1917 return new _luci2
.NetworkModel
.Device(this._get_dev(name
));
1920 getInterfaces: function()
1924 for (var name
in this._ifaces
)
1925 if (name
!= 'loopback')
1926 ifaces
.push(this.getInterface(name
));
1928 ifaces
.sort(function(a
, b
) {
1929 if (a
.name() < b
.name())
1931 else if (a
.name() > b
.name())
1940 getInterfacesByDevice: function(dev
)
1944 if (dev
instanceof _luci2
.NetworkModel
.Device
)
1947 for (var name
in this._ifaces
)
1949 var iface
= this._ifaces
[name
];
1950 if (iface
.l2dev
== dev
|| iface
.l3dev
== dev
)
1951 ifaces
.push(this.getInterface(name
));
1954 ifaces
.sort(function(a
, b
) {
1955 if (a
.name() < b
.name())
1957 else if (a
.name() > b
.name())
1966 getInterface: function(iface
)
1968 if (this._ifaces
[iface
])
1969 return new _luci2
.NetworkModel
.Interface(this._ifaces
[iface
]);
1974 getProtocols: function()
1978 for (var proto
in this._protos
)
1980 var pr
= this._protos
[proto
];
1984 description
: pr
.description
,
1985 virtual
: pr
.virtual
,
1990 return rv
.sort(function(a
, b
) {
1991 if (a
.name
< b
.name
)
1993 else if (a
.name
> b
.name
)
2000 _find_wan: function(ipaddr
)
2002 for (var i
= 0; i
< this._cache
.ifstate
.length
; i
++)
2004 var ifstate
= this._cache
.ifstate
[i
];
2009 for (var j
= 0; j
< ifstate
.route
.length
; j
++)
2010 if (ifstate
.route
[j
].mask
== 0 &&
2011 ifstate
.route
[j
].target
== ipaddr
&&
2012 typeof(ifstate
.route
[j
].table
) == 'undefined')
2014 return this.getInterface(ifstate
['interface']);
2023 return this._find_wan('0.0.0.0');
2026 findWAN6: function()
2028 return this._find_wan('::');
2031 resolveAlias: function(ifname
)
2033 if (ifname
instanceof _luci2
.NetworkModel
.Device
)
2034 ifname
= ifname
.name();
2036 var dev
= this._devs
[ifname
];
2039 while (dev
&& dev
.kind
== 'alias')
2042 if (seen
[dev
.ifname
])
2045 var ifc
= this._ifaces
[dev
.sid
];
2047 seen
[dev
.ifname
] = true;
2048 dev
= ifc
? this._devs
[ifc
.l3dev
] : undefined;
2051 return dev
? this.getDevice(dev
.ifname
) : undefined;
2055 this.NetworkModel
.Device
= Class
.extend({
2057 ap
: _luci2
.tr('Master'),
2058 sta
: _luci2
.tr('Client'),
2059 adhoc
: _luci2
.tr('Ad-Hoc'),
2060 monitor
: _luci2
.tr('Monitor'),
2061 wds
: _luci2
.tr('Static WDS')
2064 _status: function(key
)
2066 var s
= _luci2
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2069 return key
? s
[key
] : s
;
2076 var sid
= this.options
.sid
;
2077 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2078 return _luci2
.NetworkModel
._get(pkg
, sid
, key
);
2081 set: function(key
, val
)
2083 var sid
= this.options
.sid
;
2084 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2085 return _luci2
.NetworkModel
._set(pkg
, sid
, key
, val
);
2090 if (typeof(this.options
.type
) == 'undefined')
2091 this.options
.type
= 1;
2093 if (typeof(this.options
.kind
) == 'undefined')
2094 this.options
.kind
= 'ethernet';
2096 if (typeof(this.options
.networks
) == 'undefined')
2097 this.options
.networks
= [ ];
2102 return this.options
.ifname
;
2105 description: function()
2107 switch (this.options
.kind
)
2110 return _luci2
.tr('Alias for network "%s"').format(this.options
.ifname
.substring(1));
2113 return _luci2
.tr('Network bridge');
2116 return _luci2
.tr('Network device');
2119 switch (this.options
.type
)
2121 case 1: /* tuntap */
2122 return _luci2
.tr('TAP device');
2125 return _luci2
.tr('PPP tunnel');
2127 case 768: /* IP-IP Tunnel */
2128 return _luci2
.tr('IP-in-IP tunnel');
2130 case 769: /* IP6-IP6 Tunnel */
2131 return _luci2
.tr('IPv6-in-IPv6 tunnel');
2133 case 776: /* IPv6-in-IPv4 */
2134 return _luci2
.tr('IPv6-over-IPv4 tunnel');
2137 case 778: /* GRE over IP */
2138 return _luci2
.tr('GRE-over-IP tunnel');
2141 return _luci2
.tr('Tunnel device');
2145 return _luci2
.tr('VLAN %d on %s').format(this.options
.vid
, this.options
.vsw
.model
);
2148 var o
= this.options
;
2149 return _luci2
.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2150 o
.wmode
? this._wifi_modes
[o
.wmode
] : _luci2
.tr('Unknown mode'),
2151 o
.wssid
|| '?', o
.wdev
2155 return _luci2
.tr('Unknown device');
2160 var kind
= this.options
.kind
;
2162 if (kind
== 'alias')
2165 if (typeof(up
) == 'undefined')
2168 return _luci2
.globals
.resource
+ '/icons/%s%s.png'.format(kind
, up
? '' : '_disabled');
2173 var l
= _luci2
.NetworkModel
._cache
.devlist
;
2175 for (var i
= 0; i
< l
.length
; i
++)
2176 if (l
[i
].device
== this.options
.ifname
)
2177 return (l
[i
].is_up
=== true);
2184 return (this.options
.kind
== 'alias');
2187 isBridge: function()
2189 return (this.options
.kind
== 'bridge');
2192 isBridgeable: function()
2194 return (this.options
.type
== 1 && this.options
.kind
!= 'bridge');
2197 isWireless: function()
2199 return (this.options
.kind
== 'wifi');
2202 isInNetwork: function(net
)
2204 if (!(net
instanceof _luci2
.NetworkModel
.Interface
))
2205 net
= _luci2
.NetworkModel
.getInterface(net
);
2209 if (net
.options
.l3dev
== this.options
.ifname
||
2210 net
.options
.l2dev
== this.options
.ifname
)
2213 var dev
= _luci2
.NetworkModel
._devs
[net
.options
.l2dev
];
2214 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
)
2215 return ($.inArray(this.options
.ifname
, dev
.ports
) > -1);
2223 var dev
= _luci2
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2224 if (dev
&& !isNaN(dev
.mtu
))
2230 getMACAddress: function()
2232 if (this.options
.type
!= 1)
2235 var dev
= _luci2
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2236 if (dev
&& dev
.macaddr
)
2237 return dev
.macaddr
.toUpperCase();
2242 getInterfaces: function()
2244 return _luci2
.NetworkModel
.getInterfacesByDevice(this.options
.name
);
2247 getStatistics: function()
2249 var s
= this._status('statistics') || { };
2251 rx_bytes
: (s
.rx_bytes
|| 0),
2252 tx_bytes
: (s
.tx_bytes
|| 0),
2253 rx_packets
: (s
.rx_packets
|| 0),
2254 tx_packets
: (s
.tx_packets
|| 0)
2258 getTrafficHistory: function()
2260 var def
= new Array(120);
2262 for (var i
= 0; i
< 120; i
++)
2265 var h
= _luci2
.NetworkModel
._cache
.bwstate
[this.options
.ifname
] || { };
2267 rx_bytes
: (h
.rx_bytes
|| def
),
2268 tx_bytes
: (h
.tx_bytes
|| def
),
2269 rx_packets
: (h
.rx_packets
|| def
),
2270 tx_packets
: (h
.tx_packets
|| def
)
2274 removeFromInterface: function(iface
)
2276 if (!(iface
instanceof _luci2
.NetworkModel
.Interface
))
2277 iface
= _luci2
.NetworkModel
.getInterface(iface
);
2282 var ifnames
= _luci2
.toArray(iface
.get('ifname'));
2283 if ($.inArray(this.options
.ifname
, ifnames
) > -1)
2284 iface
.set('ifname', _luci2
.filterArray(ifnames
, this.options
.ifname
));
2286 if (this.options
.kind
!= 'wifi')
2289 var networks
= _luci2
.toArray(this.get('network'));
2290 if ($.inArray(iface
.name(), networks
) > -1)
2291 this.set('network', _luci2
.filterArray(networks
, iface
.name()));
2294 attachToInterface: function(iface
)
2296 if (!(iface
instanceof _luci2
.NetworkModel
.Interface
))
2297 iface
= _luci2
.NetworkModel
.getInterface(iface
);
2302 if (this.options
.kind
!= 'wifi')
2304 var ifnames
= _luci2
.toArray(iface
.get('ifname'));
2305 if ($.inArray(this.options
.ifname
, ifnames
) < 0)
2307 ifnames
.push(this.options
.ifname
);
2308 iface
.set('ifname', (ifnames
.length
> 1) ? ifnames
: ifnames
[0]);
2313 var networks
= _luci2
.toArray(this.get('network'));
2314 if ($.inArray(iface
.name(), networks
) < 0)
2316 networks
.push(iface
.name());
2317 this.set('network', (networks
.length
> 1) ? networks
: networks
[0]);
2323 this.NetworkModel
.Interface
= Class
.extend({
2324 _status: function(key
)
2326 var s
= _luci2
.NetworkModel
._cache
.ifstate
;
2328 for (var i
= 0; i
< s
.length
; i
++)
2329 if (s
[i
]['interface'] == this.options
.name
)
2330 return key
? s
[i
][key
] : s
[i
];
2337 return _luci2
.NetworkModel
._get('network', this.options
.name
, key
);
2340 set: function(key
, val
)
2342 return _luci2
.NetworkModel
._set('network', this.options
.name
, key
, val
);
2347 return this.options
.name
;
2350 protocol: function()
2352 return (this.get('proto') || 'none');
2357 return (this._status('up') === true);
2360 isVirtual: function()
2362 return (typeof(this.options
.sid
) != 'string');
2365 getProtocol: function()
2367 var prname
= this.get('proto') || 'none';
2368 return _luci2
.NetworkModel
._protos
[prname
] || _luci2
.NetworkModel
._protos
.none
;
2371 getUptime: function()
2373 var uptime
= this._status('uptime');
2374 return isNaN(uptime
) ? 0 : uptime
;
2377 getDevice: function(resolveAlias
)
2379 if (this.options
.l3dev
)
2380 return _luci2
.NetworkModel
.getDevice(this.options
.l3dev
);
2385 getPhysdev: function()
2387 if (this.options
.l2dev
)
2388 return _luci2
.NetworkModel
.getDevice(this.options
.l2dev
);
2393 getSubdevices: function()
2396 var dev
= this.options
.l2dev
?
2397 _luci2
.NetworkModel
._devs
[this.options
.l2dev
] : undefined;
2399 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
&& dev
.ports
.length
)
2400 for (var i
= 0; i
< dev
.ports
.length
; i
++)
2401 rv
.push(_luci2
.NetworkModel
.getDevice(dev
.ports
[i
]));
2406 getIPv4Addrs: function(mask
)
2409 var addrs
= this._status('ipv4-address');
2412 for (var i
= 0; i
< addrs
.length
; i
++)
2414 rv
.push(addrs
[i
].address
);
2416 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2421 getIPv6Addrs: function(mask
)
2426 addrs
= this._status('ipv6-address');
2429 for (var i
= 0; i
< addrs
.length
; i
++)
2431 rv
.push(addrs
[i
].address
);
2433 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2435 addrs
= this._status('ipv6-prefix-assignment');
2438 for (var i
= 0; i
< addrs
.length
; i
++)
2440 rv
.push('%s1'.format(addrs
[i
].address
));
2442 rv
.push('%s1/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2447 getDNSAddrs: function()
2450 var addrs
= this._status('dns-server');
2453 for (var i
= 0; i
< addrs
.length
; i
++)
2459 getIPv4DNS: function()
2462 var dns
= this._status('dns-server');
2465 for (var i
= 0; i
< dns
.length
; i
++)
2466 if (dns
[i
].indexOf(':') == -1)
2472 getIPv6DNS: function()
2475 var dns
= this._status('dns-server');
2478 for (var i
= 0; i
< dns
.length
; i
++)
2479 if (dns
[i
].indexOf(':') > -1)
2485 getIPv4Gateway: function()
2487 var rt
= this._status('route');
2490 for (var i
= 0; i
< rt
.length
; i
++)
2491 if (rt
[i
].target
== '0.0.0.0' && rt
[i
].mask
== 0)
2492 return rt
[i
].nexthop
;
2497 getIPv6Gateway: function()
2499 var rt
= this._status('route');
2502 for (var i
= 0; i
< rt
.length
; i
++)
2503 if (rt
[i
].target
== '::' && rt
[i
].mask
== 0)
2504 return rt
[i
].nexthop
;
2509 getStatistics: function()
2511 var dev
= this.getDevice() || new _luci2
.NetworkModel
.Device({});
2512 return dev
.getStatistics();
2515 getTrafficHistory: function()
2517 var dev
= this.getDevice() || new _luci2
.NetworkModel
.Device({});
2518 return dev
.getTrafficHistory();
2521 setDevices: function(devs
)
2523 var dev
= this.getPhysdev();
2525 var changed
= false;
2527 if (dev
&& dev
.isBridge())
2528 old_devs
= this.getSubdevices();
2532 if (old_devs
.length
!= devs
.length
)
2535 for (var i
= 0; i
< old_devs
.length
; i
++)
2539 if (dev
instanceof _luci2
.NetworkModel
.Device
)
2542 if (!dev
|| old_devs
[i
].name() != dev
)
2551 for (var i
= 0; i
< old_devs
.length
; i
++)
2552 old_devs
[i
].removeFromInterface(this);
2554 for (var i
= 0; i
< devs
.length
; i
++)
2558 if (!(dev
instanceof _luci2
.NetworkModel
.Device
))
2559 dev
= _luci2
.NetworkModel
.getDevice(dev
);
2562 dev
.attachToInterface(this);
2567 changeProtocol: function(proto
)
2569 var pr
= _luci2
.NetworkModel
._protos
[proto
];
2574 for (var opt
in (this.get() || { }))
2582 this.set(opt
, undefined);
2590 this.set(opt
, pr
.protocol
);
2594 this.set(opt
, undefined);
2600 createForm: function(mapwidget
)
2603 var proto
= self
.getProtocol();
2604 var device
= self
.getDevice();
2607 mapwidget
= _luci2
.cbi
.Map
;
2609 var map
= new mapwidget('network', {
2610 caption
: _luci2
.tr('Configure "%s"').format(self
.name())
2613 var section
= map
.section(_luci2
.cbi
.SingleSection
, self
.name(), {
2619 caption
: _luci2
.tr('General Settings')
2624 caption
: _luci2
.tr('Advanced Settings')
2629 caption
: _luci2
.tr('IPv6')
2634 caption
: _luci2
.tr('Physical Settings')
2638 section
.taboption('general', _luci2
.cbi
.CheckboxValue
, 'auto', {
2639 caption
: _luci2
.tr('Start on boot'),
2644 var pr
= section
.taboption('general', _luci2
.cbi
.ListValue
, 'proto', {
2645 caption
: _luci2
.tr('Protocol')
2648 pr
.ucivalue = function(sid
) {
2649 return self
.get('proto') || 'none';
2652 var ok
= section
.taboption('general', _luci2
.cbi
.ButtonValue
, '_confirm', {
2653 caption
: _luci2
.tr('Really switch?'),
2654 description
: _luci2
.tr('Changing the protocol will clear all configuration for this interface!'),
2655 text
: _luci2
.tr('Change protocol')
2658 ok
.on('click', function(ev
) {
2659 self
.changeProtocol(pr
.formvalue(ev
.data
.sid
));
2660 self
.createForm(mapwidget
).show();
2663 var protos
= _luci2
.NetworkModel
.getProtocols();
2665 for (var i
= 0; i
< protos
.length
; i
++)
2666 pr
.value(protos
[i
].name
, protos
[i
].description
);
2668 proto
.populateForm(section
, self
);
2672 var br
= section
.taboption('physical', _luci2
.cbi
.CheckboxValue
, 'type', {
2673 caption
: _luci2
.tr('Network bridge'),
2674 description
: _luci2
.tr('Merges multiple devices into one logical bridge'),
2681 section
.taboption('physical', _luci2
.cbi
.DeviceList
, '__iface_multi', {
2682 caption
: _luci2
.tr('Devices'),
2685 }).depends('type', true);
2687 section
.taboption('physical', _luci2
.cbi
.DeviceList
, '__iface_single', {
2688 caption
: _luci2
.tr('Device'),
2691 }).depends('type', false);
2693 var mac
= section
.taboption('physical', _luci2
.cbi
.InputValue
, 'macaddr', {
2694 caption
: _luci2
.tr('Override MAC'),
2696 placeholder
: device
? device
.getMACAddress() : undefined,
2700 mac
.ucivalue = function(sid
)
2703 return device
.get('macaddr');
2705 return this.callSuper('ucivalue', sid
);
2708 mac
.save = function(sid
)
2710 if (!this.changed(sid
))
2714 device
.set('macaddr', this.formvalue(sid
));
2716 this.callSuper('set', sid
);
2722 section
.taboption('physical', _luci2
.cbi
.InputValue
, 'mtu', {
2723 caption
: _luci2
.tr('Override MTU'),
2725 placeholder
: device
? device
.getMTU() : undefined,
2726 datatype
: 'range(1, 9000)'
2729 section
.taboption('physical', _luci2
.cbi
.InputValue
, 'metric', {
2730 caption
: _luci2
.tr('Override Metric'),
2733 datatype
: 'uinteger'
2736 for (var field
in section
.fields
)
2744 for (var i
= 0; i
< protos
.length
; i
++)
2745 if (protos
[i
].name
!= (this.get('proto') || 'none'))
2746 section
.fields
[field
].depends('proto', protos
[i
].name
);
2750 section
.fields
[field
].depends('proto', this.get('proto') || 'none', true);
2759 this.NetworkModel
.Protocol
= this.NetworkModel
.Interface
.extend({
2760 description
: '__unknown__',
2764 populateForm: function(section
, iface
)
2771 getSystemInfo
: _luci2
.rpc
.declare({
2777 getBoardInfo
: _luci2
.rpc
.declare({
2783 getDiskInfo
: _luci2
.rpc
.declare({
2784 object
: 'luci2.system',
2789 getInfo: function(cb
)
2793 this.getSystemInfo();
2794 this.getBoardInfo();
2797 return _luci2
.rpc
.flush().then(function(info
) {
2800 $.extend(rv
, info
[0]);
2801 $.extend(rv
, info
[1]);
2802 $.extend(rv
, info
[2]);
2808 getProcessList
: _luci2
.rpc
.declare({
2809 object
: 'luci2.system',
2810 method
: 'process_list',
2811 expect
: { processes
: [ ] },
2812 filter: function(data
) {
2813 data
.sort(function(a
, b
) { return a
.pid
- b
.pid
});
2818 getSystemLog
: _luci2
.rpc
.declare({
2819 object
: 'luci2.system',
2824 getKernelLog
: _luci2
.rpc
.declare({
2825 object
: 'luci2.system',
2830 getZoneInfo: function(cb
)
2832 return $.getJSON(_luci2
.globals
.resource
+ '/zoneinfo.json', cb
);
2835 sendSignal
: _luci2
.rpc
.declare({
2836 object
: 'luci2.system',
2837 method
: 'process_signal',
2838 params
: [ 'pid', 'signal' ],
2839 filter: function(data
) {
2844 initList
: _luci2
.rpc
.declare({
2845 object
: 'luci2.system',
2846 method
: 'init_list',
2847 expect
: { initscripts
: [ ] },
2848 filter: function(data
) {
2849 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
2854 initEnabled: function(init
, cb
)
2856 return this.initList().then(function(list
) {
2857 for (var i
= 0; i
< list
.length
; i
++)
2858 if (list
[i
].name
== init
)
2859 return !!list
[i
].enabled
;
2865 initRun
: _luci2
.rpc
.declare({
2866 object
: 'luci2.system',
2867 method
: 'init_action',
2868 params
: [ 'name', 'action' ],
2869 filter: function(data
) {
2874 initStart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'start', cb
) },
2875 initStop: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'stop', cb
) },
2876 initRestart: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'restart', cb
) },
2877 initReload: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'reload', cb
) },
2878 initEnable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'enable', cb
) },
2879 initDisable: function(init
, cb
) { return _luci2
.system
.initRun(init
, 'disable', cb
) },
2882 getRcLocal
: _luci2
.rpc
.declare({
2883 object
: 'luci2.system',
2884 method
: 'rclocal_get',
2885 expect
: { data
: '' }
2888 setRcLocal
: _luci2
.rpc
.declare({
2889 object
: 'luci2.system',
2890 method
: 'rclocal_set',
2895 getCrontab
: _luci2
.rpc
.declare({
2896 object
: 'luci2.system',
2897 method
: 'crontab_get',
2898 expect
: { data
: '' }
2901 setCrontab
: _luci2
.rpc
.declare({
2902 object
: 'luci2.system',
2903 method
: 'crontab_set',
2908 getSSHKeys
: _luci2
.rpc
.declare({
2909 object
: 'luci2.system',
2910 method
: 'sshkeys_get',
2911 expect
: { keys
: [ ] }
2914 setSSHKeys
: _luci2
.rpc
.declare({
2915 object
: 'luci2.system',
2916 method
: 'sshkeys_set',
2921 setPassword
: _luci2
.rpc
.declare({
2922 object
: 'luci2.system',
2923 method
: 'password_set',
2924 params
: [ 'user', 'password' ]
2928 listLEDs
: _luci2
.rpc
.declare({
2929 object
: 'luci2.system',
2931 expect
: { leds
: [ ] }
2934 listUSBDevices
: _luci2
.rpc
.declare({
2935 object
: 'luci2.system',
2937 expect
: { devices
: [ ] }
2941 testUpgrade
: _luci2
.rpc
.declare({
2942 object
: 'luci2.system',
2943 method
: 'upgrade_test',
2947 startUpgrade
: _luci2
.rpc
.declare({
2948 object
: 'luci2.system',
2949 method
: 'upgrade_start',
2953 cleanUpgrade
: _luci2
.rpc
.declare({
2954 object
: 'luci2.system',
2955 method
: 'upgrade_clean'
2959 restoreBackup
: _luci2
.rpc
.declare({
2960 object
: 'luci2.system',
2961 method
: 'backup_restore'
2964 cleanBackup
: _luci2
.rpc
.declare({
2965 object
: 'luci2.system',
2966 method
: 'backup_clean'
2970 getBackupConfig
: _luci2
.rpc
.declare({
2971 object
: 'luci2.system',
2972 method
: 'backup_config_get',
2973 expect
: { config
: '' }
2976 setBackupConfig
: _luci2
.rpc
.declare({
2977 object
: 'luci2.system',
2978 method
: 'backup_config_set',
2983 listBackup
: _luci2
.rpc
.declare({
2984 object
: 'luci2.system',
2985 method
: 'backup_list',
2986 expect
: { files
: [ ] }
2990 testReset
: _luci2
.rpc
.declare({
2991 object
: 'luci2.system',
2992 method
: 'reset_test',
2993 expect
: { supported
: false }
2996 startReset
: _luci2
.rpc
.declare({
2997 object
: 'luci2.system',
2998 method
: 'reset_start'
3002 performReboot
: _luci2
.rpc
.declare({
3003 object
: 'luci2.system',
3009 updateLists
: _luci2
.rpc
.declare({
3010 object
: 'luci2.opkg',
3015 _allPackages
: _luci2
.rpc
.declare({
3016 object
: 'luci2.opkg',
3018 params
: [ 'offset', 'limit', 'pattern' ],
3022 _installedPackages
: _luci2
.rpc
.declare({
3023 object
: 'luci2.opkg',
3024 method
: 'list_installed',
3025 params
: [ 'offset', 'limit', 'pattern' ],
3029 _findPackages
: _luci2
.rpc
.declare({
3030 object
: 'luci2.opkg',
3032 params
: [ 'offset', 'limit', 'pattern' ],
3036 _fetchPackages: function(action
, offset
, limit
, pattern
)
3040 return action(offset
, limit
, pattern
).then(function(list
) {
3041 if (!list
.total
|| !list
.packages
)
3042 return { length
: 0, total
: 0 };
3044 packages
.push
.apply(packages
, list
.packages
);
3045 packages
.total
= list
.total
;
3050 if (packages
.length
>= limit
)
3055 for (var i
= offset
+ packages
.length
; i
< limit
; i
+= 100)
3056 action(i
, (Math
.min(i
+ 100, limit
) % 100) || 100, pattern
);
3058 return _luci2
.rpc
.flush();
3059 }).then(function(lists
) {
3060 for (var i
= 0; i
< lists
.length
; i
++)
3062 if (!lists
[i
].total
|| !lists
[i
].packages
)
3065 packages
.push
.apply(packages
, lists
[i
].packages
);
3066 packages
.total
= lists
[i
].total
;
3073 listPackages: function(offset
, limit
, pattern
)
3075 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._allPackages
, offset
, limit
, pattern
);
3078 installedPackages: function(offset
, limit
, pattern
)
3080 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._installedPackages
, offset
, limit
, pattern
);
3083 findPackages: function(offset
, limit
, pattern
)
3085 return _luci2
.opkg
._fetchPackages(_luci2
.opkg
._findPackages
, offset
, limit
, pattern
);
3088 installPackage
: _luci2
.rpc
.declare({
3089 object
: 'luci2.opkg',
3091 params
: [ 'package' ],
3095 removePackage
: _luci2
.rpc
.declare({
3096 object
: 'luci2.opkg',
3098 params
: [ 'package' ],
3102 getConfig
: _luci2
.rpc
.declare({
3103 object
: 'luci2.opkg',
3104 method
: 'config_get',
3105 expect
: { config
: '' }
3108 setConfig
: _luci2
.rpc
.declare({
3109 object
: 'luci2.opkg',
3110 method
: 'config_set',
3117 login
: _luci2
.rpc
.declare({
3120 params
: [ 'username', 'password' ],
3124 access
: _luci2
.rpc
.declare({
3127 params
: [ 'scope', 'object', 'function' ],
3128 expect
: { access
: false }
3133 return _luci2
.session
.access('ubus', 'session', 'access');
3136 startHeartbeat: function()
3138 this._hearbeatInterval
= window
.setInterval(function() {
3139 _luci2
.session
.isAlive().then(function(alive
) {
3142 _luci2
.session
.stopHeartbeat();
3143 _luci2
.ui
.login(true);
3147 }, _luci2
.globals
.timeout
* 2);
3150 stopHeartbeat: function()
3152 if (typeof(this._hearbeatInterval
) != 'undefined')
3154 window
.clearInterval(this._hearbeatInterval
);
3155 delete this._hearbeatInterval
;
3162 _fetch_acls
: _luci2
.rpc
.declare({
3168 _fetch_acls_cb: function(acls
)
3170 _luci2
.session
._acls
= acls
;
3173 updateACLs: function()
3175 return _luci2
.session
._fetch_acls()
3176 .then(_luci2
.session
._fetch_acls_cb
);
3179 hasACL: function(scope
, object
, func
)
3181 var acls
= _luci2
.session
._acls
;
3183 if (typeof(func
) == 'undefined')
3184 return (acls
&& acls
[scope
] && acls
[scope
][object
]);
3186 if (acls
&& acls
[scope
] && acls
[scope
][object
])
3187 for (var i
= 0; i
< acls
[scope
][object
].length
; i
++)
3188 if (acls
[scope
][object
][i
] == func
)
3197 saveScrollTop: function()
3199 this._scroll_top
= $(document
).scrollTop();
3202 restoreScrollTop: function()
3204 if (typeof(this._scroll_top
) == 'undefined')
3207 $(document
).scrollTop(this._scroll_top
);
3209 delete this._scroll_top
;
3212 loading: function(enable
)
3214 var win
= $(window
);
3215 var body
= $('body');
3217 var state
= _luci2
.ui
._loading
|| (_luci2
.ui
._loading
= {
3219 .css('z-index', 2000)
3220 .addClass('modal fade')
3221 .append($('<div />')
3222 .addClass('modal-dialog')
3223 .append($('<div />')
3224 .addClass('modal-content luci2-modal-loader')
3225 .append($('<div />')
3226 .addClass('modal-body')
3227 .text(_luci2
.tr('Loading data…')))))
3235 state
.modal
.modal(enable
? 'show' : 'hide');
3238 dialog: function(title
, content
, options
)
3240 var win
= $(window
);
3241 var body
= $('body');
3243 var state
= _luci2
.ui
._dialog
|| (_luci2
.ui
._dialog
= {
3244 dialog
: $('<div />')
3245 .addClass('modal fade')
3246 .append($('<div />')
3247 .addClass('modal-dialog')
3248 .append($('<div />')
3249 .addClass('modal-content')
3250 .append($('<div />')
3251 .addClass('modal-header')
3253 .addClass('modal-title'))
3254 .append($('<div />')
3255 .addClass('modal-body'))
3256 .append($('<div />')
3257 .addClass('modal-footer')
3258 .append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
3260 $(this).parents('div.modal').modal('hide');
3265 if (typeof(options
) != 'object')
3268 if (title
=== false)
3270 state
.dialog
.modal('hide');
3272 return state
.dialog
;
3275 var cnt
= state
.dialog
.children().children().children('div.modal-body');
3276 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
3280 if (options
.style
== 'confirm')
3282 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Ok'), 'primary')
3283 .click(options
.confirm
|| function() { _luci2
.ui
.dialog(false) }));
3285 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Cancel'), 'default')
3286 .click(options
.cancel
|| function() { _luci2
.ui
.dialog(false) }));
3288 else if (options
.style
== 'close')
3290 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
3291 .click(options
.close
|| function() { _luci2
.ui
.dialog(false) }));
3293 else if (options
.style
== 'wait')
3295 ftr
.append(_luci2
.ui
.button(_luci2
.tr('Close'), 'primary')
3296 .attr('disabled', true));
3301 state
.dialog
.addClass('wide');
3305 state
.dialog
.removeClass('wide');
3308 state
.dialog
.find('h4:first').text(title
);
3309 state
.dialog
.modal('show');
3311 cnt
.empty().append(content
);
3313 return state
.dialog
;
3316 upload: function(title
, content
, options
)
3318 var state
= _luci2
.ui
._upload
|| (_luci2
.ui
._upload
= {
3320 .attr('method', 'post')
3321 .attr('action', '/cgi-bin/luci-upload')
3322 .attr('enctype', 'multipart/form-data')
3323 .attr('target', 'cbi-fileupload-frame')
3325 .append($('<input />')
3326 .attr('type', 'hidden')
3327 .attr('name', 'sessionid'))
3328 .append($('<input />')
3329 .attr('type', 'hidden')
3330 .attr('name', 'filename'))
3331 .append($('<input />')
3332 .attr('type', 'file')
3333 .attr('name', 'filedata')
3334 .addClass('cbi-input-file'))
3335 .append($('<div />')
3336 .css('width', '100%')
3337 .addClass('progress progress-striped active')
3338 .append($('<div />')
3339 .addClass('progress-bar')
3340 .css('width', '100%')))
3341 .append($('<iframe />')
3342 .addClass('pull-right')
3343 .attr('name', 'cbi-fileupload-frame')
3344 .css('width', '1px')
3345 .css('height', '1px')
3346 .css('visibility', 'hidden')),
3348 finish_cb: function(ev
) {
3349 $(this).off('load');
3351 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
3352 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
3353 body
= body
.firstChild
;
3357 json
= $.parseJSON(body
.innerHTML
);
3360 message
: _luci2
.tr('Invalid server response received'),
3361 error
: [ -1, _luci2
.tr('Invalid data') ]
3367 L
.ui
.dialog(L
.tr('File upload'), [
3368 $('<p />').text(_luci2
.tr('The file upload failed with the server response below:')),
3369 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
3370 $('<p />').text(_luci2
.tr('In case of network problems try uploading the file again.'))
3371 ], { style
: 'close' });
3373 else if (typeof(state
.success_cb
) == 'function')
3375 state
.success_cb(json
);
3379 confirm_cb: function() {
3380 var f
= state
.form
.find('.cbi-input-file');
3381 var b
= state
.form
.find('.progress');
3382 var p
= state
.form
.find('p');
3387 state
.form
.find('iframe').on('load', state
.finish_cb
);
3388 state
.form
.submit();
3392 p
.text(_luci2
.tr('File upload in progress …'));
3394 state
.form
.parent().parent().find('button').prop('disabled', true);
3398 state
.form
.find('.progress').hide();
3399 state
.form
.find('.cbi-input-file').val('').show();
3400 state
.form
.find('p').text(content
|| _luci2
.tr('Select the file to upload and press "%s" to proceed.').format(_luci2
.tr('Ok')));
3402 state
.form
.find('[name=sessionid]').val(_luci2
.globals
.sid
);
3403 state
.form
.find('[name=filename]').val(options
.filename
);
3405 state
.success_cb
= options
.success
;
3407 _luci2
.ui
.dialog(title
|| _luci2
.tr('File upload'), state
.form
, {
3409 confirm
: state
.confirm_cb
3413 reconnect: function()
3415 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3416 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
3417 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
3419 var interval
, timeout
;
3422 _luci2
.tr('Waiting for device'), [
3423 $('<p />').text(_luci2
.tr('Please stand by while the device is reconfiguring …')),
3425 .css('width', '100%')
3426 .addClass('progressbar')
3427 .addClass('intermediate')
3428 .append($('<div />')
3429 .css('width', '100%'))
3430 ], { style
: 'wait' }
3433 for (var i
= 0; i
< protocols
.length
; i
++)
3434 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
3436 //_luci2.network.getNetworkStatus(function(s) {
3437 // for (var i = 0; i < protocols.length; i++)
3439 // for (var j = 0; j < s.length; j++)
3441 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3442 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3444 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3445 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3448 //}).then(function() {
3449 images
.on('load', function() {
3450 var url
= this.getAttribute('url');
3451 _luci2
.session
.isAlive().then(function(access
) {
3454 window
.clearTimeout(timeout
);
3455 window
.clearInterval(interval
);
3456 _luci2
.ui
.dialog(false);
3461 location
.href
= url
;
3466 interval
= window
.setInterval(function() {
3467 images
.each(function() {
3468 this.setAttribute('src', this.getAttribute('url') + _luci2
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
3472 timeout
= window
.setTimeout(function() {
3473 window
.clearInterval(interval
);
3477 _luci2
.tr('Device not responding'),
3478 _luci2
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3485 login: function(invalid
)
3487 var state
= _luci2
.ui
._login
|| (_luci2
.ui
._login
= {
3490 .attr('method', 'post')
3492 .addClass('alert-message')
3493 .text(_luci2
.tr('Wrong username or password given!')))
3495 .append($('<label />')
3496 .text(_luci2
.tr('Username'))
3497 .append($('<br />'))
3498 .append($('<input />')
3499 .attr('type', 'text')
3500 .attr('name', 'username')
3501 .attr('value', 'root')
3502 .addClass('form-control')
3503 .keypress(function(ev
) {
3504 if (ev
.which
== 10 || ev
.which
== 13)
3508 .append($('<label />')
3509 .text(_luci2
.tr('Password'))
3510 .append($('<br />'))
3511 .append($('<input />')
3512 .attr('type', 'password')
3513 .attr('name', 'password')
3514 .addClass('form-control')
3515 .keypress(function(ev
) {
3516 if (ev
.which
== 10 || ev
.which
== 13)
3520 .text(_luci2
.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2
.tr('Ok')))),
3522 response_cb: function(response
) {
3523 if (!response
.ubus_rpc_session
)
3525 _luci2
.ui
.login(true);
3529 _luci2
.globals
.sid
= response
.ubus_rpc_session
;
3530 _luci2
.setHash('id', _luci2
.globals
.sid
);
3531 _luci2
.session
.startHeartbeat();
3532 _luci2
.ui
.dialog(false);
3533 state
.deferred
.resolve();
3537 confirm_cb: function() {
3538 var u
= state
.form
.find('[name=username]').val();
3539 var p
= state
.form
.find('[name=password]').val();
3545 _luci2
.tr('Logging in'), [
3546 $('<p />').text(_luci2
.tr('Log in in progress …')),
3548 .css('width', '100%')
3549 .addClass('progressbar')
3550 .addClass('intermediate')
3551 .append($('<div />')
3552 .css('width', '100%'))
3553 ], { style
: 'wait' }
3556 _luci2
.globals
.sid
= '00000000000000000000000000000000';
3557 _luci2
.session
.login(u
, p
).then(state
.response_cb
);
3561 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
3562 state
.deferred
= $.Deferred();
3564 /* try to find sid from hash */
3565 var sid
= _luci2
.getHash('id');
3566 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
3568 _luci2
.globals
.sid
= sid
;
3569 _luci2
.session
.isAlive().then(function(access
) {
3572 _luci2
.session
.startHeartbeat();
3573 state
.deferred
.resolve();
3577 _luci2
.setHash('id', undefined);
3582 return state
.deferred
;
3586 state
.form
.find('.alert-message').show();
3588 state
.form
.find('.alert-message').hide();
3590 _luci2
.ui
.dialog(_luci2
.tr('Authorization Required'), state
.form
, {
3592 confirm
: state
.confirm_cb
3595 state
.form
.find('[name=password]').focus();
3597 return state
.deferred
;
3600 cryptPassword
: _luci2
.rpc
.declare({
3604 expect
: { crypt
: '' }
3608 _acl_merge_scope: function(acl_scope
, scope
)
3610 if ($.isArray(scope
))
3612 for (var i
= 0; i
< scope
.length
; i
++)
3613 acl_scope
[scope
[i
]] = true;
3615 else if ($.isPlainObject(scope
))
3617 for (var object_name
in scope
)
3619 if (!$.isArray(scope
[object_name
]))
3622 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
3624 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
3625 acl_object
[scope
[object_name
][i
]] = true;
3630 _acl_merge_permission: function(acl_perm
, perm
)
3632 if ($.isPlainObject(perm
))
3634 for (var scope_name
in perm
)
3636 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
3637 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
3642 _acl_merge_group: function(acl_group
, group
)
3644 if ($.isPlainObject(group
))
3646 if (!acl_group
.description
)
3647 acl_group
.description
= group
.description
;
3651 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
3652 this._acl_merge_permission(acl_perm
, group
.read
);
3657 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
3658 this._acl_merge_permission(acl_perm
, group
.write
);
3663 _acl_merge_tree: function(acl_tree
, tree
)
3665 if ($.isPlainObject(tree
))
3667 for (var group_name
in tree
)
3669 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
3670 this._acl_merge_group(acl_group
, tree
[group_name
]);
3675 listAvailableACLs
: _luci2
.rpc
.declare({
3678 expect
: { acls
: [ ] },
3679 filter: function(trees
) {
3681 for (var i
= 0; i
< trees
.length
; i
++)
3682 _luci2
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
3687 renderMainMenu
: _luci2
.rpc
.declare({
3690 expect
: { menu
: { } },
3691 filter: function(entries
) {
3692 _luci2
.globals
.mainMenu
= new _luci2
.ui
.menu();
3693 _luci2
.globals
.mainMenu
.entries(entries
);
3697 .append(_luci2
.globals
.mainMenu
.render(0, 1));
3701 renderViewMenu: function()
3705 .append(_luci2
.globals
.mainMenu
.render(2, 900));
3708 renderView: function()
3710 var node
= arguments
[0];
3711 var name
= node
.view
.split(/\//).join('.');
3714 for (var i
= 1; i
< arguments
.length
; i
++)
3715 args
.push(arguments
[i
]);
3717 if (_luci2
.globals
.currentView
)
3718 _luci2
.globals
.currentView
.finish();
3720 _luci2
.ui
.renderViewMenu();
3723 _luci2
._views
= { };
3725 _luci2
.setHash('view', node
.view
);
3727 if (_luci2
._views
[name
] instanceof _luci2
.ui
.view
)
3729 _luci2
.globals
.currentView
= _luci2
._views
[name
];
3730 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
3733 var url
= _luci2
.globals
.resource
+ '/view/' + name
+ '.js';
3735 return $.ajax(url
, {
3739 }).then(function(data
) {
3741 var viewConstructorSource
= (
3742 '(function(L, $) { ' +
3744 '})(_luci2, $);\n\n' +
3746 ).format(data
, url
);
3748 var viewConstructor
= eval(viewConstructorSource
);
3750 _luci2
._views
[name
] = new viewConstructor({
3752 acls
: node
.write
|| { }
3755 _luci2
.globals
.currentView
= _luci2
._views
[name
];
3756 return _luci2
._views
[name
].render
.apply(_luci2
._views
[name
], args
);
3759 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
3762 return $.Deferred().resolve();
3766 changeView: function()
3768 var name
= _luci2
.getHash('view');
3769 var node
= _luci2
.globals
.defaultNode
;
3771 if (name
&& _luci2
.globals
.mainMenu
)
3772 node
= _luci2
.globals
.mainMenu
.getNode(name
);
3776 _luci2
.ui
.loading(true);
3777 _luci2
.ui
.renderView(node
).then(function() {
3778 _luci2
.ui
.loading(false);
3783 updateHostname: function()
3785 return _luci2
.system
.getBoardInfo().then(function(info
) {
3787 $('#hostname').text(info
.hostname
);
3791 updateChanges: function()
3793 return _luci2
.uci
.changes().then(function(changes
) {
3797 for (var config
in changes
)
3801 for (var i
= 0; i
< changes
[config
].length
; i
++)
3803 var c
= changes
[config
][i
];
3808 log
.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3813 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
3815 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
3820 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
3822 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3826 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
3830 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3834 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3839 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3841 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3846 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
3847 n
+= changes
[config
].length
;
3858 .text(_luci2
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
))
3859 .click(function(ev
) {
3860 _luci2
.ui
.dialog(_luci2
.tr('Staged configuration changes'), html
, { style
: 'close' });
3861 ev
.preventDefault();
3871 _luci2
.ui
.loading(true);
3874 _luci2
.session
.updateACLs(),
3875 _luci2
.ui
.updateHostname(),
3876 _luci2
.ui
.updateChanges(),
3877 _luci2
.ui
.renderMainMenu(),
3878 _luci2
.NetworkModel
.init()
3880 _luci2
.ui
.renderView(_luci2
.globals
.defaultNode
).then(function() {
3881 _luci2
.ui
.loading(false);
3884 $(window
).on('hashchange', function() {
3885 _luci2
.ui
.changeView();
3890 button: function(label
, style
, title
)
3892 style
= style
|| 'default';
3894 return $('<button />')
3895 .attr('type', 'button')
3896 .attr('title', title
? title
: '')
3897 .addClass('btn btn-' + style
)
3902 this.ui
.AbstractWidget
= Class
.extend({
3903 i18n: function(text
) {
3908 var key
= arguments
[0];
3911 for (var i
= 1; i
< arguments
.length
; i
++)
3912 args
.push(arguments
[i
]);
3914 switch (typeof(this.options
[key
]))
3920 return this.options
[key
].apply(this, args
);
3923 return ''.format
.apply('' + this.options
[key
], args
);
3927 toString: function() {
3928 return $('<div />').append(this.render()).html();
3931 insertInto: function(id
) {
3932 return $(id
).empty().append(this.render());
3935 appendTo: function(id
) {
3936 return $(id
).append(this.render());
3940 this.ui
.view
= this.ui
.AbstractWidget
.extend({
3941 _fetch_template: function()
3943 return $.ajax(_luci2
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
3947 success: function(data
) {
3948 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
3949 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
3956 return _luci2
.tr(p2
);
3959 return _luci2
.globals
[p2
] || '';
3962 return '(?' + match
+ ')';
3966 $('#maincontent').append(data
);
3973 throw "Not implemented";
3978 var container
= $('#maincontent');
3983 container
.append($('<h2 />').append(this.title
));
3985 if (this.description
)
3986 container
.append($('<p />').append(this.description
));
3991 for (var i
= 0; i
< arguments
.length
; i
++)
3992 args
.push(arguments
[i
]);
3994 return this._fetch_template().then(function() {
3995 return _luci2
.deferrable(self
.execute
.apply(self
, args
));
3999 repeat: function(func
, interval
)
4003 if (!self
._timeouts
)
4004 self
._timeouts
= [ ];
4006 var index
= self
._timeouts
.length
;
4008 if (typeof(interval
) != 'number')
4011 var setTimer
, runTimer
;
4013 setTimer = function() {
4015 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
4018 runTimer = function() {
4019 _luci2
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
4027 if ($.isArray(this._timeouts
))
4029 for (var i
= 0; i
< this._timeouts
.length
; i
++)
4030 window
.clearTimeout(this._timeouts
[i
]);
4032 delete this._timeouts
;
4037 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
4042 entries: function(entries
)
4044 for (var entry
in entries
)
4046 var path
= entry
.split(/\//);
4047 var node
= this._nodes
;
4049 for (i
= 0; i
< path
.length
; i
++)
4054 if (!node
.childs
[path
[i
]])
4055 node
.childs
[path
[i
]] = { };
4057 node
= node
.childs
[path
[i
]];
4060 $.extend(node
, entries
[entry
]);
4064 _indexcmp: function(a
, b
)
4066 var x
= a
.index
|| 0;
4067 var y
= b
.index
|| 0;
4071 firstChildView: function(node
)
4077 for (var child
in (node
.childs
|| { }))
4078 nodes
.push(node
.childs
[child
]);
4080 nodes
.sort(this._indexcmp
);
4082 for (var i
= 0; i
< nodes
.length
; i
++)
4084 var child
= this.firstChildView(nodes
[i
]);
4087 for (var key
in child
)
4088 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
4089 node
[key
] = child
[key
];
4098 _onclick: function(ev
)
4100 _luci2
.setHash('view', ev
.data
);
4102 ev
.preventDefault();
4106 _render: function(childs
, level
, min
, max
)
4109 for (var node
in childs
)
4111 var child
= this.firstChildView(childs
[node
]);
4113 nodes
.push(childs
[node
]);
4116 nodes
.sort(this._indexcmp
);
4118 var list
= $('<ul />');
4121 list
.addClass('nav').addClass('navbar-nav');
4122 else if (level
== 1)
4123 list
.addClass('dropdown-menu').addClass('navbar-inverse');
4125 for (var i
= 0; i
< nodes
.length
; i
++)
4127 if (!_luci2
.globals
.defaultNode
)
4129 var v
= _luci2
.getHash('view');
4130 if (!v
|| v
== nodes
[i
].view
)
4131 _luci2
.globals
.defaultNode
= nodes
[i
];
4134 var item
= $('<li />')
4137 .text(_luci2
.tr(nodes
[i
].title
)))
4140 if (nodes
[i
].childs
&& level
< max
)
4142 item
.addClass('dropdown');
4145 .addClass('dropdown-toggle')
4146 .attr('data-toggle', 'dropdown')
4147 .append('<b class="caret"></b>');
4149 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
4153 item
.find('a').click(nodes
[i
].view
, this._onclick
);
4160 render: function(min
, max
)
4162 var top
= min
? this.getNode(_luci2
.globals
.defaultNode
.view
, min
) : this._nodes
;
4163 return this._render(top
.childs
, 0, min
, max
);
4166 getNode: function(path
, max
)
4168 var p
= path
.split(/\//);
4169 var n
= this._nodes
;
4171 if (typeof(max
) == 'undefined')
4174 for (var i
= 0; i
< max
; i
++)
4176 if (!n
.childs
[p
[i
]])
4186 this.ui
.table
= this.ui
.AbstractWidget
.extend({
4192 row: function(values
)
4194 if ($.isArray(values
))
4196 this._rows
.push(values
);
4198 else if ($.isPlainObject(values
))
4201 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4203 var col
= this.options
.columns
[i
];
4205 if (typeof col
.key
== 'string')
4206 v
.push(values
[col
.key
]);
4214 rows: function(rows
)
4216 for (var i
= 0; i
< rows
.length
; i
++)
4220 render: function(id
)
4222 var fieldset
= document
.createElement('fieldset');
4223 fieldset
.className
= 'cbi-section';
4225 if (this.options
.caption
)
4227 var legend
= document
.createElement('legend');
4228 $(legend
).append(this.options
.caption
);
4229 fieldset
.appendChild(legend
);
4232 var table
= document
.createElement('table');
4233 table
.className
= 'table table-condensed table-hover';
4235 var has_caption
= false;
4236 var has_description
= false;
4238 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4239 if (this.options
.columns
[i
].caption
)
4244 else if (this.options
.columns
[i
].description
)
4246 has_description
= true;
4252 var tr
= table
.insertRow(-1);
4253 tr
.className
= 'cbi-section-table-titles';
4255 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4257 var col
= this.options
.columns
[i
];
4258 var th
= document
.createElement('th');
4259 th
.className
= 'cbi-section-table-cell';
4264 th
.style
.width
= col
.width
;
4267 th
.style
.textAlign
= col
.align
;
4270 $(th
).append(col
.caption
);
4274 if (has_description
)
4276 var tr
= table
.insertRow(-1);
4277 tr
.className
= 'cbi-section-table-descr';
4279 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4281 var col
= this.options
.columns
[i
];
4282 var th
= document
.createElement('th');
4283 th
.className
= 'cbi-section-table-cell';
4288 th
.style
.width
= col
.width
;
4291 th
.style
.textAlign
= col
.align
;
4293 if (col
.description
)
4294 $(th
).append(col
.description
);
4298 if (this._rows
.length
== 0)
4300 if (this.options
.placeholder
)
4302 var tr
= table
.insertRow(-1);
4303 var td
= tr
.insertCell(-1);
4304 td
.className
= 'cbi-section-table-cell';
4306 td
.colSpan
= this.options
.columns
.length
;
4307 $(td
).append(this.options
.placeholder
);
4312 for (var i
= 0; i
< this._rows
.length
; i
++)
4314 var tr
= table
.insertRow(-1);
4316 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
4318 var col
= this.options
.columns
[j
];
4319 var td
= tr
.insertCell(-1);
4321 var val
= this._rows
[i
][j
];
4323 if (typeof(val
) == 'undefined')
4324 val
= col
.placeholder
;
4326 if (typeof(val
) == 'undefined')
4330 td
.style
.width
= col
.width
;
4333 td
.style
.textAlign
= col
.align
;
4335 if (typeof col
.format
== 'string')
4336 $(td
).append(col
.format
.format(val
));
4337 else if (typeof col
.format
== 'function')
4338 $(td
).append(col
.format(val
, i
));
4346 fieldset
.appendChild(table
);
4352 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
4355 var vn
= parseInt(this.options
.value
) || 0;
4356 var mn
= parseInt(this.options
.max
) || 100;
4357 var pc
= Math
.floor((100 / mn
) * vn
);
4361 if (typeof(this.options
.format
) == 'string')
4362 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
4363 else if (typeof(this.options
.format
) == 'function')
4364 text
= this.options
.format(pc
);
4366 text
= '%.2f%%'.format(pc
);
4369 .addClass('progress')
4370 .append($('<div />')
4371 .addClass('progress-bar')
4372 .addClass('progress-bar-info')
4373 .css('width', pc
+ '%'))
4374 .append($('<small />')
4379 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
4382 var l2dev
= this.options
.l2_device
|| this.options
.device
;
4383 var l3dev
= this.options
.l3_device
;
4384 var dev
= l3dev
|| l2dev
|| '?';
4386 var span
= document
.createElement('span');
4387 span
.className
= 'badge';
4389 if (typeof(this.options
.signal
) == 'number' ||
4390 typeof(this.options
.noise
) == 'number')
4393 if (typeof(this.options
.signal
) != 'undefined' &&
4394 typeof(this.options
.noise
) != 'undefined')
4396 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
4409 span
.appendChild(document
.createElement('img'));
4410 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
4413 span
.title
= _luci2
.tr('No signal');
4415 span
.title
= '%s: %d %s / %s: %d %s'.format(
4416 _luci2
.tr('Signal'), this.options
.signal
, _luci2
.tr('dBm'),
4417 _luci2
.tr('Noise'), this.options
.noise
, _luci2
.tr('dBm')
4422 var type
= 'ethernet';
4423 var desc
= _luci2
.tr('Ethernet device');
4428 desc
= _luci2
.tr('Tunnel interface');
4430 else if (dev
.indexOf('br-') == 0)
4433 desc
= _luci2
.tr('Bridge');
4435 else if (dev
.indexOf('.') > 0)
4438 desc
= _luci2
.tr('VLAN interface');
4440 else if (dev
.indexOf('wlan') == 0 ||
4441 dev
.indexOf('ath') == 0 ||
4442 dev
.indexOf('wl') == 0)
4445 desc
= _luci2
.tr('Wireless Network');
4448 span
.appendChild(document
.createElement('img'));
4449 span
.lastChild
.src
= _luci2
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
4453 $(span
).append(' ');
4454 $(span
).append(dev
);
4460 var type = function(f
, l
)
4470 _luci2
.cbi
.validation
.message
= _luci2
.tr(msg
);
4473 compile: function(code
)
4478 var types
= _luci2
.cbi
.validation
.types
;
4483 for (var i
= 0; i
< code
.length
; i
++)
4491 switch (code
.charCodeAt(i
))
4503 var label
= code
.substring(pos
, i
);
4504 label
= label
.replace(/\\(.)/g, '$1');
4505 label
= label
.replace(/^[ \t]+/g, '');
4506 label
= label
.replace(/[ \t]+$/g, '');
4508 if (label
&& !isNaN(label
))
4510 stack
.push(parseFloat(label
));
4512 else if (label
.match(/^(['"]).*\1$/))
4514 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
4516 else if (typeof types
[label
] == 'function')
4518 stack
.push(types
[label
]);
4523 throw "Syntax error, unhandled token '"+label
+"'";
4528 depth
+= (code
.charCodeAt(i
) == 40);
4534 if (typeof stack
[stack
.length
-2] != 'function')
4535 throw "Syntax error, argument list follows non-function";
4537 stack
[stack
.length
-1] =
4538 _luci2
.cbi
.validation
.compile(code
.substring(pos
, i
));
4551 var validation
= this.cbi
.validation
;
4553 validation
.types
= {
4554 'integer': function()
4556 if (this.match(/^-?[0-9]+$/) != null)
4559 validation
.i18n('Must be a valid integer');
4563 'uinteger': function()
4565 if (validation
.types
['integer'].apply(this) && (this >= 0))
4568 validation
.i18n('Must be a positive integer');
4574 if (!isNaN(parseFloat(this)))
4577 validation
.i18n('Must be a valid number');
4581 'ufloat': function()
4583 if (validation
.types
['float'].apply(this) && (this >= 0))
4586 validation
.i18n('Must be a positive number');
4590 'ipaddr': function()
4592 if (validation
.types
['ip4addr'].apply(this) ||
4593 validation
.types
['ip6addr'].apply(this))
4596 validation
.i18n('Must be a valid IP address');
4600 'ip4addr': function()
4602 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
4604 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
4605 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
4606 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
4607 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
4608 ((RegExp
.$6.indexOf('.') < 0)
4609 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
4610 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
4614 validation
.i18n('Must be a valid IPv4 address');
4618 'ip6addr': function()
4620 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
4622 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
4624 var addr
= RegExp
.$1;
4631 if (addr
.indexOf('.') > 0)
4633 var off
= addr
.lastIndexOf(':');
4635 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
4637 validation
.i18n('Must be a valid IPv6 address');
4641 addr
= addr
.substr(0, off
) + ':0:0';
4644 if (addr
.indexOf('::') >= 0)
4649 for (var i
= 1; i
< (addr
.length
-1); i
++)
4650 if (addr
.charAt(i
) == ':')
4655 validation
.i18n('Must be a valid IPv6 address');
4659 for (var i
= 0; i
< (7 - colons
); i
++)
4662 if (addr
.match(/^(.*?)::(.*?)$/))
4663 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
4664 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
4667 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
4670 validation
.i18n('Must be a valid IPv6 address');
4675 validation
.i18n('Must be a valid IPv6 address');
4681 if (validation
.types
['integer'].apply(this) &&
4682 (this >= 0) && (this <= 65535))
4685 validation
.i18n('Must be a valid port number');
4689 'portrange': function()
4691 if (this.match(/^(\d+)-(\d+)$/))
4696 if (validation
.types
['port'].apply(p1
) &&
4697 validation
.types
['port'].apply(p2
) &&
4698 (parseInt(p1
) <= parseInt(p2
)))
4701 else if (validation
.types
['port'].apply(this))
4706 validation
.i18n('Must be a valid port range');
4710 'macaddr': function()
4712 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4715 validation
.i18n('Must be a valid MAC address');
4721 if (validation
.types
['hostname'].apply(this) ||
4722 validation
.types
['ipaddr'].apply(this))
4725 validation
.i18n('Must be a valid hostname or IP address');
4729 'hostname': function()
4731 if ((this.length
<= 253) &&
4732 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4733 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4734 this.match(/[^0-9.]/)))))
4737 validation
.i18n('Must be a valid host name');
4741 'network': function()
4743 if (validation
.types
['uciname'].apply(this) ||
4744 validation
.types
['host'].apply(this))
4747 validation
.i18n('Must be a valid network name');
4751 'wpakey': function()
4755 if ((v
.length
== 64)
4756 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
4757 : ((v
.length
>= 8) && (v
.length
<= 63)))
4760 validation
.i18n('Must be a valid WPA key');
4764 'wepkey': function()
4768 if (v
.substr(0,2) == 's:')
4771 if (((v
.length
== 10) || (v
.length
== 26))
4772 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
4773 : ((v
.length
== 5) || (v
.length
== 13)))
4776 validation
.i18n('Must be a valid WEP key');
4780 'uciname': function()
4782 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4785 validation
.i18n('Must be a valid UCI identifier');
4789 'range': function(min
, max
)
4791 var val
= parseFloat(this);
4793 if (validation
.types
['integer'].apply(this) &&
4794 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
4797 validation
.i18n('Must be a number between %d and %d');
4801 'min': function(min
)
4803 var val
= parseFloat(this);
4805 if (validation
.types
['integer'].apply(this) &&
4806 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
4809 validation
.i18n('Must be a number greater or equal to %d');
4813 'max': function(max
)
4815 var val
= parseFloat(this);
4817 if (validation
.types
['integer'].apply(this) &&
4818 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
4821 validation
.i18n('Must be a number lower or equal to %d');
4825 'rangelength': function(min
, max
)
4827 var val
= '' + this;
4829 if (!isNaN(min
) && !isNaN(max
) &&
4830 (val
.length
>= min
) && (val
.length
<= max
))
4833 validation
.i18n('Must be between %d and %d characters');
4837 'minlength': function(min
)
4839 var val
= '' + this;
4841 if (!isNaN(min
) && (val
.length
>= min
))
4844 validation
.i18n('Must be at least %d characters');
4848 'maxlength': function(max
)
4850 var val
= '' + this;
4852 if (!isNaN(max
) && (val
.length
<= max
))
4855 validation
.i18n('Must be at most %d characters');
4863 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4865 delete validation
.message
;
4867 if (typeof(arguments
[i
]) != 'function')
4869 if (arguments
[i
] == this)
4873 else if (arguments
[i
].apply(this, arguments
[i
+1]))
4878 if (validation
.message
)
4879 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4882 validation
.message
= msgs
.join( _luci2
.tr(' - or - '));
4890 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4892 delete validation
.message
;
4894 if (typeof arguments
[i
] != 'function')
4896 if (arguments
[i
] != this)
4900 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
4905 if (validation
.message
)
4906 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4909 validation
.message
= msgs
.join(', ');
4915 return validation
.types
['or'].apply(
4916 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
4919 'list': function(subvalidator
, subargs
)
4921 if (typeof subvalidator
!= 'function')
4924 var tokens
= this.match(/[^ \t]+/g);
4925 for (var i
= 0; i
< tokens
.length
; i
++)
4926 if (!subvalidator
.apply(tokens
[i
], subargs
))
4932 'phonedigit': function()
4934 if (this.match(/^[0-9\*#!\.]+$/) != null)
4937 validation
.i18n('Must be a valid phone number digit');
4941 'string': function()
4948 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
4949 init: function(name
, options
)
4952 this.instance
= { };
4953 this.dependencies
= [ ];
4954 this.rdependency
= { };
4956 this.options
= _luci2
.defaults(options
, {
4966 return this.section
.id('field', sid
|| '__unknown__', this.name
);
4969 render: function(sid
, condensed
)
4971 var i
= this.instance
[sid
] = { };
4973 i
.top
= $('<div />');
4977 i
.top
.addClass('form-group');
4979 if (typeof(this.options
.caption
) == 'string')
4981 .addClass('col-lg-2 control-label')
4982 .attr('for', this.id(sid
))
4983 .text(this.options
.caption
)
4987 i
.error
= $('<div />')
4989 .addClass('label label-danger');
4991 i
.widget
= $('<div />')
4993 .append(this.widget(sid
))
4999 i
.widget
.addClass('col-lg-5');
5002 .addClass('col-lg-5')
5003 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
5010 ucipath: function(sid
)
5013 config
: (this.options
.uci_package
|| this.map
.uci_package
),
5014 section
: (this.options
.uci_section
|| sid
),
5015 option
: (this.options
.uci_option
|| this.name
)
5019 ucivalue: function(sid
)
5021 var uci
= this.ucipath(sid
);
5022 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
5024 if (typeof(val
) == 'undefined')
5025 return this.options
.initial
;
5030 formvalue: function(sid
)
5032 var v
= $('#' + this.id(sid
)).val();
5033 return (v
=== '') ? undefined : v
;
5036 textvalue: function(sid
)
5038 var v
= this.formvalue(sid
);
5040 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5041 v
= this.ucivalue(sid
);
5043 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5044 v
= this.options
.placeholder
;
5046 if (typeof(v
) == 'undefined' || v
=== '')
5049 if (typeof(v
) == 'string' && $.isArray(this.choices
))
5051 for (var i
= 0; i
< this.choices
.length
; i
++)
5052 if (v
=== this.choices
[i
][0])
5053 return this.choices
[i
][1];
5055 else if (v
=== true)
5056 return _luci2
.tr('yes');
5057 else if (v
=== false)
5058 return _luci2
.tr('no');
5059 else if ($.isArray(v
))
5060 return v
.join(', ');
5065 changed: function(sid
)
5067 var a
= this.ucivalue(sid
);
5068 var b
= this.formvalue(sid
);
5070 if (typeof(a
) != typeof(b
))
5073 if (typeof(a
) == 'object')
5075 if (a
.length
!= b
.length
)
5078 for (var i
= 0; i
< a
.length
; i
++)
5090 var uci
= this.ucipath(sid
);
5092 if (this.instance
[sid
].disabled
)
5094 if (!this.options
.keep
)
5095 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5100 var chg
= this.changed(sid
);
5101 var val
= this.formvalue(sid
);
5104 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
5109 _ev_validate: function(ev
)
5113 var val
= d
.elem
.val();
5114 var vstack
= d
.vstack
;
5116 if (vstack
&& typeof(vstack
[0]) == 'function')
5118 delete validation
.message
;
5120 if ((val
.length
== 0 && !d
.opt
))
5122 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
5123 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5125 d
.inst
.error
.text(_luci2
.tr('Field must not be empty')).show();
5128 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
5130 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
5131 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5133 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
5138 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
5139 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
5141 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
5144 d
.inst
.error
.text('').hide();
5149 for (var field
in d
.self
.rdependency
)
5150 d
.self
.rdependency
[field
].toggle(d
.sid
);
5155 validator: function(sid
, elem
, multi
)
5157 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
5161 if (typeof(this.options
.datatype
) == 'string')
5164 vstack
= _luci2
.cbi
.validation
.compile(this.options
.datatype
);
5167 else if (typeof(this.options
.datatype
) == 'function')
5169 var vfunc
= this.options
.datatype
;
5170 vstack
= [ function(elem
) {
5171 var rv
= vfunc(this, elem
);
5173 validation
.message
= rv
;
5174 return (rv
=== true);
5184 inst
: this.instance
[sid
],
5185 opt
: this.options
.optional
5188 if (elem
.prop('tagName') == 'SELECT')
5190 elem
.change(evdata
, this._ev_validate
);
5192 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
5194 elem
.click(evdata
, this._ev_validate
);
5195 elem
.blur(evdata
, this._ev_validate
);
5199 elem
.keyup(evdata
, this._ev_validate
);
5200 elem
.blur(evdata
, this._ev_validate
);
5203 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
5208 validate: function(sid
)
5210 var i
= this.instance
[sid
];
5212 i
.widget
.find('[cbi-validate]').trigger('validate');
5214 return (i
.disabled
|| i
.error
.text() == '');
5217 depends: function(d
, v
)
5224 for (var i
= 0; i
< d
.length
; i
++)
5226 if (typeof(d
[i
]) == 'string')
5228 else if (d
[i
] instanceof _luci2
.cbi
.AbstractValue
)
5229 dep
[d
[i
].name
] = true;
5232 else if (d
instanceof _luci2
.cbi
.AbstractValue
)
5235 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
5237 else if (typeof(d
) == 'object')
5241 else if (typeof(d
) == 'string')
5244 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
5247 if (!dep
|| $.isEmptyObject(dep
))
5250 for (var field
in dep
)
5252 var f
= this.section
.fields
[field
];
5254 f
.rdependency
[this.name
] = this;
5259 if ($.isEmptyObject(dep
))
5262 this.dependencies
.push(dep
);
5267 toggle: function(sid
)
5269 var d
= this.dependencies
;
5270 var i
= this.instance
[sid
];
5275 for (var n
= 0; n
< d
.length
; n
++)
5279 for (var field
in d
[n
])
5281 var val
= this.section
.fields
[field
].formvalue(sid
);
5282 var cmp
= d
[n
][field
];
5284 if (typeof(cmp
) == 'boolean')
5286 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
5292 else if (typeof(cmp
) == 'string')
5300 else if (typeof(cmp
) == 'function')
5308 else if (cmp
instanceof RegExp
)
5333 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
5340 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
5341 widget: function(sid
)
5343 var o
= this.options
;
5345 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
5346 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
5348 var i
= $('<input />')
5349 .attr('id', this.id(sid
))
5350 .attr('type', 'checkbox')
5351 .prop('checked', this.ucivalue(sid
));
5354 .addClass('checkbox')
5355 .append(this.validator(sid
, i
));
5358 ucivalue: function(sid
)
5360 var v
= this.callSuper('ucivalue', sid
);
5362 if (typeof(v
) == 'boolean')
5365 return (v
== this.options
.enabled
);
5368 formvalue: function(sid
)
5370 var v
= $('#' + this.id(sid
)).prop('checked');
5372 if (typeof(v
) == 'undefined')
5373 return !!this.options
.initial
;
5380 var uci
= this.ucipath(sid
);
5382 if (this.instance
[sid
].disabled
)
5384 if (!this.options
.keep
)
5385 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5390 var chg
= this.changed(sid
);
5391 var val
= this.formvalue(sid
);
5395 if (this.options
.optional
&& val
== this.options
.initial
)
5396 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5398 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
5405 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
5406 widget: function(sid
)
5408 var i
= $('<input />')
5409 .addClass('form-control')
5410 .attr('id', this.id(sid
))
5411 .attr('type', 'text')
5412 .attr('placeholder', this.options
.placeholder
)
5413 .val(this.ucivalue(sid
));
5415 return this.validator(sid
, i
);
5419 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
5420 widget: function(sid
)
5422 var i
= $('<input />')
5423 .addClass('form-control')
5424 .attr('id', this.id(sid
))
5425 .attr('type', 'password')
5426 .attr('placeholder', this.options
.placeholder
)
5427 .val(this.ucivalue(sid
));
5429 var t
= $('<span />')
5430 .addClass('input-group-btn')
5431 .append(_luci2
.ui
.button(_luci2
.tr('Reveal'), 'default')
5432 .click(function(ev
) {
5434 var i
= b
.parent().prev();
5435 var t
= i
.attr('type');
5436 b
.text(t
== 'password' ? _luci2
.tr('Hide') : _luci2
.tr('Reveal'));
5437 i
.attr('type', (t
== 'password') ? 'text' : 'password');
5441 this.validator(sid
, i
);
5444 .addClass('input-group')
5450 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
5451 widget: function(sid
)
5453 var s
= $('<select />')
5454 .addClass('form-control');
5456 if (this.options
.optional
)
5459 .text(_luci2
.tr('-- Please choose --'))
5463 for (var i
= 0; i
< this.choices
.length
; i
++)
5465 .attr('value', this.choices
[i
][0])
5466 .text(this.choices
[i
][1])
5469 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
5471 return this.validator(sid
, s
);
5474 value: function(k
, v
)
5479 this.choices
.push([k
, v
|| k
]);
5484 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
5485 widget: function(sid
)
5487 var v
= this.ucivalue(sid
);
5488 var t
= $('<div />').attr('id', this.id(sid
));
5491 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5494 for (var i
= 0; i
< v
.length
; i
++)
5498 for (var i
= 0; i
< this.choices
.length
; i
++)
5501 .addClass('checkbox')
5502 .append($('<input />')
5503 .attr('type', 'checkbox')
5504 .attr('value', this.choices
[i
][0])
5505 .prop('checked', s
[this.choices
[i
][0]]))
5506 .append(this.choices
[i
][1])
5513 formvalue: function(sid
)
5516 var fields
= $('#' + this.id(sid
) + ' > label > input');
5518 for (var i
= 0; i
< fields
.length
; i
++)
5519 if (fields
[i
].checked
)
5520 rv
.push(fields
[i
].getAttribute('value'));
5525 textvalue: function(sid
)
5527 var v
= this.formvalue(sid
);
5531 for (var i
= 0; i
< this.choices
.length
; i
++)
5532 c
[this.choices
[i
][0]] = this.choices
[i
][1];
5536 for (var i
= 0; i
< v
.length
; i
++)
5537 t
.push(c
[v
[i
]] || v
[i
]);
5539 return t
.join(', ');
5543 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
5544 _change: function(ev
)
5547 var self
= ev
.data
.self
;
5549 if (s
.selectedIndex
== (s
.options
.length
- 1))
5551 ev
.data
.select
.hide();
5552 ev
.data
.input
.show().focus();
5554 var v
= ev
.data
.input
.val();
5555 ev
.data
.input
.val(' ');
5556 ev
.data
.input
.val(v
);
5558 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
5560 ev
.data
.input
.val('');
5564 ev
.data
.input
.val(ev
.data
.select
.val());
5571 var val
= this.value
;
5572 var self
= ev
.data
.self
;
5574 ev
.data
.select
.empty();
5576 if (self
.options
.optional
)
5579 .text(_luci2
.tr('-- please choose --'))
5580 .appendTo(ev
.data
.select
);
5583 for (var i
= 0; i
< self
.choices
.length
; i
++)
5585 if (self
.choices
[i
][0] == val
)
5589 .attr('value', self
.choices
[i
][0])
5590 .text(self
.choices
[i
][1])
5591 .appendTo(ev
.data
.select
);
5594 if (!seen
&& val
!= '')
5598 .appendTo(ev
.data
.select
);
5602 .text(_luci2
.tr('-- custom --'))
5603 .appendTo(ev
.data
.select
);
5605 ev
.data
.input
.hide();
5606 ev
.data
.select
.val(val
).show().focus();
5609 _enter: function(ev
)
5614 ev
.preventDefault();
5615 ev
.data
.self
._blur(ev
);
5619 widget: function(sid
)
5621 var d
= $('<div />')
5622 .attr('id', this.id(sid
));
5624 var t
= $('<input />')
5625 .attr('type', 'text')
5629 var s
= $('<select />')
5634 input
: this.validator(sid
, t
),
5635 select
: this.validator(sid
, s
)
5638 s
.change(evdata
, this._change
);
5639 t
.blur(evdata
, this._blur
);
5640 t
.keydown(evdata
, this._enter
);
5642 t
.val(this.ucivalue(sid
));
5648 value: function(k
, v
)
5653 this.choices
.push([k
, v
|| k
]);
5657 formvalue: function(sid
)
5659 var v
= $('#' + this.id(sid
)).children('input').val();
5660 return (v
== '') ? undefined : v
;
5664 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
5665 _redraw: function(focus
, add
, del
, s
)
5667 var v
= s
.values
|| [ ];
5670 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
5672 v
.push(this.value
|| '');
5675 $(s
.parent
).empty();
5680 v
.splice(focus
, 0, '');
5682 else if (v
.length
== 0)
5688 for (var i
= 0; i
< v
.length
; i
++)
5695 remove
: ((i
+1) < v
.length
)
5700 btn
= _luci2
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
5702 btn
= _luci2
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
5706 var txt
= $('<input />')
5707 .addClass('form-control')
5708 .attr('type', 'text')
5711 var sel
= $('<select />')
5712 .addClass('form-control');
5715 .addClass('input-group')
5718 .append($('<span />')
5719 .addClass('input-group-btn')
5721 .appendTo(s
.parent
);
5723 evdata
.input
= this.validator(s
.sid
, txt
, true);
5724 evdata
.select
= this.validator(s
.sid
, sel
, true);
5726 sel
.change(evdata
, this._change
);
5727 txt
.blur(evdata
, this._blur
);
5728 txt
.keydown(evdata
, this._keydown
);
5733 if (i
== focus
|| -(i
+1) == focus
)
5740 var f
= $('<input />')
5741 .attr('type', 'text')
5743 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
5744 .addClass('form-control')
5745 .keydown(evdata
, this._keydown
)
5746 .keypress(evdata
, this._keypress
)
5750 .addClass('input-group')
5752 .append($('<span />')
5753 .addClass('input-group-btn')
5755 .appendTo(s
.parent
);
5761 else if (-(i
+1) == focus
)
5765 /* force cursor to end */
5771 evdata
.input
= this.validator(s
.sid
, f
, true);
5782 _keypress: function(ev
)
5786 /* backspace, delete */
5789 if (ev
.data
.input
.val() == '')
5791 ev
.preventDefault();
5797 /* enter, arrow up, arrow down */
5801 ev
.preventDefault();
5808 _keydown: function(ev
)
5810 var input
= ev
.data
.input
;
5814 /* backspace, delete */
5817 if (input
.val().length
== 0)
5819 ev
.preventDefault();
5821 var index
= ev
.data
.index
;
5827 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
5835 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5840 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
5841 if (prev
.is(':visible'))
5844 prev
.next('select').focus();
5849 var next
= input
.parent().nextAll('div.input-group:first').children('input');
5850 if (next
.is(':visible'))
5853 next
.next('select').focus();
5860 _btnclick: function(ev
)
5862 if (!this.getAttribute('disabled'))
5866 var index
= ev
.data
.index
;
5867 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
5871 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5878 widget: function(sid
)
5880 this.options
.optional
= true;
5882 var v
= this.ucivalue(sid
);
5885 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5887 var d
= $('<div />')
5888 .attr('id', this.id(sid
))
5889 .addClass('cbi-input-dynlist');
5891 this._redraw(NaN
, -1, -1, {
5901 ucivalue: function(sid
)
5903 var v
= this.callSuper('ucivalue', sid
);
5906 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5911 formvalue: function(sid
)
5914 var fields
= $('#' + this.id(sid
) + ' > input');
5916 for (var i
= 0; i
< fields
.length
; i
++)
5917 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
5918 rv
.push(fields
[i
].value
);
5924 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
5925 widget: function(sid
)
5928 .addClass('form-control-static')
5929 .attr('id', this.id(sid
))
5930 .html(this.ucivalue(sid
));
5933 formvalue: function(sid
)
5935 return this.ucivalue(sid
);
5939 this.cbi
.ButtonValue
= this.cbi
.AbstractValue
.extend({
5940 widget: function(sid
)
5942 this.options
.optional
= true;
5944 var btn
= $('<button />')
5945 .addClass('btn btn-default')
5946 .attr('id', this.id(sid
))
5947 .attr('type', 'button')
5948 .text(this.label('text'));
5950 return this.validator(sid
, btn
);
5954 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
5957 return _luci2
.NetworkModel
.init();
5960 _device_icon: function(dev
)
5963 .attr('src', dev
.icon())
5964 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?'));
5967 widget: function(sid
)
5969 var id
= this.id(sid
);
5970 var ul
= $('<ul />')
5972 .addClass('list-unstyled');
5974 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
5975 var value
= this.ucivalue(sid
);
5978 if (!this.options
.multiple
)
5979 check
[value
] = true;
5981 for (var i
= 0; i
< value
.length
; i
++)
5982 check
[value
[i
]] = true;
5984 var interfaces
= _luci2
.NetworkModel
.getInterfaces();
5986 for (var i
= 0; i
< interfaces
.length
; i
++)
5988 var iface
= interfaces
[i
];
5989 var badge
= $('<span />')
5991 .text('%s: '.format(iface
.name()));
5993 var dev
= iface
.getDevice();
5994 var subdevs
= iface
.getSubdevices();
5997 for (var j
= 0; j
< subdevs
.length
; j
++)
5998 badge
.append(this._device_icon(subdevs
[j
]));
6000 badge
.append(this._device_icon(dev
));
6002 badge
.append($('<em />').text(_luci2
.tr('(No devices attached)')));
6005 .append($('<label />')
6006 .addClass(itype
+ ' inline')
6007 .append($('<input />')
6008 .attr('name', itype
+ id
)
6009 .attr('type', itype
)
6010 .attr('value', iface
.name())
6011 .prop('checked', !!check
[iface
.name()]))
6016 if (!this.options
.multiple
)
6019 .append($('<label />')
6020 .addClass(itype
+ ' inline text-muted')
6021 .append($('<input />')
6022 .attr('name', itype
+ id
)
6023 .attr('type', itype
)
6025 .prop('checked', $.isEmptyObject(check
)))
6026 .append(_luci2
.tr('unspecified')))
6033 ucivalue: function(sid
)
6035 var v
= this.callSuper('ucivalue', sid
);
6037 if (!this.options
.multiple
)
6043 else if (typeof(v
) == 'string')
6046 return v
? v
[0] : undefined;
6053 if (typeof(v
) == 'string')
6054 v
= v
.match(/\S+/g);
6060 formvalue: function(sid
)
6062 var inputs
= $('#' + this.id(sid
) + ' input');
6064 if (!this.options
.multiple
)
6066 for (var i
= 0; i
< inputs
.length
; i
++)
6067 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
6068 return inputs
[i
].value
;
6075 for (var i
= 0; i
< inputs
.length
; i
++)
6076 if (inputs
[i
].checked
)
6077 rv
.push(inputs
[i
].value
);
6079 return rv
.length
? rv
: undefined;
6084 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
6087 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
6089 for (var i
= 1; i
< arguments
.length
; i
++)
6090 s
.push(arguments
[i
].replace(/\./g, '_'));
6095 option: function(widget
, name
, options
)
6097 if (this.tabs
.length
== 0)
6098 this.tab({ id
: '__default__', selected
: true });
6100 return this.taboption('__default__', widget
, name
, options
);
6103 tab: function(options
)
6105 if (options
.selected
)
6106 this.tabs
.selected
= this.tabs
.length
;
6110 caption
: options
.caption
,
6111 description
: options
.description
,
6117 taboption: function(tabid
, widget
, name
, options
)
6120 for (var i
= 0; i
< this.tabs
.length
; i
++)
6122 if (this.tabs
[i
].id
== tabid
)
6130 throw 'Cannot append to unknown tab ' + tabid
;
6132 var w
= widget
? new widget(name
, options
) : null;
6134 if (!(w
instanceof _luci2
.cbi
.AbstractValue
))
6135 throw 'Widget must be an instance of AbstractValue';
6140 this.fields
[name
] = w
;
6146 ucipackages: function(pkg
)
6148 for (var i
= 0; i
< this.tabs
.length
; i
++)
6149 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6150 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
6151 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
6154 formvalue: function()
6158 this.sections(function(s
) {
6159 var sid
= s
['.name'];
6160 var sv
= rv
[sid
] || (rv
[sid
] = { });
6162 for (var i
= 0; i
< this.tabs
.length
; i
++)
6163 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6165 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
6166 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
6173 validate_section: function(sid
)
6175 var inst
= this.instance
[sid
];
6178 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
6180 for (var i
= 0; i
< this.tabs
.length
; i
++)
6183 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
6185 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6186 if (!this.tabs
[i
].fields
[j
].validate(sid
))
6192 .attr('title', _luci2
.trp('1 Error', '%d Errors', inval
).format(inval
));
6202 .attr('title', _luci2
.trp('1 Error', '%d Errors', invals
).format(invals
));
6209 validate: function()
6211 this.error_count
= 0;
6213 var as
= this.sections();
6215 for (var i
= 0; i
< as
.length
; i
++)
6217 var invals
= this.validate_section(as
[i
]['.name']);
6220 this.error_count
+= invals
;
6223 var badge
= $('#' + this.id('sectiontab')).children('span:first');
6225 if (this.error_count
> 0)
6227 .text(this.error_count
)
6228 .attr('title', _luci2
.trp('1 Error', '%d Errors', this.error_count
).format(this.error_count
));
6232 return (this.error_count
== 0);
6236 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
6237 init: function(uci_type
, options
)
6239 this.uci_type
= uci_type
;
6240 this.options
= options
;
6243 this.error_count
= 0;
6244 this.active_panel
= 0;
6245 this.active_tab
= { };
6248 filter: function(section
)
6253 sections: function(cb
)
6255 var s1
= _luci2
.uci
.sections(this.map
.uci_package
);
6258 for (var i
= 0; i
< s1
.length
; i
++)
6259 if (s1
[i
]['.type'] == this.uci_type
)
6260 if (this.filter(s1
[i
]))
6263 if (typeof(cb
) == 'function')
6264 for (var i
= 0; i
< s2
.length
; i
++)
6265 cb
.apply(this, [ s2
[i
] ]);
6272 this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
6275 remove: function(sid
)
6277 this.map
.remove(this.map
.uci_package
, sid
);
6280 _ev_add: function(ev
)
6283 var name
= undefined;
6284 var self
= ev
.data
.self
;
6286 if (addb
.prev().prop('nodeName') == 'INPUT')
6287 name
= addb
.prev().val();
6289 if (addb
.prop('disabled') || name
=== '')
6292 _luci2
.ui
.saveScrollTop();
6294 self
.active_panel
= -1;
6299 _luci2
.ui
.restoreScrollTop();
6302 _ev_remove: function(ev
)
6304 var self
= ev
.data
.self
;
6305 var sid
= ev
.data
.sid
;
6307 _luci2
.ui
.saveScrollTop();
6313 _luci2
.ui
.restoreScrollTop();
6315 ev
.stopPropagation();
6318 _ev_sid: function(ev
)
6320 var self
= ev
.data
.self
;
6322 var addb
= text
.next();
6323 var errt
= addb
.next();
6324 var name
= text
.val();
6326 if (!/^[a-zA-Z0-9_]*$/.test(name
))
6328 errt
.text(_luci2
.tr('Invalid section name')).show();
6329 text
.addClass('error');
6330 addb
.prop('disabled', true);
6334 if (_luci2
.uci
.get(self
.map
.uci_package
, name
))
6336 errt
.text(_luci2
.tr('Name already used')).show();
6337 text
.addClass('error');
6338 addb
.prop('disabled', true);
6342 errt
.text('').hide();
6343 text
.removeClass('error');
6344 addb
.prop('disabled', false);
6348 _ev_tab: function(ev
)
6350 var self
= ev
.data
.self
;
6351 var sid
= ev
.data
.sid
;
6354 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
6357 _ev_panel_collapse: function(ev
)
6359 var self
= ev
.data
.self
;
6361 var this_panel
= $(ev
.target
);
6362 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
6364 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
6365 var prev_panel
= $(prev_toggle
.attr('data-target'));
6369 .addClass('collapse');
6371 prev_toggle
.find('.luci2-section-teaser')
6373 .children('span:last')
6375 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
6377 this_toggle
.find('.luci2-section-teaser')
6380 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
6384 _ev_panel_open: function(ev
)
6386 var self
= ev
.data
.self
;
6387 var panel
= $($(this).attr('data-target'));
6388 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
6390 if (index
== self
.active_panel
)
6391 ev
.stopPropagation();
6394 _ev_sort: function(ev
)
6396 var self
= ev
.data
.self
;
6397 var cur_idx
= ev
.data
.index
;
6398 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
6399 var s
= self
.sections();
6401 if (new_idx
>= 0 && new_idx
< s
.length
)
6403 _luci2
.uci
.swap(self
.map
.uci_package
, s
[cur_idx
]['.name'], s
[new_idx
]['.name']);
6409 ev
.stopPropagation();
6412 teaser: function(sid
)
6414 var tf
= this.teaser_fields
;
6418 tf
= this.teaser_fields
= [ ];
6420 if ($.isArray(this.options
.teasers
))
6422 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
6424 var f
= this.options
.teasers
[i
];
6425 if (f
instanceof _luci2
.cbi
.AbstractValue
)
6427 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof _luci2
.cbi
.AbstractValue
)
6428 tf
.push(this.fields
[f
]);
6433 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
6434 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
6435 tf
.push(this.tabs
[i
].fields
[j
]);
6441 for (var i
= 0; i
< tf
.length
; i
++)
6443 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
6446 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
6447 var v
= tf
[i
].textvalue(sid
);
6449 if (typeof(v
) == 'undefined')
6452 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
6458 _render_add: function()
6460 if (!this.options
.addremove
)
6463 var text
= _luci2
.tr('Add section');
6464 var ttip
= _luci2
.tr('Create new section...');
6466 if ($.isArray(this.options
.add_caption
))
6467 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
6468 else if (typeof(this.options
.add_caption
) == 'string')
6469 text
= this.options
.add_caption
, ttip
= '';
6471 var add
= $('<div />');
6473 if (this.options
.anonymous
=== false)
6476 .addClass('cbi-input-text')
6477 .attr('type', 'text')
6478 .attr('placeholder', ttip
)
6479 .blur({ self
: this }, this._ev_sid
)
6480 .keyup({ self
: this }, this._ev_sid
)
6484 .attr('src', _luci2
.globals
.resource
+ '/icons/cbi/add.gif')
6485 .attr('title', text
)
6486 .addClass('cbi-button')
6487 .click({ self
: this }, this._ev_add
)
6491 .addClass('cbi-value-error')
6497 _luci2
.ui
.button(text
, 'success', ttip
)
6498 .click({ self
: this }, this._ev_add
)
6505 _render_remove: function(sid
, index
)
6507 if (!this.options
.addremove
)
6510 var text
= _luci2
.tr('Remove');
6511 var ttip
= _luci2
.tr('Remove this section');
6513 if ($.isArray(this.options
.remove_caption
))
6514 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
6515 else if (typeof(this.options
.remove_caption
) == 'string')
6516 text
= this.options
.remove_caption
, ttip
= '';
6518 return _luci2
.ui
.button(text
, 'danger', ttip
)
6519 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
6522 _render_sort: function(sid
, index
)
6524 if (!this.options
.sortable
)
6527 var b1
= _luci2
.ui
.button('↑', 'info', _luci2
.tr('Move up'))
6528 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
6530 var b2
= _luci2
.ui
.button('↓', 'info', _luci2
.tr('Move down'))
6531 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
6536 _render_caption: function()
6539 .addClass('panel-title')
6540 .append(this.label('caption') || this.uci_type
);
6543 _render_description: function()
6545 var text
= this.label('description');
6549 .addClass('luci2-section-description')
6555 _render_teaser: function(sid
, index
)
6557 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6560 .attr('id', this.id('teaser', sid
))
6561 .addClass('luci2-section-teaser well well-sm')
6562 .append($('<span />')
6564 .append($('<span />'));
6570 _render_head: function(condensed
)
6576 .addClass('panel-heading')
6577 .append(this._render_caption())
6578 .append(this._render_description());
6581 _render_tab_description: function(sid
, index
, tab_index
)
6583 var tab
= this.tabs
[tab_index
];
6585 if (typeof(tab
.description
) == 'string')
6588 .addClass('cbi-tab-descr')
6589 .text(tab
.description
);
6595 _render_tab_head: function(sid
, index
, tab_index
)
6597 var tab
= this.tabs
[tab_index
];
6598 var cur
= this.active_tab
[sid
] || 0;
6600 var tabh
= $('<li />')
6602 .attr('id', this.id('nodetab', sid
, tab
.id
))
6603 .attr('href', '#' + this.id('node', sid
, tab
.id
))
6604 .attr('data-toggle', 'tab')
6605 .attr('data-luci2-tab-index', tab_index
)
6606 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
6607 .append($('<span />')
6609 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
6611 if (cur
== tab_index
)
6612 tabh
.addClass('active');
6617 _render_tab_body: function(sid
, index
, tab_index
)
6619 var tab
= this.tabs
[tab_index
];
6620 var cur
= this.active_tab
[sid
] || 0;
6622 var tabb
= $('<div />')
6623 .addClass('tab-pane')
6624 .attr('id', this.id('node', sid
, tab
.id
))
6625 .attr('data-luci2-tab-index', tab_index
)
6626 .append(this._render_tab_description(sid
, index
, tab_index
));
6628 if (cur
== tab_index
)
6629 tabb
.addClass('active');
6631 for (var i
= 0; i
< tab
.fields
.length
; i
++)
6632 tabb
.append(tab
.fields
[i
].render(sid
));
6637 _render_section_head: function(sid
, index
)
6639 var head
= $('<div />')
6640 .addClass('luci2-section-header')
6641 .append(this._render_teaser(sid
, index
))
6642 .append($('<div />')
6643 .addClass('btn-group')
6644 .append(this._render_sort(sid
, index
))
6645 .append(this._render_remove(sid
, index
)));
6647 if (this.options
.collabsible
)
6649 head
.attr('data-toggle', 'collapse')
6650 .attr('data-parent', this.id('sectiongroup'))
6651 .attr('data-target', '#' + this.id('panel', sid
))
6652 .on('click', { self
: this }, this._ev_panel_open
);
6658 _render_section_body: function(sid
, index
)
6660 var body
= $('<div />')
6661 .attr('id', this.id('panel', sid
))
6662 .attr('data-luci2-panel-index', index
)
6663 .attr('data-luci2-sid', sid
);
6665 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6667 body
.addClass('panel-collapse collapse');
6669 if (index
== this.active_panel
)
6670 body
.addClass('in');
6673 var tab_heads
= $('<ul />')
6674 .addClass('nav nav-tabs');
6676 var tab_bodies
= $('<div />')
6677 .addClass('form-horizontal tab-content')
6680 for (var j
= 0; j
< this.tabs
.length
; j
++)
6682 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
6683 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
6686 body
.append(tab_bodies
);
6688 if (this.tabs
.length
<= 1)
6694 _render_body: function(condensed
)
6696 var s
= this.sections();
6698 if (this.active_panel
< 0)
6699 this.active_panel
+= s
.length
;
6700 else if (this.active_panel
>= s
.length
)
6701 this.active_panel
= s
.length
- 1;
6703 var body
= $('<ul />')
6704 .addClass('list-group');
6706 if (this.options
.collabsible
)
6708 body
.attr('id', this.id('sectiongroup'))
6709 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
6714 body
.append($('<li />')
6715 .addClass('list-group-item text-muted')
6716 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.')))
6719 for (var i
= 0; i
< s
.length
; i
++)
6721 var sid
= s
[i
]['.name'];
6722 var inst
= this.instance
[sid
] = { tabs
: [ ] };
6724 body
.append($('<li />')
6725 .addClass('list-group-item')
6726 .append(this._render_section_head(sid
, i
))
6727 .append(this._render_section_body(sid
, i
)));
6733 render: function(condensed
)
6735 this.instance
= { };
6737 var panel
= $('<div />')
6738 .addClass('panel panel-default')
6739 .append(this._render_head(condensed
))
6740 .append(this._render_body(condensed
));
6742 if (this.options
.addremove
)
6743 panel
.append($('<div />')
6744 .addClass('panel-footer')
6745 .append(this._render_add()));
6752 var s
= this.sections();
6754 for (var i
= 0; i
< s
.length
; i
++)
6756 var sid
= s
[i
]['.name'];
6758 this.validate_section(sid
);
6760 if (i
!= this.active_panel
)
6761 $('#' + this.id('teaser', sid
)).children('span:last')
6762 .append(this.teaser(sid
));
6764 $('#' + this.id('teaser', sid
))
6770 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
6771 _render_table_head: function()
6773 var thead
= $('<thead />')
6775 .addClass('cbi-section-table-titles'));
6777 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
6778 thead
.children().append($('<th />')
6779 .addClass('cbi-section-table-cell')
6780 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
6781 .append(this.tabs
[0].fields
[j
].label('caption')));
6783 if (this.options
.addremove
!== false || this.options
.sortable
)
6784 thead
.children().append($('<th />')
6785 .addClass('cbi-section-table-cell')
6791 _render_table_row: function(sid
, index
)
6793 var row
= $('<tr />')
6794 .attr('data-luci2-sid', sid
);
6796 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
6798 row
.append($('<td />')
6799 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
6800 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
6803 if (this.options
.addremove
!== false || this.options
.sortable
)
6805 row
.append($('<td />')
6806 .addClass('text-right')
6807 .append($('<div />')
6808 .addClass('btn-group')
6809 .append(this._render_sort(sid
, index
))
6810 .append(this._render_remove(sid
, index
))));
6816 _render_table_body: function()
6818 var s
= this.sections();
6820 var tbody
= $('<tbody />');
6824 var cols
= this.tabs
[0].fields
.length
;
6826 if (this.options
.addremove
!== false || this.options
.sortable
)
6829 tbody
.append($('<tr />')
6831 .addClass('text-muted')
6832 .attr('colspan', cols
)
6833 .text(this.label('placeholder') || _luci2
.tr('There are no entries defined yet.'))));
6836 for (var i
= 0; i
< s
.length
; i
++)
6838 var sid
= s
[i
]['.name'];
6839 var inst
= this.instance
[sid
] = { tabs
: [ ] };
6841 tbody
.append(this._render_table_row(sid
, i
));
6847 _render_body: function(condensed
)
6849 return $('<table />')
6850 .addClass('table table-condensed table-hover')
6851 .append(this._render_table_head())
6852 .append(this._render_table_body());
6856 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
6857 sections: function(cb
)
6860 var sl
= _luci2
.uci
.sections(this.map
.uci_package
);
6862 for (var i
= 0; i
< sl
.length
; i
++)
6863 if (sl
[i
]['.name'] == this.uci_type
)
6869 if (typeof(cb
) == 'function' && sa
.length
> 0)
6870 cb
.call(this, sa
[0]);
6876 this.cbi
.SingleSection
= this.cbi
.NamedSection
.extend({
6879 this.instance
= { };
6880 this.instance
[this.uci_type
] = { tabs
: [ ] };
6882 return this._render_section_body(this.uci_type
, 0);
6886 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
6887 sections: function(cb
)
6889 if (typeof(cb
) == 'function')
6890 cb
.apply(this, [ { '.name': this.uci_type
} ]);
6892 return [ { '.name': this.uci_type
} ];
6896 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
6897 init: function(uci_package
, options
)
6901 this.uci_package
= uci_package
;
6902 this.sections
= [ ];
6903 this.options
= _luci2
.defaults(options
, {
6904 save: function() { },
6905 prepare: function() { }
6909 _load_cb: function()
6911 var deferreds
= [ _luci2
.deferrable(this.options
.prepare()) ];
6913 for (var i
= 0; i
< this.sections
.length
; i
++)
6915 for (var f
in this.sections
[i
].fields
)
6917 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
6920 var s
= this.sections
[i
].sections();
6921 for (var j
= 0; j
< s
.length
; j
++)
6923 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
6924 if (_luci2
.isDeferred(rv
))
6930 return $.when
.apply($, deferreds
);
6938 for (var i
= 0; i
< this.sections
.length
; i
++)
6939 this.sections
[i
].ucipackages(packages
);
6941 packages
[this.uci_package
] = true;
6943 for (var pkg
in packages
)
6944 if (!_luci2
.uci
.writable(pkg
))
6945 this.options
.readonly
= true;
6947 return _luci2
.uci
.load(_luci2
.toArray(packages
)).then(function() {
6948 return self
._load_cb();
6952 _ev_tab: function(ev
)
6954 var self
= ev
.data
.self
;
6957 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
6960 _render_tab_head: function(tab_index
)
6962 var section
= this.sections
[tab_index
];
6963 var cur
= this.active_tab
|| 0;
6965 var tabh
= $('<li />')
6967 .attr('id', section
.id('sectiontab'))
6968 .attr('href', '#' + section
.id('section'))
6969 .attr('data-toggle', 'tab')
6970 .attr('data-luci2-tab-index', tab_index
)
6971 .text(section
.label('caption') + ' ')
6972 .append($('<span />')
6974 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
6976 if (cur
== tab_index
)
6977 tabh
.addClass('active');
6982 _render_tab_body: function(tab_index
)
6984 var section
= this.sections
[tab_index
];
6985 var desc
= section
.label('description');
6986 var cur
= this.active_tab
|| 0;
6988 var tabb
= $('<div />')
6989 .addClass('tab-pane')
6990 .attr('id', section
.id('section'))
6991 .attr('data-luci2-tab-index', tab_index
);
6993 if (cur
== tab_index
)
6994 tabb
.addClass('active');
6997 tabb
.append($('<p />')
7000 var s
= section
.render(this.options
.tabbed
);
7002 if (this.options
.readonly
|| section
.options
.readonly
)
7003 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
7010 _render_body: function()
7012 var tabs
= $('<ul />')
7013 .addClass('nav nav-tabs');
7015 var body
= $('<div />')
7018 for (var i
= 0; i
< this.sections
.length
; i
++)
7020 tabs
.append(this._render_tab_head(i
));
7021 body
.append(this._render_tab_body(i
));
7024 if (this.options
.tabbed
)
7025 body
.addClass('tab-content');
7034 var map
= $('<form />');
7036 if (typeof(this.options
.caption
) == 'string')
7037 map
.append($('<h2 />')
7038 .text(this.options
.caption
));
7040 if (typeof(this.options
.description
) == 'string')
7041 map
.append($('<p />')
7042 .text(this.options
.description
));
7044 map
.append(this._render_body());
7046 if (this.options
.pageaction
!== false)
7048 map
.append($('<div />')
7049 .addClass('panel panel-default panel-body text-right')
7050 .append($('<div />')
7051 .addClass('btn-group')
7052 .append(_luci2
.ui
.button(_luci2
.tr('Save & Apply'), 'primary')
7053 .click({ self
: this }, function(ev
) { }))
7054 .append(_luci2
.ui
.button(_luci2
.tr('Save'), 'default')
7055 .click({ self
: this }, function(ev
) { ev
.data
.self
.send(); }))
7056 .append(_luci2
.ui
.button(_luci2
.tr('Reset'), 'default')
7057 .click({ self
: this }, function(ev
) { ev
.data
.self
.insertInto(ev
.data
.self
.target
); }))));
7065 for (var i
= 0; i
< this.sections
.length
; i
++)
7066 this.sections
[i
].finish();
7073 this.target
.hide().empty().append(this.render());
7078 section: function(widget
, uci_type
, options
)
7080 var w
= widget
? new widget(uci_type
, options
) : null;
7082 if (!(w
instanceof _luci2
.cbi
.AbstractSection
))
7083 throw 'Widget must be an instance of AbstractSection';
7086 w
.index
= this.sections
.length
;
7088 this.sections
.push(w
);
7092 formvalue: function()
7096 for (var i
= 0; i
< this.sections
.length
; i
++)
7098 var sids
= this.sections
[i
].formvalue();
7099 for (var sid
in sids
)
7101 var s
= rv
[sid
] || (rv
[sid
] = { });
7102 $.extend(s
, sids
[sid
]);
7109 add: function(conf
, type
, name
)
7111 return _luci2
.uci
.add(conf
, type
, name
);
7114 remove: function(conf
, sid
)
7116 return _luci2
.uci
.remove(conf
, sid
);
7119 get: function(conf
, sid
, opt
)
7121 return _luci2
.uci
.get(conf
, sid
, opt
);
7124 set: function(conf
, sid
, opt
, val
)
7126 return _luci2
.uci
.set(conf
, sid
, opt
, val
);
7129 validate: function()
7133 for (var i
= 0; i
< this.sections
.length
; i
++)
7135 if (!this.sections
[i
].validate())
7146 if (self
.options
.readonly
)
7147 return _luci2
.deferrable();
7149 var deferreds
= [ ];
7151 for (var i
= 0; i
< self
.sections
.length
; i
++)
7153 if (self
.sections
[i
].options
.readonly
)
7156 for (var f
in self
.sections
[i
].fields
)
7158 if (typeof(self
.sections
[i
].fields
[f
].save
) != 'function')
7161 var s
= self
.sections
[i
].sections();
7162 for (var j
= 0; j
< s
.length
; j
++)
7164 var rv
= self
.sections
[i
].fields
[f
].save(s
[j
]['.name']);
7165 if (_luci2
.isDeferred(rv
))
7171 return $.when
.apply($, deferreds
).then(function() {
7172 return _luci2
.deferrable(self
.options
.save());
7178 if (!this.validate())
7179 return _luci2
.deferrable();
7183 _luci2
.ui
.saveScrollTop();
7184 _luci2
.ui
.loading(true);
7186 return this.save().then(function() {
7187 return _luci2
.uci
.save();
7188 }).then(function() {
7189 return _luci2
.ui
.updateChanges();
7190 }).then(function() {
7192 }).then(function() {
7196 _luci2
.ui
.loading(false);
7197 _luci2
.ui
.restoreScrollTop();
7201 insertInto: function(id
)
7204 self
.target
= $(id
);
7206 _luci2
.ui
.loading(true);
7209 return self
.load().then(function() {
7210 self
.target
.empty().append(self
.render());
7214 _luci2
.ui
.loading(false);