2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013-2014 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')
488 this.toColor = function(str
)
490 if (typeof(str
) != 'string' || str
.length
== 0)
495 else if (str
== 'lan')
500 while (i
< str
.length
)
501 hash
= str
.charCodeAt(i
++) + ((hash
<< 5) - hash
);
503 var r
= (hash
& 0xFF) % 128;
504 var g
= ((hash
>> 8) & 0xFF) % 128;
514 var b
= min
+ (((hash
>> 16) & 0xFF) % (max
- min
));
516 return '#%02X%02X%02X'.format(0xFF - r
, 0xFF - g
, 0xFF - b
);
519 this.parseIPv4 = function(str
)
521 if ((typeof(str
) != 'string' && !(str
instanceof String
)) ||
522 !str
.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/))
526 var parts
= str
.split(/\./);
528 for (var i
= 0; i
< parts
.length
; i
++)
530 var n
= parseInt(parts
[i
], 10);
531 if (isNaN(n
) || n
> 255)
540 this.parseIPv6 = function(str
)
542 if ((typeof(str
) != 'string' && !(str
instanceof String
)) ||
543 !str
.match(/^[a-fA-F0-9:]+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/))
546 var parts
= str
.split(/::/);
547 if (parts
.length
== 0 || parts
.length
> 2)
551 if (parts
[0].length
> 0)
553 var left
= parts
[0].split(/:/);
554 for (var i
= 0; i
< left
.length
; i
++)
556 var n
= parseInt(left
[i
], 16);
560 lnum
.push((n
/ 256) >> 0);
566 if (parts
.length
> 1 && parts
[1].length
> 0)
568 var right
= parts
[1].split(/:/);
570 for (var i
= 0; i
< right
.length
; i
++)
572 if (right
[i
].indexOf('.') > 0)
574 var addr
= L
.parseIPv4(right
[i
]);
578 rnum
.push
.apply(rnum
, addr
);
582 var n
= parseInt(right
[i
], 16);
586 rnum
.push((n
/ 256) >> 0);
591 if (rnum
.length
> 0 && (lnum
.length
+ rnum
.length
) > 15)
596 num
.push
.apply(num
, lnum
);
598 for (var i
= 0; i
< (16 - lnum
.length
- rnum
.length
); i
++)
601 num
.push
.apply(num
, rnum
);
609 this.isNetmask = function(addr
)
611 if (!$.isArray(addr
))
616 for (c
= 0; (c
< addr
.length
) && (addr
[c
] == 255); c
++);
618 if (c
== addr
.length
)
621 if ((addr
[c
] == 254) || (addr
[c
] == 252) || (addr
[c
] == 248) ||
622 (addr
[c
] == 240) || (addr
[c
] == 224) || (addr
[c
] == 192) ||
623 (addr
[c
] == 128) || (addr
[c
] == 0))
625 for (c
++; (c
< addr
.length
) && (addr
[c
] == 0); c
++);
627 if (c
== addr
.length
)
637 sid
: '00000000000000000000000000000000'
646 _call: function(req
, cb
)
648 return $.ajax('/ubus', {
650 contentType
: 'application/json',
651 data
: JSON
.stringify(req
),
654 timeout
: L
.globals
.timeout
,
659 _list_cb: function(msg
)
661 var list
= msg
.result
;
663 /* verify message frame */
664 if (typeof(msg
) != 'object' || msg
.jsonrpc
!= '2.0' || !msg
.id
|| !$.isArray(list
))
667 return $.Deferred().resolveWith(this, [ list
]);
670 _call_cb: function(msg
)
673 var type
= Object
.prototype.toString
;
674 var reqs
= this._rpc_req
;
676 if (!$.isArray(reqs
))
682 for (var i
= 0; i
< msg
.length
; i
++)
684 /* fetch related request info */
685 var req
= L
.rpc
._requests
[reqs
[i
].id
];
686 if (typeof(req
) != 'object')
687 throw 'No related request for JSON response';
689 /* fetch response attribute and verify returned type */
692 /* verify message frame */
693 if (typeof(msg
[i
]) == 'object' && msg
[i
].jsonrpc
== '2.0')
694 if ($.isArray(msg
[i
].result
) && msg
[i
].result
[0] == 0)
695 ret
= (msg
[i
].result
.length
> 1) ? msg
[i
].result
[1] : msg
[i
].result
[0];
699 for (var key
in req
.expect
)
701 if (typeof(ret
) != 'undefined' && key
!= '')
704 if (typeof(ret
) == 'undefined' || type
.call(ret
) != type
.call(req
.expect
[key
]))
705 ret
= req
.expect
[key
];
712 if (typeof(req
.filter
) == 'function')
715 req
.priv
[1] = req
.params
;
716 ret
= req
.filter
.apply(L
.rpc
, req
.priv
);
719 /* store response data */
720 if (typeof(req
.index
) == 'number')
721 data
[req
.index
] = ret
;
725 /* delete request object */
726 delete L
.rpc
._requests
[reqs
[i
].id
];
729 return $.Deferred().resolveWith(this, [ data
]);
735 for (var i
= 0; i
< arguments
.length
; i
++)
736 params
[i
] = arguments
[i
];
742 params
: (params
.length
> 0) ? params
: undefined
745 return this._call(msg
, this._list_cb
);
750 if (!$.isArray(this._batch
))
756 if (!$.isArray(this._batch
))
757 return L
.deferrable([ ]);
759 var req
= this._batch
;
763 return this._call(req
, this._call_cb
);
766 declare: function(options
)
771 /* build parameter object */
774 if ($.isArray(options
.params
))
775 for (p_off
= 0; p_off
< options
.params
.length
; p_off
++)
776 params
[options
.params
[p_off
]] = arguments
[p_off
];
778 /* all remaining arguments are private args */
779 var priv
= [ undefined, undefined ];
780 for (; p_off
< arguments
.length
; p_off
++)
781 priv
.push(arguments
[p_off
]);
783 /* store request info */
784 var req
= _rpc
._requests
[_rpc
._id
] = {
785 expect
: options
.expect
,
786 filter
: options
.filter
,
791 /* build message object */
804 /* when a batch is in progress then store index in request data
805 * and push message object onto the stack */
806 if ($.isArray(_rpc
._batch
))
808 req
.index
= _rpc
._batch
.push(msg
) - 1;
809 return L
.deferrable(msg
);
813 return _rpc
._call(msg
, _rpc
._call_cb
);
818 this.UCIContext
= Class
.extend({
832 callLoad
: L
.rpc
.declare({
835 params
: [ 'config' ],
836 expect
: { values
: { } }
839 callOrder
: L
.rpc
.declare({
842 params
: [ 'config', 'sections' ]
845 callAdd
: L
.rpc
.declare({
848 params
: [ 'config', 'type', 'name', 'values' ],
849 expect
: { section
: '' }
852 callSet
: L
.rpc
.declare({
855 params
: [ 'config', 'section', 'values' ]
858 callDelete
: L
.rpc
.declare({
861 params
: [ 'config', 'section', 'options' ]
864 callApply
: L
.rpc
.declare({
867 params
: [ 'timeout', 'rollback' ]
870 callConfirm
: L
.rpc
.declare({
875 createSID: function(conf
)
877 var v
= this.state
.values
;
878 var n
= this.state
.creates
;
882 sid
= "new%06x".format(Math
.random() * 0xFFFFFF);
883 } while ((n
[conf
] && n
[conf
][sid
]) || (v
[conf
] && v
[conf
][sid
]));
888 reorderSections: function()
890 var v
= this.state
.values
;
891 var n
= this.state
.creates
;
892 var r
= this.state
.reorder
;
894 if ($.isEmptyObject(r
))
895 return L
.deferrable();
900 gather all created and existing sections, sort them according
901 to their index value and issue an uci order call
916 o
.sort(function(a
, b
) {
917 return (a
['.index'] - b
['.index']);
922 for (var i
= 0; i
< o
.length
; i
++)
923 sids
.push(o
[i
]['.name']);
925 this.callOrder(c
, sids
);
929 this.state
.reorder
= { };
930 return L
.rpc
.flush();
933 load: function(packages
)
939 if (!$.isArray(packages
))
940 packages
= [ packages
];
944 for (var i
= 0; i
< packages
.length
; i
++)
945 if (!seen
[packages
[i
]] && !self
.state
.values
[packages
[i
]])
947 pkgs
.push(packages
[i
]);
948 seen
[packages
[i
]] = true;
949 self
.callLoad(packages
[i
]);
952 return L
.rpc
.flush().then(function(responses
) {
953 for (var i
= 0; i
< responses
.length
; i
++)
954 self
.state
.values
[pkgs
[i
]] = responses
[i
];
960 unload: function(packages
)
962 if (!$.isArray(packages
))
963 packages
= [ packages
];
965 for (var i
= 0; i
< packages
.length
; i
++)
967 delete this.state
.values
[packages
[i
]];
968 delete this.state
.creates
[packages
[i
]];
969 delete this.state
.changes
[packages
[i
]];
970 delete this.state
.deletes
[packages
[i
]];
974 add: function(conf
, type
, name
)
976 var n
= this.state
.creates
;
977 var sid
= this.createSID(conf
);
987 '.index': 1000 + this.state
.newidx
++
993 remove: function(conf
, sid
)
995 var n
= this.state
.creates
;
996 var c
= this.state
.changes
;
997 var d
= this.state
.deletes
;
999 /* requested deletion of a just created section */
1000 if (n
[conf
] && n
[conf
][sid
])
1002 delete n
[conf
][sid
];
1007 delete c
[conf
][sid
];
1012 d
[conf
][sid
] = true;
1016 sections: function(conf
, type
, cb
)
1019 var v
= this.state
.values
[conf
];
1020 var n
= this.state
.creates
[conf
];
1021 var c
= this.state
.changes
[conf
];
1022 var d
= this.state
.deletes
[conf
];
1028 if (!d
|| d
[s
] !== true)
1029 if (!type
|| v
[s
]['.type'] == type
)
1030 sa
.push($.extend({ }, v
[s
], c
? c
[s
] : undefined));
1034 if (!type
|| n
[s
]['.type'] == type
)
1037 sa
.sort(function(a
, b
) {
1038 return a
['.index'] - b
['.index'];
1041 for (var i
= 0; i
< sa
.length
; i
++)
1042 sa
[i
]['.index'] = i
;
1044 if (typeof(cb
) == 'function')
1045 for (var i
= 0; i
< sa
.length
; i
++)
1046 cb
.call(this, sa
[i
], sa
[i
]['.name']);
1051 get: function(conf
, sid
, opt
)
1053 var v
= this.state
.values
;
1054 var n
= this.state
.creates
;
1055 var c
= this.state
.changes
;
1056 var d
= this.state
.deletes
;
1058 if (typeof(sid
) == 'undefined')
1061 /* requested option in a just created section */
1062 if (n
[conf
] && n
[conf
][sid
])
1067 if (typeof(opt
) == 'undefined')
1068 return n
[conf
][sid
];
1070 return n
[conf
][sid
][opt
];
1073 /* requested an option value */
1074 if (typeof(opt
) != 'undefined')
1076 /* check whether option was deleted */
1077 if (d
[conf
] && d
[conf
][sid
])
1079 if (d
[conf
][sid
] === true)
1082 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
1083 if (d
[conf
][sid
][i
] == opt
)
1087 /* check whether option was changed */
1088 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
1089 return c
[conf
][sid
][opt
];
1091 /* return base value */
1092 if (v
[conf
] && v
[conf
][sid
])
1093 return v
[conf
][sid
][opt
];
1098 /* requested an entire section */
1100 return v
[conf
][sid
];
1105 set: function(conf
, sid
, opt
, val
)
1107 var v
= this.state
.values
;
1108 var n
= this.state
.creates
;
1109 var c
= this.state
.changes
;
1110 var d
= this.state
.deletes
;
1112 if (typeof(sid
) == 'undefined' ||
1113 typeof(opt
) == 'undefined' ||
1114 opt
.charAt(0) == '.')
1117 if (n
[conf
] && n
[conf
][sid
])
1119 if (typeof(val
) != 'undefined')
1120 n
[conf
][sid
][opt
] = val
;
1122 delete n
[conf
][sid
][opt
];
1124 else if (typeof(val
) != 'undefined')
1126 /* do not set within deleted section */
1127 if (d
[conf
] && d
[conf
][sid
] === true)
1130 /* only set in existing sections */
1131 if (!v
[conf
] || !v
[conf
][sid
])
1140 /* undelete option */
1141 if (d
[conf
] && d
[conf
][sid
])
1142 d
[conf
][sid
] = L
.filterArray(d
[conf
][sid
], opt
);
1144 c
[conf
][sid
][opt
] = val
;
1148 /* only delete in existing sections */
1149 if (!v
[conf
] || !v
[conf
][sid
])
1158 if (d
[conf
][sid
] !== true)
1159 d
[conf
][sid
].push(opt
);
1163 unset: function(conf
, sid
, opt
)
1165 return this.set(conf
, sid
, opt
, undefined);
1168 get_first: function(conf
, type
, opt
)
1170 var sid
= undefined;
1172 L
.uci
.sections(conf
, type
, function(s
) {
1173 if (typeof(sid
) != 'string')
1177 return this.get(conf
, sid
, opt
);
1180 set_first: function(conf
, type
, opt
, val
)
1182 var sid
= undefined;
1184 L
.uci
.sections(conf
, type
, function(s
) {
1185 if (typeof(sid
) != 'string')
1189 return this.set(conf
, sid
, opt
, val
);
1192 unset_first: function(conf
, type
, opt
)
1194 return this.set_first(conf
, type
, opt
, undefined);
1197 swap: function(conf
, sid1
, sid2
)
1199 var s1
= this.get(conf
, sid1
);
1200 var s2
= this.get(conf
, sid2
);
1201 var n1
= s1
? s1
['.index'] : NaN
;
1202 var n2
= s2
? s2
['.index'] : NaN
;
1204 if (isNaN(n1
) || isNaN(n2
))
1210 this.state
.reorder
[conf
] = true;
1219 var v
= this.state
.values
;
1220 var n
= this.state
.creates
;
1221 var c
= this.state
.changes
;
1222 var d
= this.state
.deletes
;
1231 for (var sid
in n
[conf
])
1238 for (var k
in n
[conf
][sid
])
1241 r
.type
= n
[conf
][sid
][k
];
1242 else if (k
== '.create')
1243 r
.name
= n
[conf
][sid
][k
];
1244 else if (k
.charAt(0) != '.')
1245 r
.values
[k
] = n
[conf
][sid
][k
];
1248 snew
.push(n
[conf
][sid
]);
1250 self
.callAdd(r
.config
, r
.type
, r
.name
, r
.values
);
1259 for (var sid
in c
[conf
])
1260 self
.callSet(conf
, sid
, c
[conf
][sid
]);
1268 for (var sid
in d
[conf
])
1270 var o
= d
[conf
][sid
];
1271 self
.callDelete(conf
, sid
, (o
=== true) ? undefined : o
);
1277 return L
.rpc
.flush().then(function(responses
) {
1279 array "snew" holds references to the created uci sections,
1280 use it to assign the returned names of the new sections
1282 for (var i
= 0; i
< snew
.length
; i
++)
1283 snew
[i
]['.name'] = responses
[i
];
1285 return self
.reorderSections();
1286 }).then(function() {
1287 pkgs
= L
.toArray(pkgs
);
1291 return self
.load(pkgs
);
1295 apply: function(timeout
)
1298 var date
= new Date();
1299 var deferred
= $.Deferred();
1301 if (typeof(timeout
) != 'number' || timeout
< 1)
1304 self
.callApply(timeout
, true).then(function(rv
) {
1307 deferred
.rejectWith(self
, [ rv
]);
1311 var try_deadline
= date
.getTime() + 1000 * timeout
;
1312 var try_confirm = function()
1314 return self
.callConfirm().then(function(rv
) {
1317 if (date
.getTime() < try_deadline
)
1318 window
.setTimeout(try_confirm
, 250);
1320 deferred
.rejectWith(self
, [ rv
]);
1325 deferred
.resolveWith(self
, [ rv
]);
1329 window
.setTimeout(try_confirm
, 1000);
1335 changes
: L
.rpc
.declare({
1338 expect
: { changes
: { } }
1341 readable: function(conf
)
1343 return L
.session
.hasACL('uci', conf
, 'read');
1346 writable: function(conf
)
1348 return L
.session
.hasACL('uci', conf
, 'write');
1352 this.uci
= new this.UCIContext();
1355 listDeviceNames
: L
.rpc
.declare({
1358 expect
: { 'devices': [ ] },
1359 filter: function(data
) {
1365 getDeviceStatus
: L
.rpc
.declare({
1368 params
: [ 'device' ],
1369 expect
: { '': { } },
1370 filter: function(data
, params
) {
1371 if (!$.isEmptyObject(data
))
1373 data
['device'] = params
['device'];
1380 getAssocList
: L
.rpc
.declare({
1382 method
: 'assoclist',
1383 params
: [ 'device' ],
1384 expect
: { results
: [ ] },
1385 filter: function(data
, params
) {
1386 for (var i
= 0; i
< data
.length
; i
++)
1387 data
[i
]['device'] = params
['device'];
1389 data
.sort(function(a
, b
) {
1390 if (a
.bssid
< b
.bssid
)
1392 else if (a
.bssid
> b
.bssid
)
1402 getWirelessStatus: function() {
1403 return this.listDeviceNames().then(function(names
) {
1406 for (var i
= 0; i
< names
.length
; i
++)
1407 L
.wireless
.getDeviceStatus(names
[i
]);
1409 return L
.rpc
.flush();
1410 }).then(function(networks
) {
1414 'country', 'channel', 'frequency', 'frequency_offset',
1415 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1419 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1420 'signal', 'noise', 'bitrate', 'encryption'
1423 for (var i
= 0; i
< networks
.length
; i
++)
1425 var phy
= rv
[networks
[i
].phy
] || (
1426 rv
[networks
[i
].phy
] = { networks
: [ ] }
1430 device
: networks
[i
].device
1433 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1434 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1436 for (var j
= 0; j
< net_attrs
.length
; j
++)
1437 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1439 phy
.networks
.push(net
);
1446 getAssocLists: function()
1448 return this.listDeviceNames().then(function(names
) {
1451 for (var i
= 0; i
< names
.length
; i
++)
1452 L
.wireless
.getAssocList(names
[i
]);
1454 return L
.rpc
.flush();
1455 }).then(function(assoclists
) {
1458 for (var i
= 0; i
< assoclists
.length
; i
++)
1459 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1460 rv
.push(assoclists
[i
][j
]);
1466 formatEncryption: function(enc
)
1468 var format_list = function(l
, s
)
1471 for (var i
= 0; i
< l
.length
; i
++)
1472 rv
.push(l
[i
].toUpperCase());
1473 return rv
.join(s
? s
: ', ');
1476 if (!enc
|| !enc
.enabled
)
1477 return L
.tr('None');
1481 if (enc
.wep
.length
== 2)
1482 return L
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1483 else if (enc
.wep
[0] == 'shared')
1484 return L
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1486 return L
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1490 if (enc
.wpa
.length
== 2)
1491 return L
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1492 format_list(enc
.authentication
, '/'),
1493 format_list(enc
.ciphers
, ', ')
1495 else if (enc
.wpa
[0] == 2)
1496 return 'WPA2 %s (%s)'.format(
1497 format_list(enc
.authentication
, '/'),
1498 format_list(enc
.ciphers
, ', ')
1501 return 'WPA %s (%s)'.format(
1502 format_list(enc
.authentication
, '/'),
1503 format_list(enc
.ciphers
, ', ')
1507 return L
.tr('Unknown');
1512 getZoneColor: function(zone
)
1514 if ($.isPlainObject(zone
))
1519 else if (zone
== 'wan')
1522 for (var i
= 0, hash
= 0;
1524 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1526 for (var i
= 0, color
= '#';
1528 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tostring(16)).slice(-2));
1533 findZoneByNetwork: function(network
)
1536 var zone
= undefined;
1538 return L
.uci
.sections('firewall', 'zone', function(z
) {
1539 if (!z
.name
|| !z
.network
)
1542 if (!$.isArray(z
.network
))
1543 z
.network
= z
.network
.split(/\s+/);
1545 for (var i
= 0; i
< z
.network
.length
; i
++)
1547 if (z
.network
[i
] == network
)
1553 }).then(function() {
1555 zone
.color
= self
.getZoneColor(zone
);
1562 this.NetworkModel
= {
1569 /^wlan[0-9]+\.sta[0-9]+$/
1572 rpcCacheFunctions
: [
1573 'protolist', 0, L
.rpc
.declare({
1575 method
: 'get_proto_handlers',
1578 'ifstate', 1, L
.rpc
.declare({
1579 object
: 'network.interface',
1581 expect
: { 'interface': [ ] }
1583 'devstate', 2, L
.rpc
.declare({
1584 object
: 'network.device',
1588 'wifistate', 0, L
.rpc
.declare({
1589 object
: 'network.wireless',
1593 'bwstate', 2, L
.rpc
.declare({
1594 object
: 'luci2.network.bwmon',
1595 method
: 'statistics',
1596 expect
: { 'statistics': { } }
1598 'devlist', 2, L
.rpc
.declare({
1599 object
: 'luci2.network',
1600 method
: 'device_list',
1601 expect
: { 'devices': [ ] }
1603 'swlist', 0, L
.rpc
.declare({
1604 object
: 'luci2.network',
1605 method
: 'switch_list',
1606 expect
: { 'switches': [ ] }
1610 loadProtocolHandler: function(proto
)
1612 var url
= L
.globals
.resource
+ '/proto/' + proto
+ '.js';
1613 var self
= L
.NetworkModel
;
1615 var def
= $.Deferred();
1621 }).then(function(data
) {
1623 var protoConstructorSource
= (
1624 '(function(L, $) { ' +
1628 ).format(data
, url
);
1630 var protoClass
= eval(protoConstructorSource
);
1632 self
.protocolHandlers
[proto
] = new protoClass();
1635 alert('Unable to instantiate proto "%s": %s'.format(url
, e
));
1639 }).fail(function() {
1646 loadProtocolHandlers: function()
1648 var self
= L
.NetworkModel
;
1650 self
.loadProtocolHandler('none')
1653 for (var proto
in self
.rpcCache
.protolist
)
1654 deferreds
.push(self
.loadProtocolHandler(proto
));
1656 return $.when
.apply($, deferreds
);
1659 callSwitchInfo
: L
.rpc
.declare({
1660 object
: 'luci2.network',
1661 method
: 'switch_info',
1662 params
: [ 'switch' ],
1663 expect
: { 'info': { } }
1666 callSwitchInfoCallback: function(responses
) {
1667 var self
= L
.NetworkModel
;
1668 var swlist
= self
.rpcCache
.swlist
;
1669 var swstate
= self
.rpcCache
.swstate
= { };
1671 for (var i
= 0; i
< responses
.length
; i
++)
1672 swstate
[swlist
[i
]] = responses
[i
];
1675 loadCacheCallback: function(level
)
1677 var self
= L
.NetworkModel
;
1678 var name
= '_fetch_cache_cb_' + level
;
1680 return self
[name
] || (
1681 self
[name
] = function(responses
)
1683 for (var i
= 0; i
< self
.rpcCacheFunctions
.length
; i
+= 3)
1684 if (!level
|| self
.rpcCacheFunctions
[i
+ 1] == level
)
1685 self
.rpcCache
[self
.rpcCacheFunctions
[i
]] = responses
.shift();
1691 for (var i
= 0; i
< self
.rpcCache
.swlist
.length
; i
++)
1692 self
.callSwitchInfo(self
.rpcCache
.swlist
[i
]);
1694 return L
.rpc
.flush().then(self
.callSwitchInfoCallback
);
1697 return L
.deferrable();
1702 loadCache: function(level
)
1704 var self
= L
.NetworkModel
;
1706 return L
.uci
.load(['network', 'wireless']).then(function() {
1709 for (var i
= 0; i
< self
.rpcCacheFunctions
.length
; i
+= 3)
1710 if (!level
|| self
.rpcCacheFunctions
[i
+ 1] == level
)
1711 self
.rpcCacheFunctions
[i
+ 2]();
1713 return L
.rpc
.flush().then(self
.loadCacheCallback(level
|| 0));
1717 isBlacklistedDevice: function(dev
)
1719 for (var i
= 0; i
< this.deviceBlacklist
.length
; i
++)
1720 if (dev
.match(this.deviceBlacklist
[i
]))
1726 sortDevicesCallback: function(a
, b
)
1728 if (a
.options
.kind
< b
.options
.kind
)
1730 else if (a
.options
.kind
> b
.options
.kind
)
1733 if (a
.options
.name
< b
.options
.name
)
1735 else if (a
.options
.name
> b
.options
.name
)
1741 getDeviceObject: function(ifname
)
1743 var alias
= (ifname
.charAt(0) == '@');
1744 return this.deviceObjects
[ifname
] || (
1745 this.deviceObjects
[ifname
] = {
1747 kind
: alias
? 'alias' : 'ethernet',
1748 type
: alias
? 0 : 1,
1755 getInterfaceObject: function(name
)
1757 return this.interfaceObjects
[name
] || (
1758 this.interfaceObjects
[name
] = {
1760 proto
: this.protocolHandlers
.none
,
1766 loadDevicesCallback: function()
1768 var self
= L
.NetworkModel
;
1769 var wificount
= { };
1771 for (var ifname
in self
.rpcCache
.devstate
)
1773 if (self
.isBlacklistedDevice(ifname
))
1776 var dev
= self
.rpcCache
.devstate
[ifname
];
1777 var entry
= self
.getDeviceObject(ifname
);
1784 entry
.kind
= 'tunnel';
1788 entry
.kind
= 'bridge';
1789 //entry.ports = dev['bridge-members'].sort();
1794 for (var i
= 0; i
< self
.rpcCache
.devlist
.length
; i
++)
1796 var dev
= self
.rpcCache
.devlist
[i
];
1798 if (self
.isBlacklistedDevice(dev
.device
))
1801 var entry
= self
.getDeviceObject(dev
.device
);
1803 entry
.up
= dev
.is_up
;
1804 entry
.type
= dev
.type
;
1808 case 1: /* Ethernet */
1810 entry
.kind
= 'bridge';
1811 else if (dev
.is_tuntap
)
1812 entry
.kind
= 'tunnel';
1813 else if (dev
.is_wireless
)
1814 entry
.kind
= 'wifi';
1818 case 768: /* IP-IP Tunnel */
1819 case 769: /* IP6-IP6 Tunnel */
1820 case 776: /* IPv6-in-IPv4 */
1821 case 778: /* GRE over IP */
1822 entry
.kind
= 'tunnel';
1827 var net
= L
.uci
.sections('network');
1828 for (var i
= 0; i
< net
.length
; i
++)
1831 var sid
= s
['.name'];
1833 if (s
['.type'] == 'device' && s
.name
)
1835 var entry
= self
.getDeviceObject(s
.name
);
1841 entry
.kind
= 'tunnel';
1847 else if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.ifname
)
1849 var ifnames
= L
.toArray(s
.ifname
);
1851 for (var j
= 0; j
< ifnames
.length
; j
++)
1852 self
.getDeviceObject(ifnames
[j
]);
1854 if (s
['.name'] != 'loopback')
1856 var entry
= self
.getDeviceObject('@%s'.format(s
['.name']));
1859 entry
.kind
= 'alias';
1863 else if (s
['.type'] == 'switch_vlan' && s
.device
)
1865 var sw
= self
.rpcCache
.swstate
[s
.device
];
1866 var vid
= parseInt(s
.vid
|| s
.vlan
);
1867 var ports
= L
.toArray(s
.ports
);
1869 if (!sw
|| !ports
.length
|| isNaN(vid
))
1872 var ifname
= undefined;
1874 for (var j
= 0; j
< ports
.length
; j
++)
1876 var port
= parseInt(ports
[j
]);
1877 var tag
= (ports
[j
].replace(/[^tu]/g, '') == 't');
1879 if (port
== sw
.cpu_port
)
1881 // XXX: need a way to map switch to netdev
1883 ifname
= 'eth0.%d'.format(vid
);
1894 var entry
= self
.getDeviceObject(ifname
);
1896 entry
.kind
= 'vlan';
1903 var wifi
= L
.uci
.sections('wireless');
1904 for (var i
= 0; i
< wifi
.length
; i
++)
1907 var sid
= s
['.name'];
1909 if (s
['.type'] == 'wifi-iface' && s
.device
)
1911 var r
= parseInt(s
.device
.replace(/^[^0-9]+/, ''));
1912 var n
= wificount
[s
.device
] = (wificount
[s
.device
] || 0) + 1;
1913 var id
= 'radio%d.network%d'.format(r
, n
);
1916 if (self
.rpcCache
.wifistate
[s
.device
])
1918 var ifcs
= self
.rpcCache
.wifistate
[s
.device
].interfaces
;
1919 for (var ifc
in ifcs
)
1921 if (ifcs
[ifc
].section
== sid
)
1923 ifname
= ifcs
[ifc
].ifname
;
1929 var entry
= self
.getDeviceObject(ifname
);
1931 entry
.kind
= 'wifi';
1934 entry
.wdev
= s
.device
;
1935 entry
.wmode
= s
.mode
;
1936 entry
.wssid
= s
.ssid
;
1937 entry
.wbssid
= s
.bssid
;
1941 for (var i
= 0; i
< net
.length
; i
++)
1944 var sid
= s
['.name'];
1946 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.type
== 'bridge')
1948 var ifnames
= L
.toArray(s
.ifname
);
1950 for (var ifname
in self
.deviceObjects
)
1952 var dev
= self
.deviceObjects
[ifname
];
1954 if (dev
.kind
!= 'wifi')
1957 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1958 if ($.inArray(sid
, wnets
) > -1)
1959 ifnames
.push(ifname
);
1962 entry
= self
.getDeviceObject('br-%s'.format(s
['.name']));
1964 entry
.kind
= 'bridge';
1966 entry
.ports
= ifnames
.sort();
1971 loadInterfacesCallback: function()
1973 var self
= L
.NetworkModel
;
1974 var net
= L
.uci
.sections('network');
1976 for (var i
= 0; i
< net
.length
; i
++)
1979 var sid
= s
['.name'];
1981 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.proto
)
1983 var entry
= self
.getInterfaceObject(s
['.name']);
1984 var proto
= self
.protocolHandlers
[s
.proto
] || self
.protocolHandlers
.none
;
1986 var l3dev
= undefined;
1987 var l2dev
= undefined;
1989 var ifnames
= L
.toArray(s
.ifname
);
1991 for (var ifname
in self
.deviceObjects
)
1993 var dev
= self
.deviceObjects
[ifname
];
1995 if (dev
.kind
!= 'wifi')
1998 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1999 if ($.inArray(entry
.name
, wnets
) > -1)
2000 ifnames
.push(ifname
);
2004 l3dev
= '%s-%s'.format(s
.proto
, entry
.name
);
2005 else if (s
.type
== 'bridge')
2006 l3dev
= 'br-%s'.format(entry
.name
);
2010 if (!proto
.virtual
&& s
.type
== 'bridge')
2011 l2dev
= 'br-%s'.format(entry
.name
);
2012 else if (!proto
.virtual
)
2015 entry
.proto
= proto
;
2017 entry
.l3dev
= l3dev
;
2018 entry
.l2dev
= l2dev
;
2022 for (var i
= 0; i
< self
.rpcCache
.ifstate
.length
; i
++)
2024 var iface
= self
.rpcCache
.ifstate
[i
];
2025 var entry
= self
.getInterfaceObject(iface
['interface']);
2026 var proto
= self
.protocolHandlers
[iface
.proto
] || self
.protocolHandlers
.none
;
2028 /* this is a virtual interface, either deleted from config but
2029 not applied yet or set up from external tools (6rd) */
2032 entry
.proto
= proto
;
2033 entry
.l2dev
= iface
.device
;
2034 entry
.l3dev
= iface
.l3_device
;
2044 return L
.deferrable();
2046 self
.rpcCache
= { };
2047 self
.deviceObjects
= { };
2048 self
.interfaceObjects
= { };
2049 self
.protocolHandlers
= { };
2051 return self
.loadCache()
2052 .then(self
.loadProtocolHandlers
)
2053 .then(self
.loadDevicesCallback
)
2054 .then(self
.loadInterfacesCallback
);
2059 delete this.rpcCache
;
2063 refreshInterfaceStatus: function()
2065 return this.loadCache(1).then(this.loadInterfacesCallback
);
2068 refreshDeviceStatus: function()
2070 return this.loadCache(2).then(this.loadDevicesCallback
);
2073 refreshStatus: function()
2075 return this.loadCache(1)
2076 .then(this.loadCache(2))
2077 .then(this.loadDevicesCallback
)
2078 .then(this.loadInterfacesCallback
);
2081 getDevices: function()
2085 for (var ifname
in this.deviceObjects
)
2087 devs
.push(new L
.NetworkModel
.Device(this.deviceObjects
[ifname
]));
2089 return devs
.sort(this.sortDevicesCallback
);
2092 getDeviceByInterface: function(iface
)
2094 if (iface
instanceof L
.NetworkModel
.Interface
)
2095 iface
= iface
.name();
2097 if (this.interfaceObjects
[iface
])
2098 return this.getDevice(this.interfaceObjects
[iface
].l3dev
) ||
2099 this.getDevice(this.interfaceObjects
[iface
].l2dev
);
2104 getDevice: function(ifname
)
2106 if (this.deviceObjects
[ifname
])
2107 return new L
.NetworkModel
.Device(this.deviceObjects
[ifname
]);
2112 createDevice: function(name
)
2114 return new L
.NetworkModel
.Device(this.getDeviceObject(name
));
2117 getInterfaces: function()
2121 for (var name
in this.interfaceObjects
)
2122 if (name
!= 'loopback')
2123 ifaces
.push(this.getInterface(name
));
2125 ifaces
.sort(function(a
, b
) {
2126 if (a
.name() < b
.name())
2128 else if (a
.name() > b
.name())
2137 getInterfacesByDevice: function(dev
)
2141 if (dev
instanceof L
.NetworkModel
.Device
)
2144 for (var name
in this.interfaceObjects
)
2146 var iface
= this.interfaceObjects
[name
];
2147 if (iface
.l2dev
== dev
|| iface
.l3dev
== dev
)
2148 ifaces
.push(this.getInterface(name
));
2151 ifaces
.sort(function(a
, b
) {
2152 if (a
.name() < b
.name())
2154 else if (a
.name() > b
.name())
2163 getInterface: function(iface
)
2165 if (this.interfaceObjects
[iface
])
2166 return new L
.NetworkModel
.Interface(this.interfaceObjects
[iface
]);
2171 getProtocols: function()
2175 for (var proto
in this.protocolHandlers
)
2177 var pr
= this.protocolHandlers
[proto
];
2181 description
: pr
.description
,
2182 virtual
: pr
.virtual
,
2187 return rv
.sort(function(a
, b
) {
2188 if (a
.name
< b
.name
)
2190 else if (a
.name
> b
.name
)
2197 findWANByAddr: function(ipaddr
)
2199 for (var i
= 0; i
< this.rpcCache
.ifstate
.length
; i
++)
2201 var ifstate
= this.rpcCache
.ifstate
[i
];
2206 for (var j
= 0; j
< ifstate
.route
.length
; j
++)
2207 if (ifstate
.route
[j
].mask
== 0 &&
2208 ifstate
.route
[j
].target
== ipaddr
&&
2209 typeof(ifstate
.route
[j
].table
) == 'undefined')
2211 return this.getInterface(ifstate
['interface']);
2220 return this.findWANByAddr('0.0.0.0');
2223 findWAN6: function()
2225 return this.findWANByAddr('::');
2228 resolveAlias: function(ifname
)
2230 if (ifname
instanceof L
.NetworkModel
.Device
)
2231 ifname
= ifname
.name();
2233 var dev
= this.deviceObjects
[ifname
];
2236 while (dev
&& dev
.kind
== 'alias')
2239 if (seen
[dev
.ifname
])
2242 var ifc
= this.interfaceObjects
[dev
.sid
];
2244 seen
[dev
.ifname
] = true;
2245 dev
= ifc
? this.deviceObjects
[ifc
.l3dev
] : undefined;
2248 return dev
? this.getDevice(dev
.ifname
) : undefined;
2252 this.NetworkModel
.Device
= Class
.extend({
2255 sta
: L
.tr('Client'),
2256 adhoc
: L
.tr('Ad-Hoc'),
2257 monitor
: L
.tr('Monitor'),
2258 wds
: L
.tr('Static WDS')
2261 getStatus: function(key
)
2263 var s
= L
.NetworkModel
.rpcCache
.devstate
[this.options
.ifname
];
2266 return key
? s
[key
] : s
;
2273 var sid
= this.options
.sid
;
2274 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2275 return L
.uci
.get(pkg
, sid
, key
);
2278 set: function(key
, val
)
2280 var sid
= this.options
.sid
;
2281 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2282 return L
.uci
.set(pkg
, sid
, key
, val
);
2287 if (typeof(this.options
.type
) == 'undefined')
2288 this.options
.type
= 1;
2290 if (typeof(this.options
.kind
) == 'undefined')
2291 this.options
.kind
= 'ethernet';
2293 if (typeof(this.options
.networks
) == 'undefined')
2294 this.options
.networks
= [ ];
2299 return this.options
.ifname
;
2302 description: function()
2304 switch (this.options
.kind
)
2307 return L
.tr('Alias for network "%s"').format(this.options
.ifname
.substring(1));
2310 return L
.tr('Network bridge');
2313 return L
.tr('Network device');
2316 switch (this.options
.type
)
2318 case 1: /* tuntap */
2319 return L
.tr('TAP device');
2322 return L
.tr('PPP tunnel');
2324 case 768: /* IP-IP Tunnel */
2325 return L
.tr('IP-in-IP tunnel');
2327 case 769: /* IP6-IP6 Tunnel */
2328 return L
.tr('IPv6-in-IPv6 tunnel');
2330 case 776: /* IPv6-in-IPv4 */
2331 return L
.tr('IPv6-over-IPv4 tunnel');
2334 case 778: /* GRE over IP */
2335 return L
.tr('GRE-over-IP tunnel');
2338 return L
.tr('Tunnel device');
2342 return L
.tr('VLAN %d on %s').format(this.options
.vid
, this.options
.vsw
.model
);
2345 var o
= this.options
;
2346 return L
.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2347 o
.wmode
? this.wifiModeStrings
[o
.wmode
] : L
.tr('Unknown mode'),
2348 o
.wssid
|| '?', o
.wdev
2352 return L
.tr('Unknown device');
2357 var kind
= this.options
.kind
;
2359 if (kind
== 'alias')
2362 if (typeof(up
) == 'undefined')
2365 return L
.globals
.resource
+ '/icons/%s%s.png'.format(kind
, up
? '' : '_disabled');
2370 var l
= L
.NetworkModel
.rpcCache
.devlist
;
2372 for (var i
= 0; i
< l
.length
; i
++)
2373 if (l
[i
].device
== this.options
.ifname
)
2374 return (l
[i
].is_up
=== true);
2381 return (this.options
.kind
== 'alias');
2384 isBridge: function()
2386 return (this.options
.kind
== 'bridge');
2389 isBridgeable: function()
2391 return (this.options
.type
== 1 && this.options
.kind
!= 'bridge');
2394 isWireless: function()
2396 return (this.options
.kind
== 'wifi');
2399 isInNetwork: function(net
)
2401 if (!(net
instanceof L
.NetworkModel
.Interface
))
2402 net
= L
.NetworkModel
.getInterface(net
);
2406 if (net
.options
.l3dev
== this.options
.ifname
||
2407 net
.options
.l2dev
== this.options
.ifname
)
2410 var dev
= L
.NetworkModel
.deviceObjects
[net
.options
.l2dev
];
2411 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
)
2412 return ($.inArray(this.options
.ifname
, dev
.ports
) > -1);
2420 var dev
= L
.NetworkModel
.rpcCache
.devstate
[this.options
.ifname
];
2421 if (dev
&& !isNaN(dev
.mtu
))
2427 getMACAddress: function()
2429 if (this.options
.type
!= 1)
2432 var dev
= L
.NetworkModel
.rpcCache
.devstate
[this.options
.ifname
];
2433 if (dev
&& dev
.macaddr
)
2434 return dev
.macaddr
.toUpperCase();
2439 getInterfaces: function()
2441 return L
.NetworkModel
.getInterfacesByDevice(this.options
.name
);
2444 getStatistics: function()
2446 var s
= this.getStatus('statistics') || { };
2448 rx_bytes
: (s
.rx_bytes
|| 0),
2449 tx_bytes
: (s
.tx_bytes
|| 0),
2450 rx_packets
: (s
.rx_packets
|| 0),
2451 tx_packets
: (s
.tx_packets
|| 0)
2455 getTrafficHistory: function()
2457 var def
= new Array(120);
2459 for (var i
= 0; i
< 120; i
++)
2462 var h
= L
.NetworkModel
.rpcCache
.bwstate
[this.options
.ifname
] || { };
2464 rx_bytes
: (h
.rx_bytes
|| def
),
2465 tx_bytes
: (h
.tx_bytes
|| def
),
2466 rx_packets
: (h
.rx_packets
|| def
),
2467 tx_packets
: (h
.tx_packets
|| def
)
2471 removeFromInterface: function(iface
)
2473 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2474 iface
= L
.NetworkModel
.getInterface(iface
);
2479 var ifnames
= L
.toArray(iface
.get('ifname'));
2480 if ($.inArray(this.options
.ifname
, ifnames
) > -1)
2481 iface
.set('ifname', L
.filterArray(ifnames
, this.options
.ifname
));
2483 if (this.options
.kind
!= 'wifi')
2486 var networks
= L
.toArray(this.get('network'));
2487 if ($.inArray(iface
.name(), networks
) > -1)
2488 this.set('network', L
.filterArray(networks
, iface
.name()));
2491 attachToInterface: function(iface
)
2493 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2494 iface
= L
.NetworkModel
.getInterface(iface
);
2499 if (this.options
.kind
!= 'wifi')
2501 var ifnames
= L
.toArray(iface
.get('ifname'));
2502 if ($.inArray(this.options
.ifname
, ifnames
) < 0)
2504 ifnames
.push(this.options
.ifname
);
2505 iface
.set('ifname', (ifnames
.length
> 1) ? ifnames
: ifnames
[0]);
2510 var networks
= L
.toArray(this.get('network'));
2511 if ($.inArray(iface
.name(), networks
) < 0)
2513 networks
.push(iface
.name());
2514 this.set('network', (networks
.length
> 1) ? networks
: networks
[0]);
2520 this.NetworkModel
.Interface
= Class
.extend({
2521 getStatus: function(key
)
2523 var s
= L
.NetworkModel
.rpcCache
.ifstate
;
2525 for (var i
= 0; i
< s
.length
; i
++)
2526 if (s
[i
]['interface'] == this.options
.name
)
2527 return key
? s
[i
][key
] : s
[i
];
2534 return L
.uci
.get('network', this.options
.name
, key
);
2537 set: function(key
, val
)
2539 return L
.uci
.set('network', this.options
.name
, key
, val
);
2544 return this.options
.name
;
2547 protocol: function()
2549 return (this.get('proto') || 'none');
2554 return (this.getStatus('up') === true);
2557 isVirtual: function()
2559 return (typeof(this.options
.sid
) != 'string');
2562 getProtocol: function()
2564 var prname
= this.get('proto') || 'none';
2565 return L
.NetworkModel
.protocolHandlers
[prname
] || L
.NetworkModel
.protocolHandlers
.none
;
2568 getUptime: function()
2570 var uptime
= this.getStatus('uptime');
2571 return isNaN(uptime
) ? 0 : uptime
;
2574 getDevice: function(resolveAlias
)
2576 if (this.options
.l3dev
)
2577 return L
.NetworkModel
.getDevice(this.options
.l3dev
);
2582 getPhysdev: function()
2584 if (this.options
.l2dev
)
2585 return L
.NetworkModel
.getDevice(this.options
.l2dev
);
2590 getSubdevices: function()
2593 var dev
= this.options
.l2dev
?
2594 L
.NetworkModel
.deviceObjects
[this.options
.l2dev
] : undefined;
2596 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
&& dev
.ports
.length
)
2597 for (var i
= 0; i
< dev
.ports
.length
; i
++)
2598 rv
.push(L
.NetworkModel
.getDevice(dev
.ports
[i
]));
2603 getIPv4Addrs: function(mask
)
2606 var addrs
= this.getStatus('ipv4-address');
2609 for (var i
= 0; i
< addrs
.length
; i
++)
2611 rv
.push(addrs
[i
].address
);
2613 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2618 getIPv6Addrs: function(mask
)
2623 addrs
= this.getStatus('ipv6-address');
2626 for (var i
= 0; i
< addrs
.length
; i
++)
2628 rv
.push(addrs
[i
].address
);
2630 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2632 addrs
= this.getStatus('ipv6-prefix-assignment');
2635 for (var i
= 0; i
< addrs
.length
; i
++)
2637 rv
.push('%s1'.format(addrs
[i
].address
));
2639 rv
.push('%s1/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2644 getDNSAddrs: function()
2647 var addrs
= this.getStatus('dns-server');
2650 for (var i
= 0; i
< addrs
.length
; i
++)
2656 getIPv4DNS: function()
2659 var dns
= this.getStatus('dns-server');
2662 for (var i
= 0; i
< dns
.length
; i
++)
2663 if (dns
[i
].indexOf(':') == -1)
2669 getIPv6DNS: function()
2672 var dns
= this.getStatus('dns-server');
2675 for (var i
= 0; i
< dns
.length
; i
++)
2676 if (dns
[i
].indexOf(':') > -1)
2682 getIPv4Gateway: function()
2684 var rt
= this.getStatus('route');
2687 for (var i
= 0; i
< rt
.length
; i
++)
2688 if (rt
[i
].target
== '0.0.0.0' && rt
[i
].mask
== 0)
2689 return rt
[i
].nexthop
;
2694 getIPv6Gateway: function()
2696 var rt
= this.getStatus('route');
2699 for (var i
= 0; i
< rt
.length
; i
++)
2700 if (rt
[i
].target
== '::' && rt
[i
].mask
== 0)
2701 return rt
[i
].nexthop
;
2706 getStatistics: function()
2708 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2709 return dev
.getStatistics();
2712 getTrafficHistory: function()
2714 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2715 return dev
.getTrafficHistory();
2718 renderBadge: function()
2720 var badge
= $('<span />')
2722 .text('%s: '.format(this.name()));
2724 var dev
= this.getDevice();
2725 var subdevs
= this.getSubdevices();
2728 for (var j
= 0; j
< subdevs
.length
; j
++)
2729 badge
.append($('<img />')
2730 .attr('src', subdevs
[j
].icon())
2731 .attr('title', '%s (%s)'.format(subdevs
[j
].description(), subdevs
[j
].name() || '?')));
2733 badge
.append($('<img />')
2734 .attr('src', dev
.icon())
2735 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?')));
2737 badge
.append($('<em />').text(L
.tr('(No devices attached)')));
2742 setDevices: function(devs
)
2744 var dev
= this.getPhysdev();
2746 var changed
= false;
2748 if (dev
&& dev
.isBridge())
2749 old_devs
= this.getSubdevices();
2753 if (old_devs
.length
!= devs
.length
)
2756 for (var i
= 0; i
< old_devs
.length
; i
++)
2760 if (dev
instanceof L
.NetworkModel
.Device
)
2763 if (!dev
|| old_devs
[i
].name() != dev
)
2772 for (var i
= 0; i
< old_devs
.length
; i
++)
2773 old_devs
[i
].removeFromInterface(this);
2775 for (var i
= 0; i
< devs
.length
; i
++)
2779 if (!(dev
instanceof L
.NetworkModel
.Device
))
2780 dev
= L
.NetworkModel
.getDevice(dev
);
2783 dev
.attachToInterface(this);
2788 changeProtocol: function(proto
)
2790 var pr
= L
.NetworkModel
.protocolHandlers
[proto
];
2795 for (var opt
in (this.get() || { }))
2803 this.set(opt
, undefined);
2811 this.set(opt
, pr
.protocol
);
2815 this.set(opt
, undefined);
2821 createForm: function(mapwidget
)
2824 var proto
= self
.getProtocol();
2825 var device
= self
.getDevice();
2828 mapwidget
= L
.cbi
.Map
;
2830 var map
= new mapwidget('network', {
2831 caption
: L
.tr('Configure "%s"').format(self
.name())
2834 var section
= map
.section(L
.cbi
.SingleSection
, self
.name(), {
2840 caption
: L
.tr('General Settings')
2845 caption
: L
.tr('Advanced Settings')
2850 caption
: L
.tr('IPv6')
2855 caption
: L
.tr('Physical Settings')
2859 section
.taboption('general', L
.cbi
.CheckboxValue
, 'auto', {
2860 caption
: L
.tr('Start on boot'),
2865 var pr
= section
.taboption('general', L
.cbi
.ListValue
, 'proto', {
2866 caption
: L
.tr('Protocol')
2869 pr
.ucivalue = function(sid
) {
2870 return self
.get('proto') || 'none';
2873 var ok
= section
.taboption('general', L
.cbi
.ButtonValue
, '_confirm', {
2874 caption
: L
.tr('Really switch?'),
2875 description
: L
.tr('Changing the protocol will clear all configuration for this interface!'),
2876 text
: L
.tr('Change protocol')
2879 ok
.on('click', function(ev
) {
2880 self
.changeProtocol(pr
.formvalue(ev
.data
.sid
));
2881 self
.createForm(mapwidget
).show();
2884 var protos
= L
.NetworkModel
.getProtocols();
2886 for (var i
= 0; i
< protos
.length
; i
++)
2887 pr
.value(protos
[i
].name
, protos
[i
].description
);
2889 proto
.populateForm(section
, self
);
2893 var br
= section
.taboption('physical', L
.cbi
.CheckboxValue
, 'type', {
2894 caption
: L
.tr('Network bridge'),
2895 description
: L
.tr('Merges multiple devices into one logical bridge'),
2902 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_multi', {
2903 caption
: L
.tr('Devices'),
2906 }).depends('type', true);
2908 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_single', {
2909 caption
: L
.tr('Device'),
2912 }).depends('type', false);
2914 var mac
= section
.taboption('physical', L
.cbi
.InputValue
, 'macaddr', {
2915 caption
: L
.tr('Override MAC'),
2917 placeholder
: device
? device
.getMACAddress() : undefined,
2921 mac
.ucivalue = function(sid
)
2924 return device
.get('macaddr');
2926 return this.callSuper('ucivalue', sid
);
2929 mac
.save = function(sid
)
2931 if (!this.changed(sid
))
2935 device
.set('macaddr', this.formvalue(sid
));
2937 this.callSuper('set', sid
);
2943 section
.taboption('physical', L
.cbi
.InputValue
, 'mtu', {
2944 caption
: L
.tr('Override MTU'),
2946 placeholder
: device
? device
.getMTU() : undefined,
2947 datatype
: 'range(1, 9000)'
2950 section
.taboption('physical', L
.cbi
.InputValue
, 'metric', {
2951 caption
: L
.tr('Override Metric'),
2954 datatype
: 'uinteger'
2957 for (var field
in section
.fields
)
2965 for (var i
= 0; i
< protos
.length
; i
++)
2966 if (protos
[i
].name
!= (this.get('proto') || 'none'))
2967 section
.fields
[field
].depends('proto', protos
[i
].name
);
2971 section
.fields
[field
].depends('proto', this.get('proto') || 'none', true);
2980 this.NetworkModel
.Protocol
= this.NetworkModel
.Interface
.extend({
2981 description
: '__unknown__',
2985 populateForm: function(section
, iface
)
2992 getSystemInfo
: L
.rpc
.declare({
2998 getBoardInfo
: L
.rpc
.declare({
3004 getDiskInfo
: L
.rpc
.declare({
3005 object
: 'luci2.system',
3010 getInfo: function(cb
)
3014 this.getSystemInfo();
3015 this.getBoardInfo();
3018 return L
.rpc
.flush().then(function(info
) {
3021 $.extend(rv
, info
[0]);
3022 $.extend(rv
, info
[1]);
3023 $.extend(rv
, info
[2]);
3030 initList
: L
.rpc
.declare({
3031 object
: 'luci2.system',
3032 method
: 'init_list',
3033 expect
: { initscripts
: [ ] },
3034 filter: function(data
) {
3035 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
3040 initEnabled: function(init
, cb
)
3042 return this.initList().then(function(list
) {
3043 for (var i
= 0; i
< list
.length
; i
++)
3044 if (list
[i
].name
== init
)
3045 return !!list
[i
].enabled
;
3051 initRun
: L
.rpc
.declare({
3052 object
: 'luci2.system',
3053 method
: 'init_action',
3054 params
: [ 'name', 'action' ],
3055 filter: function(data
) {
3060 initStart: function(init
, cb
) { return L
.system
.initRun(init
, 'start', cb
) },
3061 initStop: function(init
, cb
) { return L
.system
.initRun(init
, 'stop', cb
) },
3062 initRestart: function(init
, cb
) { return L
.system
.initRun(init
, 'restart', cb
) },
3063 initReload: function(init
, cb
) { return L
.system
.initRun(init
, 'reload', cb
) },
3064 initEnable: function(init
, cb
) { return L
.system
.initRun(init
, 'enable', cb
) },
3065 initDisable: function(init
, cb
) { return L
.system
.initRun(init
, 'disable', cb
) },
3068 performReboot
: L
.rpc
.declare({
3069 object
: 'luci2.system',
3076 login
: L
.rpc
.declare({
3079 params
: [ 'username', 'password' ],
3083 access
: L
.rpc
.declare({
3086 params
: [ 'scope', 'object', 'function' ],
3087 expect
: { access
: false }
3092 return L
.session
.access('ubus', 'session', 'access');
3095 startHeartbeat: function()
3097 this._hearbeatInterval
= window
.setInterval(function() {
3098 L
.session
.isAlive().then(function(alive
) {
3101 L
.session
.stopHeartbeat();
3106 }, L
.globals
.timeout
* 2);
3109 stopHeartbeat: function()
3111 if (typeof(this._hearbeatInterval
) != 'undefined')
3113 window
.clearInterval(this._hearbeatInterval
);
3114 delete this._hearbeatInterval
;
3121 callAccess
: L
.rpc
.declare({
3127 callAccessCallback: function(acls
)
3129 L
.session
.aclCache
= acls
;
3132 updateACLs: function()
3134 return L
.session
.callAccess()
3135 .then(L
.session
.callAccessCallback
);
3138 hasACL: function(scope
, object
, func
)
3140 var acls
= L
.session
.aclCache
;
3142 if (typeof(func
) == 'undefined')
3143 return (acls
&& acls
[scope
] && acls
[scope
][object
]);
3145 if (acls
&& acls
[scope
] && acls
[scope
][object
])
3146 for (var i
= 0; i
< acls
[scope
][object
].length
; i
++)
3147 if (acls
[scope
][object
][i
] == func
)
3156 saveScrollTop: function()
3158 this._scroll_top
= $(document
).scrollTop();
3161 restoreScrollTop: function()
3163 if (typeof(this._scroll_top
) == 'undefined')
3166 $(document
).scrollTop(this._scroll_top
);
3168 delete this._scroll_top
;
3171 loading: function(enable
)
3173 var win
= $(window
);
3174 var body
= $('body');
3176 var state
= L
.ui
._loading
|| (L
.ui
._loading
= {
3178 .css('z-index', 2000)
3179 .addClass('modal fade')
3180 .append($('<div />')
3181 .addClass('modal-dialog')
3182 .append($('<div />')
3183 .addClass('modal-content luci2-modal-loader')
3184 .append($('<div />')
3185 .addClass('modal-body')
3186 .text(L
.tr('Loading data…')))))
3194 state
.modal
.modal(enable
? 'show' : 'hide');
3197 dialog: function(title
, content
, options
)
3199 var win
= $(window
);
3200 var body
= $('body');
3202 var state
= L
.ui
._dialog
|| (L
.ui
._dialog
= {
3203 dialog
: $('<div />')
3204 .addClass('modal fade')
3205 .append($('<div />')
3206 .addClass('modal-dialog')
3207 .append($('<div />')
3208 .addClass('modal-content')
3209 .append($('<div />')
3210 .addClass('modal-header')
3212 .addClass('modal-title'))
3213 .append($('<div />')
3214 .addClass('modal-body'))
3215 .append($('<div />')
3216 .addClass('modal-footer')
3217 .append(L
.ui
.button(L
.tr('Close'), 'primary')
3219 $(this).parents('div.modal').modal('hide');
3224 if (typeof(options
) != 'object')
3227 if (title
=== false)
3229 state
.dialog
.modal('hide');
3231 return state
.dialog
;
3234 var cnt
= state
.dialog
.children().children().children('div.modal-body');
3235 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
3239 if (options
.style
== 'confirm')
3241 ftr
.append(L
.ui
.button(L
.tr('Ok'), 'primary')
3242 .click(options
.confirm
|| function() { L
.ui
.dialog(false) }));
3244 ftr
.append(L
.ui
.button(L
.tr('Cancel'), 'default')
3245 .click(options
.cancel
|| function() { L
.ui
.dialog(false) }));
3247 else if (options
.style
== 'close')
3249 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3250 .click(options
.close
|| function() { L
.ui
.dialog(false) }));
3252 else if (options
.style
== 'wait')
3254 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3255 .attr('disabled', true));
3260 state
.dialog
.addClass('wide');
3264 state
.dialog
.removeClass('wide');
3267 state
.dialog
.find('h4:first').text(title
);
3268 state
.dialog
.modal('show');
3270 cnt
.empty().append(content
);
3272 return state
.dialog
;
3275 upload: function(title
, content
, options
)
3277 var state
= L
.ui
._upload
|| (L
.ui
._upload
= {
3279 .attr('method', 'post')
3280 .attr('action', '/cgi-bin/luci-upload')
3281 .attr('enctype', 'multipart/form-data')
3282 .attr('target', 'cbi-fileupload-frame')
3284 .append($('<input />')
3285 .attr('type', 'hidden')
3286 .attr('name', 'sessionid'))
3287 .append($('<input />')
3288 .attr('type', 'hidden')
3289 .attr('name', 'filename'))
3290 .append($('<input />')
3291 .attr('type', 'file')
3292 .attr('name', 'filedata')
3293 .addClass('cbi-input-file'))
3294 .append($('<div />')
3295 .css('width', '100%')
3296 .addClass('progress progress-striped active')
3297 .append($('<div />')
3298 .addClass('progress-bar')
3299 .css('width', '100%')))
3300 .append($('<iframe />')
3301 .addClass('pull-right')
3302 .attr('name', 'cbi-fileupload-frame')
3303 .css('width', '1px')
3304 .css('height', '1px')
3305 .css('visibility', 'hidden')),
3307 finish_cb: function(ev
) {
3308 $(this).off('load');
3310 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
3311 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
3312 body
= body
.firstChild
;
3316 json
= $.parseJSON(body
.innerHTML
);
3319 message
: L
.tr('Invalid server response received'),
3320 error
: [ -1, L
.tr('Invalid data') ]
3326 L
.ui
.dialog(L
.tr('File upload'), [
3327 $('<p />').text(L
.tr('The file upload failed with the server response below:')),
3328 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
3329 $('<p />').text(L
.tr('In case of network problems try uploading the file again.'))
3330 ], { style
: 'close' });
3332 else if (typeof(state
.success_cb
) == 'function')
3334 state
.success_cb(json
);
3338 confirm_cb: function() {
3339 var f
= state
.form
.find('.cbi-input-file');
3340 var b
= state
.form
.find('.progress');
3341 var p
= state
.form
.find('p');
3346 state
.form
.find('iframe').on('load', state
.finish_cb
);
3347 state
.form
.submit();
3351 p
.text(L
.tr('File upload in progress …'));
3353 state
.form
.parent().parent().find('button').prop('disabled', true);
3357 state
.form
.find('.progress').hide();
3358 state
.form
.find('.cbi-input-file').val('').show();
3359 state
.form
.find('p').text(content
|| L
.tr('Select the file to upload and press "%s" to proceed.').format(L
.tr('Ok')));
3361 state
.form
.find('[name=sessionid]').val(L
.globals
.sid
);
3362 state
.form
.find('[name=filename]').val(options
.filename
);
3364 state
.success_cb
= options
.success
;
3366 L
.ui
.dialog(title
|| L
.tr('File upload'), state
.form
, {
3368 confirm
: state
.confirm_cb
3372 reconnect: function()
3374 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3375 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
3376 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
3378 var interval
, timeout
;
3381 L
.tr('Waiting for device'), [
3382 $('<p />').text(L
.tr('Please stand by while the device is reconfiguring …')),
3384 .css('width', '100%')
3385 .addClass('progressbar')
3386 .addClass('intermediate')
3387 .append($('<div />')
3388 .css('width', '100%'))
3389 ], { style
: 'wait' }
3392 for (var i
= 0; i
< protocols
.length
; i
++)
3393 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
3395 //L.network.getNetworkStatus(function(s) {
3396 // for (var i = 0; i < protocols.length; i++)
3398 // for (var j = 0; j < s.length; j++)
3400 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3401 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3403 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3404 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3407 //}).then(function() {
3408 images
.on('load', function() {
3409 var url
= this.getAttribute('url');
3410 L
.session
.isAlive().then(function(access
) {
3413 window
.clearTimeout(timeout
);
3414 window
.clearInterval(interval
);
3420 location
.href
= url
;
3425 interval
= window
.setInterval(function() {
3426 images
.each(function() {
3427 this.setAttribute('src', this.getAttribute('url') + L
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
3431 timeout
= window
.setTimeout(function() {
3432 window
.clearInterval(interval
);
3436 L
.tr('Device not responding'),
3437 L
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3444 login: function(invalid
)
3446 var state
= L
.ui
._login
|| (L
.ui
._login
= {
3449 .attr('method', 'post')
3451 .addClass('alert-message')
3452 .text(L
.tr('Wrong username or password given!')))
3454 .append($('<label />')
3455 .text(L
.tr('Username'))
3456 .append($('<br />'))
3457 .append($('<input />')
3458 .attr('type', 'text')
3459 .attr('name', 'username')
3460 .attr('value', 'root')
3461 .addClass('form-control')
3462 .keypress(function(ev
) {
3463 if (ev
.which
== 10 || ev
.which
== 13)
3467 .append($('<label />')
3468 .text(L
.tr('Password'))
3469 .append($('<br />'))
3470 .append($('<input />')
3471 .attr('type', 'password')
3472 .attr('name', 'password')
3473 .addClass('form-control')
3474 .keypress(function(ev
) {
3475 if (ev
.which
== 10 || ev
.which
== 13)
3479 .text(L
.tr('Enter your username and password above, then click "%s" to proceed.').format(L
.tr('Ok')))),
3481 response_cb: function(response
) {
3482 if (!response
.ubus_rpc_session
)
3488 L
.globals
.sid
= response
.ubus_rpc_session
;
3489 L
.setHash('id', L
.globals
.sid
);
3490 L
.session
.startHeartbeat();
3492 state
.deferred
.resolve();
3496 confirm_cb: function() {
3497 var u
= state
.form
.find('[name=username]').val();
3498 var p
= state
.form
.find('[name=password]').val();
3504 L
.tr('Logging in'), [
3505 $('<p />').text(L
.tr('Log in in progress …')),
3507 .css('width', '100%')
3508 .addClass('progressbar')
3509 .addClass('intermediate')
3510 .append($('<div />')
3511 .css('width', '100%'))
3512 ], { style
: 'wait' }
3515 L
.globals
.sid
= '00000000000000000000000000000000';
3516 L
.session
.login(u
, p
).then(state
.response_cb
);
3520 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
3521 state
.deferred
= $.Deferred();
3523 /* try to find sid from hash */
3524 var sid
= L
.getHash('id');
3525 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
3527 L
.globals
.sid
= sid
;
3528 L
.session
.isAlive().then(function(access
) {
3531 L
.session
.startHeartbeat();
3532 state
.deferred
.resolve();
3536 L
.setHash('id', undefined);
3541 return state
.deferred
;
3545 state
.form
.find('.alert-message').show();
3547 state
.form
.find('.alert-message').hide();
3549 L
.ui
.dialog(L
.tr('Authorization Required'), state
.form
, {
3551 confirm
: state
.confirm_cb
3554 state
.form
.find('[name=password]').focus();
3556 return state
.deferred
;
3559 cryptPassword
: L
.rpc
.declare({
3563 expect
: { crypt
: '' }
3567 mergeACLScope: function(acl_scope
, scope
)
3569 if ($.isArray(scope
))
3571 for (var i
= 0; i
< scope
.length
; i
++)
3572 acl_scope
[scope
[i
]] = true;
3574 else if ($.isPlainObject(scope
))
3576 for (var object_name
in scope
)
3578 if (!$.isArray(scope
[object_name
]))
3581 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
3583 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
3584 acl_object
[scope
[object_name
][i
]] = true;
3589 mergeACLPermission: function(acl_perm
, perm
)
3591 if ($.isPlainObject(perm
))
3593 for (var scope_name
in perm
)
3595 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
3596 L
.ui
.mergeACLScope(acl_scope
, perm
[scope_name
]);
3601 mergeACLGroup: function(acl_group
, group
)
3603 if ($.isPlainObject(group
))
3605 if (!acl_group
.description
)
3606 acl_group
.description
= group
.description
;
3610 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
3611 L
.ui
.mergeACLPermission(acl_perm
, group
.read
);
3616 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
3617 L
.ui
.mergeACLPermission(acl_perm
, group
.write
);
3622 callACLsCallback: function(trees
)
3626 for (var i
= 0; i
< trees
.length
; i
++)
3628 if (!$.isPlainObject(trees
[i
]))
3631 for (var group_name
in trees
[i
])
3633 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
3634 L
.ui
.mergeACLGroup(acl_group
, trees
[i
][group_name
]);
3641 callACLs
: L
.rpc
.declare({
3644 expect
: { acls
: [ ] }
3647 getAvailableACLs: function()
3649 return this.callACLs().then(this.callACLsCallback
);
3652 renderChangeIndicator: function()
3655 .addClass('nav navbar-nav navbar-right')
3658 .attr('id', 'changes')
3660 .append($('<span />')
3661 .addClass('label label-info'))));
3664 callMenuCallback: function(entries
)
3666 L
.globals
.mainMenu
= new L
.ui
.menu();
3667 L
.globals
.mainMenu
.entries(entries
);
3671 .append(L
.globals
.mainMenu
.render(0, 1))
3672 .append(L
.ui
.renderChangeIndicator());
3675 callMenu
: L
.rpc
.declare({
3678 expect
: { menu
: { } }
3681 renderMainMenu: function()
3683 return this.callMenu().then(this.callMenuCallback
);
3686 renderViewMenu: function()
3690 .append(L
.globals
.mainMenu
.render(2, 900));
3693 renderView: function()
3695 var node
= arguments
[0];
3696 var name
= node
.view
.split(/\//).join('.');
3697 var cname
= L
.toClassName(name
);
3698 var views
= L
.views
|| (L
.views
= { });
3701 for (var i
= 1; i
< arguments
.length
; i
++)
3702 args
.push(arguments
[i
]);
3704 if (L
.globals
.currentView
)
3705 L
.globals
.currentView
.finish();
3707 L
.ui
.renderViewMenu();
3708 L
.setHash('view', node
.view
);
3710 if (views
[cname
] instanceof L
.ui
.view
)
3712 L
.globals
.currentView
= views
[cname
];
3713 return views
[cname
].render
.apply(views
[cname
], args
);
3716 var url
= L
.globals
.resource
+ '/view/' + name
+ '.js';
3718 return $.ajax(url
, {
3722 }).then(function(data
) {
3724 var viewConstructorSource
= (
3725 '(function(L, $) { ' +
3729 ).format(data
, url
);
3731 var viewConstructor
= eval(viewConstructorSource
);
3733 views
[cname
] = new viewConstructor({
3735 acls
: node
.write
|| { }
3738 L
.globals
.currentView
= views
[cname
];
3739 return views
[cname
].render
.apply(views
[cname
], args
);
3742 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
3745 return $.Deferred().resolve();
3749 changeView: function()
3751 var name
= L
.getHash('view');
3752 var node
= L
.globals
.defaultNode
;
3754 if (name
&& L
.globals
.mainMenu
)
3755 node
= L
.globals
.mainMenu
.getNode(name
);
3760 L
.ui
.renderView(node
).then(function() {
3761 L
.ui
.loading(false);
3766 updateHostname: function()
3768 return L
.system
.getBoardInfo().then(function(info
) {
3770 $('#hostname').text(info
.hostname
);
3774 updateChanges: function()
3776 return L
.uci
.changes().then(function(changes
) {
3780 for (var config
in changes
)
3784 for (var i
= 0; i
< changes
[config
].length
; i
++)
3786 var c
= changes
[config
][i
];
3791 log
.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3796 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
3798 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
3803 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
3805 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3809 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
3813 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3817 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3822 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3824 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3829 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
3830 n
+= changes
[config
].length
;
3835 .click(function(ev
) {
3836 L
.ui
.dialog(L
.tr('Staged configuration changes'), html
, {
3838 confirm: function() {
3840 function(code
) { alert('Success with code ' + code
); },
3841 function(code
) { alert('Error with code ' + code
); }
3845 ev
.preventDefault();
3849 .text(L
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
));
3851 $('#changes').children('span').hide();
3860 L
.session
.updateACLs(),
3861 L
.ui
.updateHostname(),
3862 L
.ui
.updateChanges(),
3863 L
.ui
.renderMainMenu(),
3864 L
.NetworkModel
.init()
3866 L
.ui
.renderView(L
.globals
.defaultNode
).then(function() {
3867 L
.ui
.loading(false);
3870 $(window
).on('hashchange', function() {
3876 button: function(label
, style
, title
)
3878 style
= style
|| 'default';
3880 return $('<button />')
3881 .attr('type', 'button')
3882 .attr('title', title
? title
: '')
3883 .addClass('btn btn-' + style
)
3888 this.ui
.AbstractWidget
= Class
.extend({
3889 i18n: function(text
) {
3894 var key
= arguments
[0];
3897 for (var i
= 1; i
< arguments
.length
; i
++)
3898 args
.push(arguments
[i
]);
3900 switch (typeof(this.options
[key
]))
3906 return this.options
[key
].apply(this, args
);
3909 return ''.format
.apply('' + this.options
[key
], args
);
3913 toString: function() {
3914 return $('<div />').append(this.render()).html();
3917 insertInto: function(id
) {
3918 return $(id
).empty().append(this.render());
3921 appendTo: function(id
) {
3922 return $(id
).append(this.render());
3925 on: function(evname
, evfunc
)
3927 var evnames
= L
.toArray(evname
);
3932 for (var i
= 0; i
< evnames
.length
; i
++)
3933 this.events
[evnames
[i
]] = evfunc
;
3938 trigger: function(evname
, evdata
)
3942 var evnames
= L
.toArray(evname
);
3944 for (var i
= 0; i
< evnames
.length
; i
++)
3945 if (this.events
[evnames
[i
]])
3946 this.events
[evnames
[i
]].call(this, evdata
);
3953 this.ui
.view
= this.ui
.AbstractWidget
.extend({
3954 _fetch_template: function()
3956 return $.ajax(L
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
3960 success: function(data
) {
3961 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
3962 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
3972 return L
.globals
[p2
] || '';
3975 return '(?' + match
+ ')';
3979 $('#maincontent').append(data
);
3986 throw "Not implemented";
3991 var container
= $('#maincontent');
3996 container
.append($('<h2 />').append(this.title
));
3998 if (this.description
)
3999 container
.append($('<p />').append(this.description
));
4004 for (var i
= 0; i
< arguments
.length
; i
++)
4005 args
.push(arguments
[i
]);
4007 return this._fetch_template().then(function() {
4008 return L
.deferrable(self
.execute
.apply(self
, args
));
4012 repeat: function(func
, interval
)
4016 if (!self
._timeouts
)
4017 self
._timeouts
= [ ];
4019 var index
= self
._timeouts
.length
;
4021 if (typeof(interval
) != 'number')
4024 var setTimer
, runTimer
;
4026 setTimer = function() {
4028 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
4031 runTimer = function() {
4032 L
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
4040 if ($.isArray(this._timeouts
))
4042 for (var i
= 0; i
< this._timeouts
.length
; i
++)
4043 window
.clearTimeout(this._timeouts
[i
]);
4045 delete this._timeouts
;
4050 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
4055 entries: function(entries
)
4057 for (var entry
in entries
)
4059 var path
= entry
.split(/\//);
4060 var node
= this._nodes
;
4062 for (i
= 0; i
< path
.length
; i
++)
4067 if (!node
.childs
[path
[i
]])
4068 node
.childs
[path
[i
]] = { };
4070 node
= node
.childs
[path
[i
]];
4073 $.extend(node
, entries
[entry
]);
4077 sortNodesCallback: function(a
, b
)
4079 var x
= a
.index
|| 0;
4080 var y
= b
.index
|| 0;
4084 firstChildView: function(node
)
4090 for (var child
in (node
.childs
|| { }))
4091 nodes
.push(node
.childs
[child
]);
4093 nodes
.sort(this.sortNodesCallback
);
4095 for (var i
= 0; i
< nodes
.length
; i
++)
4097 var child
= this.firstChildView(nodes
[i
]);
4100 for (var key
in child
)
4101 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
4102 node
[key
] = child
[key
];
4111 handleClick: function(ev
)
4113 L
.setHash('view', ev
.data
);
4115 ev
.preventDefault();
4119 renderNodes: function(childs
, level
, min
, max
)
4122 for (var node
in childs
)
4124 var child
= this.firstChildView(childs
[node
]);
4126 nodes
.push(childs
[node
]);
4129 nodes
.sort(this.sortNodesCallback
);
4131 var list
= $('<ul />');
4134 list
.addClass('nav').addClass('navbar-nav');
4135 else if (level
== 1)
4136 list
.addClass('dropdown-menu').addClass('navbar-inverse');
4138 for (var i
= 0; i
< nodes
.length
; i
++)
4140 if (!L
.globals
.defaultNode
)
4142 var v
= L
.getHash('view');
4143 if (!v
|| v
== nodes
[i
].view
)
4144 L
.globals
.defaultNode
= nodes
[i
];
4147 var item
= $('<li />')
4150 .text(L
.tr(nodes
[i
].title
)))
4153 if (nodes
[i
].childs
&& level
< max
)
4155 item
.addClass('dropdown');
4158 .addClass('dropdown-toggle')
4159 .attr('data-toggle', 'dropdown')
4160 .append('<b class="caret"></b>');
4162 item
.append(this.renderNodes(nodes
[i
].childs
, level
+ 1));
4166 item
.find('a').click(nodes
[i
].view
, this.handleClick
);
4173 render: function(min
, max
)
4175 var top
= min
? this.getNode(L
.globals
.defaultNode
.view
, min
) : this._nodes
;
4176 return this.renderNodes(top
.childs
, 0, min
, max
);
4179 getNode: function(path
, max
)
4181 var p
= path
.split(/\//);
4182 var n
= this._nodes
;
4184 if (typeof(max
) == 'undefined')
4187 for (var i
= 0; i
< max
; i
++)
4189 if (!n
.childs
[p
[i
]])
4199 this.ui
.table
= this.ui
.AbstractWidget
.extend({
4205 row: function(values
)
4207 if ($.isArray(values
))
4209 this._rows
.push(values
);
4211 else if ($.isPlainObject(values
))
4214 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4216 var col
= this.options
.columns
[i
];
4218 if (typeof col
.key
== 'string')
4219 v
.push(values
[col
.key
]);
4227 rows: function(rows
)
4229 for (var i
= 0; i
< rows
.length
; i
++)
4233 render: function(id
)
4235 var fieldset
= document
.createElement('fieldset');
4236 fieldset
.className
= 'cbi-section';
4238 if (this.options
.caption
)
4240 var legend
= document
.createElement('legend');
4241 $(legend
).append(this.options
.caption
);
4242 fieldset
.appendChild(legend
);
4245 var table
= document
.createElement('table');
4246 table
.className
= 'table table-condensed table-hover';
4248 var has_caption
= false;
4249 var has_description
= false;
4251 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4252 if (this.options
.columns
[i
].caption
)
4257 else if (this.options
.columns
[i
].description
)
4259 has_description
= true;
4265 var tr
= table
.insertRow(-1);
4266 tr
.className
= 'cbi-section-table-titles';
4268 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4270 var col
= this.options
.columns
[i
];
4271 var th
= document
.createElement('th');
4272 th
.className
= 'cbi-section-table-cell';
4277 th
.style
.width
= col
.width
;
4280 th
.style
.textAlign
= col
.align
;
4283 $(th
).append(col
.caption
);
4287 if (has_description
)
4289 var tr
= table
.insertRow(-1);
4290 tr
.className
= 'cbi-section-table-descr';
4292 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4294 var col
= this.options
.columns
[i
];
4295 var th
= document
.createElement('th');
4296 th
.className
= 'cbi-section-table-cell';
4301 th
.style
.width
= col
.width
;
4304 th
.style
.textAlign
= col
.align
;
4306 if (col
.description
)
4307 $(th
).append(col
.description
);
4311 if (this._rows
.length
== 0)
4313 if (this.options
.placeholder
)
4315 var tr
= table
.insertRow(-1);
4316 var td
= tr
.insertCell(-1);
4317 td
.className
= 'cbi-section-table-cell';
4319 td
.colSpan
= this.options
.columns
.length
;
4320 $(td
).append(this.options
.placeholder
);
4325 for (var i
= 0; i
< this._rows
.length
; i
++)
4327 var tr
= table
.insertRow(-1);
4329 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
4331 var col
= this.options
.columns
[j
];
4332 var td
= tr
.insertCell(-1);
4334 var val
= this._rows
[i
][j
];
4336 if (typeof(val
) == 'undefined')
4337 val
= col
.placeholder
;
4339 if (typeof(val
) == 'undefined')
4343 td
.style
.width
= col
.width
;
4346 td
.style
.textAlign
= col
.align
;
4348 if (typeof col
.format
== 'string')
4349 $(td
).append(col
.format
.format(val
));
4350 else if (typeof col
.format
== 'function')
4351 $(td
).append(col
.format(val
, i
));
4359 fieldset
.appendChild(table
);
4365 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
4368 var vn
= parseInt(this.options
.value
) || 0;
4369 var mn
= parseInt(this.options
.max
) || 100;
4370 var pc
= Math
.floor((100 / mn
) * vn
);
4374 if (typeof(this.options
.format
) == 'string')
4375 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
4376 else if (typeof(this.options
.format
) == 'function')
4377 text
= this.options
.format(pc
);
4379 text
= '%.2f%%'.format(pc
);
4382 .addClass('progress')
4383 .append($('<div />')
4384 .addClass('progress-bar')
4385 .addClass('progress-bar-info')
4386 .css('width', pc
+ '%'))
4387 .append($('<small />')
4392 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
4395 var l2dev
= this.options
.l2_device
|| this.options
.device
;
4396 var l3dev
= this.options
.l3_device
;
4397 var dev
= l3dev
|| l2dev
|| '?';
4399 var span
= document
.createElement('span');
4400 span
.className
= 'badge';
4402 if (typeof(this.options
.signal
) == 'number' ||
4403 typeof(this.options
.noise
) == 'number')
4406 if (typeof(this.options
.signal
) != 'undefined' &&
4407 typeof(this.options
.noise
) != 'undefined')
4409 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
4422 span
.appendChild(document
.createElement('img'));
4423 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
4426 span
.title
= L
.tr('No signal');
4428 span
.title
= '%s: %d %s / %s: %d %s'.format(
4429 L
.tr('Signal'), this.options
.signal
, L
.tr('dBm'),
4430 L
.tr('Noise'), this.options
.noise
, L
.tr('dBm')
4435 var type
= 'ethernet';
4436 var desc
= L
.tr('Ethernet device');
4441 desc
= L
.tr('Tunnel interface');
4443 else if (dev
.indexOf('br-') == 0)
4446 desc
= L
.tr('Bridge');
4448 else if (dev
.indexOf('.') > 0)
4451 desc
= L
.tr('VLAN interface');
4453 else if (dev
.indexOf('wlan') == 0 ||
4454 dev
.indexOf('ath') == 0 ||
4455 dev
.indexOf('wl') == 0)
4458 desc
= L
.tr('Wireless Network');
4461 span
.appendChild(document
.createElement('img'));
4462 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
4466 $(span
).append(' ');
4467 $(span
).append(dev
);
4473 var type = function(f
, l
)
4483 L
.cbi
.validation
.message
= L
.tr(msg
);
4486 compile: function(code
)
4491 var types
= L
.cbi
.validation
.types
;
4496 for (var i
= 0; i
< code
.length
; i
++)
4504 switch (code
.charCodeAt(i
))
4516 var label
= code
.substring(pos
, i
);
4517 label
= label
.replace(/\\(.)/g, '$1');
4518 label
= label
.replace(/^[ \t]+/g, '');
4519 label
= label
.replace(/[ \t]+$/g, '');
4521 if (label
&& !isNaN(label
))
4523 stack
.push(parseFloat(label
));
4525 else if (label
.match(/^(['"]).*\1$/))
4527 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
4529 else if (typeof types
[label
] == 'function')
4531 stack
.push(types
[label
]);
4536 throw "Syntax error, unhandled token '"+label
+"'";
4541 depth
+= (code
.charCodeAt(i
) == 40);
4547 if (typeof stack
[stack
.length
-2] != 'function')
4548 throw "Syntax error, argument list follows non-function";
4550 stack
[stack
.length
-1] =
4551 L
.cbi
.validation
.compile(code
.substring(pos
, i
));
4564 var validation
= this.cbi
.validation
;
4566 validation
.types
= {
4567 'integer': function()
4569 if (this.match(/^-?[0-9]+$/) != null)
4572 validation
.i18n('Must be a valid integer');
4576 'uinteger': function()
4578 if (validation
.types
['integer'].apply(this) && (this >= 0))
4581 validation
.i18n('Must be a positive integer');
4587 if (!isNaN(parseFloat(this)))
4590 validation
.i18n('Must be a valid number');
4594 'ufloat': function()
4596 if (validation
.types
['float'].apply(this) && (this >= 0))
4599 validation
.i18n('Must be a positive number');
4603 'ipaddr': function()
4605 if (L
.parseIPv4(this) || L
.parseIPv6(this))
4608 validation
.i18n('Must be a valid IP address');
4612 'ip4addr': function()
4614 if (L
.parseIPv4(this))
4617 validation
.i18n('Must be a valid IPv4 address');
4621 'ip6addr': function()
4623 if (L
.parseIPv6(this))
4626 validation
.i18n('Must be a valid IPv6 address');
4630 'netmask4': function()
4632 if (L
.isNetmask(L
.parseIPv4(this)))
4635 validation
.i18n('Must be a valid IPv4 netmask');
4639 'netmask6': function()
4641 if (L
.isNetmask(L
.parseIPv6(this)))
4644 validation
.i18n('Must be a valid IPv6 netmask6');
4650 if (this.match(/^([0-9.]+)\/(\d{1,2})$/))
4651 if (RegExp
.$2 <= 32 && L
.parseIPv4(RegExp
.$1))
4654 validation
.i18n('Must be a valid IPv4 prefix');
4660 if (this.match(/^([a-fA-F0-9:.]+)\/(\d{1,3})$/))
4661 if (RegExp
.$2 <= 128 && L
.parseIPv6(RegExp
.$1))
4664 validation
.i18n('Must be a valid IPv6 prefix');
4668 'ipmask4': function()
4670 if (this.match(/^([0-9.]+)\/([0-9.]+)$/))
4672 var addr
= RegExp
.$1, mask
= RegExp
.$2;
4673 if (L
.parseIPv4(addr
) && L
.isNetmask(L
.parseIPv4(mask
)))
4677 validation
.i18n('Must be a valid IPv4 address/netmask pair');
4681 'ipmask6': function()
4683 if (this.match(/^([a-fA-F0-9:.]+)\/([a-fA-F0-9:.]+)$/))
4685 var addr
= RegExp
.$1, mask
= RegExp
.$2;
4686 if (L
.parseIPv6(addr
) && L
.isNetmask(L
.parseIPv6(mask
)))
4690 validation
.i18n('Must be a valid IPv6 address/netmask pair');
4696 if (validation
.types
['integer'].apply(this) &&
4697 (this >= 0) && (this <= 65535))
4700 validation
.i18n('Must be a valid port number');
4704 'portrange': function()
4706 if (this.match(/^(\d+)-(\d+)$/))
4711 if (validation
.types
['port'].apply(p1
) &&
4712 validation
.types
['port'].apply(p2
) &&
4713 (parseInt(p1
) <= parseInt(p2
)))
4716 else if (validation
.types
['port'].apply(this))
4721 validation
.i18n('Must be a valid port range');
4725 'macaddr': function()
4727 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4730 validation
.i18n('Must be a valid MAC address');
4736 if (validation
.types
['hostname'].apply(this) ||
4737 validation
.types
['ipaddr'].apply(this))
4740 validation
.i18n('Must be a valid hostname or IP address');
4744 'hostname': function()
4746 if ((this.length
<= 253) &&
4747 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4748 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4749 this.match(/[^0-9.]/)))))
4752 validation
.i18n('Must be a valid host name');
4756 'network': function()
4758 if (validation
.types
['uciname'].apply(this) ||
4759 validation
.types
['host'].apply(this))
4762 validation
.i18n('Must be a valid network name');
4766 'wpakey': function()
4770 if ((v
.length
== 64)
4771 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
4772 : ((v
.length
>= 8) && (v
.length
<= 63)))
4775 validation
.i18n('Must be a valid WPA key');
4779 'wepkey': function()
4783 if (v
.substr(0,2) == 's:')
4786 if (((v
.length
== 10) || (v
.length
== 26))
4787 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
4788 : ((v
.length
== 5) || (v
.length
== 13)))
4791 validation
.i18n('Must be a valid WEP key');
4795 'uciname': function()
4797 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4800 validation
.i18n('Must be a valid UCI identifier');
4804 'range': function(min
, max
)
4806 var val
= parseFloat(this);
4808 if (validation
.types
['integer'].apply(this) &&
4809 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
4812 validation
.i18n('Must be a number between %d and %d');
4816 'min': function(min
)
4818 var val
= parseFloat(this);
4820 if (validation
.types
['integer'].apply(this) &&
4821 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
4824 validation
.i18n('Must be a number greater or equal to %d');
4828 'max': function(max
)
4830 var val
= parseFloat(this);
4832 if (validation
.types
['integer'].apply(this) &&
4833 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
4836 validation
.i18n('Must be a number lower or equal to %d');
4840 'rangelength': function(min
, max
)
4842 var val
= '' + this;
4844 if (!isNaN(min
) && !isNaN(max
) &&
4845 (val
.length
>= min
) && (val
.length
<= max
))
4848 validation
.i18n('Must be between %d and %d characters');
4852 'minlength': function(min
)
4854 var val
= '' + this;
4856 if (!isNaN(min
) && (val
.length
>= min
))
4859 validation
.i18n('Must be at least %d characters');
4863 'maxlength': function(max
)
4865 var val
= '' + this;
4867 if (!isNaN(max
) && (val
.length
<= max
))
4870 validation
.i18n('Must be at most %d characters');
4878 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4880 delete validation
.message
;
4882 if (typeof(arguments
[i
]) != 'function')
4884 if (arguments
[i
] == this)
4888 else if (arguments
[i
].apply(this, arguments
[i
+1]))
4893 if (validation
.message
)
4894 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4897 validation
.message
= msgs
.join( L
.tr(' - or - '));
4905 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4907 delete validation
.message
;
4909 if (typeof arguments
[i
] != 'function')
4911 if (arguments
[i
] != this)
4915 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
4920 if (validation
.message
)
4921 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4924 validation
.message
= msgs
.join(', ');
4930 return validation
.types
['or'].apply(
4931 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
4934 'list': function(subvalidator
, subargs
)
4936 if (typeof subvalidator
!= 'function')
4939 var tokens
= this.match(/[^ \t]+/g);
4940 for (var i
= 0; i
< tokens
.length
; i
++)
4941 if (!subvalidator
.apply(tokens
[i
], subargs
))
4947 'phonedigit': function()
4949 if (this.match(/^[0-9\*#!\.]+$/) != null)
4952 validation
.i18n('Must be a valid phone number digit');
4956 'string': function()
4963 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
4964 init: function(name
, options
)
4967 this.instance
= { };
4968 this.dependencies
= [ ];
4969 this.rdependency
= { };
4971 this.options
= L
.defaults(options
, {
4981 return this.ownerSection
.id('field', sid
|| '__unknown__', this.name
);
4984 render: function(sid
, condensed
)
4986 var i
= this.instance
[sid
] = { };
4988 i
.top
= $('<div />')
4989 .addClass('luci2-field');
4993 i
.top
.addClass('form-group');
4995 if (typeof(this.options
.caption
) == 'string')
4997 .addClass('col-lg-2 control-label')
4998 .attr('for', this.id(sid
))
4999 .text(this.options
.caption
)
5003 i
.error
= $('<div />')
5005 .addClass('luci2-field-error label label-danger');
5007 i
.widget
= $('<div />')
5008 .addClass('luci2-field-widget')
5009 .append(this.widget(sid
))
5015 i
.widget
.addClass('col-lg-5');
5018 .addClass('col-lg-5')
5019 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
5026 active: function(sid
)
5028 return (this.instance
[sid
] && !this.instance
[sid
].disabled
);
5031 ucipath: function(sid
)
5034 config
: (this.options
.uci_package
|| this.ownerMap
.uci_package
),
5035 section
: (this.options
.uci_section
|| sid
),
5036 option
: (this.options
.uci_option
|| this.name
)
5040 ucivalue: function(sid
)
5042 var uci
= this.ucipath(sid
);
5043 var val
= this.ownerMap
.get(uci
.config
, uci
.section
, uci
.option
);
5045 if (typeof(val
) == 'undefined')
5046 return this.options
.initial
;
5051 formvalue: function(sid
)
5053 var v
= $('#' + this.id(sid
)).val();
5054 return (v
=== '') ? undefined : v
;
5057 textvalue: function(sid
)
5059 var v
= this.formvalue(sid
);
5061 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5062 v
= this.ucivalue(sid
);
5064 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5065 v
= this.options
.placeholder
;
5067 if (typeof(v
) == 'undefined' || v
=== '')
5070 if (typeof(v
) == 'string' && $.isArray(this.choices
))
5072 for (var i
= 0; i
< this.choices
.length
; i
++)
5073 if (v
=== this.choices
[i
][0])
5074 return this.choices
[i
][1];
5076 else if (v
=== true)
5078 else if (v
=== false)
5080 else if ($.isArray(v
))
5081 return v
.join(', ');
5086 changed: function(sid
)
5088 var a
= this.ucivalue(sid
);
5089 var b
= this.formvalue(sid
);
5091 if (typeof(a
) != typeof(b
))
5096 if (a
.length
!= b
.length
)
5099 for (var i
= 0; i
< a
.length
; i
++)
5105 else if ($.isPlainObject(a
))
5112 if (!(k
in a
) || a
[k
] !== b
[k
])
5123 var uci
= this.ucipath(sid
);
5125 if (this.instance
[sid
].disabled
)
5127 if (!this.options
.keep
)
5128 return this.ownerMap
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5133 var chg
= this.changed(sid
);
5134 var val
= this.formvalue(sid
);
5137 this.ownerMap
.set(uci
.config
, uci
.section
, uci
.option
, val
);
5142 findSectionID: function($elem
)
5144 return this.ownerSection
.findParentSectionIDs($elem
)[0];
5147 setError: function($elem
, msg
, msgargs
)
5149 var $field
= $elem
.parents('.luci2-field:first');
5150 var $error
= $field
.find('.luci2-field-error:first');
5152 if (typeof(msg
) == 'string' && msg
.length
> 0)
5154 $field
.addClass('luci2-form-error');
5155 $elem
.parent().addClass('has-error');
5157 $error
.text(msg
.format
.apply(msg
, msgargs
)).show();
5158 $field
.trigger('validate');
5164 $elem
.parent().removeClass('has-error');
5166 var $other_errors
= $field
.find('.has-error');
5167 if ($other_errors
.length
== 0)
5169 $field
.removeClass('luci2-form-error');
5170 $error
.text('').hide();
5171 $field
.trigger('validate');
5180 handleValidate: function(ev
)
5182 var $elem
= $(this);
5186 var val
= $elem
.val();
5187 var vstack
= d
.vstack
;
5189 if (vstack
&& typeof(vstack
[0]) == 'function')
5191 delete validation
.message
;
5193 if ((val
.length
== 0 && !d
.opt
))
5195 rv
= d
.self
.setError($elem
, L
.tr('Field must not be empty'));
5197 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
5199 rv
= d
.self
.setError($elem
, validation
.message
, vstack
[1]);
5203 rv
= d
.self
.setError($elem
);
5209 var sid
= d
.self
.findSectionID($elem
);
5211 for (var field
in d
.self
.rdependency
)
5213 d
.self
.rdependency
[field
].toggle(sid
);
5214 d
.self
.rdependency
[field
].validate(sid
);
5217 d
.self
.ownerSection
.tabtoggle(sid
);
5223 attachEvents: function(sid
, elem
)
5227 opt
: this.options
.optional
5231 for (var evname
in this.events
)
5232 elem
.on(evname
, evdata
, this.events
[evname
]);
5234 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
5238 if (typeof(this.options
.datatype
) == 'string')
5241 evdata
.vstack
= L
.cbi
.validation
.compile(this.options
.datatype
);
5244 else if (typeof(this.options
.datatype
) == 'function')
5246 var vfunc
= this.options
.datatype
;
5247 evdata
.vstack
= [ function(elem
) {
5248 var rv
= vfunc(this, elem
);
5250 validation
.message
= rv
;
5251 return (rv
=== true);
5255 if (elem
.prop('tagName') == 'SELECT')
5257 elem
.change(evdata
, this.handleValidate
);
5259 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
5261 elem
.click(evdata
, this.handleValidate
);
5262 elem
.blur(evdata
, this.handleValidate
);
5266 elem
.keyup(evdata
, this.handleValidate
);
5267 elem
.blur(evdata
, this.handleValidate
);
5270 elem
.addClass('luci2-field-validate')
5271 .on('validate', evdata
, this.handleValidate
);
5276 validate: function(sid
)
5278 var i
= this.instance
[sid
];
5280 i
.widget
.find('.luci2-field-validate').trigger('validate');
5282 return (i
.disabled
|| i
.error
.text() == '');
5285 depends: function(d
, v
, add
)
5292 for (var i
= 0; i
< d
.length
; i
++)
5294 if (typeof(d
[i
]) == 'string')
5296 else if (d
[i
] instanceof L
.cbi
.AbstractValue
)
5297 dep
[d
[i
].name
] = true;
5300 else if (d
instanceof L
.cbi
.AbstractValue
)
5303 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
5305 else if (typeof(d
) == 'object')
5309 else if (typeof(d
) == 'string')
5312 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
5315 if (!dep
|| $.isEmptyObject(dep
))
5318 for (var field
in dep
)
5320 var f
= this.ownerSection
.fields
[field
];
5322 f
.rdependency
[this.name
] = this;
5327 if ($.isEmptyObject(dep
))
5330 if (!add
|| !this.dependencies
.length
)
5331 this.dependencies
.push(dep
);
5333 for (var i
= 0; i
< this.dependencies
.length
; i
++)
5334 $.extend(this.dependencies
[i
], dep
);
5339 toggle: function(sid
)
5341 var d
= this.dependencies
;
5342 var i
= this.instance
[sid
];
5347 for (var n
= 0; n
< d
.length
; n
++)
5351 for (var field
in d
[n
])
5353 var val
= this.ownerSection
.fields
[field
].formvalue(sid
);
5354 var cmp
= d
[n
][field
];
5356 if (typeof(cmp
) == 'boolean')
5358 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
5364 else if (typeof(cmp
) == 'string' || typeof(cmp
) == 'number')
5372 else if (typeof(cmp
) == 'function')
5380 else if (cmp
instanceof RegExp
)
5395 i
.top
.removeClass('luci2-field-disabled');
5406 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
5407 i
.top
.addClass('luci2-field-disabled');
5414 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
5415 widget: function(sid
)
5417 var o
= this.options
;
5419 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
5420 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
5422 var i
= $('<input />')
5423 .attr('id', this.id(sid
))
5424 .attr('type', 'checkbox')
5425 .prop('checked', this.ucivalue(sid
));
5428 .addClass('checkbox')
5429 .append(this.attachEvents(sid
, i
));
5432 ucivalue: function(sid
)
5434 var v
= this.callSuper('ucivalue', sid
);
5436 if (typeof(v
) == 'boolean')
5439 return (v
== this.options
.enabled
);
5442 formvalue: function(sid
)
5444 var v
= $('#' + this.id(sid
)).prop('checked');
5446 if (typeof(v
) == 'undefined')
5447 return !!this.options
.initial
;
5454 var uci
= this.ucipath(sid
);
5456 if (this.instance
[sid
].disabled
)
5458 if (!this.options
.keep
)
5459 return this.ownerMap
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5464 var chg
= this.changed(sid
);
5465 var val
= this.formvalue(sid
);
5469 if (this.options
.optional
&& val
== this.options
.initial
)
5470 this.ownerMap
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5472 this.ownerMap
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
5479 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
5480 widget: function(sid
)
5482 var i
= $('<input />')
5483 .addClass('form-control')
5484 .attr('id', this.id(sid
))
5485 .attr('type', 'text')
5486 .attr('placeholder', this.options
.placeholder
)
5487 .val(this.ucivalue(sid
));
5489 return this.attachEvents(sid
, i
);
5493 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
5494 widget: function(sid
)
5496 var i
= $('<input />')
5497 .addClass('form-control')
5498 .attr('id', this.id(sid
))
5499 .attr('type', 'password')
5500 .attr('placeholder', this.options
.placeholder
)
5501 .val(this.ucivalue(sid
));
5503 var t
= $('<span />')
5504 .addClass('input-group-btn')
5505 .append(L
.ui
.button(L
.tr('Reveal'), 'default')
5506 .click(function(ev
) {
5508 var i
= b
.parent().prev();
5509 var t
= i
.attr('type');
5510 b
.text(t
== 'password' ? L
.tr('Hide') : L
.tr('Reveal'));
5511 i
.attr('type', (t
== 'password') ? 'text' : 'password');
5515 this.attachEvents(sid
, i
);
5518 .addClass('input-group')
5524 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
5525 widget: function(sid
)
5527 var s
= $('<select />')
5528 .addClass('form-control');
5530 if (this.options
.optional
&& !this.has_empty
)
5533 .text(L
.tr('-- Please choose --'))
5537 for (var i
= 0; i
< this.choices
.length
; i
++)
5539 .attr('value', this.choices
[i
][0])
5540 .text(this.choices
[i
][1])
5543 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
5545 return this.attachEvents(sid
, s
);
5548 value: function(k
, v
)
5554 this.has_empty
= true;
5556 this.choices
.push([k
, v
|| k
]);
5561 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
5562 widget: function(sid
)
5564 var v
= this.ucivalue(sid
);
5565 var t
= $('<div />').attr('id', this.id(sid
));
5568 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5571 for (var i
= 0; i
< v
.length
; i
++)
5575 for (var i
= 0; i
< this.choices
.length
; i
++)
5578 .addClass('checkbox')
5579 .append($('<input />')
5580 .attr('type', 'checkbox')
5581 .attr('value', this.choices
[i
][0])
5582 .prop('checked', s
[this.choices
[i
][0]]))
5583 .append(this.choices
[i
][1])
5590 formvalue: function(sid
)
5593 var fields
= $('#' + this.id(sid
) + ' > label > input');
5595 for (var i
= 0; i
< fields
.length
; i
++)
5596 if (fields
[i
].checked
)
5597 rv
.push(fields
[i
].getAttribute('value'));
5602 textvalue: function(sid
)
5604 var v
= this.formvalue(sid
);
5608 for (var i
= 0; i
< this.choices
.length
; i
++)
5609 c
[this.choices
[i
][0]] = this.choices
[i
][1];
5613 for (var i
= 0; i
< v
.length
; i
++)
5614 t
.push(c
[v
[i
]] || v
[i
]);
5616 return t
.join(', ');
5620 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
5621 _change: function(ev
)
5624 var self
= ev
.data
.self
;
5626 if (s
.selectedIndex
== (s
.options
.length
- 1))
5628 ev
.data
.select
.hide();
5629 ev
.data
.input
.show().focus();
5630 ev
.data
.input
.val('');
5632 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
5634 ev
.data
.input
.val('');
5638 ev
.data
.input
.val(ev
.data
.select
.val());
5641 ev
.stopPropagation();
5647 var val
= this.value
;
5648 var self
= ev
.data
.self
;
5650 ev
.data
.select
.empty();
5652 if (self
.options
.optional
&& !self
.has_empty
)
5655 .text(L
.tr('-- please choose --'))
5656 .appendTo(ev
.data
.select
);
5659 for (var i
= 0; i
< self
.choices
.length
; i
++)
5661 if (self
.choices
[i
][0] == val
)
5665 .attr('value', self
.choices
[i
][0])
5666 .text(self
.choices
[i
][1])
5667 .appendTo(ev
.data
.select
);
5670 if (!seen
&& val
!= '')
5674 .appendTo(ev
.data
.select
);
5678 .text(L
.tr('-- custom --'))
5679 .appendTo(ev
.data
.select
);
5681 ev
.data
.input
.hide();
5682 ev
.data
.select
.val(val
).show().blur();
5685 _enter: function(ev
)
5690 ev
.preventDefault();
5691 ev
.data
.self
._blur(ev
);
5695 widget: function(sid
)
5697 var d
= $('<div />')
5698 .attr('id', this.id(sid
));
5700 var t
= $('<input />')
5701 .addClass('form-control')
5702 .attr('type', 'text')
5706 var s
= $('<select />')
5707 .addClass('form-control')
5716 s
.change(evdata
, this._change
);
5717 t
.blur(evdata
, this._blur
);
5718 t
.keydown(evdata
, this._enter
);
5720 t
.val(this.ucivalue(sid
));
5723 this.attachEvents(sid
, t
);
5724 this.attachEvents(sid
, s
);
5729 value: function(k
, v
)
5735 this.has_empty
= true;
5737 this.choices
.push([k
, v
|| k
]);
5741 formvalue: function(sid
)
5743 var v
= $('#' + this.id(sid
)).children('input').val();
5744 return (v
== '') ? undefined : v
;
5748 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
5749 _redraw: function(focus
, add
, del
, s
)
5751 var v
= s
.values
|| [ ];
5754 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
5756 v
.push(this.value
|| '');
5759 $(s
.parent
).empty();
5764 v
.splice(focus
, 0, '');
5766 else if (v
.length
== 0)
5772 for (var i
= 0; i
< v
.length
; i
++)
5779 remove
: ((i
+1) < v
.length
)
5784 btn
= L
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
5786 btn
= L
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
5790 var txt
= $('<input />')
5791 .addClass('form-control')
5792 .attr('type', 'text')
5795 var sel
= $('<select />')
5796 .addClass('form-control');
5799 .addClass('input-group')
5802 .append($('<span />')
5803 .addClass('input-group-btn')
5805 .appendTo(s
.parent
);
5807 evdata
.input
= this.attachEvents(s
.sid
, txt
);
5808 evdata
.select
= this.attachEvents(s
.sid
, sel
);
5810 sel
.change(evdata
, this._change
);
5811 txt
.blur(evdata
, this._blur
);
5812 txt
.keydown(evdata
, this._keydown
);
5817 if (i
== focus
|| -(i
+1) == focus
)
5824 var f
= $('<input />')
5825 .attr('type', 'text')
5827 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
5828 .addClass('form-control')
5829 .keydown(evdata
, this._keydown
)
5830 .keypress(evdata
, this._keypress
)
5834 .addClass('input-group')
5836 .append($('<span />')
5837 .addClass('input-group-btn')
5839 .appendTo(s
.parent
);
5845 else if (-(i
+1) == focus
)
5849 /* force cursor to end */
5855 evdata
.input
= this.attachEvents(s
.sid
, f
);
5866 _keypress: function(ev
)
5870 /* backspace, delete */
5873 if (ev
.data
.input
.val() == '')
5875 ev
.preventDefault();
5881 /* enter, arrow up, arrow down */
5885 ev
.preventDefault();
5892 _keydown: function(ev
)
5894 var input
= ev
.data
.input
;
5898 /* backspace, delete */
5901 if (input
.val().length
== 0)
5903 ev
.preventDefault();
5905 var index
= ev
.data
.index
;
5911 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
5919 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5924 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
5925 if (prev
.is(':visible'))
5928 prev
.next('select').focus();
5933 var next
= input
.parent().nextAll('div.input-group:first').children('input');
5934 if (next
.is(':visible'))
5937 next
.next('select').focus();
5944 _btnclick: function(ev
)
5946 if (!this.getAttribute('disabled'))
5950 var index
= ev
.data
.index
;
5951 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
5955 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5962 widget: function(sid
)
5964 this.options
.optional
= true;
5966 var v
= this.ucivalue(sid
);
5969 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5971 var d
= $('<div />')
5972 .attr('id', this.id(sid
))
5973 .addClass('cbi-input-dynlist');
5975 this._redraw(NaN
, -1, -1, {
5985 ucivalue: function(sid
)
5987 var v
= this.callSuper('ucivalue', sid
);
5990 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5995 formvalue: function(sid
)
5998 var fields
= $('#' + this.id(sid
) + ' input');
6000 for (var i
= 0; i
< fields
.length
; i
++)
6001 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
6002 rv
.push(fields
[i
].value
);
6008 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
6009 widget: function(sid
)
6012 .addClass('form-control-static')
6013 .attr('id', this.id(sid
))
6014 .html(this.ucivalue(sid
) || this.label('placeholder'));
6017 formvalue: function(sid
)
6019 return this.ucivalue(sid
);
6023 this.cbi
.ButtonValue
= this.cbi
.AbstractValue
.extend({
6024 widget: function(sid
)
6026 this.options
.optional
= true;
6028 var btn
= $('<button />')
6029 .addClass('btn btn-default')
6030 .attr('id', this.id(sid
))
6031 .attr('type', 'button')
6032 .text(this.label('text'));
6034 return this.attachEvents(sid
, btn
);
6038 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
6041 return L
.NetworkModel
.init();
6044 _device_icon: function(dev
)
6047 .attr('src', dev
.icon())
6048 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?'));
6051 widget: function(sid
)
6053 var id
= this.id(sid
);
6054 var ul
= $('<ul />')
6056 .addClass('list-unstyled');
6058 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
6059 var value
= this.ucivalue(sid
);
6062 if (!this.options
.multiple
)
6063 check
[value
] = true;
6065 for (var i
= 0; i
< value
.length
; i
++)
6066 check
[value
[i
]] = true;
6068 var interfaces
= L
.NetworkModel
.getInterfaces();
6070 for (var i
= 0; i
< interfaces
.length
; i
++)
6072 var iface
= interfaces
[i
];
6075 .append($('<label />')
6076 .addClass(itype
+ ' inline')
6077 .append(this.attachEvents(sid
, $('<input />')
6078 .attr('name', itype
+ id
)
6079 .attr('type', itype
)
6080 .attr('value', iface
.name())
6081 .prop('checked', !!check
[iface
.name()])))
6082 .append(iface
.renderBadge()))
6086 if (!this.options
.multiple
)
6089 .append($('<label />')
6090 .addClass(itype
+ ' inline text-muted')
6091 .append(this.attachEvents(sid
, $('<input />')
6092 .attr('name', itype
+ id
)
6093 .attr('type', itype
)
6095 .prop('checked', $.isEmptyObject(check
))))
6096 .append(L
.tr('unspecified')))
6103 ucivalue: function(sid
)
6105 var v
= this.callSuper('ucivalue', sid
);
6107 if (!this.options
.multiple
)
6113 else if (typeof(v
) == 'string')
6116 return v
? v
[0] : undefined;
6123 if (typeof(v
) == 'string')
6124 v
= v
.match(/\S+/g);
6130 formvalue: function(sid
)
6132 var inputs
= $('#' + this.id(sid
) + ' input');
6134 if (!this.options
.multiple
)
6136 for (var i
= 0; i
< inputs
.length
; i
++)
6137 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
6138 return inputs
[i
].value
;
6145 for (var i
= 0; i
< inputs
.length
; i
++)
6146 if (inputs
[i
].checked
)
6147 rv
.push(inputs
[i
].value
);
6149 return rv
.length
? rv
: undefined;
6153 this.cbi
.DeviceList
= this.cbi
.NetworkList
.extend({
6154 handleFocus: function(ev
)
6156 var self
= ev
.data
.self
;
6157 var input
= $(this);
6159 input
.parent().prev().prop('checked', true);
6162 handleBlur: function(ev
)
6165 ev
.data
.self
.handleKeydown
.call(this, ev
);
6168 handleKeydown: function(ev
)
6170 if (ev
.which
!= 10 && ev
.which
!= 13)
6173 var sid
= ev
.data
.sid
;
6174 var self
= ev
.data
.self
;
6175 var input
= $(this);
6176 var ifnames
= L
.toArray(input
.val());
6178 if (!ifnames
.length
)
6181 L
.NetworkModel
.createDevice(ifnames
[0]);
6183 self
._redraw(sid
, $('#' + self
.id(sid
)), ifnames
[0]);
6188 return L
.NetworkModel
.init();
6191 _redraw: function(sid
, ul
, sel
)
6193 var id
= ul
.attr('id');
6194 var devs
= L
.NetworkModel
.getDevices();
6195 var iface
= L
.NetworkModel
.getInterface(sid
);
6196 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
6201 for (var i
= 0; i
< devs
.length
; i
++)
6202 if (devs
[i
].isInNetwork(iface
))
6203 check
[devs
[i
].name()] = true;
6207 if (this.options
.multiple
)
6208 check
= L
.toObject(this.formvalue(sid
));
6215 for (var i
= 0; i
< devs
.length
; i
++)
6219 if (dev
.isBridge() && this.options
.bridges
=== false)
6222 if (!dev
.isBridgeable() && this.options
.multiple
)
6225 var badge
= $('<span />')
6227 .append($('<img />').attr('src', dev
.icon()))
6228 .append(' %s: %s'.format(dev
.name(), dev
.description()));
6230 //var ifcs = dev.getInterfaces();
6233 // for (var j = 0; j < ifcs.length; j++)
6234 // badge.append((j ? ', ' : ' (') + ifcs[j].name());
6236 // badge.append(')');
6240 .append($('<label />')
6241 .addClass(itype
+ ' inline')
6242 .append($('<input />')
6243 .attr('name', itype
+ id
)
6244 .attr('type', itype
)
6245 .attr('value', dev
.name())
6246 .prop('checked', !!check
[dev
.name()]))
6253 .append($('<label />')
6254 .attr('for', 'custom' + id
)
6255 .addClass(itype
+ ' inline')
6256 .append($('<input />')
6257 .attr('name', itype
+ id
)
6258 .attr('type', itype
)
6260 .append($('<span />')
6262 .append($('<input />')
6263 .attr('id', 'custom' + id
)
6264 .attr('type', 'text')
6265 .attr('placeholder', L
.tr('Custom device …'))
6266 .on('focus', { self
: this, sid
: sid
}, this.handleFocus
)
6267 .on('blur', { self
: this, sid
: sid
}, this.handleBlur
)
6268 .on('keydown', { self
: this, sid
: sid
}, this.handleKeydown
))))
6271 if (!this.options
.multiple
)
6274 .append($('<label />')
6275 .addClass(itype
+ ' inline text-muted')
6276 .append($('<input />')
6277 .attr('name', itype
+ id
)
6278 .attr('type', itype
)
6280 .prop('checked', $.isEmptyObject(check
)))
6281 .append(L
.tr('unspecified')))
6286 widget: function(sid
)
6288 var id
= this.id(sid
);
6289 var ul
= $('<ul />')
6291 .addClass('list-unstyled');
6293 this._redraw(sid
, ul
);
6300 if (this.instance
[sid
].disabled
)
6303 var ifnames
= this.formvalue(sid
);
6307 var iface
= L
.NetworkModel
.getInterface(sid
);
6311 iface
.setDevices($.isArray(ifnames
) ? ifnames
: [ ifnames
]);
6316 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
6319 var s
= [ arguments
[0], this.ownerMap
.uci_package
, this.uci_type
];
6321 for (var i
= 1; i
< arguments
.length
&& typeof(arguments
[i
]) == 'string'; i
++)
6322 s
.push(arguments
[i
].replace(/\./g, '_'));
6327 option: function(widget
, name
, options
)
6329 if (this.tabs
.length
== 0)
6330 this.tab({ id
: '__default__', selected
: true });
6332 return this.taboption('__default__', widget
, name
, options
);
6335 tab: function(options
)
6337 if (options
.selected
)
6338 this.tabs
.selected
= this.tabs
.length
;
6342 caption
: options
.caption
,
6343 description
: options
.description
,
6349 taboption: function(tabid
, widget
, name
, options
)
6352 for (var i
= 0; i
< this.tabs
.length
; i
++)
6354 if (this.tabs
[i
].id
== tabid
)
6362 throw 'Cannot append to unknown tab ' + tabid
;
6364 var w
= widget
? new widget(name
, options
) : null;
6366 if (!(w
instanceof L
.cbi
.AbstractValue
))
6367 throw 'Widget must be an instance of AbstractValue';
6369 w
.ownerSection
= this;
6370 w
.ownerMap
= this.ownerMap
;
6372 this.fields
[name
] = w
;
6378 tabtoggle: function(sid
)
6380 for (var i
= 0; i
< this.tabs
.length
; i
++)
6382 var tab
= this.tabs
[i
];
6383 var elem
= $('#' + this.id('nodetab', sid
, tab
.id
));
6386 for (var j
= 0; j
< tab
.fields
.length
; j
++)
6388 if (tab
.fields
[j
].active(sid
))
6395 if (empty
&& elem
.is(':visible'))
6402 validate: function(parent_sid
)
6404 var s
= this.getUCISections(parent_sid
);
6407 for (var i
= 0; i
< s
.length
; i
++)
6409 var $item
= $('#' + this.id('sectionitem', s
[i
]['.name']));
6411 $item
.find('.luci2-field-validate').trigger('validate');
6412 n
+= $item
.find('.luci2-field.luci2-form-error').not('.luci2-field-disabled').length
;
6418 load: function(parent_sid
)
6420 var deferreds
= [ ];
6422 var s
= this.getUCISections(parent_sid
);
6423 for (var i
= 0; i
< s
.length
; i
++)
6425 for (var f
in this.fields
)
6427 if (typeof(this.fields
[f
].load
) != 'function')
6430 var rv
= this.fields
[f
].load(s
[i
]['.name']);
6431 if (L
.isDeferred(rv
))
6435 for (var j
= 0; j
< this.subsections
.length
; j
++)
6437 var rv
= this.subsections
[j
].load(s
[i
]['.name']);
6438 deferreds
.push
.apply(deferreds
, rv
);
6445 save: function(parent_sid
)
6447 var deferreds
= [ ];
6448 var s
= this.getUCISections(parent_sid
);
6450 for (i
= 0; i
< s
.length
; i
++)
6452 if (!this.options
.readonly
)
6454 for (var f
in this.fields
)
6456 if (typeof(this.fields
[f
].save
) != 'function')
6459 var rv
= this.fields
[f
].save(s
[i
]['.name']);
6460 if (L
.isDeferred(rv
))
6465 for (var j
= 0; j
< this.subsections
.length
; j
++)
6467 var rv
= this.subsections
[j
].save(s
[i
]['.name']);
6468 deferreds
.push
.apply(deferreds
, rv
);
6475 teaser: function(sid
)
6477 var tf
= this.teaser_fields
;
6481 tf
= this.teaser_fields
= [ ];
6483 if ($.isArray(this.options
.teasers
))
6485 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
6487 var f
= this.options
.teasers
[i
];
6488 if (f
instanceof L
.cbi
.AbstractValue
)
6490 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof L
.cbi
.AbstractValue
)
6491 tf
.push(this.fields
[f
]);
6496 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
6497 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
6498 tf
.push(this.tabs
[i
].fields
[j
]);
6504 for (var i
= 0; i
< tf
.length
; i
++)
6506 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
6509 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
6510 var v
= tf
[i
].textvalue(sid
);
6512 if (typeof(v
) == 'undefined')
6515 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
6521 findAdditionalUCIPackages: function()
6525 for (var i
= 0; i
< this.tabs
.length
; i
++)
6526 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6527 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
6528 packages
.push(this.tabs
[i
].fields
[j
].options
.uci_package
);
6533 findParentSectionIDs: function($elem
)
6536 var $parents
= $elem
.parents('.luci2-section-item');
6538 for (var i
= 0; i
< $parents
.length
; i
++)
6539 rv
.push($parents
[i
].getAttribute('data-luci2-sid'));
6545 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
6546 init: function(uci_type
, options
)
6548 this.uci_type
= uci_type
;
6549 this.options
= options
;
6552 this.subsections
= [ ];
6553 this.active_panel
= { };
6554 this.active_tab
= { };
6556 this.instance
= { };
6559 filter: function(section
, parent_sid
)
6564 sort: function(section1
, section2
)
6569 subsection: function(widget
, uci_type
, options
)
6571 var w
= widget
? new widget(uci_type
, options
) : null;
6573 if (!(w
instanceof L
.cbi
.AbstractSection
))
6574 throw 'Widget must be an instance of AbstractSection';
6576 w
.ownerSection
= this;
6577 w
.ownerMap
= this.ownerMap
;
6578 w
.index
= this.subsections
.length
;
6580 this.subsections
.push(w
);
6584 getUCISections: function(parent_sid
)
6586 var s1
= L
.uci
.sections(this.ownerMap
.uci_package
);
6589 for (var i
= 0; i
< s1
.length
; i
++)
6590 if (s1
[i
]['.type'] == this.uci_type
)
6591 if (this.filter(s1
[i
], parent_sid
))
6599 add: function(name
, parent_sid
)
6601 return this.ownerMap
.add(this.ownerMap
.uci_package
, this.uci_type
, name
);
6604 remove: function(sid
, parent_sid
)
6606 return this.ownerMap
.remove(this.ownerMap
.uci_package
, sid
);
6609 handleAdd: function(ev
)
6612 var name
= undefined;
6613 var self
= ev
.data
.self
;
6614 var sid
= self
.findParentSectionIDs(addb
)[0];
6616 if (addb
.prev().prop('nodeName') == 'INPUT')
6617 name
= addb
.prev().val();
6619 if (addb
.prop('disabled') || name
=== '')
6622 L
.ui
.saveScrollTop();
6624 self
.setPanelIndex(sid
, -1);
6625 self
.ownerMap
.save();
6627 ev
.data
.sid
= self
.add(name
, sid
);
6628 ev
.data
.type
= self
.uci_type
;
6629 ev
.data
.name
= name
;
6631 self
.trigger('add', ev
);
6633 self
.ownerMap
.redraw();
6635 L
.ui
.restoreScrollTop();
6638 handleRemove: function(ev
)
6640 var self
= ev
.data
.self
;
6641 var sids
= self
.findParentSectionIDs($(this));
6645 L
.ui
.saveScrollTop();
6648 ev
.parent_sid
= sids
[1];
6650 self
.trigger('remove', ev
);
6652 self
.ownerMap
.save();
6653 self
.remove(ev
.sid
, ev
.parent_sid
);
6654 self
.ownerMap
.redraw();
6656 L
.ui
.restoreScrollTop();
6659 ev
.stopPropagation();
6662 handleSID: function(ev
)
6664 var self
= ev
.data
.self
;
6666 var addb
= text
.next();
6667 var errt
= addb
.next();
6668 var name
= text
.val();
6670 if (!/^[a-zA-Z0-9_]*$/.test(name
))
6672 errt
.text(L
.tr('Invalid section name')).show();
6673 text
.addClass('error');
6674 addb
.prop('disabled', true);
6678 if (L
.uci
.get(self
.ownerMap
.uci_package
, name
))
6680 errt
.text(L
.tr('Name already used')).show();
6681 text
.addClass('error');
6682 addb
.prop('disabled', true);
6686 errt
.text('').hide();
6687 text
.removeClass('error');
6688 addb
.prop('disabled', false);
6692 handleTab: function(ev
)
6694 var self
= ev
.data
.self
;
6696 var sid
= self
.findParentSectionIDs($tab
)[0];
6698 self
.active_tab
[sid
] = $tab
.parent().index();
6701 handleTabValidate: function(ev
)
6703 var $pane
= $(ev
.delegateTarget
);
6704 var $badge
= $pane
.parent()
6705 .children('.nav-tabs')
6707 .eq($pane
.index() - 1) // item #1 is the <ul>
6708 .find('.badge:first');
6710 var err_count
= $pane
.find('.luci2-field.luci2-form-error').not('.luci2-field-disabled').length
;
6714 .attr('title', L
.trp('1 Error', '%d Errors', err_count
).format(err_count
))
6720 handlePanelValidate: function(ev
)
6722 var $elem
= $(this);
6724 .prevAll('.luci2-section-header:first')
6725 .children('.luci2-section-teaser')
6726 .find('.badge:first');
6728 var err_count
= $elem
.find('.luci2-field.luci2-form-error').not('.luci2-field-disabled').length
;
6732 .attr('title', L
.trp('1 Error', '%d Errors', err_count
).format(err_count
))
6738 handlePanelCollapse: function(ev
)
6740 var self
= ev
.data
.self
;
6742 var $items
= $(ev
.delegateTarget
).children('.luci2-section-item');
6744 var $this_panel
= $(ev
.target
);
6745 var $this_teaser
= $this_panel
.prevAll('.luci2-section-header:first').children('.luci2-section-teaser');
6747 var $prev_panel
= $items
.children('.luci2-section-panel.in');
6748 var $prev_teaser
= $prev_panel
.prevAll('.luci2-section-header:first').children('.luci2-section-teaser');
6750 var sids
= self
.findParentSectionIDs($prev_panel
);
6752 self
.setPanelIndex(sids
[1], $this_panel
.parent().index());
6756 .addClass('collapse');
6760 .children('span:last')
6762 .append(self
.teaser(sids
[0]));
6767 ev
.stopPropagation();
6770 handleSort: function(ev
)
6772 var self
= ev
.data
.self
;
6774 var $item
= $(this).parents('.luci2-section-item:first');
6775 var $next
= ev
.data
.up
? $item
.prev() : $item
.next();
6777 if ($item
.length
&& $next
.length
)
6779 var cur_sid
= $item
.attr('data-luci2-sid');
6780 var new_sid
= $next
.attr('data-luci2-sid');
6782 L
.uci
.swap(self
.ownerMap
.uci_package
, cur_sid
, new_sid
);
6784 self
.ownerMap
.save();
6785 self
.ownerMap
.redraw();
6788 ev
.stopPropagation();
6791 getPanelIndex: function(parent_sid
)
6793 return (this.active_panel
[parent_sid
|| '__top__'] || 0);
6796 setPanelIndex: function(parent_sid
, new_index
)
6798 if (typeof(new_index
) == 'number')
6799 this.active_panel
[parent_sid
|| '__top__'] = new_index
;
6802 renderAdd: function()
6804 if (!this.options
.addremove
)
6807 var text
= L
.tr('Add section');
6808 var ttip
= L
.tr('Create new section...');
6810 if ($.isArray(this.options
.add_caption
))
6811 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
6812 else if (typeof(this.options
.add_caption
) == 'string')
6813 text
= this.options
.add_caption
, ttip
= '';
6815 var add
= $('<div />');
6817 if (this.options
.anonymous
=== false)
6820 .addClass('cbi-input-text')
6821 .attr('type', 'text')
6822 .attr('placeholder', ttip
)
6823 .blur({ self
: this }, this.handleSID
)
6824 .keyup({ self
: this }, this.handleSID
)
6828 .attr('src', L
.globals
.resource
+ '/icons/cbi/add.gif')
6829 .attr('title', text
)
6830 .addClass('cbi-button')
6831 .click({ self
: this }, this.handleAdd
)
6835 .addClass('cbi-value-error')
6841 L
.ui
.button(text
, 'success', ttip
)
6842 .click({ self
: this }, this.handleAdd
)
6849 renderRemove: function(index
)
6851 if (!this.options
.addremove
)
6854 var text
= L
.tr('Remove');
6855 var ttip
= L
.tr('Remove this section');
6857 if ($.isArray(this.options
.remove_caption
))
6858 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
6859 else if (typeof(this.options
.remove_caption
) == 'string')
6860 text
= this.options
.remove_caption
, ttip
= '';
6862 return L
.ui
.button(text
, 'danger', ttip
)
6863 .click({ self
: this, index
: index
}, this.handleRemove
);
6866 renderSort: function(index
)
6868 if (!this.options
.sortable
)
6871 var b1
= L
.ui
.button('↑', 'info', L
.tr('Move up'))
6872 .click({ self
: this, index
: index
, up
: true }, this.handleSort
);
6874 var b2
= L
.ui
.button('↓', 'info', L
.tr('Move down'))
6875 .click({ self
: this, index
: index
, up
: false }, this.handleSort
);
6880 renderCaption: function()
6883 .addClass('panel-title')
6884 .append(this.label('caption') || this.uci_type
);
6887 renderDescription: function()
6889 var text
= this.label('description');
6893 .addClass('luci2-section-description')
6899 renderTeaser: function(sid
, index
)
6901 if (this.options
.collabsible
|| this.ownerMap
.options
.collabsible
)
6904 .attr('id', this.id('teaser', sid
))
6905 .addClass('luci2-section-teaser well well-sm')
6906 .append($('<span />')
6908 .append($('<span />'));
6914 renderHead: function(condensed
)
6920 .addClass('panel-heading')
6921 .append(this.renderCaption())
6922 .append(this.renderDescription());
6925 renderTabDescription: function(sid
, index
, tab_index
)
6927 var tab
= this.tabs
[tab_index
];
6929 if (typeof(tab
.description
) == 'string')
6932 .addClass('cbi-tab-descr')
6933 .text(tab
.description
);
6939 renderTabHead: function(sid
, index
, tab_index
)
6941 var tab
= this.tabs
[tab_index
];
6942 var cur
= this.active_tab
[sid
] || 0;
6944 var tabh
= $('<li />')
6946 .attr('id', this.id('nodetab', sid
, tab
.id
))
6947 .attr('href', '#' + this.id('node', sid
, tab
.id
))
6948 .attr('data-toggle', 'tab')
6949 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
6950 .append($('<span />')
6952 .on('shown.bs.tab', { self
: this, sid
: sid
}, this.handleTab
));
6954 if (cur
== tab_index
)
6955 tabh
.addClass('active');
6957 if (!tab
.fields
.length
)
6963 renderTabBody: function(sid
, index
, tab_index
)
6965 var tab
= this.tabs
[tab_index
];
6966 var cur
= this.active_tab
[sid
] || 0;
6968 var tabb
= $('<div />')
6969 .addClass('tab-pane')
6970 .attr('id', this.id('node', sid
, tab
.id
))
6971 .append(this.renderTabDescription(sid
, index
, tab_index
))
6972 .on('validate', this.handleTabValidate
);
6974 if (cur
== tab_index
)
6975 tabb
.addClass('active');
6977 for (var i
= 0; i
< tab
.fields
.length
; i
++)
6978 tabb
.append(tab
.fields
[i
].render(sid
));
6983 renderPanelHead: function(sid
, index
, parent_sid
)
6985 var head
= $('<div />')
6986 .addClass('luci2-section-header')
6987 .append(this.renderTeaser(sid
, index
))
6988 .append($('<div />')
6989 .addClass('btn-group')
6990 .append(this.renderSort(index
))
6991 .append(this.renderRemove(index
)));
6993 if (this.options
.collabsible
)
6995 head
.attr('data-toggle', 'collapse')
6996 .attr('data-parent', this.id('sectiongroup', parent_sid
))
6997 .attr('data-target', '#' + this.id('panel', sid
));
7003 renderPanelBody: function(sid
, index
, parent_sid
)
7005 var body
= $('<div />')
7006 .attr('id', this.id('panel', sid
))
7007 .addClass('luci2-section-panel')
7008 .on('validate', this.handlePanelValidate
);
7010 if (this.options
.collabsible
|| this.ownerMap
.options
.collabsible
)
7012 body
.addClass('panel-collapse collapse');
7014 if (index
== this.getPanelIndex(parent_sid
))
7015 body
.addClass('in');
7018 var tab_heads
= $('<ul />')
7019 .addClass('nav nav-tabs');
7021 var tab_bodies
= $('<div />')
7022 .addClass('form-horizontal tab-content')
7025 for (var j
= 0; j
< this.tabs
.length
; j
++)
7027 tab_heads
.append(this.renderTabHead(sid
, index
, j
));
7028 tab_bodies
.append(this.renderTabBody(sid
, index
, j
));
7031 body
.append(tab_bodies
);
7033 if (this.tabs
.length
<= 1)
7036 for (var i
= 0; i
< this.subsections
.length
; i
++)
7037 body
.append(this.subsections
[i
].render(false, sid
));
7042 renderBody: function(condensed
, parent_sid
)
7044 var s
= this.getUCISections(parent_sid
);
7045 var n
= this.getPanelIndex(parent_sid
);
7048 this.setPanelIndex(parent_sid
, n
+ s
.length
);
7049 else if (n
>= s
.length
)
7050 this.setPanelIndex(parent_sid
, s
.length
- 1);
7052 var body
= $('<ul />')
7053 .addClass('luci2-section-group list-group');
7055 if (this.options
.collabsible
)
7057 body
.attr('id', this.id('sectiongroup', parent_sid
))
7058 .on('show.bs.collapse', { self
: this }, this.handlePanelCollapse
);
7063 body
.append($('<li />')
7064 .addClass('list-group-item text-muted')
7065 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.')))
7068 for (var i
= 0; i
< s
.length
; i
++)
7070 var sid
= s
[i
]['.name'];
7071 var inst
= this.instance
[sid
] = { tabs
: [ ] };
7073 body
.append($('<li />')
7074 .addClass('luci2-section-item list-group-item')
7075 .attr('id', this.id('sectionitem', sid
))
7076 .attr('data-luci2-sid', sid
)
7077 .append(this.renderPanelHead(sid
, i
, parent_sid
))
7078 .append(this.renderPanelBody(sid
, i
, parent_sid
)));
7084 render: function(condensed
, parent_sid
)
7086 this.instance
= { };
7088 var panel
= $('<div />')
7089 .addClass('panel panel-default')
7090 .append(this.renderHead(condensed
))
7091 .append(this.renderBody(condensed
, parent_sid
));
7093 if (this.options
.addremove
)
7094 panel
.append($('<div />')
7095 .addClass('panel-footer')
7096 .append(this.renderAdd()));
7101 finish: function(parent_sid
)
7103 var s
= this.getUCISections(parent_sid
);
7105 for (var i
= 0; i
< s
.length
; i
++)
7107 var sid
= s
[i
]['.name'];
7109 if (i
!= this.getPanelIndex(parent_sid
))
7110 $('#' + this.id('teaser', sid
)).children('span:last')
7111 .append(this.teaser(sid
));
7113 $('#' + this.id('teaser', sid
))
7116 for (var j
= 0; j
< this.subsections
.length
; j
++)
7117 this.subsections
[j
].finish(sid
);
7122 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
7123 renderTableHead: function()
7125 var thead
= $('<thead />')
7127 .addClass('cbi-section-table-titles'));
7129 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
7130 thead
.children().append($('<th />')
7131 .addClass('cbi-section-table-cell')
7132 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
7133 .append(this.tabs
[0].fields
[j
].label('caption')));
7135 if (this.options
.addremove
!== false || this.options
.sortable
)
7136 thead
.children().append($('<th />')
7137 .addClass('cbi-section-table-cell')
7143 renderTableRow: function(sid
, index
)
7145 var row
= $('<tr />')
7146 .addClass('luci2-section-item')
7147 .attr('id', this.id('sectionitem', sid
))
7148 .attr('data-luci2-sid', sid
);
7150 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
7152 row
.append($('<td />')
7153 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
7154 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
7157 if (this.options
.addremove
!== false || this.options
.sortable
)
7159 row
.append($('<td />')
7161 .addClass('text-right')
7162 .append($('<div />')
7163 .addClass('btn-group')
7164 .append(this.renderSort(index
))
7165 .append(this.renderRemove(index
))));
7171 renderTableBody: function(parent_sid
)
7173 var s
= this.getUCISections(parent_sid
);
7175 var tbody
= $('<tbody />');
7179 var cols
= this.tabs
[0].fields
.length
;
7181 if (this.options
.addremove
!== false || this.options
.sortable
)
7184 tbody
.append($('<tr />')
7186 .addClass('text-muted')
7187 .attr('colspan', cols
)
7188 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.'))));
7191 for (var i
= 0; i
< s
.length
; i
++)
7193 var sid
= s
[i
]['.name'];
7194 var inst
= this.instance
[sid
] = { tabs
: [ ] };
7196 tbody
.append(this.renderTableRow(sid
, i
));
7202 renderBody: function(condensed
, parent_sid
)
7204 return $('<table />')
7205 .addClass('table table-condensed table-hover')
7206 .append(this.renderTableHead())
7207 .append(this.renderTableBody(parent_sid
));
7211 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
7212 getUCISections: function(cb
)
7215 var sl
= L
.uci
.sections(this.ownerMap
.uci_package
);
7217 for (var i
= 0; i
< sl
.length
; i
++)
7218 if (sl
[i
]['.name'] == this.uci_type
)
7224 if (typeof(cb
) == 'function' && sa
.length
> 0)
7225 cb
.call(this, sa
[0]);
7231 this.cbi
.SingleSection
= this.cbi
.NamedSection
.extend({
7234 this.instance
= { };
7235 this.instance
[this.uci_type
] = { tabs
: [ ] };
7238 .addClass('luci2-section-item')
7239 .attr('id', this.id('sectionitem', this.uci_type
))
7240 .attr('data-luci2-sid', this.uci_type
)
7241 .append(this.renderPanelBody(this.uci_type
, 0));
7245 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
7246 getUCISections: function(cb
)
7248 if (typeof(cb
) == 'function')
7249 cb
.apply(this, [ { '.name': this.uci_type
} ]);
7251 return [ { '.name': this.uci_type
} ];
7255 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
7256 init: function(uci_package
, options
)
7260 this.uci_package
= uci_package
;
7261 this.sections
= [ ];
7262 this.options
= L
.defaults(options
, {
7263 save: function() { },
7264 prepare: function() { }
7268 loadCallback: function()
7270 var deferreds
= [ L
.deferrable(this.options
.prepare()) ];
7272 for (var i
= 0; i
< this.sections
.length
; i
++)
7274 var rv
= this.sections
[i
].load();
7275 deferreds
.push
.apply(deferreds
, rv
);
7278 return $.when
.apply($, deferreds
);
7284 var packages
= [ this.uci_package
];
7286 for (var i
= 0; i
< this.sections
.length
; i
++)
7287 packages
.push
.apply(packages
, this.sections
[i
].findAdditionalUCIPackages());
7289 for (var i
= 0; i
< packages
.length
; i
++)
7290 if (!L
.uci
.writable(packages
[i
]))
7292 this.options
.readonly
= true;
7296 return L
.uci
.load(packages
).then(function() {
7297 return self
.loadCallback();
7301 handleTab: function(ev
)
7303 ev
.data
.self
.active_tab
= $(ev
.target
).parent().index();
7306 handleApply: function(ev
)
7308 var self
= ev
.data
.self
;
7310 self
.trigger('apply', ev
);
7313 handleSave: function(ev
)
7315 var self
= ev
.data
.self
;
7317 self
.send().then(function() {
7318 self
.trigger('save', ev
);
7322 handleReset: function(ev
)
7324 var self
= ev
.data
.self
;
7326 self
.trigger('reset', ev
);
7330 renderTabHead: function(tab_index
)
7332 var section
= this.sections
[tab_index
];
7333 var cur
= this.active_tab
|| 0;
7335 var tabh
= $('<li />')
7337 .attr('id', section
.id('sectiontab'))
7338 .attr('href', '#' + section
.id('section'))
7339 .attr('data-toggle', 'tab')
7340 .text(section
.label('caption') + ' ')
7341 .append($('<span />')
7343 .on('shown.bs.tab', { self
: this }, this.handleTab
));
7345 if (cur
== tab_index
)
7346 tabh
.addClass('active');
7351 renderTabBody: function(tab_index
)
7353 var section
= this.sections
[tab_index
];
7354 var desc
= section
.label('description');
7355 var cur
= this.active_tab
|| 0;
7357 var tabb
= $('<div />')
7358 .addClass('tab-pane')
7359 .attr('id', section
.id('section'));
7361 if (cur
== tab_index
)
7362 tabb
.addClass('active');
7365 tabb
.append($('<p />')
7368 var s
= section
.render(this.options
.tabbed
);
7370 if (this.options
.readonly
|| section
.options
.readonly
)
7371 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
7378 renderBody: function()
7380 var tabs
= $('<ul />')
7381 .addClass('nav nav-tabs');
7383 var body
= $('<div />')
7386 for (var i
= 0; i
< this.sections
.length
; i
++)
7388 tabs
.append(this.renderTabHead(i
));
7389 body
.append(this.renderTabBody(i
));
7392 if (this.options
.tabbed
)
7393 body
.addClass('tab-content');
7400 renderFooter: function()
7407 .addClass('panel panel-default panel-body text-right')
7408 .append($('<div />')
7409 .addClass('btn-group')
7410 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7411 .click(evdata
, this.handleApply
))
7412 .append(L
.ui
.button(L
.tr('Save'), 'default')
7413 .click(evdata
, this.handleSave
))
7414 .append(L
.ui
.button(L
.tr('Reset'), 'default')
7415 .click(evdata
, this.handleReset
)));
7420 var map
= $('<form />');
7422 if (typeof(this.options
.caption
) == 'string')
7423 map
.append($('<h2 />')
7424 .text(this.options
.caption
));
7426 if (typeof(this.options
.description
) == 'string')
7427 map
.append($('<p />')
7428 .text(this.options
.description
));
7430 map
.append(this.renderBody());
7432 if (this.options
.pageaction
!== false)
7433 map
.append(this.renderFooter());
7440 for (var i
= 0; i
< this.sections
.length
; i
++)
7441 this.sections
[i
].finish();
7448 this.target
.hide().empty().append(this.render());
7453 section: function(widget
, uci_type
, options
)
7455 var w
= widget
? new widget(uci_type
, options
) : null;
7457 if (!(w
instanceof L
.cbi
.AbstractSection
))
7458 throw 'Widget must be an instance of AbstractSection';
7461 w
.index
= this.sections
.length
;
7463 this.sections
.push(w
);
7467 add: function(conf
, type
, name
)
7469 return L
.uci
.add(conf
, type
, name
);
7472 remove: function(conf
, sid
)
7474 return L
.uci
.remove(conf
, sid
);
7477 get: function(conf
, sid
, opt
)
7479 return L
.uci
.get(conf
, sid
, opt
);
7482 set: function(conf
, sid
, opt
, val
)
7484 return L
.uci
.set(conf
, sid
, opt
, val
);
7487 validate: function()
7491 for (var i
= 0; i
< this.sections
.length
; i
++)
7493 if (!this.sections
[i
].validate())
7504 if (self
.options
.readonly
)
7505 return L
.deferrable();
7507 var deferreds
= [ ];
7509 for (var i
= 0; i
< self
.sections
.length
; i
++)
7511 var rv
= self
.sections
[i
].save();
7512 deferreds
.push
.apply(deferreds
, rv
);
7515 return $.when
.apply($, deferreds
).then(function() {
7516 return L
.deferrable(self
.options
.save());
7522 if (!this.validate())
7523 return L
.deferrable();
7527 L
.ui
.saveScrollTop();
7530 return this.save().then(function() {
7531 return L
.uci
.save();
7532 }).then(function() {
7533 return L
.ui
.updateChanges();
7534 }).then(function() {
7536 }).then(function() {
7540 L
.ui
.loading(false);
7541 L
.ui
.restoreScrollTop();
7547 var packages
= [ this.uci_package
];
7549 for (var i
= 0; i
< this.sections
.length
; i
++)
7550 packages
.push
.apply(packages
, this.sections
[i
].findAdditionalUCIPackages());
7552 L
.uci
.unload(packages
);
7561 return self
.insertInto(self
.target
);
7564 insertInto: function(id
)
7567 self
.target
= $(id
);
7572 return self
.load().then(function() {
7573 self
.target
.empty().append(self
.render());
7577 L
.ui
.loading(false);
7582 this.cbi
.Modal
= this.cbi
.Map
.extend({
7583 handleApply: function(ev
)
7585 var self
= ev
.data
.self
;
7587 self
.trigger('apply', ev
);
7590 handleSave: function(ev
)
7592 var self
= ev
.data
.self
;
7594 self
.send().then(function() {
7595 self
.trigger('save', ev
);
7600 handleReset: function(ev
)
7602 var self
= ev
.data
.self
;
7604 self
.trigger('close', ev
);
7609 renderFooter: function()
7616 .addClass('btn-group')
7617 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7618 .click(evdata
, this.handleApply
))
7619 .append(L
.ui
.button(L
.tr('Save'), 'default')
7620 .click(evdata
, this.handleSave
))
7621 .append(L
.ui
.button(L
.tr('Cancel'), 'default')
7622 .click(evdata
, this.handleReset
));
7627 var modal
= L
.ui
.dialog(this.label('caption'), null, { wide
: true });
7628 var map
= $('<form />');
7630 var desc
= this.label('description');
7632 map
.append($('<p />').text(desc
));
7634 map
.append(this.renderBody());
7636 modal
.find('.modal-body').append(map
);
7637 modal
.find('.modal-footer').append(this.renderFooter());
7654 return self
.load().then(function() {
7658 L
.ui
.loading(false);