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) },
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(L
.globals
.resource
, langs
[i
]), {
267 success: function(data
) {
268 $.extend(L
.i18n
.catalog
, data
);
270 var pe
= L
.i18n
.catalog
[''];
273 delete L
.i18n
.catalog
[''];
275 var pf
= new Function('n', 'return 0 + (' + pe
+ ')');
282 L
.i18n
.loaded
= true;
287 this.tr = function(msgid
)
291 var msgstr
= L
.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
= L
.i18n
.catalog
[msgid
];
307 if (typeof(msgstr
) == 'undefined')
308 return (count
== 1) ? msgid
: msgid_plural
;
309 else if (typeof(msgstr
) == 'string')
312 return msgstr
[L
.i18n
.plural(count
)];
315 this.trc = function(msgctx
, msgid
)
319 var msgstr
= L
.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
= L
.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
[L
.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
: L
.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
= L
.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(L
.rpc
, req
.priv
);
573 /* store response data */
574 if (typeof(req
.index
) == 'number')
575 data
[req
.index
] = ret
;
579 /* delete request object */
580 delete L
.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 L
.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 L
.deferrable(msg
);
667 return _rpc
._call(msg
, _rpc
._call_cb
);
672 this.UCIContext
= Class
.extend({
686 _load
: L
.rpc
.declare({
689 params
: [ 'config' ],
690 expect
: { values
: { } }
693 _order
: L
.rpc
.declare({
696 params
: [ 'config', 'sections' ]
699 _add
: L
.rpc
.declare({
702 params
: [ 'config', 'type', 'name', 'values' ],
703 expect
: { section
: '' }
706 _set
: L
.rpc
.declare({
709 params
: [ 'config', 'section', 'values' ]
712 _delete
: L
.rpc
.declare({
715 params
: [ 'config', 'section', 'options' ]
718 _newid: function(conf
)
720 var v
= this.state
.values
;
721 var n
= this.state
.creates
;
725 sid
= "new%06x".format(Math
.random() * 0xFFFFFF);
726 } while ((n
[conf
] && n
[conf
][sid
]) || (v
[conf
] && v
[conf
][sid
]));
731 load: function(packages
)
737 if (!$.isArray(packages
))
738 packages
= [ packages
];
742 for (var i
= 0; i
< packages
.length
; i
++)
743 if (!seen
[packages
[i
]] && !self
.state
.values
[packages
[i
]])
745 pkgs
.push(packages
[i
]);
746 seen
[packages
[i
]] = true;
747 self
._load(packages
[i
]);
750 return L
.rpc
.flush().then(function(responses
) {
751 for (var i
= 0; i
< responses
.length
; i
++)
752 self
.state
.values
[pkgs
[i
]] = responses
[i
];
758 unload: function(packages
)
760 if (!$.isArray(packages
))
761 packages
= [ packages
];
763 for (var i
= 0; i
< packages
.length
; i
++)
765 delete this.state
.values
[packages
[i
]];
766 delete this.state
.creates
[packages
[i
]];
767 delete this.state
.changes
[packages
[i
]];
768 delete this.state
.deletes
[packages
[i
]];
772 add: function(conf
, type
, name
)
774 var n
= this.state
.creates
;
775 var sid
= this._newid(conf
);
785 '.index': 1000 + this.state
.newidx
++
791 remove: function(conf
, sid
)
793 var n
= this.state
.creates
;
794 var c
= this.state
.changes
;
795 var d
= this.state
.deletes
;
797 /* requested deletion of a just created section */
798 if (n
[conf
] && n
[conf
][sid
])
814 sections: function(conf
, type
, cb
)
817 var v
= this.state
.values
[conf
];
818 var n
= this.state
.creates
[conf
];
819 var c
= this.state
.changes
[conf
];
820 var d
= this.state
.deletes
[conf
];
826 if (!d
|| d
[s
] !== true)
827 if (!type
|| v
[s
]['.type'] == type
)
828 sa
.push($.extend({ }, v
[s
], c
? c
[s
] : undefined));
832 if (!type
|| n
[s
]['.type'] == type
)
835 sa
.sort(function(a
, b
) {
836 return a
['.index'] - b
['.index'];
839 for (var i
= 0; i
< sa
.length
; i
++)
842 if (typeof(cb
) == 'function')
843 for (var i
= 0; i
< sa
.length
; i
++)
844 cb
.call(this, sa
[i
], sa
[i
]['.name']);
849 get: function(conf
, sid
, opt
)
851 var v
= this.state
.values
;
852 var n
= this.state
.creates
;
853 var c
= this.state
.changes
;
854 var d
= this.state
.deletes
;
856 if (typeof(sid
) == 'undefined')
859 /* requested option in a just created section */
860 if (n
[conf
] && n
[conf
][sid
])
865 if (typeof(opt
) == 'undefined')
868 return n
[conf
][sid
][opt
];
871 /* requested an option value */
872 if (typeof(opt
) != 'undefined')
874 /* check whether option was deleted */
875 if (d
[conf
] && d
[conf
][sid
])
877 if (d
[conf
][sid
] === true)
880 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
881 if (d
[conf
][sid
][i
] == opt
)
885 /* check whether option was changed */
886 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
887 return c
[conf
][sid
][opt
];
889 /* return base value */
890 if (v
[conf
] && v
[conf
][sid
])
891 return v
[conf
][sid
][opt
];
896 /* requested an entire section */
903 set: function(conf
, sid
, opt
, val
)
905 var v
= this.state
.values
;
906 var n
= this.state
.creates
;
907 var c
= this.state
.changes
;
908 var d
= this.state
.deletes
;
910 if (typeof(sid
) == 'undefined' ||
911 typeof(opt
) == 'undefined' ||
912 opt
.charAt(0) == '.')
915 if (n
[conf
] && n
[conf
][sid
])
917 if (typeof(val
) != 'undefined')
918 n
[conf
][sid
][opt
] = val
;
920 delete n
[conf
][sid
][opt
];
922 else if (typeof(val
) != 'undefined')
924 /* do not set within deleted section */
925 if (d
[conf
] && d
[conf
][sid
] === true)
928 /* only set in existing sections */
929 if (!v
[conf
] || !v
[conf
][sid
])
938 /* undelete option */
939 if (d
[conf
] && d
[conf
][sid
])
940 d
[conf
][sid
] = L
.filterArray(d
[conf
][sid
], opt
);
942 c
[conf
][sid
][opt
] = val
;
946 /* only delete in existing sections */
947 if (!v
[conf
] || !v
[conf
][sid
])
956 if (d
[conf
][sid
] !== true)
957 d
[conf
][sid
].push(opt
);
961 unset: function(conf
, sid
, opt
)
963 return this.set(conf
, sid
, opt
, undefined);
970 for (var pkg
in this.state
.values
)
975 return this.load(pkgs
);
980 var v
= this.state
.values
;
981 var n
= this.state
.creates
;
982 var r
= this.state
.reorder
;
984 if ($.isEmptyObject(r
))
985 return L
.deferrable();
990 gather all created and existing sections, sort them according
991 to their index value and issue an uci order call
1006 o
.sort(function(a
, b
) {
1007 return (a
['.index'] - b
['.index']);
1012 for (var i
= 0; i
< o
.length
; i
++)
1013 sids
.push(o
[i
]['.name']);
1015 this._order(c
, sids
);
1019 this.state
.reorder
= { };
1020 return L
.rpc
.flush();
1023 swap: function(conf
, sid1
, sid2
)
1025 var s1
= this.get(conf
, sid1
);
1026 var s2
= this.get(conf
, sid2
);
1027 var n1
= s1
? s1
['.index'] : NaN
;
1028 var n2
= s2
? s2
['.index'] : NaN
;
1030 if (isNaN(n1
) || isNaN(n2
))
1036 this.state
.reorder
[conf
] = true;
1045 var v
= this.state
.values
;
1046 var n
= this.state
.creates
;
1047 var c
= this.state
.changes
;
1048 var d
= this.state
.deletes
;
1057 for (var sid
in n
[conf
])
1064 for (var k
in n
[conf
][sid
])
1067 r
.type
= n
[conf
][sid
][k
];
1068 else if (k
== '.create')
1069 r
.name
= n
[conf
][sid
][k
];
1070 else if (k
.charAt(0) != '.')
1071 r
.values
[k
] = n
[conf
][sid
][k
];
1074 snew
.push(n
[conf
][sid
]);
1076 self
._add(r
.config
, r
.type
, r
.name
, r
.values
);
1085 for (var sid
in c
[conf
])
1086 self
._set(conf
, sid
, c
[conf
][sid
]);
1094 for (var sid
in d
[conf
])
1096 var o
= d
[conf
][sid
];
1097 self
._delete(conf
, sid
, (o
=== true) ? undefined : o
);
1103 return L
.rpc
.flush().then(function(responses
) {
1105 array "snew" holds references to the created uci sections,
1106 use it to assign the returned names of the new sections
1108 for (var i
= 0; i
< snew
.length
; i
++)
1109 snew
[i
]['.name'] = responses
[i
];
1111 return self
._reorder();
1112 }).then(function() {
1113 pkgs
= L
.toArray(pkgs
);
1117 return self
.load(pkgs
);
1121 _apply
: L
.rpc
.declare({
1124 params
: [ 'timeout', 'rollback' ]
1127 _confirm
: L
.rpc
.declare({
1132 apply: function(timeout
)
1135 var date
= new Date();
1136 var deferred
= $.Deferred();
1138 if (typeof(timeout
) != 'number' || timeout
< 1)
1141 self
._apply(timeout
, true).then(function(rv
) {
1144 deferred
.rejectWith(self
, [ rv
]);
1148 var try_deadline
= date
.getTime() + 1000 * timeout
;
1149 var try_confirm = function()
1151 return self
._confirm().then(function(rv
) {
1154 if (date
.getTime() < try_deadline
)
1155 window
.setTimeout(try_confirm
, 250);
1157 deferred
.rejectWith(self
, [ rv
]);
1162 deferred
.resolveWith(self
, [ rv
]);
1166 window
.setTimeout(try_confirm
, 1000);
1172 changes
: L
.rpc
.declare({
1175 expect
: { changes
: { } }
1178 readable: function(conf
)
1180 return L
.session
.hasACL('uci', conf
, 'read');
1183 writable: function(conf
)
1185 return L
.session
.hasACL('uci', conf
, 'write');
1189 this.uci
= new this.UCIContext();
1192 listDeviceNames
: L
.rpc
.declare({
1195 expect
: { 'devices': [ ] },
1196 filter: function(data
) {
1202 getDeviceStatus
: L
.rpc
.declare({
1205 params
: [ 'device' ],
1206 expect
: { '': { } },
1207 filter: function(data
, params
) {
1208 if (!$.isEmptyObject(data
))
1210 data
['device'] = params
['device'];
1217 getAssocList
: L
.rpc
.declare({
1219 method
: 'assoclist',
1220 params
: [ 'device' ],
1221 expect
: { results
: [ ] },
1222 filter: function(data
, params
) {
1223 for (var i
= 0; i
< data
.length
; i
++)
1224 data
[i
]['device'] = params
['device'];
1226 data
.sort(function(a
, b
) {
1227 if (a
.bssid
< b
.bssid
)
1229 else if (a
.bssid
> b
.bssid
)
1239 getWirelessStatus: function() {
1240 return this.listDeviceNames().then(function(names
) {
1243 for (var i
= 0; i
< names
.length
; i
++)
1244 L
.wireless
.getDeviceStatus(names
[i
]);
1246 return L
.rpc
.flush();
1247 }).then(function(networks
) {
1251 'country', 'channel', 'frequency', 'frequency_offset',
1252 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1256 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1257 'signal', 'noise', 'bitrate', 'encryption'
1260 for (var i
= 0; i
< networks
.length
; i
++)
1262 var phy
= rv
[networks
[i
].phy
] || (
1263 rv
[networks
[i
].phy
] = { networks
: [ ] }
1267 device
: networks
[i
].device
1270 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1271 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1273 for (var j
= 0; j
< net_attrs
.length
; j
++)
1274 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1276 phy
.networks
.push(net
);
1283 getAssocLists: function()
1285 return this.listDeviceNames().then(function(names
) {
1288 for (var i
= 0; i
< names
.length
; i
++)
1289 L
.wireless
.getAssocList(names
[i
]);
1291 return L
.rpc
.flush();
1292 }).then(function(assoclists
) {
1295 for (var i
= 0; i
< assoclists
.length
; i
++)
1296 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1297 rv
.push(assoclists
[i
][j
]);
1303 formatEncryption: function(enc
)
1305 var format_list = function(l
, s
)
1308 for (var i
= 0; i
< l
.length
; i
++)
1309 rv
.push(l
[i
].toUpperCase());
1310 return rv
.join(s
? s
: ', ');
1313 if (!enc
|| !enc
.enabled
)
1314 return L
.tr('None');
1318 if (enc
.wep
.length
== 2)
1319 return L
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1320 else if (enc
.wep
[0] == 'shared')
1321 return L
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1323 return L
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1327 if (enc
.wpa
.length
== 2)
1328 return L
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1329 format_list(enc
.authentication
, '/'),
1330 format_list(enc
.ciphers
, ', ')
1332 else if (enc
.wpa
[0] == 2)
1333 return 'WPA2 %s (%s)'.format(
1334 format_list(enc
.authentication
, '/'),
1335 format_list(enc
.ciphers
, ', ')
1338 return 'WPA %s (%s)'.format(
1339 format_list(enc
.authentication
, '/'),
1340 format_list(enc
.ciphers
, ', ')
1344 return L
.tr('Unknown');
1349 getZoneColor: function(zone
)
1351 if ($.isPlainObject(zone
))
1356 else if (zone
== 'wan')
1359 for (var i
= 0, hash
= 0;
1361 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1363 for (var i
= 0, color
= '#';
1365 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tostring(16)).slice(-2));
1370 findZoneByNetwork: function(network
)
1373 var zone
= undefined;
1375 return L
.uci
.sections('firewall', 'zone', function(z
) {
1376 if (!z
.name
|| !z
.network
)
1379 if (!$.isArray(z
.network
))
1380 z
.network
= z
.network
.split(/\s+/);
1382 for (var i
= 0; i
< z
.network
.length
; i
++)
1384 if (z
.network
[i
] == network
)
1390 }).then(function() {
1392 zone
.color
= self
.getZoneColor(zone
);
1399 this.NetworkModel
= {
1400 _device_blacklist
: [
1406 /^wlan[0-9]+\.sta[0-9]+$/
1410 'protolist', 0, L
.rpc
.declare({
1412 method
: 'get_proto_handlers',
1415 'ifstate', 1, L
.rpc
.declare({
1416 object
: 'network.interface',
1418 expect
: { 'interface': [ ] }
1420 'devstate', 2, L
.rpc
.declare({
1421 object
: 'network.device',
1425 'wifistate', 0, L
.rpc
.declare({
1426 object
: 'network.wireless',
1430 'bwstate', 2, L
.rpc
.declare({
1431 object
: 'luci2.network.bwmon',
1432 method
: 'statistics',
1433 expect
: { 'statistics': { } }
1435 'devlist', 2, L
.rpc
.declare({
1436 object
: 'luci2.network',
1437 method
: 'device_list',
1438 expect
: { 'devices': [ ] }
1440 'swlist', 0, L
.rpc
.declare({
1441 object
: 'luci2.network',
1442 method
: 'switch_list',
1443 expect
: { 'switches': [ ] }
1447 _fetch_protocol: function(proto
)
1449 var url
= L
.globals
.resource
+ '/proto/' + proto
+ '.js';
1450 var self
= L
.NetworkModel
;
1452 var def
= $.Deferred();
1458 }).then(function(data
) {
1460 var protoConstructorSource
= (
1461 '(function(L, $) { ' +
1465 ).format(data
, url
);
1467 var protoClass
= eval(protoConstructorSource
);
1469 self
._protos
[proto
] = new protoClass();
1472 alert('Unable to instantiate proto "%s": %s'.format(url
, e
));
1476 }).fail(function() {
1483 _fetch_protocols: function()
1485 var self
= L
.NetworkModel
;
1486 var deferreds
= [ ];
1488 for (var proto
in self
._cache
.protolist
)
1489 deferreds
.push(self
._fetch_protocol(proto
));
1491 return $.when
.apply($, deferreds
);
1494 _fetch_swstate
: L
.rpc
.declare({
1495 object
: 'luci2.network',
1496 method
: 'switch_info',
1497 params
: [ 'switch' ],
1498 expect
: { 'info': { } }
1501 _fetch_swstate_cb: function(responses
) {
1502 var self
= L
.NetworkModel
;
1503 var swlist
= self
._cache
.swlist
;
1504 var swstate
= self
._cache
.swstate
= { };
1506 for (var i
= 0; i
< responses
.length
; i
++)
1507 swstate
[swlist
[i
]] = responses
[i
];
1510 _fetch_cache_cb: function(level
)
1512 var self
= L
.NetworkModel
;
1513 var name
= '_fetch_cache_cb_' + level
;
1515 return self
[name
] || (
1516 self
[name
] = function(responses
)
1518 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1519 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1520 self
._cache
[self
._cache_functions
[i
]] = responses
.shift();
1526 for (var i
= 0; i
< self
._cache
.swlist
.length
; i
++)
1527 self
._fetch_swstate(self
._cache
.swlist
[i
]);
1529 return L
.rpc
.flush().then(self
._fetch_swstate_cb
);
1532 return L
.deferrable();
1537 _fetch_cache: function(level
)
1539 var self
= L
.NetworkModel
;
1541 return L
.uci
.load(['network', 'wireless']).then(function() {
1544 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1545 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1546 self
._cache_functions
[i
+ 2]();
1548 return L
.rpc
.flush().then(self
._fetch_cache_cb(level
|| 0));
1552 _get: function(pkg
, sid
, key
)
1554 return L
.uci
.get(pkg
, sid
, key
);
1557 _set: function(pkg
, sid
, key
, val
)
1559 return L
.uci
.set(pkg
, sid
, key
, val
);
1562 _is_blacklisted: function(dev
)
1564 for (var i
= 0; i
< this._device_blacklist
.length
; i
++)
1565 if (dev
.match(this._device_blacklist
[i
]))
1571 _sort_devices: function(a
, b
)
1573 if (a
.options
.kind
< b
.options
.kind
)
1575 else if (a
.options
.kind
> b
.options
.kind
)
1578 if (a
.options
.name
< b
.options
.name
)
1580 else if (a
.options
.name
> b
.options
.name
)
1586 _get_dev: function(ifname
)
1588 var alias
= (ifname
.charAt(0) == '@');
1589 return this._devs
[ifname
] || (
1590 this._devs
[ifname
] = {
1592 kind
: alias
? 'alias' : 'ethernet',
1593 type
: alias
? 0 : 1,
1600 _get_iface: function(name
)
1602 return this._ifaces
[name
] || (
1603 this._ifaces
[name
] = {
1605 proto
: this._protos
.none
,
1611 _parse_devices: function()
1613 var self
= L
.NetworkModel
;
1614 var wificount
= { };
1616 for (var ifname
in self
._cache
.devstate
)
1618 if (self
._is_blacklisted(ifname
))
1621 var dev
= self
._cache
.devstate
[ifname
];
1622 var entry
= self
._get_dev(ifname
);
1629 entry
.kind
= 'tunnel';
1633 entry
.kind
= 'bridge';
1634 //entry.ports = dev['bridge-members'].sort();
1639 for (var i
= 0; i
< self
._cache
.devlist
.length
; i
++)
1641 var dev
= self
._cache
.devlist
[i
];
1643 if (self
._is_blacklisted(dev
.device
))
1646 var entry
= self
._get_dev(dev
.device
);
1648 entry
.up
= dev
.is_up
;
1649 entry
.type
= dev
.type
;
1653 case 1: /* Ethernet */
1655 entry
.kind
= 'bridge';
1656 else if (dev
.is_tuntap
)
1657 entry
.kind
= 'tunnel';
1658 else if (dev
.is_wireless
)
1659 entry
.kind
= 'wifi';
1663 case 768: /* IP-IP Tunnel */
1664 case 769: /* IP6-IP6 Tunnel */
1665 case 776: /* IPv6-in-IPv4 */
1666 case 778: /* GRE over IP */
1667 entry
.kind
= 'tunnel';
1672 var net
= L
.uci
.sections('network');
1673 for (var i
= 0; i
< net
.length
; i
++)
1676 var sid
= s
['.name'];
1678 if (s
['.type'] == 'device' && s
.name
)
1680 var entry
= self
._get_dev(s
.name
);
1686 entry
.kind
= 'tunnel';
1692 else if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.ifname
)
1694 var ifnames
= L
.toArray(s
.ifname
);
1696 for (var j
= 0; j
< ifnames
.length
; j
++)
1697 self
._get_dev(ifnames
[j
]);
1699 if (s
['.name'] != 'loopback')
1701 var entry
= self
._get_dev('@%s'.format(s
['.name']));
1704 entry
.kind
= 'alias';
1708 else if (s
['.type'] == 'switch_vlan' && s
.device
)
1710 var sw
= self
._cache
.swstate
[s
.device
];
1711 var vid
= parseInt(s
.vid
|| s
.vlan
);
1712 var ports
= L
.toArray(s
.ports
);
1714 if (!sw
|| !ports
.length
|| isNaN(vid
))
1717 var ifname
= undefined;
1719 for (var j
= 0; j
< ports
.length
; j
++)
1721 var port
= parseInt(ports
[j
]);
1722 var tag
= (ports
[j
].replace(/[^tu]/g, '') == 't');
1724 if (port
== sw
.cpu_port
)
1726 // XXX: need a way to map switch to netdev
1728 ifname
= 'eth0.%d'.format(vid
);
1739 var entry
= self
._get_dev(ifname
);
1741 entry
.kind
= 'vlan';
1748 var wifi
= L
.uci
.sections('wireless');
1749 for (var i
= 0; i
< wifi
.length
; i
++)
1752 var sid
= s
['.name'];
1754 if (s
['.type'] == 'wifi-iface' && s
.device
)
1756 var r
= parseInt(s
.device
.replace(/^[^0-9]+/, ''));
1757 var n
= wificount
[s
.device
] = (wificount
[s
.device
] || 0) + 1;
1758 var id
= 'radio%d.network%d'.format(r
, n
);
1761 if (self
._cache
.wifistate
[s
.device
])
1763 var ifcs
= self
._cache
.wifistate
[s
.device
].interfaces
;
1764 for (var ifc
in ifcs
)
1766 if (ifcs
[ifc
].section
== sid
)
1768 ifname
= ifcs
[ifc
].ifname
;
1774 var entry
= self
._get_dev(ifname
);
1776 entry
.kind
= 'wifi';
1779 entry
.wdev
= s
.device
;
1780 entry
.wmode
= s
.mode
;
1781 entry
.wssid
= s
.ssid
;
1782 entry
.wbssid
= s
.bssid
;
1786 for (var i
= 0; i
< net
.length
; i
++)
1789 var sid
= s
['.name'];
1791 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.type
== 'bridge')
1793 var ifnames
= L
.toArray(s
.ifname
);
1795 for (var ifname
in self
._devs
)
1797 var dev
= self
._devs
[ifname
];
1799 if (dev
.kind
!= 'wifi')
1802 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1803 if ($.inArray(sid
, wnets
) > -1)
1804 ifnames
.push(ifname
);
1807 entry
= self
._get_dev('br-%s'.format(s
['.name']));
1809 entry
.kind
= 'bridge';
1811 entry
.ports
= ifnames
.sort();
1816 _parse_interfaces: function()
1818 var self
= L
.NetworkModel
;
1819 var net
= L
.uci
.sections('network');
1821 for (var i
= 0; i
< net
.length
; i
++)
1824 var sid
= s
['.name'];
1826 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.proto
)
1828 var entry
= self
._get_iface(s
['.name']);
1829 var proto
= self
._protos
[s
.proto
] || self
._protos
.none
;
1831 var l3dev
= undefined;
1832 var l2dev
= undefined;
1834 var ifnames
= L
.toArray(s
.ifname
);
1836 for (var ifname
in self
._devs
)
1838 var dev
= self
._devs
[ifname
];
1840 if (dev
.kind
!= 'wifi')
1843 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1844 if ($.inArray(entry
.name
, wnets
) > -1)
1845 ifnames
.push(ifname
);
1849 l3dev
= '%s-%s'.format(s
.proto
, entry
.name
);
1850 else if (s
.type
== 'bridge')
1851 l3dev
= 'br-%s'.format(entry
.name
);
1855 if (!proto
.virtual
&& s
.type
== 'bridge')
1856 l2dev
= 'br-%s'.format(entry
.name
);
1857 else if (!proto
.virtual
)
1860 entry
.proto
= proto
;
1862 entry
.l3dev
= l3dev
;
1863 entry
.l2dev
= l2dev
;
1867 for (var i
= 0; i
< self
._cache
.ifstate
.length
; i
++)
1869 var iface
= self
._cache
.ifstate
[i
];
1870 var entry
= self
._get_iface(iface
['interface']);
1871 var proto
= self
._protos
[iface
.proto
] || self
._protos
.none
;
1873 /* this is a virtual interface, either deleted from config but
1874 not applied yet or set up from external tools (6rd) */
1877 entry
.proto
= proto
;
1878 entry
.l2dev
= iface
.device
;
1879 entry
.l3dev
= iface
.l3_device
;
1889 return L
.deferrable();
1896 return self
._fetch_cache()
1897 .then(self
._fetch_protocols
)
1898 .then(self
._parse_devices
)
1899 .then(self
._parse_interfaces
);
1908 refreshInterfaceStatus: function()
1910 return this._fetch_cache(1).then(this._parse_interfaces
);
1913 refreshDeviceStatus: function()
1915 return this._fetch_cache(2).then(this._parse_devices
);
1918 refreshStatus: function()
1920 return this._fetch_cache(1)
1921 .then(this._fetch_cache(2))
1922 .then(this._parse_devices
)
1923 .then(this._parse_interfaces
);
1926 getDevices: function()
1930 for (var ifname
in this._devs
)
1932 devs
.push(new L
.NetworkModel
.Device(this._devs
[ifname
]));
1934 return devs
.sort(this._sort_devices
);
1937 getDeviceByInterface: function(iface
)
1939 if (iface
instanceof L
.NetworkModel
.Interface
)
1940 iface
= iface
.name();
1942 if (this._ifaces
[iface
])
1943 return this.getDevice(this._ifaces
[iface
].l3dev
) ||
1944 this.getDevice(this._ifaces
[iface
].l2dev
);
1949 getDevice: function(ifname
)
1951 if (this._devs
[ifname
])
1952 return new L
.NetworkModel
.Device(this._devs
[ifname
]);
1957 createDevice: function(name
)
1959 return new L
.NetworkModel
.Device(this._get_dev(name
));
1962 getInterfaces: function()
1966 for (var name
in this._ifaces
)
1967 if (name
!= 'loopback')
1968 ifaces
.push(this.getInterface(name
));
1970 ifaces
.sort(function(a
, b
) {
1971 if (a
.name() < b
.name())
1973 else if (a
.name() > b
.name())
1982 getInterfacesByDevice: function(dev
)
1986 if (dev
instanceof L
.NetworkModel
.Device
)
1989 for (var name
in this._ifaces
)
1991 var iface
= this._ifaces
[name
];
1992 if (iface
.l2dev
== dev
|| iface
.l3dev
== dev
)
1993 ifaces
.push(this.getInterface(name
));
1996 ifaces
.sort(function(a
, b
) {
1997 if (a
.name() < b
.name())
1999 else if (a
.name() > b
.name())
2008 getInterface: function(iface
)
2010 if (this._ifaces
[iface
])
2011 return new L
.NetworkModel
.Interface(this._ifaces
[iface
]);
2016 getProtocols: function()
2020 for (var proto
in this._protos
)
2022 var pr
= this._protos
[proto
];
2026 description
: pr
.description
,
2027 virtual
: pr
.virtual
,
2032 return rv
.sort(function(a
, b
) {
2033 if (a
.name
< b
.name
)
2035 else if (a
.name
> b
.name
)
2042 _find_wan: function(ipaddr
)
2044 for (var i
= 0; i
< this._cache
.ifstate
.length
; i
++)
2046 var ifstate
= this._cache
.ifstate
[i
];
2051 for (var j
= 0; j
< ifstate
.route
.length
; j
++)
2052 if (ifstate
.route
[j
].mask
== 0 &&
2053 ifstate
.route
[j
].target
== ipaddr
&&
2054 typeof(ifstate
.route
[j
].table
) == 'undefined')
2056 return this.getInterface(ifstate
['interface']);
2065 return this._find_wan('0.0.0.0');
2068 findWAN6: function()
2070 return this._find_wan('::');
2073 resolveAlias: function(ifname
)
2075 if (ifname
instanceof L
.NetworkModel
.Device
)
2076 ifname
= ifname
.name();
2078 var dev
= this._devs
[ifname
];
2081 while (dev
&& dev
.kind
== 'alias')
2084 if (seen
[dev
.ifname
])
2087 var ifc
= this._ifaces
[dev
.sid
];
2089 seen
[dev
.ifname
] = true;
2090 dev
= ifc
? this._devs
[ifc
.l3dev
] : undefined;
2093 return dev
? this.getDevice(dev
.ifname
) : undefined;
2097 this.NetworkModel
.Device
= Class
.extend({
2100 sta
: L
.tr('Client'),
2101 adhoc
: L
.tr('Ad-Hoc'),
2102 monitor
: L
.tr('Monitor'),
2103 wds
: L
.tr('Static WDS')
2106 _status: function(key
)
2108 var s
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2111 return key
? s
[key
] : s
;
2118 var sid
= this.options
.sid
;
2119 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2120 return L
.NetworkModel
._get(pkg
, sid
, key
);
2123 set: function(key
, val
)
2125 var sid
= this.options
.sid
;
2126 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2127 return L
.NetworkModel
._set(pkg
, sid
, key
, val
);
2132 if (typeof(this.options
.type
) == 'undefined')
2133 this.options
.type
= 1;
2135 if (typeof(this.options
.kind
) == 'undefined')
2136 this.options
.kind
= 'ethernet';
2138 if (typeof(this.options
.networks
) == 'undefined')
2139 this.options
.networks
= [ ];
2144 return this.options
.ifname
;
2147 description: function()
2149 switch (this.options
.kind
)
2152 return L
.tr('Alias for network "%s"').format(this.options
.ifname
.substring(1));
2155 return L
.tr('Network bridge');
2158 return L
.tr('Network device');
2161 switch (this.options
.type
)
2163 case 1: /* tuntap */
2164 return L
.tr('TAP device');
2167 return L
.tr('PPP tunnel');
2169 case 768: /* IP-IP Tunnel */
2170 return L
.tr('IP-in-IP tunnel');
2172 case 769: /* IP6-IP6 Tunnel */
2173 return L
.tr('IPv6-in-IPv6 tunnel');
2175 case 776: /* IPv6-in-IPv4 */
2176 return L
.tr('IPv6-over-IPv4 tunnel');
2179 case 778: /* GRE over IP */
2180 return L
.tr('GRE-over-IP tunnel');
2183 return L
.tr('Tunnel device');
2187 return L
.tr('VLAN %d on %s').format(this.options
.vid
, this.options
.vsw
.model
);
2190 var o
= this.options
;
2191 return L
.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2192 o
.wmode
? this._wifi_modes
[o
.wmode
] : L
.tr('Unknown mode'),
2193 o
.wssid
|| '?', o
.wdev
2197 return L
.tr('Unknown device');
2202 var kind
= this.options
.kind
;
2204 if (kind
== 'alias')
2207 if (typeof(up
) == 'undefined')
2210 return L
.globals
.resource
+ '/icons/%s%s.png'.format(kind
, up
? '' : '_disabled');
2215 var l
= L
.NetworkModel
._cache
.devlist
;
2217 for (var i
= 0; i
< l
.length
; i
++)
2218 if (l
[i
].device
== this.options
.ifname
)
2219 return (l
[i
].is_up
=== true);
2226 return (this.options
.kind
== 'alias');
2229 isBridge: function()
2231 return (this.options
.kind
== 'bridge');
2234 isBridgeable: function()
2236 return (this.options
.type
== 1 && this.options
.kind
!= 'bridge');
2239 isWireless: function()
2241 return (this.options
.kind
== 'wifi');
2244 isInNetwork: function(net
)
2246 if (!(net
instanceof L
.NetworkModel
.Interface
))
2247 net
= L
.NetworkModel
.getInterface(net
);
2251 if (net
.options
.l3dev
== this.options
.ifname
||
2252 net
.options
.l2dev
== this.options
.ifname
)
2255 var dev
= L
.NetworkModel
._devs
[net
.options
.l2dev
];
2256 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
)
2257 return ($.inArray(this.options
.ifname
, dev
.ports
) > -1);
2265 var dev
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2266 if (dev
&& !isNaN(dev
.mtu
))
2272 getMACAddress: function()
2274 if (this.options
.type
!= 1)
2277 var dev
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2278 if (dev
&& dev
.macaddr
)
2279 return dev
.macaddr
.toUpperCase();
2284 getInterfaces: function()
2286 return L
.NetworkModel
.getInterfacesByDevice(this.options
.name
);
2289 getStatistics: function()
2291 var s
= this._status('statistics') || { };
2293 rx_bytes
: (s
.rx_bytes
|| 0),
2294 tx_bytes
: (s
.tx_bytes
|| 0),
2295 rx_packets
: (s
.rx_packets
|| 0),
2296 tx_packets
: (s
.tx_packets
|| 0)
2300 getTrafficHistory: function()
2302 var def
= new Array(120);
2304 for (var i
= 0; i
< 120; i
++)
2307 var h
= L
.NetworkModel
._cache
.bwstate
[this.options
.ifname
] || { };
2309 rx_bytes
: (h
.rx_bytes
|| def
),
2310 tx_bytes
: (h
.tx_bytes
|| def
),
2311 rx_packets
: (h
.rx_packets
|| def
),
2312 tx_packets
: (h
.tx_packets
|| def
)
2316 removeFromInterface: function(iface
)
2318 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2319 iface
= L
.NetworkModel
.getInterface(iface
);
2324 var ifnames
= L
.toArray(iface
.get('ifname'));
2325 if ($.inArray(this.options
.ifname
, ifnames
) > -1)
2326 iface
.set('ifname', L
.filterArray(ifnames
, this.options
.ifname
));
2328 if (this.options
.kind
!= 'wifi')
2331 var networks
= L
.toArray(this.get('network'));
2332 if ($.inArray(iface
.name(), networks
) > -1)
2333 this.set('network', L
.filterArray(networks
, iface
.name()));
2336 attachToInterface: function(iface
)
2338 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2339 iface
= L
.NetworkModel
.getInterface(iface
);
2344 if (this.options
.kind
!= 'wifi')
2346 var ifnames
= L
.toArray(iface
.get('ifname'));
2347 if ($.inArray(this.options
.ifname
, ifnames
) < 0)
2349 ifnames
.push(this.options
.ifname
);
2350 iface
.set('ifname', (ifnames
.length
> 1) ? ifnames
: ifnames
[0]);
2355 var networks
= L
.toArray(this.get('network'));
2356 if ($.inArray(iface
.name(), networks
) < 0)
2358 networks
.push(iface
.name());
2359 this.set('network', (networks
.length
> 1) ? networks
: networks
[0]);
2365 this.NetworkModel
.Interface
= Class
.extend({
2366 _status: function(key
)
2368 var s
= L
.NetworkModel
._cache
.ifstate
;
2370 for (var i
= 0; i
< s
.length
; i
++)
2371 if (s
[i
]['interface'] == this.options
.name
)
2372 return key
? s
[i
][key
] : s
[i
];
2379 return L
.NetworkModel
._get('network', this.options
.name
, key
);
2382 set: function(key
, val
)
2384 return L
.NetworkModel
._set('network', this.options
.name
, key
, val
);
2389 return this.options
.name
;
2392 protocol: function()
2394 return (this.get('proto') || 'none');
2399 return (this._status('up') === true);
2402 isVirtual: function()
2404 return (typeof(this.options
.sid
) != 'string');
2407 getProtocol: function()
2409 var prname
= this.get('proto') || 'none';
2410 return L
.NetworkModel
._protos
[prname
] || L
.NetworkModel
._protos
.none
;
2413 getUptime: function()
2415 var uptime
= this._status('uptime');
2416 return isNaN(uptime
) ? 0 : uptime
;
2419 getDevice: function(resolveAlias
)
2421 if (this.options
.l3dev
)
2422 return L
.NetworkModel
.getDevice(this.options
.l3dev
);
2427 getPhysdev: function()
2429 if (this.options
.l2dev
)
2430 return L
.NetworkModel
.getDevice(this.options
.l2dev
);
2435 getSubdevices: function()
2438 var dev
= this.options
.l2dev
?
2439 L
.NetworkModel
._devs
[this.options
.l2dev
] : undefined;
2441 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
&& dev
.ports
.length
)
2442 for (var i
= 0; i
< dev
.ports
.length
; i
++)
2443 rv
.push(L
.NetworkModel
.getDevice(dev
.ports
[i
]));
2448 getIPv4Addrs: function(mask
)
2451 var addrs
= this._status('ipv4-address');
2454 for (var i
= 0; i
< addrs
.length
; i
++)
2456 rv
.push(addrs
[i
].address
);
2458 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2463 getIPv6Addrs: function(mask
)
2468 addrs
= this._status('ipv6-address');
2471 for (var i
= 0; i
< addrs
.length
; i
++)
2473 rv
.push(addrs
[i
].address
);
2475 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2477 addrs
= this._status('ipv6-prefix-assignment');
2480 for (var i
= 0; i
< addrs
.length
; i
++)
2482 rv
.push('%s1'.format(addrs
[i
].address
));
2484 rv
.push('%s1/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2489 getDNSAddrs: function()
2492 var addrs
= this._status('dns-server');
2495 for (var i
= 0; i
< addrs
.length
; i
++)
2501 getIPv4DNS: function()
2504 var dns
= this._status('dns-server');
2507 for (var i
= 0; i
< dns
.length
; i
++)
2508 if (dns
[i
].indexOf(':') == -1)
2514 getIPv6DNS: function()
2517 var dns
= this._status('dns-server');
2520 for (var i
= 0; i
< dns
.length
; i
++)
2521 if (dns
[i
].indexOf(':') > -1)
2527 getIPv4Gateway: function()
2529 var rt
= this._status('route');
2532 for (var i
= 0; i
< rt
.length
; i
++)
2533 if (rt
[i
].target
== '0.0.0.0' && rt
[i
].mask
== 0)
2534 return rt
[i
].nexthop
;
2539 getIPv6Gateway: function()
2541 var rt
= this._status('route');
2544 for (var i
= 0; i
< rt
.length
; i
++)
2545 if (rt
[i
].target
== '::' && rt
[i
].mask
== 0)
2546 return rt
[i
].nexthop
;
2551 getStatistics: function()
2553 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2554 return dev
.getStatistics();
2557 getTrafficHistory: function()
2559 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2560 return dev
.getTrafficHistory();
2563 setDevices: function(devs
)
2565 var dev
= this.getPhysdev();
2567 var changed
= false;
2569 if (dev
&& dev
.isBridge())
2570 old_devs
= this.getSubdevices();
2574 if (old_devs
.length
!= devs
.length
)
2577 for (var i
= 0; i
< old_devs
.length
; i
++)
2581 if (dev
instanceof L
.NetworkModel
.Device
)
2584 if (!dev
|| old_devs
[i
].name() != dev
)
2593 for (var i
= 0; i
< old_devs
.length
; i
++)
2594 old_devs
[i
].removeFromInterface(this);
2596 for (var i
= 0; i
< devs
.length
; i
++)
2600 if (!(dev
instanceof L
.NetworkModel
.Device
))
2601 dev
= L
.NetworkModel
.getDevice(dev
);
2604 dev
.attachToInterface(this);
2609 changeProtocol: function(proto
)
2611 var pr
= L
.NetworkModel
._protos
[proto
];
2616 for (var opt
in (this.get() || { }))
2624 this.set(opt
, undefined);
2632 this.set(opt
, pr
.protocol
);
2636 this.set(opt
, undefined);
2642 createForm: function(mapwidget
)
2645 var proto
= self
.getProtocol();
2646 var device
= self
.getDevice();
2649 mapwidget
= L
.cbi
.Map
;
2651 var map
= new mapwidget('network', {
2652 caption
: L
.tr('Configure "%s"').format(self
.name())
2655 var section
= map
.section(L
.cbi
.SingleSection
, self
.name(), {
2661 caption
: L
.tr('General Settings')
2666 caption
: L
.tr('Advanced Settings')
2671 caption
: L
.tr('IPv6')
2676 caption
: L
.tr('Physical Settings')
2680 section
.taboption('general', L
.cbi
.CheckboxValue
, 'auto', {
2681 caption
: L
.tr('Start on boot'),
2686 var pr
= section
.taboption('general', L
.cbi
.ListValue
, 'proto', {
2687 caption
: L
.tr('Protocol')
2690 pr
.ucivalue = function(sid
) {
2691 return self
.get('proto') || 'none';
2694 var ok
= section
.taboption('general', L
.cbi
.ButtonValue
, '_confirm', {
2695 caption
: L
.tr('Really switch?'),
2696 description
: L
.tr('Changing the protocol will clear all configuration for this interface!'),
2697 text
: L
.tr('Change protocol')
2700 ok
.on('click', function(ev
) {
2701 self
.changeProtocol(pr
.formvalue(ev
.data
.sid
));
2702 self
.createForm(mapwidget
).show();
2705 var protos
= L
.NetworkModel
.getProtocols();
2707 for (var i
= 0; i
< protos
.length
; i
++)
2708 pr
.value(protos
[i
].name
, protos
[i
].description
);
2710 proto
.populateForm(section
, self
);
2714 var br
= section
.taboption('physical', L
.cbi
.CheckboxValue
, 'type', {
2715 caption
: L
.tr('Network bridge'),
2716 description
: L
.tr('Merges multiple devices into one logical bridge'),
2723 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_multi', {
2724 caption
: L
.tr('Devices'),
2727 }).depends('type', true);
2729 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_single', {
2730 caption
: L
.tr('Device'),
2733 }).depends('type', false);
2735 var mac
= section
.taboption('physical', L
.cbi
.InputValue
, 'macaddr', {
2736 caption
: L
.tr('Override MAC'),
2738 placeholder
: device
? device
.getMACAddress() : undefined,
2742 mac
.ucivalue = function(sid
)
2745 return device
.get('macaddr');
2747 return this.callSuper('ucivalue', sid
);
2750 mac
.save = function(sid
)
2752 if (!this.changed(sid
))
2756 device
.set('macaddr', this.formvalue(sid
));
2758 this.callSuper('set', sid
);
2764 section
.taboption('physical', L
.cbi
.InputValue
, 'mtu', {
2765 caption
: L
.tr('Override MTU'),
2767 placeholder
: device
? device
.getMTU() : undefined,
2768 datatype
: 'range(1, 9000)'
2771 section
.taboption('physical', L
.cbi
.InputValue
, 'metric', {
2772 caption
: L
.tr('Override Metric'),
2775 datatype
: 'uinteger'
2778 for (var field
in section
.fields
)
2786 for (var i
= 0; i
< protos
.length
; i
++)
2787 if (protos
[i
].name
!= (this.get('proto') || 'none'))
2788 section
.fields
[field
].depends('proto', protos
[i
].name
);
2792 section
.fields
[field
].depends('proto', this.get('proto') || 'none', true);
2801 this.NetworkModel
.Protocol
= this.NetworkModel
.Interface
.extend({
2802 description
: '__unknown__',
2806 populateForm: function(section
, iface
)
2813 getSystemInfo
: L
.rpc
.declare({
2819 getBoardInfo
: L
.rpc
.declare({
2825 getDiskInfo
: L
.rpc
.declare({
2826 object
: 'luci2.system',
2831 getInfo: function(cb
)
2835 this.getSystemInfo();
2836 this.getBoardInfo();
2839 return L
.rpc
.flush().then(function(info
) {
2842 $.extend(rv
, info
[0]);
2843 $.extend(rv
, info
[1]);
2844 $.extend(rv
, info
[2]);
2851 initList
: L
.rpc
.declare({
2852 object
: 'luci2.system',
2853 method
: 'init_list',
2854 expect
: { initscripts
: [ ] },
2855 filter: function(data
) {
2856 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
2861 initEnabled: function(init
, cb
)
2863 return this.initList().then(function(list
) {
2864 for (var i
= 0; i
< list
.length
; i
++)
2865 if (list
[i
].name
== init
)
2866 return !!list
[i
].enabled
;
2872 initRun
: L
.rpc
.declare({
2873 object
: 'luci2.system',
2874 method
: 'init_action',
2875 params
: [ 'name', 'action' ],
2876 filter: function(data
) {
2881 initStart: function(init
, cb
) { return L
.system
.initRun(init
, 'start', cb
) },
2882 initStop: function(init
, cb
) { return L
.system
.initRun(init
, 'stop', cb
) },
2883 initRestart: function(init
, cb
) { return L
.system
.initRun(init
, 'restart', cb
) },
2884 initReload: function(init
, cb
) { return L
.system
.initRun(init
, 'reload', cb
) },
2885 initEnable: function(init
, cb
) { return L
.system
.initRun(init
, 'enable', cb
) },
2886 initDisable: function(init
, cb
) { return L
.system
.initRun(init
, 'disable', cb
) },
2889 performReboot
: L
.rpc
.declare({
2890 object
: 'luci2.system',
2897 login
: L
.rpc
.declare({
2900 params
: [ 'username', 'password' ],
2904 access
: L
.rpc
.declare({
2907 params
: [ 'scope', 'object', 'function' ],
2908 expect
: { access
: false }
2913 return L
.session
.access('ubus', 'session', 'access');
2916 startHeartbeat: function()
2918 this._hearbeatInterval
= window
.setInterval(function() {
2919 L
.session
.isAlive().then(function(alive
) {
2922 L
.session
.stopHeartbeat();
2927 }, L
.globals
.timeout
* 2);
2930 stopHeartbeat: function()
2932 if (typeof(this._hearbeatInterval
) != 'undefined')
2934 window
.clearInterval(this._hearbeatInterval
);
2935 delete this._hearbeatInterval
;
2942 _fetch_acls
: L
.rpc
.declare({
2948 _fetch_acls_cb: function(acls
)
2950 L
.session
._acls
= acls
;
2953 updateACLs: function()
2955 return L
.session
._fetch_acls()
2956 .then(L
.session
._fetch_acls_cb
);
2959 hasACL: function(scope
, object
, func
)
2961 var acls
= L
.session
._acls
;
2963 if (typeof(func
) == 'undefined')
2964 return (acls
&& acls
[scope
] && acls
[scope
][object
]);
2966 if (acls
&& acls
[scope
] && acls
[scope
][object
])
2967 for (var i
= 0; i
< acls
[scope
][object
].length
; i
++)
2968 if (acls
[scope
][object
][i
] == func
)
2977 saveScrollTop: function()
2979 this._scroll_top
= $(document
).scrollTop();
2982 restoreScrollTop: function()
2984 if (typeof(this._scroll_top
) == 'undefined')
2987 $(document
).scrollTop(this._scroll_top
);
2989 delete this._scroll_top
;
2992 loading: function(enable
)
2994 var win
= $(window
);
2995 var body
= $('body');
2997 var state
= L
.ui
._loading
|| (L
.ui
._loading
= {
2999 .css('z-index', 2000)
3000 .addClass('modal fade')
3001 .append($('<div />')
3002 .addClass('modal-dialog')
3003 .append($('<div />')
3004 .addClass('modal-content luci2-modal-loader')
3005 .append($('<div />')
3006 .addClass('modal-body')
3007 .text(L
.tr('Loading data…')))))
3015 state
.modal
.modal(enable
? 'show' : 'hide');
3018 dialog: function(title
, content
, options
)
3020 var win
= $(window
);
3021 var body
= $('body');
3023 var state
= L
.ui
._dialog
|| (L
.ui
._dialog
= {
3024 dialog
: $('<div />')
3025 .addClass('modal fade')
3026 .append($('<div />')
3027 .addClass('modal-dialog')
3028 .append($('<div />')
3029 .addClass('modal-content')
3030 .append($('<div />')
3031 .addClass('modal-header')
3033 .addClass('modal-title'))
3034 .append($('<div />')
3035 .addClass('modal-body'))
3036 .append($('<div />')
3037 .addClass('modal-footer')
3038 .append(L
.ui
.button(L
.tr('Close'), 'primary')
3040 $(this).parents('div.modal').modal('hide');
3045 if (typeof(options
) != 'object')
3048 if (title
=== false)
3050 state
.dialog
.modal('hide');
3052 return state
.dialog
;
3055 var cnt
= state
.dialog
.children().children().children('div.modal-body');
3056 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
3060 if (options
.style
== 'confirm')
3062 ftr
.append(L
.ui
.button(L
.tr('Ok'), 'primary')
3063 .click(options
.confirm
|| function() { L
.ui
.dialog(false) }));
3065 ftr
.append(L
.ui
.button(L
.tr('Cancel'), 'default')
3066 .click(options
.cancel
|| function() { L
.ui
.dialog(false) }));
3068 else if (options
.style
== 'close')
3070 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3071 .click(options
.close
|| function() { L
.ui
.dialog(false) }));
3073 else if (options
.style
== 'wait')
3075 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3076 .attr('disabled', true));
3081 state
.dialog
.addClass('wide');
3085 state
.dialog
.removeClass('wide');
3088 state
.dialog
.find('h4:first').text(title
);
3089 state
.dialog
.modal('show');
3091 cnt
.empty().append(content
);
3093 return state
.dialog
;
3096 upload: function(title
, content
, options
)
3098 var state
= L
.ui
._upload
|| (L
.ui
._upload
= {
3100 .attr('method', 'post')
3101 .attr('action', '/cgi-bin/luci-upload')
3102 .attr('enctype', 'multipart/form-data')
3103 .attr('target', 'cbi-fileupload-frame')
3105 .append($('<input />')
3106 .attr('type', 'hidden')
3107 .attr('name', 'sessionid'))
3108 .append($('<input />')
3109 .attr('type', 'hidden')
3110 .attr('name', 'filename'))
3111 .append($('<input />')
3112 .attr('type', 'file')
3113 .attr('name', 'filedata')
3114 .addClass('cbi-input-file'))
3115 .append($('<div />')
3116 .css('width', '100%')
3117 .addClass('progress progress-striped active')
3118 .append($('<div />')
3119 .addClass('progress-bar')
3120 .css('width', '100%')))
3121 .append($('<iframe />')
3122 .addClass('pull-right')
3123 .attr('name', 'cbi-fileupload-frame')
3124 .css('width', '1px')
3125 .css('height', '1px')
3126 .css('visibility', 'hidden')),
3128 finish_cb: function(ev
) {
3129 $(this).off('load');
3131 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
3132 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
3133 body
= body
.firstChild
;
3137 json
= $.parseJSON(body
.innerHTML
);
3140 message
: L
.tr('Invalid server response received'),
3141 error
: [ -1, L
.tr('Invalid data') ]
3147 L
.ui
.dialog(L
.tr('File upload'), [
3148 $('<p />').text(L
.tr('The file upload failed with the server response below:')),
3149 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
3150 $('<p />').text(L
.tr('In case of network problems try uploading the file again.'))
3151 ], { style
: 'close' });
3153 else if (typeof(state
.success_cb
) == 'function')
3155 state
.success_cb(json
);
3159 confirm_cb: function() {
3160 var f
= state
.form
.find('.cbi-input-file');
3161 var b
= state
.form
.find('.progress');
3162 var p
= state
.form
.find('p');
3167 state
.form
.find('iframe').on('load', state
.finish_cb
);
3168 state
.form
.submit();
3172 p
.text(L
.tr('File upload in progress …'));
3174 state
.form
.parent().parent().find('button').prop('disabled', true);
3178 state
.form
.find('.progress').hide();
3179 state
.form
.find('.cbi-input-file').val('').show();
3180 state
.form
.find('p').text(content
|| L
.tr('Select the file to upload and press "%s" to proceed.').format(L
.tr('Ok')));
3182 state
.form
.find('[name=sessionid]').val(L
.globals
.sid
);
3183 state
.form
.find('[name=filename]').val(options
.filename
);
3185 state
.success_cb
= options
.success
;
3187 L
.ui
.dialog(title
|| L
.tr('File upload'), state
.form
, {
3189 confirm
: state
.confirm_cb
3193 reconnect: function()
3195 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3196 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
3197 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
3199 var interval
, timeout
;
3202 L
.tr('Waiting for device'), [
3203 $('<p />').text(L
.tr('Please stand by while the device is reconfiguring …')),
3205 .css('width', '100%')
3206 .addClass('progressbar')
3207 .addClass('intermediate')
3208 .append($('<div />')
3209 .css('width', '100%'))
3210 ], { style
: 'wait' }
3213 for (var i
= 0; i
< protocols
.length
; i
++)
3214 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
3216 //L.network.getNetworkStatus(function(s) {
3217 // for (var i = 0; i < protocols.length; i++)
3219 // for (var j = 0; j < s.length; j++)
3221 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3222 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3224 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3225 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3228 //}).then(function() {
3229 images
.on('load', function() {
3230 var url
= this.getAttribute('url');
3231 L
.session
.isAlive().then(function(access
) {
3234 window
.clearTimeout(timeout
);
3235 window
.clearInterval(interval
);
3241 location
.href
= url
;
3246 interval
= window
.setInterval(function() {
3247 images
.each(function() {
3248 this.setAttribute('src', this.getAttribute('url') + L
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
3252 timeout
= window
.setTimeout(function() {
3253 window
.clearInterval(interval
);
3257 L
.tr('Device not responding'),
3258 L
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3265 login: function(invalid
)
3267 var state
= L
.ui
._login
|| (L
.ui
._login
= {
3270 .attr('method', 'post')
3272 .addClass('alert-message')
3273 .text(L
.tr('Wrong username or password given!')))
3275 .append($('<label />')
3276 .text(L
.tr('Username'))
3277 .append($('<br />'))
3278 .append($('<input />')
3279 .attr('type', 'text')
3280 .attr('name', 'username')
3281 .attr('value', 'root')
3282 .addClass('form-control')
3283 .keypress(function(ev
) {
3284 if (ev
.which
== 10 || ev
.which
== 13)
3288 .append($('<label />')
3289 .text(L
.tr('Password'))
3290 .append($('<br />'))
3291 .append($('<input />')
3292 .attr('type', 'password')
3293 .attr('name', 'password')
3294 .addClass('form-control')
3295 .keypress(function(ev
) {
3296 if (ev
.which
== 10 || ev
.which
== 13)
3300 .text(L
.tr('Enter your username and password above, then click "%s" to proceed.').format(L
.tr('Ok')))),
3302 response_cb: function(response
) {
3303 if (!response
.ubus_rpc_session
)
3309 L
.globals
.sid
= response
.ubus_rpc_session
;
3310 L
.setHash('id', L
.globals
.sid
);
3311 L
.session
.startHeartbeat();
3313 state
.deferred
.resolve();
3317 confirm_cb: function() {
3318 var u
= state
.form
.find('[name=username]').val();
3319 var p
= state
.form
.find('[name=password]').val();
3325 L
.tr('Logging in'), [
3326 $('<p />').text(L
.tr('Log in in progress …')),
3328 .css('width', '100%')
3329 .addClass('progressbar')
3330 .addClass('intermediate')
3331 .append($('<div />')
3332 .css('width', '100%'))
3333 ], { style
: 'wait' }
3336 L
.globals
.sid
= '00000000000000000000000000000000';
3337 L
.session
.login(u
, p
).then(state
.response_cb
);
3341 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
3342 state
.deferred
= $.Deferred();
3344 /* try to find sid from hash */
3345 var sid
= L
.getHash('id');
3346 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
3348 L
.globals
.sid
= sid
;
3349 L
.session
.isAlive().then(function(access
) {
3352 L
.session
.startHeartbeat();
3353 state
.deferred
.resolve();
3357 L
.setHash('id', undefined);
3362 return state
.deferred
;
3366 state
.form
.find('.alert-message').show();
3368 state
.form
.find('.alert-message').hide();
3370 L
.ui
.dialog(L
.tr('Authorization Required'), state
.form
, {
3372 confirm
: state
.confirm_cb
3375 state
.form
.find('[name=password]').focus();
3377 return state
.deferred
;
3380 cryptPassword
: L
.rpc
.declare({
3384 expect
: { crypt
: '' }
3388 _acl_merge_scope: function(acl_scope
, scope
)
3390 if ($.isArray(scope
))
3392 for (var i
= 0; i
< scope
.length
; i
++)
3393 acl_scope
[scope
[i
]] = true;
3395 else if ($.isPlainObject(scope
))
3397 for (var object_name
in scope
)
3399 if (!$.isArray(scope
[object_name
]))
3402 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
3404 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
3405 acl_object
[scope
[object_name
][i
]] = true;
3410 _acl_merge_permission: function(acl_perm
, perm
)
3412 if ($.isPlainObject(perm
))
3414 for (var scope_name
in perm
)
3416 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
3417 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
3422 _acl_merge_group: function(acl_group
, group
)
3424 if ($.isPlainObject(group
))
3426 if (!acl_group
.description
)
3427 acl_group
.description
= group
.description
;
3431 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
3432 this._acl_merge_permission(acl_perm
, group
.read
);
3437 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
3438 this._acl_merge_permission(acl_perm
, group
.write
);
3443 _acl_merge_tree: function(acl_tree
, tree
)
3445 if ($.isPlainObject(tree
))
3447 for (var group_name
in tree
)
3449 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
3450 this._acl_merge_group(acl_group
, tree
[group_name
]);
3455 listAvailableACLs
: L
.rpc
.declare({
3458 expect
: { acls
: [ ] },
3459 filter: function(trees
) {
3461 for (var i
= 0; i
< trees
.length
; i
++)
3462 L
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
3467 _render_change_indicator: function()
3470 .addClass('nav navbar-nav navbar-right')
3473 .attr('id', 'changes')
3475 .append($('<span />')
3476 .addClass('label label-info'))));
3479 renderMainMenu
: L
.rpc
.declare({
3482 expect
: { menu
: { } },
3483 filter: function(entries
) {
3484 L
.globals
.mainMenu
= new L
.ui
.menu();
3485 L
.globals
.mainMenu
.entries(entries
);
3489 .append(L
.globals
.mainMenu
.render(0, 1))
3490 .append(L
.ui
._render_change_indicator());
3494 renderViewMenu: function()
3498 .append(L
.globals
.mainMenu
.render(2, 900));
3501 renderView: function()
3503 var node
= arguments
[0];
3504 var name
= node
.view
.split(/\//).join('.');
3505 var cname
= L
.toClassName(name
);
3506 var views
= L
.views
|| (L
.views
= { });
3509 for (var i
= 1; i
< arguments
.length
; i
++)
3510 args
.push(arguments
[i
]);
3512 if (L
.globals
.currentView
)
3513 L
.globals
.currentView
.finish();
3515 L
.ui
.renderViewMenu();
3516 L
.setHash('view', node
.view
);
3518 if (views
[cname
] instanceof L
.ui
.view
)
3520 L
.globals
.currentView
= views
[cname
];
3521 return views
[cname
].render
.apply(views
[cname
], args
);
3524 var url
= L
.globals
.resource
+ '/view/' + name
+ '.js';
3526 return $.ajax(url
, {
3530 }).then(function(data
) {
3532 var viewConstructorSource
= (
3533 '(function(L, $) { ' +
3537 ).format(data
, url
);
3539 var viewConstructor
= eval(viewConstructorSource
);
3541 views
[cname
] = new viewConstructor({
3543 acls
: node
.write
|| { }
3546 L
.globals
.currentView
= views
[cname
];
3547 return views
[cname
].render
.apply(views
[cname
], args
);
3550 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
3553 return $.Deferred().resolve();
3557 changeView: function()
3559 var name
= L
.getHash('view');
3560 var node
= L
.globals
.defaultNode
;
3562 if (name
&& L
.globals
.mainMenu
)
3563 node
= L
.globals
.mainMenu
.getNode(name
);
3568 L
.ui
.renderView(node
).then(function() {
3569 L
.ui
.loading(false);
3574 updateHostname: function()
3576 return L
.system
.getBoardInfo().then(function(info
) {
3578 $('#hostname').text(info
.hostname
);
3582 updateChanges: function()
3584 return L
.uci
.changes().then(function(changes
) {
3588 for (var config
in changes
)
3592 for (var i
= 0; i
< changes
[config
].length
; i
++)
3594 var c
= changes
[config
][i
];
3599 log
.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3604 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
3606 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
3611 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
3613 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3617 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
3621 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3625 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3630 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3632 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3637 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
3638 n
+= changes
[config
].length
;
3643 .click(function(ev
) {
3644 L
.ui
.dialog(L
.tr('Staged configuration changes'), html
, {
3646 confirm: function() {
3648 function(code
) { alert('Success with code ' + code
); },
3649 function(code
) { alert('Error with code ' + code
); }
3653 ev
.preventDefault();
3657 .text(L
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
));
3659 $('#changes').children('span').hide();
3668 L
.session
.updateACLs(),
3669 L
.ui
.updateHostname(),
3670 L
.ui
.updateChanges(),
3671 L
.ui
.renderMainMenu(),
3672 L
.NetworkModel
.init()
3674 L
.ui
.renderView(L
.globals
.defaultNode
).then(function() {
3675 L
.ui
.loading(false);
3678 $(window
).on('hashchange', function() {
3684 button: function(label
, style
, title
)
3686 style
= style
|| 'default';
3688 return $('<button />')
3689 .attr('type', 'button')
3690 .attr('title', title
? title
: '')
3691 .addClass('btn btn-' + style
)
3696 this.ui
.AbstractWidget
= Class
.extend({
3697 i18n: function(text
) {
3702 var key
= arguments
[0];
3705 for (var i
= 1; i
< arguments
.length
; i
++)
3706 args
.push(arguments
[i
]);
3708 switch (typeof(this.options
[key
]))
3714 return this.options
[key
].apply(this, args
);
3717 return ''.format
.apply('' + this.options
[key
], args
);
3721 toString: function() {
3722 return $('<div />').append(this.render()).html();
3725 insertInto: function(id
) {
3726 return $(id
).empty().append(this.render());
3729 appendTo: function(id
) {
3730 return $(id
).append(this.render());
3733 on: function(evname
, evfunc
)
3735 var evnames
= L
.toArray(evname
);
3740 for (var i
= 0; i
< evnames
.length
; i
++)
3741 this.events
[evnames
[i
]] = evfunc
;
3746 trigger: function(evname
, evdata
)
3750 var evnames
= L
.toArray(evname
);
3752 for (var i
= 0; i
< evnames
.length
; i
++)
3753 if (this.events
[evnames
[i
]])
3754 this.events
[evnames
[i
]].call(this, evdata
);
3761 this.ui
.view
= this.ui
.AbstractWidget
.extend({
3762 _fetch_template: function()
3764 return $.ajax(L
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
3768 success: function(data
) {
3769 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
3770 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
3780 return L
.globals
[p2
] || '';
3783 return '(?' + match
+ ')';
3787 $('#maincontent').append(data
);
3794 throw "Not implemented";
3799 var container
= $('#maincontent');
3804 container
.append($('<h2 />').append(this.title
));
3806 if (this.description
)
3807 container
.append($('<p />').append(this.description
));
3812 for (var i
= 0; i
< arguments
.length
; i
++)
3813 args
.push(arguments
[i
]);
3815 return this._fetch_template().then(function() {
3816 return L
.deferrable(self
.execute
.apply(self
, args
));
3820 repeat: function(func
, interval
)
3824 if (!self
._timeouts
)
3825 self
._timeouts
= [ ];
3827 var index
= self
._timeouts
.length
;
3829 if (typeof(interval
) != 'number')
3832 var setTimer
, runTimer
;
3834 setTimer = function() {
3836 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
3839 runTimer = function() {
3840 L
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
3848 if ($.isArray(this._timeouts
))
3850 for (var i
= 0; i
< this._timeouts
.length
; i
++)
3851 window
.clearTimeout(this._timeouts
[i
]);
3853 delete this._timeouts
;
3858 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
3863 entries: function(entries
)
3865 for (var entry
in entries
)
3867 var path
= entry
.split(/\//);
3868 var node
= this._nodes
;
3870 for (i
= 0; i
< path
.length
; i
++)
3875 if (!node
.childs
[path
[i
]])
3876 node
.childs
[path
[i
]] = { };
3878 node
= node
.childs
[path
[i
]];
3881 $.extend(node
, entries
[entry
]);
3885 _indexcmp: function(a
, b
)
3887 var x
= a
.index
|| 0;
3888 var y
= b
.index
|| 0;
3892 firstChildView: function(node
)
3898 for (var child
in (node
.childs
|| { }))
3899 nodes
.push(node
.childs
[child
]);
3901 nodes
.sort(this._indexcmp
);
3903 for (var i
= 0; i
< nodes
.length
; i
++)
3905 var child
= this.firstChildView(nodes
[i
]);
3908 for (var key
in child
)
3909 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
3910 node
[key
] = child
[key
];
3919 _onclick: function(ev
)
3921 L
.setHash('view', ev
.data
);
3923 ev
.preventDefault();
3927 _render: function(childs
, level
, min
, max
)
3930 for (var node
in childs
)
3932 var child
= this.firstChildView(childs
[node
]);
3934 nodes
.push(childs
[node
]);
3937 nodes
.sort(this._indexcmp
);
3939 var list
= $('<ul />');
3942 list
.addClass('nav').addClass('navbar-nav');
3943 else if (level
== 1)
3944 list
.addClass('dropdown-menu').addClass('navbar-inverse');
3946 for (var i
= 0; i
< nodes
.length
; i
++)
3948 if (!L
.globals
.defaultNode
)
3950 var v
= L
.getHash('view');
3951 if (!v
|| v
== nodes
[i
].view
)
3952 L
.globals
.defaultNode
= nodes
[i
];
3955 var item
= $('<li />')
3958 .text(L
.tr(nodes
[i
].title
)))
3961 if (nodes
[i
].childs
&& level
< max
)
3963 item
.addClass('dropdown');
3966 .addClass('dropdown-toggle')
3967 .attr('data-toggle', 'dropdown')
3968 .append('<b class="caret"></b>');
3970 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
3974 item
.find('a').click(nodes
[i
].view
, this._onclick
);
3981 render: function(min
, max
)
3983 var top
= min
? this.getNode(L
.globals
.defaultNode
.view
, min
) : this._nodes
;
3984 return this._render(top
.childs
, 0, min
, max
);
3987 getNode: function(path
, max
)
3989 var p
= path
.split(/\//);
3990 var n
= this._nodes
;
3992 if (typeof(max
) == 'undefined')
3995 for (var i
= 0; i
< max
; i
++)
3997 if (!n
.childs
[p
[i
]])
4007 this.ui
.table
= this.ui
.AbstractWidget
.extend({
4013 row: function(values
)
4015 if ($.isArray(values
))
4017 this._rows
.push(values
);
4019 else if ($.isPlainObject(values
))
4022 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4024 var col
= this.options
.columns
[i
];
4026 if (typeof col
.key
== 'string')
4027 v
.push(values
[col
.key
]);
4035 rows: function(rows
)
4037 for (var i
= 0; i
< rows
.length
; i
++)
4041 render: function(id
)
4043 var fieldset
= document
.createElement('fieldset');
4044 fieldset
.className
= 'cbi-section';
4046 if (this.options
.caption
)
4048 var legend
= document
.createElement('legend');
4049 $(legend
).append(this.options
.caption
);
4050 fieldset
.appendChild(legend
);
4053 var table
= document
.createElement('table');
4054 table
.className
= 'table table-condensed table-hover';
4056 var has_caption
= false;
4057 var has_description
= false;
4059 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4060 if (this.options
.columns
[i
].caption
)
4065 else if (this.options
.columns
[i
].description
)
4067 has_description
= true;
4073 var tr
= table
.insertRow(-1);
4074 tr
.className
= 'cbi-section-table-titles';
4076 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4078 var col
= this.options
.columns
[i
];
4079 var th
= document
.createElement('th');
4080 th
.className
= 'cbi-section-table-cell';
4085 th
.style
.width
= col
.width
;
4088 th
.style
.textAlign
= col
.align
;
4091 $(th
).append(col
.caption
);
4095 if (has_description
)
4097 var tr
= table
.insertRow(-1);
4098 tr
.className
= 'cbi-section-table-descr';
4100 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4102 var col
= this.options
.columns
[i
];
4103 var th
= document
.createElement('th');
4104 th
.className
= 'cbi-section-table-cell';
4109 th
.style
.width
= col
.width
;
4112 th
.style
.textAlign
= col
.align
;
4114 if (col
.description
)
4115 $(th
).append(col
.description
);
4119 if (this._rows
.length
== 0)
4121 if (this.options
.placeholder
)
4123 var tr
= table
.insertRow(-1);
4124 var td
= tr
.insertCell(-1);
4125 td
.className
= 'cbi-section-table-cell';
4127 td
.colSpan
= this.options
.columns
.length
;
4128 $(td
).append(this.options
.placeholder
);
4133 for (var i
= 0; i
< this._rows
.length
; i
++)
4135 var tr
= table
.insertRow(-1);
4137 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
4139 var col
= this.options
.columns
[j
];
4140 var td
= tr
.insertCell(-1);
4142 var val
= this._rows
[i
][j
];
4144 if (typeof(val
) == 'undefined')
4145 val
= col
.placeholder
;
4147 if (typeof(val
) == 'undefined')
4151 td
.style
.width
= col
.width
;
4154 td
.style
.textAlign
= col
.align
;
4156 if (typeof col
.format
== 'string')
4157 $(td
).append(col
.format
.format(val
));
4158 else if (typeof col
.format
== 'function')
4159 $(td
).append(col
.format(val
, i
));
4167 fieldset
.appendChild(table
);
4173 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
4176 var vn
= parseInt(this.options
.value
) || 0;
4177 var mn
= parseInt(this.options
.max
) || 100;
4178 var pc
= Math
.floor((100 / mn
) * vn
);
4182 if (typeof(this.options
.format
) == 'string')
4183 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
4184 else if (typeof(this.options
.format
) == 'function')
4185 text
= this.options
.format(pc
);
4187 text
= '%.2f%%'.format(pc
);
4190 .addClass('progress')
4191 .append($('<div />')
4192 .addClass('progress-bar')
4193 .addClass('progress-bar-info')
4194 .css('width', pc
+ '%'))
4195 .append($('<small />')
4200 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
4203 var l2dev
= this.options
.l2_device
|| this.options
.device
;
4204 var l3dev
= this.options
.l3_device
;
4205 var dev
= l3dev
|| l2dev
|| '?';
4207 var span
= document
.createElement('span');
4208 span
.className
= 'badge';
4210 if (typeof(this.options
.signal
) == 'number' ||
4211 typeof(this.options
.noise
) == 'number')
4214 if (typeof(this.options
.signal
) != 'undefined' &&
4215 typeof(this.options
.noise
) != 'undefined')
4217 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
4230 span
.appendChild(document
.createElement('img'));
4231 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
4234 span
.title
= L
.tr('No signal');
4236 span
.title
= '%s: %d %s / %s: %d %s'.format(
4237 L
.tr('Signal'), this.options
.signal
, L
.tr('dBm'),
4238 L
.tr('Noise'), this.options
.noise
, L
.tr('dBm')
4243 var type
= 'ethernet';
4244 var desc
= L
.tr('Ethernet device');
4249 desc
= L
.tr('Tunnel interface');
4251 else if (dev
.indexOf('br-') == 0)
4254 desc
= L
.tr('Bridge');
4256 else if (dev
.indexOf('.') > 0)
4259 desc
= L
.tr('VLAN interface');
4261 else if (dev
.indexOf('wlan') == 0 ||
4262 dev
.indexOf('ath') == 0 ||
4263 dev
.indexOf('wl') == 0)
4266 desc
= L
.tr('Wireless Network');
4269 span
.appendChild(document
.createElement('img'));
4270 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
4274 $(span
).append(' ');
4275 $(span
).append(dev
);
4281 var type = function(f
, l
)
4291 L
.cbi
.validation
.message
= L
.tr(msg
);
4294 compile: function(code
)
4299 var types
= L
.cbi
.validation
.types
;
4304 for (var i
= 0; i
< code
.length
; i
++)
4312 switch (code
.charCodeAt(i
))
4324 var label
= code
.substring(pos
, i
);
4325 label
= label
.replace(/\\(.)/g, '$1');
4326 label
= label
.replace(/^[ \t]+/g, '');
4327 label
= label
.replace(/[ \t]+$/g, '');
4329 if (label
&& !isNaN(label
))
4331 stack
.push(parseFloat(label
));
4333 else if (label
.match(/^(['"]).*\1$/))
4335 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
4337 else if (typeof types
[label
] == 'function')
4339 stack
.push(types
[label
]);
4344 throw "Syntax error, unhandled token '"+label
+"'";
4349 depth
+= (code
.charCodeAt(i
) == 40);
4355 if (typeof stack
[stack
.length
-2] != 'function')
4356 throw "Syntax error, argument list follows non-function";
4358 stack
[stack
.length
-1] =
4359 L
.cbi
.validation
.compile(code
.substring(pos
, i
));
4372 var validation
= this.cbi
.validation
;
4374 validation
.types
= {
4375 'integer': function()
4377 if (this.match(/^-?[0-9]+$/) != null)
4380 validation
.i18n('Must be a valid integer');
4384 'uinteger': function()
4386 if (validation
.types
['integer'].apply(this) && (this >= 0))
4389 validation
.i18n('Must be a positive integer');
4395 if (!isNaN(parseFloat(this)))
4398 validation
.i18n('Must be a valid number');
4402 'ufloat': function()
4404 if (validation
.types
['float'].apply(this) && (this >= 0))
4407 validation
.i18n('Must be a positive number');
4411 'ipaddr': function()
4413 if (validation
.types
['ip4addr'].apply(this) ||
4414 validation
.types
['ip6addr'].apply(this))
4417 validation
.i18n('Must be a valid IP address');
4421 'ip4addr': function()
4423 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
4425 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
4426 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
4427 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
4428 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
4429 ((RegExp
.$6.indexOf('.') < 0)
4430 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
4431 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
4435 validation
.i18n('Must be a valid IPv4 address');
4439 'ip6addr': function()
4441 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
4443 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
4445 var addr
= RegExp
.$1;
4452 if (addr
.indexOf('.') > 0)
4454 var off
= addr
.lastIndexOf(':');
4456 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
4458 validation
.i18n('Must be a valid IPv6 address');
4462 addr
= addr
.substr(0, off
) + ':0:0';
4465 if (addr
.indexOf('::') >= 0)
4470 for (var i
= 1; i
< (addr
.length
-1); i
++)
4471 if (addr
.charAt(i
) == ':')
4476 validation
.i18n('Must be a valid IPv6 address');
4480 for (var i
= 0; i
< (7 - colons
); i
++)
4483 if (addr
.match(/^(.*?)::(.*?)$/))
4484 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
4485 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
4488 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
4491 validation
.i18n('Must be a valid IPv6 address');
4496 validation
.i18n('Must be a valid IPv6 address');
4502 if (validation
.types
['integer'].apply(this) &&
4503 (this >= 0) && (this <= 65535))
4506 validation
.i18n('Must be a valid port number');
4510 'portrange': function()
4512 if (this.match(/^(\d+)-(\d+)$/))
4517 if (validation
.types
['port'].apply(p1
) &&
4518 validation
.types
['port'].apply(p2
) &&
4519 (parseInt(p1
) <= parseInt(p2
)))
4522 else if (validation
.types
['port'].apply(this))
4527 validation
.i18n('Must be a valid port range');
4531 'macaddr': function()
4533 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4536 validation
.i18n('Must be a valid MAC address');
4542 if (validation
.types
['hostname'].apply(this) ||
4543 validation
.types
['ipaddr'].apply(this))
4546 validation
.i18n('Must be a valid hostname or IP address');
4550 'hostname': function()
4552 if ((this.length
<= 253) &&
4553 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4554 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4555 this.match(/[^0-9.]/)))))
4558 validation
.i18n('Must be a valid host name');
4562 'network': function()
4564 if (validation
.types
['uciname'].apply(this) ||
4565 validation
.types
['host'].apply(this))
4568 validation
.i18n('Must be a valid network name');
4572 'wpakey': function()
4576 if ((v
.length
== 64)
4577 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
4578 : ((v
.length
>= 8) && (v
.length
<= 63)))
4581 validation
.i18n('Must be a valid WPA key');
4585 'wepkey': function()
4589 if (v
.substr(0,2) == 's:')
4592 if (((v
.length
== 10) || (v
.length
== 26))
4593 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
4594 : ((v
.length
== 5) || (v
.length
== 13)))
4597 validation
.i18n('Must be a valid WEP key');
4601 'uciname': function()
4603 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4606 validation
.i18n('Must be a valid UCI identifier');
4610 'range': function(min
, max
)
4612 var val
= parseFloat(this);
4614 if (validation
.types
['integer'].apply(this) &&
4615 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
4618 validation
.i18n('Must be a number between %d and %d');
4622 'min': function(min
)
4624 var val
= parseFloat(this);
4626 if (validation
.types
['integer'].apply(this) &&
4627 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
4630 validation
.i18n('Must be a number greater or equal to %d');
4634 'max': function(max
)
4636 var val
= parseFloat(this);
4638 if (validation
.types
['integer'].apply(this) &&
4639 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
4642 validation
.i18n('Must be a number lower or equal to %d');
4646 'rangelength': function(min
, max
)
4648 var val
= '' + this;
4650 if (!isNaN(min
) && !isNaN(max
) &&
4651 (val
.length
>= min
) && (val
.length
<= max
))
4654 validation
.i18n('Must be between %d and %d characters');
4658 'minlength': function(min
)
4660 var val
= '' + this;
4662 if (!isNaN(min
) && (val
.length
>= min
))
4665 validation
.i18n('Must be at least %d characters');
4669 'maxlength': function(max
)
4671 var val
= '' + this;
4673 if (!isNaN(max
) && (val
.length
<= max
))
4676 validation
.i18n('Must be at most %d characters');
4684 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4686 delete validation
.message
;
4688 if (typeof(arguments
[i
]) != 'function')
4690 if (arguments
[i
] == this)
4694 else if (arguments
[i
].apply(this, arguments
[i
+1]))
4699 if (validation
.message
)
4700 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4703 validation
.message
= msgs
.join( L
.tr(' - or - '));
4711 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4713 delete validation
.message
;
4715 if (typeof arguments
[i
] != 'function')
4717 if (arguments
[i
] != this)
4721 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
4726 if (validation
.message
)
4727 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4730 validation
.message
= msgs
.join(', ');
4736 return validation
.types
['or'].apply(
4737 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
4740 'list': function(subvalidator
, subargs
)
4742 if (typeof subvalidator
!= 'function')
4745 var tokens
= this.match(/[^ \t]+/g);
4746 for (var i
= 0; i
< tokens
.length
; i
++)
4747 if (!subvalidator
.apply(tokens
[i
], subargs
))
4753 'phonedigit': function()
4755 if (this.match(/^[0-9\*#!\.]+$/) != null)
4758 validation
.i18n('Must be a valid phone number digit');
4762 'string': function()
4769 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
4770 init: function(name
, options
)
4773 this.instance
= { };
4774 this.dependencies
= [ ];
4775 this.rdependency
= { };
4777 this.options
= L
.defaults(options
, {
4787 return this.section
.id('field', sid
|| '__unknown__', this.name
);
4790 render: function(sid
, condensed
)
4792 var i
= this.instance
[sid
] = { };
4794 i
.top
= $('<div />');
4798 i
.top
.addClass('form-group');
4800 if (typeof(this.options
.caption
) == 'string')
4802 .addClass('col-lg-2 control-label')
4803 .attr('for', this.id(sid
))
4804 .text(this.options
.caption
)
4808 i
.error
= $('<div />')
4810 .addClass('label label-danger');
4812 i
.widget
= $('<div />')
4814 .append(this.widget(sid
))
4820 i
.widget
.addClass('col-lg-5');
4823 .addClass('col-lg-5')
4824 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
4831 active: function(sid
)
4833 return (this.instance
[sid
] && !this.instance
[sid
].disabled
);
4836 ucipath: function(sid
)
4839 config
: (this.options
.uci_package
|| this.map
.uci_package
),
4840 section
: (this.options
.uci_section
|| sid
),
4841 option
: (this.options
.uci_option
|| this.name
)
4845 ucivalue: function(sid
)
4847 var uci
= this.ucipath(sid
);
4848 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
4850 if (typeof(val
) == 'undefined')
4851 return this.options
.initial
;
4856 formvalue: function(sid
)
4858 var v
= $('#' + this.id(sid
)).val();
4859 return (v
=== '') ? undefined : v
;
4862 textvalue: function(sid
)
4864 var v
= this.formvalue(sid
);
4866 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
4867 v
= this.ucivalue(sid
);
4869 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
4870 v
= this.options
.placeholder
;
4872 if (typeof(v
) == 'undefined' || v
=== '')
4875 if (typeof(v
) == 'string' && $.isArray(this.choices
))
4877 for (var i
= 0; i
< this.choices
.length
; i
++)
4878 if (v
=== this.choices
[i
][0])
4879 return this.choices
[i
][1];
4881 else if (v
=== true)
4883 else if (v
=== false)
4885 else if ($.isArray(v
))
4886 return v
.join(', ');
4891 changed: function(sid
)
4893 var a
= this.ucivalue(sid
);
4894 var b
= this.formvalue(sid
);
4896 if (typeof(a
) != typeof(b
))
4899 if (typeof(a
) == 'object')
4901 if (a
.length
!= b
.length
)
4904 for (var i
= 0; i
< a
.length
; i
++)
4916 var uci
= this.ucipath(sid
);
4918 if (this.instance
[sid
].disabled
)
4920 if (!this.options
.keep
)
4921 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
4926 var chg
= this.changed(sid
);
4927 var val
= this.formvalue(sid
);
4930 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
4935 _ev_validate: function(ev
)
4939 var val
= d
.elem
.val();
4940 var vstack
= d
.vstack
;
4942 if (vstack
&& typeof(vstack
[0]) == 'function')
4944 delete validation
.message
;
4946 if ((val
.length
== 0 && !d
.opt
))
4948 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
4949 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4951 d
.inst
.error
.text(L
.tr('Field must not be empty')).show();
4954 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
4956 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
4957 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
4959 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
4964 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
4965 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
4967 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
4970 d
.inst
.error
.text('').hide();
4976 for (var field
in d
.self
.rdependency
)
4977 d
.self
.rdependency
[field
].toggle(d
.sid
);
4979 d
.self
.section
.tabtoggle(d
.sid
);
4985 validator: function(sid
, elem
, multi
)
4992 inst
: this.instance
[sid
],
4993 opt
: this.options
.optional
4997 for (var evname
in this.events
)
4998 elem
.on(evname
, evdata
, this.events
[evname
]);
5000 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
5004 if (typeof(this.options
.datatype
) == 'string')
5007 evdata
.vstack
= L
.cbi
.validation
.compile(this.options
.datatype
);
5010 else if (typeof(this.options
.datatype
) == 'function')
5012 var vfunc
= this.options
.datatype
;
5013 evdata
.vstack
= [ function(elem
) {
5014 var rv
= vfunc(this, elem
);
5016 validation
.message
= rv
;
5017 return (rv
=== true);
5021 if (elem
.prop('tagName') == 'SELECT')
5023 elem
.change(evdata
, this._ev_validate
);
5025 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
5027 elem
.click(evdata
, this._ev_validate
);
5028 elem
.blur(evdata
, this._ev_validate
);
5032 elem
.keyup(evdata
, this._ev_validate
);
5033 elem
.blur(evdata
, this._ev_validate
);
5036 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
5041 validate: function(sid
)
5043 var i
= this.instance
[sid
];
5045 i
.widget
.find('[cbi-validate]').trigger('validate');
5047 return (i
.disabled
|| i
.error
.text() == '');
5050 depends: function(d
, v
, add
)
5057 for (var i
= 0; i
< d
.length
; i
++)
5059 if (typeof(d
[i
]) == 'string')
5061 else if (d
[i
] instanceof L
.cbi
.AbstractValue
)
5062 dep
[d
[i
].name
] = true;
5065 else if (d
instanceof L
.cbi
.AbstractValue
)
5068 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
5070 else if (typeof(d
) == 'object')
5074 else if (typeof(d
) == 'string')
5077 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
5080 if (!dep
|| $.isEmptyObject(dep
))
5083 for (var field
in dep
)
5085 var f
= this.section
.fields
[field
];
5087 f
.rdependency
[this.name
] = this;
5092 if ($.isEmptyObject(dep
))
5095 if (!add
|| !this.dependencies
.length
)
5096 this.dependencies
.push(dep
);
5098 for (var i
= 0; i
< this.dependencies
.length
; i
++)
5099 $.extend(this.dependencies
[i
], dep
);
5104 toggle: function(sid
)
5106 var d
= this.dependencies
;
5107 var i
= this.instance
[sid
];
5112 for (var n
= 0; n
< d
.length
; n
++)
5116 for (var field
in d
[n
])
5118 var val
= this.section
.fields
[field
].formvalue(sid
);
5119 var cmp
= d
[n
][field
];
5121 if (typeof(cmp
) == 'boolean')
5123 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
5129 else if (typeof(cmp
) == 'string' || typeof(cmp
) == 'number')
5137 else if (typeof(cmp
) == 'function')
5145 else if (cmp
instanceof RegExp
)
5170 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
5177 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
5178 widget: function(sid
)
5180 var o
= this.options
;
5182 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
5183 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
5185 var i
= $('<input />')
5186 .attr('id', this.id(sid
))
5187 .attr('type', 'checkbox')
5188 .prop('checked', this.ucivalue(sid
));
5191 .addClass('checkbox')
5192 .append(this.validator(sid
, i
));
5195 ucivalue: function(sid
)
5197 var v
= this.callSuper('ucivalue', sid
);
5199 if (typeof(v
) == 'boolean')
5202 return (v
== this.options
.enabled
);
5205 formvalue: function(sid
)
5207 var v
= $('#' + this.id(sid
)).prop('checked');
5209 if (typeof(v
) == 'undefined')
5210 return !!this.options
.initial
;
5217 var uci
= this.ucipath(sid
);
5219 if (this.instance
[sid
].disabled
)
5221 if (!this.options
.keep
)
5222 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5227 var chg
= this.changed(sid
);
5228 var val
= this.formvalue(sid
);
5232 if (this.options
.optional
&& val
== this.options
.initial
)
5233 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5235 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
5242 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
5243 widget: function(sid
)
5245 var i
= $('<input />')
5246 .addClass('form-control')
5247 .attr('id', this.id(sid
))
5248 .attr('type', 'text')
5249 .attr('placeholder', this.options
.placeholder
)
5250 .val(this.ucivalue(sid
));
5252 return this.validator(sid
, i
);
5256 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
5257 widget: function(sid
)
5259 var i
= $('<input />')
5260 .addClass('form-control')
5261 .attr('id', this.id(sid
))
5262 .attr('type', 'password')
5263 .attr('placeholder', this.options
.placeholder
)
5264 .val(this.ucivalue(sid
));
5266 var t
= $('<span />')
5267 .addClass('input-group-btn')
5268 .append(L
.ui
.button(L
.tr('Reveal'), 'default')
5269 .click(function(ev
) {
5271 var i
= b
.parent().prev();
5272 var t
= i
.attr('type');
5273 b
.text(t
== 'password' ? L
.tr('Hide') : L
.tr('Reveal'));
5274 i
.attr('type', (t
== 'password') ? 'text' : 'password');
5278 this.validator(sid
, i
);
5281 .addClass('input-group')
5287 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
5288 widget: function(sid
)
5290 var s
= $('<select />')
5291 .addClass('form-control');
5293 if (this.options
.optional
&& !this.has_empty
)
5296 .text(L
.tr('-- Please choose --'))
5300 for (var i
= 0; i
< this.choices
.length
; i
++)
5302 .attr('value', this.choices
[i
][0])
5303 .text(this.choices
[i
][1])
5306 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
5308 return this.validator(sid
, s
);
5311 value: function(k
, v
)
5317 this.has_empty
= true;
5319 this.choices
.push([k
, v
|| k
]);
5324 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
5325 widget: function(sid
)
5327 var v
= this.ucivalue(sid
);
5328 var t
= $('<div />').attr('id', this.id(sid
));
5331 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5334 for (var i
= 0; i
< v
.length
; i
++)
5338 for (var i
= 0; i
< this.choices
.length
; i
++)
5341 .addClass('checkbox')
5342 .append($('<input />')
5343 .attr('type', 'checkbox')
5344 .attr('value', this.choices
[i
][0])
5345 .prop('checked', s
[this.choices
[i
][0]]))
5346 .append(this.choices
[i
][1])
5353 formvalue: function(sid
)
5356 var fields
= $('#' + this.id(sid
) + ' > label > input');
5358 for (var i
= 0; i
< fields
.length
; i
++)
5359 if (fields
[i
].checked
)
5360 rv
.push(fields
[i
].getAttribute('value'));
5365 textvalue: function(sid
)
5367 var v
= this.formvalue(sid
);
5371 for (var i
= 0; i
< this.choices
.length
; i
++)
5372 c
[this.choices
[i
][0]] = this.choices
[i
][1];
5376 for (var i
= 0; i
< v
.length
; i
++)
5377 t
.push(c
[v
[i
]] || v
[i
]);
5379 return t
.join(', ');
5383 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
5384 _change: function(ev
)
5387 var self
= ev
.data
.self
;
5389 if (s
.selectedIndex
== (s
.options
.length
- 1))
5391 ev
.data
.select
.hide();
5392 ev
.data
.input
.show().focus();
5393 ev
.data
.input
.val('');
5395 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
5397 ev
.data
.input
.val('');
5401 ev
.data
.input
.val(ev
.data
.select
.val());
5404 ev
.stopPropagation();
5410 var val
= this.value
;
5411 var self
= ev
.data
.self
;
5413 ev
.data
.select
.empty();
5415 if (self
.options
.optional
&& !self
.has_empty
)
5418 .text(L
.tr('-- please choose --'))
5419 .appendTo(ev
.data
.select
);
5422 for (var i
= 0; i
< self
.choices
.length
; i
++)
5424 if (self
.choices
[i
][0] == val
)
5428 .attr('value', self
.choices
[i
][0])
5429 .text(self
.choices
[i
][1])
5430 .appendTo(ev
.data
.select
);
5433 if (!seen
&& val
!= '')
5437 .appendTo(ev
.data
.select
);
5441 .text(L
.tr('-- custom --'))
5442 .appendTo(ev
.data
.select
);
5444 ev
.data
.input
.hide();
5445 ev
.data
.select
.val(val
).show().blur();
5448 _enter: function(ev
)
5453 ev
.preventDefault();
5454 ev
.data
.self
._blur(ev
);
5458 widget: function(sid
)
5460 var d
= $('<div />')
5461 .attr('id', this.id(sid
));
5463 var t
= $('<input />')
5464 .addClass('form-control')
5465 .attr('type', 'text')
5469 var s
= $('<select />')
5470 .addClass('form-control')
5479 s
.change(evdata
, this._change
);
5480 t
.blur(evdata
, this._blur
);
5481 t
.keydown(evdata
, this._enter
);
5483 t
.val(this.ucivalue(sid
));
5486 this.validator(sid
, t
);
5487 this.validator(sid
, s
);
5492 value: function(k
, v
)
5498 this.has_empty
= true;
5500 this.choices
.push([k
, v
|| k
]);
5504 formvalue: function(sid
)
5506 var v
= $('#' + this.id(sid
)).children('input').val();
5507 return (v
== '') ? undefined : v
;
5511 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
5512 _redraw: function(focus
, add
, del
, s
)
5514 var v
= s
.values
|| [ ];
5517 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
5519 v
.push(this.value
|| '');
5522 $(s
.parent
).empty();
5527 v
.splice(focus
, 0, '');
5529 else if (v
.length
== 0)
5535 for (var i
= 0; i
< v
.length
; i
++)
5542 remove
: ((i
+1) < v
.length
)
5547 btn
= L
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
5549 btn
= L
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
5553 var txt
= $('<input />')
5554 .addClass('form-control')
5555 .attr('type', 'text')
5558 var sel
= $('<select />')
5559 .addClass('form-control');
5562 .addClass('input-group')
5565 .append($('<span />')
5566 .addClass('input-group-btn')
5568 .appendTo(s
.parent
);
5570 evdata
.input
= this.validator(s
.sid
, txt
, true);
5571 evdata
.select
= this.validator(s
.sid
, sel
, true);
5573 sel
.change(evdata
, this._change
);
5574 txt
.blur(evdata
, this._blur
);
5575 txt
.keydown(evdata
, this._keydown
);
5580 if (i
== focus
|| -(i
+1) == focus
)
5587 var f
= $('<input />')
5588 .attr('type', 'text')
5590 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
5591 .addClass('form-control')
5592 .keydown(evdata
, this._keydown
)
5593 .keypress(evdata
, this._keypress
)
5597 .addClass('input-group')
5599 .append($('<span />')
5600 .addClass('input-group-btn')
5602 .appendTo(s
.parent
);
5608 else if (-(i
+1) == focus
)
5612 /* force cursor to end */
5618 evdata
.input
= this.validator(s
.sid
, f
, true);
5629 _keypress: function(ev
)
5633 /* backspace, delete */
5636 if (ev
.data
.input
.val() == '')
5638 ev
.preventDefault();
5644 /* enter, arrow up, arrow down */
5648 ev
.preventDefault();
5655 _keydown: function(ev
)
5657 var input
= ev
.data
.input
;
5661 /* backspace, delete */
5664 if (input
.val().length
== 0)
5666 ev
.preventDefault();
5668 var index
= ev
.data
.index
;
5674 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
5682 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5687 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
5688 if (prev
.is(':visible'))
5691 prev
.next('select').focus();
5696 var next
= input
.parent().nextAll('div.input-group:first').children('input');
5697 if (next
.is(':visible'))
5700 next
.next('select').focus();
5707 _btnclick: function(ev
)
5709 if (!this.getAttribute('disabled'))
5713 var index
= ev
.data
.index
;
5714 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
5718 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5725 widget: function(sid
)
5727 this.options
.optional
= true;
5729 var v
= this.ucivalue(sid
);
5732 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5734 var d
= $('<div />')
5735 .attr('id', this.id(sid
))
5736 .addClass('cbi-input-dynlist');
5738 this._redraw(NaN
, -1, -1, {
5748 ucivalue: function(sid
)
5750 var v
= this.callSuper('ucivalue', sid
);
5753 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5758 formvalue: function(sid
)
5761 var fields
= $('#' + this.id(sid
) + ' input');
5763 for (var i
= 0; i
< fields
.length
; i
++)
5764 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
5765 rv
.push(fields
[i
].value
);
5771 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
5772 widget: function(sid
)
5775 .addClass('form-control-static')
5776 .attr('id', this.id(sid
))
5777 .html(this.ucivalue(sid
));
5780 formvalue: function(sid
)
5782 return this.ucivalue(sid
);
5786 this.cbi
.ButtonValue
= this.cbi
.AbstractValue
.extend({
5787 widget: function(sid
)
5789 this.options
.optional
= true;
5791 var btn
= $('<button />')
5792 .addClass('btn btn-default')
5793 .attr('id', this.id(sid
))
5794 .attr('type', 'button')
5795 .text(this.label('text'));
5797 return this.validator(sid
, btn
);
5801 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
5804 return L
.NetworkModel
.init();
5807 _device_icon: function(dev
)
5810 .attr('src', dev
.icon())
5811 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?'));
5814 widget: function(sid
)
5816 var id
= this.id(sid
);
5817 var ul
= $('<ul />')
5819 .addClass('list-unstyled');
5821 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
5822 var value
= this.ucivalue(sid
);
5825 if (!this.options
.multiple
)
5826 check
[value
] = true;
5828 for (var i
= 0; i
< value
.length
; i
++)
5829 check
[value
[i
]] = true;
5831 var interfaces
= L
.NetworkModel
.getInterfaces();
5833 for (var i
= 0; i
< interfaces
.length
; i
++)
5835 var iface
= interfaces
[i
];
5836 var badge
= $('<span />')
5838 .text('%s: '.format(iface
.name()));
5840 var dev
= iface
.getDevice();
5841 var subdevs
= iface
.getSubdevices();
5844 for (var j
= 0; j
< subdevs
.length
; j
++)
5845 badge
.append(this._device_icon(subdevs
[j
]));
5847 badge
.append(this._device_icon(dev
));
5849 badge
.append($('<em />').text(L
.tr('(No devices attached)')));
5852 .append($('<label />')
5853 .addClass(itype
+ ' inline')
5854 .append($('<input />')
5855 .attr('name', itype
+ id
)
5856 .attr('type', itype
)
5857 .attr('value', iface
.name())
5858 .prop('checked', !!check
[iface
.name()]))
5863 if (!this.options
.multiple
)
5866 .append($('<label />')
5867 .addClass(itype
+ ' inline text-muted')
5868 .append($('<input />')
5869 .attr('name', itype
+ id
)
5870 .attr('type', itype
)
5872 .prop('checked', $.isEmptyObject(check
)))
5873 .append(L
.tr('unspecified')))
5880 ucivalue: function(sid
)
5882 var v
= this.callSuper('ucivalue', sid
);
5884 if (!this.options
.multiple
)
5890 else if (typeof(v
) == 'string')
5893 return v
? v
[0] : undefined;
5900 if (typeof(v
) == 'string')
5901 v
= v
.match(/\S+/g);
5907 formvalue: function(sid
)
5909 var inputs
= $('#' + this.id(sid
) + ' input');
5911 if (!this.options
.multiple
)
5913 for (var i
= 0; i
< inputs
.length
; i
++)
5914 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
5915 return inputs
[i
].value
;
5922 for (var i
= 0; i
< inputs
.length
; i
++)
5923 if (inputs
[i
].checked
)
5924 rv
.push(inputs
[i
].value
);
5926 return rv
.length
? rv
: undefined;
5930 this.cbi
.DeviceList
= this.cbi
.NetworkList
.extend({
5931 _ev_focus: function(ev
)
5933 var self
= ev
.data
.self
;
5934 var input
= $(this);
5936 input
.parent().prev().prop('checked', true);
5939 _ev_blur: function(ev
)
5942 ev
.data
.self
._ev_keydown
.call(this, ev
);
5945 _ev_keydown: function(ev
)
5947 if (ev
.which
!= 10 && ev
.which
!= 13)
5950 var sid
= ev
.data
.sid
;
5951 var self
= ev
.data
.self
;
5952 var input
= $(this);
5953 var ifnames
= L
.toArray(input
.val());
5955 if (!ifnames
.length
)
5958 L
.NetworkModel
.createDevice(ifnames
[0]);
5960 self
._redraw(sid
, $('#' + self
.id(sid
)), ifnames
[0]);
5965 return L
.NetworkModel
.init();
5968 _redraw: function(sid
, ul
, sel
)
5970 var id
= ul
.attr('id');
5971 var devs
= L
.NetworkModel
.getDevices();
5972 var iface
= L
.NetworkModel
.getInterface(sid
);
5973 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
5978 for (var i
= 0; i
< devs
.length
; i
++)
5979 if (devs
[i
].isInNetwork(iface
))
5980 check
[devs
[i
].name()] = true;
5984 if (this.options
.multiple
)
5985 check
= L
.toObject(this.formvalue(sid
));
5992 for (var i
= 0; i
< devs
.length
; i
++)
5996 if (dev
.isBridge() && this.options
.bridges
=== false)
5999 if (!dev
.isBridgeable() && this.options
.multiple
)
6002 var badge
= $('<span />')
6004 .append($('<img />').attr('src', dev
.icon()))
6005 .append(' %s: %s'.format(dev
.name(), dev
.description()));
6007 //var ifcs = dev.getInterfaces();
6010 // for (var j = 0; j < ifcs.length; j++)
6011 // badge.append((j ? ', ' : ' (') + ifcs[j].name());
6013 // badge.append(')');
6017 .append($('<label />')
6018 .addClass(itype
+ ' inline')
6019 .append($('<input />')
6020 .attr('name', itype
+ id
)
6021 .attr('type', itype
)
6022 .attr('value', dev
.name())
6023 .prop('checked', !!check
[dev
.name()]))
6030 .append($('<label />')
6031 .attr('for', 'custom' + id
)
6032 .addClass(itype
+ ' inline')
6033 .append($('<input />')
6034 .attr('name', itype
+ id
)
6035 .attr('type', itype
)
6037 .append($('<span />')
6039 .append($('<input />')
6040 .attr('id', 'custom' + id
)
6041 .attr('type', 'text')
6042 .attr('placeholder', L
.tr('Custom device …'))
6043 .on('focus', { self
: this, sid
: sid
}, this._ev_focus
)
6044 .on('blur', { self
: this, sid
: sid
}, this._ev_blur
)
6045 .on('keydown', { self
: this, sid
: sid
}, this._ev_keydown
))))
6048 if (!this.options
.multiple
)
6051 .append($('<label />')
6052 .addClass(itype
+ ' inline text-muted')
6053 .append($('<input />')
6054 .attr('name', itype
+ id
)
6055 .attr('type', itype
)
6057 .prop('checked', $.isEmptyObject(check
)))
6058 .append(L
.tr('unspecified')))
6063 widget: function(sid
)
6065 var id
= this.id(sid
);
6066 var ul
= $('<ul />')
6068 .addClass('list-unstyled');
6070 this._redraw(sid
, ul
);
6077 if (this.instance
[sid
].disabled
)
6080 var ifnames
= this.formvalue(sid
);
6084 var iface
= L
.NetworkModel
.getInterface(sid
);
6088 iface
.setDevices($.isArray(ifnames
) ? ifnames
: [ ifnames
]);
6093 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
6096 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
6098 for (var i
= 1; i
< arguments
.length
; i
++)
6099 s
.push(arguments
[i
].replace(/\./g, '_'));
6104 option: function(widget
, name
, options
)
6106 if (this.tabs
.length
== 0)
6107 this.tab({ id
: '__default__', selected
: true });
6109 return this.taboption('__default__', widget
, name
, options
);
6112 tab: function(options
)
6114 if (options
.selected
)
6115 this.tabs
.selected
= this.tabs
.length
;
6119 caption
: options
.caption
,
6120 description
: options
.description
,
6126 taboption: function(tabid
, widget
, name
, options
)
6129 for (var i
= 0; i
< this.tabs
.length
; i
++)
6131 if (this.tabs
[i
].id
== tabid
)
6139 throw 'Cannot append to unknown tab ' + tabid
;
6141 var w
= widget
? new widget(name
, options
) : null;
6143 if (!(w
instanceof L
.cbi
.AbstractValue
))
6144 throw 'Widget must be an instance of AbstractValue';
6149 this.fields
[name
] = w
;
6155 tabtoggle: function(sid
)
6157 for (var i
= 0; i
< this.tabs
.length
; i
++)
6159 var tab
= this.tabs
[i
];
6160 var elem
= $('#' + this.id('nodetab', sid
, tab
.id
));
6163 for (var j
= 0; j
< tab
.fields
.length
; j
++)
6165 if (tab
.fields
[j
].active(sid
))
6172 if (empty
&& elem
.is(':visible'))
6179 ucipackages: function(pkg
)
6181 for (var i
= 0; i
< this.tabs
.length
; i
++)
6182 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6183 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
6184 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
6187 formvalue: function()
6191 this.sections(function(s
) {
6192 var sid
= s
['.name'];
6193 var sv
= rv
[sid
] || (rv
[sid
] = { });
6195 for (var i
= 0; i
< this.tabs
.length
; i
++)
6196 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6198 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
6199 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
6206 validate_section: function(sid
)
6208 var inst
= this.instance
[sid
];
6211 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
6213 for (var i
= 0; i
< this.tabs
.length
; i
++)
6216 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
6218 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6219 if (!this.tabs
[i
].fields
[j
].validate(sid
))
6225 .attr('title', L
.trp('1 Error', '%d Errors', inval
).format(inval
));
6235 .attr('title', L
.trp('1 Error', '%d Errors', invals
).format(invals
));
6242 validate: function()
6245 var as
= this.sections();
6247 for (var i
= 0; i
< as
.length
; i
++)
6249 var invals
= this.validate_section(as
[i
]['.name']);
6255 var badge
= $('#' + this.id('sectiontab')).children('span:first');
6260 .attr('title', L
.trp('1 Error', '%d Errors', errors
).format(errors
));
6264 return (errors
== 0);
6268 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
6269 init: function(uci_type
, options
)
6271 this.uci_type
= uci_type
;
6272 this.options
= options
;
6275 this.active_panel
= 0;
6276 this.active_tab
= { };
6279 filter: function(section
)
6284 sections: function(cb
)
6286 var s1
= L
.uci
.sections(this.map
.uci_package
);
6289 for (var i
= 0; i
< s1
.length
; i
++)
6290 if (s1
[i
]['.type'] == this.uci_type
)
6291 if (this.filter(s1
[i
]))
6294 if (typeof(cb
) == 'function')
6295 for (var i
= 0; i
< s2
.length
; i
++)
6296 cb
.call(this, s2
[i
]);
6303 return this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
6306 remove: function(sid
)
6308 return this.map
.remove(this.map
.uci_package
, sid
);
6311 _ev_add: function(ev
)
6314 var name
= undefined;
6315 var self
= ev
.data
.self
;
6317 if (addb
.prev().prop('nodeName') == 'INPUT')
6318 name
= addb
.prev().val();
6320 if (addb
.prop('disabled') || name
=== '')
6323 L
.ui
.saveScrollTop();
6325 self
.active_panel
= -1;
6328 ev
.data
.sid
= self
.add(name
);
6329 ev
.data
.type
= self
.uci_type
;
6330 ev
.data
.name
= name
;
6332 self
.trigger('add', ev
);
6336 L
.ui
.restoreScrollTop();
6339 _ev_remove: function(ev
)
6341 var self
= ev
.data
.self
;
6342 var sid
= ev
.data
.sid
;
6344 L
.ui
.saveScrollTop();
6346 self
.trigger('remove', ev
);
6352 L
.ui
.restoreScrollTop();
6354 ev
.stopPropagation();
6357 _ev_sid: function(ev
)
6359 var self
= ev
.data
.self
;
6361 var addb
= text
.next();
6362 var errt
= addb
.next();
6363 var name
= text
.val();
6365 if (!/^[a-zA-Z0-9_]*$/.test(name
))
6367 errt
.text(L
.tr('Invalid section name')).show();
6368 text
.addClass('error');
6369 addb
.prop('disabled', true);
6373 if (L
.uci
.get(self
.map
.uci_package
, name
))
6375 errt
.text(L
.tr('Name already used')).show();
6376 text
.addClass('error');
6377 addb
.prop('disabled', true);
6381 errt
.text('').hide();
6382 text
.removeClass('error');
6383 addb
.prop('disabled', false);
6387 _ev_tab: function(ev
)
6389 var self
= ev
.data
.self
;
6390 var sid
= ev
.data
.sid
;
6393 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
6396 _ev_panel_collapse: function(ev
)
6398 var self
= ev
.data
.self
;
6400 var this_panel
= $(ev
.target
);
6401 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
6403 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
6404 var prev_panel
= $(prev_toggle
.attr('data-target'));
6408 .addClass('collapse');
6410 prev_toggle
.find('.luci2-section-teaser')
6412 .children('span:last')
6414 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
6416 this_toggle
.find('.luci2-section-teaser')
6419 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
6423 _ev_panel_open: function(ev
)
6425 var self
= ev
.data
.self
;
6426 var panel
= $($(this).attr('data-target'));
6427 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
6429 if (index
== self
.active_panel
)
6430 ev
.stopPropagation();
6433 _ev_sort: function(ev
)
6435 var self
= ev
.data
.self
;
6436 var cur_idx
= ev
.data
.index
;
6437 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
6438 var s
= self
.sections();
6440 if (new_idx
>= 0 && new_idx
< s
.length
)
6442 L
.uci
.swap(self
.map
.uci_package
, s
[cur_idx
]['.name'], s
[new_idx
]['.name']);
6448 ev
.stopPropagation();
6451 teaser: function(sid
)
6453 var tf
= this.teaser_fields
;
6457 tf
= this.teaser_fields
= [ ];
6459 if ($.isArray(this.options
.teasers
))
6461 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
6463 var f
= this.options
.teasers
[i
];
6464 if (f
instanceof L
.cbi
.AbstractValue
)
6466 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof L
.cbi
.AbstractValue
)
6467 tf
.push(this.fields
[f
]);
6472 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
6473 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
6474 tf
.push(this.tabs
[i
].fields
[j
]);
6480 for (var i
= 0; i
< tf
.length
; i
++)
6482 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
6485 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
6486 var v
= tf
[i
].textvalue(sid
);
6488 if (typeof(v
) == 'undefined')
6491 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
6497 _render_add: function()
6499 if (!this.options
.addremove
)
6502 var text
= L
.tr('Add section');
6503 var ttip
= L
.tr('Create new section...');
6505 if ($.isArray(this.options
.add_caption
))
6506 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
6507 else if (typeof(this.options
.add_caption
) == 'string')
6508 text
= this.options
.add_caption
, ttip
= '';
6510 var add
= $('<div />');
6512 if (this.options
.anonymous
=== false)
6515 .addClass('cbi-input-text')
6516 .attr('type', 'text')
6517 .attr('placeholder', ttip
)
6518 .blur({ self
: this }, this._ev_sid
)
6519 .keyup({ self
: this }, this._ev_sid
)
6523 .attr('src', L
.globals
.resource
+ '/icons/cbi/add.gif')
6524 .attr('title', text
)
6525 .addClass('cbi-button')
6526 .click({ self
: this }, this._ev_add
)
6530 .addClass('cbi-value-error')
6536 L
.ui
.button(text
, 'success', ttip
)
6537 .click({ self
: this }, this._ev_add
)
6544 _render_remove: function(sid
, index
)
6546 if (!this.options
.addremove
)
6549 var text
= L
.tr('Remove');
6550 var ttip
= L
.tr('Remove this section');
6552 if ($.isArray(this.options
.remove_caption
))
6553 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
6554 else if (typeof(this.options
.remove_caption
) == 'string')
6555 text
= this.options
.remove_caption
, ttip
= '';
6557 return L
.ui
.button(text
, 'danger', ttip
)
6558 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
6561 _render_sort: function(sid
, index
)
6563 if (!this.options
.sortable
)
6566 var b1
= L
.ui
.button('↑', 'info', L
.tr('Move up'))
6567 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
6569 var b2
= L
.ui
.button('↓', 'info', L
.tr('Move down'))
6570 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
6575 _render_caption: function()
6578 .addClass('panel-title')
6579 .append(this.label('caption') || this.uci_type
);
6582 _render_description: function()
6584 var text
= this.label('description');
6588 .addClass('luci2-section-description')
6594 _render_teaser: function(sid
, index
)
6596 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6599 .attr('id', this.id('teaser', sid
))
6600 .addClass('luci2-section-teaser well well-sm')
6601 .append($('<span />')
6603 .append($('<span />'));
6609 _render_head: function(condensed
)
6615 .addClass('panel-heading')
6616 .append(this._render_caption())
6617 .append(this._render_description());
6620 _render_tab_description: function(sid
, index
, tab_index
)
6622 var tab
= this.tabs
[tab_index
];
6624 if (typeof(tab
.description
) == 'string')
6627 .addClass('cbi-tab-descr')
6628 .text(tab
.description
);
6634 _render_tab_head: function(sid
, index
, tab_index
)
6636 var tab
= this.tabs
[tab_index
];
6637 var cur
= this.active_tab
[sid
] || 0;
6639 var tabh
= $('<li />')
6641 .attr('id', this.id('nodetab', sid
, tab
.id
))
6642 .attr('href', '#' + this.id('node', sid
, tab
.id
))
6643 .attr('data-toggle', 'tab')
6644 .attr('data-luci2-tab-index', tab_index
)
6645 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
6646 .append($('<span />')
6648 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
6650 if (cur
== tab_index
)
6651 tabh
.addClass('active');
6653 if (!tab
.fields
.length
)
6659 _render_tab_body: function(sid
, index
, tab_index
)
6661 var tab
= this.tabs
[tab_index
];
6662 var cur
= this.active_tab
[sid
] || 0;
6664 var tabb
= $('<div />')
6665 .addClass('tab-pane')
6666 .attr('id', this.id('node', sid
, tab
.id
))
6667 .attr('data-luci2-tab-index', tab_index
)
6668 .append(this._render_tab_description(sid
, index
, tab_index
));
6670 if (cur
== tab_index
)
6671 tabb
.addClass('active');
6673 for (var i
= 0; i
< tab
.fields
.length
; i
++)
6674 tabb
.append(tab
.fields
[i
].render(sid
));
6679 _render_section_head: function(sid
, index
)
6681 var head
= $('<div />')
6682 .addClass('luci2-section-header')
6683 .append(this._render_teaser(sid
, index
))
6684 .append($('<div />')
6685 .addClass('btn-group')
6686 .append(this._render_sort(sid
, index
))
6687 .append(this._render_remove(sid
, index
)));
6689 if (this.options
.collabsible
)
6691 head
.attr('data-toggle', 'collapse')
6692 .attr('data-parent', this.id('sectiongroup'))
6693 .attr('data-target', '#' + this.id('panel', sid
))
6694 .on('click', { self
: this }, this._ev_panel_open
);
6700 _render_section_body: function(sid
, index
)
6702 var body
= $('<div />')
6703 .attr('id', this.id('panel', sid
))
6704 .attr('data-luci2-panel-index', index
)
6705 .attr('data-luci2-sid', sid
);
6707 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6709 body
.addClass('panel-collapse collapse');
6711 if (index
== this.active_panel
)
6712 body
.addClass('in');
6715 var tab_heads
= $('<ul />')
6716 .addClass('nav nav-tabs');
6718 var tab_bodies
= $('<div />')
6719 .addClass('form-horizontal tab-content')
6722 for (var j
= 0; j
< this.tabs
.length
; j
++)
6724 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
6725 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
6728 body
.append(tab_bodies
);
6730 if (this.tabs
.length
<= 1)
6736 _render_body: function(condensed
)
6738 var s
= this.sections();
6740 if (this.active_panel
< 0)
6741 this.active_panel
+= s
.length
;
6742 else if (this.active_panel
>= s
.length
)
6743 this.active_panel
= s
.length
- 1;
6745 var body
= $('<ul />')
6746 .addClass('list-group');
6748 if (this.options
.collabsible
)
6750 body
.attr('id', this.id('sectiongroup'))
6751 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
6756 body
.append($('<li />')
6757 .addClass('list-group-item text-muted')
6758 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.')))
6761 for (var i
= 0; i
< s
.length
; i
++)
6763 var sid
= s
[i
]['.name'];
6764 var inst
= this.instance
[sid
] = { tabs
: [ ] };
6766 body
.append($('<li />')
6767 .addClass('list-group-item')
6768 .append(this._render_section_head(sid
, i
))
6769 .append(this._render_section_body(sid
, i
)));
6775 render: function(condensed
)
6777 this.instance
= { };
6779 var panel
= $('<div />')
6780 .addClass('panel panel-default')
6781 .append(this._render_head(condensed
))
6782 .append(this._render_body(condensed
));
6784 if (this.options
.addremove
)
6785 panel
.append($('<div />')
6786 .addClass('panel-footer')
6787 .append(this._render_add()));
6794 var s
= this.sections();
6796 for (var i
= 0; i
< s
.length
; i
++)
6798 var sid
= s
[i
]['.name'];
6800 this.validate_section(sid
);
6802 if (i
!= this.active_panel
)
6803 $('#' + this.id('teaser', sid
)).children('span:last')
6804 .append(this.teaser(sid
));
6806 $('#' + this.id('teaser', sid
))
6812 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
6813 _render_table_head: function()
6815 var thead
= $('<thead />')
6817 .addClass('cbi-section-table-titles'));
6819 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
6820 thead
.children().append($('<th />')
6821 .addClass('cbi-section-table-cell')
6822 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
6823 .append(this.tabs
[0].fields
[j
].label('caption')));
6825 if (this.options
.addremove
!== false || this.options
.sortable
)
6826 thead
.children().append($('<th />')
6827 .addClass('cbi-section-table-cell')
6833 _render_table_row: function(sid
, index
)
6835 var row
= $('<tr />')
6836 .attr('data-luci2-sid', sid
);
6838 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
6840 row
.append($('<td />')
6841 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
6842 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
6845 if (this.options
.addremove
!== false || this.options
.sortable
)
6847 row
.append($('<td />')
6848 .addClass('text-right')
6849 .append($('<div />')
6850 .addClass('btn-group')
6851 .append(this._render_sort(sid
, index
))
6852 .append(this._render_remove(sid
, index
))));
6858 _render_table_body: function()
6860 var s
= this.sections();
6862 var tbody
= $('<tbody />');
6866 var cols
= this.tabs
[0].fields
.length
;
6868 if (this.options
.addremove
!== false || this.options
.sortable
)
6871 tbody
.append($('<tr />')
6873 .addClass('text-muted')
6874 .attr('colspan', cols
)
6875 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.'))));
6878 for (var i
= 0; i
< s
.length
; i
++)
6880 var sid
= s
[i
]['.name'];
6881 var inst
= this.instance
[sid
] = { tabs
: [ ] };
6883 tbody
.append(this._render_table_row(sid
, i
));
6889 _render_body: function(condensed
)
6891 return $('<table />')
6892 .addClass('table table-condensed table-hover')
6893 .append(this._render_table_head())
6894 .append(this._render_table_body());
6898 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
6899 sections: function(cb
)
6902 var sl
= L
.uci
.sections(this.map
.uci_package
);
6904 for (var i
= 0; i
< sl
.length
; i
++)
6905 if (sl
[i
]['.name'] == this.uci_type
)
6911 if (typeof(cb
) == 'function' && sa
.length
> 0)
6912 cb
.call(this, sa
[0]);
6918 this.cbi
.SingleSection
= this.cbi
.NamedSection
.extend({
6921 this.instance
= { };
6922 this.instance
[this.uci_type
] = { tabs
: [ ] };
6924 return this._render_section_body(this.uci_type
, 0);
6928 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
6929 sections: function(cb
)
6931 if (typeof(cb
) == 'function')
6932 cb
.apply(this, [ { '.name': this.uci_type
} ]);
6934 return [ { '.name': this.uci_type
} ];
6938 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
6939 init: function(uci_package
, options
)
6943 this.uci_package
= uci_package
;
6944 this.sections
= [ ];
6945 this.options
= L
.defaults(options
, {
6946 save: function() { },
6947 prepare: function() { }
6951 _load_cb: function()
6953 var deferreds
= [ L
.deferrable(this.options
.prepare()) ];
6955 for (var i
= 0; i
< this.sections
.length
; i
++)
6957 for (var f
in this.sections
[i
].fields
)
6959 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
6962 var s
= this.sections
[i
].sections();
6963 for (var j
= 0; j
< s
.length
; j
++)
6965 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
6966 if (L
.isDeferred(rv
))
6972 return $.when
.apply($, deferreds
);
6980 for (var i
= 0; i
< this.sections
.length
; i
++)
6981 this.sections
[i
].ucipackages(packages
);
6983 packages
[this.uci_package
] = true;
6985 for (var pkg
in packages
)
6986 if (!L
.uci
.writable(pkg
))
6987 this.options
.readonly
= true;
6989 return L
.uci
.load(L
.toArray(packages
)).then(function() {
6990 return self
._load_cb();
6994 _ev_tab: function(ev
)
6996 var self
= ev
.data
.self
;
6999 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
7002 _ev_apply: function(ev
)
7004 var self
= ev
.data
.self
;
7006 self
.trigger('apply', ev
);
7009 _ev_save: function(ev
)
7011 var self
= ev
.data
.self
;
7013 self
.trigger('save', ev
);
7016 _ev_reset: function(ev
)
7018 var self
= ev
.data
.self
;
7020 self
.trigger('reset', ev
);
7024 _render_tab_head: function(tab_index
)
7026 var section
= this.sections
[tab_index
];
7027 var cur
= this.active_tab
|| 0;
7029 var tabh
= $('<li />')
7031 .attr('id', section
.id('sectiontab'))
7032 .attr('href', '#' + section
.id('section'))
7033 .attr('data-toggle', 'tab')
7034 .attr('data-luci2-tab-index', tab_index
)
7035 .text(section
.label('caption') + ' ')
7036 .append($('<span />')
7038 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
7040 if (cur
== tab_index
)
7041 tabh
.addClass('active');
7046 _render_tab_body: function(tab_index
)
7048 var section
= this.sections
[tab_index
];
7049 var desc
= section
.label('description');
7050 var cur
= this.active_tab
|| 0;
7052 var tabb
= $('<div />')
7053 .addClass('tab-pane')
7054 .attr('id', section
.id('section'))
7055 .attr('data-luci2-tab-index', tab_index
);
7057 if (cur
== tab_index
)
7058 tabb
.addClass('active');
7061 tabb
.append($('<p />')
7064 var s
= section
.render(this.options
.tabbed
);
7066 if (this.options
.readonly
|| section
.options
.readonly
)
7067 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
7074 _render_body: function()
7076 var tabs
= $('<ul />')
7077 .addClass('nav nav-tabs');
7079 var body
= $('<div />')
7082 for (var i
= 0; i
< this.sections
.length
; i
++)
7084 tabs
.append(this._render_tab_head(i
));
7085 body
.append(this._render_tab_body(i
));
7088 if (this.options
.tabbed
)
7089 body
.addClass('tab-content');
7096 _render_footer: function()
7103 .addClass('panel panel-default panel-body text-right')
7104 .append($('<div />')
7105 .addClass('btn-group')
7106 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7107 .click(evdata
, this._ev_apply
))
7108 .append(L
.ui
.button(L
.tr('Save'), 'default')
7109 .click(evdata
, this._ev_save
))
7110 .append(L
.ui
.button(L
.tr('Reset'), 'default')
7111 .click(evdata
, this._ev_reset
)));
7116 var map
= $('<form />');
7118 if (typeof(this.options
.caption
) == 'string')
7119 map
.append($('<h2 />')
7120 .text(this.options
.caption
));
7122 if (typeof(this.options
.description
) == 'string')
7123 map
.append($('<p />')
7124 .text(this.options
.description
));
7126 map
.append(this._render_body());
7128 if (this.options
.pageaction
!== false)
7129 map
.append(this._render_footer());
7136 for (var i
= 0; i
< this.sections
.length
; i
++)
7137 this.sections
[i
].finish();
7144 this.target
.hide().empty().append(this.render());
7149 section: function(widget
, uci_type
, options
)
7151 var w
= widget
? new widget(uci_type
, options
) : null;
7153 if (!(w
instanceof L
.cbi
.AbstractSection
))
7154 throw 'Widget must be an instance of AbstractSection';
7157 w
.index
= this.sections
.length
;
7159 this.sections
.push(w
);
7163 formvalue: function()
7167 for (var i
= 0; i
< this.sections
.length
; i
++)
7169 var sids
= this.sections
[i
].formvalue();
7170 for (var sid
in sids
)
7172 var s
= rv
[sid
] || (rv
[sid
] = { });
7173 $.extend(s
, sids
[sid
]);
7180 add: function(conf
, type
, name
)
7182 return L
.uci
.add(conf
, type
, name
);
7185 remove: function(conf
, sid
)
7187 return L
.uci
.remove(conf
, sid
);
7190 get: function(conf
, sid
, opt
)
7192 return L
.uci
.get(conf
, sid
, opt
);
7195 set: function(conf
, sid
, opt
, val
)
7197 return L
.uci
.set(conf
, sid
, opt
, val
);
7200 validate: function()
7204 for (var i
= 0; i
< this.sections
.length
; i
++)
7206 if (!this.sections
[i
].validate())
7217 if (self
.options
.readonly
)
7218 return L
.deferrable();
7220 var deferreds
= [ ];
7222 for (var i
= 0; i
< self
.sections
.length
; i
++)
7224 if (self
.sections
[i
].options
.readonly
)
7227 for (var f
in self
.sections
[i
].fields
)
7229 if (typeof(self
.sections
[i
].fields
[f
].save
) != 'function')
7232 var s
= self
.sections
[i
].sections();
7233 for (var j
= 0; j
< s
.length
; j
++)
7235 var rv
= self
.sections
[i
].fields
[f
].save(s
[j
]['.name']);
7236 if (L
.isDeferred(rv
))
7242 return $.when
.apply($, deferreds
).then(function() {
7243 return L
.deferrable(self
.options
.save());
7249 if (!this.validate())
7250 return L
.deferrable();
7254 L
.ui
.saveScrollTop();
7257 return this.save().then(function() {
7258 return L
.uci
.save();
7259 }).then(function() {
7260 return L
.ui
.updateChanges();
7261 }).then(function() {
7263 }).then(function() {
7267 L
.ui
.loading(false);
7268 L
.ui
.restoreScrollTop();
7277 for (var i
= 0; i
< this.sections
.length
; i
++)
7278 this.sections
[i
].ucipackages(packages
);
7280 packages
[this.uci_package
] = true;
7282 L
.uci
.unload(L
.toArray(packages
));
7284 return self
.insertInto(self
.target
);
7287 insertInto: function(id
)
7290 self
.target
= $(id
);
7295 return self
.load().then(function() {
7296 self
.target
.empty().append(self
.render());
7300 L
.ui
.loading(false);
7305 this.cbi
.Modal
= this.cbi
.Map
.extend({
7306 _ev_apply: function(ev
)
7308 var self
= ev
.data
.self
;
7310 self
.trigger('apply', ev
);
7313 _ev_save: function(ev
)
7315 var self
= ev
.data
.self
;
7317 self
.send().then(function() {
7318 self
.trigger('save', ev
);
7323 _ev_reset: function(ev
)
7325 var self
= ev
.data
.self
;
7327 self
.trigger('close', ev
);
7331 _render_footer: function()
7338 .addClass('btn-group')
7339 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7340 .click(evdata
, this._ev_apply
))
7341 .append(L
.ui
.button(L
.tr('Save'), 'default')
7342 .click(evdata
, this._ev_save
))
7343 .append(L
.ui
.button(L
.tr('Cancel'), 'default')
7344 .click(evdata
, this._ev_reset
));
7349 var modal
= L
.ui
.dialog(this.label('caption'), null, { wide
: true });
7350 var map
= $('<form />');
7352 var desc
= this.label('description');
7354 map
.append($('<p />').text(desc
));
7356 map
.append(this._render_body());
7358 modal
.find('.modal-body').append(map
);
7359 modal
.find('.modal-footer').append(this._render_footer());
7376 return self
.load().then(function() {
7380 L
.ui
.loading(false);