desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Tests unblock_interface when the interface is blocked'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_unblock_interface_not_blocked_none(self, pyric):
| interface_name = 'wlan0'
interface_object = 'Card Object'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
pyric.isblocked.return_value = False
self.network_manager.unblock_interface(interface_name)
pyric.unblock.assert_not_called()
|
'Tests set_interface_channel method when setting a channel'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_set_interface_channel_normal_none(self, pyric):
| interface_name = 'wlan0'
interface_object = 'Card Object'
channel = 4
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager.set_interface_channel(interface_name, channel)
pyric.chset.assert_called_once_with(interface_object, channel)
|
'Tests start method when no interface is found'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_start_no_interface_none(self, pyric):
| pyric.interfaces.return_value = []
self.assertIsNone(self.network_manager.start())
|
'Tests start method when interface(s) has been found'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_start_has_interface_none(self, pyric):
| interface_name = 'wlan0'
pyric.interfaces.return_value = [interface_name]
self.assertIsNone(self.network_manager.start())
|
'Tests start method when interface is not supported'
| @mock.patch('wifiphisher.common.interfaces.pyw.getcard')
def test_start_interface_not_compatible_none(self, pyw):
| pyw.side_effect = pyric.error(93, 'Device does not support nl80211')
self.network_manager.start()
|
'Tests start method when there is no such interface'
| @mock.patch('wifiphisher.common.interfaces.pyw.getcard')
def test_start_interface_no_such_device_none(self, pyw):
| pyw.side_effect = pyric.error(19, 'No such device')
self.assertIsNone(self.network_manager.start())
|
'Tests start method when an unidentified error has happened
while getting the card'
| @mock.patch('wifiphisher.common.interfaces.pyw.getcard')
def test_start_interface_unidentified_error_error(self, pyw):
| pyw.side_effect = pyric.error(2220, 'This is a fake error')
with self.assertRaises(pyric.error) as error:
self.network_manager.start()
the_exception = error.exception
self.assertEqual(the_exception[0], 2220, 'The error was not caught.')
|
'Tests on_exit method when there are no active interfaces'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_on_exit_no_active_none(self, pyw):
| self.network_manager.on_exit()
pyw.modeset.assert_not_called()
|
'Tests on_exit method when there are active interfaces'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_on_exit_has_active_none(self, pyric):
| interface_name = 'wlan0'
interface_object = 'Card Object'
mode = 'managed'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager._active.add(interface_name)
self.network_manager.on_exit()
pyric.modeset.assert_called_once_with(interface_object, mode)
|
'Test set_interface_mac with an invalid MAC address to raise an
error'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_set_interface_mac_invalid_mac_error(self, pyw):
| pyw.macset.side_effect = pyric.error(22, 'Invalid mac address')
interface_name = 'wlan0'
interface_object = 'Card Object'
mac_address = '1'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager._active.add(interface_name)
with self.assertRaises(interfaces.InvalidMacAddressError):
self.network_manager.set_interface_mac(interface_name, mac_address)
|
'Test set_interface_mac with an valid MAC address to simulate
normal operation'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_set_interface_mac_valid_mac_none(self, pyw):
| interface_name = 'wlan0'
interface_object = 'Card Object'
mac_address = '11:22:33:44:55:66'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager._active.add(interface_name)
operation = self.network_manager.set_interface_mac(interface_name, mac_address)
message = 'Failed when a valid mac address was provided'
self.assertIsNone(operation, message)
|
'Test set_interface_mac when an unexpected error occurs'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_set_interface_unexpected_error(self, pyw):
| pyw.macset.side_effect = pyric.error(5534, 'Unexpected error')
interface_name = 'wlan0'
interface_object = 'Card Object'
mac_address = '11:22:33:44:55:66'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager._active.add(interface_name)
with self.assertRaises(pyric.error) as error:
self.network_manager.set_interface_mac(interface_name, mac_address)
self.assertEqual(error.exception[0], 5534, 'Unexpected error')
|
'Test set_interface_mac_random under normal conditions'
| @mock.patch('wifiphisher.common.interfaces.pyw')
def test_set_interface_mac_random_none(self, pyw):
| new_mac_address = '00:11:22:33:44:55'
interface_name = 'wlan0'
interface_object = 'Card Object'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager._active.add(interface_name)
with mock.patch('wifiphisher.common.interfaces.generate_random_address') as generator:
generator.return_value = new_mac_address
self.network_manager.set_interface_mac_random(interface_name)
pyw.macset.assert_called_once_with(interface_object, new_mac_address)
|
'Test get_interface_mac under normal conditions'
| def test_get_interface_mac_address(self):
| interface_name = 'wlan0'
interface_object = 'Card Object'
adapter = interfaces.NetworkAdapter(interface_name, interface_object, self.mac_address)
self.network_manager._name_to_object[interface_name] = adapter
self.network_manager._active.add(interface_name)
self.assertEqual(self.network_manager.get_interface_mac(interface_name), self.mac_address)
|
'Test generate_random_address function to make sure that the
values are correctly returned'
| @mock.patch('wifiphisher.common.interfaces.random')
def test_generate_random_address(self, random_module):
| random_module.randint.side_effect = [10, 100, 200]
expected = '00:00:00:0a:64:c8'
actual = interfaces.generate_random_address()
self.assertEqual(actual, expected)
|
'Do your initialization here. Correct bottom-to-up inheritance call order guaranteed.'
| def init(self):
| self.context = extract_context()
if self.context:
self.load_classconfig()
|
'Loads the content of ``classconfig`` attribute from the user\'s configuration section.'
| def load_classconfig(self):
| self.create_classconfig()
if (self.default_classconfig is not None):
self.classconfig = self.__get_config_store()[self.classname].data
|
'Provides access to plugin-specific files from ``/content`` directory of the package
:param path: path relative to package\'s ``/content``
:param mode: Python file access mode
:type path: str
:type mode: str
:returns: An open file object
:rtype: file'
| def open_content(self, path, mode='r'):
| _check_plugin(self.__class__)
root = os.path.split(self.__class__._path)[0]
while ((len(root) > 1) and (not os.path.exists(os.path.join(root, 'content')))):
root = os.path.split(root)[0]
if (len(root) <= 1):
raise Exception('content directory not found')
return open(os.path.join(root, 'content', path), mode)
|
'Saves the content of ``classconfig`` attribute into the user\'s configuration section.'
| def save_classconfig(self):
| self.create_classconfig()
self.__get_config_store()[self.classname].data = self.classconfig
ajenti.config.save()
|
'Returns a Sensor by name
:param id: sensor ID
:type id: str
:rtype: :class:`Sensor`, None'
| @staticmethod
def find(id):
| for cls in Sensor.get_classes():
if (cls.id == id):
return cls.get()
else:
return None
|
'Returns sensor\'s measurement for a specific `variant`. Sensors can have multiple variants; for example, disk usage sensor accepts device name as a variant.
:param variant: variant to measure
:type variant: str, None
:rtype: int, float, tuple, list, dict, str'
| def value(self, variant=None):
| t = time.time()
if ((not (variant in self.cache)) or ((t - self.last_measurement[variant]) > self.timeout)):
self.cache[variant] = self.measure(variant)
self.last_measurement[variant] = t
return self.cache[variant]
|
'Override this and return a list of available variants.
:rtype: list'
| def get_variants(self):
| return [None]
|
'Finds and executes the handler for given request context (handlers are methods decorated with :func:`url` )
:param context: HTTP context
:type context: :class:`ajenti.http.HttpContext`'
| def handle(self, context):
| for (name, method) in self.__class__.__dict__.iteritems():
if hasattr(method, '_url_pattern'):
method = getattr(self, name)
match = method._url_pattern.match(context.path)
if match:
context.route_data = match.groupdict()
data = method(context, **context.route_data)
if (type(data) is types.GeneratorType):
return data
else:
return [data]
|
'Internal'
| def recv_connect(self):
| if (self.request.session.identity is None):
self.emit('auth-error', '')
return
self.context = self.request.session.appcontext
self.on_connect()
|
'Internal'
| def recv_disconnect(self):
| if (self.request.session.identity is None):
return
self.on_disconnect()
self.disconnect(silent=True)
|
'Internal'
| def recv_message(self, message):
| if (self.request.session.identity is None):
return
self.request.session.touch()
self.on_message(json.loads(message))
|
'Construct a Cookie object from a dict of strings to parse.
The main difference between this and Cookie(name, value, **kwargs) is
that the values in the argument to this method are parsed.
If ignore_bad_attributes=True (default), values which did not parse
are set to \'\' in order to avoid passing bad data.'
| @classmethod
def from_dict(cls, cookie_dict, ignore_bad_attributes=True):
| name = cookie_dict.get('name', None)
if (not name):
raise InvalidCookieError('Cookie must have name')
raw_value = cookie_dict.get('value', '')
value = cls.attribute_parsers['value'](raw_value)
cookie = Cookie(name, value)
parsed = {}
for (key, value) in cookie_dict.items():
if (key in ('name', 'value')):
continue
parser = cls.attribute_parsers.get(key)
if (not parser):
if (not ignore_bad_attributes):
raise InvalidCookieAttributeError(key, value, ("unknown cookie attribute '%s'" % key))
_report_unknown_attribute(key)
continue
try:
parsed_value = parser(value)
except Exception as e:
reason = ('did not parse with %r: %r' % (parser, e))
if (not ignore_bad_attributes):
raise InvalidCookieAttributeError(key, value, reason)
_report_invalid_attribute(key, value, reason)
parsed_value = ''
parsed[key] = parsed_value
cookie._set_attributes(parsed, ignore_bad_attributes)
return cookie
|
'Construct a Cookie object from a line of Set-Cookie header data.'
| @classmethod
def from_string(cls, line, ignore_bad_cookies=False, ignore_bad_attributes=True):
| cookie_dict = parse_one_response(line, ignore_bad_cookies=ignore_bad_cookies, ignore_bad_attributes=ignore_bad_attributes)
if (not cookie_dict):
return None
return cls.from_dict(cookie_dict, ignore_bad_attributes=ignore_bad_attributes)
|
'Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.'
| def validate(self, name, value):
| validator = self.attribute_validators.get(name, None)
if validator:
return (True if validator(value) else False)
return True
|
'Attributes mentioned in attribute_names get validated using
functions in attribute_validators, raising an exception on failure.
Others get left alone.'
| def __setattr__(self, name, value):
| if ((name in self.attribute_names) or (name in ('name', 'value'))):
if ((name == 'name') and (not value)):
raise InvalidCookieError(message='Cookies must have names')
if (value is not None):
if (not self.validate(name, value)):
pass
object.__setattr__(self, name, value)
|
'Provide for acting like everything in attribute_names is
automatically set to None, rather than having to do so explicitly and
only at import time.'
| def __getattr__(self, name):
| if (name in self.attribute_names):
return None
raise AttributeError(name)
|
'Export this cookie\'s attributes as a dict of encoded values.
This is an important part of the code for rendering attributes, e.g.
render_response().'
| def attributes(self):
| dictionary = {}
for (python_attr_name, cookie_attr_name) in self.attribute_names.items():
value = getattr(self, python_attr_name)
renderer = self.attribute_renderers.get(python_attr_name, None)
if renderer:
value = renderer(value)
if (not value):
continue
dictionary[cookie_attr_name] = value
return dictionary
|
'Render as a string formatted for HTTP request headers
(simple \'Cookie: \' style).'
| def render_request(self):
| (name, value) = (self.name, self.value)
renderer = self.attribute_renderers.get('name', None)
if renderer:
name = renderer(name)
renderer = self.attribute_renderers.get('value', None)
if renderer:
value = renderer(value)
return ''.join((name, '=', value))
|
'Render as a string formatted for HTTP response headers
(detailed \'Set-Cookie: \' style).'
| def render_response(self):
| (name, value) = (self.name, self.value)
renderer = self.attribute_renderers.get('name', None)
if renderer:
name = renderer(name)
renderer = self.attribute_renderers.get('value', None)
if renderer:
value = renderer(value)
return '; '.join((['{0}={1}'.format(name, value)] + [(key if isinstance(value, bool) else '='.join((key, value))) for (key, value) in self.attributes().items()]))
|
'Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as the cookie name and the
value as the UNENCODED value stored in the cookie.'
| def add(self, *args, **kwargs):
| for cookie in args:
self.all_cookies.append(cookie)
if (cookie.name in self):
continue
self[cookie.name] = cookie
for (key, value) in kwargs.items():
cookie = Cookie(key, value)
self.all_cookies.append(cookie)
if (key in self):
continue
self[key] = cookie
|
'Parse \'Cookie\' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only \'Cookie:\' request headers or
header values (as in CGI/WSGI HTTP_COOKIE); if more than one, they must
be separated by CRLF (\r\n).
:arg ignore_bad_cookies: if set, will log each syntactically invalid
cookie (at the granularity of semicolon-delimited blocks) rather than
raising an exception at the first bad cookie.
:returns: a Cookies instance containing Cookie objects parsed from
header_data.
.. note::
If you want to parse \'Set-Cookie:\' response headers, please use
parse_response instead. parse_request will happily turn \'expires=frob\'
into a separate cookie without complaining, according to the grammar.'
| def parse_request(self, header_data, ignore_bad_cookies=False):
| cookies_dict = _parse_request(header_data, ignore_bad_cookies=ignore_bad_cookies)
cookie_objects = []
for (name, values) in cookies_dict.items():
for value in values:
cookie_dict = {'name': name, 'value': value}
try:
cookie = Cookie.from_dict(cookie_dict)
except InvalidCookieError:
if (not ignore_bad_cookies):
raise
else:
cookie_objects.append(cookie)
try:
self.add(*cookie_objects)
except InvalidCookieError:
if (not ignore_bad_cookies):
raise
_report_invalid_cookie(header_data)
return self
|
'Parse \'Set-Cookie\' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only \'Set-Cookie:\' request headers
or their corresponding header values; if more than one, they must be
separated by CRLF (\r\n).
:arg ignore_bad_cookies: if set, will log each syntactically invalid
cookie rather than raising an exception at the first bad cookie. (This
includes cookies which have noncompliant characters in the attribute
section).
:arg ignore_bad_attributes: defaults to True, which means to log but
not raise an error when a particular attribute is unrecognized. (This
does not necessarily mean that the attribute is invalid, although that
would often be the case.) if unset, then an error will be raised at the
first semicolon-delimited block which has an unknown attribute.
:returns: a Cookies instance containing Cookie objects parsed from
header_data, each with recognized attributes populated.
.. note::
If you want to parse \'Cookie:\' headers (i.e., data like what\'s sent
with an HTTP request, which has only name=value pairs and no
attributes), then please use parse_request instead. Such lines often
contain multiple name=value pairs, and parse_response will throw away
the pairs after the first one, which will probably generate errors or
confusing behavior. (Since there\'s no perfect way to automatically
determine which kind of parsing to do, you have to tell it manually by
choosing correctly from parse_request between part_response.)'
| def parse_response(self, header_data, ignore_bad_cookies=False, ignore_bad_attributes=True):
| cookie_dicts = _parse_response(header_data, ignore_bad_cookies=ignore_bad_cookies, ignore_bad_attributes=ignore_bad_attributes)
cookie_objects = []
for cookie_dict in cookie_dicts:
cookie = Cookie.from_dict(cookie_dict)
cookie_objects.append(cookie)
self.add(*cookie_objects)
return self
|
'Construct a Cookies object from request header data.'
| @classmethod
def from_request(cls, header_data, ignore_bad_cookies=False):
| cookies = Cookies()
cookies.parse_request(header_data, ignore_bad_cookies=ignore_bad_cookies)
return cookies
|
'Construct a Cookies object from response header data.'
| @classmethod
def from_response(cls, header_data, ignore_bad_cookies=False, ignore_bad_attributes=True):
| cookies = Cookies()
cookies.parse_response(header_data, ignore_bad_cookies=ignore_bad_cookies, ignore_bad_attributes=ignore_bad_attributes)
return cookies
|
'Render the dict\'s Cookie objects into a string formatted for HTTP
request headers (simple \'Cookie: \' style).'
| def render_request(self, sort=True):
| if (not sort):
return '; '.join((cookie.render_request() for cookie in self.values()))
return '; '.join(sorted((cookie.render_request() for cookie in self.values())))
|
'Render the dict\'s Cookie objects into list of strings formatted for
HTTP response headers (detailed \'Set-Cookie: \' style).'
| def render_response(self, sort=True):
| rendered = [cookie.render_response() for cookie in self.values()]
return (rendered if (not sort) else sorted(rendered))
|
'Test if a Cookies object is globally \'equal\' to another one by
seeing if it looks like a dict such that d[k] == self[k]. This depends
on each Cookie object reporting its equality correctly.'
| def __eq__(self, other):
| if (not hasattr(other, 'keys')):
return False
try:
keys = sorted((set(self.keys()) | set(other.keys())))
for key in keys:
if (not (key in self)):
return False
if (not (key in other)):
return False
if (not (self[key] == other[key])):
return False
except (TypeError, KeyError):
raise
return True
|
'Dispatch the request to every HttpPlugin'
| @profiled((lambda a, k: ('HTTP %s' % a[1].path)))
def handle(self, context):
| if hasattr(context.session, 'appcontext'):
self.context = context.session.appcontext
else:
self.context = manager.context
if context.path.startswith('/ajenti:socket'):
return context.fallthrough(self.io)
if (not hasattr(self.context, 'http_handlers')):
self.context.http_handlers = HttpPlugin.get_all()
for instance in self.context.http_handlers:
try:
output = instance.handle(context)
except Exception as e:
return [self.respond_error(context, e)]
if (output is not None):
return output
return context.fallthrough(self.invalid)
|
':type object: object
:type attribute: str
:type ui: UIElement'
| def __init__(self, object, attribute, ui):
| self.object = object
self.attribute = attribute
self.ui = ui
self.dict_mode = False
if (attribute and attribute.startswith('[') and attribute.endswith(']')):
self.dict_mode = True
self.attribute = self.attribute[1:(-1)]
|
':returns: value of the bound attribute'
| def get(self):
| if self.dict_mode:
return self.object.get(self.attribute, None)
else:
return getattr(self.object, self.attribute)
|
'Sets value of the bound attribute'
| def set(self, value):
| try:
if self.dict_mode:
self.object[self.attribute] = value
else:
setattr(self.object, self.attribute, value)
except Exception:
raise Exception(('Binder set failed: %s.%s = %s' % (self.object, self.attribute, repr(value))))
|
':type attribute: str
:type ui: UIElement
:type property: str, None'
| def __init__(self, obj, attribute, ui, property=None):
| Binding.__init__(self, obj, attribute, ui)
if (property is None):
v = self.__get_transformed()
for prop in ui.property_definitions.values():
if prop.bindtypes:
if ((type(v) in prop.bindtypes) or (v is None) or (object in prop.bindtypes)):
self.property = prop.name
break
else:
raise Exception(('Cannot bind %s.%s (%s, = %s) to %s' % (repr(obj), attribute, repr(type(v)), repr(v), ui)))
else:
self.property = property
self.oneway = (ui.bindtransform is not None)
|
'Initializes the Binder with a data object.
:type object: object'
| def setup(self, object=None):
| self.unpopulate()
if (object is not None):
self.object = object
self.__autodiscover()
return self
|
'Cancels the binding and replaces Python object / UI root.
:type object: object
:type ui: UIElement, None'
| def reset(self, object=None, ui=None):
| self.__warn_new_binder('Binder.reset(object, ui)')
self.unpopulate()
if (object is not None):
self.object = object
if ui:
self.ui = ui
return self
|
'Recursively scans UI tree for ``bind`` properties, and creates bindings.'
| def __autodiscover(self, object=None, ui=None):
| if ((object is None) and (ui is None)):
self.bindings = []
if (ui is None):
ui = self.ui
if (object is None):
object = self.object
bindables = ui.nearest((lambda x: is_bound(x)), exclude=(lambda x: ((x.parent != ui) and (x != ui) and (('{bind}context' in x.parent.properties) or x.parent.typeid.startswith('bind:')))))
for bindable in bindables:
if bindable.typeid.startswith('bind:'):
k = bindable.bind
if (k and Binding.applicable(object, k)):
self.add(bindable.binding(object, k, bindable))
continue
for prop in bindable.properties:
if ((not prop.startswith('{bind')) and (prop != 'bind')):
continue
k = bindable.properties[prop]
if (prop == '{binder}context'):
if ((bindable is not ui) and k):
if Binding.applicable(object, k):
self.__autodiscover(Binding.extract(object, k), bindable)
if (prop.startswith('{bind}') or (prop == 'bind')):
propname = (None if (prop == 'bind') else prop.split('}')[1])
if (k and Binding.applicable(object, k)):
self.add(PropertyBinding(object, k, bindable, propname))
return self
|
'Populates the bindings.'
| def populate(self):
| for binding in self.bindings:
binding.populate()
return self
|
'Unpopulates the bindings.'
| def unpopulate(self):
| for binding in self.bindings:
binding.unpopulate()
return self
|
'Updates the bindings.'
| def update(self):
| for binding in self.bindings:
binding.update()
return self
|
'Creates an element by its type ID.'
| def create_element(self, ui, typeid, *args, **kwargs):
| cls = self.get_class(typeid)
inst = cls.new(ui, context=(ui or self).context, *args, **kwargs)
inst.typeid = typeid
return inst
|
':returns: element class by element type ID'
| def get_class(self, typeid):
| if (typeid in self._element_cache):
return self._element_cache[typeid]
for cls in UIElement.get_classes():
if (cls.typeid == typeid):
self._element_cache[typeid] = cls
return cls
else:
self._element_cache[typeid] = NullElement
return NullElement
|
'Creates an element by its type ID.
:param typeid: type ID
:type typeid: str'
| def create(self, typeid, *args, **kwargs):
| return self.inflater.create_element(self, typeid, *args, **kwargs)
|
':param layout: layout spec: "<plugin id>:<layout file name without extension>"
:type layout: str
:returns: an inflated element tree of the given layout XML name
:rtype: UIElement'
| def inflate(self, layout):
| return self.inflater.inflate(self, layout)
|
'Renders the UI into JSON
:rtype: dict'
| def render(self):
| return self.root.render()
|
':param id: element ID
:type id: str
:returns: nearest element with given ID
:rtype: UIElement, None'
| def find(self, id):
| return self.root.find(id)
|
':param uid: element UID
:type uid: int
:returns: nearest element with given unique ID
:rtype: UIElement, None'
| def find_uid(self, uid):
| return self.root.find_uid(uid)
|
'Dispatches an event to an element with given UID
:param uid: element UID
:type uid: int
:param event: event name
:type event: str
:param params: event arguments
:type params: dict, None'
| def dispatch_event(self, uid, event, params=None):
| self.root.dispatch_event(uid, event, params)
|
'Checks for pending UI updates
:rtype: bool'
| def has_updates(self):
| return self.root.has_updates()
|
'Marks all pending updates as processed'
| def clear_updates(self):
| return self.root.clear_updates()
|
':param ui: UI
:type ui: :class:`ajenti.ui.UI`
:param typeid: type ID
:type typeid: str
:param children:
:type children: list'
| def __init__(self, ui, typeid=None, children=[], **kwargs):
| self.ui = ui
self._prepare()
if (typeid is not None):
self.typeid = typeid
for c in children:
self.append(c)
self.properties = {}
self.properties_dirty = {}
for prop in self._properties.values():
self.properties[prop.name] = prop.default
self.properties_dirty[prop.name] = False
for key in kwargs:
self.properties[key] = kwargs[key]
|
':returns: a deep copy of the element and its children. Property values are shallow copies.
:rtype: :class:`UIElement`'
| def clone(self, set_ui=None, set_context=None):
| o = self.__class__.__new__(self.__class__)
o._prepare()
(o.ui, o.typeid, o.context) = ((set_ui or self.ui), self.typeid, (set_context or self.context))
o.events = self.events.copy()
o.event_args = self.event_args.copy()
o.properties = self.properties.copy()
o.properties_dirty = self.properties_dirty.copy()
o.children = []
for c in self.children:
o.append(c.clone(set_ui=set_ui, set_context=set_context))
o.post_clone()
return o
|
'Returns the nearest child which matches an arbitrary predicate lambda
:param predicate: ``lambda element: bool``
:type predicate: function
:param exclude: ``lambda element: bool`` - excludes matching branches from search
:type exclude: function, None
:param descend: whether to descend inside matching elements
:type descend: bool'
| def nearest(self, predicate, exclude=None, descend=True):
| r = []
q = [self]
while (len(q) > 0):
e = q.pop(0)
if (exclude and exclude(e)):
continue
if predicate(e):
r.append(e)
if ((not descend) and (e is not self)):
continue
q.extend(e.children)
return r
|
':param id: element ID
:type id: str
:returns: the nearest child with given ID or ``None``
:rtype: :class:`UIElement`, None'
| def find(self, id):
| r = self.nearest((lambda x: (x.id == id)))
return (r[0] if (len(r) > 0) else None)
|
':param uid: element UID
:type uid: int
:returns: the nearest child with given UID or ``None``
:rtype: :class:`UIElement`, None'
| def find_uid(self, uid):
| r = self.nearest((lambda x: (x.uid == uid)))
return (r[0] if (len(r) > 0) else None)
|
':returns: the nearest child with given type ID or ``None``
:rtype: :class:`UIElement`, None'
| def find_type(self, typeid):
| r = self.nearest((lambda x: (x.typeid == typeid)))
return (r[0] if (len(r) > 0) else None)
|
'Checks if the ``element`` is in the subtree of ``self``
:param element: element
:type element: :class:`UIElement`'
| def contains(self, element):
| return (len(self.nearest((lambda x: (x == element)))) > 0)
|
':returns: a list of elements forming a path from ``self`` to ``element``
:rtype: list'
| def path_to(self, element):
| r = []
while (element != self):
r.insert(0, element)
element = element.parent
return r
|
'Renders this element and its subtree to JSON
:rtype: dict'
| def render(self):
| attributes = {'uid': self.uid, 'typeid': self.typeid, 'children': [c.render() for c in self.children if self.visible]}
attr_defaults = {'visible': True, 'client': False}
attr_map = {'children': '_c', 'typeid': '_t', 'style': '_s'}
result = {}
for (key, value) in attributes.iteritems():
if (attr_defaults.get(key, None) != value):
result[attr_map.get(key, key)] = value
for prop in self.properties:
if self.property_definitions[prop].public:
value = getattr(self, prop)
if (attr_defaults.get(prop, None) != value):
result[attr_map.get(prop, prop)] = value
return result
|
'Binds event with ID ``event`` to ``handler``. ``*args`` will be passed to the ``handler``.
:param event: event
:type event: str
:param handler: handler
:type handler: function'
| def on(self, event, handler, *args):
| self.events[event] = handler
self.event_args[event] = args
|
'Checks for pending UI updates'
| def has_updates(self):
| if (self.children_changed or self.invalidated):
return True
if any(self.properties_dirty.values()):
return True
if self.visible:
for child in self.children:
if child.has_updates():
return True
return False
|
'Marks all pending updates as processed'
| def clear_updates(self):
| self.children_changed = False
self.invalidated = False
for property in self.properties:
self.properties_dirty[property] = False
if self.visible:
for child in self.children:
child.clear_updates()
|
'Calls ``method`` on every member of the subtree
:param method: method
:type method: str'
| def broadcast(self, method, *args, **kwargs):
| if hasattr(self, method):
getattr(self, method)(*args, **kwargs)
if (not self.visible):
return
for child in self.children:
child.broadcast(method, *args, **kwargs)
|
'Dispatches an event to an element with given UID
:param uid: element UID
:type uid: int
:param event: event name
:type event: str
:param params: event arguments
:type params: dict, None'
| def dispatch_event(self, uid, event, params=None):
| if (not self.visible):
return False
if (self.uid == uid):
self.event(event, params)
return True
else:
for child in self.children:
if child.dispatch_event(uid, event, params):
for k in dir(self):
v = getattr(self, k)
if hasattr(v, '_event_id'):
element = self.find(v._event_id)
if (element and (element.uid == uid) and (v._event_name == event)):
getattr(self, k)(**(params or {}))
return True
|
'Invokes handler for ``event`` on this element with given ``**params``
:param event: event name
:type event: str
:param params: event arguments
:type params: dict, None'
| def event(self, event, params=None):
| self_event = event.replace('-', '_')
if hasattr(self, ('on_%s' % self_event)):
getattr(self, ('on_%s' % self_event))(**(params or {}))
if (event in self.events):
self.events[event](*self.event_args[event], **(params or {}))
|
'Raises the event on this element by feeding it to the UI root (so that ``@on`` methods in ancestors will work).
:param event: event name
:type event: str
:param params: event arguments
:type params: dict'
| def reverse_event(self, event, params=None):
| self.ui.dispatch_event(self.uid, event, params)
|
'Detaches all child elements'
| def empty(self):
| self.children = []
self.children_changed = True
|
'Appends a ``child``
:param child: child
:type child: :class:`UIElement`'
| def append(self, child):
| if (child in self.children):
return
self.children.append(child)
child.parent = self
self.children_changed = True
|
'Detaches this element from its parent'
| def delete(self):
| self.parent.remove(self)
|
'Detaches the ``child``
:param child: child
:type child: :class:`UIElement`'
| def remove(self, child):
| self.children.remove(child)
child.parent = None
self.children_changed = True
|
'Activate this section'
| def activate(self):
| self.context.endpoint.switch_tab(self)
|
'Loads given plugin'
| def load(self, name):
| logging.debug(('Loading plugin %s' % name))
try:
try:
mod = imp.load_module(('ajenti.plugins.%s' % name), *imp.find_module(name, [self.get_plugins_root(), self.extra_location]))
if (not hasattr(mod, 'info')):
raise PluginFormatError()
except PluginFormatError:
raise
except Exception as e:
from ajenti.api import PluginInfo
info = PluginInfo(name=name, crash=e)
self.__plugins[name] = info
raise PluginCrashed(e)
info = mod.info
info.module = mod
info.active = False
info.name = name
info.path = mod.__path__[0]
info.crash = None
if hasattr(mod, 'init'):
info.init = mod.init
self.__plugins[name] = info
for dependency in info.dependencies:
dependency.check()
info.active = True
try:
info.init()
except Exception as e:
raise PluginCrashed(e)
if (name in self.__order):
self.__order.remove(name)
self.__order.append(name)
return True
except PluginDependency.Unsatisfied as e:
raise
except PluginFormatError as e:
logging.warn((' *** [%s] Plugin error: %s' % (name, e)))
except PluginCrashed as e:
logging.warn((' *** [%s] Plugin crashed: %s' % (name, e)))
print e.traceback
info.crash = e
except Dependency.Unsatisfied as e:
logging.debug((' *** [%s] skipping due to %s' % (name, e)))
info.crash = e
except PluginLoadError as e:
logging.warn((' *** [%s] Plugin failed to load: %s' % (name, e)))
info.crash = e
|
'Initializes instance variables, creates manager instance and tests connection
@return: Nothing'
| def setup(self):
| addr = self.classconfig['addr']
password = self.classconfig['password']
if (not addr):
raise Exception('No address specified')
(host, colon, port) = addr.partition(':')
try:
if colon:
self._m = manager.manager(host=host, port=int(port), password=password)
else:
self._m = manager.manager(path=addr, password=password)
self.getpid()
except Exception as e:
raise Exception(str(e))
|
'OpenVPN management interface is unable to handle more than one connection.
This method is used to connect and disconnect (if was not connected manually) every
time plugin wants to execute a command.
@param func: Function to call
@param args: Argument List
@return: Function result'
| def _execute(self, func, *args):
| if (not self._m.connected):
self._m.connect()
result = self._execute(func, *args)
self._m.disconnect()
else:
result = func(*args)
return result
|
'Calls superclass constructor and initializes instance variables.'
| def __init__(self, *args, **kwargs):
| super(lsocket, self).__init__(*args, **kwargs)
self._b = ''
|
'Adds CRLF to the supplied line and sends it
@type line: str
@param line: Line to send'
| def sendl(self, line):
| self.send((line + CRLF))
|
'Fills internal buffer with data from socket and returns first found line.
@type peek: Bool
@param peek: Keeps line in the buffer if true
@rtype: str
@return: First found line'
| def recvl(self, peek=False):
| while True:
i = self._b.find(CRLF)
if (i == (-1)):
self._b += self.recv(1024)
else:
line = self._b[:i]
if (not peek):
self._b = self._b[(i + 2):]
return line
|
'Fills internal buffer with data from socket and returns first B{count} received bytes.
@type count: int
@param count: Number of bytes to recieve
@type peek: Bool
@param peek: Keeps bytes in the buffer if true
@rtype: str
@return: First B{count} received bytes'
| def recvb(self, count, peek=False):
| while True:
if (count > len(self._b)):
self._b += self.recv((count - len(self._b)))
else:
bytez = self._b[:count]
if (not peek):
self._b = self._b[count:]
return bytez
|
'Same as peekb(count, peek = True)
@type count: int
@param count: Number of bytes to peek
@rtype: str
@return: First B{count} received bytes'
| def peekb(self, count):
| return self.recvb(count, peek=True)
|
'Same as recvl(peek = True)
@rtype: str
@return: First found line'
| def peekl(self):
| return self.recvl(peek=True)
|
'Returns list of lines received until the line matching the B{marker} was found.
@type marker: str
@param marker: Marker
@rtype: list
@return: List of strings'
| def recvuntil(self, marker):
| lines = []
while True:
line = self.recvl()
if (line == marker):
return lines
lines.append(line)
|
'Initializes instance variables.
@type host: str
@param host: Hostname or address to connect to
@type port: int
@param port: Port number to connect to
@type path: str
@param path: Path to UNIX socket to connect to
@type password: str
@param password: Password
@type timeout: int
@param timeout: Connection timeout
@note: host/port and path should not be specified at the same time'
| def __init__(self, host=None, port=None, path=None, password='', timeout=5):
| assert (bool((host and port)) ^ bool(path))
(self._host, self._port, self._path, self._password, self._timeout) = (host, port, path, password, timeout)
self._s = None
|
'Initializes and opens a socket. Performs authentication if needed.'
| def connect(self):
| if self._path:
self._s = lsocket(socket.AF_UNIX)
self._s.settimeout(self._timeout)
self._s.connect(self._path)
else:
ai = socket.getaddrinfo(self._host, self._port, 0, socket.SOCK_STREAM)[0]
self._s = lsocket(ai[0], ai[1], ai[2])
self._s.settimeout(self._timeout)
self._s.connect((self._host, self._port))
if (self._s.peekb(len(PASSWORD_PROMPT)) == PASSWORD_PROMPT):
self._s.recvb(len(PASSWORD_PROMPT))
self._s.sendl(self._password)
if (self._s.peekb(len(PASSWORD_PROMPT)) == PASSWORD_PROMPT):
self._s.recvb(len(PASSWORD_PROMPT))
raise Exception('Authentication error')
else:
self._s.recvl()
|
'Closes a socket.'
| def disconnect(self):
| self._s.close()
self._s = None
|
'Returns socket status.'
| @property
def connected(self):
| return bool(self._s)
|
'Executes command and returns response as a list of lines.
@type name: str
@param name: Command name
@type args: list
@param args: Argument List
@rtype: list
@return: List of strings'
| def execute(self, name, *args):
| cmd = name
if args:
cmd += (' ' + ' '.join(args))
self._s.sendl(cmd)
while self._s.peekl().startswith(NOTIFICATION_PREFIX):
self._s.recvl()
if self._s.peekl().startswith(STATUS_SUCCESS):
return [self._s.recvl()[len(STATUS_SUCCESS):]]
elif self._s.peekl().startswith(STATUS_ERROR):
raise Exception(self._s.recvl()[len(STATUS_ERROR):])
return self._s.recvuntil(END_MARKER)
|
'Executes "status 2" command and returns response as a dictionary.
@rtype: dict
@return: Dictionary'
| def status(self):
| status = dict()
status['clients'] = list()
for line in self.execute('status', '2'):
fields = line.split(',')
if (fields[0] == 'TITLE'):
status['title'] = fields[1]
elif (fields[0] == 'TIME'):
status['time'] = fields[1]
status['timeu'] = fields[2]
elif (fields[0] == 'HEADER'):
continue
elif (fields[0] == 'CLIENT_LIST'):
status['clients'].append(dict(zip(('cn', 'raddress', 'vaddress', 'brecv', 'bsent', 'connsince', 'connsinceu'), fields[1:])))
return status
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.