5e9510504f5f840388475a656a2d477e761f8a6c
2 LuCI2 - OpenWrt Web Interface
4 Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
13 String
.prototype.format = function()
15 var html_esc
= [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
16 var quot_esc = [/"/g
, '"', /'/g, '''];
19 for( var i = 0; i < r.length; i += 2 )
20 s = s.replace(r[i], r[i+1]);
26 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d
+)?(\.\d
+)?(%|b
|c
|d
|u
|f
|o
|s
|x
|X
|q
|h
|j
|t
|m
))/;
27 var a
= b
= [], numSubstitutions
= 0, numMatches
= 0;
29 while ((a
= re
.exec(str
)) != null)
32 var leftpart
= a
[2], pPad
= a
[3], pJustify
= a
[4], pMinLength
= a
[5];
33 var pPrecision
= a
[6], pType
= a
[7];
43 if (numSubstitutions
< arguments
.length
)
45 var param
= arguments
[numSubstitutions
++];
48 if (pPad
&& pPad
.substr(0,1) == "'")
49 pad
= leftpart
.substr(1,1);
53 var justifyRight
= true;
54 if (pJustify
&& pJustify
=== "-")
59 minLength
= parseInt(pMinLength
);
62 if (pPrecision
&& pType
== 'f')
63 precision
= parseInt(pPrecision
.substring(1));
70 subst
= (parseInt(param
) || 0).toString(2);
74 subst
= String
.fromCharCode(parseInt(param
) || 0);
78 subst
= (parseInt(param
) || 0);
82 subst
= Math
.abs(parseInt(param
) || 0);
86 subst
= (precision
> -1)
87 ? ((parseFloat(param
) || 0.0)).toFixed(precision
)
88 : (parseFloat(param
) || 0.0);
92 subst
= (parseInt(param
) || 0).toString(8);
100 subst
= ('' + (parseInt(param
) || 0).toString(16)).toLowerCase();
104 subst
= ('' + (parseInt(param
) || 0).toString(16)).toUpperCase();
108 subst
= esc(param
, html_esc
);
112 subst
= esc(param
, quot_esc
);
116 subst
= String
.serialize(param
);
123 var ts
= (param
|| 0);
126 tm
= Math
.floor(ts
/ 60);
131 th
= Math
.floor(tm
/ 60);
136 td
= Math
.floor(th
/ 24);
141 ? '%dd %dh %dm %ds'.format(td
, th
, tm
, ts
)
142 : '%dh %dm %ds'.format(th
, tm
, ts
);
147 var mf
= pMinLength
? parseInt(pMinLength
) : 1000;
148 var pr
= pPrecision
? Math
.floor(10*parseFloat('0'+pPrecision
)) : 2;
151 var val
= parseFloat(param
|| 0);
152 var units
= [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
154 for (i
= 0; (i
< units
.length
) && (val
> mf
); i
++)
157 subst
= val
.toFixed(pr
) + ' ' + units
[i
];
161 subst
= (typeof(subst
) == 'undefined') ? '' : subst
.toString();
163 if (minLength
> 0 && pad
.length
> 0)
164 for (var i
= 0; i
< (minLength
- subst
.length
); i
++)
165 subst
= justifyRight
? (pad
+ subst
) : (subst
+ pad
);
169 out
+= leftpart
+ subst
;
170 str
= str
.substr(m
.length
);
180 var Class = function() { };
182 Class
.extend = function(properties
)
184 Class
.initializing
= true;
186 var prototype = new this();
187 var superprot
= this.prototype;
189 Class
.initializing
= false;
191 $.extend(prototype, properties
, {
192 callSuper: function() {
194 var meth
= arguments
[0];
196 if (typeof(superprot
[meth
]) != 'function')
199 for (var i
= 1; i
< arguments
.length
; i
++)
200 args
.push(arguments
[i
]);
202 return superprot
[meth
].apply(this, args
);
208 this.options
= arguments
[0] || { };
210 if (!Class
.initializing
&& typeof(this.init
) == 'function')
211 this.init
.apply(this, arguments
);
214 _class
.prototype = prototype;
215 _class
.prototype.constructor = _class
;
217 _class
.extend
= Class
.extend
;
222 this.defaults = function(obj
, def
)
225 if (typeof(obj
[key
]) == 'undefined')
231 this.isDeferred = function(x
)
233 return (typeof(x
) == 'object' &&
234 typeof(x
.then
) == 'function' &&
235 typeof(x
.promise
) == 'function');
238 this.deferrable = function()
240 if (this.isDeferred(arguments
[0]))
243 var d
= $.Deferred();
244 d
.resolve
.apply(d
, arguments
);
253 plural: function(n
) { return 0 + (n
!= 1) },
259 var lang
= (navigator
.userLanguage
|| navigator
.language
|| 'en').toLowerCase();
260 var langs
= (lang
.indexOf('-') > -1) ? [ lang
, lang
.split(/-/)[0] ] : [ lang
];
262 for (var i
= 0; i
< langs
.length
; i
++)
263 $.ajax('%s/i18n/base.%s.json'.format(L
.globals
.resource
, langs
[i
]), {
267 success: function(data
) {
268 $.extend(L
.i18n
.catalog
, data
);
270 var pe
= L
.i18n
.catalog
[''];
273 delete L
.i18n
.catalog
[''];
275 var pf
= new Function('n', 'return 0 + (' + pe
+ ')');
282 L
.i18n
.loaded
= true;
287 this.tr = function(msgid
)
291 var msgstr
= L
.i18n
.catalog
[msgid
];
293 if (typeof(msgstr
) == 'undefined')
295 else if (typeof(msgstr
) == 'string')
301 this.trp = function(msgid
, msgid_plural
, count
)
305 var msgstr
= L
.i18n
.catalog
[msgid
];
307 if (typeof(msgstr
) == 'undefined')
308 return (count
== 1) ? msgid
: msgid_plural
;
309 else if (typeof(msgstr
) == 'string')
312 return msgstr
[L
.i18n
.plural(count
)];
315 this.trc = function(msgctx
, msgid
)
319 var msgstr
= L
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
321 if (typeof(msgstr
) == 'undefined')
323 else if (typeof(msgstr
) == 'string')
329 this.trcp = function(msgctx
, msgid
, msgid_plural
, count
)
333 var msgstr
= L
.i18n
.catalog
[msgid
+ '\u0004' + msgctx
];
335 if (typeof(msgstr
) == 'undefined')
336 return (count
== 1) ? msgid
: msgid_plural
;
337 else if (typeof(msgstr
) == 'string')
340 return msgstr
[L
.i18n
.plural(count
)];
343 this.setHash = function(key
, value
)
346 var data
= this.getHash(undefined);
348 if (typeof(value
) == 'undefined')
359 for (var i
= 0; i
< keys
.length
; i
++)
364 h
+= keys
[i
] + ':' + data
[keys
[i
]];
368 location
.hash
= '#' + h
;
373 this.getHash = function(key
)
376 var tuples
= (location
.hash
|| '#').substring(1).split(/,/);
378 for (var i
= 0; i
< tuples
.length
; i
++)
380 var tuple
= tuples
[i
].split(/:/);
381 if (tuple
.length
== 2)
382 data
[tuple
[0]] = tuple
[1];
385 if (typeof(key
) != 'undefined')
391 this.toArray = function(x
)
401 var l
= x
.split(/\s+/);
402 for (var i
= 0; i
< l
.length
; i
++)
411 for (var i
= 0; i
< x
.length
; i
++)
415 else if ($.isPlainObject(x
))
419 if (x
.hasOwnProperty(k
))
428 this.toObject = function(x
)
438 var l
= x
.split(/\x+/);
439 for (var i
= 0; i
< l
.length
; i
++)
448 for (var i
= 0; i
< x
.length
; i
++)
452 else if ($.isPlainObject(x
))
461 this.filterArray = function(array
, item
)
463 if (!$.isArray(array
))
466 for (var i
= 0; i
< array
.length
; i
++)
467 if (array
[i
] === item
)
468 array
.splice(i
--, 1);
473 this.toClassName = function(str
, suffix
)
476 var l
= str
.split(/[\/.]/);
478 for (var i
= 0; i
< l
.length
; i
++)
480 n
+= l
[i
].charAt(0).toUpperCase() + l
[i
].substr(1).toLowerCase();
482 if (typeof(suffix
) == 'string')
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 _load
: L
.rpc
.declare({
835 params
: [ 'config' ],
836 expect
: { values
: { } }
839 _order
: L
.rpc
.declare({
842 params
: [ 'config', 'sections' ]
845 _add
: L
.rpc
.declare({
848 params
: [ 'config', 'type', 'name', 'values' ],
849 expect
: { section
: '' }
852 _set
: L
.rpc
.declare({
855 params
: [ 'config', 'section', 'values' ]
858 _delete
: L
.rpc
.declare({
861 params
: [ 'config', 'section', 'options' ]
864 _newid: function(conf
)
866 var v
= this.state
.values
;
867 var n
= this.state
.creates
;
871 sid
= "new%06x".format(Math
.random() * 0xFFFFFF);
872 } while ((n
[conf
] && n
[conf
][sid
]) || (v
[conf
] && v
[conf
][sid
]));
877 load: function(packages
)
883 if (!$.isArray(packages
))
884 packages
= [ packages
];
888 for (var i
= 0; i
< packages
.length
; i
++)
889 if (!seen
[packages
[i
]] && !self
.state
.values
[packages
[i
]])
891 pkgs
.push(packages
[i
]);
892 seen
[packages
[i
]] = true;
893 self
._load(packages
[i
]);
896 return L
.rpc
.flush().then(function(responses
) {
897 for (var i
= 0; i
< responses
.length
; i
++)
898 self
.state
.values
[pkgs
[i
]] = responses
[i
];
904 unload: function(packages
)
906 if (!$.isArray(packages
))
907 packages
= [ packages
];
909 for (var i
= 0; i
< packages
.length
; i
++)
911 delete this.state
.values
[packages
[i
]];
912 delete this.state
.creates
[packages
[i
]];
913 delete this.state
.changes
[packages
[i
]];
914 delete this.state
.deletes
[packages
[i
]];
918 add: function(conf
, type
, name
)
920 var n
= this.state
.creates
;
921 var sid
= this._newid(conf
);
931 '.index': 1000 + this.state
.newidx
++
937 remove: function(conf
, sid
)
939 var n
= this.state
.creates
;
940 var c
= this.state
.changes
;
941 var d
= this.state
.deletes
;
943 /* requested deletion of a just created section */
944 if (n
[conf
] && n
[conf
][sid
])
960 sections: function(conf
, type
, cb
)
963 var v
= this.state
.values
[conf
];
964 var n
= this.state
.creates
[conf
];
965 var c
= this.state
.changes
[conf
];
966 var d
= this.state
.deletes
[conf
];
972 if (!d
|| d
[s
] !== true)
973 if (!type
|| v
[s
]['.type'] == type
)
974 sa
.push($.extend({ }, v
[s
], c
? c
[s
] : undefined));
978 if (!type
|| n
[s
]['.type'] == type
)
981 sa
.sort(function(a
, b
) {
982 return a
['.index'] - b
['.index'];
985 for (var i
= 0; i
< sa
.length
; i
++)
988 if (typeof(cb
) == 'function')
989 for (var i
= 0; i
< sa
.length
; i
++)
990 cb
.call(this, sa
[i
], sa
[i
]['.name']);
995 get: function(conf
, sid
, opt
)
997 var v
= this.state
.values
;
998 var n
= this.state
.creates
;
999 var c
= this.state
.changes
;
1000 var d
= this.state
.deletes
;
1002 if (typeof(sid
) == 'undefined')
1005 /* requested option in a just created section */
1006 if (n
[conf
] && n
[conf
][sid
])
1011 if (typeof(opt
) == 'undefined')
1012 return n
[conf
][sid
];
1014 return n
[conf
][sid
][opt
];
1017 /* requested an option value */
1018 if (typeof(opt
) != 'undefined')
1020 /* check whether option was deleted */
1021 if (d
[conf
] && d
[conf
][sid
])
1023 if (d
[conf
][sid
] === true)
1026 for (var i
= 0; i
< d
[conf
][sid
].length
; i
++)
1027 if (d
[conf
][sid
][i
] == opt
)
1031 /* check whether option was changed */
1032 if (c
[conf
] && c
[conf
][sid
] && typeof(c
[conf
][sid
][opt
]) != 'undefined')
1033 return c
[conf
][sid
][opt
];
1035 /* return base value */
1036 if (v
[conf
] && v
[conf
][sid
])
1037 return v
[conf
][sid
][opt
];
1042 /* requested an entire section */
1044 return v
[conf
][sid
];
1049 set: function(conf
, sid
, opt
, val
)
1051 var v
= this.state
.values
;
1052 var n
= this.state
.creates
;
1053 var c
= this.state
.changes
;
1054 var d
= this.state
.deletes
;
1056 if (typeof(sid
) == 'undefined' ||
1057 typeof(opt
) == 'undefined' ||
1058 opt
.charAt(0) == '.')
1061 if (n
[conf
] && n
[conf
][sid
])
1063 if (typeof(val
) != 'undefined')
1064 n
[conf
][sid
][opt
] = val
;
1066 delete n
[conf
][sid
][opt
];
1068 else if (typeof(val
) != 'undefined')
1070 /* do not set within deleted section */
1071 if (d
[conf
] && d
[conf
][sid
] === true)
1074 /* only set in existing sections */
1075 if (!v
[conf
] || !v
[conf
][sid
])
1084 /* undelete option */
1085 if (d
[conf
] && d
[conf
][sid
])
1086 d
[conf
][sid
] = L
.filterArray(d
[conf
][sid
], opt
);
1088 c
[conf
][sid
][opt
] = val
;
1092 /* only delete in existing sections */
1093 if (!v
[conf
] || !v
[conf
][sid
])
1102 if (d
[conf
][sid
] !== true)
1103 d
[conf
][sid
].push(opt
);
1107 unset: function(conf
, sid
, opt
)
1109 return this.set(conf
, sid
, opt
, undefined);
1112 get_first: function(conf
, type
, opt
)
1114 var sid
= undefined;
1116 L
.uci
.sections(conf
, type
, function(s
) {
1117 if (typeof(sid
) != 'string')
1121 return this.get(conf
, sid
, opt
);
1124 set_first: function(conf
, type
, opt
, val
)
1126 var sid
= undefined;
1128 L
.uci
.sections(conf
, type
, function(s
) {
1129 if (typeof(sid
) != 'string')
1133 return this.set(conf
, sid
, opt
, val
);
1136 unset_first: function(conf
, type
, opt
)
1138 return this.set_first(conf
, type
, opt
, undefined);
1145 for (var pkg
in this.state
.values
)
1150 return this.load(pkgs
);
1153 _reorder: function()
1155 var v
= this.state
.values
;
1156 var n
= this.state
.creates
;
1157 var r
= this.state
.reorder
;
1159 if ($.isEmptyObject(r
))
1160 return L
.deferrable();
1165 gather all created and existing sections, sort them according
1166 to their index value and issue an uci order call
1181 o
.sort(function(a
, b
) {
1182 return (a
['.index'] - b
['.index']);
1187 for (var i
= 0; i
< o
.length
; i
++)
1188 sids
.push(o
[i
]['.name']);
1190 this._order(c
, sids
);
1194 this.state
.reorder
= { };
1195 return L
.rpc
.flush();
1198 swap: function(conf
, sid1
, sid2
)
1200 var s1
= this.get(conf
, sid1
);
1201 var s2
= this.get(conf
, sid2
);
1202 var n1
= s1
? s1
['.index'] : NaN
;
1203 var n2
= s2
? s2
['.index'] : NaN
;
1205 if (isNaN(n1
) || isNaN(n2
))
1211 this.state
.reorder
[conf
] = true;
1220 var v
= this.state
.values
;
1221 var n
= this.state
.creates
;
1222 var c
= this.state
.changes
;
1223 var d
= this.state
.deletes
;
1232 for (var sid
in n
[conf
])
1239 for (var k
in n
[conf
][sid
])
1242 r
.type
= n
[conf
][sid
][k
];
1243 else if (k
== '.create')
1244 r
.name
= n
[conf
][sid
][k
];
1245 else if (k
.charAt(0) != '.')
1246 r
.values
[k
] = n
[conf
][sid
][k
];
1249 snew
.push(n
[conf
][sid
]);
1251 self
._add(r
.config
, r
.type
, r
.name
, r
.values
);
1260 for (var sid
in c
[conf
])
1261 self
._set(conf
, sid
, c
[conf
][sid
]);
1269 for (var sid
in d
[conf
])
1271 var o
= d
[conf
][sid
];
1272 self
._delete(conf
, sid
, (o
=== true) ? undefined : o
);
1278 return L
.rpc
.flush().then(function(responses
) {
1280 array "snew" holds references to the created uci sections,
1281 use it to assign the returned names of the new sections
1283 for (var i
= 0; i
< snew
.length
; i
++)
1284 snew
[i
]['.name'] = responses
[i
];
1286 return self
._reorder();
1287 }).then(function() {
1288 pkgs
= L
.toArray(pkgs
);
1292 return self
.load(pkgs
);
1296 _apply
: L
.rpc
.declare({
1299 params
: [ 'timeout', 'rollback' ]
1302 _confirm
: L
.rpc
.declare({
1307 apply: function(timeout
)
1310 var date
= new Date();
1311 var deferred
= $.Deferred();
1313 if (typeof(timeout
) != 'number' || timeout
< 1)
1316 self
._apply(timeout
, true).then(function(rv
) {
1319 deferred
.rejectWith(self
, [ rv
]);
1323 var try_deadline
= date
.getTime() + 1000 * timeout
;
1324 var try_confirm = function()
1326 return self
._confirm().then(function(rv
) {
1329 if (date
.getTime() < try_deadline
)
1330 window
.setTimeout(try_confirm
, 250);
1332 deferred
.rejectWith(self
, [ rv
]);
1337 deferred
.resolveWith(self
, [ rv
]);
1341 window
.setTimeout(try_confirm
, 1000);
1347 changes
: L
.rpc
.declare({
1350 expect
: { changes
: { } }
1353 readable: function(conf
)
1355 return L
.session
.hasACL('uci', conf
, 'read');
1358 writable: function(conf
)
1360 return L
.session
.hasACL('uci', conf
, 'write');
1364 this.uci
= new this.UCIContext();
1367 listDeviceNames
: L
.rpc
.declare({
1370 expect
: { 'devices': [ ] },
1371 filter: function(data
) {
1377 getDeviceStatus
: L
.rpc
.declare({
1380 params
: [ 'device' ],
1381 expect
: { '': { } },
1382 filter: function(data
, params
) {
1383 if (!$.isEmptyObject(data
))
1385 data
['device'] = params
['device'];
1392 getAssocList
: L
.rpc
.declare({
1394 method
: 'assoclist',
1395 params
: [ 'device' ],
1396 expect
: { results
: [ ] },
1397 filter: function(data
, params
) {
1398 for (var i
= 0; i
< data
.length
; i
++)
1399 data
[i
]['device'] = params
['device'];
1401 data
.sort(function(a
, b
) {
1402 if (a
.bssid
< b
.bssid
)
1404 else if (a
.bssid
> b
.bssid
)
1414 getWirelessStatus: function() {
1415 return this.listDeviceNames().then(function(names
) {
1418 for (var i
= 0; i
< names
.length
; i
++)
1419 L
.wireless
.getDeviceStatus(names
[i
]);
1421 return L
.rpc
.flush();
1422 }).then(function(networks
) {
1426 'country', 'channel', 'frequency', 'frequency_offset',
1427 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1431 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1432 'signal', 'noise', 'bitrate', 'encryption'
1435 for (var i
= 0; i
< networks
.length
; i
++)
1437 var phy
= rv
[networks
[i
].phy
] || (
1438 rv
[networks
[i
].phy
] = { networks
: [ ] }
1442 device
: networks
[i
].device
1445 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1446 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1448 for (var j
= 0; j
< net_attrs
.length
; j
++)
1449 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1451 phy
.networks
.push(net
);
1458 getAssocLists: function()
1460 return this.listDeviceNames().then(function(names
) {
1463 for (var i
= 0; i
< names
.length
; i
++)
1464 L
.wireless
.getAssocList(names
[i
]);
1466 return L
.rpc
.flush();
1467 }).then(function(assoclists
) {
1470 for (var i
= 0; i
< assoclists
.length
; i
++)
1471 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1472 rv
.push(assoclists
[i
][j
]);
1478 formatEncryption: function(enc
)
1480 var format_list = function(l
, s
)
1483 for (var i
= 0; i
< l
.length
; i
++)
1484 rv
.push(l
[i
].toUpperCase());
1485 return rv
.join(s
? s
: ', ');
1488 if (!enc
|| !enc
.enabled
)
1489 return L
.tr('None');
1493 if (enc
.wep
.length
== 2)
1494 return L
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1495 else if (enc
.wep
[0] == 'shared')
1496 return L
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1498 return L
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1502 if (enc
.wpa
.length
== 2)
1503 return L
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1504 format_list(enc
.authentication
, '/'),
1505 format_list(enc
.ciphers
, ', ')
1507 else if (enc
.wpa
[0] == 2)
1508 return 'WPA2 %s (%s)'.format(
1509 format_list(enc
.authentication
, '/'),
1510 format_list(enc
.ciphers
, ', ')
1513 return 'WPA %s (%s)'.format(
1514 format_list(enc
.authentication
, '/'),
1515 format_list(enc
.ciphers
, ', ')
1519 return L
.tr('Unknown');
1524 getZoneColor: function(zone
)
1526 if ($.isPlainObject(zone
))
1531 else if (zone
== 'wan')
1534 for (var i
= 0, hash
= 0;
1536 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1538 for (var i
= 0, color
= '#';
1540 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tostring(16)).slice(-2));
1545 findZoneByNetwork: function(network
)
1548 var zone
= undefined;
1550 return L
.uci
.sections('firewall', 'zone', function(z
) {
1551 if (!z
.name
|| !z
.network
)
1554 if (!$.isArray(z
.network
))
1555 z
.network
= z
.network
.split(/\s+/);
1557 for (var i
= 0; i
< z
.network
.length
; i
++)
1559 if (z
.network
[i
] == network
)
1565 }).then(function() {
1567 zone
.color
= self
.getZoneColor(zone
);
1574 this.NetworkModel
= {
1575 _device_blacklist
: [
1581 /^wlan[0-9]+\.sta[0-9]+$/
1585 'protolist', 0, L
.rpc
.declare({
1587 method
: 'get_proto_handlers',
1590 'ifstate', 1, L
.rpc
.declare({
1591 object
: 'network.interface',
1593 expect
: { 'interface': [ ] }
1595 'devstate', 2, L
.rpc
.declare({
1596 object
: 'network.device',
1600 'wifistate', 0, L
.rpc
.declare({
1601 object
: 'network.wireless',
1605 'bwstate', 2, L
.rpc
.declare({
1606 object
: 'luci2.network.bwmon',
1607 method
: 'statistics',
1608 expect
: { 'statistics': { } }
1610 'devlist', 2, L
.rpc
.declare({
1611 object
: 'luci2.network',
1612 method
: 'device_list',
1613 expect
: { 'devices': [ ] }
1615 'swlist', 0, L
.rpc
.declare({
1616 object
: 'luci2.network',
1617 method
: 'switch_list',
1618 expect
: { 'switches': [ ] }
1622 _fetch_protocol: function(proto
)
1624 var url
= L
.globals
.resource
+ '/proto/' + proto
+ '.js';
1625 var self
= L
.NetworkModel
;
1627 var def
= $.Deferred();
1633 }).then(function(data
) {
1635 var protoConstructorSource
= (
1636 '(function(L, $) { ' +
1640 ).format(data
, url
);
1642 var protoClass
= eval(protoConstructorSource
);
1644 self
._protos
[proto
] = new protoClass();
1647 alert('Unable to instantiate proto "%s": %s'.format(url
, e
));
1651 }).fail(function() {
1658 _fetch_protocols: function()
1660 var self
= L
.NetworkModel
;
1662 self
._fetch_protocol('none')
1665 for (var proto
in self
._cache
.protolist
)
1666 deferreds
.push(self
._fetch_protocol(proto
));
1668 return $.when
.apply($, deferreds
);
1671 _fetch_swstate
: L
.rpc
.declare({
1672 object
: 'luci2.network',
1673 method
: 'switch_info',
1674 params
: [ 'switch' ],
1675 expect
: { 'info': { } }
1678 _fetch_swstate_cb: function(responses
) {
1679 var self
= L
.NetworkModel
;
1680 var swlist
= self
._cache
.swlist
;
1681 var swstate
= self
._cache
.swstate
= { };
1683 for (var i
= 0; i
< responses
.length
; i
++)
1684 swstate
[swlist
[i
]] = responses
[i
];
1687 _fetch_cache_cb: function(level
)
1689 var self
= L
.NetworkModel
;
1690 var name
= '_fetch_cache_cb_' + level
;
1692 return self
[name
] || (
1693 self
[name
] = function(responses
)
1695 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1696 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1697 self
._cache
[self
._cache_functions
[i
]] = responses
.shift();
1703 for (var i
= 0; i
< self
._cache
.swlist
.length
; i
++)
1704 self
._fetch_swstate(self
._cache
.swlist
[i
]);
1706 return L
.rpc
.flush().then(self
._fetch_swstate_cb
);
1709 return L
.deferrable();
1714 _fetch_cache: function(level
)
1716 var self
= L
.NetworkModel
;
1718 return L
.uci
.load(['network', 'wireless']).then(function() {
1721 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1722 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1723 self
._cache_functions
[i
+ 2]();
1725 return L
.rpc
.flush().then(self
._fetch_cache_cb(level
|| 0));
1729 _get: function(pkg
, sid
, key
)
1731 return L
.uci
.get(pkg
, sid
, key
);
1734 _set: function(pkg
, sid
, key
, val
)
1736 return L
.uci
.set(pkg
, sid
, key
, val
);
1739 _is_blacklisted: function(dev
)
1741 for (var i
= 0; i
< this._device_blacklist
.length
; i
++)
1742 if (dev
.match(this._device_blacklist
[i
]))
1748 _sort_devices: function(a
, b
)
1750 if (a
.options
.kind
< b
.options
.kind
)
1752 else if (a
.options
.kind
> b
.options
.kind
)
1755 if (a
.options
.name
< b
.options
.name
)
1757 else if (a
.options
.name
> b
.options
.name
)
1763 _get_dev: function(ifname
)
1765 var alias
= (ifname
.charAt(0) == '@');
1766 return this._devs
[ifname
] || (
1767 this._devs
[ifname
] = {
1769 kind
: alias
? 'alias' : 'ethernet',
1770 type
: alias
? 0 : 1,
1777 _get_iface: function(name
)
1779 return this._ifaces
[name
] || (
1780 this._ifaces
[name
] = {
1782 proto
: this._protos
.none
,
1788 _parse_devices: function()
1790 var self
= L
.NetworkModel
;
1791 var wificount
= { };
1793 for (var ifname
in self
._cache
.devstate
)
1795 if (self
._is_blacklisted(ifname
))
1798 var dev
= self
._cache
.devstate
[ifname
];
1799 var entry
= self
._get_dev(ifname
);
1806 entry
.kind
= 'tunnel';
1810 entry
.kind
= 'bridge';
1811 //entry.ports = dev['bridge-members'].sort();
1816 for (var i
= 0; i
< self
._cache
.devlist
.length
; i
++)
1818 var dev
= self
._cache
.devlist
[i
];
1820 if (self
._is_blacklisted(dev
.device
))
1823 var entry
= self
._get_dev(dev
.device
);
1825 entry
.up
= dev
.is_up
;
1826 entry
.type
= dev
.type
;
1830 case 1: /* Ethernet */
1832 entry
.kind
= 'bridge';
1833 else if (dev
.is_tuntap
)
1834 entry
.kind
= 'tunnel';
1835 else if (dev
.is_wireless
)
1836 entry
.kind
= 'wifi';
1840 case 768: /* IP-IP Tunnel */
1841 case 769: /* IP6-IP6 Tunnel */
1842 case 776: /* IPv6-in-IPv4 */
1843 case 778: /* GRE over IP */
1844 entry
.kind
= 'tunnel';
1849 var net
= L
.uci
.sections('network');
1850 for (var i
= 0; i
< net
.length
; i
++)
1853 var sid
= s
['.name'];
1855 if (s
['.type'] == 'device' && s
.name
)
1857 var entry
= self
._get_dev(s
.name
);
1863 entry
.kind
= 'tunnel';
1869 else if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.ifname
)
1871 var ifnames
= L
.toArray(s
.ifname
);
1873 for (var j
= 0; j
< ifnames
.length
; j
++)
1874 self
._get_dev(ifnames
[j
]);
1876 if (s
['.name'] != 'loopback')
1878 var entry
= self
._get_dev('@%s'.format(s
['.name']));
1881 entry
.kind
= 'alias';
1885 else if (s
['.type'] == 'switch_vlan' && s
.device
)
1887 var sw
= self
._cache
.swstate
[s
.device
];
1888 var vid
= parseInt(s
.vid
|| s
.vlan
);
1889 var ports
= L
.toArray(s
.ports
);
1891 if (!sw
|| !ports
.length
|| isNaN(vid
))
1894 var ifname
= undefined;
1896 for (var j
= 0; j
< ports
.length
; j
++)
1898 var port
= parseInt(ports
[j
]);
1899 var tag
= (ports
[j
].replace(/[^tu]/g, '') == 't');
1901 if (port
== sw
.cpu_port
)
1903 // XXX: need a way to map switch to netdev
1905 ifname
= 'eth0.%d'.format(vid
);
1916 var entry
= self
._get_dev(ifname
);
1918 entry
.kind
= 'vlan';
1925 var wifi
= L
.uci
.sections('wireless');
1926 for (var i
= 0; i
< wifi
.length
; i
++)
1929 var sid
= s
['.name'];
1931 if (s
['.type'] == 'wifi-iface' && s
.device
)
1933 var r
= parseInt(s
.device
.replace(/^[^0-9]+/, ''));
1934 var n
= wificount
[s
.device
] = (wificount
[s
.device
] || 0) + 1;
1935 var id
= 'radio%d.network%d'.format(r
, n
);
1938 if (self
._cache
.wifistate
[s
.device
])
1940 var ifcs
= self
._cache
.wifistate
[s
.device
].interfaces
;
1941 for (var ifc
in ifcs
)
1943 if (ifcs
[ifc
].section
== sid
)
1945 ifname
= ifcs
[ifc
].ifname
;
1951 var entry
= self
._get_dev(ifname
);
1953 entry
.kind
= 'wifi';
1956 entry
.wdev
= s
.device
;
1957 entry
.wmode
= s
.mode
;
1958 entry
.wssid
= s
.ssid
;
1959 entry
.wbssid
= s
.bssid
;
1963 for (var i
= 0; i
< net
.length
; i
++)
1966 var sid
= s
['.name'];
1968 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.type
== 'bridge')
1970 var ifnames
= L
.toArray(s
.ifname
);
1972 for (var ifname
in self
._devs
)
1974 var dev
= self
._devs
[ifname
];
1976 if (dev
.kind
!= 'wifi')
1979 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1980 if ($.inArray(sid
, wnets
) > -1)
1981 ifnames
.push(ifname
);
1984 entry
= self
._get_dev('br-%s'.format(s
['.name']));
1986 entry
.kind
= 'bridge';
1988 entry
.ports
= ifnames
.sort();
1993 _parse_interfaces: function()
1995 var self
= L
.NetworkModel
;
1996 var net
= L
.uci
.sections('network');
1998 for (var i
= 0; i
< net
.length
; i
++)
2001 var sid
= s
['.name'];
2003 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.proto
)
2005 var entry
= self
._get_iface(s
['.name']);
2006 var proto
= self
._protos
[s
.proto
] || self
._protos
.none
;
2008 var l3dev
= undefined;
2009 var l2dev
= undefined;
2011 var ifnames
= L
.toArray(s
.ifname
);
2013 for (var ifname
in self
._devs
)
2015 var dev
= self
._devs
[ifname
];
2017 if (dev
.kind
!= 'wifi')
2020 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
2021 if ($.inArray(entry
.name
, wnets
) > -1)
2022 ifnames
.push(ifname
);
2026 l3dev
= '%s-%s'.format(s
.proto
, entry
.name
);
2027 else if (s
.type
== 'bridge')
2028 l3dev
= 'br-%s'.format(entry
.name
);
2032 if (!proto
.virtual
&& s
.type
== 'bridge')
2033 l2dev
= 'br-%s'.format(entry
.name
);
2034 else if (!proto
.virtual
)
2037 entry
.proto
= proto
;
2039 entry
.l3dev
= l3dev
;
2040 entry
.l2dev
= l2dev
;
2044 for (var i
= 0; i
< self
._cache
.ifstate
.length
; i
++)
2046 var iface
= self
._cache
.ifstate
[i
];
2047 var entry
= self
._get_iface(iface
['interface']);
2048 var proto
= self
._protos
[iface
.proto
] || self
._protos
.none
;
2050 /* this is a virtual interface, either deleted from config but
2051 not applied yet or set up from external tools (6rd) */
2054 entry
.proto
= proto
;
2055 entry
.l2dev
= iface
.device
;
2056 entry
.l3dev
= iface
.l3_device
;
2066 return L
.deferrable();
2073 return self
._fetch_cache()
2074 .then(self
._fetch_protocols
)
2075 .then(self
._parse_devices
)
2076 .then(self
._parse_interfaces
);
2085 refreshInterfaceStatus: function()
2087 return this._fetch_cache(1).then(this._parse_interfaces
);
2090 refreshDeviceStatus: function()
2092 return this._fetch_cache(2).then(this._parse_devices
);
2095 refreshStatus: function()
2097 return this._fetch_cache(1)
2098 .then(this._fetch_cache(2))
2099 .then(this._parse_devices
)
2100 .then(this._parse_interfaces
);
2103 getDevices: function()
2107 for (var ifname
in this._devs
)
2109 devs
.push(new L
.NetworkModel
.Device(this._devs
[ifname
]));
2111 return devs
.sort(this._sort_devices
);
2114 getDeviceByInterface: function(iface
)
2116 if (iface
instanceof L
.NetworkModel
.Interface
)
2117 iface
= iface
.name();
2119 if (this._ifaces
[iface
])
2120 return this.getDevice(this._ifaces
[iface
].l3dev
) ||
2121 this.getDevice(this._ifaces
[iface
].l2dev
);
2126 getDevice: function(ifname
)
2128 if (this._devs
[ifname
])
2129 return new L
.NetworkModel
.Device(this._devs
[ifname
]);
2134 createDevice: function(name
)
2136 return new L
.NetworkModel
.Device(this._get_dev(name
));
2139 getInterfaces: function()
2143 for (var name
in this._ifaces
)
2144 if (name
!= 'loopback')
2145 ifaces
.push(this.getInterface(name
));
2147 ifaces
.sort(function(a
, b
) {
2148 if (a
.name() < b
.name())
2150 else if (a
.name() > b
.name())
2159 getInterfacesByDevice: function(dev
)
2163 if (dev
instanceof L
.NetworkModel
.Device
)
2166 for (var name
in this._ifaces
)
2168 var iface
= this._ifaces
[name
];
2169 if (iface
.l2dev
== dev
|| iface
.l3dev
== dev
)
2170 ifaces
.push(this.getInterface(name
));
2173 ifaces
.sort(function(a
, b
) {
2174 if (a
.name() < b
.name())
2176 else if (a
.name() > b
.name())
2185 getInterface: function(iface
)
2187 if (this._ifaces
[iface
])
2188 return new L
.NetworkModel
.Interface(this._ifaces
[iface
]);
2193 getProtocols: function()
2197 for (var proto
in this._protos
)
2199 var pr
= this._protos
[proto
];
2203 description
: pr
.description
,
2204 virtual
: pr
.virtual
,
2209 return rv
.sort(function(a
, b
) {
2210 if (a
.name
< b
.name
)
2212 else if (a
.name
> b
.name
)
2219 _find_wan: function(ipaddr
)
2221 for (var i
= 0; i
< this._cache
.ifstate
.length
; i
++)
2223 var ifstate
= this._cache
.ifstate
[i
];
2228 for (var j
= 0; j
< ifstate
.route
.length
; j
++)
2229 if (ifstate
.route
[j
].mask
== 0 &&
2230 ifstate
.route
[j
].target
== ipaddr
&&
2231 typeof(ifstate
.route
[j
].table
) == 'undefined')
2233 return this.getInterface(ifstate
['interface']);
2242 return this._find_wan('0.0.0.0');
2245 findWAN6: function()
2247 return this._find_wan('::');
2250 resolveAlias: function(ifname
)
2252 if (ifname
instanceof L
.NetworkModel
.Device
)
2253 ifname
= ifname
.name();
2255 var dev
= this._devs
[ifname
];
2258 while (dev
&& dev
.kind
== 'alias')
2261 if (seen
[dev
.ifname
])
2264 var ifc
= this._ifaces
[dev
.sid
];
2266 seen
[dev
.ifname
] = true;
2267 dev
= ifc
? this._devs
[ifc
.l3dev
] : undefined;
2270 return dev
? this.getDevice(dev
.ifname
) : undefined;
2274 this.NetworkModel
.Device
= Class
.extend({
2277 sta
: L
.tr('Client'),
2278 adhoc
: L
.tr('Ad-Hoc'),
2279 monitor
: L
.tr('Monitor'),
2280 wds
: L
.tr('Static WDS')
2283 _status: function(key
)
2285 var s
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2288 return key
? s
[key
] : s
;
2295 var sid
= this.options
.sid
;
2296 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2297 return L
.NetworkModel
._get(pkg
, sid
, key
);
2300 set: function(key
, val
)
2302 var sid
= this.options
.sid
;
2303 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2304 return L
.NetworkModel
._set(pkg
, sid
, key
, val
);
2309 if (typeof(this.options
.type
) == 'undefined')
2310 this.options
.type
= 1;
2312 if (typeof(this.options
.kind
) == 'undefined')
2313 this.options
.kind
= 'ethernet';
2315 if (typeof(this.options
.networks
) == 'undefined')
2316 this.options
.networks
= [ ];
2321 return this.options
.ifname
;
2324 description: function()
2326 switch (this.options
.kind
)
2329 return L
.tr('Alias for network "%s"').format(this.options
.ifname
.substring(1));
2332 return L
.tr('Network bridge');
2335 return L
.tr('Network device');
2338 switch (this.options
.type
)
2340 case 1: /* tuntap */
2341 return L
.tr('TAP device');
2344 return L
.tr('PPP tunnel');
2346 case 768: /* IP-IP Tunnel */
2347 return L
.tr('IP-in-IP tunnel');
2349 case 769: /* IP6-IP6 Tunnel */
2350 return L
.tr('IPv6-in-IPv6 tunnel');
2352 case 776: /* IPv6-in-IPv4 */
2353 return L
.tr('IPv6-over-IPv4 tunnel');
2356 case 778: /* GRE over IP */
2357 return L
.tr('GRE-over-IP tunnel');
2360 return L
.tr('Tunnel device');
2364 return L
.tr('VLAN %d on %s').format(this.options
.vid
, this.options
.vsw
.model
);
2367 var o
= this.options
;
2368 return L
.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2369 o
.wmode
? this._wifi_modes
[o
.wmode
] : L
.tr('Unknown mode'),
2370 o
.wssid
|| '?', o
.wdev
2374 return L
.tr('Unknown device');
2379 var kind
= this.options
.kind
;
2381 if (kind
== 'alias')
2384 if (typeof(up
) == 'undefined')
2387 return L
.globals
.resource
+ '/icons/%s%s.png'.format(kind
, up
? '' : '_disabled');
2392 var l
= L
.NetworkModel
._cache
.devlist
;
2394 for (var i
= 0; i
< l
.length
; i
++)
2395 if (l
[i
].device
== this.options
.ifname
)
2396 return (l
[i
].is_up
=== true);
2403 return (this.options
.kind
== 'alias');
2406 isBridge: function()
2408 return (this.options
.kind
== 'bridge');
2411 isBridgeable: function()
2413 return (this.options
.type
== 1 && this.options
.kind
!= 'bridge');
2416 isWireless: function()
2418 return (this.options
.kind
== 'wifi');
2421 isInNetwork: function(net
)
2423 if (!(net
instanceof L
.NetworkModel
.Interface
))
2424 net
= L
.NetworkModel
.getInterface(net
);
2428 if (net
.options
.l3dev
== this.options
.ifname
||
2429 net
.options
.l2dev
== this.options
.ifname
)
2432 var dev
= L
.NetworkModel
._devs
[net
.options
.l2dev
];
2433 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
)
2434 return ($.inArray(this.options
.ifname
, dev
.ports
) > -1);
2442 var dev
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2443 if (dev
&& !isNaN(dev
.mtu
))
2449 getMACAddress: function()
2451 if (this.options
.type
!= 1)
2454 var dev
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2455 if (dev
&& dev
.macaddr
)
2456 return dev
.macaddr
.toUpperCase();
2461 getInterfaces: function()
2463 return L
.NetworkModel
.getInterfacesByDevice(this.options
.name
);
2466 getStatistics: function()
2468 var s
= this._status('statistics') || { };
2470 rx_bytes
: (s
.rx_bytes
|| 0),
2471 tx_bytes
: (s
.tx_bytes
|| 0),
2472 rx_packets
: (s
.rx_packets
|| 0),
2473 tx_packets
: (s
.tx_packets
|| 0)
2477 getTrafficHistory: function()
2479 var def
= new Array(120);
2481 for (var i
= 0; i
< 120; i
++)
2484 var h
= L
.NetworkModel
._cache
.bwstate
[this.options
.ifname
] || { };
2486 rx_bytes
: (h
.rx_bytes
|| def
),
2487 tx_bytes
: (h
.tx_bytes
|| def
),
2488 rx_packets
: (h
.rx_packets
|| def
),
2489 tx_packets
: (h
.tx_packets
|| def
)
2493 removeFromInterface: function(iface
)
2495 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2496 iface
= L
.NetworkModel
.getInterface(iface
);
2501 var ifnames
= L
.toArray(iface
.get('ifname'));
2502 if ($.inArray(this.options
.ifname
, ifnames
) > -1)
2503 iface
.set('ifname', L
.filterArray(ifnames
, this.options
.ifname
));
2505 if (this.options
.kind
!= 'wifi')
2508 var networks
= L
.toArray(this.get('network'));
2509 if ($.inArray(iface
.name(), networks
) > -1)
2510 this.set('network', L
.filterArray(networks
, iface
.name()));
2513 attachToInterface: function(iface
)
2515 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2516 iface
= L
.NetworkModel
.getInterface(iface
);
2521 if (this.options
.kind
!= 'wifi')
2523 var ifnames
= L
.toArray(iface
.get('ifname'));
2524 if ($.inArray(this.options
.ifname
, ifnames
) < 0)
2526 ifnames
.push(this.options
.ifname
);
2527 iface
.set('ifname', (ifnames
.length
> 1) ? ifnames
: ifnames
[0]);
2532 var networks
= L
.toArray(this.get('network'));
2533 if ($.inArray(iface
.name(), networks
) < 0)
2535 networks
.push(iface
.name());
2536 this.set('network', (networks
.length
> 1) ? networks
: networks
[0]);
2542 this.NetworkModel
.Interface
= Class
.extend({
2543 _status: function(key
)
2545 var s
= L
.NetworkModel
._cache
.ifstate
;
2547 for (var i
= 0; i
< s
.length
; i
++)
2548 if (s
[i
]['interface'] == this.options
.name
)
2549 return key
? s
[i
][key
] : s
[i
];
2556 return L
.NetworkModel
._get('network', this.options
.name
, key
);
2559 set: function(key
, val
)
2561 return L
.NetworkModel
._set('network', this.options
.name
, key
, val
);
2566 return this.options
.name
;
2569 protocol: function()
2571 return (this.get('proto') || 'none');
2576 return (this._status('up') === true);
2579 isVirtual: function()
2581 return (typeof(this.options
.sid
) != 'string');
2584 getProtocol: function()
2586 var prname
= this.get('proto') || 'none';
2587 return L
.NetworkModel
._protos
[prname
] || L
.NetworkModel
._protos
.none
;
2590 getUptime: function()
2592 var uptime
= this._status('uptime');
2593 return isNaN(uptime
) ? 0 : uptime
;
2596 getDevice: function(resolveAlias
)
2598 if (this.options
.l3dev
)
2599 return L
.NetworkModel
.getDevice(this.options
.l3dev
);
2604 getPhysdev: function()
2606 if (this.options
.l2dev
)
2607 return L
.NetworkModel
.getDevice(this.options
.l2dev
);
2612 getSubdevices: function()
2615 var dev
= this.options
.l2dev
?
2616 L
.NetworkModel
._devs
[this.options
.l2dev
] : undefined;
2618 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
&& dev
.ports
.length
)
2619 for (var i
= 0; i
< dev
.ports
.length
; i
++)
2620 rv
.push(L
.NetworkModel
.getDevice(dev
.ports
[i
]));
2625 getIPv4Addrs: function(mask
)
2628 var addrs
= this._status('ipv4-address');
2631 for (var i
= 0; i
< addrs
.length
; i
++)
2633 rv
.push(addrs
[i
].address
);
2635 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2640 getIPv6Addrs: function(mask
)
2645 addrs
= this._status('ipv6-address');
2648 for (var i
= 0; i
< addrs
.length
; i
++)
2650 rv
.push(addrs
[i
].address
);
2652 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2654 addrs
= this._status('ipv6-prefix-assignment');
2657 for (var i
= 0; i
< addrs
.length
; i
++)
2659 rv
.push('%s1'.format(addrs
[i
].address
));
2661 rv
.push('%s1/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2666 getDNSAddrs: function()
2669 var addrs
= this._status('dns-server');
2672 for (var i
= 0; i
< addrs
.length
; i
++)
2678 getIPv4DNS: function()
2681 var dns
= this._status('dns-server');
2684 for (var i
= 0; i
< dns
.length
; i
++)
2685 if (dns
[i
].indexOf(':') == -1)
2691 getIPv6DNS: function()
2694 var dns
= this._status('dns-server');
2697 for (var i
= 0; i
< dns
.length
; i
++)
2698 if (dns
[i
].indexOf(':') > -1)
2704 getIPv4Gateway: function()
2706 var rt
= this._status('route');
2709 for (var i
= 0; i
< rt
.length
; i
++)
2710 if (rt
[i
].target
== '0.0.0.0' && rt
[i
].mask
== 0)
2711 return rt
[i
].nexthop
;
2716 getIPv6Gateway: function()
2718 var rt
= this._status('route');
2721 for (var i
= 0; i
< rt
.length
; i
++)
2722 if (rt
[i
].target
== '::' && rt
[i
].mask
== 0)
2723 return rt
[i
].nexthop
;
2728 getStatistics: function()
2730 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2731 return dev
.getStatistics();
2734 getTrafficHistory: function()
2736 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2737 return dev
.getTrafficHistory();
2740 renderBadge: function()
2742 var badge
= $('<span />')
2744 .text('%s: '.format(this.name()));
2746 var dev
= this.getDevice();
2747 var subdevs
= this.getSubdevices();
2750 for (var j
= 0; j
< subdevs
.length
; j
++)
2751 badge
.append($('<img />')
2752 .attr('src', subdevs
[j
].icon())
2753 .attr('title', '%s (%s)'.format(subdevs
[j
].description(), subdevs
[j
].name() || '?')));
2755 badge
.append($('<img />')
2756 .attr('src', dev
.icon())
2757 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?')));
2759 badge
.append($('<em />').text(L
.tr('(No devices attached)')));
2764 setDevices: function(devs
)
2766 var dev
= this.getPhysdev();
2768 var changed
= false;
2770 if (dev
&& dev
.isBridge())
2771 old_devs
= this.getSubdevices();
2775 if (old_devs
.length
!= devs
.length
)
2778 for (var i
= 0; i
< old_devs
.length
; i
++)
2782 if (dev
instanceof L
.NetworkModel
.Device
)
2785 if (!dev
|| old_devs
[i
].name() != dev
)
2794 for (var i
= 0; i
< old_devs
.length
; i
++)
2795 old_devs
[i
].removeFromInterface(this);
2797 for (var i
= 0; i
< devs
.length
; i
++)
2801 if (!(dev
instanceof L
.NetworkModel
.Device
))
2802 dev
= L
.NetworkModel
.getDevice(dev
);
2805 dev
.attachToInterface(this);
2810 changeProtocol: function(proto
)
2812 var pr
= L
.NetworkModel
._protos
[proto
];
2817 for (var opt
in (this.get() || { }))
2825 this.set(opt
, undefined);
2833 this.set(opt
, pr
.protocol
);
2837 this.set(opt
, undefined);
2843 createForm: function(mapwidget
)
2846 var proto
= self
.getProtocol();
2847 var device
= self
.getDevice();
2850 mapwidget
= L
.cbi
.Map
;
2852 var map
= new mapwidget('network', {
2853 caption
: L
.tr('Configure "%s"').format(self
.name())
2856 var section
= map
.section(L
.cbi
.SingleSection
, self
.name(), {
2862 caption
: L
.tr('General Settings')
2867 caption
: L
.tr('Advanced Settings')
2872 caption
: L
.tr('IPv6')
2877 caption
: L
.tr('Physical Settings')
2881 section
.taboption('general', L
.cbi
.CheckboxValue
, 'auto', {
2882 caption
: L
.tr('Start on boot'),
2887 var pr
= section
.taboption('general', L
.cbi
.ListValue
, 'proto', {
2888 caption
: L
.tr('Protocol')
2891 pr
.ucivalue = function(sid
) {
2892 return self
.get('proto') || 'none';
2895 var ok
= section
.taboption('general', L
.cbi
.ButtonValue
, '_confirm', {
2896 caption
: L
.tr('Really switch?'),
2897 description
: L
.tr('Changing the protocol will clear all configuration for this interface!'),
2898 text
: L
.tr('Change protocol')
2901 ok
.on('click', function(ev
) {
2902 self
.changeProtocol(pr
.formvalue(ev
.data
.sid
));
2903 self
.createForm(mapwidget
).show();
2906 var protos
= L
.NetworkModel
.getProtocols();
2908 for (var i
= 0; i
< protos
.length
; i
++)
2909 pr
.value(protos
[i
].name
, protos
[i
].description
);
2911 proto
.populateForm(section
, self
);
2915 var br
= section
.taboption('physical', L
.cbi
.CheckboxValue
, 'type', {
2916 caption
: L
.tr('Network bridge'),
2917 description
: L
.tr('Merges multiple devices into one logical bridge'),
2924 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_multi', {
2925 caption
: L
.tr('Devices'),
2928 }).depends('type', true);
2930 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_single', {
2931 caption
: L
.tr('Device'),
2934 }).depends('type', false);
2936 var mac
= section
.taboption('physical', L
.cbi
.InputValue
, 'macaddr', {
2937 caption
: L
.tr('Override MAC'),
2939 placeholder
: device
? device
.getMACAddress() : undefined,
2943 mac
.ucivalue = function(sid
)
2946 return device
.get('macaddr');
2948 return this.callSuper('ucivalue', sid
);
2951 mac
.save = function(sid
)
2953 if (!this.changed(sid
))
2957 device
.set('macaddr', this.formvalue(sid
));
2959 this.callSuper('set', sid
);
2965 section
.taboption('physical', L
.cbi
.InputValue
, 'mtu', {
2966 caption
: L
.tr('Override MTU'),
2968 placeholder
: device
? device
.getMTU() : undefined,
2969 datatype
: 'range(1, 9000)'
2972 section
.taboption('physical', L
.cbi
.InputValue
, 'metric', {
2973 caption
: L
.tr('Override Metric'),
2976 datatype
: 'uinteger'
2979 for (var field
in section
.fields
)
2987 for (var i
= 0; i
< protos
.length
; i
++)
2988 if (protos
[i
].name
!= (this.get('proto') || 'none'))
2989 section
.fields
[field
].depends('proto', protos
[i
].name
);
2993 section
.fields
[field
].depends('proto', this.get('proto') || 'none', true);
3002 this.NetworkModel
.Protocol
= this.NetworkModel
.Interface
.extend({
3003 description
: '__unknown__',
3007 populateForm: function(section
, iface
)
3014 getSystemInfo
: L
.rpc
.declare({
3020 getBoardInfo
: L
.rpc
.declare({
3026 getDiskInfo
: L
.rpc
.declare({
3027 object
: 'luci2.system',
3032 getInfo: function(cb
)
3036 this.getSystemInfo();
3037 this.getBoardInfo();
3040 return L
.rpc
.flush().then(function(info
) {
3043 $.extend(rv
, info
[0]);
3044 $.extend(rv
, info
[1]);
3045 $.extend(rv
, info
[2]);
3052 initList
: L
.rpc
.declare({
3053 object
: 'luci2.system',
3054 method
: 'init_list',
3055 expect
: { initscripts
: [ ] },
3056 filter: function(data
) {
3057 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
3062 initEnabled: function(init
, cb
)
3064 return this.initList().then(function(list
) {
3065 for (var i
= 0; i
< list
.length
; i
++)
3066 if (list
[i
].name
== init
)
3067 return !!list
[i
].enabled
;
3073 initRun
: L
.rpc
.declare({
3074 object
: 'luci2.system',
3075 method
: 'init_action',
3076 params
: [ 'name', 'action' ],
3077 filter: function(data
) {
3082 initStart: function(init
, cb
) { return L
.system
.initRun(init
, 'start', cb
) },
3083 initStop: function(init
, cb
) { return L
.system
.initRun(init
, 'stop', cb
) },
3084 initRestart: function(init
, cb
) { return L
.system
.initRun(init
, 'restart', cb
) },
3085 initReload: function(init
, cb
) { return L
.system
.initRun(init
, 'reload', cb
) },
3086 initEnable: function(init
, cb
) { return L
.system
.initRun(init
, 'enable', cb
) },
3087 initDisable: function(init
, cb
) { return L
.system
.initRun(init
, 'disable', cb
) },
3090 performReboot
: L
.rpc
.declare({
3091 object
: 'luci2.system',
3098 login
: L
.rpc
.declare({
3101 params
: [ 'username', 'password' ],
3105 access
: L
.rpc
.declare({
3108 params
: [ 'scope', 'object', 'function' ],
3109 expect
: { access
: false }
3114 return L
.session
.access('ubus', 'session', 'access');
3117 startHeartbeat: function()
3119 this._hearbeatInterval
= window
.setInterval(function() {
3120 L
.session
.isAlive().then(function(alive
) {
3123 L
.session
.stopHeartbeat();
3128 }, L
.globals
.timeout
* 2);
3131 stopHeartbeat: function()
3133 if (typeof(this._hearbeatInterval
) != 'undefined')
3135 window
.clearInterval(this._hearbeatInterval
);
3136 delete this._hearbeatInterval
;
3143 _fetch_acls
: L
.rpc
.declare({
3149 _fetch_acls_cb: function(acls
)
3151 L
.session
._acls
= acls
;
3154 updateACLs: function()
3156 return L
.session
._fetch_acls()
3157 .then(L
.session
._fetch_acls_cb
);
3160 hasACL: function(scope
, object
, func
)
3162 var acls
= L
.session
._acls
;
3164 if (typeof(func
) == 'undefined')
3165 return (acls
&& acls
[scope
] && acls
[scope
][object
]);
3167 if (acls
&& acls
[scope
] && acls
[scope
][object
])
3168 for (var i
= 0; i
< acls
[scope
][object
].length
; i
++)
3169 if (acls
[scope
][object
][i
] == func
)
3178 saveScrollTop: function()
3180 this._scroll_top
= $(document
).scrollTop();
3183 restoreScrollTop: function()
3185 if (typeof(this._scroll_top
) == 'undefined')
3188 $(document
).scrollTop(this._scroll_top
);
3190 delete this._scroll_top
;
3193 loading: function(enable
)
3195 var win
= $(window
);
3196 var body
= $('body');
3198 var state
= L
.ui
._loading
|| (L
.ui
._loading
= {
3200 .css('z-index', 2000)
3201 .addClass('modal fade')
3202 .append($('<div />')
3203 .addClass('modal-dialog')
3204 .append($('<div />')
3205 .addClass('modal-content luci2-modal-loader')
3206 .append($('<div />')
3207 .addClass('modal-body')
3208 .text(L
.tr('Loading data…')))))
3216 state
.modal
.modal(enable
? 'show' : 'hide');
3219 dialog: function(title
, content
, options
)
3221 var win
= $(window
);
3222 var body
= $('body');
3224 var state
= L
.ui
._dialog
|| (L
.ui
._dialog
= {
3225 dialog
: $('<div />')
3226 .addClass('modal fade')
3227 .append($('<div />')
3228 .addClass('modal-dialog')
3229 .append($('<div />')
3230 .addClass('modal-content')
3231 .append($('<div />')
3232 .addClass('modal-header')
3234 .addClass('modal-title'))
3235 .append($('<div />')
3236 .addClass('modal-body'))
3237 .append($('<div />')
3238 .addClass('modal-footer')
3239 .append(L
.ui
.button(L
.tr('Close'), 'primary')
3241 $(this).parents('div.modal').modal('hide');
3246 if (typeof(options
) != 'object')
3249 if (title
=== false)
3251 state
.dialog
.modal('hide');
3253 return state
.dialog
;
3256 var cnt
= state
.dialog
.children().children().children('div.modal-body');
3257 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
3261 if (options
.style
== 'confirm')
3263 ftr
.append(L
.ui
.button(L
.tr('Ok'), 'primary')
3264 .click(options
.confirm
|| function() { L
.ui
.dialog(false) }));
3266 ftr
.append(L
.ui
.button(L
.tr('Cancel'), 'default')
3267 .click(options
.cancel
|| function() { L
.ui
.dialog(false) }));
3269 else if (options
.style
== 'close')
3271 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3272 .click(options
.close
|| function() { L
.ui
.dialog(false) }));
3274 else if (options
.style
== 'wait')
3276 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3277 .attr('disabled', true));
3282 state
.dialog
.addClass('wide');
3286 state
.dialog
.removeClass('wide');
3289 state
.dialog
.find('h4:first').text(title
);
3290 state
.dialog
.modal('show');
3292 cnt
.empty().append(content
);
3294 return state
.dialog
;
3297 upload: function(title
, content
, options
)
3299 var state
= L
.ui
._upload
|| (L
.ui
._upload
= {
3301 .attr('method', 'post')
3302 .attr('action', '/cgi-bin/luci-upload')
3303 .attr('enctype', 'multipart/form-data')
3304 .attr('target', 'cbi-fileupload-frame')
3306 .append($('<input />')
3307 .attr('type', 'hidden')
3308 .attr('name', 'sessionid'))
3309 .append($('<input />')
3310 .attr('type', 'hidden')
3311 .attr('name', 'filename'))
3312 .append($('<input />')
3313 .attr('type', 'file')
3314 .attr('name', 'filedata')
3315 .addClass('cbi-input-file'))
3316 .append($('<div />')
3317 .css('width', '100%')
3318 .addClass('progress progress-striped active')
3319 .append($('<div />')
3320 .addClass('progress-bar')
3321 .css('width', '100%')))
3322 .append($('<iframe />')
3323 .addClass('pull-right')
3324 .attr('name', 'cbi-fileupload-frame')
3325 .css('width', '1px')
3326 .css('height', '1px')
3327 .css('visibility', 'hidden')),
3329 finish_cb: function(ev
) {
3330 $(this).off('load');
3332 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
3333 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
3334 body
= body
.firstChild
;
3338 json
= $.parseJSON(body
.innerHTML
);
3341 message
: L
.tr('Invalid server response received'),
3342 error
: [ -1, L
.tr('Invalid data') ]
3348 L
.ui
.dialog(L
.tr('File upload'), [
3349 $('<p />').text(L
.tr('The file upload failed with the server response below:')),
3350 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
3351 $('<p />').text(L
.tr('In case of network problems try uploading the file again.'))
3352 ], { style
: 'close' });
3354 else if (typeof(state
.success_cb
) == 'function')
3356 state
.success_cb(json
);
3360 confirm_cb: function() {
3361 var f
= state
.form
.find('.cbi-input-file');
3362 var b
= state
.form
.find('.progress');
3363 var p
= state
.form
.find('p');
3368 state
.form
.find('iframe').on('load', state
.finish_cb
);
3369 state
.form
.submit();
3373 p
.text(L
.tr('File upload in progress …'));
3375 state
.form
.parent().parent().find('button').prop('disabled', true);
3379 state
.form
.find('.progress').hide();
3380 state
.form
.find('.cbi-input-file').val('').show();
3381 state
.form
.find('p').text(content
|| L
.tr('Select the file to upload and press "%s" to proceed.').format(L
.tr('Ok')));
3383 state
.form
.find('[name=sessionid]').val(L
.globals
.sid
);
3384 state
.form
.find('[name=filename]').val(options
.filename
);
3386 state
.success_cb
= options
.success
;
3388 L
.ui
.dialog(title
|| L
.tr('File upload'), state
.form
, {
3390 confirm
: state
.confirm_cb
3394 reconnect: function()
3396 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3397 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
3398 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
3400 var interval
, timeout
;
3403 L
.tr('Waiting for device'), [
3404 $('<p />').text(L
.tr('Please stand by while the device is reconfiguring …')),
3406 .css('width', '100%')
3407 .addClass('progressbar')
3408 .addClass('intermediate')
3409 .append($('<div />')
3410 .css('width', '100%'))
3411 ], { style
: 'wait' }
3414 for (var i
= 0; i
< protocols
.length
; i
++)
3415 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
3417 //L.network.getNetworkStatus(function(s) {
3418 // for (var i = 0; i < protocols.length; i++)
3420 // for (var j = 0; j < s.length; j++)
3422 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3423 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3425 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3426 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3429 //}).then(function() {
3430 images
.on('load', function() {
3431 var url
= this.getAttribute('url');
3432 L
.session
.isAlive().then(function(access
) {
3435 window
.clearTimeout(timeout
);
3436 window
.clearInterval(interval
);
3442 location
.href
= url
;
3447 interval
= window
.setInterval(function() {
3448 images
.each(function() {
3449 this.setAttribute('src', this.getAttribute('url') + L
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
3453 timeout
= window
.setTimeout(function() {
3454 window
.clearInterval(interval
);
3458 L
.tr('Device not responding'),
3459 L
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3466 login: function(invalid
)
3468 var state
= L
.ui
._login
|| (L
.ui
._login
= {
3471 .attr('method', 'post')
3473 .addClass('alert-message')
3474 .text(L
.tr('Wrong username or password given!')))
3476 .append($('<label />')
3477 .text(L
.tr('Username'))
3478 .append($('<br />'))
3479 .append($('<input />')
3480 .attr('type', 'text')
3481 .attr('name', 'username')
3482 .attr('value', 'root')
3483 .addClass('form-control')
3484 .keypress(function(ev
) {
3485 if (ev
.which
== 10 || ev
.which
== 13)
3489 .append($('<label />')
3490 .text(L
.tr('Password'))
3491 .append($('<br />'))
3492 .append($('<input />')
3493 .attr('type', 'password')
3494 .attr('name', 'password')
3495 .addClass('form-control')
3496 .keypress(function(ev
) {
3497 if (ev
.which
== 10 || ev
.which
== 13)
3501 .text(L
.tr('Enter your username and password above, then click "%s" to proceed.').format(L
.tr('Ok')))),
3503 response_cb: function(response
) {
3504 if (!response
.ubus_rpc_session
)
3510 L
.globals
.sid
= response
.ubus_rpc_session
;
3511 L
.setHash('id', L
.globals
.sid
);
3512 L
.session
.startHeartbeat();
3514 state
.deferred
.resolve();
3518 confirm_cb: function() {
3519 var u
= state
.form
.find('[name=username]').val();
3520 var p
= state
.form
.find('[name=password]').val();
3526 L
.tr('Logging in'), [
3527 $('<p />').text(L
.tr('Log in in progress …')),
3529 .css('width', '100%')
3530 .addClass('progressbar')
3531 .addClass('intermediate')
3532 .append($('<div />')
3533 .css('width', '100%'))
3534 ], { style
: 'wait' }
3537 L
.globals
.sid
= '00000000000000000000000000000000';
3538 L
.session
.login(u
, p
).then(state
.response_cb
);
3542 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
3543 state
.deferred
= $.Deferred();
3545 /* try to find sid from hash */
3546 var sid
= L
.getHash('id');
3547 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
3549 L
.globals
.sid
= sid
;
3550 L
.session
.isAlive().then(function(access
) {
3553 L
.session
.startHeartbeat();
3554 state
.deferred
.resolve();
3558 L
.setHash('id', undefined);
3563 return state
.deferred
;
3567 state
.form
.find('.alert-message').show();
3569 state
.form
.find('.alert-message').hide();
3571 L
.ui
.dialog(L
.tr('Authorization Required'), state
.form
, {
3573 confirm
: state
.confirm_cb
3576 state
.form
.find('[name=password]').focus();
3578 return state
.deferred
;
3581 cryptPassword
: L
.rpc
.declare({
3585 expect
: { crypt
: '' }
3589 _acl_merge_scope: function(acl_scope
, scope
)
3591 if ($.isArray(scope
))
3593 for (var i
= 0; i
< scope
.length
; i
++)
3594 acl_scope
[scope
[i
]] = true;
3596 else if ($.isPlainObject(scope
))
3598 for (var object_name
in scope
)
3600 if (!$.isArray(scope
[object_name
]))
3603 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
3605 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
3606 acl_object
[scope
[object_name
][i
]] = true;
3611 _acl_merge_permission: function(acl_perm
, perm
)
3613 if ($.isPlainObject(perm
))
3615 for (var scope_name
in perm
)
3617 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
3618 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
3623 _acl_merge_group: function(acl_group
, group
)
3625 if ($.isPlainObject(group
))
3627 if (!acl_group
.description
)
3628 acl_group
.description
= group
.description
;
3632 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
3633 this._acl_merge_permission(acl_perm
, group
.read
);
3638 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
3639 this._acl_merge_permission(acl_perm
, group
.write
);
3644 _acl_merge_tree: function(acl_tree
, tree
)
3646 if ($.isPlainObject(tree
))
3648 for (var group_name
in tree
)
3650 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
3651 this._acl_merge_group(acl_group
, tree
[group_name
]);
3656 listAvailableACLs
: L
.rpc
.declare({
3659 expect
: { acls
: [ ] },
3660 filter: function(trees
) {
3662 for (var i
= 0; i
< trees
.length
; i
++)
3663 L
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
3668 _render_change_indicator: function()
3671 .addClass('nav navbar-nav navbar-right')
3674 .attr('id', 'changes')
3676 .append($('<span />')
3677 .addClass('label label-info'))));
3680 renderMainMenu
: L
.rpc
.declare({
3683 expect
: { menu
: { } },
3684 filter: function(entries
) {
3685 L
.globals
.mainMenu
= new L
.ui
.menu();
3686 L
.globals
.mainMenu
.entries(entries
);
3690 .append(L
.globals
.mainMenu
.render(0, 1))
3691 .append(L
.ui
._render_change_indicator());
3695 renderViewMenu: function()
3699 .append(L
.globals
.mainMenu
.render(2, 900));
3702 renderView: function()
3704 var node
= arguments
[0];
3705 var name
= node
.view
.split(/\//).join('.');
3706 var cname
= L
.toClassName(name
);
3707 var views
= L
.views
|| (L
.views
= { });
3710 for (var i
= 1; i
< arguments
.length
; i
++)
3711 args
.push(arguments
[i
]);
3713 if (L
.globals
.currentView
)
3714 L
.globals
.currentView
.finish();
3716 L
.ui
.renderViewMenu();
3717 L
.setHash('view', node
.view
);
3719 if (views
[cname
] instanceof L
.ui
.view
)
3721 L
.globals
.currentView
= views
[cname
];
3722 return views
[cname
].render
.apply(views
[cname
], args
);
3725 var url
= L
.globals
.resource
+ '/view/' + name
+ '.js';
3727 return $.ajax(url
, {
3731 }).then(function(data
) {
3733 var viewConstructorSource
= (
3734 '(function(L, $) { ' +
3738 ).format(data
, url
);
3740 var viewConstructor
= eval(viewConstructorSource
);
3742 views
[cname
] = new viewConstructor({
3744 acls
: node
.write
|| { }
3747 L
.globals
.currentView
= views
[cname
];
3748 return views
[cname
].render
.apply(views
[cname
], args
);
3751 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
3754 return $.Deferred().resolve();
3758 changeView: function()
3760 var name
= L
.getHash('view');
3761 var node
= L
.globals
.defaultNode
;
3763 if (name
&& L
.globals
.mainMenu
)
3764 node
= L
.globals
.mainMenu
.getNode(name
);
3769 L
.ui
.renderView(node
).then(function() {
3770 L
.ui
.loading(false);
3775 updateHostname: function()
3777 return L
.system
.getBoardInfo().then(function(info
) {
3779 $('#hostname').text(info
.hostname
);
3783 updateChanges: function()
3785 return L
.uci
.changes().then(function(changes
) {
3789 for (var config
in changes
)
3793 for (var i
= 0; i
< changes
[config
].length
; i
++)
3795 var c
= changes
[config
][i
];
3800 log
.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3805 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
3807 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
3812 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
3814 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3818 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
3822 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3826 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3831 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3833 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3838 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
3839 n
+= changes
[config
].length
;
3844 .click(function(ev
) {
3845 L
.ui
.dialog(L
.tr('Staged configuration changes'), html
, {
3847 confirm: function() {
3849 function(code
) { alert('Success with code ' + code
); },
3850 function(code
) { alert('Error with code ' + code
); }
3854 ev
.preventDefault();
3858 .text(L
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
));
3860 $('#changes').children('span').hide();
3869 L
.session
.updateACLs(),
3870 L
.ui
.updateHostname(),
3871 L
.ui
.updateChanges(),
3872 L
.ui
.renderMainMenu(),
3873 L
.NetworkModel
.init()
3875 L
.ui
.renderView(L
.globals
.defaultNode
).then(function() {
3876 L
.ui
.loading(false);
3879 $(window
).on('hashchange', function() {
3885 button: function(label
, style
, title
)
3887 style
= style
|| 'default';
3889 return $('<button />')
3890 .attr('type', 'button')
3891 .attr('title', title
? title
: '')
3892 .addClass('btn btn-' + style
)
3897 this.ui
.AbstractWidget
= Class
.extend({
3898 i18n: function(text
) {
3903 var key
= arguments
[0];
3906 for (var i
= 1; i
< arguments
.length
; i
++)
3907 args
.push(arguments
[i
]);
3909 switch (typeof(this.options
[key
]))
3915 return this.options
[key
].apply(this, args
);
3918 return ''.format
.apply('' + this.options
[key
], args
);
3922 toString: function() {
3923 return $('<div />').append(this.render()).html();
3926 insertInto: function(id
) {
3927 return $(id
).empty().append(this.render());
3930 appendTo: function(id
) {
3931 return $(id
).append(this.render());
3934 on: function(evname
, evfunc
)
3936 var evnames
= L
.toArray(evname
);
3941 for (var i
= 0; i
< evnames
.length
; i
++)
3942 this.events
[evnames
[i
]] = evfunc
;
3947 trigger: function(evname
, evdata
)
3951 var evnames
= L
.toArray(evname
);
3953 for (var i
= 0; i
< evnames
.length
; i
++)
3954 if (this.events
[evnames
[i
]])
3955 this.events
[evnames
[i
]].call(this, evdata
);
3962 this.ui
.view
= this.ui
.AbstractWidget
.extend({
3963 _fetch_template: function()
3965 return $.ajax(L
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
3969 success: function(data
) {
3970 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
3971 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
3981 return L
.globals
[p2
] || '';
3984 return '(?' + match
+ ')';
3988 $('#maincontent').append(data
);
3995 throw "Not implemented";
4000 var container
= $('#maincontent');
4005 container
.append($('<h2 />').append(this.title
));
4007 if (this.description
)
4008 container
.append($('<p />').append(this.description
));
4013 for (var i
= 0; i
< arguments
.length
; i
++)
4014 args
.push(arguments
[i
]);
4016 return this._fetch_template().then(function() {
4017 return L
.deferrable(self
.execute
.apply(self
, args
));
4021 repeat: function(func
, interval
)
4025 if (!self
._timeouts
)
4026 self
._timeouts
= [ ];
4028 var index
= self
._timeouts
.length
;
4030 if (typeof(interval
) != 'number')
4033 var setTimer
, runTimer
;
4035 setTimer = function() {
4037 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
4040 runTimer = function() {
4041 L
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
4049 if ($.isArray(this._timeouts
))
4051 for (var i
= 0; i
< this._timeouts
.length
; i
++)
4052 window
.clearTimeout(this._timeouts
[i
]);
4054 delete this._timeouts
;
4059 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
4064 entries: function(entries
)
4066 for (var entry
in entries
)
4068 var path
= entry
.split(/\//);
4069 var node
= this._nodes
;
4071 for (i
= 0; i
< path
.length
; i
++)
4076 if (!node
.childs
[path
[i
]])
4077 node
.childs
[path
[i
]] = { };
4079 node
= node
.childs
[path
[i
]];
4082 $.extend(node
, entries
[entry
]);
4086 _indexcmp: function(a
, b
)
4088 var x
= a
.index
|| 0;
4089 var y
= b
.index
|| 0;
4093 firstChildView: function(node
)
4099 for (var child
in (node
.childs
|| { }))
4100 nodes
.push(node
.childs
[child
]);
4102 nodes
.sort(this._indexcmp
);
4104 for (var i
= 0; i
< nodes
.length
; i
++)
4106 var child
= this.firstChildView(nodes
[i
]);
4109 for (var key
in child
)
4110 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
4111 node
[key
] = child
[key
];
4120 _onclick: function(ev
)
4122 L
.setHash('view', ev
.data
);
4124 ev
.preventDefault();
4128 _render: function(childs
, level
, min
, max
)
4131 for (var node
in childs
)
4133 var child
= this.firstChildView(childs
[node
]);
4135 nodes
.push(childs
[node
]);
4138 nodes
.sort(this._indexcmp
);
4140 var list
= $('<ul />');
4143 list
.addClass('nav').addClass('navbar-nav');
4144 else if (level
== 1)
4145 list
.addClass('dropdown-menu').addClass('navbar-inverse');
4147 for (var i
= 0; i
< nodes
.length
; i
++)
4149 if (!L
.globals
.defaultNode
)
4151 var v
= L
.getHash('view');
4152 if (!v
|| v
== nodes
[i
].view
)
4153 L
.globals
.defaultNode
= nodes
[i
];
4156 var item
= $('<li />')
4159 .text(L
.tr(nodes
[i
].title
)))
4162 if (nodes
[i
].childs
&& level
< max
)
4164 item
.addClass('dropdown');
4167 .addClass('dropdown-toggle')
4168 .attr('data-toggle', 'dropdown')
4169 .append('<b class="caret"></b>');
4171 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
4175 item
.find('a').click(nodes
[i
].view
, this._onclick
);
4182 render: function(min
, max
)
4184 var top
= min
? this.getNode(L
.globals
.defaultNode
.view
, min
) : this._nodes
;
4185 return this._render(top
.childs
, 0, min
, max
);
4188 getNode: function(path
, max
)
4190 var p
= path
.split(/\//);
4191 var n
= this._nodes
;
4193 if (typeof(max
) == 'undefined')
4196 for (var i
= 0; i
< max
; i
++)
4198 if (!n
.childs
[p
[i
]])
4208 this.ui
.table
= this.ui
.AbstractWidget
.extend({
4214 row: function(values
)
4216 if ($.isArray(values
))
4218 this._rows
.push(values
);
4220 else if ($.isPlainObject(values
))
4223 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4225 var col
= this.options
.columns
[i
];
4227 if (typeof col
.key
== 'string')
4228 v
.push(values
[col
.key
]);
4236 rows: function(rows
)
4238 for (var i
= 0; i
< rows
.length
; i
++)
4242 render: function(id
)
4244 var fieldset
= document
.createElement('fieldset');
4245 fieldset
.className
= 'cbi-section';
4247 if (this.options
.caption
)
4249 var legend
= document
.createElement('legend');
4250 $(legend
).append(this.options
.caption
);
4251 fieldset
.appendChild(legend
);
4254 var table
= document
.createElement('table');
4255 table
.className
= 'table table-condensed table-hover';
4257 var has_caption
= false;
4258 var has_description
= false;
4260 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4261 if (this.options
.columns
[i
].caption
)
4266 else if (this.options
.columns
[i
].description
)
4268 has_description
= true;
4274 var tr
= table
.insertRow(-1);
4275 tr
.className
= 'cbi-section-table-titles';
4277 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4279 var col
= this.options
.columns
[i
];
4280 var th
= document
.createElement('th');
4281 th
.className
= 'cbi-section-table-cell';
4286 th
.style
.width
= col
.width
;
4289 th
.style
.textAlign
= col
.align
;
4292 $(th
).append(col
.caption
);
4296 if (has_description
)
4298 var tr
= table
.insertRow(-1);
4299 tr
.className
= 'cbi-section-table-descr';
4301 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4303 var col
= this.options
.columns
[i
];
4304 var th
= document
.createElement('th');
4305 th
.className
= 'cbi-section-table-cell';
4310 th
.style
.width
= col
.width
;
4313 th
.style
.textAlign
= col
.align
;
4315 if (col
.description
)
4316 $(th
).append(col
.description
);
4320 if (this._rows
.length
== 0)
4322 if (this.options
.placeholder
)
4324 var tr
= table
.insertRow(-1);
4325 var td
= tr
.insertCell(-1);
4326 td
.className
= 'cbi-section-table-cell';
4328 td
.colSpan
= this.options
.columns
.length
;
4329 $(td
).append(this.options
.placeholder
);
4334 for (var i
= 0; i
< this._rows
.length
; i
++)
4336 var tr
= table
.insertRow(-1);
4338 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
4340 var col
= this.options
.columns
[j
];
4341 var td
= tr
.insertCell(-1);
4343 var val
= this._rows
[i
][j
];
4345 if (typeof(val
) == 'undefined')
4346 val
= col
.placeholder
;
4348 if (typeof(val
) == 'undefined')
4352 td
.style
.width
= col
.width
;
4355 td
.style
.textAlign
= col
.align
;
4357 if (typeof col
.format
== 'string')
4358 $(td
).append(col
.format
.format(val
));
4359 else if (typeof col
.format
== 'function')
4360 $(td
).append(col
.format(val
, i
));
4368 fieldset
.appendChild(table
);
4374 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
4377 var vn
= parseInt(this.options
.value
) || 0;
4378 var mn
= parseInt(this.options
.max
) || 100;
4379 var pc
= Math
.floor((100 / mn
) * vn
);
4383 if (typeof(this.options
.format
) == 'string')
4384 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
4385 else if (typeof(this.options
.format
) == 'function')
4386 text
= this.options
.format(pc
);
4388 text
= '%.2f%%'.format(pc
);
4391 .addClass('progress')
4392 .append($('<div />')
4393 .addClass('progress-bar')
4394 .addClass('progress-bar-info')
4395 .css('width', pc
+ '%'))
4396 .append($('<small />')
4401 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
4404 var l2dev
= this.options
.l2_device
|| this.options
.device
;
4405 var l3dev
= this.options
.l3_device
;
4406 var dev
= l3dev
|| l2dev
|| '?';
4408 var span
= document
.createElement('span');
4409 span
.className
= 'badge';
4411 if (typeof(this.options
.signal
) == 'number' ||
4412 typeof(this.options
.noise
) == 'number')
4415 if (typeof(this.options
.signal
) != 'undefined' &&
4416 typeof(this.options
.noise
) != 'undefined')
4418 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
4431 span
.appendChild(document
.createElement('img'));
4432 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
4435 span
.title
= L
.tr('No signal');
4437 span
.title
= '%s: %d %s / %s: %d %s'.format(
4438 L
.tr('Signal'), this.options
.signal
, L
.tr('dBm'),
4439 L
.tr('Noise'), this.options
.noise
, L
.tr('dBm')
4444 var type
= 'ethernet';
4445 var desc
= L
.tr('Ethernet device');
4450 desc
= L
.tr('Tunnel interface');
4452 else if (dev
.indexOf('br-') == 0)
4455 desc
= L
.tr('Bridge');
4457 else if (dev
.indexOf('.') > 0)
4460 desc
= L
.tr('VLAN interface');
4462 else if (dev
.indexOf('wlan') == 0 ||
4463 dev
.indexOf('ath') == 0 ||
4464 dev
.indexOf('wl') == 0)
4467 desc
= L
.tr('Wireless Network');
4470 span
.appendChild(document
.createElement('img'));
4471 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
4475 $(span
).append(' ');
4476 $(span
).append(dev
);
4482 var type = function(f
, l
)
4492 L
.cbi
.validation
.message
= L
.tr(msg
);
4495 compile: function(code
)
4500 var types
= L
.cbi
.validation
.types
;
4505 for (var i
= 0; i
< code
.length
; i
++)
4513 switch (code
.charCodeAt(i
))
4525 var label
= code
.substring(pos
, i
);
4526 label
= label
.replace(/\\(.)/g, '$1');
4527 label
= label
.replace(/^[ \t]+/g, '');
4528 label
= label
.replace(/[ \t]+$/g, '');
4530 if (label
&& !isNaN(label
))
4532 stack
.push(parseFloat(label
));
4534 else if (label
.match(/^(['"]).*\1$/))
4536 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
4538 else if (typeof types
[label
] == 'function')
4540 stack
.push(types
[label
]);
4545 throw "Syntax error, unhandled token '"+label
+"'";
4550 depth
+= (code
.charCodeAt(i
) == 40);
4556 if (typeof stack
[stack
.length
-2] != 'function')
4557 throw "Syntax error, argument list follows non-function";
4559 stack
[stack
.length
-1] =
4560 L
.cbi
.validation
.compile(code
.substring(pos
, i
));
4573 var validation
= this.cbi
.validation
;
4575 validation
.types
= {
4576 'integer': function()
4578 if (this.match(/^-?[0-9]+$/) != null)
4581 validation
.i18n('Must be a valid integer');
4585 'uinteger': function()
4587 if (validation
.types
['integer'].apply(this) && (this >= 0))
4590 validation
.i18n('Must be a positive integer');
4596 if (!isNaN(parseFloat(this)))
4599 validation
.i18n('Must be a valid number');
4603 'ufloat': function()
4605 if (validation
.types
['float'].apply(this) && (this >= 0))
4608 validation
.i18n('Must be a positive number');
4612 'ipaddr': function()
4614 if (validation
.types
['ip4addr'].apply(this) ||
4615 validation
.types
['ip6addr'].apply(this))
4618 validation
.i18n('Must be a valid IP address');
4622 'ip4addr': function()
4624 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
4626 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
4627 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
4628 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
4629 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
4630 ((RegExp
.$6.indexOf('.') < 0)
4631 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
4632 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
4636 validation
.i18n('Must be a valid IPv4 address');
4640 'ip6addr': function()
4642 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
4644 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
4646 var addr
= RegExp
.$1;
4653 if (addr
.indexOf('.') > 0)
4655 var off
= addr
.lastIndexOf(':');
4657 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
4659 validation
.i18n('Must be a valid IPv6 address');
4663 addr
= addr
.substr(0, off
) + ':0:0';
4666 if (addr
.indexOf('::') >= 0)
4671 for (var i
= 1; i
< (addr
.length
-1); i
++)
4672 if (addr
.charAt(i
) == ':')
4677 validation
.i18n('Must be a valid IPv6 address');
4681 for (var i
= 0; i
< (7 - colons
); i
++)
4684 if (addr
.match(/^(.*?)::(.*?)$/))
4685 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
4686 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
4689 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
4692 validation
.i18n('Must be a valid IPv6 address');
4697 validation
.i18n('Must be a valid IPv6 address');
4703 if (validation
.types
['integer'].apply(this) &&
4704 (this >= 0) && (this <= 65535))
4707 validation
.i18n('Must be a valid port number');
4711 'portrange': function()
4713 if (this.match(/^(\d+)-(\d+)$/))
4718 if (validation
.types
['port'].apply(p1
) &&
4719 validation
.types
['port'].apply(p2
) &&
4720 (parseInt(p1
) <= parseInt(p2
)))
4723 else if (validation
.types
['port'].apply(this))
4728 validation
.i18n('Must be a valid port range');
4732 'macaddr': function()
4734 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4737 validation
.i18n('Must be a valid MAC address');
4743 if (validation
.types
['hostname'].apply(this) ||
4744 validation
.types
['ipaddr'].apply(this))
4747 validation
.i18n('Must be a valid hostname or IP address');
4751 'hostname': function()
4753 if ((this.length
<= 253) &&
4754 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4755 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4756 this.match(/[^0-9.]/)))))
4759 validation
.i18n('Must be a valid host name');
4763 'network': function()
4765 if (validation
.types
['uciname'].apply(this) ||
4766 validation
.types
['host'].apply(this))
4769 validation
.i18n('Must be a valid network name');
4773 'wpakey': function()
4777 if ((v
.length
== 64)
4778 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
4779 : ((v
.length
>= 8) && (v
.length
<= 63)))
4782 validation
.i18n('Must be a valid WPA key');
4786 'wepkey': function()
4790 if (v
.substr(0,2) == 's:')
4793 if (((v
.length
== 10) || (v
.length
== 26))
4794 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
4795 : ((v
.length
== 5) || (v
.length
== 13)))
4798 validation
.i18n('Must be a valid WEP key');
4802 'uciname': function()
4804 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4807 validation
.i18n('Must be a valid UCI identifier');
4811 'range': function(min
, max
)
4813 var val
= parseFloat(this);
4815 if (validation
.types
['integer'].apply(this) &&
4816 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
4819 validation
.i18n('Must be a number between %d and %d');
4823 'min': function(min
)
4825 var val
= parseFloat(this);
4827 if (validation
.types
['integer'].apply(this) &&
4828 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
4831 validation
.i18n('Must be a number greater or equal to %d');
4835 'max': function(max
)
4837 var val
= parseFloat(this);
4839 if (validation
.types
['integer'].apply(this) &&
4840 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
4843 validation
.i18n('Must be a number lower or equal to %d');
4847 'rangelength': function(min
, max
)
4849 var val
= '' + this;
4851 if (!isNaN(min
) && !isNaN(max
) &&
4852 (val
.length
>= min
) && (val
.length
<= max
))
4855 validation
.i18n('Must be between %d and %d characters');
4859 'minlength': function(min
)
4861 var val
= '' + this;
4863 if (!isNaN(min
) && (val
.length
>= min
))
4866 validation
.i18n('Must be at least %d characters');
4870 'maxlength': function(max
)
4872 var val
= '' + this;
4874 if (!isNaN(max
) && (val
.length
<= max
))
4877 validation
.i18n('Must be at most %d characters');
4885 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4887 delete validation
.message
;
4889 if (typeof(arguments
[i
]) != 'function')
4891 if (arguments
[i
] == this)
4895 else if (arguments
[i
].apply(this, arguments
[i
+1]))
4900 if (validation
.message
)
4901 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4904 validation
.message
= msgs
.join( L
.tr(' - or - '));
4912 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4914 delete validation
.message
;
4916 if (typeof arguments
[i
] != 'function')
4918 if (arguments
[i
] != this)
4922 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
4927 if (validation
.message
)
4928 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4931 validation
.message
= msgs
.join(', ');
4937 return validation
.types
['or'].apply(
4938 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
4941 'list': function(subvalidator
, subargs
)
4943 if (typeof subvalidator
!= 'function')
4946 var tokens
= this.match(/[^ \t]+/g);
4947 for (var i
= 0; i
< tokens
.length
; i
++)
4948 if (!subvalidator
.apply(tokens
[i
], subargs
))
4954 'phonedigit': function()
4956 if (this.match(/^[0-9\*#!\.]+$/) != null)
4959 validation
.i18n('Must be a valid phone number digit');
4963 'string': function()
4970 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
4971 init: function(name
, options
)
4974 this.instance
= { };
4975 this.dependencies
= [ ];
4976 this.rdependency
= { };
4978 this.options
= L
.defaults(options
, {
4988 return this.section
.id('field', sid
|| '__unknown__', this.name
);
4991 render: function(sid
, condensed
)
4993 var i
= this.instance
[sid
] = { };
4995 i
.top
= $('<div />');
4999 i
.top
.addClass('form-group');
5001 if (typeof(this.options
.caption
) == 'string')
5003 .addClass('col-lg-2 control-label')
5004 .attr('for', this.id(sid
))
5005 .text(this.options
.caption
)
5009 i
.error
= $('<div />')
5011 .addClass('label label-danger');
5013 i
.widget
= $('<div />')
5015 .append(this.widget(sid
))
5021 i
.widget
.addClass('col-lg-5');
5024 .addClass('col-lg-5')
5025 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
5032 active: function(sid
)
5034 return (this.instance
[sid
] && !this.instance
[sid
].disabled
);
5037 ucipath: function(sid
)
5040 config
: (this.options
.uci_package
|| this.map
.uci_package
),
5041 section
: (this.options
.uci_section
|| sid
),
5042 option
: (this.options
.uci_option
|| this.name
)
5046 ucivalue: function(sid
)
5048 var uci
= this.ucipath(sid
);
5049 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
5051 if (typeof(val
) == 'undefined')
5052 return this.options
.initial
;
5057 formvalue: function(sid
)
5059 var v
= $('#' + this.id(sid
)).val();
5060 return (v
=== '') ? undefined : v
;
5063 textvalue: function(sid
)
5065 var v
= this.formvalue(sid
);
5067 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5068 v
= this.ucivalue(sid
);
5070 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5071 v
= this.options
.placeholder
;
5073 if (typeof(v
) == 'undefined' || v
=== '')
5076 if (typeof(v
) == 'string' && $.isArray(this.choices
))
5078 for (var i
= 0; i
< this.choices
.length
; i
++)
5079 if (v
=== this.choices
[i
][0])
5080 return this.choices
[i
][1];
5082 else if (v
=== true)
5084 else if (v
=== false)
5086 else if ($.isArray(v
))
5087 return v
.join(', ');
5092 changed: function(sid
)
5094 var a
= this.ucivalue(sid
);
5095 var b
= this.formvalue(sid
);
5097 if (typeof(a
) != typeof(b
))
5100 if (typeof(a
) == 'object')
5102 if (a
.length
!= b
.length
)
5105 for (var i
= 0; i
< a
.length
; i
++)
5117 var uci
= this.ucipath(sid
);
5119 if (this.instance
[sid
].disabled
)
5121 if (!this.options
.keep
)
5122 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5127 var chg
= this.changed(sid
);
5128 var val
= this.formvalue(sid
);
5131 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
5136 _ev_validate: function(ev
)
5140 var val
= d
.elem
.val();
5141 var vstack
= d
.vstack
;
5143 if (vstack
&& typeof(vstack
[0]) == 'function')
5145 delete validation
.message
;
5147 if ((val
.length
== 0 && !d
.opt
))
5149 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
5150 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5152 d
.inst
.error
.text(L
.tr('Field must not be empty')).show();
5155 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
5157 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
5158 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5160 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
5165 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
5166 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
5168 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
5171 d
.inst
.error
.text('').hide();
5177 for (var field
in d
.self
.rdependency
)
5178 d
.self
.rdependency
[field
].toggle(d
.sid
);
5180 d
.self
.section
.tabtoggle(d
.sid
);
5186 validator: function(sid
, elem
, multi
)
5193 inst
: this.instance
[sid
],
5194 opt
: this.options
.optional
5198 for (var evname
in this.events
)
5199 elem
.on(evname
, evdata
, this.events
[evname
]);
5201 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
5205 if (typeof(this.options
.datatype
) == 'string')
5208 evdata
.vstack
= L
.cbi
.validation
.compile(this.options
.datatype
);
5211 else if (typeof(this.options
.datatype
) == 'function')
5213 var vfunc
= this.options
.datatype
;
5214 evdata
.vstack
= [ function(elem
) {
5215 var rv
= vfunc(this, elem
);
5217 validation
.message
= rv
;
5218 return (rv
=== true);
5222 if (elem
.prop('tagName') == 'SELECT')
5224 elem
.change(evdata
, this._ev_validate
);
5226 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
5228 elem
.click(evdata
, this._ev_validate
);
5229 elem
.blur(evdata
, this._ev_validate
);
5233 elem
.keyup(evdata
, this._ev_validate
);
5234 elem
.blur(evdata
, this._ev_validate
);
5237 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
5242 validate: function(sid
)
5244 var i
= this.instance
[sid
];
5246 i
.widget
.find('[cbi-validate]').trigger('validate');
5248 return (i
.disabled
|| i
.error
.text() == '');
5251 depends: function(d
, v
, add
)
5258 for (var i
= 0; i
< d
.length
; i
++)
5260 if (typeof(d
[i
]) == 'string')
5262 else if (d
[i
] instanceof L
.cbi
.AbstractValue
)
5263 dep
[d
[i
].name
] = true;
5266 else if (d
instanceof L
.cbi
.AbstractValue
)
5269 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
5271 else if (typeof(d
) == 'object')
5275 else if (typeof(d
) == 'string')
5278 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
5281 if (!dep
|| $.isEmptyObject(dep
))
5284 for (var field
in dep
)
5286 var f
= this.section
.fields
[field
];
5288 f
.rdependency
[this.name
] = this;
5293 if ($.isEmptyObject(dep
))
5296 if (!add
|| !this.dependencies
.length
)
5297 this.dependencies
.push(dep
);
5299 for (var i
= 0; i
< this.dependencies
.length
; i
++)
5300 $.extend(this.dependencies
[i
], dep
);
5305 toggle: function(sid
)
5307 var d
= this.dependencies
;
5308 var i
= this.instance
[sid
];
5313 for (var n
= 0; n
< d
.length
; n
++)
5317 for (var field
in d
[n
])
5319 var val
= this.section
.fields
[field
].formvalue(sid
);
5320 var cmp
= d
[n
][field
];
5322 if (typeof(cmp
) == 'boolean')
5324 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
5330 else if (typeof(cmp
) == 'string' || typeof(cmp
) == 'number')
5338 else if (typeof(cmp
) == 'function')
5346 else if (cmp
instanceof RegExp
)
5371 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
5378 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
5379 widget: function(sid
)
5381 var o
= this.options
;
5383 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
5384 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
5386 var i
= $('<input />')
5387 .attr('id', this.id(sid
))
5388 .attr('type', 'checkbox')
5389 .prop('checked', this.ucivalue(sid
));
5392 .addClass('checkbox')
5393 .append(this.validator(sid
, i
));
5396 ucivalue: function(sid
)
5398 var v
= this.callSuper('ucivalue', sid
);
5400 if (typeof(v
) == 'boolean')
5403 return (v
== this.options
.enabled
);
5406 formvalue: function(sid
)
5408 var v
= $('#' + this.id(sid
)).prop('checked');
5410 if (typeof(v
) == 'undefined')
5411 return !!this.options
.initial
;
5418 var uci
= this.ucipath(sid
);
5420 if (this.instance
[sid
].disabled
)
5422 if (!this.options
.keep
)
5423 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5428 var chg
= this.changed(sid
);
5429 var val
= this.formvalue(sid
);
5433 if (this.options
.optional
&& val
== this.options
.initial
)
5434 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5436 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
5443 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
5444 widget: function(sid
)
5446 var i
= $('<input />')
5447 .addClass('form-control')
5448 .attr('id', this.id(sid
))
5449 .attr('type', 'text')
5450 .attr('placeholder', this.options
.placeholder
)
5451 .val(this.ucivalue(sid
));
5453 return this.validator(sid
, i
);
5457 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
5458 widget: function(sid
)
5460 var i
= $('<input />')
5461 .addClass('form-control')
5462 .attr('id', this.id(sid
))
5463 .attr('type', 'password')
5464 .attr('placeholder', this.options
.placeholder
)
5465 .val(this.ucivalue(sid
));
5467 var t
= $('<span />')
5468 .addClass('input-group-btn')
5469 .append(L
.ui
.button(L
.tr('Reveal'), 'default')
5470 .click(function(ev
) {
5472 var i
= b
.parent().prev();
5473 var t
= i
.attr('type');
5474 b
.text(t
== 'password' ? L
.tr('Hide') : L
.tr('Reveal'));
5475 i
.attr('type', (t
== 'password') ? 'text' : 'password');
5479 this.validator(sid
, i
);
5482 .addClass('input-group')
5488 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
5489 widget: function(sid
)
5491 var s
= $('<select />')
5492 .addClass('form-control');
5494 if (this.options
.optional
&& !this.has_empty
)
5497 .text(L
.tr('-- Please choose --'))
5501 for (var i
= 0; i
< this.choices
.length
; i
++)
5503 .attr('value', this.choices
[i
][0])
5504 .text(this.choices
[i
][1])
5507 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
5509 return this.validator(sid
, s
);
5512 value: function(k
, v
)
5518 this.has_empty
= true;
5520 this.choices
.push([k
, v
|| k
]);
5525 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
5526 widget: function(sid
)
5528 var v
= this.ucivalue(sid
);
5529 var t
= $('<div />').attr('id', this.id(sid
));
5532 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5535 for (var i
= 0; i
< v
.length
; i
++)
5539 for (var i
= 0; i
< this.choices
.length
; i
++)
5542 .addClass('checkbox')
5543 .append($('<input />')
5544 .attr('type', 'checkbox')
5545 .attr('value', this.choices
[i
][0])
5546 .prop('checked', s
[this.choices
[i
][0]]))
5547 .append(this.choices
[i
][1])
5554 formvalue: function(sid
)
5557 var fields
= $('#' + this.id(sid
) + ' > label > input');
5559 for (var i
= 0; i
< fields
.length
; i
++)
5560 if (fields
[i
].checked
)
5561 rv
.push(fields
[i
].getAttribute('value'));
5566 textvalue: function(sid
)
5568 var v
= this.formvalue(sid
);
5572 for (var i
= 0; i
< this.choices
.length
; i
++)
5573 c
[this.choices
[i
][0]] = this.choices
[i
][1];
5577 for (var i
= 0; i
< v
.length
; i
++)
5578 t
.push(c
[v
[i
]] || v
[i
]);
5580 return t
.join(', ');
5584 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
5585 _change: function(ev
)
5588 var self
= ev
.data
.self
;
5590 if (s
.selectedIndex
== (s
.options
.length
- 1))
5592 ev
.data
.select
.hide();
5593 ev
.data
.input
.show().focus();
5594 ev
.data
.input
.val('');
5596 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
5598 ev
.data
.input
.val('');
5602 ev
.data
.input
.val(ev
.data
.select
.val());
5605 ev
.stopPropagation();
5611 var val
= this.value
;
5612 var self
= ev
.data
.self
;
5614 ev
.data
.select
.empty();
5616 if (self
.options
.optional
&& !self
.has_empty
)
5619 .text(L
.tr('-- please choose --'))
5620 .appendTo(ev
.data
.select
);
5623 for (var i
= 0; i
< self
.choices
.length
; i
++)
5625 if (self
.choices
[i
][0] == val
)
5629 .attr('value', self
.choices
[i
][0])
5630 .text(self
.choices
[i
][1])
5631 .appendTo(ev
.data
.select
);
5634 if (!seen
&& val
!= '')
5638 .appendTo(ev
.data
.select
);
5642 .text(L
.tr('-- custom --'))
5643 .appendTo(ev
.data
.select
);
5645 ev
.data
.input
.hide();
5646 ev
.data
.select
.val(val
).show().blur();
5649 _enter: function(ev
)
5654 ev
.preventDefault();
5655 ev
.data
.self
._blur(ev
);
5659 widget: function(sid
)
5661 var d
= $('<div />')
5662 .attr('id', this.id(sid
));
5664 var t
= $('<input />')
5665 .addClass('form-control')
5666 .attr('type', 'text')
5670 var s
= $('<select />')
5671 .addClass('form-control')
5680 s
.change(evdata
, this._change
);
5681 t
.blur(evdata
, this._blur
);
5682 t
.keydown(evdata
, this._enter
);
5684 t
.val(this.ucivalue(sid
));
5687 this.validator(sid
, t
);
5688 this.validator(sid
, s
);
5693 value: function(k
, v
)
5699 this.has_empty
= true;
5701 this.choices
.push([k
, v
|| k
]);
5705 formvalue: function(sid
)
5707 var v
= $('#' + this.id(sid
)).children('input').val();
5708 return (v
== '') ? undefined : v
;
5712 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
5713 _redraw: function(focus
, add
, del
, s
)
5715 var v
= s
.values
|| [ ];
5718 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
5720 v
.push(this.value
|| '');
5723 $(s
.parent
).empty();
5728 v
.splice(focus
, 0, '');
5730 else if (v
.length
== 0)
5736 for (var i
= 0; i
< v
.length
; i
++)
5743 remove
: ((i
+1) < v
.length
)
5748 btn
= L
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
5750 btn
= L
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
5754 var txt
= $('<input />')
5755 .addClass('form-control')
5756 .attr('type', 'text')
5759 var sel
= $('<select />')
5760 .addClass('form-control');
5763 .addClass('input-group')
5766 .append($('<span />')
5767 .addClass('input-group-btn')
5769 .appendTo(s
.parent
);
5771 evdata
.input
= this.validator(s
.sid
, txt
, true);
5772 evdata
.select
= this.validator(s
.sid
, sel
, true);
5774 sel
.change(evdata
, this._change
);
5775 txt
.blur(evdata
, this._blur
);
5776 txt
.keydown(evdata
, this._keydown
);
5781 if (i
== focus
|| -(i
+1) == focus
)
5788 var f
= $('<input />')
5789 .attr('type', 'text')
5791 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
5792 .addClass('form-control')
5793 .keydown(evdata
, this._keydown
)
5794 .keypress(evdata
, this._keypress
)
5798 .addClass('input-group')
5800 .append($('<span />')
5801 .addClass('input-group-btn')
5803 .appendTo(s
.parent
);
5809 else if (-(i
+1) == focus
)
5813 /* force cursor to end */
5819 evdata
.input
= this.validator(s
.sid
, f
, true);
5830 _keypress: function(ev
)
5834 /* backspace, delete */
5837 if (ev
.data
.input
.val() == '')
5839 ev
.preventDefault();
5845 /* enter, arrow up, arrow down */
5849 ev
.preventDefault();
5856 _keydown: function(ev
)
5858 var input
= ev
.data
.input
;
5862 /* backspace, delete */
5865 if (input
.val().length
== 0)
5867 ev
.preventDefault();
5869 var index
= ev
.data
.index
;
5875 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
5883 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5888 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
5889 if (prev
.is(':visible'))
5892 prev
.next('select').focus();
5897 var next
= input
.parent().nextAll('div.input-group:first').children('input');
5898 if (next
.is(':visible'))
5901 next
.next('select').focus();
5908 _btnclick: function(ev
)
5910 if (!this.getAttribute('disabled'))
5914 var index
= ev
.data
.index
;
5915 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
5919 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5926 widget: function(sid
)
5928 this.options
.optional
= true;
5930 var v
= this.ucivalue(sid
);
5933 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5935 var d
= $('<div />')
5936 .attr('id', this.id(sid
))
5937 .addClass('cbi-input-dynlist');
5939 this._redraw(NaN
, -1, -1, {
5949 ucivalue: function(sid
)
5951 var v
= this.callSuper('ucivalue', sid
);
5954 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5959 formvalue: function(sid
)
5962 var fields
= $('#' + this.id(sid
) + ' input');
5964 for (var i
= 0; i
< fields
.length
; i
++)
5965 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
5966 rv
.push(fields
[i
].value
);
5972 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
5973 widget: function(sid
)
5976 .addClass('form-control-static')
5977 .attr('id', this.id(sid
))
5978 .html(this.ucivalue(sid
));
5981 formvalue: function(sid
)
5983 return this.ucivalue(sid
);
5987 this.cbi
.ButtonValue
= this.cbi
.AbstractValue
.extend({
5988 widget: function(sid
)
5990 this.options
.optional
= true;
5992 var btn
= $('<button />')
5993 .addClass('btn btn-default')
5994 .attr('id', this.id(sid
))
5995 .attr('type', 'button')
5996 .text(this.label('text'));
5998 return this.validator(sid
, btn
);
6002 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
6005 return L
.NetworkModel
.init();
6008 _device_icon: function(dev
)
6011 .attr('src', dev
.icon())
6012 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?'));
6015 widget: function(sid
)
6017 var id
= this.id(sid
);
6018 var ul
= $('<ul />')
6020 .addClass('list-unstyled');
6022 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
6023 var value
= this.ucivalue(sid
);
6026 if (!this.options
.multiple
)
6027 check
[value
] = true;
6029 for (var i
= 0; i
< value
.length
; i
++)
6030 check
[value
[i
]] = true;
6032 var interfaces
= L
.NetworkModel
.getInterfaces();
6034 for (var i
= 0; i
< interfaces
.length
; i
++)
6036 var iface
= interfaces
[i
];
6039 .append($('<label />')
6040 .addClass(itype
+ ' inline')
6041 .append(this.validator(sid
, $('<input />')
6042 .attr('name', itype
+ id
)
6043 .attr('type', itype
)
6044 .attr('value', iface
.name())
6045 .prop('checked', !!check
[iface
.name()]), true))
6046 .append(iface
.renderBadge()))
6050 if (!this.options
.multiple
)
6053 .append($('<label />')
6054 .addClass(itype
+ ' inline text-muted')
6055 .append($('<input />')
6056 .attr('name', itype
+ id
)
6057 .attr('type', itype
)
6059 .prop('checked', $.isEmptyObject(check
)))
6060 .append(L
.tr('unspecified')))
6067 ucivalue: function(sid
)
6069 var v
= this.callSuper('ucivalue', sid
);
6071 if (!this.options
.multiple
)
6077 else if (typeof(v
) == 'string')
6080 return v
? v
[0] : undefined;
6087 if (typeof(v
) == 'string')
6088 v
= v
.match(/\S+/g);
6094 formvalue: function(sid
)
6096 var inputs
= $('#' + this.id(sid
) + ' input');
6098 if (!this.options
.multiple
)
6100 for (var i
= 0; i
< inputs
.length
; i
++)
6101 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
6102 return inputs
[i
].value
;
6109 for (var i
= 0; i
< inputs
.length
; i
++)
6110 if (inputs
[i
].checked
)
6111 rv
.push(inputs
[i
].value
);
6113 return rv
.length
? rv
: undefined;
6117 this.cbi
.DeviceList
= this.cbi
.NetworkList
.extend({
6118 _ev_focus: function(ev
)
6120 var self
= ev
.data
.self
;
6121 var input
= $(this);
6123 input
.parent().prev().prop('checked', true);
6126 _ev_blur: function(ev
)
6129 ev
.data
.self
._ev_keydown
.call(this, ev
);
6132 _ev_keydown: function(ev
)
6134 if (ev
.which
!= 10 && ev
.which
!= 13)
6137 var sid
= ev
.data
.sid
;
6138 var self
= ev
.data
.self
;
6139 var input
= $(this);
6140 var ifnames
= L
.toArray(input
.val());
6142 if (!ifnames
.length
)
6145 L
.NetworkModel
.createDevice(ifnames
[0]);
6147 self
._redraw(sid
, $('#' + self
.id(sid
)), ifnames
[0]);
6152 return L
.NetworkModel
.init();
6155 _redraw: function(sid
, ul
, sel
)
6157 var id
= ul
.attr('id');
6158 var devs
= L
.NetworkModel
.getDevices();
6159 var iface
= L
.NetworkModel
.getInterface(sid
);
6160 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
6165 for (var i
= 0; i
< devs
.length
; i
++)
6166 if (devs
[i
].isInNetwork(iface
))
6167 check
[devs
[i
].name()] = true;
6171 if (this.options
.multiple
)
6172 check
= L
.toObject(this.formvalue(sid
));
6179 for (var i
= 0; i
< devs
.length
; i
++)
6183 if (dev
.isBridge() && this.options
.bridges
=== false)
6186 if (!dev
.isBridgeable() && this.options
.multiple
)
6189 var badge
= $('<span />')
6191 .append($('<img />').attr('src', dev
.icon()))
6192 .append(' %s: %s'.format(dev
.name(), dev
.description()));
6194 //var ifcs = dev.getInterfaces();
6197 // for (var j = 0; j < ifcs.length; j++)
6198 // badge.append((j ? ', ' : ' (') + ifcs[j].name());
6200 // badge.append(')');
6204 .append($('<label />')
6205 .addClass(itype
+ ' inline')
6206 .append($('<input />')
6207 .attr('name', itype
+ id
)
6208 .attr('type', itype
)
6209 .attr('value', dev
.name())
6210 .prop('checked', !!check
[dev
.name()]))
6217 .append($('<label />')
6218 .attr('for', 'custom' + id
)
6219 .addClass(itype
+ ' inline')
6220 .append($('<input />')
6221 .attr('name', itype
+ id
)
6222 .attr('type', itype
)
6224 .append($('<span />')
6226 .append($('<input />')
6227 .attr('id', 'custom' + id
)
6228 .attr('type', 'text')
6229 .attr('placeholder', L
.tr('Custom device …'))
6230 .on('focus', { self
: this, sid
: sid
}, this._ev_focus
)
6231 .on('blur', { self
: this, sid
: sid
}, this._ev_blur
)
6232 .on('keydown', { self
: this, sid
: sid
}, this._ev_keydown
))))
6235 if (!this.options
.multiple
)
6238 .append($('<label />')
6239 .addClass(itype
+ ' inline text-muted')
6240 .append($('<input />')
6241 .attr('name', itype
+ id
)
6242 .attr('type', itype
)
6244 .prop('checked', $.isEmptyObject(check
)))
6245 .append(L
.tr('unspecified')))
6250 widget: function(sid
)
6252 var id
= this.id(sid
);
6253 var ul
= $('<ul />')
6255 .addClass('list-unstyled');
6257 this._redraw(sid
, ul
);
6264 if (this.instance
[sid
].disabled
)
6267 var ifnames
= this.formvalue(sid
);
6271 var iface
= L
.NetworkModel
.getInterface(sid
);
6275 iface
.setDevices($.isArray(ifnames
) ? ifnames
: [ ifnames
]);
6280 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
6283 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
6285 for (var i
= 1; i
< arguments
.length
; i
++)
6286 s
.push(arguments
[i
].replace(/\./g, '_'));
6291 option: function(widget
, name
, options
)
6293 if (this.tabs
.length
== 0)
6294 this.tab({ id
: '__default__', selected
: true });
6296 return this.taboption('__default__', widget
, name
, options
);
6299 tab: function(options
)
6301 if (options
.selected
)
6302 this.tabs
.selected
= this.tabs
.length
;
6306 caption
: options
.caption
,
6307 description
: options
.description
,
6313 taboption: function(tabid
, widget
, name
, options
)
6316 for (var i
= 0; i
< this.tabs
.length
; i
++)
6318 if (this.tabs
[i
].id
== tabid
)
6326 throw 'Cannot append to unknown tab ' + tabid
;
6328 var w
= widget
? new widget(name
, options
) : null;
6330 if (!(w
instanceof L
.cbi
.AbstractValue
))
6331 throw 'Widget must be an instance of AbstractValue';
6336 this.fields
[name
] = w
;
6342 tabtoggle: function(sid
)
6344 for (var i
= 0; i
< this.tabs
.length
; i
++)
6346 var tab
= this.tabs
[i
];
6347 var elem
= $('#' + this.id('nodetab', sid
, tab
.id
));
6350 for (var j
= 0; j
< tab
.fields
.length
; j
++)
6352 if (tab
.fields
[j
].active(sid
))
6359 if (empty
&& elem
.is(':visible'))
6366 ucipackages: function(pkg
)
6368 for (var i
= 0; i
< this.tabs
.length
; i
++)
6369 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6370 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
6371 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
6374 formvalue: function()
6378 this.sections(function(s
) {
6379 var sid
= s
['.name'];
6380 var sv
= rv
[sid
] || (rv
[sid
] = { });
6382 for (var i
= 0; i
< this.tabs
.length
; i
++)
6383 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6385 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
6386 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
6393 validate_section: function(sid
)
6395 var inst
= this.instance
[sid
];
6398 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
6400 for (var i
= 0; i
< this.tabs
.length
; i
++)
6403 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
6405 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6406 if (!this.tabs
[i
].fields
[j
].validate(sid
))
6412 .attr('title', L
.trp('1 Error', '%d Errors', inval
).format(inval
));
6422 .attr('title', L
.trp('1 Error', '%d Errors', invals
).format(invals
));
6429 validate: function()
6432 var as
= this.sections();
6434 for (var i
= 0; i
< as
.length
; i
++)
6436 var invals
= this.validate_section(as
[i
]['.name']);
6442 var badge
= $('#' + this.id('sectiontab')).children('span:first');
6447 .attr('title', L
.trp('1 Error', '%d Errors', errors
).format(errors
));
6451 return (errors
== 0);
6455 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
6456 init: function(uci_type
, options
)
6458 this.uci_type
= uci_type
;
6459 this.options
= options
;
6462 this.active_panel
= 0;
6463 this.active_tab
= { };
6466 filter: function(section
)
6471 sections: function(cb
)
6473 var s1
= L
.uci
.sections(this.map
.uci_package
);
6476 for (var i
= 0; i
< s1
.length
; i
++)
6477 if (s1
[i
]['.type'] == this.uci_type
)
6478 if (this.filter(s1
[i
]))
6481 if (typeof(cb
) == 'function')
6482 for (var i
= 0; i
< s2
.length
; i
++)
6483 cb
.call(this, s2
[i
]);
6490 return this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
6493 remove: function(sid
)
6495 return this.map
.remove(this.map
.uci_package
, sid
);
6498 _ev_add: function(ev
)
6501 var name
= undefined;
6502 var self
= ev
.data
.self
;
6504 if (addb
.prev().prop('nodeName') == 'INPUT')
6505 name
= addb
.prev().val();
6507 if (addb
.prop('disabled') || name
=== '')
6510 L
.ui
.saveScrollTop();
6512 self
.active_panel
= -1;
6515 ev
.data
.sid
= self
.add(name
);
6516 ev
.data
.type
= self
.uci_type
;
6517 ev
.data
.name
= name
;
6519 self
.trigger('add', ev
);
6523 L
.ui
.restoreScrollTop();
6526 _ev_remove: function(ev
)
6528 var self
= ev
.data
.self
;
6529 var sid
= ev
.data
.sid
;
6531 L
.ui
.saveScrollTop();
6533 self
.trigger('remove', ev
);
6539 L
.ui
.restoreScrollTop();
6541 ev
.stopPropagation();
6544 _ev_sid: function(ev
)
6546 var self
= ev
.data
.self
;
6548 var addb
= text
.next();
6549 var errt
= addb
.next();
6550 var name
= text
.val();
6552 if (!/^[a-zA-Z0-9_]*$/.test(name
))
6554 errt
.text(L
.tr('Invalid section name')).show();
6555 text
.addClass('error');
6556 addb
.prop('disabled', true);
6560 if (L
.uci
.get(self
.map
.uci_package
, name
))
6562 errt
.text(L
.tr('Name already used')).show();
6563 text
.addClass('error');
6564 addb
.prop('disabled', true);
6568 errt
.text('').hide();
6569 text
.removeClass('error');
6570 addb
.prop('disabled', false);
6574 _ev_tab: function(ev
)
6576 var self
= ev
.data
.self
;
6577 var sid
= ev
.data
.sid
;
6580 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
6583 _ev_panel_collapse: function(ev
)
6585 var self
= ev
.data
.self
;
6587 var this_panel
= $(ev
.target
);
6588 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
6590 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
6591 var prev_panel
= $(prev_toggle
.attr('data-target'));
6595 .addClass('collapse');
6597 prev_toggle
.find('.luci2-section-teaser')
6599 .children('span:last')
6601 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
6603 this_toggle
.find('.luci2-section-teaser')
6606 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
6610 _ev_panel_open: function(ev
)
6612 var self
= ev
.data
.self
;
6613 var panel
= $($(this).attr('data-target'));
6614 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
6616 if (index
== self
.active_panel
)
6617 ev
.stopPropagation();
6620 _ev_sort: function(ev
)
6622 var self
= ev
.data
.self
;
6623 var cur_idx
= ev
.data
.index
;
6624 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
6625 var s
= self
.sections();
6627 if (new_idx
>= 0 && new_idx
< s
.length
)
6629 L
.uci
.swap(self
.map
.uci_package
, s
[cur_idx
]['.name'], s
[new_idx
]['.name']);
6635 ev
.stopPropagation();
6638 teaser: function(sid
)
6640 var tf
= this.teaser_fields
;
6644 tf
= this.teaser_fields
= [ ];
6646 if ($.isArray(this.options
.teasers
))
6648 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
6650 var f
= this.options
.teasers
[i
];
6651 if (f
instanceof L
.cbi
.AbstractValue
)
6653 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof L
.cbi
.AbstractValue
)
6654 tf
.push(this.fields
[f
]);
6659 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
6660 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
6661 tf
.push(this.tabs
[i
].fields
[j
]);
6667 for (var i
= 0; i
< tf
.length
; i
++)
6669 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
6672 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
6673 var v
= tf
[i
].textvalue(sid
);
6675 if (typeof(v
) == 'undefined')
6678 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
6684 _render_add: function()
6686 if (!this.options
.addremove
)
6689 var text
= L
.tr('Add section');
6690 var ttip
= L
.tr('Create new section...');
6692 if ($.isArray(this.options
.add_caption
))
6693 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
6694 else if (typeof(this.options
.add_caption
) == 'string')
6695 text
= this.options
.add_caption
, ttip
= '';
6697 var add
= $('<div />');
6699 if (this.options
.anonymous
=== false)
6702 .addClass('cbi-input-text')
6703 .attr('type', 'text')
6704 .attr('placeholder', ttip
)
6705 .blur({ self
: this }, this._ev_sid
)
6706 .keyup({ self
: this }, this._ev_sid
)
6710 .attr('src', L
.globals
.resource
+ '/icons/cbi/add.gif')
6711 .attr('title', text
)
6712 .addClass('cbi-button')
6713 .click({ self
: this }, this._ev_add
)
6717 .addClass('cbi-value-error')
6723 L
.ui
.button(text
, 'success', ttip
)
6724 .click({ self
: this }, this._ev_add
)
6731 _render_remove: function(sid
, index
)
6733 if (!this.options
.addremove
)
6736 var text
= L
.tr('Remove');
6737 var ttip
= L
.tr('Remove this section');
6739 if ($.isArray(this.options
.remove_caption
))
6740 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
6741 else if (typeof(this.options
.remove_caption
) == 'string')
6742 text
= this.options
.remove_caption
, ttip
= '';
6744 return L
.ui
.button(text
, 'danger', ttip
)
6745 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
6748 _render_sort: function(sid
, index
)
6750 if (!this.options
.sortable
)
6753 var b1
= L
.ui
.button('↑', 'info', L
.tr('Move up'))
6754 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
6756 var b2
= L
.ui
.button('↓', 'info', L
.tr('Move down'))
6757 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
6762 _render_caption: function()
6765 .addClass('panel-title')
6766 .append(this.label('caption') || this.uci_type
);
6769 _render_description: function()
6771 var text
= this.label('description');
6775 .addClass('luci2-section-description')
6781 _render_teaser: function(sid
, index
)
6783 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6786 .attr('id', this.id('teaser', sid
))
6787 .addClass('luci2-section-teaser well well-sm')
6788 .append($('<span />')
6790 .append($('<span />'));
6796 _render_head: function(condensed
)
6802 .addClass('panel-heading')
6803 .append(this._render_caption())
6804 .append(this._render_description());
6807 _render_tab_description: function(sid
, index
, tab_index
)
6809 var tab
= this.tabs
[tab_index
];
6811 if (typeof(tab
.description
) == 'string')
6814 .addClass('cbi-tab-descr')
6815 .text(tab
.description
);
6821 _render_tab_head: function(sid
, index
, tab_index
)
6823 var tab
= this.tabs
[tab_index
];
6824 var cur
= this.active_tab
[sid
] || 0;
6826 var tabh
= $('<li />')
6828 .attr('id', this.id('nodetab', sid
, tab
.id
))
6829 .attr('href', '#' + this.id('node', sid
, tab
.id
))
6830 .attr('data-toggle', 'tab')
6831 .attr('data-luci2-tab-index', tab_index
)
6832 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
6833 .append($('<span />')
6835 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
6837 if (cur
== tab_index
)
6838 tabh
.addClass('active');
6840 if (!tab
.fields
.length
)
6846 _render_tab_body: function(sid
, index
, tab_index
)
6848 var tab
= this.tabs
[tab_index
];
6849 var cur
= this.active_tab
[sid
] || 0;
6851 var tabb
= $('<div />')
6852 .addClass('tab-pane')
6853 .attr('id', this.id('node', sid
, tab
.id
))
6854 .attr('data-luci2-tab-index', tab_index
)
6855 .append(this._render_tab_description(sid
, index
, tab_index
));
6857 if (cur
== tab_index
)
6858 tabb
.addClass('active');
6860 for (var i
= 0; i
< tab
.fields
.length
; i
++)
6861 tabb
.append(tab
.fields
[i
].render(sid
));
6866 _render_section_head: function(sid
, index
)
6868 var head
= $('<div />')
6869 .addClass('luci2-section-header')
6870 .append(this._render_teaser(sid
, index
))
6871 .append($('<div />')
6872 .addClass('btn-group')
6873 .append(this._render_sort(sid
, index
))
6874 .append(this._render_remove(sid
, index
)));
6876 if (this.options
.collabsible
)
6878 head
.attr('data-toggle', 'collapse')
6879 .attr('data-parent', this.id('sectiongroup'))
6880 .attr('data-target', '#' + this.id('panel', sid
))
6881 .on('click', { self
: this }, this._ev_panel_open
);
6887 _render_section_body: function(sid
, index
)
6889 var body
= $('<div />')
6890 .attr('id', this.id('panel', sid
))
6891 .attr('data-luci2-panel-index', index
)
6892 .attr('data-luci2-sid', sid
);
6894 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6896 body
.addClass('panel-collapse collapse');
6898 if (index
== this.active_panel
)
6899 body
.addClass('in');
6902 var tab_heads
= $('<ul />')
6903 .addClass('nav nav-tabs');
6905 var tab_bodies
= $('<div />')
6906 .addClass('form-horizontal tab-content')
6909 for (var j
= 0; j
< this.tabs
.length
; j
++)
6911 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
6912 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
6915 body
.append(tab_bodies
);
6917 if (this.tabs
.length
<= 1)
6923 _render_body: function(condensed
)
6925 var s
= this.sections();
6927 if (this.active_panel
< 0)
6928 this.active_panel
+= s
.length
;
6929 else if (this.active_panel
>= s
.length
)
6930 this.active_panel
= s
.length
- 1;
6932 var body
= $('<ul />')
6933 .addClass('list-group');
6935 if (this.options
.collabsible
)
6937 body
.attr('id', this.id('sectiongroup'))
6938 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
6943 body
.append($('<li />')
6944 .addClass('list-group-item text-muted')
6945 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.')))
6948 for (var i
= 0; i
< s
.length
; i
++)
6950 var sid
= s
[i
]['.name'];
6951 var inst
= this.instance
[sid
] = { tabs
: [ ] };
6953 body
.append($('<li />')
6954 .addClass('list-group-item')
6955 .append(this._render_section_head(sid
, i
))
6956 .append(this._render_section_body(sid
, i
)));
6962 render: function(condensed
)
6964 this.instance
= { };
6966 var panel
= $('<div />')
6967 .addClass('panel panel-default')
6968 .append(this._render_head(condensed
))
6969 .append(this._render_body(condensed
));
6971 if (this.options
.addremove
)
6972 panel
.append($('<div />')
6973 .addClass('panel-footer')
6974 .append(this._render_add()));
6981 var s
= this.sections();
6983 for (var i
= 0; i
< s
.length
; i
++)
6985 var sid
= s
[i
]['.name'];
6987 this.validate_section(sid
);
6989 if (i
!= this.active_panel
)
6990 $('#' + this.id('teaser', sid
)).children('span:last')
6991 .append(this.teaser(sid
));
6993 $('#' + this.id('teaser', sid
))
6999 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
7000 _render_table_head: function()
7002 var thead
= $('<thead />')
7004 .addClass('cbi-section-table-titles'));
7006 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
7007 thead
.children().append($('<th />')
7008 .addClass('cbi-section-table-cell')
7009 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
7010 .append(this.tabs
[0].fields
[j
].label('caption')));
7012 if (this.options
.addremove
!== false || this.options
.sortable
)
7013 thead
.children().append($('<th />')
7014 .addClass('cbi-section-table-cell')
7020 _render_table_row: function(sid
, index
)
7022 var row
= $('<tr />')
7023 .attr('data-luci2-sid', sid
);
7025 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
7027 row
.append($('<td />')
7028 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
7029 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
7032 if (this.options
.addremove
!== false || this.options
.sortable
)
7034 row
.append($('<td />')
7035 .addClass('text-right')
7036 .append($('<div />')
7037 .addClass('btn-group')
7038 .append(this._render_sort(sid
, index
))
7039 .append(this._render_remove(sid
, index
))));
7045 _render_table_body: function()
7047 var s
= this.sections();
7049 var tbody
= $('<tbody />');
7053 var cols
= this.tabs
[0].fields
.length
;
7055 if (this.options
.addremove
!== false || this.options
.sortable
)
7058 tbody
.append($('<tr />')
7060 .addClass('text-muted')
7061 .attr('colspan', cols
)
7062 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.'))));
7065 for (var i
= 0; i
< s
.length
; i
++)
7067 var sid
= s
[i
]['.name'];
7068 var inst
= this.instance
[sid
] = { tabs
: [ ] };
7070 tbody
.append(this._render_table_row(sid
, i
));
7076 _render_body: function(condensed
)
7078 return $('<table />')
7079 .addClass('table table-condensed table-hover')
7080 .append(this._render_table_head())
7081 .append(this._render_table_body());
7085 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
7086 sections: function(cb
)
7089 var sl
= L
.uci
.sections(this.map
.uci_package
);
7091 for (var i
= 0; i
< sl
.length
; i
++)
7092 if (sl
[i
]['.name'] == this.uci_type
)
7098 if (typeof(cb
) == 'function' && sa
.length
> 0)
7099 cb
.call(this, sa
[0]);
7105 this.cbi
.SingleSection
= this.cbi
.NamedSection
.extend({
7108 this.instance
= { };
7109 this.instance
[this.uci_type
] = { tabs
: [ ] };
7111 return this._render_section_body(this.uci_type
, 0);
7115 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
7116 sections: function(cb
)
7118 if (typeof(cb
) == 'function')
7119 cb
.apply(this, [ { '.name': this.uci_type
} ]);
7121 return [ { '.name': this.uci_type
} ];
7125 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
7126 init: function(uci_package
, options
)
7130 this.uci_package
= uci_package
;
7131 this.sections
= [ ];
7132 this.options
= L
.defaults(options
, {
7133 save: function() { },
7134 prepare: function() { }
7138 _load_cb: function()
7140 var deferreds
= [ L
.deferrable(this.options
.prepare()) ];
7142 for (var i
= 0; i
< this.sections
.length
; i
++)
7144 for (var f
in this.sections
[i
].fields
)
7146 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
7149 var s
= this.sections
[i
].sections();
7150 for (var j
= 0; j
< s
.length
; j
++)
7152 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
7153 if (L
.isDeferred(rv
))
7159 return $.when
.apply($, deferreds
);
7167 for (var i
= 0; i
< this.sections
.length
; i
++)
7168 this.sections
[i
].ucipackages(packages
);
7170 packages
[this.uci_package
] = true;
7172 for (var pkg
in packages
)
7173 if (!L
.uci
.writable(pkg
))
7174 this.options
.readonly
= true;
7176 return L
.uci
.load(L
.toArray(packages
)).then(function() {
7177 return self
._load_cb();
7181 _ev_tab: function(ev
)
7183 var self
= ev
.data
.self
;
7186 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
7189 _ev_apply: function(ev
)
7191 var self
= ev
.data
.self
;
7193 self
.trigger('apply', ev
);
7196 _ev_save: function(ev
)
7198 var self
= ev
.data
.self
;
7200 self
.send().then(function() {
7201 self
.trigger('save', ev
);
7205 _ev_reset: function(ev
)
7207 var self
= ev
.data
.self
;
7209 self
.trigger('reset', ev
);
7213 _render_tab_head: function(tab_index
)
7215 var section
= this.sections
[tab_index
];
7216 var cur
= this.active_tab
|| 0;
7218 var tabh
= $('<li />')
7220 .attr('id', section
.id('sectiontab'))
7221 .attr('href', '#' + section
.id('section'))
7222 .attr('data-toggle', 'tab')
7223 .attr('data-luci2-tab-index', tab_index
)
7224 .text(section
.label('caption') + ' ')
7225 .append($('<span />')
7227 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
7229 if (cur
== tab_index
)
7230 tabh
.addClass('active');
7235 _render_tab_body: function(tab_index
)
7237 var section
= this.sections
[tab_index
];
7238 var desc
= section
.label('description');
7239 var cur
= this.active_tab
|| 0;
7241 var tabb
= $('<div />')
7242 .addClass('tab-pane')
7243 .attr('id', section
.id('section'))
7244 .attr('data-luci2-tab-index', tab_index
);
7246 if (cur
== tab_index
)
7247 tabb
.addClass('active');
7250 tabb
.append($('<p />')
7253 var s
= section
.render(this.options
.tabbed
);
7255 if (this.options
.readonly
|| section
.options
.readonly
)
7256 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
7263 _render_body: function()
7265 var tabs
= $('<ul />')
7266 .addClass('nav nav-tabs');
7268 var body
= $('<div />')
7271 for (var i
= 0; i
< this.sections
.length
; i
++)
7273 tabs
.append(this._render_tab_head(i
));
7274 body
.append(this._render_tab_body(i
));
7277 if (this.options
.tabbed
)
7278 body
.addClass('tab-content');
7285 _render_footer: function()
7292 .addClass('panel panel-default panel-body text-right')
7293 .append($('<div />')
7294 .addClass('btn-group')
7295 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7296 .click(evdata
, this._ev_apply
))
7297 .append(L
.ui
.button(L
.tr('Save'), 'default')
7298 .click(evdata
, this._ev_save
))
7299 .append(L
.ui
.button(L
.tr('Reset'), 'default')
7300 .click(evdata
, this._ev_reset
)));
7305 var map
= $('<form />');
7307 if (typeof(this.options
.caption
) == 'string')
7308 map
.append($('<h2 />')
7309 .text(this.options
.caption
));
7311 if (typeof(this.options
.description
) == 'string')
7312 map
.append($('<p />')
7313 .text(this.options
.description
));
7315 map
.append(this._render_body());
7317 if (this.options
.pageaction
!== false)
7318 map
.append(this._render_footer());
7325 for (var i
= 0; i
< this.sections
.length
; i
++)
7326 this.sections
[i
].finish();
7333 this.target
.hide().empty().append(this.render());
7338 section: function(widget
, uci_type
, options
)
7340 var w
= widget
? new widget(uci_type
, options
) : null;
7342 if (!(w
instanceof L
.cbi
.AbstractSection
))
7343 throw 'Widget must be an instance of AbstractSection';
7346 w
.index
= this.sections
.length
;
7348 this.sections
.push(w
);
7352 formvalue: function()
7356 for (var i
= 0; i
< this.sections
.length
; i
++)
7358 var sids
= this.sections
[i
].formvalue();
7359 for (var sid
in sids
)
7361 var s
= rv
[sid
] || (rv
[sid
] = { });
7362 $.extend(s
, sids
[sid
]);
7369 add: function(conf
, type
, name
)
7371 return L
.uci
.add(conf
, type
, name
);
7374 remove: function(conf
, sid
)
7376 return L
.uci
.remove(conf
, sid
);
7379 get: function(conf
, sid
, opt
)
7381 return L
.uci
.get(conf
, sid
, opt
);
7384 set: function(conf
, sid
, opt
, val
)
7386 return L
.uci
.set(conf
, sid
, opt
, val
);
7389 validate: function()
7393 for (var i
= 0; i
< this.sections
.length
; i
++)
7395 if (!this.sections
[i
].validate())
7406 if (self
.options
.readonly
)
7407 return L
.deferrable();
7409 var deferreds
= [ ];
7411 for (var i
= 0; i
< self
.sections
.length
; i
++)
7413 if (self
.sections
[i
].options
.readonly
)
7416 for (var f
in self
.sections
[i
].fields
)
7418 if (typeof(self
.sections
[i
].fields
[f
].save
) != 'function')
7421 var s
= self
.sections
[i
].sections();
7422 for (var j
= 0; j
< s
.length
; j
++)
7424 var rv
= self
.sections
[i
].fields
[f
].save(s
[j
]['.name']);
7425 if (L
.isDeferred(rv
))
7431 return $.when
.apply($, deferreds
).then(function() {
7432 return L
.deferrable(self
.options
.save());
7438 if (!this.validate())
7439 return L
.deferrable();
7443 L
.ui
.saveScrollTop();
7446 return this.save().then(function() {
7447 return L
.uci
.save();
7448 }).then(function() {
7449 return L
.ui
.updateChanges();
7450 }).then(function() {
7452 }).then(function() {
7456 L
.ui
.loading(false);
7457 L
.ui
.restoreScrollTop();
7465 for (var i
= 0; i
< this.sections
.length
; i
++)
7466 this.sections
[i
].ucipackages(packages
);
7468 packages
[this.uci_package
] = true;
7470 L
.uci
.unload(L
.toArray(packages
));
7479 return self
.insertInto(self
.target
);
7482 insertInto: function(id
)
7485 self
.target
= $(id
);
7490 return self
.load().then(function() {
7491 self
.target
.empty().append(self
.render());
7495 L
.ui
.loading(false);
7500 this.cbi
.Modal
= this.cbi
.Map
.extend({
7501 _ev_apply: function(ev
)
7503 var self
= ev
.data
.self
;
7505 self
.trigger('apply', ev
);
7508 _ev_save: function(ev
)
7510 var self
= ev
.data
.self
;
7512 self
.send().then(function() {
7513 self
.trigger('save', ev
);
7518 _ev_reset: function(ev
)
7520 var self
= ev
.data
.self
;
7522 self
.trigger('close', ev
);
7527 _render_footer: function()
7534 .addClass('btn-group')
7535 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7536 .click(evdata
, this._ev_apply
))
7537 .append(L
.ui
.button(L
.tr('Save'), 'default')
7538 .click(evdata
, this._ev_save
))
7539 .append(L
.ui
.button(L
.tr('Cancel'), 'default')
7540 .click(evdata
, this._ev_reset
));
7545 var modal
= L
.ui
.dialog(this.label('caption'), null, { wide
: true });
7546 var map
= $('<form />');
7548 var desc
= this.label('description');
7550 map
.append($('<p />').text(desc
));
7552 map
.append(this._render_body());
7554 modal
.find('.modal-body').append(map
);
7555 modal
.find('.modal-footer').append(this._render_footer());
7572 return self
.load().then(function() {
7576 L
.ui
.loading(false);