INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Starts the progress bar TCP service on the specified port. This service will only be started once per instance regardless of the number of times this method is invoked.
def status_server(self, port): ''' Starts the progress bar TCP service on the specified port. This service will only be started once per instance, regardless of the number of times this method is invoked. Failure to start the status service is considered non-critical; that is, ...
Returns a 2 byte integer.
def _make_short(self, data, endianness): """Returns a 2 byte integer.""" data = binwalk.core.compat.str2bytes(data) return struct.unpack('%sH' % endianness, data)[0]
Returns the number of bytes designated for the filename.
def _get_fname_len(self, bufflen=128): """Returns the number of bytes designated for the filename.""" buff = self.meta.peek(bufflen) strlen = buff.find('\0') for i, b in enumerate(buff[strlen:]): if b != '\0': return strlen+i return bufflen
Reads a chunk of meta data from file and returns a PFSNode.
def _get_node(self): """Reads a chunk of meta data from file and returns a PFSNode.""" data = self.meta.read(self.node_size) return PFSNode(data, self.endianness)
Returns file meta - data entries one by one.
def entries(self): """Returns file meta-data entries one by one.""" self.meta.seek(self.file_list_start) for i in range(0, self.num_files): yield self._get_node()
Extracts the actual string from the available bytes.
def _decode_fname(self): """Extracts the actual string from the available bytes.""" self.fname = self.fname[:self.fname.find('\0')] self.fname = self.fname.replace('\\', '/')
Generates a regular expression from the magic bytes of a signature. The regex is used by Magic. _analyze.
def _generate_regex(self, line): ''' Generates a regular expression from the magic bytes of a signature. The regex is used by Magic._analyze. @line - The first SignatureLine object of the signature. Returns a compile regular expression. ''' restr = "" #...
Tests if a string should be filtered out or not.
def _filtered(self, text): ''' Tests if a string should be filtered out or not. @text - The string to check against filter rules. Returns True if the string should be filtered out, i.e., not displayed. Returns False if the string should be displayed. ''' filtere...
Parses and evaluates complex expressions e. g. ( 4. l + 12 ) ( 6 * 32 ) etc.
def _do_math(self, offset, expression): ''' Parses and evaluates complex expressions, e.g., "(4.l+12)", "(6*32)", etc. @offset - The offset inside self.data that the current signature starts at. @expressions - The expression to evaluate. Returns an integer value that is th...
Analyzes self. data for the specified signature data at the specified offset.
def _analyze(self, signature, offset): ''' Analyzes self.data for the specified signature data at the specified offset . @signature - The signature to apply to the data. @offset - The offset in self.data to apply the signature to. Returns a dictionary of tags parsed from the...
Scan a data block for matching signatures.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 ().
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.
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 ().
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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
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 last n messages from chat: type use_unread...
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.
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
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
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
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
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
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
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
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.
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.
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.
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
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
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.
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
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
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
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
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
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
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
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
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 client_id: to identify ...
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)