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);
1116 for (var pkg
in this.state
.values
)
1121 return this.load(pkgs
);
1124 _reorder: function()
1126 var v
= this.state
.values
;
1127 var n
= this.state
.creates
;
1128 var r
= this.state
.reorder
;
1130 if ($.isEmptyObject(r
))
1131 return L
.deferrable();
1136 gather all created and existing sections, sort them according
1137 to their index value and issue an uci order call
1152 o
.sort(function(a
, b
) {
1153 return (a
['.index'] - b
['.index']);
1158 for (var i
= 0; i
< o
.length
; i
++)
1159 sids
.push(o
[i
]['.name']);
1161 this._order(c
, sids
);
1165 this.state
.reorder
= { };
1166 return L
.rpc
.flush();
1169 swap: function(conf
, sid1
, sid2
)
1171 var s1
= this.get(conf
, sid1
);
1172 var s2
= this.get(conf
, sid2
);
1173 var n1
= s1
? s1
['.index'] : NaN
;
1174 var n2
= s2
? s2
['.index'] : NaN
;
1176 if (isNaN(n1
) || isNaN(n2
))
1182 this.state
.reorder
[conf
] = true;
1191 var v
= this.state
.values
;
1192 var n
= this.state
.creates
;
1193 var c
= this.state
.changes
;
1194 var d
= this.state
.deletes
;
1203 for (var sid
in n
[conf
])
1210 for (var k
in n
[conf
][sid
])
1213 r
.type
= n
[conf
][sid
][k
];
1214 else if (k
== '.create')
1215 r
.name
= n
[conf
][sid
][k
];
1216 else if (k
.charAt(0) != '.')
1217 r
.values
[k
] = n
[conf
][sid
][k
];
1220 snew
.push(n
[conf
][sid
]);
1222 self
._add(r
.config
, r
.type
, r
.name
, r
.values
);
1231 for (var sid
in c
[conf
])
1232 self
._set(conf
, sid
, c
[conf
][sid
]);
1240 for (var sid
in d
[conf
])
1242 var o
= d
[conf
][sid
];
1243 self
._delete(conf
, sid
, (o
=== true) ? undefined : o
);
1249 return L
.rpc
.flush().then(function(responses
) {
1251 array "snew" holds references to the created uci sections,
1252 use it to assign the returned names of the new sections
1254 for (var i
= 0; i
< snew
.length
; i
++)
1255 snew
[i
]['.name'] = responses
[i
];
1257 return self
._reorder();
1258 }).then(function() {
1259 pkgs
= L
.toArray(pkgs
);
1263 return self
.load(pkgs
);
1267 _apply
: L
.rpc
.declare({
1270 params
: [ 'timeout', 'rollback' ]
1273 _confirm
: L
.rpc
.declare({
1278 apply: function(timeout
)
1281 var date
= new Date();
1282 var deferred
= $.Deferred();
1284 if (typeof(timeout
) != 'number' || timeout
< 1)
1287 self
._apply(timeout
, true).then(function(rv
) {
1290 deferred
.rejectWith(self
, [ rv
]);
1294 var try_deadline
= date
.getTime() + 1000 * timeout
;
1295 var try_confirm = function()
1297 return self
._confirm().then(function(rv
) {
1300 if (date
.getTime() < try_deadline
)
1301 window
.setTimeout(try_confirm
, 250);
1303 deferred
.rejectWith(self
, [ rv
]);
1308 deferred
.resolveWith(self
, [ rv
]);
1312 window
.setTimeout(try_confirm
, 1000);
1318 changes
: L
.rpc
.declare({
1321 expect
: { changes
: { } }
1324 readable: function(conf
)
1326 return L
.session
.hasACL('uci', conf
, 'read');
1329 writable: function(conf
)
1331 return L
.session
.hasACL('uci', conf
, 'write');
1335 this.uci
= new this.UCIContext();
1338 listDeviceNames
: L
.rpc
.declare({
1341 expect
: { 'devices': [ ] },
1342 filter: function(data
) {
1348 getDeviceStatus
: L
.rpc
.declare({
1351 params
: [ 'device' ],
1352 expect
: { '': { } },
1353 filter: function(data
, params
) {
1354 if (!$.isEmptyObject(data
))
1356 data
['device'] = params
['device'];
1363 getAssocList
: L
.rpc
.declare({
1365 method
: 'assoclist',
1366 params
: [ 'device' ],
1367 expect
: { results
: [ ] },
1368 filter: function(data
, params
) {
1369 for (var i
= 0; i
< data
.length
; i
++)
1370 data
[i
]['device'] = params
['device'];
1372 data
.sort(function(a
, b
) {
1373 if (a
.bssid
< b
.bssid
)
1375 else if (a
.bssid
> b
.bssid
)
1385 getWirelessStatus: function() {
1386 return this.listDeviceNames().then(function(names
) {
1389 for (var i
= 0; i
< names
.length
; i
++)
1390 L
.wireless
.getDeviceStatus(names
[i
]);
1392 return L
.rpc
.flush();
1393 }).then(function(networks
) {
1397 'country', 'channel', 'frequency', 'frequency_offset',
1398 'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1402 'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1403 'signal', 'noise', 'bitrate', 'encryption'
1406 for (var i
= 0; i
< networks
.length
; i
++)
1408 var phy
= rv
[networks
[i
].phy
] || (
1409 rv
[networks
[i
].phy
] = { networks
: [ ] }
1413 device
: networks
[i
].device
1416 for (var j
= 0; j
< phy_attrs
.length
; j
++)
1417 phy
[phy_attrs
[j
]] = networks
[i
][phy_attrs
[j
]];
1419 for (var j
= 0; j
< net_attrs
.length
; j
++)
1420 net
[net_attrs
[j
]] = networks
[i
][net_attrs
[j
]];
1422 phy
.networks
.push(net
);
1429 getAssocLists: function()
1431 return this.listDeviceNames().then(function(names
) {
1434 for (var i
= 0; i
< names
.length
; i
++)
1435 L
.wireless
.getAssocList(names
[i
]);
1437 return L
.rpc
.flush();
1438 }).then(function(assoclists
) {
1441 for (var i
= 0; i
< assoclists
.length
; i
++)
1442 for (var j
= 0; j
< assoclists
[i
].length
; j
++)
1443 rv
.push(assoclists
[i
][j
]);
1449 formatEncryption: function(enc
)
1451 var format_list = function(l
, s
)
1454 for (var i
= 0; i
< l
.length
; i
++)
1455 rv
.push(l
[i
].toUpperCase());
1456 return rv
.join(s
? s
: ', ');
1459 if (!enc
|| !enc
.enabled
)
1460 return L
.tr('None');
1464 if (enc
.wep
.length
== 2)
1465 return L
.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1466 else if (enc
.wep
[0] == 'shared')
1467 return L
.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1469 return L
.tr('WEP Open System') + ' (%s)'.format(format_list(enc
.ciphers
, ', '));
1473 if (enc
.wpa
.length
== 2)
1474 return L
.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1475 format_list(enc
.authentication
, '/'),
1476 format_list(enc
.ciphers
, ', ')
1478 else if (enc
.wpa
[0] == 2)
1479 return 'WPA2 %s (%s)'.format(
1480 format_list(enc
.authentication
, '/'),
1481 format_list(enc
.ciphers
, ', ')
1484 return 'WPA %s (%s)'.format(
1485 format_list(enc
.authentication
, '/'),
1486 format_list(enc
.ciphers
, ', ')
1490 return L
.tr('Unknown');
1495 getZoneColor: function(zone
)
1497 if ($.isPlainObject(zone
))
1502 else if (zone
== 'wan')
1505 for (var i
= 0, hash
= 0;
1507 hash
= zone
.charCodeAt(i
++) + ((hash
<< 5) - hash
));
1509 for (var i
= 0, color
= '#';
1511 color
+= ('00' + ((hash
>> i
++ * 8) & 0xFF).tostring(16)).slice(-2));
1516 findZoneByNetwork: function(network
)
1519 var zone
= undefined;
1521 return L
.uci
.sections('firewall', 'zone', function(z
) {
1522 if (!z
.name
|| !z
.network
)
1525 if (!$.isArray(z
.network
))
1526 z
.network
= z
.network
.split(/\s+/);
1528 for (var i
= 0; i
< z
.network
.length
; i
++)
1530 if (z
.network
[i
] == network
)
1536 }).then(function() {
1538 zone
.color
= self
.getZoneColor(zone
);
1545 this.NetworkModel
= {
1546 _device_blacklist
: [
1552 /^wlan[0-9]+\.sta[0-9]+$/
1556 'protolist', 0, L
.rpc
.declare({
1558 method
: 'get_proto_handlers',
1561 'ifstate', 1, L
.rpc
.declare({
1562 object
: 'network.interface',
1564 expect
: { 'interface': [ ] }
1566 'devstate', 2, L
.rpc
.declare({
1567 object
: 'network.device',
1571 'wifistate', 0, L
.rpc
.declare({
1572 object
: 'network.wireless',
1576 'bwstate', 2, L
.rpc
.declare({
1577 object
: 'luci2.network.bwmon',
1578 method
: 'statistics',
1579 expect
: { 'statistics': { } }
1581 'devlist', 2, L
.rpc
.declare({
1582 object
: 'luci2.network',
1583 method
: 'device_list',
1584 expect
: { 'devices': [ ] }
1586 'swlist', 0, L
.rpc
.declare({
1587 object
: 'luci2.network',
1588 method
: 'switch_list',
1589 expect
: { 'switches': [ ] }
1593 _fetch_protocol: function(proto
)
1595 var url
= L
.globals
.resource
+ '/proto/' + proto
+ '.js';
1596 var self
= L
.NetworkModel
;
1598 var def
= $.Deferred();
1604 }).then(function(data
) {
1606 var protoConstructorSource
= (
1607 '(function(L, $) { ' +
1611 ).format(data
, url
);
1613 var protoClass
= eval(protoConstructorSource
);
1615 self
._protos
[proto
] = new protoClass();
1618 alert('Unable to instantiate proto "%s": %s'.format(url
, e
));
1622 }).fail(function() {
1629 _fetch_protocols: function()
1631 var self
= L
.NetworkModel
;
1633 self
._fetch_protocol('none')
1636 for (var proto
in self
._cache
.protolist
)
1637 deferreds
.push(self
._fetch_protocol(proto
));
1639 return $.when
.apply($, deferreds
);
1642 _fetch_swstate
: L
.rpc
.declare({
1643 object
: 'luci2.network',
1644 method
: 'switch_info',
1645 params
: [ 'switch' ],
1646 expect
: { 'info': { } }
1649 _fetch_swstate_cb: function(responses
) {
1650 var self
= L
.NetworkModel
;
1651 var swlist
= self
._cache
.swlist
;
1652 var swstate
= self
._cache
.swstate
= { };
1654 for (var i
= 0; i
< responses
.length
; i
++)
1655 swstate
[swlist
[i
]] = responses
[i
];
1658 _fetch_cache_cb: function(level
)
1660 var self
= L
.NetworkModel
;
1661 var name
= '_fetch_cache_cb_' + level
;
1663 return self
[name
] || (
1664 self
[name
] = function(responses
)
1666 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1667 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1668 self
._cache
[self
._cache_functions
[i
]] = responses
.shift();
1674 for (var i
= 0; i
< self
._cache
.swlist
.length
; i
++)
1675 self
._fetch_swstate(self
._cache
.swlist
[i
]);
1677 return L
.rpc
.flush().then(self
._fetch_swstate_cb
);
1680 return L
.deferrable();
1685 _fetch_cache: function(level
)
1687 var self
= L
.NetworkModel
;
1689 return L
.uci
.load(['network', 'wireless']).then(function() {
1692 for (var i
= 0; i
< self
._cache_functions
.length
; i
+= 3)
1693 if (!level
|| self
._cache_functions
[i
+ 1] == level
)
1694 self
._cache_functions
[i
+ 2]();
1696 return L
.rpc
.flush().then(self
._fetch_cache_cb(level
|| 0));
1700 _get: function(pkg
, sid
, key
)
1702 return L
.uci
.get(pkg
, sid
, key
);
1705 _set: function(pkg
, sid
, key
, val
)
1707 return L
.uci
.set(pkg
, sid
, key
, val
);
1710 _is_blacklisted: function(dev
)
1712 for (var i
= 0; i
< this._device_blacklist
.length
; i
++)
1713 if (dev
.match(this._device_blacklist
[i
]))
1719 _sort_devices: function(a
, b
)
1721 if (a
.options
.kind
< b
.options
.kind
)
1723 else if (a
.options
.kind
> b
.options
.kind
)
1726 if (a
.options
.name
< b
.options
.name
)
1728 else if (a
.options
.name
> b
.options
.name
)
1734 _get_dev: function(ifname
)
1736 var alias
= (ifname
.charAt(0) == '@');
1737 return this._devs
[ifname
] || (
1738 this._devs
[ifname
] = {
1740 kind
: alias
? 'alias' : 'ethernet',
1741 type
: alias
? 0 : 1,
1748 _get_iface: function(name
)
1750 return this._ifaces
[name
] || (
1751 this._ifaces
[name
] = {
1753 proto
: this._protos
.none
,
1759 _parse_devices: function()
1761 var self
= L
.NetworkModel
;
1762 var wificount
= { };
1764 for (var ifname
in self
._cache
.devstate
)
1766 if (self
._is_blacklisted(ifname
))
1769 var dev
= self
._cache
.devstate
[ifname
];
1770 var entry
= self
._get_dev(ifname
);
1777 entry
.kind
= 'tunnel';
1781 entry
.kind
= 'bridge';
1782 //entry.ports = dev['bridge-members'].sort();
1787 for (var i
= 0; i
< self
._cache
.devlist
.length
; i
++)
1789 var dev
= self
._cache
.devlist
[i
];
1791 if (self
._is_blacklisted(dev
.device
))
1794 var entry
= self
._get_dev(dev
.device
);
1796 entry
.up
= dev
.is_up
;
1797 entry
.type
= dev
.type
;
1801 case 1: /* Ethernet */
1803 entry
.kind
= 'bridge';
1804 else if (dev
.is_tuntap
)
1805 entry
.kind
= 'tunnel';
1806 else if (dev
.is_wireless
)
1807 entry
.kind
= 'wifi';
1811 case 768: /* IP-IP Tunnel */
1812 case 769: /* IP6-IP6 Tunnel */
1813 case 776: /* IPv6-in-IPv4 */
1814 case 778: /* GRE over IP */
1815 entry
.kind
= 'tunnel';
1820 var net
= L
.uci
.sections('network');
1821 for (var i
= 0; i
< net
.length
; i
++)
1824 var sid
= s
['.name'];
1826 if (s
['.type'] == 'device' && s
.name
)
1828 var entry
= self
._get_dev(s
.name
);
1834 entry
.kind
= 'tunnel';
1840 else if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.ifname
)
1842 var ifnames
= L
.toArray(s
.ifname
);
1844 for (var j
= 0; j
< ifnames
.length
; j
++)
1845 self
._get_dev(ifnames
[j
]);
1847 if (s
['.name'] != 'loopback')
1849 var entry
= self
._get_dev('@%s'.format(s
['.name']));
1852 entry
.kind
= 'alias';
1856 else if (s
['.type'] == 'switch_vlan' && s
.device
)
1858 var sw
= self
._cache
.swstate
[s
.device
];
1859 var vid
= parseInt(s
.vid
|| s
.vlan
);
1860 var ports
= L
.toArray(s
.ports
);
1862 if (!sw
|| !ports
.length
|| isNaN(vid
))
1865 var ifname
= undefined;
1867 for (var j
= 0; j
< ports
.length
; j
++)
1869 var port
= parseInt(ports
[j
]);
1870 var tag
= (ports
[j
].replace(/[^tu]/g, '') == 't');
1872 if (port
== sw
.cpu_port
)
1874 // XXX: need a way to map switch to netdev
1876 ifname
= 'eth0.%d'.format(vid
);
1887 var entry
= self
._get_dev(ifname
);
1889 entry
.kind
= 'vlan';
1896 var wifi
= L
.uci
.sections('wireless');
1897 for (var i
= 0; i
< wifi
.length
; i
++)
1900 var sid
= s
['.name'];
1902 if (s
['.type'] == 'wifi-iface' && s
.device
)
1904 var r
= parseInt(s
.device
.replace(/^[^0-9]+/, ''));
1905 var n
= wificount
[s
.device
] = (wificount
[s
.device
] || 0) + 1;
1906 var id
= 'radio%d.network%d'.format(r
, n
);
1909 if (self
._cache
.wifistate
[s
.device
])
1911 var ifcs
= self
._cache
.wifistate
[s
.device
].interfaces
;
1912 for (var ifc
in ifcs
)
1914 if (ifcs
[ifc
].section
== sid
)
1916 ifname
= ifcs
[ifc
].ifname
;
1922 var entry
= self
._get_dev(ifname
);
1924 entry
.kind
= 'wifi';
1927 entry
.wdev
= s
.device
;
1928 entry
.wmode
= s
.mode
;
1929 entry
.wssid
= s
.ssid
;
1930 entry
.wbssid
= s
.bssid
;
1934 for (var i
= 0; i
< net
.length
; i
++)
1937 var sid
= s
['.name'];
1939 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.type
== 'bridge')
1941 var ifnames
= L
.toArray(s
.ifname
);
1943 for (var ifname
in self
._devs
)
1945 var dev
= self
._devs
[ifname
];
1947 if (dev
.kind
!= 'wifi')
1950 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1951 if ($.inArray(sid
, wnets
) > -1)
1952 ifnames
.push(ifname
);
1955 entry
= self
._get_dev('br-%s'.format(s
['.name']));
1957 entry
.kind
= 'bridge';
1959 entry
.ports
= ifnames
.sort();
1964 _parse_interfaces: function()
1966 var self
= L
.NetworkModel
;
1967 var net
= L
.uci
.sections('network');
1969 for (var i
= 0; i
< net
.length
; i
++)
1972 var sid
= s
['.name'];
1974 if (s
['.type'] == 'interface' && !s
['.anonymous'] && s
.proto
)
1976 var entry
= self
._get_iface(s
['.name']);
1977 var proto
= self
._protos
[s
.proto
] || self
._protos
.none
;
1979 var l3dev
= undefined;
1980 var l2dev
= undefined;
1982 var ifnames
= L
.toArray(s
.ifname
);
1984 for (var ifname
in self
._devs
)
1986 var dev
= self
._devs
[ifname
];
1988 if (dev
.kind
!= 'wifi')
1991 var wnets
= L
.toArray(L
.uci
.get('wireless', dev
.sid
, 'network'));
1992 if ($.inArray(entry
.name
, wnets
) > -1)
1993 ifnames
.push(ifname
);
1997 l3dev
= '%s-%s'.format(s
.proto
, entry
.name
);
1998 else if (s
.type
== 'bridge')
1999 l3dev
= 'br-%s'.format(entry
.name
);
2003 if (!proto
.virtual
&& s
.type
== 'bridge')
2004 l2dev
= 'br-%s'.format(entry
.name
);
2005 else if (!proto
.virtual
)
2008 entry
.proto
= proto
;
2010 entry
.l3dev
= l3dev
;
2011 entry
.l2dev
= l2dev
;
2015 for (var i
= 0; i
< self
._cache
.ifstate
.length
; i
++)
2017 var iface
= self
._cache
.ifstate
[i
];
2018 var entry
= self
._get_iface(iface
['interface']);
2019 var proto
= self
._protos
[iface
.proto
] || self
._protos
.none
;
2021 /* this is a virtual interface, either deleted from config but
2022 not applied yet or set up from external tools (6rd) */
2025 entry
.proto
= proto
;
2026 entry
.l2dev
= iface
.device
;
2027 entry
.l3dev
= iface
.l3_device
;
2037 return L
.deferrable();
2044 return self
._fetch_cache()
2045 .then(self
._fetch_protocols
)
2046 .then(self
._parse_devices
)
2047 .then(self
._parse_interfaces
);
2056 refreshInterfaceStatus: function()
2058 return this._fetch_cache(1).then(this._parse_interfaces
);
2061 refreshDeviceStatus: function()
2063 return this._fetch_cache(2).then(this._parse_devices
);
2066 refreshStatus: function()
2068 return this._fetch_cache(1)
2069 .then(this._fetch_cache(2))
2070 .then(this._parse_devices
)
2071 .then(this._parse_interfaces
);
2074 getDevices: function()
2078 for (var ifname
in this._devs
)
2080 devs
.push(new L
.NetworkModel
.Device(this._devs
[ifname
]));
2082 return devs
.sort(this._sort_devices
);
2085 getDeviceByInterface: function(iface
)
2087 if (iface
instanceof L
.NetworkModel
.Interface
)
2088 iface
= iface
.name();
2090 if (this._ifaces
[iface
])
2091 return this.getDevice(this._ifaces
[iface
].l3dev
) ||
2092 this.getDevice(this._ifaces
[iface
].l2dev
);
2097 getDevice: function(ifname
)
2099 if (this._devs
[ifname
])
2100 return new L
.NetworkModel
.Device(this._devs
[ifname
]);
2105 createDevice: function(name
)
2107 return new L
.NetworkModel
.Device(this._get_dev(name
));
2110 getInterfaces: function()
2114 for (var name
in this._ifaces
)
2115 if (name
!= 'loopback')
2116 ifaces
.push(this.getInterface(name
));
2118 ifaces
.sort(function(a
, b
) {
2119 if (a
.name() < b
.name())
2121 else if (a
.name() > b
.name())
2130 getInterfacesByDevice: function(dev
)
2134 if (dev
instanceof L
.NetworkModel
.Device
)
2137 for (var name
in this._ifaces
)
2139 var iface
= this._ifaces
[name
];
2140 if (iface
.l2dev
== dev
|| iface
.l3dev
== dev
)
2141 ifaces
.push(this.getInterface(name
));
2144 ifaces
.sort(function(a
, b
) {
2145 if (a
.name() < b
.name())
2147 else if (a
.name() > b
.name())
2156 getInterface: function(iface
)
2158 if (this._ifaces
[iface
])
2159 return new L
.NetworkModel
.Interface(this._ifaces
[iface
]);
2164 getProtocols: function()
2168 for (var proto
in this._protos
)
2170 var pr
= this._protos
[proto
];
2174 description
: pr
.description
,
2175 virtual
: pr
.virtual
,
2180 return rv
.sort(function(a
, b
) {
2181 if (a
.name
< b
.name
)
2183 else if (a
.name
> b
.name
)
2190 _find_wan: function(ipaddr
)
2192 for (var i
= 0; i
< this._cache
.ifstate
.length
; i
++)
2194 var ifstate
= this._cache
.ifstate
[i
];
2199 for (var j
= 0; j
< ifstate
.route
.length
; j
++)
2200 if (ifstate
.route
[j
].mask
== 0 &&
2201 ifstate
.route
[j
].target
== ipaddr
&&
2202 typeof(ifstate
.route
[j
].table
) == 'undefined')
2204 return this.getInterface(ifstate
['interface']);
2213 return this._find_wan('0.0.0.0');
2216 findWAN6: function()
2218 return this._find_wan('::');
2221 resolveAlias: function(ifname
)
2223 if (ifname
instanceof L
.NetworkModel
.Device
)
2224 ifname
= ifname
.name();
2226 var dev
= this._devs
[ifname
];
2229 while (dev
&& dev
.kind
== 'alias')
2232 if (seen
[dev
.ifname
])
2235 var ifc
= this._ifaces
[dev
.sid
];
2237 seen
[dev
.ifname
] = true;
2238 dev
= ifc
? this._devs
[ifc
.l3dev
] : undefined;
2241 return dev
? this.getDevice(dev
.ifname
) : undefined;
2245 this.NetworkModel
.Device
= Class
.extend({
2248 sta
: L
.tr('Client'),
2249 adhoc
: L
.tr('Ad-Hoc'),
2250 monitor
: L
.tr('Monitor'),
2251 wds
: L
.tr('Static WDS')
2254 _status: function(key
)
2256 var s
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2259 return key
? s
[key
] : s
;
2266 var sid
= this.options
.sid
;
2267 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2268 return L
.NetworkModel
._get(pkg
, sid
, key
);
2271 set: function(key
, val
)
2273 var sid
= this.options
.sid
;
2274 var pkg
= (this.options
.kind
== 'wifi') ? 'wireless' : 'network';
2275 return L
.NetworkModel
._set(pkg
, sid
, key
, val
);
2280 if (typeof(this.options
.type
) == 'undefined')
2281 this.options
.type
= 1;
2283 if (typeof(this.options
.kind
) == 'undefined')
2284 this.options
.kind
= 'ethernet';
2286 if (typeof(this.options
.networks
) == 'undefined')
2287 this.options
.networks
= [ ];
2292 return this.options
.ifname
;
2295 description: function()
2297 switch (this.options
.kind
)
2300 return L
.tr('Alias for network "%s"').format(this.options
.ifname
.substring(1));
2303 return L
.tr('Network bridge');
2306 return L
.tr('Network device');
2309 switch (this.options
.type
)
2311 case 1: /* tuntap */
2312 return L
.tr('TAP device');
2315 return L
.tr('PPP tunnel');
2317 case 768: /* IP-IP Tunnel */
2318 return L
.tr('IP-in-IP tunnel');
2320 case 769: /* IP6-IP6 Tunnel */
2321 return L
.tr('IPv6-in-IPv6 tunnel');
2323 case 776: /* IPv6-in-IPv4 */
2324 return L
.tr('IPv6-over-IPv4 tunnel');
2327 case 778: /* GRE over IP */
2328 return L
.tr('GRE-over-IP tunnel');
2331 return L
.tr('Tunnel device');
2335 return L
.tr('VLAN %d on %s').format(this.options
.vid
, this.options
.vsw
.model
);
2338 var o
= this.options
;
2339 return L
.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2340 o
.wmode
? this._wifi_modes
[o
.wmode
] : L
.tr('Unknown mode'),
2341 o
.wssid
|| '?', o
.wdev
2345 return L
.tr('Unknown device');
2350 var kind
= this.options
.kind
;
2352 if (kind
== 'alias')
2355 if (typeof(up
) == 'undefined')
2358 return L
.globals
.resource
+ '/icons/%s%s.png'.format(kind
, up
? '' : '_disabled');
2363 var l
= L
.NetworkModel
._cache
.devlist
;
2365 for (var i
= 0; i
< l
.length
; i
++)
2366 if (l
[i
].device
== this.options
.ifname
)
2367 return (l
[i
].is_up
=== true);
2374 return (this.options
.kind
== 'alias');
2377 isBridge: function()
2379 return (this.options
.kind
== 'bridge');
2382 isBridgeable: function()
2384 return (this.options
.type
== 1 && this.options
.kind
!= 'bridge');
2387 isWireless: function()
2389 return (this.options
.kind
== 'wifi');
2392 isInNetwork: function(net
)
2394 if (!(net
instanceof L
.NetworkModel
.Interface
))
2395 net
= L
.NetworkModel
.getInterface(net
);
2399 if (net
.options
.l3dev
== this.options
.ifname
||
2400 net
.options
.l2dev
== this.options
.ifname
)
2403 var dev
= L
.NetworkModel
._devs
[net
.options
.l2dev
];
2404 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
)
2405 return ($.inArray(this.options
.ifname
, dev
.ports
) > -1);
2413 var dev
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2414 if (dev
&& !isNaN(dev
.mtu
))
2420 getMACAddress: function()
2422 if (this.options
.type
!= 1)
2425 var dev
= L
.NetworkModel
._cache
.devstate
[this.options
.ifname
];
2426 if (dev
&& dev
.macaddr
)
2427 return dev
.macaddr
.toUpperCase();
2432 getInterfaces: function()
2434 return L
.NetworkModel
.getInterfacesByDevice(this.options
.name
);
2437 getStatistics: function()
2439 var s
= this._status('statistics') || { };
2441 rx_bytes
: (s
.rx_bytes
|| 0),
2442 tx_bytes
: (s
.tx_bytes
|| 0),
2443 rx_packets
: (s
.rx_packets
|| 0),
2444 tx_packets
: (s
.tx_packets
|| 0)
2448 getTrafficHistory: function()
2450 var def
= new Array(120);
2452 for (var i
= 0; i
< 120; i
++)
2455 var h
= L
.NetworkModel
._cache
.bwstate
[this.options
.ifname
] || { };
2457 rx_bytes
: (h
.rx_bytes
|| def
),
2458 tx_bytes
: (h
.tx_bytes
|| def
),
2459 rx_packets
: (h
.rx_packets
|| def
),
2460 tx_packets
: (h
.tx_packets
|| def
)
2464 removeFromInterface: function(iface
)
2466 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2467 iface
= L
.NetworkModel
.getInterface(iface
);
2472 var ifnames
= L
.toArray(iface
.get('ifname'));
2473 if ($.inArray(this.options
.ifname
, ifnames
) > -1)
2474 iface
.set('ifname', L
.filterArray(ifnames
, this.options
.ifname
));
2476 if (this.options
.kind
!= 'wifi')
2479 var networks
= L
.toArray(this.get('network'));
2480 if ($.inArray(iface
.name(), networks
) > -1)
2481 this.set('network', L
.filterArray(networks
, iface
.name()));
2484 attachToInterface: function(iface
)
2486 if (!(iface
instanceof L
.NetworkModel
.Interface
))
2487 iface
= L
.NetworkModel
.getInterface(iface
);
2492 if (this.options
.kind
!= 'wifi')
2494 var ifnames
= L
.toArray(iface
.get('ifname'));
2495 if ($.inArray(this.options
.ifname
, ifnames
) < 0)
2497 ifnames
.push(this.options
.ifname
);
2498 iface
.set('ifname', (ifnames
.length
> 1) ? ifnames
: ifnames
[0]);
2503 var networks
= L
.toArray(this.get('network'));
2504 if ($.inArray(iface
.name(), networks
) < 0)
2506 networks
.push(iface
.name());
2507 this.set('network', (networks
.length
> 1) ? networks
: networks
[0]);
2513 this.NetworkModel
.Interface
= Class
.extend({
2514 _status: function(key
)
2516 var s
= L
.NetworkModel
._cache
.ifstate
;
2518 for (var i
= 0; i
< s
.length
; i
++)
2519 if (s
[i
]['interface'] == this.options
.name
)
2520 return key
? s
[i
][key
] : s
[i
];
2527 return L
.NetworkModel
._get('network', this.options
.name
, key
);
2530 set: function(key
, val
)
2532 return L
.NetworkModel
._set('network', this.options
.name
, key
, val
);
2537 return this.options
.name
;
2540 protocol: function()
2542 return (this.get('proto') || 'none');
2547 return (this._status('up') === true);
2550 isVirtual: function()
2552 return (typeof(this.options
.sid
) != 'string');
2555 getProtocol: function()
2557 var prname
= this.get('proto') || 'none';
2558 return L
.NetworkModel
._protos
[prname
] || L
.NetworkModel
._protos
.none
;
2561 getUptime: function()
2563 var uptime
= this._status('uptime');
2564 return isNaN(uptime
) ? 0 : uptime
;
2567 getDevice: function(resolveAlias
)
2569 if (this.options
.l3dev
)
2570 return L
.NetworkModel
.getDevice(this.options
.l3dev
);
2575 getPhysdev: function()
2577 if (this.options
.l2dev
)
2578 return L
.NetworkModel
.getDevice(this.options
.l2dev
);
2583 getSubdevices: function()
2586 var dev
= this.options
.l2dev
?
2587 L
.NetworkModel
._devs
[this.options
.l2dev
] : undefined;
2589 if (dev
&& dev
.kind
== 'bridge' && dev
.ports
&& dev
.ports
.length
)
2590 for (var i
= 0; i
< dev
.ports
.length
; i
++)
2591 rv
.push(L
.NetworkModel
.getDevice(dev
.ports
[i
]));
2596 getIPv4Addrs: function(mask
)
2599 var addrs
= this._status('ipv4-address');
2602 for (var i
= 0; i
< addrs
.length
; i
++)
2604 rv
.push(addrs
[i
].address
);
2606 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2611 getIPv6Addrs: function(mask
)
2616 addrs
= this._status('ipv6-address');
2619 for (var i
= 0; i
< addrs
.length
; i
++)
2621 rv
.push(addrs
[i
].address
);
2623 rv
.push('%s/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2625 addrs
= this._status('ipv6-prefix-assignment');
2628 for (var i
= 0; i
< addrs
.length
; i
++)
2630 rv
.push('%s1'.format(addrs
[i
].address
));
2632 rv
.push('%s1/%d'.format(addrs
[i
].address
, addrs
[i
].mask
));
2637 getDNSAddrs: function()
2640 var addrs
= this._status('dns-server');
2643 for (var i
= 0; i
< addrs
.length
; i
++)
2649 getIPv4DNS: function()
2652 var dns
= this._status('dns-server');
2655 for (var i
= 0; i
< dns
.length
; i
++)
2656 if (dns
[i
].indexOf(':') == -1)
2662 getIPv6DNS: function()
2665 var dns
= this._status('dns-server');
2668 for (var i
= 0; i
< dns
.length
; i
++)
2669 if (dns
[i
].indexOf(':') > -1)
2675 getIPv4Gateway: function()
2677 var rt
= this._status('route');
2680 for (var i
= 0; i
< rt
.length
; i
++)
2681 if (rt
[i
].target
== '0.0.0.0' && rt
[i
].mask
== 0)
2682 return rt
[i
].nexthop
;
2687 getIPv6Gateway: function()
2689 var rt
= this._status('route');
2692 for (var i
= 0; i
< rt
.length
; i
++)
2693 if (rt
[i
].target
== '::' && rt
[i
].mask
== 0)
2694 return rt
[i
].nexthop
;
2699 getStatistics: function()
2701 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2702 return dev
.getStatistics();
2705 getTrafficHistory: function()
2707 var dev
= this.getDevice() || new L
.NetworkModel
.Device({});
2708 return dev
.getTrafficHistory();
2711 setDevices: function(devs
)
2713 var dev
= this.getPhysdev();
2715 var changed
= false;
2717 if (dev
&& dev
.isBridge())
2718 old_devs
= this.getSubdevices();
2722 if (old_devs
.length
!= devs
.length
)
2725 for (var i
= 0; i
< old_devs
.length
; i
++)
2729 if (dev
instanceof L
.NetworkModel
.Device
)
2732 if (!dev
|| old_devs
[i
].name() != dev
)
2741 for (var i
= 0; i
< old_devs
.length
; i
++)
2742 old_devs
[i
].removeFromInterface(this);
2744 for (var i
= 0; i
< devs
.length
; i
++)
2748 if (!(dev
instanceof L
.NetworkModel
.Device
))
2749 dev
= L
.NetworkModel
.getDevice(dev
);
2752 dev
.attachToInterface(this);
2757 changeProtocol: function(proto
)
2759 var pr
= L
.NetworkModel
._protos
[proto
];
2764 for (var opt
in (this.get() || { }))
2772 this.set(opt
, undefined);
2780 this.set(opt
, pr
.protocol
);
2784 this.set(opt
, undefined);
2790 createForm: function(mapwidget
)
2793 var proto
= self
.getProtocol();
2794 var device
= self
.getDevice();
2797 mapwidget
= L
.cbi
.Map
;
2799 var map
= new mapwidget('network', {
2800 caption
: L
.tr('Configure "%s"').format(self
.name())
2803 var section
= map
.section(L
.cbi
.SingleSection
, self
.name(), {
2809 caption
: L
.tr('General Settings')
2814 caption
: L
.tr('Advanced Settings')
2819 caption
: L
.tr('IPv6')
2824 caption
: L
.tr('Physical Settings')
2828 section
.taboption('general', L
.cbi
.CheckboxValue
, 'auto', {
2829 caption
: L
.tr('Start on boot'),
2834 var pr
= section
.taboption('general', L
.cbi
.ListValue
, 'proto', {
2835 caption
: L
.tr('Protocol')
2838 pr
.ucivalue = function(sid
) {
2839 return self
.get('proto') || 'none';
2842 var ok
= section
.taboption('general', L
.cbi
.ButtonValue
, '_confirm', {
2843 caption
: L
.tr('Really switch?'),
2844 description
: L
.tr('Changing the protocol will clear all configuration for this interface!'),
2845 text
: L
.tr('Change protocol')
2848 ok
.on('click', function(ev
) {
2849 self
.changeProtocol(pr
.formvalue(ev
.data
.sid
));
2850 self
.createForm(mapwidget
).show();
2853 var protos
= L
.NetworkModel
.getProtocols();
2855 for (var i
= 0; i
< protos
.length
; i
++)
2856 pr
.value(protos
[i
].name
, protos
[i
].description
);
2858 proto
.populateForm(section
, self
);
2862 var br
= section
.taboption('physical', L
.cbi
.CheckboxValue
, 'type', {
2863 caption
: L
.tr('Network bridge'),
2864 description
: L
.tr('Merges multiple devices into one logical bridge'),
2871 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_multi', {
2872 caption
: L
.tr('Devices'),
2875 }).depends('type', true);
2877 section
.taboption('physical', L
.cbi
.DeviceList
, '__iface_single', {
2878 caption
: L
.tr('Device'),
2881 }).depends('type', false);
2883 var mac
= section
.taboption('physical', L
.cbi
.InputValue
, 'macaddr', {
2884 caption
: L
.tr('Override MAC'),
2886 placeholder
: device
? device
.getMACAddress() : undefined,
2890 mac
.ucivalue = function(sid
)
2893 return device
.get('macaddr');
2895 return this.callSuper('ucivalue', sid
);
2898 mac
.save = function(sid
)
2900 if (!this.changed(sid
))
2904 device
.set('macaddr', this.formvalue(sid
));
2906 this.callSuper('set', sid
);
2912 section
.taboption('physical', L
.cbi
.InputValue
, 'mtu', {
2913 caption
: L
.tr('Override MTU'),
2915 placeholder
: device
? device
.getMTU() : undefined,
2916 datatype
: 'range(1, 9000)'
2919 section
.taboption('physical', L
.cbi
.InputValue
, 'metric', {
2920 caption
: L
.tr('Override Metric'),
2923 datatype
: 'uinteger'
2926 for (var field
in section
.fields
)
2934 for (var i
= 0; i
< protos
.length
; i
++)
2935 if (protos
[i
].name
!= (this.get('proto') || 'none'))
2936 section
.fields
[field
].depends('proto', protos
[i
].name
);
2940 section
.fields
[field
].depends('proto', this.get('proto') || 'none', true);
2949 this.NetworkModel
.Protocol
= this.NetworkModel
.Interface
.extend({
2950 description
: '__unknown__',
2954 populateForm: function(section
, iface
)
2961 getSystemInfo
: L
.rpc
.declare({
2967 getBoardInfo
: L
.rpc
.declare({
2973 getDiskInfo
: L
.rpc
.declare({
2974 object
: 'luci2.system',
2979 getInfo: function(cb
)
2983 this.getSystemInfo();
2984 this.getBoardInfo();
2987 return L
.rpc
.flush().then(function(info
) {
2990 $.extend(rv
, info
[0]);
2991 $.extend(rv
, info
[1]);
2992 $.extend(rv
, info
[2]);
2999 initList
: L
.rpc
.declare({
3000 object
: 'luci2.system',
3001 method
: 'init_list',
3002 expect
: { initscripts
: [ ] },
3003 filter: function(data
) {
3004 data
.sort(function(a
, b
) { return (a
.start
|| 0) - (b
.start
|| 0) });
3009 initEnabled: function(init
, cb
)
3011 return this.initList().then(function(list
) {
3012 for (var i
= 0; i
< list
.length
; i
++)
3013 if (list
[i
].name
== init
)
3014 return !!list
[i
].enabled
;
3020 initRun
: L
.rpc
.declare({
3021 object
: 'luci2.system',
3022 method
: 'init_action',
3023 params
: [ 'name', 'action' ],
3024 filter: function(data
) {
3029 initStart: function(init
, cb
) { return L
.system
.initRun(init
, 'start', cb
) },
3030 initStop: function(init
, cb
) { return L
.system
.initRun(init
, 'stop', cb
) },
3031 initRestart: function(init
, cb
) { return L
.system
.initRun(init
, 'restart', cb
) },
3032 initReload: function(init
, cb
) { return L
.system
.initRun(init
, 'reload', cb
) },
3033 initEnable: function(init
, cb
) { return L
.system
.initRun(init
, 'enable', cb
) },
3034 initDisable: function(init
, cb
) { return L
.system
.initRun(init
, 'disable', cb
) },
3037 performReboot
: L
.rpc
.declare({
3038 object
: 'luci2.system',
3045 login
: L
.rpc
.declare({
3048 params
: [ 'username', 'password' ],
3052 access
: L
.rpc
.declare({
3055 params
: [ 'scope', 'object', 'function' ],
3056 expect
: { access
: false }
3061 return L
.session
.access('ubus', 'session', 'access');
3064 startHeartbeat: function()
3066 this._hearbeatInterval
= window
.setInterval(function() {
3067 L
.session
.isAlive().then(function(alive
) {
3070 L
.session
.stopHeartbeat();
3075 }, L
.globals
.timeout
* 2);
3078 stopHeartbeat: function()
3080 if (typeof(this._hearbeatInterval
) != 'undefined')
3082 window
.clearInterval(this._hearbeatInterval
);
3083 delete this._hearbeatInterval
;
3090 _fetch_acls
: L
.rpc
.declare({
3096 _fetch_acls_cb: function(acls
)
3098 L
.session
._acls
= acls
;
3101 updateACLs: function()
3103 return L
.session
._fetch_acls()
3104 .then(L
.session
._fetch_acls_cb
);
3107 hasACL: function(scope
, object
, func
)
3109 var acls
= L
.session
._acls
;
3111 if (typeof(func
) == 'undefined')
3112 return (acls
&& acls
[scope
] && acls
[scope
][object
]);
3114 if (acls
&& acls
[scope
] && acls
[scope
][object
])
3115 for (var i
= 0; i
< acls
[scope
][object
].length
; i
++)
3116 if (acls
[scope
][object
][i
] == func
)
3125 saveScrollTop: function()
3127 this._scroll_top
= $(document
).scrollTop();
3130 restoreScrollTop: function()
3132 if (typeof(this._scroll_top
) == 'undefined')
3135 $(document
).scrollTop(this._scroll_top
);
3137 delete this._scroll_top
;
3140 loading: function(enable
)
3142 var win
= $(window
);
3143 var body
= $('body');
3145 var state
= L
.ui
._loading
|| (L
.ui
._loading
= {
3147 .css('z-index', 2000)
3148 .addClass('modal fade')
3149 .append($('<div />')
3150 .addClass('modal-dialog')
3151 .append($('<div />')
3152 .addClass('modal-content luci2-modal-loader')
3153 .append($('<div />')
3154 .addClass('modal-body')
3155 .text(L
.tr('Loading data…')))))
3163 state
.modal
.modal(enable
? 'show' : 'hide');
3166 dialog: function(title
, content
, options
)
3168 var win
= $(window
);
3169 var body
= $('body');
3171 var state
= L
.ui
._dialog
|| (L
.ui
._dialog
= {
3172 dialog
: $('<div />')
3173 .addClass('modal fade')
3174 .append($('<div />')
3175 .addClass('modal-dialog')
3176 .append($('<div />')
3177 .addClass('modal-content')
3178 .append($('<div />')
3179 .addClass('modal-header')
3181 .addClass('modal-title'))
3182 .append($('<div />')
3183 .addClass('modal-body'))
3184 .append($('<div />')
3185 .addClass('modal-footer')
3186 .append(L
.ui
.button(L
.tr('Close'), 'primary')
3188 $(this).parents('div.modal').modal('hide');
3193 if (typeof(options
) != 'object')
3196 if (title
=== false)
3198 state
.dialog
.modal('hide');
3200 return state
.dialog
;
3203 var cnt
= state
.dialog
.children().children().children('div.modal-body');
3204 var ftr
= state
.dialog
.children().children().children('div.modal-footer');
3208 if (options
.style
== 'confirm')
3210 ftr
.append(L
.ui
.button(L
.tr('Ok'), 'primary')
3211 .click(options
.confirm
|| function() { L
.ui
.dialog(false) }));
3213 ftr
.append(L
.ui
.button(L
.tr('Cancel'), 'default')
3214 .click(options
.cancel
|| function() { L
.ui
.dialog(false) }));
3216 else if (options
.style
== 'close')
3218 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3219 .click(options
.close
|| function() { L
.ui
.dialog(false) }));
3221 else if (options
.style
== 'wait')
3223 ftr
.append(L
.ui
.button(L
.tr('Close'), 'primary')
3224 .attr('disabled', true));
3229 state
.dialog
.addClass('wide');
3233 state
.dialog
.removeClass('wide');
3236 state
.dialog
.find('h4:first').text(title
);
3237 state
.dialog
.modal('show');
3239 cnt
.empty().append(content
);
3241 return state
.dialog
;
3244 upload: function(title
, content
, options
)
3246 var state
= L
.ui
._upload
|| (L
.ui
._upload
= {
3248 .attr('method', 'post')
3249 .attr('action', '/cgi-bin/luci-upload')
3250 .attr('enctype', 'multipart/form-data')
3251 .attr('target', 'cbi-fileupload-frame')
3253 .append($('<input />')
3254 .attr('type', 'hidden')
3255 .attr('name', 'sessionid'))
3256 .append($('<input />')
3257 .attr('type', 'hidden')
3258 .attr('name', 'filename'))
3259 .append($('<input />')
3260 .attr('type', 'file')
3261 .attr('name', 'filedata')
3262 .addClass('cbi-input-file'))
3263 .append($('<div />')
3264 .css('width', '100%')
3265 .addClass('progress progress-striped active')
3266 .append($('<div />')
3267 .addClass('progress-bar')
3268 .css('width', '100%')))
3269 .append($('<iframe />')
3270 .addClass('pull-right')
3271 .attr('name', 'cbi-fileupload-frame')
3272 .css('width', '1px')
3273 .css('height', '1px')
3274 .css('visibility', 'hidden')),
3276 finish_cb: function(ev
) {
3277 $(this).off('load');
3279 var body
= (this.contentDocument
|| this.contentWindow
.document
).body
;
3280 if (body
.firstChild
.tagName
.toLowerCase() == 'pre')
3281 body
= body
.firstChild
;
3285 json
= $.parseJSON(body
.innerHTML
);
3288 message
: L
.tr('Invalid server response received'),
3289 error
: [ -1, L
.tr('Invalid data') ]
3295 L
.ui
.dialog(L
.tr('File upload'), [
3296 $('<p />').text(L
.tr('The file upload failed with the server response below:')),
3297 $('<pre />').addClass('alert-message').text(json
.message
|| json
.error
[1]),
3298 $('<p />').text(L
.tr('In case of network problems try uploading the file again.'))
3299 ], { style
: 'close' });
3301 else if (typeof(state
.success_cb
) == 'function')
3303 state
.success_cb(json
);
3307 confirm_cb: function() {
3308 var f
= state
.form
.find('.cbi-input-file');
3309 var b
= state
.form
.find('.progress');
3310 var p
= state
.form
.find('p');
3315 state
.form
.find('iframe').on('load', state
.finish_cb
);
3316 state
.form
.submit();
3320 p
.text(L
.tr('File upload in progress …'));
3322 state
.form
.parent().parent().find('button').prop('disabled', true);
3326 state
.form
.find('.progress').hide();
3327 state
.form
.find('.cbi-input-file').val('').show();
3328 state
.form
.find('p').text(content
|| L
.tr('Select the file to upload and press "%s" to proceed.').format(L
.tr('Ok')));
3330 state
.form
.find('[name=sessionid]').val(L
.globals
.sid
);
3331 state
.form
.find('[name=filename]').val(options
.filename
);
3333 state
.success_cb
= options
.success
;
3335 L
.ui
.dialog(title
|| L
.tr('File upload'), state
.form
, {
3337 confirm
: state
.confirm_cb
3341 reconnect: function()
3343 var protocols
= (location
.protocol
== 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3344 var ports
= (location
.protocol
== 'https:') ? [ 80, location
.port
|| 443 ] : [ location
.port
|| 80 ];
3345 var address
= location
.hostname
.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location
.hostname
+ ']' : location
.hostname
;
3347 var interval
, timeout
;
3350 L
.tr('Waiting for device'), [
3351 $('<p />').text(L
.tr('Please stand by while the device is reconfiguring …')),
3353 .css('width', '100%')
3354 .addClass('progressbar')
3355 .addClass('intermediate')
3356 .append($('<div />')
3357 .css('width', '100%'))
3358 ], { style
: 'wait' }
3361 for (var i
= 0; i
< protocols
.length
; i
++)
3362 images
= images
.add($('<img />').attr('url', protocols
[i
] + '://' + address
+ ':' + ports
[i
]));
3364 //L.network.getNetworkStatus(function(s) {
3365 // for (var i = 0; i < protocols.length; i++)
3367 // for (var j = 0; j < s.length; j++)
3369 // for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3370 // images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3372 // for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3373 // images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3376 //}).then(function() {
3377 images
.on('load', function() {
3378 var url
= this.getAttribute('url');
3379 L
.session
.isAlive().then(function(access
) {
3382 window
.clearTimeout(timeout
);
3383 window
.clearInterval(interval
);
3389 location
.href
= url
;
3394 interval
= window
.setInterval(function() {
3395 images
.each(function() {
3396 this.setAttribute('src', this.getAttribute('url') + L
.globals
.resource
+ '/icons/loading.gif?r=' + Math
.random());
3400 timeout
= window
.setTimeout(function() {
3401 window
.clearInterval(interval
);
3405 L
.tr('Device not responding'),
3406 L
.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3413 login: function(invalid
)
3415 var state
= L
.ui
._login
|| (L
.ui
._login
= {
3418 .attr('method', 'post')
3420 .addClass('alert-message')
3421 .text(L
.tr('Wrong username or password given!')))
3423 .append($('<label />')
3424 .text(L
.tr('Username'))
3425 .append($('<br />'))
3426 .append($('<input />')
3427 .attr('type', 'text')
3428 .attr('name', 'username')
3429 .attr('value', 'root')
3430 .addClass('form-control')
3431 .keypress(function(ev
) {
3432 if (ev
.which
== 10 || ev
.which
== 13)
3436 .append($('<label />')
3437 .text(L
.tr('Password'))
3438 .append($('<br />'))
3439 .append($('<input />')
3440 .attr('type', 'password')
3441 .attr('name', 'password')
3442 .addClass('form-control')
3443 .keypress(function(ev
) {
3444 if (ev
.which
== 10 || ev
.which
== 13)
3448 .text(L
.tr('Enter your username and password above, then click "%s" to proceed.').format(L
.tr('Ok')))),
3450 response_cb: function(response
) {
3451 if (!response
.ubus_rpc_session
)
3457 L
.globals
.sid
= response
.ubus_rpc_session
;
3458 L
.setHash('id', L
.globals
.sid
);
3459 L
.session
.startHeartbeat();
3461 state
.deferred
.resolve();
3465 confirm_cb: function() {
3466 var u
= state
.form
.find('[name=username]').val();
3467 var p
= state
.form
.find('[name=password]').val();
3473 L
.tr('Logging in'), [
3474 $('<p />').text(L
.tr('Log in in progress …')),
3476 .css('width', '100%')
3477 .addClass('progressbar')
3478 .addClass('intermediate')
3479 .append($('<div />')
3480 .css('width', '100%'))
3481 ], { style
: 'wait' }
3484 L
.globals
.sid
= '00000000000000000000000000000000';
3485 L
.session
.login(u
, p
).then(state
.response_cb
);
3489 if (!state
.deferred
|| state
.deferred
.state() != 'pending')
3490 state
.deferred
= $.Deferred();
3492 /* try to find sid from hash */
3493 var sid
= L
.getHash('id');
3494 if (sid
&& sid
.match(/^[a-f0-9]{32}$/))
3496 L
.globals
.sid
= sid
;
3497 L
.session
.isAlive().then(function(access
) {
3500 L
.session
.startHeartbeat();
3501 state
.deferred
.resolve();
3505 L
.setHash('id', undefined);
3510 return state
.deferred
;
3514 state
.form
.find('.alert-message').show();
3516 state
.form
.find('.alert-message').hide();
3518 L
.ui
.dialog(L
.tr('Authorization Required'), state
.form
, {
3520 confirm
: state
.confirm_cb
3523 state
.form
.find('[name=password]').focus();
3525 return state
.deferred
;
3528 cryptPassword
: L
.rpc
.declare({
3532 expect
: { crypt
: '' }
3536 _acl_merge_scope: function(acl_scope
, scope
)
3538 if ($.isArray(scope
))
3540 for (var i
= 0; i
< scope
.length
; i
++)
3541 acl_scope
[scope
[i
]] = true;
3543 else if ($.isPlainObject(scope
))
3545 for (var object_name
in scope
)
3547 if (!$.isArray(scope
[object_name
]))
3550 var acl_object
= acl_scope
[object_name
] || (acl_scope
[object_name
] = { });
3552 for (var i
= 0; i
< scope
[object_name
].length
; i
++)
3553 acl_object
[scope
[object_name
][i
]] = true;
3558 _acl_merge_permission: function(acl_perm
, perm
)
3560 if ($.isPlainObject(perm
))
3562 for (var scope_name
in perm
)
3564 var acl_scope
= acl_perm
[scope_name
] || (acl_perm
[scope_name
] = { });
3565 this._acl_merge_scope(acl_scope
, perm
[scope_name
]);
3570 _acl_merge_group: function(acl_group
, group
)
3572 if ($.isPlainObject(group
))
3574 if (!acl_group
.description
)
3575 acl_group
.description
= group
.description
;
3579 var acl_perm
= acl_group
.read
|| (acl_group
.read
= { });
3580 this._acl_merge_permission(acl_perm
, group
.read
);
3585 var acl_perm
= acl_group
.write
|| (acl_group
.write
= { });
3586 this._acl_merge_permission(acl_perm
, group
.write
);
3591 _acl_merge_tree: function(acl_tree
, tree
)
3593 if ($.isPlainObject(tree
))
3595 for (var group_name
in tree
)
3597 var acl_group
= acl_tree
[group_name
] || (acl_tree
[group_name
] = { });
3598 this._acl_merge_group(acl_group
, tree
[group_name
]);
3603 listAvailableACLs
: L
.rpc
.declare({
3606 expect
: { acls
: [ ] },
3607 filter: function(trees
) {
3609 for (var i
= 0; i
< trees
.length
; i
++)
3610 L
.ui
._acl_merge_tree(acl_tree
, trees
[i
]);
3615 _render_change_indicator: function()
3618 .addClass('nav navbar-nav navbar-right')
3621 .attr('id', 'changes')
3623 .append($('<span />')
3624 .addClass('label label-info'))));
3627 renderMainMenu
: L
.rpc
.declare({
3630 expect
: { menu
: { } },
3631 filter: function(entries
) {
3632 L
.globals
.mainMenu
= new L
.ui
.menu();
3633 L
.globals
.mainMenu
.entries(entries
);
3637 .append(L
.globals
.mainMenu
.render(0, 1))
3638 .append(L
.ui
._render_change_indicator());
3642 renderViewMenu: function()
3646 .append(L
.globals
.mainMenu
.render(2, 900));
3649 renderView: function()
3651 var node
= arguments
[0];
3652 var name
= node
.view
.split(/\//).join('.');
3653 var cname
= L
.toClassName(name
);
3654 var views
= L
.views
|| (L
.views
= { });
3657 for (var i
= 1; i
< arguments
.length
; i
++)
3658 args
.push(arguments
[i
]);
3660 if (L
.globals
.currentView
)
3661 L
.globals
.currentView
.finish();
3663 L
.ui
.renderViewMenu();
3664 L
.setHash('view', node
.view
);
3666 if (views
[cname
] instanceof L
.ui
.view
)
3668 L
.globals
.currentView
= views
[cname
];
3669 return views
[cname
].render
.apply(views
[cname
], args
);
3672 var url
= L
.globals
.resource
+ '/view/' + name
+ '.js';
3674 return $.ajax(url
, {
3678 }).then(function(data
) {
3680 var viewConstructorSource
= (
3681 '(function(L, $) { ' +
3685 ).format(data
, url
);
3687 var viewConstructor
= eval(viewConstructorSource
);
3689 views
[cname
] = new viewConstructor({
3691 acls
: node
.write
|| { }
3694 L
.globals
.currentView
= views
[cname
];
3695 return views
[cname
].render
.apply(views
[cname
], args
);
3698 alert('Unable to instantiate view "%s": %s'.format(url
, e
));
3701 return $.Deferred().resolve();
3705 changeView: function()
3707 var name
= L
.getHash('view');
3708 var node
= L
.globals
.defaultNode
;
3710 if (name
&& L
.globals
.mainMenu
)
3711 node
= L
.globals
.mainMenu
.getNode(name
);
3716 L
.ui
.renderView(node
).then(function() {
3717 L
.ui
.loading(false);
3722 updateHostname: function()
3724 return L
.system
.getBoardInfo().then(function(info
) {
3726 $('#hostname').text(info
.hostname
);
3730 updateChanges: function()
3732 return L
.uci
.changes().then(function(changes
) {
3736 for (var config
in changes
)
3740 for (var i
= 0; i
< changes
[config
].length
; i
++)
3742 var c
= changes
[config
][i
];
3747 log
.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3752 log
.push('uci delete %s.<del>%s</del>'.format(config
, c
[1]));
3754 log
.push('uci delete %s.%s.<del>%s</del>'.format(config
, c
[1], c
[2]));
3759 log
.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3]));
3761 log
.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3765 log
.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config
, c
[2], c
[1]));
3769 log
.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3773 log
.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3778 log
.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2]));
3780 log
.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config
, c
[1], c
[2], c
[3], c
[4]));
3785 html
+= '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config
, log
.join('\n'));
3786 n
+= changes
[config
].length
;
3791 .click(function(ev
) {
3792 L
.ui
.dialog(L
.tr('Staged configuration changes'), html
, {
3794 confirm: function() {
3796 function(code
) { alert('Success with code ' + code
); },
3797 function(code
) { alert('Error with code ' + code
); }
3801 ev
.preventDefault();
3805 .text(L
.trcp('Pending configuration changes', '1 change', '%d changes', n
).format(n
));
3807 $('#changes').children('span').hide();
3816 L
.session
.updateACLs(),
3817 L
.ui
.updateHostname(),
3818 L
.ui
.updateChanges(),
3819 L
.ui
.renderMainMenu(),
3820 L
.NetworkModel
.init()
3822 L
.ui
.renderView(L
.globals
.defaultNode
).then(function() {
3823 L
.ui
.loading(false);
3826 $(window
).on('hashchange', function() {
3832 button: function(label
, style
, title
)
3834 style
= style
|| 'default';
3836 return $('<button />')
3837 .attr('type', 'button')
3838 .attr('title', title
? title
: '')
3839 .addClass('btn btn-' + style
)
3844 this.ui
.AbstractWidget
= Class
.extend({
3845 i18n: function(text
) {
3850 var key
= arguments
[0];
3853 for (var i
= 1; i
< arguments
.length
; i
++)
3854 args
.push(arguments
[i
]);
3856 switch (typeof(this.options
[key
]))
3862 return this.options
[key
].apply(this, args
);
3865 return ''.format
.apply('' + this.options
[key
], args
);
3869 toString: function() {
3870 return $('<div />').append(this.render()).html();
3873 insertInto: function(id
) {
3874 return $(id
).empty().append(this.render());
3877 appendTo: function(id
) {
3878 return $(id
).append(this.render());
3881 on: function(evname
, evfunc
)
3883 var evnames
= L
.toArray(evname
);
3888 for (var i
= 0; i
< evnames
.length
; i
++)
3889 this.events
[evnames
[i
]] = evfunc
;
3894 trigger: function(evname
, evdata
)
3898 var evnames
= L
.toArray(evname
);
3900 for (var i
= 0; i
< evnames
.length
; i
++)
3901 if (this.events
[evnames
[i
]])
3902 this.events
[evnames
[i
]].call(this, evdata
);
3909 this.ui
.view
= this.ui
.AbstractWidget
.extend({
3910 _fetch_template: function()
3912 return $.ajax(L
.globals
.resource
+ '/template/' + this.options
.name
+ '.htm', {
3916 success: function(data
) {
3917 data
= data
.replace(/<%([#:=])?(.+?)%>/g, function(match
, p1
, p2
) {
3918 p2
= p2
.replace(/^\s+/, '').replace(/\s+$/, '');
3928 return L
.globals
[p2
] || '';
3931 return '(?' + match
+ ')';
3935 $('#maincontent').append(data
);
3942 throw "Not implemented";
3947 var container
= $('#maincontent');
3952 container
.append($('<h2 />').append(this.title
));
3954 if (this.description
)
3955 container
.append($('<p />').append(this.description
));
3960 for (var i
= 0; i
< arguments
.length
; i
++)
3961 args
.push(arguments
[i
]);
3963 return this._fetch_template().then(function() {
3964 return L
.deferrable(self
.execute
.apply(self
, args
));
3968 repeat: function(func
, interval
)
3972 if (!self
._timeouts
)
3973 self
._timeouts
= [ ];
3975 var index
= self
._timeouts
.length
;
3977 if (typeof(interval
) != 'number')
3980 var setTimer
, runTimer
;
3982 setTimer = function() {
3984 self
._timeouts
[index
] = window
.setTimeout(runTimer
, interval
);
3987 runTimer = function() {
3988 L
.deferrable(func
.call(self
)).then(setTimer
, setTimer
);
3996 if ($.isArray(this._timeouts
))
3998 for (var i
= 0; i
< this._timeouts
.length
; i
++)
3999 window
.clearTimeout(this._timeouts
[i
]);
4001 delete this._timeouts
;
4006 this.ui
.menu
= this.ui
.AbstractWidget
.extend({
4011 entries: function(entries
)
4013 for (var entry
in entries
)
4015 var path
= entry
.split(/\//);
4016 var node
= this._nodes
;
4018 for (i
= 0; i
< path
.length
; i
++)
4023 if (!node
.childs
[path
[i
]])
4024 node
.childs
[path
[i
]] = { };
4026 node
= node
.childs
[path
[i
]];
4029 $.extend(node
, entries
[entry
]);
4033 _indexcmp: function(a
, b
)
4035 var x
= a
.index
|| 0;
4036 var y
= b
.index
|| 0;
4040 firstChildView: function(node
)
4046 for (var child
in (node
.childs
|| { }))
4047 nodes
.push(node
.childs
[child
]);
4049 nodes
.sort(this._indexcmp
);
4051 for (var i
= 0; i
< nodes
.length
; i
++)
4053 var child
= this.firstChildView(nodes
[i
]);
4056 for (var key
in child
)
4057 if (!node
.hasOwnProperty(key
) && child
.hasOwnProperty(key
))
4058 node
[key
] = child
[key
];
4067 _onclick: function(ev
)
4069 L
.setHash('view', ev
.data
);
4071 ev
.preventDefault();
4075 _render: function(childs
, level
, min
, max
)
4078 for (var node
in childs
)
4080 var child
= this.firstChildView(childs
[node
]);
4082 nodes
.push(childs
[node
]);
4085 nodes
.sort(this._indexcmp
);
4087 var list
= $('<ul />');
4090 list
.addClass('nav').addClass('navbar-nav');
4091 else if (level
== 1)
4092 list
.addClass('dropdown-menu').addClass('navbar-inverse');
4094 for (var i
= 0; i
< nodes
.length
; i
++)
4096 if (!L
.globals
.defaultNode
)
4098 var v
= L
.getHash('view');
4099 if (!v
|| v
== nodes
[i
].view
)
4100 L
.globals
.defaultNode
= nodes
[i
];
4103 var item
= $('<li />')
4106 .text(L
.tr(nodes
[i
].title
)))
4109 if (nodes
[i
].childs
&& level
< max
)
4111 item
.addClass('dropdown');
4114 .addClass('dropdown-toggle')
4115 .attr('data-toggle', 'dropdown')
4116 .append('<b class="caret"></b>');
4118 item
.append(this._render(nodes
[i
].childs
, level
+ 1));
4122 item
.find('a').click(nodes
[i
].view
, this._onclick
);
4129 render: function(min
, max
)
4131 var top
= min
? this.getNode(L
.globals
.defaultNode
.view
, min
) : this._nodes
;
4132 return this._render(top
.childs
, 0, min
, max
);
4135 getNode: function(path
, max
)
4137 var p
= path
.split(/\//);
4138 var n
= this._nodes
;
4140 if (typeof(max
) == 'undefined')
4143 for (var i
= 0; i
< max
; i
++)
4145 if (!n
.childs
[p
[i
]])
4155 this.ui
.table
= this.ui
.AbstractWidget
.extend({
4161 row: function(values
)
4163 if ($.isArray(values
))
4165 this._rows
.push(values
);
4167 else if ($.isPlainObject(values
))
4170 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4172 var col
= this.options
.columns
[i
];
4174 if (typeof col
.key
== 'string')
4175 v
.push(values
[col
.key
]);
4183 rows: function(rows
)
4185 for (var i
= 0; i
< rows
.length
; i
++)
4189 render: function(id
)
4191 var fieldset
= document
.createElement('fieldset');
4192 fieldset
.className
= 'cbi-section';
4194 if (this.options
.caption
)
4196 var legend
= document
.createElement('legend');
4197 $(legend
).append(this.options
.caption
);
4198 fieldset
.appendChild(legend
);
4201 var table
= document
.createElement('table');
4202 table
.className
= 'table table-condensed table-hover';
4204 var has_caption
= false;
4205 var has_description
= false;
4207 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4208 if (this.options
.columns
[i
].caption
)
4213 else if (this.options
.columns
[i
].description
)
4215 has_description
= true;
4221 var tr
= table
.insertRow(-1);
4222 tr
.className
= 'cbi-section-table-titles';
4224 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4226 var col
= this.options
.columns
[i
];
4227 var th
= document
.createElement('th');
4228 th
.className
= 'cbi-section-table-cell';
4233 th
.style
.width
= col
.width
;
4236 th
.style
.textAlign
= col
.align
;
4239 $(th
).append(col
.caption
);
4243 if (has_description
)
4245 var tr
= table
.insertRow(-1);
4246 tr
.className
= 'cbi-section-table-descr';
4248 for (var i
= 0; i
< this.options
.columns
.length
; i
++)
4250 var col
= this.options
.columns
[i
];
4251 var th
= document
.createElement('th');
4252 th
.className
= 'cbi-section-table-cell';
4257 th
.style
.width
= col
.width
;
4260 th
.style
.textAlign
= col
.align
;
4262 if (col
.description
)
4263 $(th
).append(col
.description
);
4267 if (this._rows
.length
== 0)
4269 if (this.options
.placeholder
)
4271 var tr
= table
.insertRow(-1);
4272 var td
= tr
.insertCell(-1);
4273 td
.className
= 'cbi-section-table-cell';
4275 td
.colSpan
= this.options
.columns
.length
;
4276 $(td
).append(this.options
.placeholder
);
4281 for (var i
= 0; i
< this._rows
.length
; i
++)
4283 var tr
= table
.insertRow(-1);
4285 for (var j
= 0; j
< this.options
.columns
.length
; j
++)
4287 var col
= this.options
.columns
[j
];
4288 var td
= tr
.insertCell(-1);
4290 var val
= this._rows
[i
][j
];
4292 if (typeof(val
) == 'undefined')
4293 val
= col
.placeholder
;
4295 if (typeof(val
) == 'undefined')
4299 td
.style
.width
= col
.width
;
4302 td
.style
.textAlign
= col
.align
;
4304 if (typeof col
.format
== 'string')
4305 $(td
).append(col
.format
.format(val
));
4306 else if (typeof col
.format
== 'function')
4307 $(td
).append(col
.format(val
, i
));
4315 fieldset
.appendChild(table
);
4321 this.ui
.progress
= this.ui
.AbstractWidget
.extend({
4324 var vn
= parseInt(this.options
.value
) || 0;
4325 var mn
= parseInt(this.options
.max
) || 100;
4326 var pc
= Math
.floor((100 / mn
) * vn
);
4330 if (typeof(this.options
.format
) == 'string')
4331 text
= this.options
.format
.format(this.options
.value
, this.options
.max
, pc
);
4332 else if (typeof(this.options
.format
) == 'function')
4333 text
= this.options
.format(pc
);
4335 text
= '%.2f%%'.format(pc
);
4338 .addClass('progress')
4339 .append($('<div />')
4340 .addClass('progress-bar')
4341 .addClass('progress-bar-info')
4342 .css('width', pc
+ '%'))
4343 .append($('<small />')
4348 this.ui
.devicebadge
= this.ui
.AbstractWidget
.extend({
4351 var l2dev
= this.options
.l2_device
|| this.options
.device
;
4352 var l3dev
= this.options
.l3_device
;
4353 var dev
= l3dev
|| l2dev
|| '?';
4355 var span
= document
.createElement('span');
4356 span
.className
= 'badge';
4358 if (typeof(this.options
.signal
) == 'number' ||
4359 typeof(this.options
.noise
) == 'number')
4362 if (typeof(this.options
.signal
) != 'undefined' &&
4363 typeof(this.options
.noise
) != 'undefined')
4365 var q
= (-1 * (this.options
.noise
- this.options
.signal
)) / 5;
4378 span
.appendChild(document
.createElement('img'));
4379 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/signal-' + r
+ '.png';
4382 span
.title
= L
.tr('No signal');
4384 span
.title
= '%s: %d %s / %s: %d %s'.format(
4385 L
.tr('Signal'), this.options
.signal
, L
.tr('dBm'),
4386 L
.tr('Noise'), this.options
.noise
, L
.tr('dBm')
4391 var type
= 'ethernet';
4392 var desc
= L
.tr('Ethernet device');
4397 desc
= L
.tr('Tunnel interface');
4399 else if (dev
.indexOf('br-') == 0)
4402 desc
= L
.tr('Bridge');
4404 else if (dev
.indexOf('.') > 0)
4407 desc
= L
.tr('VLAN interface');
4409 else if (dev
.indexOf('wlan') == 0 ||
4410 dev
.indexOf('ath') == 0 ||
4411 dev
.indexOf('wl') == 0)
4414 desc
= L
.tr('Wireless Network');
4417 span
.appendChild(document
.createElement('img'));
4418 span
.lastChild
.src
= L
.globals
.resource
+ '/icons/' + type
+ (this.options
.up
? '' : '_disabled') + '.png';
4422 $(span
).append(' ');
4423 $(span
).append(dev
);
4429 var type = function(f
, l
)
4439 L
.cbi
.validation
.message
= L
.tr(msg
);
4442 compile: function(code
)
4447 var types
= L
.cbi
.validation
.types
;
4452 for (var i
= 0; i
< code
.length
; i
++)
4460 switch (code
.charCodeAt(i
))
4472 var label
= code
.substring(pos
, i
);
4473 label
= label
.replace(/\\(.)/g, '$1');
4474 label
= label
.replace(/^[ \t]+/g, '');
4475 label
= label
.replace(/[ \t]+$/g, '');
4477 if (label
&& !isNaN(label
))
4479 stack
.push(parseFloat(label
));
4481 else if (label
.match(/^(['"]).*\1$/))
4483 stack
.push(label
.replace(/^(['"])(.*)\1$/, '$2'));
4485 else if (typeof types
[label
] == 'function')
4487 stack
.push(types
[label
]);
4492 throw "Syntax error, unhandled token '"+label
+"'";
4497 depth
+= (code
.charCodeAt(i
) == 40);
4503 if (typeof stack
[stack
.length
-2] != 'function')
4504 throw "Syntax error, argument list follows non-function";
4506 stack
[stack
.length
-1] =
4507 L
.cbi
.validation
.compile(code
.substring(pos
, i
));
4520 var validation
= this.cbi
.validation
;
4522 validation
.types
= {
4523 'integer': function()
4525 if (this.match(/^-?[0-9]+$/) != null)
4528 validation
.i18n('Must be a valid integer');
4532 'uinteger': function()
4534 if (validation
.types
['integer'].apply(this) && (this >= 0))
4537 validation
.i18n('Must be a positive integer');
4543 if (!isNaN(parseFloat(this)))
4546 validation
.i18n('Must be a valid number');
4550 'ufloat': function()
4552 if (validation
.types
['float'].apply(this) && (this >= 0))
4555 validation
.i18n('Must be a positive number');
4559 'ipaddr': function()
4561 if (validation
.types
['ip4addr'].apply(this) ||
4562 validation
.types
['ip6addr'].apply(this))
4565 validation
.i18n('Must be a valid IP address');
4569 'ip4addr': function()
4571 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
4573 if ((RegExp
.$1 >= 0) && (RegExp
.$1 <= 255) &&
4574 (RegExp
.$2 >= 0) && (RegExp
.$2 <= 255) &&
4575 (RegExp
.$3 >= 0) && (RegExp
.$3 <= 255) &&
4576 (RegExp
.$4 >= 0) && (RegExp
.$4 <= 255) &&
4577 ((RegExp
.$6.indexOf('.') < 0)
4578 ? ((RegExp
.$6 >= 0) && (RegExp
.$6 <= 32))
4579 : (validation
.types
['ip4addr'].apply(RegExp
.$6))))
4583 validation
.i18n('Must be a valid IPv4 address');
4587 'ip6addr': function()
4589 if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
4591 if (!RegExp
.$2 || ((RegExp
.$3 >= 0) && (RegExp
.$3 <= 128)))
4593 var addr
= RegExp
.$1;
4600 if (addr
.indexOf('.') > 0)
4602 var off
= addr
.lastIndexOf(':');
4604 if (!(off
&& validation
.types
['ip4addr'].apply(addr
.substr(off
+1))))
4606 validation
.i18n('Must be a valid IPv6 address');
4610 addr
= addr
.substr(0, off
) + ':0:0';
4613 if (addr
.indexOf('::') >= 0)
4618 for (var i
= 1; i
< (addr
.length
-1); i
++)
4619 if (addr
.charAt(i
) == ':')
4624 validation
.i18n('Must be a valid IPv6 address');
4628 for (var i
= 0; i
< (7 - colons
); i
++)
4631 if (addr
.match(/^(.*?)::(.*?)$/))
4632 addr
= (RegExp
.$1 ? RegExp
.$1 + ':' : '') + fill
+
4633 (RegExp
.$2 ? ':' + RegExp
.$2 : '');
4636 if (addr
.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
4639 validation
.i18n('Must be a valid IPv6 address');
4644 validation
.i18n('Must be a valid IPv6 address');
4650 if (validation
.types
['integer'].apply(this) &&
4651 (this >= 0) && (this <= 65535))
4654 validation
.i18n('Must be a valid port number');
4658 'portrange': function()
4660 if (this.match(/^(\d+)-(\d+)$/))
4665 if (validation
.types
['port'].apply(p1
) &&
4666 validation
.types
['port'].apply(p2
) &&
4667 (parseInt(p1
) <= parseInt(p2
)))
4670 else if (validation
.types
['port'].apply(this))
4675 validation
.i18n('Must be a valid port range');
4679 'macaddr': function()
4681 if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4684 validation
.i18n('Must be a valid MAC address');
4690 if (validation
.types
['hostname'].apply(this) ||
4691 validation
.types
['ipaddr'].apply(this))
4694 validation
.i18n('Must be a valid hostname or IP address');
4698 'hostname': function()
4700 if ((this.length
<= 253) &&
4701 ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4702 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4703 this.match(/[^0-9.]/)))))
4706 validation
.i18n('Must be a valid host name');
4710 'network': function()
4712 if (validation
.types
['uciname'].apply(this) ||
4713 validation
.types
['host'].apply(this))
4716 validation
.i18n('Must be a valid network name');
4720 'wpakey': function()
4724 if ((v
.length
== 64)
4725 ? (v
.match(/^[a-fA-F0-9]{64}$/) != null)
4726 : ((v
.length
>= 8) && (v
.length
<= 63)))
4729 validation
.i18n('Must be a valid WPA key');
4733 'wepkey': function()
4737 if (v
.substr(0,2) == 's:')
4740 if (((v
.length
== 10) || (v
.length
== 26))
4741 ? (v
.match(/^[a-fA-F0-9]{10,26}$/) != null)
4742 : ((v
.length
== 5) || (v
.length
== 13)))
4745 validation
.i18n('Must be a valid WEP key');
4749 'uciname': function()
4751 if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4754 validation
.i18n('Must be a valid UCI identifier');
4758 'range': function(min
, max
)
4760 var val
= parseFloat(this);
4762 if (validation
.types
['integer'].apply(this) &&
4763 !isNaN(min
) && !isNaN(max
) && ((val
>= min
) && (val
<= max
)))
4766 validation
.i18n('Must be a number between %d and %d');
4770 'min': function(min
)
4772 var val
= parseFloat(this);
4774 if (validation
.types
['integer'].apply(this) &&
4775 !isNaN(min
) && !isNaN(val
) && (val
>= min
))
4778 validation
.i18n('Must be a number greater or equal to %d');
4782 'max': function(max
)
4784 var val
= parseFloat(this);
4786 if (validation
.types
['integer'].apply(this) &&
4787 !isNaN(max
) && !isNaN(val
) && (val
<= max
))
4790 validation
.i18n('Must be a number lower or equal to %d');
4794 'rangelength': function(min
, max
)
4796 var val
= '' + this;
4798 if (!isNaN(min
) && !isNaN(max
) &&
4799 (val
.length
>= min
) && (val
.length
<= max
))
4802 validation
.i18n('Must be between %d and %d characters');
4806 'minlength': function(min
)
4808 var val
= '' + this;
4810 if (!isNaN(min
) && (val
.length
>= min
))
4813 validation
.i18n('Must be at least %d characters');
4817 'maxlength': function(max
)
4819 var val
= '' + this;
4821 if (!isNaN(max
) && (val
.length
<= max
))
4824 validation
.i18n('Must be at most %d characters');
4832 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4834 delete validation
.message
;
4836 if (typeof(arguments
[i
]) != 'function')
4838 if (arguments
[i
] == this)
4842 else if (arguments
[i
].apply(this, arguments
[i
+1]))
4847 if (validation
.message
)
4848 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4851 validation
.message
= msgs
.join( L
.tr(' - or - '));
4859 for (var i
= 0; i
< arguments
.length
; i
+= 2)
4861 delete validation
.message
;
4863 if (typeof arguments
[i
] != 'function')
4865 if (arguments
[i
] != this)
4869 else if (!arguments
[i
].apply(this, arguments
[i
+1]))
4874 if (validation
.message
)
4875 msgs
.push(validation
.message
.format
.apply(validation
.message
, arguments
[i
+1]));
4878 validation
.message
= msgs
.join(', ');
4884 return validation
.types
['or'].apply(
4885 this.replace(/^[ \t]*![ \t]*/, ''), arguments
);
4888 'list': function(subvalidator
, subargs
)
4890 if (typeof subvalidator
!= 'function')
4893 var tokens
= this.match(/[^ \t]+/g);
4894 for (var i
= 0; i
< tokens
.length
; i
++)
4895 if (!subvalidator
.apply(tokens
[i
], subargs
))
4901 'phonedigit': function()
4903 if (this.match(/^[0-9\*#!\.]+$/) != null)
4906 validation
.i18n('Must be a valid phone number digit');
4910 'string': function()
4917 this.cbi
.AbstractValue
= this.ui
.AbstractWidget
.extend({
4918 init: function(name
, options
)
4921 this.instance
= { };
4922 this.dependencies
= [ ];
4923 this.rdependency
= { };
4925 this.options
= L
.defaults(options
, {
4935 return this.section
.id('field', sid
|| '__unknown__', this.name
);
4938 render: function(sid
, condensed
)
4940 var i
= this.instance
[sid
] = { };
4942 i
.top
= $('<div />');
4946 i
.top
.addClass('form-group');
4948 if (typeof(this.options
.caption
) == 'string')
4950 .addClass('col-lg-2 control-label')
4951 .attr('for', this.id(sid
))
4952 .text(this.options
.caption
)
4956 i
.error
= $('<div />')
4958 .addClass('label label-danger');
4960 i
.widget
= $('<div />')
4962 .append(this.widget(sid
))
4968 i
.widget
.addClass('col-lg-5');
4971 .addClass('col-lg-5')
4972 .text((typeof(this.options
.description
) == 'string') ? this.options
.description
: '')
4979 active: function(sid
)
4981 return (this.instance
[sid
] && !this.instance
[sid
].disabled
);
4984 ucipath: function(sid
)
4987 config
: (this.options
.uci_package
|| this.map
.uci_package
),
4988 section
: (this.options
.uci_section
|| sid
),
4989 option
: (this.options
.uci_option
|| this.name
)
4993 ucivalue: function(sid
)
4995 var uci
= this.ucipath(sid
);
4996 var val
= this.map
.get(uci
.config
, uci
.section
, uci
.option
);
4998 if (typeof(val
) == 'undefined')
4999 return this.options
.initial
;
5004 formvalue: function(sid
)
5006 var v
= $('#' + this.id(sid
)).val();
5007 return (v
=== '') ? undefined : v
;
5010 textvalue: function(sid
)
5012 var v
= this.formvalue(sid
);
5014 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5015 v
= this.ucivalue(sid
);
5017 if (typeof(v
) == 'undefined' || ($.isArray(v
) && !v
.length
))
5018 v
= this.options
.placeholder
;
5020 if (typeof(v
) == 'undefined' || v
=== '')
5023 if (typeof(v
) == 'string' && $.isArray(this.choices
))
5025 for (var i
= 0; i
< this.choices
.length
; i
++)
5026 if (v
=== this.choices
[i
][0])
5027 return this.choices
[i
][1];
5029 else if (v
=== true)
5031 else if (v
=== false)
5033 else if ($.isArray(v
))
5034 return v
.join(', ');
5039 changed: function(sid
)
5041 var a
= this.ucivalue(sid
);
5042 var b
= this.formvalue(sid
);
5044 if (typeof(a
) != typeof(b
))
5047 if (typeof(a
) == 'object')
5049 if (a
.length
!= b
.length
)
5052 for (var i
= 0; i
< a
.length
; i
++)
5064 var uci
= this.ucipath(sid
);
5066 if (this.instance
[sid
].disabled
)
5068 if (!this.options
.keep
)
5069 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5074 var chg
= this.changed(sid
);
5075 var val
= this.formvalue(sid
);
5078 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
);
5083 _ev_validate: function(ev
)
5087 var val
= d
.elem
.val();
5088 var vstack
= d
.vstack
;
5090 if (vstack
&& typeof(vstack
[0]) == 'function')
5092 delete validation
.message
;
5094 if ((val
.length
== 0 && !d
.opt
))
5096 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
5097 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5099 d
.inst
.error
.text(L
.tr('Field must not be empty')).show();
5102 else if (val
.length
> 0 && !vstack
[0].apply(val
, vstack
[1]))
5104 d
.elem
.parents('div.form-group, td').first().addClass('luci2-form-error');
5105 d
.elem
.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5107 d
.inst
.error
.text(validation
.message
.format
.apply(validation
.message
, vstack
[1])).show();
5112 d
.elem
.parents('div.form-group, td').first().removeClass('luci2-form-error');
5113 d
.elem
.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
5115 if (d
.multi
&& d
.inst
.widget
&& d
.inst
.widget
.find('input.error, select.error').length
> 0)
5118 d
.inst
.error
.text('').hide();
5124 for (var field
in d
.self
.rdependency
)
5125 d
.self
.rdependency
[field
].toggle(d
.sid
);
5127 d
.self
.section
.tabtoggle(d
.sid
);
5133 validator: function(sid
, elem
, multi
)
5140 inst
: this.instance
[sid
],
5141 opt
: this.options
.optional
5145 for (var evname
in this.events
)
5146 elem
.on(evname
, evdata
, this.events
[evname
]);
5148 if (typeof(this.options
.datatype
) == 'undefined' && $.isEmptyObject(this.rdependency
))
5152 if (typeof(this.options
.datatype
) == 'string')
5155 evdata
.vstack
= L
.cbi
.validation
.compile(this.options
.datatype
);
5158 else if (typeof(this.options
.datatype
) == 'function')
5160 var vfunc
= this.options
.datatype
;
5161 evdata
.vstack
= [ function(elem
) {
5162 var rv
= vfunc(this, elem
);
5164 validation
.message
= rv
;
5165 return (rv
=== true);
5169 if (elem
.prop('tagName') == 'SELECT')
5171 elem
.change(evdata
, this._ev_validate
);
5173 else if (elem
.prop('tagName') == 'INPUT' && elem
.attr('type') == 'checkbox')
5175 elem
.click(evdata
, this._ev_validate
);
5176 elem
.blur(evdata
, this._ev_validate
);
5180 elem
.keyup(evdata
, this._ev_validate
);
5181 elem
.blur(evdata
, this._ev_validate
);
5184 elem
.attr('cbi-validate', true).on('validate', evdata
, this._ev_validate
);
5189 validate: function(sid
)
5191 var i
= this.instance
[sid
];
5193 i
.widget
.find('[cbi-validate]').trigger('validate');
5195 return (i
.disabled
|| i
.error
.text() == '');
5198 depends: function(d
, v
, add
)
5205 for (var i
= 0; i
< d
.length
; i
++)
5207 if (typeof(d
[i
]) == 'string')
5209 else if (d
[i
] instanceof L
.cbi
.AbstractValue
)
5210 dep
[d
[i
].name
] = true;
5213 else if (d
instanceof L
.cbi
.AbstractValue
)
5216 dep
[d
.name
] = (typeof(v
) == 'undefined') ? true : v
;
5218 else if (typeof(d
) == 'object')
5222 else if (typeof(d
) == 'string')
5225 dep
[d
] = (typeof(v
) == 'undefined') ? true : v
;
5228 if (!dep
|| $.isEmptyObject(dep
))
5231 for (var field
in dep
)
5233 var f
= this.section
.fields
[field
];
5235 f
.rdependency
[this.name
] = this;
5240 if ($.isEmptyObject(dep
))
5243 if (!add
|| !this.dependencies
.length
)
5244 this.dependencies
.push(dep
);
5246 for (var i
= 0; i
< this.dependencies
.length
; i
++)
5247 $.extend(this.dependencies
[i
], dep
);
5252 toggle: function(sid
)
5254 var d
= this.dependencies
;
5255 var i
= this.instance
[sid
];
5260 for (var n
= 0; n
< d
.length
; n
++)
5264 for (var field
in d
[n
])
5266 var val
= this.section
.fields
[field
].formvalue(sid
);
5267 var cmp
= d
[n
][field
];
5269 if (typeof(cmp
) == 'boolean')
5271 if (cmp
== (typeof(val
) == 'undefined' || val
=== '' || val
=== false))
5277 else if (typeof(cmp
) == 'string' || typeof(cmp
) == 'number')
5285 else if (typeof(cmp
) == 'function')
5293 else if (cmp
instanceof RegExp
)
5318 i
.top
.is(':visible') ? i
.top
.fadeOut() : i
.top
.hide();
5325 this.cbi
.CheckboxValue
= this.cbi
.AbstractValue
.extend({
5326 widget: function(sid
)
5328 var o
= this.options
;
5330 if (typeof(o
.enabled
) == 'undefined') o
.enabled
= '1';
5331 if (typeof(o
.disabled
) == 'undefined') o
.disabled
= '0';
5333 var i
= $('<input />')
5334 .attr('id', this.id(sid
))
5335 .attr('type', 'checkbox')
5336 .prop('checked', this.ucivalue(sid
));
5339 .addClass('checkbox')
5340 .append(this.validator(sid
, i
));
5343 ucivalue: function(sid
)
5345 var v
= this.callSuper('ucivalue', sid
);
5347 if (typeof(v
) == 'boolean')
5350 return (v
== this.options
.enabled
);
5353 formvalue: function(sid
)
5355 var v
= $('#' + this.id(sid
)).prop('checked');
5357 if (typeof(v
) == 'undefined')
5358 return !!this.options
.initial
;
5365 var uci
= this.ucipath(sid
);
5367 if (this.instance
[sid
].disabled
)
5369 if (!this.options
.keep
)
5370 return this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5375 var chg
= this.changed(sid
);
5376 var val
= this.formvalue(sid
);
5380 if (this.options
.optional
&& val
== this.options
.initial
)
5381 this.map
.set(uci
.config
, uci
.section
, uci
.option
, undefined);
5383 this.map
.set(uci
.config
, uci
.section
, uci
.option
, val
? this.options
.enabled
: this.options
.disabled
);
5390 this.cbi
.InputValue
= this.cbi
.AbstractValue
.extend({
5391 widget: function(sid
)
5393 var i
= $('<input />')
5394 .addClass('form-control')
5395 .attr('id', this.id(sid
))
5396 .attr('type', 'text')
5397 .attr('placeholder', this.options
.placeholder
)
5398 .val(this.ucivalue(sid
));
5400 return this.validator(sid
, i
);
5404 this.cbi
.PasswordValue
= this.cbi
.AbstractValue
.extend({
5405 widget: function(sid
)
5407 var i
= $('<input />')
5408 .addClass('form-control')
5409 .attr('id', this.id(sid
))
5410 .attr('type', 'password')
5411 .attr('placeholder', this.options
.placeholder
)
5412 .val(this.ucivalue(sid
));
5414 var t
= $('<span />')
5415 .addClass('input-group-btn')
5416 .append(L
.ui
.button(L
.tr('Reveal'), 'default')
5417 .click(function(ev
) {
5419 var i
= b
.parent().prev();
5420 var t
= i
.attr('type');
5421 b
.text(t
== 'password' ? L
.tr('Hide') : L
.tr('Reveal'));
5422 i
.attr('type', (t
== 'password') ? 'text' : 'password');
5426 this.validator(sid
, i
);
5429 .addClass('input-group')
5435 this.cbi
.ListValue
= this.cbi
.AbstractValue
.extend({
5436 widget: function(sid
)
5438 var s
= $('<select />')
5439 .addClass('form-control');
5441 if (this.options
.optional
&& !this.has_empty
)
5444 .text(L
.tr('-- Please choose --'))
5448 for (var i
= 0; i
< this.choices
.length
; i
++)
5450 .attr('value', this.choices
[i
][0])
5451 .text(this.choices
[i
][1])
5454 s
.attr('id', this.id(sid
)).val(this.ucivalue(sid
));
5456 return this.validator(sid
, s
);
5459 value: function(k
, v
)
5465 this.has_empty
= true;
5467 this.choices
.push([k
, v
|| k
]);
5472 this.cbi
.MultiValue
= this.cbi
.ListValue
.extend({
5473 widget: function(sid
)
5475 var v
= this.ucivalue(sid
);
5476 var t
= $('<div />').attr('id', this.id(sid
));
5479 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5482 for (var i
= 0; i
< v
.length
; i
++)
5486 for (var i
= 0; i
< this.choices
.length
; i
++)
5489 .addClass('checkbox')
5490 .append($('<input />')
5491 .attr('type', 'checkbox')
5492 .attr('value', this.choices
[i
][0])
5493 .prop('checked', s
[this.choices
[i
][0]]))
5494 .append(this.choices
[i
][1])
5501 formvalue: function(sid
)
5504 var fields
= $('#' + this.id(sid
) + ' > label > input');
5506 for (var i
= 0; i
< fields
.length
; i
++)
5507 if (fields
[i
].checked
)
5508 rv
.push(fields
[i
].getAttribute('value'));
5513 textvalue: function(sid
)
5515 var v
= this.formvalue(sid
);
5519 for (var i
= 0; i
< this.choices
.length
; i
++)
5520 c
[this.choices
[i
][0]] = this.choices
[i
][1];
5524 for (var i
= 0; i
< v
.length
; i
++)
5525 t
.push(c
[v
[i
]] || v
[i
]);
5527 return t
.join(', ');
5531 this.cbi
.ComboBox
= this.cbi
.AbstractValue
.extend({
5532 _change: function(ev
)
5535 var self
= ev
.data
.self
;
5537 if (s
.selectedIndex
== (s
.options
.length
- 1))
5539 ev
.data
.select
.hide();
5540 ev
.data
.input
.show().focus();
5541 ev
.data
.input
.val('');
5543 else if (self
.options
.optional
&& s
.selectedIndex
== 0)
5545 ev
.data
.input
.val('');
5549 ev
.data
.input
.val(ev
.data
.select
.val());
5552 ev
.stopPropagation();
5558 var val
= this.value
;
5559 var self
= ev
.data
.self
;
5561 ev
.data
.select
.empty();
5563 if (self
.options
.optional
&& !self
.has_empty
)
5566 .text(L
.tr('-- please choose --'))
5567 .appendTo(ev
.data
.select
);
5570 for (var i
= 0; i
< self
.choices
.length
; i
++)
5572 if (self
.choices
[i
][0] == val
)
5576 .attr('value', self
.choices
[i
][0])
5577 .text(self
.choices
[i
][1])
5578 .appendTo(ev
.data
.select
);
5581 if (!seen
&& val
!= '')
5585 .appendTo(ev
.data
.select
);
5589 .text(L
.tr('-- custom --'))
5590 .appendTo(ev
.data
.select
);
5592 ev
.data
.input
.hide();
5593 ev
.data
.select
.val(val
).show().blur();
5596 _enter: function(ev
)
5601 ev
.preventDefault();
5602 ev
.data
.self
._blur(ev
);
5606 widget: function(sid
)
5608 var d
= $('<div />')
5609 .attr('id', this.id(sid
));
5611 var t
= $('<input />')
5612 .addClass('form-control')
5613 .attr('type', 'text')
5617 var s
= $('<select />')
5618 .addClass('form-control')
5627 s
.change(evdata
, this._change
);
5628 t
.blur(evdata
, this._blur
);
5629 t
.keydown(evdata
, this._enter
);
5631 t
.val(this.ucivalue(sid
));
5634 this.validator(sid
, t
);
5635 this.validator(sid
, s
);
5640 value: function(k
, v
)
5646 this.has_empty
= true;
5648 this.choices
.push([k
, v
|| k
]);
5652 formvalue: function(sid
)
5654 var v
= $('#' + this.id(sid
)).children('input').val();
5655 return (v
== '') ? undefined : v
;
5659 this.cbi
.DynamicList
= this.cbi
.ComboBox
.extend({
5660 _redraw: function(focus
, add
, del
, s
)
5662 var v
= s
.values
|| [ ];
5665 $(s
.parent
).children('div.input-group').children('input').each(function(i
) {
5667 v
.push(this.value
|| '');
5670 $(s
.parent
).empty();
5675 v
.splice(focus
, 0, '');
5677 else if (v
.length
== 0)
5683 for (var i
= 0; i
< v
.length
; i
++)
5690 remove
: ((i
+1) < v
.length
)
5695 btn
= L
.ui
.button('–', 'danger').click(evdata
, this._btnclick
);
5697 btn
= L
.ui
.button('+', 'success').click(evdata
, this._btnclick
);
5701 var txt
= $('<input />')
5702 .addClass('form-control')
5703 .attr('type', 'text')
5706 var sel
= $('<select />')
5707 .addClass('form-control');
5710 .addClass('input-group')
5713 .append($('<span />')
5714 .addClass('input-group-btn')
5716 .appendTo(s
.parent
);
5718 evdata
.input
= this.validator(s
.sid
, txt
, true);
5719 evdata
.select
= this.validator(s
.sid
, sel
, true);
5721 sel
.change(evdata
, this._change
);
5722 txt
.blur(evdata
, this._blur
);
5723 txt
.keydown(evdata
, this._keydown
);
5728 if (i
== focus
|| -(i
+1) == focus
)
5735 var f
= $('<input />')
5736 .attr('type', 'text')
5738 .attr('placeholder', (i
== 0) ? this.options
.placeholder
: '')
5739 .addClass('form-control')
5740 .keydown(evdata
, this._keydown
)
5741 .keypress(evdata
, this._keypress
)
5745 .addClass('input-group')
5747 .append($('<span />')
5748 .addClass('input-group-btn')
5750 .appendTo(s
.parent
);
5756 else if (-(i
+1) == focus
)
5760 /* force cursor to end */
5766 evdata
.input
= this.validator(s
.sid
, f
, true);
5777 _keypress: function(ev
)
5781 /* backspace, delete */
5784 if (ev
.data
.input
.val() == '')
5786 ev
.preventDefault();
5792 /* enter, arrow up, arrow down */
5796 ev
.preventDefault();
5803 _keydown: function(ev
)
5805 var input
= ev
.data
.input
;
5809 /* backspace, delete */
5812 if (input
.val().length
== 0)
5814 ev
.preventDefault();
5816 var index
= ev
.data
.index
;
5822 ev
.data
.self
._redraw(focus
, -1, index
, ev
.data
);
5830 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5835 var prev
= input
.parent().prevAll('div.input-group:first').children('input');
5836 if (prev
.is(':visible'))
5839 prev
.next('select').focus();
5844 var next
= input
.parent().nextAll('div.input-group:first').children('input');
5845 if (next
.is(':visible'))
5848 next
.next('select').focus();
5855 _btnclick: function(ev
)
5857 if (!this.getAttribute('disabled'))
5861 var index
= ev
.data
.index
;
5862 ev
.data
.self
._redraw(-index
, -1, index
, ev
.data
);
5866 ev
.data
.self
._redraw(NaN
, ev
.data
.index
, -1, ev
.data
);
5873 widget: function(sid
)
5875 this.options
.optional
= true;
5877 var v
= this.ucivalue(sid
);
5880 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5882 var d
= $('<div />')
5883 .attr('id', this.id(sid
))
5884 .addClass('cbi-input-dynlist');
5886 this._redraw(NaN
, -1, -1, {
5896 ucivalue: function(sid
)
5898 var v
= this.callSuper('ucivalue', sid
);
5901 v
= (typeof(v
) != 'undefined') ? v
.toString().split(/\s+/) : [ ];
5906 formvalue: function(sid
)
5909 var fields
= $('#' + this.id(sid
) + ' input');
5911 for (var i
= 0; i
< fields
.length
; i
++)
5912 if (typeof(fields
[i
].value
) == 'string' && fields
[i
].value
.length
)
5913 rv
.push(fields
[i
].value
);
5919 this.cbi
.DummyValue
= this.cbi
.AbstractValue
.extend({
5920 widget: function(sid
)
5923 .addClass('form-control-static')
5924 .attr('id', this.id(sid
))
5925 .html(this.ucivalue(sid
));
5928 formvalue: function(sid
)
5930 return this.ucivalue(sid
);
5934 this.cbi
.ButtonValue
= this.cbi
.AbstractValue
.extend({
5935 widget: function(sid
)
5937 this.options
.optional
= true;
5939 var btn
= $('<button />')
5940 .addClass('btn btn-default')
5941 .attr('id', this.id(sid
))
5942 .attr('type', 'button')
5943 .text(this.label('text'));
5945 return this.validator(sid
, btn
);
5949 this.cbi
.NetworkList
= this.cbi
.AbstractValue
.extend({
5952 return L
.NetworkModel
.init();
5955 _device_icon: function(dev
)
5958 .attr('src', dev
.icon())
5959 .attr('title', '%s (%s)'.format(dev
.description(), dev
.name() || '?'));
5962 widget: function(sid
)
5964 var id
= this.id(sid
);
5965 var ul
= $('<ul />')
5967 .addClass('list-unstyled');
5969 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
5970 var value
= this.ucivalue(sid
);
5973 if (!this.options
.multiple
)
5974 check
[value
] = true;
5976 for (var i
= 0; i
< value
.length
; i
++)
5977 check
[value
[i
]] = true;
5979 var interfaces
= L
.NetworkModel
.getInterfaces();
5981 for (var i
= 0; i
< interfaces
.length
; i
++)
5983 var iface
= interfaces
[i
];
5984 var badge
= $('<span />')
5986 .text('%s: '.format(iface
.name()));
5988 var dev
= iface
.getDevice();
5989 var subdevs
= iface
.getSubdevices();
5992 for (var j
= 0; j
< subdevs
.length
; j
++)
5993 badge
.append(this._device_icon(subdevs
[j
]));
5995 badge
.append(this._device_icon(dev
));
5997 badge
.append($('<em />').text(L
.tr('(No devices attached)')));
6000 .append($('<label />')
6001 .addClass(itype
+ ' inline')
6002 .append($('<input />')
6003 .attr('name', itype
+ id
)
6004 .attr('type', itype
)
6005 .attr('value', iface
.name())
6006 .prop('checked', !!check
[iface
.name()]))
6011 if (!this.options
.multiple
)
6014 .append($('<label />')
6015 .addClass(itype
+ ' inline text-muted')
6016 .append($('<input />')
6017 .attr('name', itype
+ id
)
6018 .attr('type', itype
)
6020 .prop('checked', $.isEmptyObject(check
)))
6021 .append(L
.tr('unspecified')))
6028 ucivalue: function(sid
)
6030 var v
= this.callSuper('ucivalue', sid
);
6032 if (!this.options
.multiple
)
6038 else if (typeof(v
) == 'string')
6041 return v
? v
[0] : undefined;
6048 if (typeof(v
) == 'string')
6049 v
= v
.match(/\S+/g);
6055 formvalue: function(sid
)
6057 var inputs
= $('#' + this.id(sid
) + ' input');
6059 if (!this.options
.multiple
)
6061 for (var i
= 0; i
< inputs
.length
; i
++)
6062 if (inputs
[i
].checked
&& inputs
[i
].value
!== '')
6063 return inputs
[i
].value
;
6070 for (var i
= 0; i
< inputs
.length
; i
++)
6071 if (inputs
[i
].checked
)
6072 rv
.push(inputs
[i
].value
);
6074 return rv
.length
? rv
: undefined;
6078 this.cbi
.DeviceList
= this.cbi
.NetworkList
.extend({
6079 _ev_focus: function(ev
)
6081 var self
= ev
.data
.self
;
6082 var input
= $(this);
6084 input
.parent().prev().prop('checked', true);
6087 _ev_blur: function(ev
)
6090 ev
.data
.self
._ev_keydown
.call(this, ev
);
6093 _ev_keydown: function(ev
)
6095 if (ev
.which
!= 10 && ev
.which
!= 13)
6098 var sid
= ev
.data
.sid
;
6099 var self
= ev
.data
.self
;
6100 var input
= $(this);
6101 var ifnames
= L
.toArray(input
.val());
6103 if (!ifnames
.length
)
6106 L
.NetworkModel
.createDevice(ifnames
[0]);
6108 self
._redraw(sid
, $('#' + self
.id(sid
)), ifnames
[0]);
6113 return L
.NetworkModel
.init();
6116 _redraw: function(sid
, ul
, sel
)
6118 var id
= ul
.attr('id');
6119 var devs
= L
.NetworkModel
.getDevices();
6120 var iface
= L
.NetworkModel
.getInterface(sid
);
6121 var itype
= this.options
.multiple
? 'checkbox' : 'radio';
6126 for (var i
= 0; i
< devs
.length
; i
++)
6127 if (devs
[i
].isInNetwork(iface
))
6128 check
[devs
[i
].name()] = true;
6132 if (this.options
.multiple
)
6133 check
= L
.toObject(this.formvalue(sid
));
6140 for (var i
= 0; i
< devs
.length
; i
++)
6144 if (dev
.isBridge() && this.options
.bridges
=== false)
6147 if (!dev
.isBridgeable() && this.options
.multiple
)
6150 var badge
= $('<span />')
6152 .append($('<img />').attr('src', dev
.icon()))
6153 .append(' %s: %s'.format(dev
.name(), dev
.description()));
6155 //var ifcs = dev.getInterfaces();
6158 // for (var j = 0; j < ifcs.length; j++)
6159 // badge.append((j ? ', ' : ' (') + ifcs[j].name());
6161 // badge.append(')');
6165 .append($('<label />')
6166 .addClass(itype
+ ' inline')
6167 .append($('<input />')
6168 .attr('name', itype
+ id
)
6169 .attr('type', itype
)
6170 .attr('value', dev
.name())
6171 .prop('checked', !!check
[dev
.name()]))
6178 .append($('<label />')
6179 .attr('for', 'custom' + id
)
6180 .addClass(itype
+ ' inline')
6181 .append($('<input />')
6182 .attr('name', itype
+ id
)
6183 .attr('type', itype
)
6185 .append($('<span />')
6187 .append($('<input />')
6188 .attr('id', 'custom' + id
)
6189 .attr('type', 'text')
6190 .attr('placeholder', L
.tr('Custom device …'))
6191 .on('focus', { self
: this, sid
: sid
}, this._ev_focus
)
6192 .on('blur', { self
: this, sid
: sid
}, this._ev_blur
)
6193 .on('keydown', { self
: this, sid
: sid
}, this._ev_keydown
))))
6196 if (!this.options
.multiple
)
6199 .append($('<label />')
6200 .addClass(itype
+ ' inline text-muted')
6201 .append($('<input />')
6202 .attr('name', itype
+ id
)
6203 .attr('type', itype
)
6205 .prop('checked', $.isEmptyObject(check
)))
6206 .append(L
.tr('unspecified')))
6211 widget: function(sid
)
6213 var id
= this.id(sid
);
6214 var ul
= $('<ul />')
6216 .addClass('list-unstyled');
6218 this._redraw(sid
, ul
);
6225 if (this.instance
[sid
].disabled
)
6228 var ifnames
= this.formvalue(sid
);
6232 var iface
= L
.NetworkModel
.getInterface(sid
);
6236 iface
.setDevices($.isArray(ifnames
) ? ifnames
: [ ifnames
]);
6241 this.cbi
.AbstractSection
= this.ui
.AbstractWidget
.extend({
6244 var s
= [ arguments
[0], this.map
.uci_package
, this.uci_type
];
6246 for (var i
= 1; i
< arguments
.length
; i
++)
6247 s
.push(arguments
[i
].replace(/\./g, '_'));
6252 option: function(widget
, name
, options
)
6254 if (this.tabs
.length
== 0)
6255 this.tab({ id
: '__default__', selected
: true });
6257 return this.taboption('__default__', widget
, name
, options
);
6260 tab: function(options
)
6262 if (options
.selected
)
6263 this.tabs
.selected
= this.tabs
.length
;
6267 caption
: options
.caption
,
6268 description
: options
.description
,
6274 taboption: function(tabid
, widget
, name
, options
)
6277 for (var i
= 0; i
< this.tabs
.length
; i
++)
6279 if (this.tabs
[i
].id
== tabid
)
6287 throw 'Cannot append to unknown tab ' + tabid
;
6289 var w
= widget
? new widget(name
, options
) : null;
6291 if (!(w
instanceof L
.cbi
.AbstractValue
))
6292 throw 'Widget must be an instance of AbstractValue';
6297 this.fields
[name
] = w
;
6303 tabtoggle: function(sid
)
6305 for (var i
= 0; i
< this.tabs
.length
; i
++)
6307 var tab
= this.tabs
[i
];
6308 var elem
= $('#' + this.id('nodetab', sid
, tab
.id
));
6311 for (var j
= 0; j
< tab
.fields
.length
; j
++)
6313 if (tab
.fields
[j
].active(sid
))
6320 if (empty
&& elem
.is(':visible'))
6327 ucipackages: function(pkg
)
6329 for (var i
= 0; i
< this.tabs
.length
; i
++)
6330 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6331 if (this.tabs
[i
].fields
[j
].options
.uci_package
)
6332 pkg
[this.tabs
[i
].fields
[j
].options
.uci_package
] = true;
6335 formvalue: function()
6339 this.sections(function(s
) {
6340 var sid
= s
['.name'];
6341 var sv
= rv
[sid
] || (rv
[sid
] = { });
6343 for (var i
= 0; i
< this.tabs
.length
; i
++)
6344 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6346 var val
= this.tabs
[i
].fields
[j
].formvalue(sid
);
6347 sv
[this.tabs
[i
].fields
[j
].name
] = val
;
6354 validate_section: function(sid
)
6356 var inst
= this.instance
[sid
];
6359 var badge
= $('#' + this.id('teaser', sid
)).children('span:first');
6361 for (var i
= 0; i
< this.tabs
.length
; i
++)
6364 var stbadge
= $('#' + this.id('nodetab', sid
, this.tabs
[i
].id
)).children('span:first');
6366 for (var j
= 0; j
< this.tabs
[i
].fields
.length
; j
++)
6367 if (!this.tabs
[i
].fields
[j
].validate(sid
))
6373 .attr('title', L
.trp('1 Error', '%d Errors', inval
).format(inval
));
6383 .attr('title', L
.trp('1 Error', '%d Errors', invals
).format(invals
));
6390 validate: function()
6393 var as
= this.sections();
6395 for (var i
= 0; i
< as
.length
; i
++)
6397 var invals
= this.validate_section(as
[i
]['.name']);
6403 var badge
= $('#' + this.id('sectiontab')).children('span:first');
6408 .attr('title', L
.trp('1 Error', '%d Errors', errors
).format(errors
));
6412 return (errors
== 0);
6416 this.cbi
.TypedSection
= this.cbi
.AbstractSection
.extend({
6417 init: function(uci_type
, options
)
6419 this.uci_type
= uci_type
;
6420 this.options
= options
;
6423 this.active_panel
= 0;
6424 this.active_tab
= { };
6427 filter: function(section
)
6432 sections: function(cb
)
6434 var s1
= L
.uci
.sections(this.map
.uci_package
);
6437 for (var i
= 0; i
< s1
.length
; i
++)
6438 if (s1
[i
]['.type'] == this.uci_type
)
6439 if (this.filter(s1
[i
]))
6442 if (typeof(cb
) == 'function')
6443 for (var i
= 0; i
< s2
.length
; i
++)
6444 cb
.call(this, s2
[i
]);
6451 return this.map
.add(this.map
.uci_package
, this.uci_type
, name
);
6454 remove: function(sid
)
6456 return this.map
.remove(this.map
.uci_package
, sid
);
6459 _ev_add: function(ev
)
6462 var name
= undefined;
6463 var self
= ev
.data
.self
;
6465 if (addb
.prev().prop('nodeName') == 'INPUT')
6466 name
= addb
.prev().val();
6468 if (addb
.prop('disabled') || name
=== '')
6471 L
.ui
.saveScrollTop();
6473 self
.active_panel
= -1;
6476 ev
.data
.sid
= self
.add(name
);
6477 ev
.data
.type
= self
.uci_type
;
6478 ev
.data
.name
= name
;
6480 self
.trigger('add', ev
);
6484 L
.ui
.restoreScrollTop();
6487 _ev_remove: function(ev
)
6489 var self
= ev
.data
.self
;
6490 var sid
= ev
.data
.sid
;
6492 L
.ui
.saveScrollTop();
6494 self
.trigger('remove', ev
);
6500 L
.ui
.restoreScrollTop();
6502 ev
.stopPropagation();
6505 _ev_sid: function(ev
)
6507 var self
= ev
.data
.self
;
6509 var addb
= text
.next();
6510 var errt
= addb
.next();
6511 var name
= text
.val();
6513 if (!/^[a-zA-Z0-9_]*$/.test(name
))
6515 errt
.text(L
.tr('Invalid section name')).show();
6516 text
.addClass('error');
6517 addb
.prop('disabled', true);
6521 if (L
.uci
.get(self
.map
.uci_package
, name
))
6523 errt
.text(L
.tr('Name already used')).show();
6524 text
.addClass('error');
6525 addb
.prop('disabled', true);
6529 errt
.text('').hide();
6530 text
.removeClass('error');
6531 addb
.prop('disabled', false);
6535 _ev_tab: function(ev
)
6537 var self
= ev
.data
.self
;
6538 var sid
= ev
.data
.sid
;
6541 self
.active_tab
[sid
] = parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
6544 _ev_panel_collapse: function(ev
)
6546 var self
= ev
.data
.self
;
6548 var this_panel
= $(ev
.target
);
6549 var this_toggle
= this_panel
.prevAll('[data-toggle="collapse"]:first');
6551 var prev_toggle
= $($(ev
.delegateTarget
).find('[data-toggle="collapse"]:eq(%d)'.format(self
.active_panel
)));
6552 var prev_panel
= $(prev_toggle
.attr('data-target'));
6556 .addClass('collapse');
6558 prev_toggle
.find('.luci2-section-teaser')
6560 .children('span:last')
6562 .append(self
.teaser(prev_panel
.attr('data-luci2-sid')));
6564 this_toggle
.find('.luci2-section-teaser')
6567 self
.active_panel
= parseInt(this_panel
.attr('data-luci2-panel-index'));
6571 _ev_panel_open: function(ev
)
6573 var self
= ev
.data
.self
;
6574 var panel
= $($(this).attr('data-target'));
6575 var index
= parseInt(panel
.attr('data-luci2-panel-index'));
6577 if (index
== self
.active_panel
)
6578 ev
.stopPropagation();
6581 _ev_sort: function(ev
)
6583 var self
= ev
.data
.self
;
6584 var cur_idx
= ev
.data
.index
;
6585 var new_idx
= cur_idx
+ (ev
.data
.up
? -1 : 1);
6586 var s
= self
.sections();
6588 if (new_idx
>= 0 && new_idx
< s
.length
)
6590 L
.uci
.swap(self
.map
.uci_package
, s
[cur_idx
]['.name'], s
[new_idx
]['.name']);
6596 ev
.stopPropagation();
6599 teaser: function(sid
)
6601 var tf
= this.teaser_fields
;
6605 tf
= this.teaser_fields
= [ ];
6607 if ($.isArray(this.options
.teasers
))
6609 for (var i
= 0; i
< this.options
.teasers
.length
; i
++)
6611 var f
= this.options
.teasers
[i
];
6612 if (f
instanceof L
.cbi
.AbstractValue
)
6614 else if (typeof(f
) == 'string' && this.fields
[f
] instanceof L
.cbi
.AbstractValue
)
6615 tf
.push(this.fields
[f
]);
6620 for (var i
= 0; tf
.length
<= 5 && i
< this.tabs
.length
; i
++)
6621 for (var j
= 0; tf
.length
<= 5 && j
< this.tabs
[i
].fields
.length
; j
++)
6622 tf
.push(this.tabs
[i
].fields
[j
]);
6628 for (var i
= 0; i
< tf
.length
; i
++)
6630 if (tf
[i
].instance
[sid
] && tf
[i
].instance
[sid
].disabled
)
6633 var n
= tf
[i
].options
.caption
|| tf
[i
].name
;
6634 var v
= tf
[i
].textvalue(sid
);
6636 if (typeof(v
) == 'undefined')
6639 t
= t
+ '%s%s: <strong>%s</strong>'.format(t
? ' | ' : '', n
, v
);
6645 _render_add: function()
6647 if (!this.options
.addremove
)
6650 var text
= L
.tr('Add section');
6651 var ttip
= L
.tr('Create new section...');
6653 if ($.isArray(this.options
.add_caption
))
6654 text
= this.options
.add_caption
[0], ttip
= this.options
.add_caption
[1];
6655 else if (typeof(this.options
.add_caption
) == 'string')
6656 text
= this.options
.add_caption
, ttip
= '';
6658 var add
= $('<div />');
6660 if (this.options
.anonymous
=== false)
6663 .addClass('cbi-input-text')
6664 .attr('type', 'text')
6665 .attr('placeholder', ttip
)
6666 .blur({ self
: this }, this._ev_sid
)
6667 .keyup({ self
: this }, this._ev_sid
)
6671 .attr('src', L
.globals
.resource
+ '/icons/cbi/add.gif')
6672 .attr('title', text
)
6673 .addClass('cbi-button')
6674 .click({ self
: this }, this._ev_add
)
6678 .addClass('cbi-value-error')
6684 L
.ui
.button(text
, 'success', ttip
)
6685 .click({ self
: this }, this._ev_add
)
6692 _render_remove: function(sid
, index
)
6694 if (!this.options
.addremove
)
6697 var text
= L
.tr('Remove');
6698 var ttip
= L
.tr('Remove this section');
6700 if ($.isArray(this.options
.remove_caption
))
6701 text
= this.options
.remove_caption
[0], ttip
= this.options
.remove_caption
[1];
6702 else if (typeof(this.options
.remove_caption
) == 'string')
6703 text
= this.options
.remove_caption
, ttip
= '';
6705 return L
.ui
.button(text
, 'danger', ttip
)
6706 .click({ self
: this, sid
: sid
, index
: index
}, this._ev_remove
);
6709 _render_sort: function(sid
, index
)
6711 if (!this.options
.sortable
)
6714 var b1
= L
.ui
.button('↑', 'info', L
.tr('Move up'))
6715 .click({ self
: this, index
: index
, up
: true }, this._ev_sort
);
6717 var b2
= L
.ui
.button('↓', 'info', L
.tr('Move down'))
6718 .click({ self
: this, index
: index
, up
: false }, this._ev_sort
);
6723 _render_caption: function()
6726 .addClass('panel-title')
6727 .append(this.label('caption') || this.uci_type
);
6730 _render_description: function()
6732 var text
= this.label('description');
6736 .addClass('luci2-section-description')
6742 _render_teaser: function(sid
, index
)
6744 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6747 .attr('id', this.id('teaser', sid
))
6748 .addClass('luci2-section-teaser well well-sm')
6749 .append($('<span />')
6751 .append($('<span />'));
6757 _render_head: function(condensed
)
6763 .addClass('panel-heading')
6764 .append(this._render_caption())
6765 .append(this._render_description());
6768 _render_tab_description: function(sid
, index
, tab_index
)
6770 var tab
= this.tabs
[tab_index
];
6772 if (typeof(tab
.description
) == 'string')
6775 .addClass('cbi-tab-descr')
6776 .text(tab
.description
);
6782 _render_tab_head: function(sid
, index
, tab_index
)
6784 var tab
= this.tabs
[tab_index
];
6785 var cur
= this.active_tab
[sid
] || 0;
6787 var tabh
= $('<li />')
6789 .attr('id', this.id('nodetab', sid
, tab
.id
))
6790 .attr('href', '#' + this.id('node', sid
, tab
.id
))
6791 .attr('data-toggle', 'tab')
6792 .attr('data-luci2-tab-index', tab_index
)
6793 .text((tab
.caption
? tab
.caption
.format(tab
.id
) : tab
.id
) + ' ')
6794 .append($('<span />')
6796 .on('shown.bs.tab', { self
: this, sid
: sid
}, this._ev_tab
));
6798 if (cur
== tab_index
)
6799 tabh
.addClass('active');
6801 if (!tab
.fields
.length
)
6807 _render_tab_body: function(sid
, index
, tab_index
)
6809 var tab
= this.tabs
[tab_index
];
6810 var cur
= this.active_tab
[sid
] || 0;
6812 var tabb
= $('<div />')
6813 .addClass('tab-pane')
6814 .attr('id', this.id('node', sid
, tab
.id
))
6815 .attr('data-luci2-tab-index', tab_index
)
6816 .append(this._render_tab_description(sid
, index
, tab_index
));
6818 if (cur
== tab_index
)
6819 tabb
.addClass('active');
6821 for (var i
= 0; i
< tab
.fields
.length
; i
++)
6822 tabb
.append(tab
.fields
[i
].render(sid
));
6827 _render_section_head: function(sid
, index
)
6829 var head
= $('<div />')
6830 .addClass('luci2-section-header')
6831 .append(this._render_teaser(sid
, index
))
6832 .append($('<div />')
6833 .addClass('btn-group')
6834 .append(this._render_sort(sid
, index
))
6835 .append(this._render_remove(sid
, index
)));
6837 if (this.options
.collabsible
)
6839 head
.attr('data-toggle', 'collapse')
6840 .attr('data-parent', this.id('sectiongroup'))
6841 .attr('data-target', '#' + this.id('panel', sid
))
6842 .on('click', { self
: this }, this._ev_panel_open
);
6848 _render_section_body: function(sid
, index
)
6850 var body
= $('<div />')
6851 .attr('id', this.id('panel', sid
))
6852 .attr('data-luci2-panel-index', index
)
6853 .attr('data-luci2-sid', sid
);
6855 if (this.options
.collabsible
|| this.map
.options
.collabsible
)
6857 body
.addClass('panel-collapse collapse');
6859 if (index
== this.active_panel
)
6860 body
.addClass('in');
6863 var tab_heads
= $('<ul />')
6864 .addClass('nav nav-tabs');
6866 var tab_bodies
= $('<div />')
6867 .addClass('form-horizontal tab-content')
6870 for (var j
= 0; j
< this.tabs
.length
; j
++)
6872 tab_heads
.append(this._render_tab_head(sid
, index
, j
));
6873 tab_bodies
.append(this._render_tab_body(sid
, index
, j
));
6876 body
.append(tab_bodies
);
6878 if (this.tabs
.length
<= 1)
6884 _render_body: function(condensed
)
6886 var s
= this.sections();
6888 if (this.active_panel
< 0)
6889 this.active_panel
+= s
.length
;
6890 else if (this.active_panel
>= s
.length
)
6891 this.active_panel
= s
.length
- 1;
6893 var body
= $('<ul />')
6894 .addClass('list-group');
6896 if (this.options
.collabsible
)
6898 body
.attr('id', this.id('sectiongroup'))
6899 .on('show.bs.collapse', { self
: this }, this._ev_panel_collapse
);
6904 body
.append($('<li />')
6905 .addClass('list-group-item text-muted')
6906 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.')))
6909 for (var i
= 0; i
< s
.length
; i
++)
6911 var sid
= s
[i
]['.name'];
6912 var inst
= this.instance
[sid
] = { tabs
: [ ] };
6914 body
.append($('<li />')
6915 .addClass('list-group-item')
6916 .append(this._render_section_head(sid
, i
))
6917 .append(this._render_section_body(sid
, i
)));
6923 render: function(condensed
)
6925 this.instance
= { };
6927 var panel
= $('<div />')
6928 .addClass('panel panel-default')
6929 .append(this._render_head(condensed
))
6930 .append(this._render_body(condensed
));
6932 if (this.options
.addremove
)
6933 panel
.append($('<div />')
6934 .addClass('panel-footer')
6935 .append(this._render_add()));
6942 var s
= this.sections();
6944 for (var i
= 0; i
< s
.length
; i
++)
6946 var sid
= s
[i
]['.name'];
6948 this.validate_section(sid
);
6950 if (i
!= this.active_panel
)
6951 $('#' + this.id('teaser', sid
)).children('span:last')
6952 .append(this.teaser(sid
));
6954 $('#' + this.id('teaser', sid
))
6960 this.cbi
.TableSection
= this.cbi
.TypedSection
.extend({
6961 _render_table_head: function()
6963 var thead
= $('<thead />')
6965 .addClass('cbi-section-table-titles'));
6967 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
6968 thead
.children().append($('<th />')
6969 .addClass('cbi-section-table-cell')
6970 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
6971 .append(this.tabs
[0].fields
[j
].label('caption')));
6973 if (this.options
.addremove
!== false || this.options
.sortable
)
6974 thead
.children().append($('<th />')
6975 .addClass('cbi-section-table-cell')
6981 _render_table_row: function(sid
, index
)
6983 var row
= $('<tr />')
6984 .attr('data-luci2-sid', sid
);
6986 for (var j
= 0; j
< this.tabs
[0].fields
.length
; j
++)
6988 row
.append($('<td />')
6989 .css('width', this.tabs
[0].fields
[j
].options
.width
|| '')
6990 .append(this.tabs
[0].fields
[j
].render(sid
, true)));
6993 if (this.options
.addremove
!== false || this.options
.sortable
)
6995 row
.append($('<td />')
6996 .addClass('text-right')
6997 .append($('<div />')
6998 .addClass('btn-group')
6999 .append(this._render_sort(sid
, index
))
7000 .append(this._render_remove(sid
, index
))));
7006 _render_table_body: function()
7008 var s
= this.sections();
7010 var tbody
= $('<tbody />');
7014 var cols
= this.tabs
[0].fields
.length
;
7016 if (this.options
.addremove
!== false || this.options
.sortable
)
7019 tbody
.append($('<tr />')
7021 .addClass('text-muted')
7022 .attr('colspan', cols
)
7023 .text(this.label('placeholder') || L
.tr('There are no entries defined yet.'))));
7026 for (var i
= 0; i
< s
.length
; i
++)
7028 var sid
= s
[i
]['.name'];
7029 var inst
= this.instance
[sid
] = { tabs
: [ ] };
7031 tbody
.append(this._render_table_row(sid
, i
));
7037 _render_body: function(condensed
)
7039 return $('<table />')
7040 .addClass('table table-condensed table-hover')
7041 .append(this._render_table_head())
7042 .append(this._render_table_body());
7046 this.cbi
.NamedSection
= this.cbi
.TypedSection
.extend({
7047 sections: function(cb
)
7050 var sl
= L
.uci
.sections(this.map
.uci_package
);
7052 for (var i
= 0; i
< sl
.length
; i
++)
7053 if (sl
[i
]['.name'] == this.uci_type
)
7059 if (typeof(cb
) == 'function' && sa
.length
> 0)
7060 cb
.call(this, sa
[0]);
7066 this.cbi
.SingleSection
= this.cbi
.NamedSection
.extend({
7069 this.instance
= { };
7070 this.instance
[this.uci_type
] = { tabs
: [ ] };
7072 return this._render_section_body(this.uci_type
, 0);
7076 this.cbi
.DummySection
= this.cbi
.TypedSection
.extend({
7077 sections: function(cb
)
7079 if (typeof(cb
) == 'function')
7080 cb
.apply(this, [ { '.name': this.uci_type
} ]);
7082 return [ { '.name': this.uci_type
} ];
7086 this.cbi
.Map
= this.ui
.AbstractWidget
.extend({
7087 init: function(uci_package
, options
)
7091 this.uci_package
= uci_package
;
7092 this.sections
= [ ];
7093 this.options
= L
.defaults(options
, {
7094 save: function() { },
7095 prepare: function() { }
7099 _load_cb: function()
7101 var deferreds
= [ L
.deferrable(this.options
.prepare()) ];
7103 for (var i
= 0; i
< this.sections
.length
; i
++)
7105 for (var f
in this.sections
[i
].fields
)
7107 if (typeof(this.sections
[i
].fields
[f
].load
) != 'function')
7110 var s
= this.sections
[i
].sections();
7111 for (var j
= 0; j
< s
.length
; j
++)
7113 var rv
= this.sections
[i
].fields
[f
].load(s
[j
]['.name']);
7114 if (L
.isDeferred(rv
))
7120 return $.when
.apply($, deferreds
);
7128 for (var i
= 0; i
< this.sections
.length
; i
++)
7129 this.sections
[i
].ucipackages(packages
);
7131 packages
[this.uci_package
] = true;
7133 for (var pkg
in packages
)
7134 if (!L
.uci
.writable(pkg
))
7135 this.options
.readonly
= true;
7137 return L
.uci
.load(L
.toArray(packages
)).then(function() {
7138 return self
._load_cb();
7142 _ev_tab: function(ev
)
7144 var self
= ev
.data
.self
;
7147 self
.active_tab
= parseInt(ev
.target
.getAttribute('data-luci2-tab-index'));
7150 _ev_apply: function(ev
)
7152 var self
= ev
.data
.self
;
7154 self
.trigger('apply', ev
);
7157 _ev_save: function(ev
)
7159 var self
= ev
.data
.self
;
7161 self
.send().then(function() {
7162 self
.trigger('save', ev
);
7166 _ev_reset: function(ev
)
7168 var self
= ev
.data
.self
;
7170 self
.trigger('reset', ev
);
7174 _render_tab_head: function(tab_index
)
7176 var section
= this.sections
[tab_index
];
7177 var cur
= this.active_tab
|| 0;
7179 var tabh
= $('<li />')
7181 .attr('id', section
.id('sectiontab'))
7182 .attr('href', '#' + section
.id('section'))
7183 .attr('data-toggle', 'tab')
7184 .attr('data-luci2-tab-index', tab_index
)
7185 .text(section
.label('caption') + ' ')
7186 .append($('<span />')
7188 .on('shown.bs.tab', { self
: this }, this._ev_tab
));
7190 if (cur
== tab_index
)
7191 tabh
.addClass('active');
7196 _render_tab_body: function(tab_index
)
7198 var section
= this.sections
[tab_index
];
7199 var desc
= section
.label('description');
7200 var cur
= this.active_tab
|| 0;
7202 var tabb
= $('<div />')
7203 .addClass('tab-pane')
7204 .attr('id', section
.id('section'))
7205 .attr('data-luci2-tab-index', tab_index
);
7207 if (cur
== tab_index
)
7208 tabb
.addClass('active');
7211 tabb
.append($('<p />')
7214 var s
= section
.render(this.options
.tabbed
);
7216 if (this.options
.readonly
|| section
.options
.readonly
)
7217 s
.find('input, select, button, img.cbi-button').attr('disabled', true);
7224 _render_body: function()
7226 var tabs
= $('<ul />')
7227 .addClass('nav nav-tabs');
7229 var body
= $('<div />')
7232 for (var i
= 0; i
< this.sections
.length
; i
++)
7234 tabs
.append(this._render_tab_head(i
));
7235 body
.append(this._render_tab_body(i
));
7238 if (this.options
.tabbed
)
7239 body
.addClass('tab-content');
7246 _render_footer: function()
7253 .addClass('panel panel-default panel-body text-right')
7254 .append($('<div />')
7255 .addClass('btn-group')
7256 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7257 .click(evdata
, this._ev_apply
))
7258 .append(L
.ui
.button(L
.tr('Save'), 'default')
7259 .click(evdata
, this._ev_save
))
7260 .append(L
.ui
.button(L
.tr('Reset'), 'default')
7261 .click(evdata
, this._ev_reset
)));
7266 var map
= $('<form />');
7268 if (typeof(this.options
.caption
) == 'string')
7269 map
.append($('<h2 />')
7270 .text(this.options
.caption
));
7272 if (typeof(this.options
.description
) == 'string')
7273 map
.append($('<p />')
7274 .text(this.options
.description
));
7276 map
.append(this._render_body());
7278 if (this.options
.pageaction
!== false)
7279 map
.append(this._render_footer());
7286 for (var i
= 0; i
< this.sections
.length
; i
++)
7287 this.sections
[i
].finish();
7294 this.target
.hide().empty().append(this.render());
7299 section: function(widget
, uci_type
, options
)
7301 var w
= widget
? new widget(uci_type
, options
) : null;
7303 if (!(w
instanceof L
.cbi
.AbstractSection
))
7304 throw 'Widget must be an instance of AbstractSection';
7307 w
.index
= this.sections
.length
;
7309 this.sections
.push(w
);
7313 formvalue: function()
7317 for (var i
= 0; i
< this.sections
.length
; i
++)
7319 var sids
= this.sections
[i
].formvalue();
7320 for (var sid
in sids
)
7322 var s
= rv
[sid
] || (rv
[sid
] = { });
7323 $.extend(s
, sids
[sid
]);
7330 add: function(conf
, type
, name
)
7332 return L
.uci
.add(conf
, type
, name
);
7335 remove: function(conf
, sid
)
7337 return L
.uci
.remove(conf
, sid
);
7340 get: function(conf
, sid
, opt
)
7342 return L
.uci
.get(conf
, sid
, opt
);
7345 set: function(conf
, sid
, opt
, val
)
7347 return L
.uci
.set(conf
, sid
, opt
, val
);
7350 validate: function()
7354 for (var i
= 0; i
< this.sections
.length
; i
++)
7356 if (!this.sections
[i
].validate())
7367 if (self
.options
.readonly
)
7368 return L
.deferrable();
7370 var deferreds
= [ ];
7372 for (var i
= 0; i
< self
.sections
.length
; i
++)
7374 if (self
.sections
[i
].options
.readonly
)
7377 for (var f
in self
.sections
[i
].fields
)
7379 if (typeof(self
.sections
[i
].fields
[f
].save
) != 'function')
7382 var s
= self
.sections
[i
].sections();
7383 for (var j
= 0; j
< s
.length
; j
++)
7385 var rv
= self
.sections
[i
].fields
[f
].save(s
[j
]['.name']);
7386 if (L
.isDeferred(rv
))
7392 return $.when
.apply($, deferreds
).then(function() {
7393 return L
.deferrable(self
.options
.save());
7399 if (!this.validate())
7400 return L
.deferrable();
7404 L
.ui
.saveScrollTop();
7407 return this.save().then(function() {
7408 return L
.uci
.save();
7409 }).then(function() {
7410 return L
.ui
.updateChanges();
7411 }).then(function() {
7413 }).then(function() {
7417 L
.ui
.loading(false);
7418 L
.ui
.restoreScrollTop();
7426 for (var i
= 0; i
< this.sections
.length
; i
++)
7427 this.sections
[i
].ucipackages(packages
);
7429 packages
[this.uci_package
] = true;
7431 L
.uci
.unload(L
.toArray(packages
));
7440 return self
.insertInto(self
.target
);
7443 insertInto: function(id
)
7446 self
.target
= $(id
);
7451 return self
.load().then(function() {
7452 self
.target
.empty().append(self
.render());
7456 L
.ui
.loading(false);
7461 this.cbi
.Modal
= this.cbi
.Map
.extend({
7462 _ev_apply: function(ev
)
7464 var self
= ev
.data
.self
;
7466 self
.trigger('apply', ev
);
7469 _ev_save: function(ev
)
7471 var self
= ev
.data
.self
;
7473 self
.send().then(function() {
7474 self
.trigger('save', ev
);
7479 _ev_reset: function(ev
)
7481 var self
= ev
.data
.self
;
7483 self
.trigger('close', ev
);
7488 _render_footer: function()
7495 .addClass('btn-group')
7496 .append(L
.ui
.button(L
.tr('Save & Apply'), 'primary')
7497 .click(evdata
, this._ev_apply
))
7498 .append(L
.ui
.button(L
.tr('Save'), 'default')
7499 .click(evdata
, this._ev_save
))
7500 .append(L
.ui
.button(L
.tr('Cancel'), 'default')
7501 .click(evdata
, this._ev_reset
));
7506 var modal
= L
.ui
.dialog(this.label('caption'), null, { wide
: true });
7507 var map
= $('<form />');
7509 var desc
= this.label('description');
7511 map
.append($('<p />').text(desc
));
7513 map
.append(this._render_body());
7515 modal
.find('.modal-body').append(map
);
7516 modal
.find('.modal-footer').append(this._render_footer());
7533 return self
.load().then(function() {
7537 L
.ui
.loading(false);