INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Update CPU stats using the input method.
def update(self): """Update CPU stats using the input method.""" # Grab stats into self.stats if self.input_method == 'local': stats = self.update_local() elif self.input_method == 'snmp': stats = self.update_snmp() else: stats = self.get_init...
Update CPU stats using psutil.
def update_local(self): """Update CPU stats using psutil.""" # Grab CPU stats using psutil's cpu_percent and cpu_times_percent # Get all possible values for CPU stats: user, system, idle, # nice (UNIX), iowait (Linux), irq (Linux, FreeBSD), steal (Linux 2.6.11+) # The following s...
Update CPU stats using SNMP.
def update_snmp(self): """Update CPU stats using SNMP.""" # Init new stats stats = self.get_init_value() # Update stats using SNMP if self.short_system_name in ('windows', 'esxi'): # Windows or VMWare ESXi # You can find the CPU utilization of windows sy...
Update stats views.
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert and log for key in ['user', 'system', 'iowait']: if key in self.stats: self.views[key]['decora...
Update Wifi stats using the input method. Stats is a list of dict (one dict per hotspot) :returns: list -- Stats is a list of dict (hotspot)
def update(self): """Update Wifi stats using the input method. Stats is a list of dict (one dict per hotspot) :returns: list -- Stats is a list of dict (hotspot) """ # Init new stats stats = self.get_init_value() # Exist if we can not grab the stats if ...
Overwrite the default get_alert method. Alert is on signal quality where lower is better... :returns: string -- Signal alert
def get_alert(self, value): """Overwrite the default get_alert method. Alert is on signal quality where lower is better... :returns: string -- Signal alert """ ret = 'OK' try: if value <= self.get_limit('critical', stat_name=self.plugin_name): ...
Update stats views.
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert on signal thresholds for i in self.stats: self.views[i[self.get_key()]]['signal']['decoration'] = self.get_ale...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if not self.stats or import_error_tag or self.is_disable(): return r...
Update the FS stats using the input method.
def update(self): """Update the FS stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Grab the stats using the psutil disk_partitions # If 'a...
Update stats views.
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert for i in self.stats: self.views[i[self.get_key()]]['used']['decoration'] = self.get_alert( i['...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if not self.stats or self.is_disable(): return ret # Max si...
Update RAM memory stats using the input method.
def update(self): """Update RAM memory stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Grab MEM using the psutil virtual_memory method vm_s...
Update stats views.
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() # Add specifics informations # Alert and log self.views['used']['decoration'] = self.get_alert_log(self.stats['used'], maximum=self.stats['total']) # O...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and plugin not disabled if not self.stats or self.is_disable(): return ret # Build the s...
Add an new item (key, value) to the current history.
def add(self, key, value, description='', history_max_size=None): """Add an new item (key, value) to the current history.""" if key not in self.stats_history: self.stats_history[key] = GlancesAttribute(key, descri...
Get the history as a dict of list
def get(self, nb=0): """Get the history as a dict of list""" return {i: self.stats_history[i].history_raw(nb=nb) for i in self.stats_history}
Get the history as a dict of list (with list JSON compliant)
def get_json(self, nb=0): """Get the history as a dict of list (with list JSON compliant)""" return {i: self.stats_history[i].history_json(nb=nb) for i in self.stats_history}
Load AMP parameters from the configuration file.
def load_config(self, config): """Load AMP parameters from the configuration file.""" # Read AMP confifuration. # For ex, the AMP foo should have the following section: # # [foo] # enable=true # regex=\/usr\/bin\/nginx # refresh=60 # # and...
Return True|False if the AMP is enabled in the configuration file (enable=true|false).
def enable(self): """Return True|False if the AMP is enabled in the configuration file (enable=true|false).""" ret = self.get('enable') if ret is None: return False else: return ret.lower().startswith('true')
Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false).
def one_line(self): """Return True|False if the AMP shoukd be displayed in oneline (one_lineline=true|false).""" ret = self.get('one_line') if ret is None: return False else: return ret.lower().startswith('true')
Return True is the AMP should be updated: - AMP is enable - only update every 'refresh' seconds
def should_update(self): """Return True is the AMP should be updated: - AMP is enable - only update every 'refresh' seconds """ if self.timer.finished(): self.timer.set(self.refresh()) self.timer.reset() return self.enable() return Fals...
Store the result (string) into the result key of the AMP if one_line is true then replace \n by separator
def set_result(self, result, separator=''): """Store the result (string) into the result key of the AMP if one_line is true then replace \n by separator """ if self.one_line(): self.configs['result'] = str(result).replace('\n', separator) else: self.config...
Return the result of the AMP (as a string)
def result(self): """ Return the result of the AMP (as a string)""" ret = self.get('result') if ret is not None: ret = u(ret) return ret
Wrapper for the children update
def update_wrapper(self, process_list): """Wrapper for the children update""" # Set the number of running process self.set_count(len(process_list)) # Call the children update method if self.should_update(): return self.update(process_list) else: re...
Update processes stats using the input method.
def update(self): """Update processes stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Here, update is call for processcount AND processlist ...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist and display plugin enable... if args.disable_process: msg = "PROCESSES DISABLED (press 'z' to dis...
Parse the decision tree and return the message. Note: message corresponding to the current threasholds values
def global_message(): """Parse the decision tree and return the message. Note: message corresponding to the current threasholds values """ # Compute the weight for each item in the tree current_thresholds = glances_thresholds.get() for i in tree: i['weight'] = sum([current_thresholds[t]...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if display plugin enable... if not self.stats or self.is_disable(): return ret # Build the string messa...
Compare a with b using the tolerance (if numerical).
def approx_equal(self, a, b, tolerance=0.0): """Compare a with b using the tolerance (if numerical).""" if str(int(a)).isdigit() and str(int(b)).isdigit(): return abs(a - b) <= max(abs(a), abs(b)) * tolerance else: return a == b
Export the stats to the JSON file.
def export(self, name, columns, points): """Export the stats to the JSON file.""" # Check for completion of loop for all exports if name == self.plugins_to_export()[0] and self.buffer != {}: # One whole loop has been completed # Flush stats to file logger.deb...
Overwrite the exit method to close threads.
def exit(self): """Overwrite the exit method to close threads.""" for t in itervalues(self.thread_list): t.stop() # Call the father class super(Plugin, self).exit()
Overwrite the default export method. - Only exports containers - The key is the first container name
def get_export(self): """Overwrite the default export method. - Only exports containers - The key is the first container name """ ret = [] try: ret = self.stats['containers'] except KeyError as e: logger.debug("docker plugin - Docker expor...
Connect to the Docker server.
def connect(self): """Connect to the Docker server.""" try: ret = docker.from_env() except Exception as e: logger.error("docker plugin - Can not connect to Docker ({})".format(e)) ret = None return ret
Return the all tag of the Glances/Docker configuration file. # By default, Glances only display running containers # Set the following key to True to display all containers all=True
def _all_tag(self): """Return the all tag of the Glances/Docker configuration file. # By default, Glances only display running containers # Set the following key to True to display all containers all=True """ all_tag = self.get_conf_value('all') if len(all_tag) =...
Update Docker stats using the input method.
def update(self): """Update Docker stats using the input method.""" # Init new stats stats = self.get_init_value() # The Docker-py lib is mandatory if import_error_tag: return self.stats if self.input_method == 'local': # Update stats ...
Return the container CPU usage. Input: id is the full container id all_stats is the output of the stats method of the Docker API Output: a dict {'total': 1.49}
def get_docker_cpu(self, container_id, all_stats): """Return the container CPU usage. Input: id is the full container id all_stats is the output of the stats method of the Docker API Output: a dict {'total': 1.49} """ cpu_new = {} ret = {'total': 0.0} ...
Return the container MEMORY. Input: id is the full container id all_stats is the output of the stats method of the Docker API Output: a dict {'rss': 1015808, 'cache': 356352, 'usage': ..., 'max_usage': ...}
def get_docker_memory(self, container_id, all_stats): """Return the container MEMORY. Input: id is the full container id all_stats is the output of the stats method of the Docker API Output: a dict {'rss': 1015808, 'cache': 356352, 'usage': ..., 'max_usage': ...} """ ...
Return the container network usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}. with: time_since_update: number of seconds elapsed between the latest grab rx: Number of byte rece...
def get_docker_network(self, container_id, all_stats): """Return the container network usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'rx': 10, 'tx': 65}. with: time_since_update: number of seconds e...
Return the container IO usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'ior': 10, 'iow': 65}. with: time_since_update: number of seconds elapsed between the latest grab ior: Number of byte readed...
def get_docker_io(self, container_id, all_stats): """Return the container IO usage using the Docker API (v1.0 or higher). Input: id is the full container id Output: a dict {'time_since_update': 3000, 'ior': 10, 'iow': 65}. with: time_since_update: number of seconds elapsed b...
Update stats views.
def update_views(self): """Update stats views.""" # Call the father's method super(Plugin, self).update_views() if 'containers' not in self.stats: return False # Add specifics informations # Alert for i in self.stats['containers']: # Init...
Return the dict to display in the curse interface.
def msg_curse(self, args=None, max_width=None): """Return the dict to display in the curse interface.""" # Init the return message ret = [] # Only process if stats exist (and non null) and display plugin enable... if not self.stats \ or 'containers' not in self.stats ...
Build the container name.
def _msg_name(self, container, max_width): """Build the container name.""" name = container['name'] if len(name) > max_width: name = '_' + name[-max_width + 1:] else: name = name[:max_width] return ' {:{width}}'.format(name, width=max_width)
Grab the stats. Infinite loop, should be stopped by calling the stop() method
def run(self): """Grab the stats. Infinite loop, should be stopped by calling the stop() method """ for i in self._stats_stream: self._stats = i time.sleep(0.1) if self.stopped(): break
Stop the thread.
def stop(self, timeout=None): """Stop the thread.""" logger.debug("docker plugin - Close thread for container {}".format(self._container.name)) self._stopper.set()
Return true if plugin is enabled.
def is_enable(self, plugin_name=None): """Return true if plugin is enabled.""" if not plugin_name: plugin_name = self.plugin_name try: d = getattr(self.args, 'disable_' + plugin_name) except AttributeError: return True else: return ...
Return the object 'd' in a JSON format. Manage the issue #815 for Windows OS
def _json_dumps(self, d): """Return the object 'd' in a JSON format. Manage the issue #815 for Windows OS """ try: return json.dumps(d) except UnicodeDecodeError: return json.dumps(d, ensure_ascii=False)
Init the stats history (dict of GlancesAttribute).
def init_stats_history(self): """Init the stats history (dict of GlancesAttribute).""" if self.history_enable(): init_list = [a['name'] for a in self.get_items_history_list()] logger.debug("Stats history activated for plugin {} (items: {})".format(self.plugin_name, init_list)) ...
Reset the stats history (dict of GlancesAttribute).
def reset_stats_history(self): """Reset the stats history (dict of GlancesAttribute).""" if self.history_enable(): reset_list = [a['name'] for a in self.get_items_history_list()] logger.debug("Reset history for plugin {} (items: {})".format(self.plugin_name, reset_list)) ...
Update stats history.
def update_stats_history(self): """Update stats history.""" # If the plugin data is a dict, the dict's key should be used if self.get_key() is None: item_name = '' else: item_name = self.get_key() # Build the history if self.get_export() and self.h...
Return the history (RAW format). - the stats history (dict of list) if item is None - the stats history for the given item (list) instead - None if item did not exist in the history
def get_raw_history(self, item=None, nb=0): """Return the history (RAW format). - the stats history (dict of list) if item is None - the stats history for the given item (list) instead - None if item did not exist in the history """ s = self.stats_history.get(nb=nb) ...
Return the history (JSON format). - the stats history (dict of list) if item is None - the stats history for the given item (list) instead - None if item did not exist in the history Limit to lasts nb items (all if nb=0)
def get_json_history(self, item=None, nb=0): """Return the history (JSON format). - the stats history (dict of list) if item is None - the stats history for the given item (list) instead - None if item did not exist in the history Limit to lasts nb items (all if nb=0) ""...
Return the stats history (JSON format).
def get_stats_history(self, item=None, nb=0): """Return the stats history (JSON format).""" s = self.get_json_history(nb=nb) if item is None: return self._json_dumps(s) if isinstance(s, dict): try: return self._json_dumps({item: s[item]}) ...
Get the trend regarding to the last nb values. The trend is the diff between the mean of the last nb values and the current one.
def get_trend(self, item, nb=6): """Get the trend regarding to the last nb values. The trend is the diff between the mean of the last nb values and the current one. """ raw_history = self.get_raw_history(item=item, nb=nb) if raw_history is None or len(raw_history) < nb: ...
Get the stats sorted by an alias (if present) or key.
def sorted_stats(self): """Get the stats sorted by an alias (if present) or key.""" key = self.get_key() return sorted(self.stats, key=lambda stat: tuple(map( lambda part: int(part) if part.isdigit() else part.lower(), re.split(r"(\d+|\D+)", self.has_alias(stat[key]) or s...
Update stats using SNMP. If bulk=True, use a bulk request instead of a get request.
def get_stats_snmp(self, bulk=False, snmp_oid=None): """Update stats using SNMP. If bulk=True, use a bulk request instead of a get request. """ snmp_oid = snmp_oid or {} from glances.snmp import GlancesSNMPClient # Init the SNMP request clientsnmp = GlancesSNMP...
Return the stats object for a specific item in JSON format. Stats should be a list of dict (processlist, network...)
def get_stats_item(self, item): """Return the stats object for a specific item in JSON format. Stats should be a list of dict (processlist, network...) """ if isinstance(self.stats, dict): try: return self._json_dumps({item: self.stats[item]}) exc...
Return the stats object for a specific item=value in JSON format. Stats should be a list of dict (processlist, network...)
def get_stats_value(self, item, value): """Return the stats object for a specific item=value in JSON format. Stats should be a list of dict (processlist, network...) """ if not isinstance(self.stats, list): return None else: if value.isdigit(): ...
Update the stats views. The V of MVC A dict of dict with the needed information to display the stats. Example for the stat xxx: 'xxx': {'decoration': 'DEFAULT', 'optional': False, 'additional': False, 'splittable': False}
def update_views(self): """Update the stats views. The V of MVC A dict of dict with the needed information to display the stats. Example for the stat xxx: 'xxx': {'decoration': 'DEFAULT', 'optional': False, 'additional': False, 'sp...
Return the views object. If key is None, return all the view for the current plugin else if option is None return the view for the specific key (all option) else return the view fo the specific key/option Specify item if the stats are stored in a dict of dict (ex: NETWORK, FS...)
def get_views(self, item=None, key=None, option=None): """Return the views object. If key is None, return all the view for the current plugin else if option is None return the view for the specific key (all option) else return the view fo the specific key/option Specify item if...
Return the views (in JSON).
def get_json_views(self, item=None, key=None, option=None): """Return the views (in JSON).""" return self._json_dumps(self.get_views(item, key, option))
Load limits from the configuration file, if it exists.
def load_limits(self, config): """Load limits from the configuration file, if it exists.""" # By default set the history length to 3 points per second during one day self._limits['history_size'] = 28800 if not hasattr(config, 'has_section'): return False # Read the ...
Return the stat name with an optional header
def get_stat_name(self, header=""): """"Return the stat name with an optional header""" ret = self.plugin_name if header != "": ret += '_' + header return ret
Manage the action for the current stat.
def manage_action(self, stat_name, trigger, header, action_key): """Manage the action for the current stat.""" # Here is a command line for the current trigger ? try: command, repeat = self.get_li...
Get the alert log.
def get_alert_log(self, current=0, minimum=0, maximum=100, header="", action_key=None): """Get the alert log.""" return self.get_alert(current=current, minimum=mini...
Return the limit value for the alert.
def get_limit(self, criticity, stat_name=""): """Return the limit value for the alert.""" # Get the limit for stat + header # Exemple: network_wlan0_rx_careful try: limit = self._limits[stat_name + '_' + criticity] except KeyError: # Try fallback to plugin...
Return the tuple (action, repeat) for the alert. - action is a command line - repeat is a bool
def get_limit_action(self, criticity, stat_name=""): """Return the tuple (action, repeat) for the alert. - action is a command line - repeat is a bool """ # Get the action for stat + header # Exemple: network_wlan0_rx_careful_action # Action key available ? ...
Return the log tag for the alert.
def get_limit_log(self, stat_name, default_action=False): """Return the log tag for the alert.""" # Get the log tag for stat + header # Exemple: network_wlan0_rx_log try: log_tag = self._limits[stat_name + '_log'] except KeyError: # Try fallback to plugin ...
Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var.
def get_conf_value(self, value, header="", plugin_name=None): """Return the configuration (header_) value for the current plugin. ...or the one given by the plugin_name var. """ if plugin_name is None: # If not default use the current plugin name plugin_name = se...
Return True if the value is in the hide configuration list. The hide configuration list is defined in the glances.conf file. It is a comma separed list of regexp. Example for diskio: hide=sda2,sda5,loop.*
def is_hide(self, value, header=""): """Return True if the value is in the hide configuration list. The hide configuration list is defined in the glances.conf file. It is a comma separed list of regexp. Example for diskio: hide=sda2,sda5,loop.* """ # TODO: possib...
Return the alias name for the relative header or None if nonexist.
def has_alias(self, header): """Return the alias name for the relative header or None if nonexist.""" try: # Force to lower case (issue #1126) return self._limits[self.plugin_name + '_' + header.lower() + '_' + 'alias'][0] except (KeyError, IndexError): # logg...
Return a dict with all the information needed to display the stat. key | description ---------------------------- display | Display the stat (True or False) msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ]) align | Message position
def get_stats_display(self, args=None, max_width=None): """Return a dict with all the information needed to display the stat. key | description ---------------------------- display | Display the stat (True or False) msgdict | Message to display (list of dict [{ 'msg': msg, '...
Return a dict with. Where: msg: string decoration: DEFAULT: no decoration UNDERLINE: underline BOLD: bold TITLE: for stat title PROCESS: for process name STATUS: for process status ...
def curse_add_line(self, msg, decoration="DEFAULT", optional=False, additional=False, splittable=False): """Return a dict with. Where: msg: string decoration: DEFAULT: no decoration UNDERLINE: underlin...
Make a nice human-readable string out of number. Number of decimal places increases as quantity approaches 1. CASE: 613421788 RESULT: 585M low_precision: 585M CASE: 5307033647 RESULT: 4.94G low_precision: 4.9G CASE: 44968414685 RESULT: 41.9G...
def auto_unit(self, number, low_precision=False, min_symbol='K' ): """Make a nice human-readable string out of number. Number of decimal places increases as quantity approaches 1. CASE: 613421788 RESULT: 585M low_precision: ...
Return the trend message. Do not take into account if trend < significant
def trend_msg(self, trend, significant=1): """Return the trend message. Do not take into account if trend < significant """ ret = '-' if trend is None: ret = ' ' elif trend > significant: ret = '/' elif trend < -significant: re...
Check if the plugin is enabled.
def _check_decorator(fct): """Check if the plugin is enabled.""" def wrapper(self, *args, **kw): if self.is_enable(): ret = fct(self, *args, **kw) else: ret = self.stats return ret return wrapper
Log (DEBUG) the result of the function fct.
def _log_result_decorator(fct): """Log (DEBUG) the result of the function fct.""" def wrapper(*args, **kw): ret = fct(*args, **kw) logger.debug("%s %s %s return %s" % ( args[0].__class__.__name__, args[0].__class__.__module__[len('glances_'):], ...
Update HDD stats using the input method.
def update(self): """Update HDD stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib stats = self.glancesgrabhddtemp.get() else: # Update...
Fetch the data from hddtemp daemon.
def fetch(self): """Fetch the data from hddtemp daemon.""" # Taking care of sudden deaths/stops of hddtemp daemon try: sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sck.connect((self.host, self.port)) data = b'' while True: ...
:param prekeyIds: :type prekeyIds: list :return: :rtype:
def set_prekeys_as_sent(self, prekeyIds): """ :param prekeyIds: :type prekeyIds: list :return: :rtype: """ logger.debug("set_prekeys_as_sent(prekeyIds=[%d prekeyIds])" % len(prekeyIds)) self._store.preKeyStore.setAsSent([prekey.getId() for prekey in prekey...
:param recipient_id: :type recipient_id: str :param data: :type data: bytes :return: :rtype:
def encrypt(self, recipient_id, message): logger.debug("encrypt(recipientid=%s, message=%s)" % (recipient_id, message)) """ :param recipient_id: :type recipient_id: str :param data: :type data: bytes :return: :rtype: """ cipher = self._get_...
:param groupid: :type groupid: str :param message: :type message: bytes :return: :rtype:
def group_encrypt(self, groupid, message): """ :param groupid: :type groupid: str :param message: :type message: bytes :return: :rtype: """ logger.debug("group_encrypt(groupid=%s, message=%s)" % (groupid, message)) group_cipher = self._get_...
:param groupid: :type groupid: str :param participantid: :type participantid: str :param skmsgdata: :type skmsgdata: bytearray :return: :rtype:
def group_create_session(self, groupid, participantid, skmsgdata): """ :param groupid: :type groupid: str :param participantid: :type participantid: str :param skmsgdata: :type skmsgdata: bytearray :return: :rtype: """ logger.debug(...
:param username: :type username: str :param prekeybundle: :type prekeybundle: PreKeyBundle :return: :rtype:
def create_session(self, username, prekeybundle, autotrust=False): """ :param username: :type username: str :param prekeybundle: :type prekeybundle: PreKeyBundle :return: :rtype: """ logger.debug("create_session(username=%s, prekeybunder=[omitted],...
:param username: :type username: str :return: :rtype:
def session_exists(self, username): """ :param username: :type username: str :return: :rtype: """ logger.debug("session_exists(%s)?" % username) return self._store.containsSession(username, 1)
:param data: :type data: dict :return: :rtype: dict
def transform(self, data): """ :param data: :type data: dict :return: :rtype: dict """ out = {} for key, val in data.items(): if key in self._transform_map: target = self._transform_map[key] key, val = target(key...
:param username: :type username: :return: :rtype:
def load(self, username): """ :param username: :type username: :return: :rtype: """ config_dir = StorageTools.getStorageForPhone(username) logger.debug("Detecting config for username=%s, dir=%s" % (username, config_dir)) exhausted = [] for ...
:param type: :type type: int :return: :rtype:
def _type_to_str(self, type): """ :param type: :type type: int :return: :rtype: """ for key, val in self.TYPE_NAMES.items(): if key == type: return val
:param path: :type path: :return: :rtype:
def load_path(self, path): """ :param path: :type path: :return: :rtype: """ logger.debug("load_path(path=%s)" % path) if os.path.isfile(path): configtype = self.guess_type(path) logger.debug("Detected config type: %s" % self._type_...
:type protocolTreeNode: ProtocolTreeNode
def receive(self, protocolTreeNode): """ :type protocolTreeNode: ProtocolTreeNode """ if not self.processIqRegistry(protocolTreeNode): if protocolTreeNode.tag == "notification" and protocolTreeNode["type"] == "encrypt": self.onEncryptNotification(protocolTreeN...
sends prekeys :return: :rtype:
def flush_keys(self, signed_prekey, prekeys, reboot_connection=False): """ sends prekeys :return: :rtype: """ preKeysDict = {} for prekey in prekeys: keyPair = prekey.getKeyPair() preKeysDict[self.adjustId(prekey.getId())] = self.adjustArra...
:param layer: An optional layer to put on top of default stack :param axolotl: E2E encryption enabled/ disabled :return: YowStack
def getDefaultStack(layer = None, axolotl = False, groups = True, media = True, privacy = True, profiles = True): """ :param layer: An optional layer to put on top of default stack :param axolotl: E2E encryption enabled/ disabled :return: YowStack """ allLayers = YowStac...
:type entity: IqProtocolEntity
def processIqRegistry(self, entity): """ :type entity: IqProtocolEntity """ if entity.getTag() == "iq": iq_id = entity.getId() if iq_id in self.iqRegistry: originalIq, successClbk, errorClbk = self.iqRegistry[iq_id] del self.iqRegis...
:param data: :type data: dict :return: :rtype:
def transform(self, data): """ :param data: :type data: dict :return: :rtype: """ out=[] keys = sorted(data.keys()) for k in keys: out.append("%s=%s" % (k, data[k])) return "\n".join(out)
:param config: :type config: yowsup.config.base.config.Config :return: :rtype: bytes
def serialize(self, config): """ :param config: :type config: yowsup.config.base.config.Config :return: :rtype: bytes """ for transform in self._transforms: config = transform.transform(config) return config
:type cls: type :param data: :type data: bytes :return: :rtype: yowsup.config.base.config.Config
def deserialize(self, data): """ :type cls: type :param data: :type data: bytes :return: :rtype: yowsup.config.base.config.Config """ for transform in self._transforms[::-1]: data = transform.reverse(data) return data
:type senderKeyName: SenderKeName :type senderKeyRecord: SenderKeyRecord
def storeSenderKey(self, senderKeyName, senderKeyRecord): """ :type senderKeyName: SenderKeName :type senderKeyRecord: SenderKeyRecord """ q = "INSERT INTO sender_keys (group_id, sender_id, record) VALUES(?,?, ?)" cursor = self.dbConn.cursor() serialized = senderK...
:type senderKeyName: SenderKeyName
def loadSenderKey(self, senderKeyName): """ :type senderKeyName: SenderKeyName """ q = "SELECT record FROM sender_keys WHERE group_id = ? and sender_id = ?" cursor = self.dbConn.cursor() cursor.execute(q, (senderKeyName.getGroupId(), senderKeyName.getSender().getName())) ...
:type entity: IqProtocolEntity
def sendIq(self, entity): """ :type entity: IqProtocolEntity """ if entity.getType() == IqProtocolEntity.TYPE_SET and entity.getXmlns() == "w:m": #media upload! self._sendIq(entity, self.onRequestUploadSuccess, self.onRequestUploadError)
:type protocolTreeNode: ProtocolTreeNode
def receive(self, protocolTreeNode): """ :type protocolTreeNode: ProtocolTreeNode """ if not self.processIqRegistry(protocolTreeNode): if protocolTreeNode.tag == "message": self.onMessage(protocolTreeNode) elif not protocolTreeNode.tag == "receipt"...
:param data: :type data: bytearray | bytes :return: :rtype:
def send(self, data): """ :param data: :type data: bytearray | bytes :return: :rtype: """ data = bytes(data) if type(data) is not bytes else data self._wa_noiseprotocol.send(data)