INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Scan a data block for matching signatures. @data - A string of data to scan. @dlen - If specified, signatures at offsets larger than dlen will be ignored. Returns a list of SignatureResult objects.
def scan(self, data, dlen=None): ''' Scan a data block for matching signatures. @data - A string of data to scan. @dlen - If specified, signatures at offsets larger than dlen will be ignored. Returns a list of SignatureResult objects. ''' results = [] ma...
Load signatures from a file. @fname - Path to signature file. Returns None.
def load(self, fname): ''' Load signatures from a file. @fname - Path to signature file. Returns None. ''' # Magic files must be ASCII, else encoding issues can arise. fp = open(fname, "r") lines = fp.readlines() self.parse(lines) fp.clos...
Parse signature file lines. @lines - A list of lines from a signature file. Returns None.
def parse(self, lines): ''' Parse signature file lines. @lines - A list of lines from a signature file. Returns None. ''' signature = None for line in lines: # Split at the first comment delimiter (if any) and strip the # result ...
Sets the appropriate verbosity. Must be called after self._test_target_files so that self.target_files is properly set.
def _set_verbosity(self): ''' Sets the appropriate verbosity. Must be called after self._test_target_files so that self.target_files is properly set. ''' # If more than one target file was specified, enable verbose mode; else, there is # nothing in some outputs to indicat...
Checks to see if a file should be scanned based on file name include/exclude filters. Most useful for matryoshka scans where only certian files are desired. @fp - An instances of binwalk.common.BlockFile Returns True if the file should be scanned, False if not.
def file_name_filter(self, fp): ''' Checks to see if a file should be scanned based on file name include/exclude filters. Most useful for matryoshka scans where only certian files are desired. @fp - An instances of binwalk.common.BlockFile Returns True if the file should be sca...
Opens the specified file with all pertinent configuration settings.
def open_file(self, fname, length=None, offset=None, swap=None, block=None, peek=None): ''' Opens the specified file with all pertinent configuration settings. ''' if length is None: length = self.length if offset is None: offset = self.offset if s...
Checks if the target files can be opened. Any files that cannot be opened are removed from the self.target_files list.
def _open_target_files(self): ''' Checks if the target files can be opened. Any files that cannot be opened are removed from the self.target_files list. ''' # Validate the target files listed in target_files for tfile in self.files: # Ignore directories. ...
Called automatically by self.result.
def validate(self, r): ''' Called automatically by self.result. ''' if self.show_invalid: r.valid = True elif r.valid: if not r.description: r.valid = False if r.size and (r.size + r.offset) > r.file.size: r.val...
Obtain a list of all user and system plugin modules. Returns a dictionary of: { 'user' : { 'modules' : [list, of, module, names], 'descriptions' : {'module_name' : 'module pydoc string'}, ...
def list_plugins(self): ''' Obtain a list of all user and system plugin modules. Returns a dictionary of: { 'user' : { 'modules' : [list, of, module, names], 'descriptions' : {'module_name' : 'modul...
Performs a Shannon entropy analysis on a given block of data.
def shannon(self, data): ''' Performs a Shannon entropy analysis on a given block of data. ''' entropy = 0 if data: length = len(data) seen = dict(((chr(x), 0) for x in range(0, 256))) for byte in data: seen[byte] += 1 ...
Performs an entropy analysis based on zlib compression ratio. This is faster than the shannon entropy analysis, but not as accurate.
def gzip(self, data, truncate=True): ''' Performs an entropy analysis based on zlib compression ratio. This is faster than the shannon entropy analysis, but not as accurate. ''' # Entropy is a simple ratio of: <zlib compressed size> / <original # size> e = float(f...
Convert a null-terminated string field to a python string.
def nts(self, s): """ Convert a null-terminated string field to a python string. """ # Use the string up to the first null char. p = s.find("\0") if p == -1: return s return s[:p]
Convert a number field to a python number.
def nti(self, s): """ Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0x80): try: n = int(self.nts(s) or "0", 8) except ValueError: ...
Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag.
def debug(msg): ''' Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag. ''' if DEBUG: sys.stderr.write("DEBUG: " + msg + "\n") sys.stderr.flush()
Generate an MD5 hash of the specified file. @file_name - The file to hash. Returns an MD5 hex digest string.
def file_md5(file_name): ''' Generate an MD5 hash of the specified file. @file_name - The file to hash. Returns an MD5 hex digest string. ''' md5 = hashlib.md5() with open(file_name, 'rb') as f: for chunk in iter(lambda: f.read(128 * md5.block_size), b''): md5.update(c...
Obtains the size of a given file. @filename - Path to the file. Returns the size of the file.
def file_size(filename): ''' Obtains the size of a given file. @filename - Path to the file. Returns the size of the file. ''' # Using open/lseek works on both regular files and block devices fd = os.open(filename, os.O_RDONLY) try: return os.lseek(fd, 0, os.SEEK_END) excep...
Returns a string comprised of all data in between double quotes. @quoted_string - String to get quoted data from. Returns a string of quoted data on success. Returns a blank string if no quoted data is present.
def get_quoted_strings(quoted_string): ''' Returns a string comprised of all data in between double quotes. @quoted_string - String to get quoted data from. Returns a string of quoted data on success. Returns a blank string if no quoted data is present. ''' try: # This regex grabs ...
Creates a unique file name based on the specified base name. @base_name - The base name to use for the unique file name. @extension - The file extension to use for the unique file name. Returns a unique file string.
def unique_file_name(base_name, extension=''): ''' Creates a unique file name based on the specified base name. @base_name - The base name to use for the unique file name. @extension - The file extension to use for the unique file name. Returns a unique file string. ''' idcount = 0 if...
A strings generator, similar to the Unix strings utility. @filename - The file to search for strings in. @minimum - The minimum string length to search for. Yeilds printable ASCII strings from filename.
def strings(filename, minimum=4): ''' A strings generator, similar to the Unix strings utility. @filename - The file to search for strings in. @minimum - The minimum string length to search for. Yeilds printable ASCII strings from filename. ''' result = "" with BlockFile(filename) as...
For cross compatibility between Python 2 and Python 3 strings.
def bytes2str(bs): ''' For cross compatibility between Python 2 and Python 3 strings. ''' if isinstance(bs, type(b'')) and PY_MAJOR_VERSION > 2: return bs.decode('latin1') else: return bs
Adds a set of rules to the extraction rule list. @txtrule - Rule string, or list of rule strings, in the format <regular expression>:<file extension>[:<command to run>] @regex - If rule string is not specified, this is the regular expression string to use. @extension - If rule string is n...
def create_rule(self, txtrule=None, regex=None, extension=None, cmd=None, codes=[0, None], recurse=True): ''' Adds a set of rules to the extraction rule list. @txtrule - Rule string, or list of rule strings, in the format <regular expression>:<file extension>[:<command to run>] @regex...
Remove all rules that match a specified description. @description - The description to match against. Returns the number of rules removed.
def remove_rules(self, description): ''' Remove all rules that match a specified description. @description - The description to match against. Returns the number of rules removed. ''' rm = [] description = description.lower() for i in range(0, len(self....
Edit all rules that match a specified description. @description - The description to match against. @key - The key to change for each matching rule. @value - The new key value for each matching rule. Returns the number of rules modified.
def edit_rules(self, description, key, value): ''' Edit all rules that match a specified description. @description - The description to match against. @key - The key to change for each matching rule. @value - The new key value for each matching rule. Retur...
Returns a list of extraction rules that match a given description. @description - The description to match against. Returns a list of extraction rules that match the given description. If no description is provided, a list of all rules are returned.
def get_rules(self, description=None): ''' Returns a list of extraction rules that match a given description. @description - The description to match against. Returns a list of extraction rules that match the given description. If no description is provided, a list of all rules...
Loads extraction rules from the specified file. @fname - Path to the extraction rule file. Returns None.
def load_from_file(self, fname): ''' Loads extraction rules from the specified file. @fname - Path to the extraction rule file. Returns None. ''' try: # Process each line from the extract file, ignoring comments with open(fname, 'r') as f: ...
Loads default extraction rules from the user and system extract.conf files. Returns None.
def load_defaults(self): ''' Loads default extraction rules from the user and system extract.conf files. Returns None. ''' # Load the user extract file first to ensure its rules take precedence. extract_files = [ self.config.settings.user.extract, ...
Set the output directory for extracted files. @path - The path to the file that data will be extracted from. Returns None.
def build_output_directory(self, path): ''' Set the output directory for extracted files. @path - The path to the file that data will be extracted from. Returns None. ''' # If we have not already created an output directory for this target # file, create one now...
Extract an embedded file from the target file, if it matches an extract rule. Called automatically by Binwalk.scan(). @offset - Offset inside the target file to begin the extraction. @description - Description of the embedded file to extract, as returned by libmagic. @file_name -...
def extract(self, offset, description, file_name, size, name=None): ''' Extract an embedded file from the target file, if it matches an extract rule. Called automatically by Binwalk.scan(). @offset - Offset inside the target file to begin the extraction. @description - Desc...
Gets the offset of the first entry that matches the description. @index - Index into the entries list to begin searching. @entries - Dictionary of result entries. @description - Case insensitive description. Returns the offset, if a matching description is found. Retu...
def _entry_offset(self, index, entries, description): ''' Gets the offset of the first entry that matches the description. @index - Index into the entries list to begin searching. @entries - Dictionary of result entries. @description - Case insensitive description. ...
Check to see if the provided description string matches an extract rule. Called internally by self.extract(). @description - Description string to check. Returns the associated rule dictionary if a match is found. Returns None if no match is found.
def match(self, description): ''' Check to see if the provided description string matches an extract rule. Called internally by self.extract(). @description - Description string to check. Returns the associated rule dictionary if a match is found. Returns None if no mat...
Parses an extraction rule. @rule - Rule string. Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>', '<comma separated return codes>', <recurse into extracted directories: True|False>].
def _parse_rule(self, rule): ''' Parses an extraction rule. @rule - Rule string. Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>', '<comma separated return codes>', <recurse into extracted directories: True|False>]. ''' v...
Extracts a file embedded inside the target file. @file_name - Path to the target file. @offset - Offset inside the target file where the embedded file begins. @size - Number of bytes to extract. @extension - The file exension to assign to the extracte...
def _dd(self, file_name, offset, size, extension, output_file_name=None): ''' Extracts a file embedded inside the target file. @file_name - Path to the target file. @offset - Offset inside the target file where the embedded file begins. @size - Numbe...
Execute a command against the specified file. @cmd - Command to execute. @fname - File to run command against. @codes - List of return codes indicating cmd success. Returns True on success, False on failure, or None if the external extraction utility could not be found.
def execute(self, cmd, fname, codes=[0, None]): ''' Execute a command against the specified file. @cmd - Command to execute. @fname - File to run command against. @codes - List of return codes indicating cmd success. Returns True on success, False on failure, or None ...
Convenience wrapper for self.log which is passed a list of format arguments.
def _fix_unicode_list(self, columns): ''' Convenience wrapper for self.log which is passed a list of format arguments. ''' if type(columns) in [list, tuple]: for i in range(0, len(columns)): try: columns[i] = self._fix_unicode(columns[i]) ...
Intelligently appends data to self.string_parts. For use by self._format.
def _append_to_data_parts(self, data, start, end): ''' Intelligently appends data to self.string_parts. For use by self._format. ''' try: while data[start] == ' ': start += 1 if start == end: end = len(data[start:]) ...
Formats a line of text to fit in the terminal window. For Tim.
def _format_line(self, line): ''' Formats a line of text to fit in the terminal window. For Tim. ''' delim = '\n' offset = 0 self.string_parts = [] # Split the line into an array of columns, e.g., ['0', '0x00000000', # 'Some description here'] ...
Configures output formatting, and fitting output to the current terminal width. Returns None.
def _configure_formatting(self): ''' Configures output formatting, and fitting output to the current terminal width. Returns None. ''' self.format_strings(self.DEFAULT_FORMAT, self.DEFAULT_FORMAT) if self.fit_to_screen: try: import fcntl ...
Find all user/system magic signature files. @system_only - If True, only the system magic file directory will be searched. @user_only - If True, only the user magic file directory will be searched. Returns a list of user/system magic signature files.
def _magic_signature_files(self, system_only=False, user_only=False): ''' Find all user/system magic signature files. @system_only - If True, only the system magic file directory will be searched. @user_only - If True, only the user magic file directory will be searched. Retu...
Finds the specified magic file name in the system / user magic file directories. @fname - The name of the magic file. @system_only - If True, only the system magic file directory will be searched. @user_only - If True, only the user magic file directory will be searched. If sys...
def find_magic_file(self, fname, system_only=False, user_only=False): ''' Finds the specified magic file name in the system / user magic file directories. @fname - The name of the magic file. @system_only - If True, only the system magic file directory will be searched. @u...
Get the user's home directory.
def _get_user_dir(self): ''' Get the user's home directory. ''' try: # This should work in both Windows and Unix environments for envname in ['USERPROFILE', 'HOME']: user_dir = os.getenv(envname) if user_dir is not None: ...
Builds an absolute path and creates the directory and file if they don't already exist. @dirname - Directory path. @filename - File name. Returns a full path of 'dirname/filename'.
def _file_path(self, dirname, filename): ''' Builds an absolute path and creates the directory and file if they don't already exist. @dirname - Directory path. @filename - File name. Returns a full path of 'dirname/filename'. ''' if not os.path.exists(dirname):...
Gets the full path to the 'subdir/basename' file in the user binwalk directory. @subdir - Subdirectory inside the user binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file.
def _user_path(self, subdir, basename=''): ''' Gets the full path to the 'subdir/basename' file in the user binwalk directory. @subdir - Subdirectory inside the user binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basenam...
Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/basename' file.
def _system_path(self, subdir, basename=''): ''' Gets the full path to the 'subdir/basename' file in the system binwalk directory. @subdir - Subdirectory inside the system binwalk directory. @basename - File name inside the subdirectory. Returns the full path to the 'subdir/b...
This does the extraction (e.g., it decrypts the image and writes it to a new file on disk).
def _decrypt_and_extract(self, fname): ''' This does the extraction (e.g., it decrypts the image and writes it to a new file on disk). ''' with open(fname, "r") as fp_in: encrypted_data = fp_in.read() decrypted_data = self._hilink_decrypt(encrypted_data) ...
This does the actual decryption.
def _hilink_decrypt(self, encrypted_firmware): ''' This does the actual decryption. ''' cipher = DES.new(self.DES_KEY, DES.MODE_ECB) p1 = encrypted_firmware[0:3] p2 = encrypted_firmware[3:] p2 += b"\x00" * (8 - (len(p2) % 8)) d1 = p1 + cipher.decrypt(p2)...
Validate signature results.
def scan(self, result): ''' Validate signature results. ''' if self.enabled is True: if result.valid is True: if result.description.lower().startswith(self.SIGNATURE_DESCRIPTION) is True: # Read in the first 64 bytes of the suspected encryp...
Locks the main thread while the subscription in running
def run(): print("Environment", os.environ) try: os.environ["SELENIUM"] except KeyError: print("Please set the environment variable SELENIUM to Selenium URL") sys.exit(1) driver = WhatsAPIDriver(client='remote', command_executor=os.environ["SELENIUM"]) print("Waiting for QR"...
Function to save the firefox profile to the permanant one
def save_firefox_profile(self, remove_old=False): """Function to save the firefox profile to the permanant one""" self.logger.info("Saving profile from %s to %s" % (self._profile.path, self._profile_path)) if remove_old: if os.path.exists(self._profile_path): try: ...
Waits for the QR to go away
def wait_for_login(self, timeout=90): """Waits for the QR to go away""" WebDriverWait(self.driver, timeout).until( EC.visibility_of_element_located((By.CSS_SELECTOR, self._SELECTORS['mainPage'])) )
Get pairing QR code from client
def get_qr(self, filename=None): """Get pairing QR code from client""" if "Click to reload QR code" in self.driver.page_source: self.reload_qr() qr = self.driver.find_element_by_css_selector(self._SELECTORS['qrCode']) if filename is None: fd, fn_png = tempfile.mks...
Fetches list of all contacts This will return chats with people from the address book only Use get_all_chats for all chats :return: List of contacts :rtype: list[Contact]
def get_contacts(self): """ Fetches list of all contacts This will return chats with people from the address book only Use get_all_chats for all chats :return: List of contacts :rtype: list[Contact] """ all_contacts = self.wapi_functions.getAllContacts() ...
Fetches list of added contacts :return: List of contacts :rtype: list[Contact]
def get_my_contacts(self): """ Fetches list of added contacts :return: List of contacts :rtype: list[Contact] """ my_contacts = self.wapi_functions.getMyContacts() return [Contact(contact, self) for contact in my_contacts]
Fetches all chats :return: List of chats :rtype: list[Chat]
def get_all_chats(self): """ Fetches all chats :return: List of chats :rtype: list[Chat] """ chats = self.wapi_functions.getAllChats() if chats: return [factory_chat(chat, self) for chat in chats] else: return []
Fetches unread messages :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type include_notifications: bool or None :param use_unread_count: If set uses chat's 'unreadCount' attribute to fetch ...
def get_unread(self, include_me=False, include_notifications=False, use_unread_count=False): """ Fetches unread messages :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type include_...
I fetch unread messages from an asked chat. :param id: chat id :type id: str :param include_me: if user's messages are to be included :type include_me: bool :param include_notifications: if events happening on chat are to be included :type include_notifications: bool ...
def get_unread_messages_in_chat(self, id, include_me=False, include_notifications=False): """ I fetch unread messages from an asked chat. :param id: chat id :type id: str ...
Fetches messages in chat :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type include_notifications: bool or None :return: List of messages in chat :rtype: list[Message]
def get_all_messages_in_chat(self, chat, include_me=False, include_notifications=False): """ Fetches messages in chat :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type include_no...
Fetches message ids in chat :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type include_notifications: bool or None :return: List of message ids in chat :rtype: list[str]
def get_all_message_ids_in_chat(self, chat, include_me=False, include_notifications=False): """ Fetches message ids in chat :param include_me: Include user's messages :type include_me: bool or None :param include_notifications: Include events happening on chat :type incl...
Fetch a message :param message_id: Message ID :type message_id: str :return: Message or False :rtype: Message
def get_message_by_id(self, message_id): """ Fetch a message :param message_id: Message ID :type message_id: str :return: Message or False :rtype: Message """ result = self.wapi_functions.getMessageById(message_id) if result: result =...
Fetches a contact given its ID :param contact_id: Contact ID :type contact_id: str :return: Contact or Error :rtype: Contact
def get_contact_from_id(self, contact_id): """ Fetches a contact given its ID :param contact_id: Contact ID :type contact_id: str :return: Contact or Error :rtype: Contact """ contact = self.wapi_functions.getContact(contact_id) if contact is Non...
Fetches a chat given its ID :param chat_id: Chat ID :type chat_id: str :return: Chat or Error :rtype: Chat
def get_chat_from_id(self, chat_id): """ Fetches a chat given its ID :param chat_id: Chat ID :type chat_id: str :return: Chat or Error :rtype: Chat """ chat = self.wapi_functions.getChatById(chat_id) if chat: return factory_chat(chat, ...
Gets chat by phone number Number format should be as it appears in Whatsapp ID For example, for the number: +972-51-234-5678 This function would receive: 972512345678 :param number: Phone number :return: Chat :rtype: Chat
def get_chat_from_phone_number(self, number, createIfNotFound = False): """ Gets chat by phone number Number format should be as it appears in Whatsapp ID For example, for the number: +972-51-234-5678 This function would receive: 972512345678 :param numbe...
Returns status of the driver :return: Status :rtype: WhatsAPIDriverStatus
def get_status(self): """ Returns status of the driver :return: Status :rtype: WhatsAPIDriverStatus """ if self.driver is None: return WhatsAPIDriverStatus.NotConnected if self.driver.session_id is None: return WhatsAPIDriverStatus.NotConn...
Returns groups common between a user and the contact with given id. :return: Contact or Error :rtype: Contact
def contact_get_common_groups(self, contact_id): """ Returns groups common between a user and the contact with given id. :return: Contact or Error :rtype: Contact """ for group in self.wapi_functions.getCommonGroups(contact_id): yield factory_chat(group, self...
:param path: file path :return: returns the converted string and formatted for the send media function send_media
def convert_to_base64(self, path): """ :param path: file path :return: returns the converted string and formatted for the send media function send_media """ mime = magic.Magic(mime=True) content_type = mime.from_file(path) archive = '' with open(path, "rb...
converts the file to base64 and sends it using the sendImage function of wapi.js :param path: file path :param chatid: chatId to be sent :param caption: :return:
def send_media(self, path, chatid, caption): """ converts the file to base64 and sends it using the sendImage function of wapi.js :param path: file path :param chatid: chatId to be sent :param caption: :return: """ imgBase64 = self.convert_to_base64(pa...
Get full profile pic from an id The ID must be on your contact book to successfully get their profile picture. :param id: ID :type id: str
def get_profile_pic_from_id(self, id): """ Get full profile pic from an id The ID must be on your contact book to successfully get their profile picture. :param id: ID :type id: str """ profile_pic = self.wapi_functions.getProfilePicFromId(id) if ...
Get small profile pic from an id The ID must be on your contact book to successfully get their profile picture. :param id: ID :type id: str
def get_profile_pic_small_from_id(self, id): """ Get small profile pic from an id The ID must be on your contact book to successfully get their profile picture. :param id: ID :type id: str """ profile_pic_small = self.wapi_functions.getProfilePicSmallFrom...
Delete a chat :param chat_id: id of chat :param message_array: one or more message(s) id :param revoke: Set to true so the message will be deleted for everyone, not only you :return:
def delete_message(self, chat_id, message_array, revoke=False): """ Delete a chat :param chat_id: id of chat :param message_array: one or more message(s) id :param revoke: Set to true so the message will be deleted for everyone, not only you :return: """ ...
Check if a number is valid/registered in the whatsapp service :param number_id: number id :return:
def check_number_status(self, number_id): """ Check if a number is valid/registered in the whatsapp service :param number_id: number id :return: """ number_status = self.wapi_functions.checkNumberStatus(number_id) return NumberStatus(number_status, self)
Factory function for creating appropriate object given selenium JS object
def factory_chat(js_obj, driver=None): """Factory function for creating appropriate object given selenium JS object""" if js_obj["kind"] not in ["chat", "group", "broadcast"]: raise AssertionError("Expected chat, group or broadcast object, got {0}".format(js_obj["kind"])) if js_obj["isGroup"]: ...
I fetch unread messages. :param include_me: if user's messages are to be included :type include_me: bool :param include_notifications: if events happening on chat are to be included :type include_notifications: bool :return: list of unread messages :rtype: list
def get_unread_messages(self, include_me=False, include_notifications=False): """ I fetch unread messages. :param include_me: if user's messages are to be included :type include_me: bool :param include_notifications: if e...
Triggers loading of messages till a specific point in time :param last: Datetime object for the last message to be loaded :type last: datetime :return: Nothing :rtype: None
def load_earlier_messages_till(self, last): """ Triggers loading of messages till a specific point in time :param last: Datetime object for the last message to be loaded :type last: datetime :return: Nothing :rtype: None """ timestamp = time.mktime(last.t...
Factory function for creating appropriate object given selenium JS object
def factory_message(js_obj, driver): """Factory function for creating appropriate object given selenium JS object""" if js_obj is None: return if "lat" in js_obj and "lng" in js_obj and js_obj["lat"] and js_obj["lng"]: return GeoMessage(js_obj, driver) if js_obj["isMedia"]: ret...
Initial the global logger variable
def create_logger(): """Initial the global logger variable""" global logger formatter = logging.Formatter('%(asctime)s|%(levelname)s|%(message)s') handler = TimedRotatingFileHandler(log_file, when="midnight", interval=1) handler.setFormatter(formatter) handler.setLevel(log_level) handler.su...
Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object
def init_driver(client_id): """Initialises a new driver via webwhatsapi module @param client_id: ID of user client @return webwhatsapi object """ # Create profile directory if it does not exist profile_path = CHROME_CACHE_PATH + str(client_id) if not os.path.exists(profile_path): ...
Initialse a driver for client and store for future reference @param client_id: ID of client user @return whebwhatsapi object
def init_client(client_id): """Initialse a driver for client and store for future reference @param client_id: ID of client user @return whebwhatsapi object """ if client_id not in drivers: drivers[client_id] = init_driver(client_id) return drivers[client_id]
Delete all objects related to client @param client_id: ID of client user @param preserve_cache: Boolean, whether to delete the chrome profile folder or not
def delete_client(client_id, preserve_cache): """Delete all objects related to client @param client_id: ID of client user @param preserve_cache: Boolean, whether to delete the chrome profile folder or not """ if client_id in drivers: drivers.pop(client_id).quit() try: ...
Create a timer for the client driver to watch for events @param client_id: ID of clinet user
def init_timer(client_id): """Create a timer for the client driver to watch for events @param client_id: ID of clinet user """ if client_id in timers and timers[client_id]: timers[client_id].start() return # Create a timer to call check_new_message function after every 2 seconds...
Check for new unread messages and send them to the custom api @param client_id: ID of client user
def check_new_messages(client_id): """Check for new unread messages and send them to the custom api @param client_id: ID of client user """ # Return if driver is not defined or if whatsapp is not logged in. # Stop the timer as well if client_id not in drivers or not drivers[client_id] or not dr...
Get the status of a perticular client, as to he/she is connected or not @param client_id: ID of client user @return JSON object { "driver_status": webdriver status "is_alive": if driver is active or not "is_logged_in": if user is logged in or not "is_timer": if timer is runn...
def get_client_info(client_id): """Get the status of a perticular client, as to he/she is connected or not @param client_id: ID of client user @return JSON object { "driver_status": webdriver status "is_alive": if driver is active or not "is_logged_in": if user is logged in or n...
Create a profile path folder if not exist @param client_id: ID of client user @return string profile path
def create_static_profile_path(client_id): """Create a profile path folder if not exist @param client_id: ID of client user @return string profile path """ profile_path = os.path.join(STATIC_FILES_PATH, str(client_id)) if not os.path.exists(profile_path): os.makedirs(profile_path) ...
This runs before every API request. The function take cares of creating driver object is not already created. Also it checks for few prerequisits parameters and set global variables for other functions to use Required paramters for an API hit are: auth-key: key string to identify valid request ...
def before_request(): """This runs before every API request. The function take cares of creating driver object is not already created. Also it checks for few prerequisits parameters and set global variables for other functions to use Required paramters for an API hit are: auth-key: key string t...
Create a new client driver. The driver is automatically created in before_request function.
def create_client(): """Create a new client driver. The driver is automatically created in before_request function.""" result = False if g.client_id in drivers: result = True return jsonify({'Success': result})
Delete all objects related to client
def delete_client(): """Delete all objects related to client""" preserve_cache = request.args.get('preserve_cache', False) delete_client(g.client_id, preserve_cache) return jsonify({'Success': True})
Capture chrome screen image and send it back. If the screen is currently at qr scanning phase, return the image of qr only, else return image of full screen
def get_screen(): """Capture chrome screen image and send it back. If the screen is currently at qr scanning phase, return the image of qr only, else return image of full screen""" img_title = 'screen_' + g.client_id + '.png' image_path = STATIC_FILES_PATH + img_title if g.driver_status != What...
Get all unread messages
def get_unread_messages(): """Get all unread messages""" mark_seen = request.args.get('mark_seen', True) unread_msg = g.driver.get_unread() if mark_seen: for msg in unread_msg: msg.chat.send_seen() return jsonify(unread_msg)
Return all of the chat messages
def get_messages(chat_id): """Return all of the chat messages""" mark_seen = request.args.get('mark_seen', True) chat = g.driver.get_chat_from_id(chat_id) msgs = list(g.driver.get_all_messages_in_chat(chat)) for msg in msgs: print(msg.id) if mark_seen: for msg in msgs: ...
Send a message to a chat If a media file is found, send_media is called, else a simple text message is sent
def send_message(chat_id): """Send a message to a chat If a media file is found, send_media is called, else a simple text message is sent """ files = request.files if files: res = send_media(chat_id, request) else: message = request.form.get('message') res = g.drive...
Download a media file
def download_message_media(msg_id): """Download a media file""" message = g.driver.get_message_by_id(msg_id) if not message or not message.mime: abort(404) profile_path = create_static_profile_path(g.client_id) filename = message.save_media(profile_path, True) if os.path.exists(filena...
Get a list of all active clients and their status
def get_active_clients(): """Get a list of all active clients and their status""" global drivers if not drivers: return jsonify([]) result = {client: get_client_info(client) for client in drivers} return jsonify(result)
Force create driver for client
def run_clients(): """Force create driver for client """ clients = request.form.get('clients') if not clients: return jsonify({'Error': 'no clients provided'}) result = {} for client_id in clients.split(','): if client_id not in drivers: init_client(client_id) ...
Force kill driver and other objects for a perticular clien
def kill_clients(): """Force kill driver and other objects for a perticular clien""" clients = request.form.get('clients').split(',') kill_dead = request.args.get('kill_dead', default=False) kill_dead = kill_dead and kill_dead in ['true', '1'] if not kill_dead and not clients: return jsonif...
Decorator for WhatsappObjectWithId methods that need to communicate with the browser It ensures that the object receives a driver instance at construction :param func: WhatsappObjectWithId method :return: Wrapped method
def driver_needed(func): """ Decorator for WhatsappObjectWithId methods that need to communicate with the browser It ensures that the object receives a driver instance at construction :param func: WhatsappObjectWithId method :return: Wrapped method """ def wrapped(self, *args): if...
The dist dir at which to place the finished distribution.
def dist_dir(self): '''The dist dir at which to place the finished distribution.''' if self.distribution is None: warning('Tried to access {}.dist_dir, but {}.distribution ' 'is None'.format(self, self)) exit(1) return self.distribution.dist_dir
Checks what recipes are being built to see which of the alternative and optional dependencies are being used, and returns a list of these.
def check_recipe_choices(self): '''Checks what recipes are being built to see which of the alternative and optional dependencies are being used, and returns a list of these.''' recipes = [] built_recipes = self.ctx.recipe_build_order for recipe in self.recipe_depends: ...
Ensure that a build dir exists for the recipe. This same single dir will be used for building all different archs.
def prepare_build_dir(self): '''Ensure that a build dir exists for the recipe. This same single dir will be used for building all different archs.''' self.build_dir = self.get_build_dir() self.common_dir = self.get_common_dir() copy_files(join(self.bootstrap_dir, 'build'), self.b...
Find all the available bootstraps and return them.
def list_bootstraps(cls): '''Find all the available bootstraps and return them.''' forbidden_dirs = ('__pycache__', 'common') bootstraps_dir = join(dirname(__file__), 'bootstraps') for name in listdir(bootstraps_dir): if name in forbidden_dirs: continue ...
Returns a bootstrap whose recipe requirements do not conflict with the given recipes.
def get_bootstrap_from_recipes(cls, recipes, ctx): '''Returns a bootstrap whose recipe requirements do not conflict with the given recipes.''' info('Trying to find a bootstrap that matches the given recipes.') bootstraps = [cls.get_bootstrap(name, ctx) for name in c...
Returns an instance of a bootstrap with the given name. This is the only way you should access a bootstrap class, as it sets the bootstrap directory correctly.
def get_bootstrap(cls, name, ctx): '''Returns an instance of a bootstrap with the given name. This is the only way you should access a bootstrap class, as it sets the bootstrap directory correctly. ''' if name is None: return None if not hasattr(cls, 'bootstr...
Copy existing arch libs from build dirs to current dist dir.
def distribute_libs(self, arch, src_dirs, wildcard='*', dest_dir="libs"): '''Copy existing arch libs from build dirs to current dist dir.''' info('Copying libs') tgt_dir = join(dest_dir, arch.arch) ensure_dir(tgt_dir) for src_dir in src_dirs: for lib in glob.glob(join...