text
stringlengths
81
112k
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 ...
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 ...
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: """ numbe...
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 broadca...
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 ...
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 poin...
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"]: ...
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) handle...
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 direct...
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 """ ...
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 pres...
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_i...
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 log...
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...
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.p...
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 ...
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({'S...
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,...
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...
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: ...
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) i...
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: i...
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'] ...
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 ...
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)) ...
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, ...
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....
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 nam...
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 re...
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...
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) ...
Copy existing javaclasses from build dir to current dist dir. def distribute_javaclasses(self, javaclass_dir, dest_dir="src"): '''Copy existing javaclasses from build dir to current dist dir.''' info('Copying java files') ensure_dir(dest_dir) for filename in glob.glob(javaclass_dir): ...
Process existing .aar bundles and copy to current dist dir. def distribute_aars(self, arch): '''Process existing .aar bundles and copy to current dist dir.''' info('Unpacking aars') for aar in glob.glob(join(self.ctx.aars_dir, '*.aar')): self._unpack_aar(aar, arch)
Unpack content of .aar bundle and copy to current dist dir. def _unpack_aar(self, aar, arch): '''Unpack content of .aar bundle and copy to current dist dir.''' with temp_directory() as temp_dir: name = splitext(basename(aar))[0] jar_name = name + '.jar' info("unpack ...
Returns a set of modified recipes between the current branch and the one in param. def modified_recipes(branch='origin/master'): """ Returns a set of modified recipes between the current branch and the one in param. """ # using the contrib version on purpose rather than sh.git, since it comes ...
Builds an APK given a target Python and a set of requirements. def build(target_python, requirements): """ Builds an APK given a target Python and a set of requirements. """ if not requirements: return testapp = 'setup_testapp_python2.py' android_sdk_home = os.environ['ANDROID_SDK_HOME'...
- Moves all -I<inc> -D<macro> from CFLAGS to CPPFLAGS environment. - Moves all -l<lib> from LDFLAGS to LIBS environment. - Fixes linker name (use cross compiler) and flags (appends LIBS) def get_recipe_env(self, arch=None, with_flags_in_cc=True): """ - Moves all -I<inc> -D<macro> from ...
Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow k...
Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceeding comment that begins with one of the keywords. Fo...
Parse a translatable tag. def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked at # a later state. ...
Generates a useful node from the data provided. def _make_node(self, singular, plural, variables, plural_expr): """Generates a useful node from the data provided.""" # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettex...
Load the extensions from the list and bind it to the environment. Returns a dict of instanciated environments. def load_extensions(environment, extensions): """Load the extensions from the list and bind it to the environment. Returns a dict of instanciated environments. """ result = {} for exte...
Add the items to the instance of the environment if they do not exist yet. This is used by :ref:`extensions <writing-extensions>` to register callbacks and configuration values without breaking inheritance. def extend(self, **attributes): """Add the items to the instance of the environment if ...
Internal parsing function used by `parse` and `compile`. def _parse(self, source, name, filename): """Internal parsing function used by `parse` and `compile`.""" return Parser(self, source, name, _encode_filename(filename)).parse()
Preprocesses the source with all extensions. This is automatically called for all parsing and compiling methods but *not* for :meth:`lex` because there you usually only want the actual source tokenized. def preprocess(self, source, name=None, filename=None): """Preprocesses the source with all...
Compile a node or template source code. The `name` parameter is the load name of the template after it was joined using :meth:`join_path` if necessary, not the filename on the file system. the `filename` parameter is the estimated filename of the template on the file system. If the tem...
Exception handling helper. This is used internally to either raise rewritten exceptions or return a rendered traceback for the template. def handle_exception(self, exc_info=None, rendered=False, source_hint=None): """Exception handling helper. This is used internally to either raise rewritten...
Creates a template object from compiled code and the globals. This is used by the loaders and environment to create a template object. def from_code(cls, environment, code, globals, uptodate=None): """Creates a template object from compiled code and the globals. This is used by the loaders an...
This method accepts the same arguments as the `dict` constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty. These two calls do the same:: template.render(knights='that say nih') template.render({'knights': 'that say...
For very large templates it can be useful to not render the whole template at once but evaluate each statement after another and yield piece for piece. This method basically does exactly that and returns a generator that yields one item after another as unicode strings. It accepts the ...
The template as module. This is used for imports in the template runtime but is also useful if one wants to access exported template variables from the Python layer: >>> t = Template('{% macro foo() %}42{% endmacro %}23') >>> unicode(t.module) u'23' >>> t.module.foo() ...
The debug info mapping. def debug_info(self): """The debug info mapping.""" return [tuple(map(int, x.split('='))) for x in self._debug_info.split('&')]
Dump the complete stream into a file or file-like object. Per default unicode strings are written, if you want to encode before writing specifiy an `encoding`. Example usage:: Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') def dump(self, fp, encoding=None, err...
Disable the output buffering. def disable_buffering(self): """Disable the output buffering.""" self._next = self._gen.next self.buffered = False
Enable buffering. Buffer `size` items before yielding them. def enable_buffering(self, size=5): """Enable buffering. Buffer `size` items before yielding them.""" if size <= 1: raise ValueError('buffer size too small') def generator(next): buf = [] c_size =...
Decorator for ToolchainCL methods. If present, the method will automatically make sure a dist has been built before continuing or, if no dists are present or can be obtained, will raise an error. def require_prebuilt_dist(func): """Decorator for ToolchainCL methods. If present, the method will auto...
Parses out any distribution-related arguments, and uses them to obtain a Distribution class instance for the build. def dist_from_args(ctx, args): """Parses out any distribution-related arguments, and uses them to obtain a Distribution class instance for the build. """ return Distribution.get_distr...
Parses out any bootstrap related arguments, and uses them to build a dist. def build_dist_from_args(ctx, dist, args): """Parses out any bootstrap related arguments, and uses them to build a dist.""" bs = Bootstrap.get_bootstrap(args.bootstrap, ctx) blacklist = getattr(args, "blacklist_requirements"...
Print warning messages for any deprecated arguments that were passed. def warn_on_deprecated_args(self, args): """ Print warning messages for any deprecated arguments that were passed. """ # Output warning if setup.py is present and neither --ignore-setup-py # nor --use-setup-p...
List all the bootstraps available to build with. def bootstraps(self, _args): """List all the bootstraps available to build with.""" for bs in Bootstrap.list_bootstraps(): bs = Bootstrap.get_bootstrap(bs, self.ctx) print('{Fore.BLUE}{Style.BRIGHT}{bs.name}{Style.RESET_ALL}' ...
Delete all build components; the package cache, package builds, bootstrap builds and distributions. def clean_all(self, args): """Delete all build components; the package cache, package builds, bootstrap builds and distributions.""" self.clean_dists(args) self.clean_builds(args)...
Delete all compiled distributions in the internal distribution directory. def clean_dists(self, _args): """Delete all compiled distributions in the internal distribution directory.""" ctx = self.ctx if exists(ctx.dist_dir): shutil.rmtree(ctx.dist_dir)
Delete all the bootstrap builds. def clean_bootstrap_builds(self, _args): """Delete all the bootstrap builds.""" if exists(join(self.ctx.build_dir, 'bootstrap_builds')): shutil.rmtree(join(self.ctx.build_dir, 'bootstrap_builds'))
Delete all build caches for each recipe, python-install, java code and compiled libs collection. This does *not* delete the package download cache or the final distributions. You can also use clean_recipe_build to delete the build of a specific recipe. def clean_builds(self, _args): ...
Deletes the build files of the given recipe. This is intended for debug purposes. You may experience strange behaviour or problems with some recipes if their build has made unexpected state changes. If this happens, run clean_builds, or attempt to clean other recipes until things ...
Deletes a download cache for recipes passed as arguments. If no argument is passed, it'll delete *all* downloaded caches. :: p4a clean_download_cache kivy,pyjnius This does *not* delete the build caches or final distributions. def clean_download_cache(self, args): """ Deletes a do...
Copies a created dist to an output dir. This makes it easy to navigate to the dist to investigate it or call build.py, though you do not in general need to do this and can use the apk command instead. def export_dist(self, args): """Copies a created dist to an output dir. This...
Create an APK using the given distribution. def apk(self, args): """Create an APK using the given distribution.""" ctx = self.ctx dist = self._dist # Manually fixing these arguments at the string stage is # unsatisfactory and should probably be changed somehow, but # w...
List the target architectures available to be built for. def archs(self, _args): """List the target architectures available to be built for.""" print('{Style.BRIGHT}Available target architectures are:' '{Style.RESET_ALL}'.format(Style=Out_Style)) for arch in self.ctx.archs: ...
Lists all distributions currently available (i.e. that have already been built). def distributions(self, _args): """Lists all distributions currently available (i.e. that have already been built).""" ctx = self.ctx dists = Distribution.get_distributions(ctx) if dists: ...
Runs the android binary from the detected SDK directory, passing all arguments straight to it. This binary is used to install e.g. platform-tools for different API level targets. This is intended as a convenience function if android is not in your $PATH. def sdk_tools(self, args): ...
Call the adb executable from the SDK, passing the given commands as arguments. def _adb(self, commands): """Call the adb executable from the SDK, passing the given commands as arguments.""" ctx = self.ctx ctx.prepare_build_environment(user_sdk_dir=self.sdk_dir, ...
Print the status of the specified build. def build_status(self, _args): """Print the status of the specified build. """ print('{Style.BRIGHT}Bootstraps whose core components are probably ' 'already built:{Style.RESET_ALL}'.format(Style=Out_Style)) bootstrap_dir = join(self.ctx.bu...
Make the build and target directories def prebuild_arch(self, arch): """Make the build and target directories""" path = self.get_build_dir(arch.arch) if not exists(path): info("creating {}".format(path)) shprint(sh.mkdir, '-p', path)
simple shared compile def build_arch(self, arch): """simple shared compile""" env = self.get_recipe_env(arch, with_flags_in_cc=False) for path in ( self.get_build_dir(arch.arch), join(self.ctx.python_recipe.get_build_dir(arch.arch), 'Lib'), join(s...
Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. def resolve(self, key): """Looks up a variable like `__getitem__` or `get` but returns an :class:`Undefined` object with the name of the name looked up. """ ...
Call the callable with the arguments and keyword arguments provided but inject the active context or environment as first argument if the callable is a :func:`contextfunction` or :func:`environmentfunction`. def call(__self, __obj, *args, **kwargs): """Call the callable with the argumen...
Regular callback function for undefined objects that raises an `UndefinedError` on call. def _fail_with_undefined_error(self, *args, **kwargs): """Regular callback function for undefined objects that raises an `UndefinedError` on call. """ if self._undefined_hint is None: ...
Turn a dependency list into lowercase, and make sure all entries that are just a string become a tuple of strings def fix_deplist(deps): """ Turn a dependency list into lowercase, and make sure all entries that are just a string become a tuple of strings """ deps = [ ((dep.lower(),)...
Get the dependencies of a recipe with filtered out blacklist, and turned into tuples with fix_deplist() def get_dependency_tuple_list_for_recipe(recipe, blacklist=None): """ Get the dependencies of a recipe with filtered out blacklist, and turned into tuples with fix_deplist() """ if blackl...
For each possible recipe ordering, try to add the new recipe name to that order. Recursively do the same thing with all the dependencies of each recipe. def recursively_collect_orders( name, ctx, all_inputs, orders=None, blacklist=None ): '''For each possible recipe ordering, try to add the...
Do a topological sort on the dependency graph dict. def find_order(graph): ''' Do a topological sort on the dependency graph dict. ''' while graph: # Find all items without a parent leftmost = [l for l, s in graph.items() if not s] if not leftmost: raise ValueError('...
This is a pre-flight check function that will completely ignore recipe order or choosing an actual value in any of the multiple choice tuples/dependencies, and just do a very basic obvious conflict check. def obvious_conflict_checker(ctx, name_tuples, blacklist=None): """ This is a pre-flig...
Returns a string with the include folders def include_flags(self, arch): '''Returns a string with the include folders''' openssl_includes = join(self.get_build_dir(arch.arch), 'include') return (' -I' + openssl_includes + ' -I' + join(openssl_includes, 'internal') + ...
Takes care to properly link libraries with python depending on our requirements and the attribute :attr:`opt_depends`. def set_libs_flags(self, env, arch): '''Takes care to properly link libraries with python depending on our requirements and the attribute :attr:`opt_depends`. ''' ...
Compile the python files (recursively) for the python files inside a given folder. .. note:: python2 compiles the files into extension .pyo, but in python3, and as of Python 3.5, the .pyo filename extension is no longer used...uses .pyc (https://www.python.org/dev/peps/pep-0488)...
Create a packaged python bundle in the target directory, by copying all the modules and standard library to the right place. def create_python_bundle(self, dirn, arch): """ Create a packaged python bundle in the target directory, by copying all the modules and standard library t...
Adds openssl recipe to include and library path. def get_recipe_env(self, arch, with_flags_in_cc=True): """ Adds openssl recipe to include and library path. """ env = super(ScryptRecipe, self).get_recipe_env(arch, with_flags_in_cc) openssl_recipe = self.get_recipe('openssl', sel...
Recursively walks all the files and directories in ``dirn``, ignoring directories that match any pattern in ``invalid_dirns`` and files that patch any pattern in ``invalid_filens``. ``invalid_dirns`` and ``invalid_filens`` should both be lists of strings to match. ``invalid_dir_patterns`` expects a lis...
Handles a raised BuildInterruptingException by printing its error message and associated instructions, if any, then exiting. def handle_build_exception(exception): """ Handles a raised BuildInterruptingException by printing its error message and associated instructions, if any, then exiting. """ ...
Using jinja2, render `template` to the filename `dest`, supplying the keyword arguments as template parameters. def render(template, dest, **kwargs): '''Using jinja2, render `template` to the filename `dest`, supplying the keyword arguments as template parameters. ''' dest_dir = dirname(dest) ...
Search for all the python related files, and construct the pythonXX.zip According to # http://randomsplat.com/id5-cross-compiling-python-for-embedded-linux.html site-packages, config and lib-dynload will be not included. def make_python_zip(): ''' Search for all the python related files, and constr...
Make a zip file `fn` from the contents of source_dis. def make_tar(tfn, source_dirs, ignore_path=[], optimize_python=True): ''' Make a zip file `fn` from the contents of source_dis. ''' # selector function def select(fn): rfn = realpath(fn) for p in ignore_path: if p.en...
Compile *.py in directory `dfn` to *.pyo def compile_dir(dfn, optimize_python=True): ''' Compile *.py in directory `dfn` to *.pyo ''' if PYTHON is None: return if int(PYTHON_VERSION[0]) >= 3: args = [PYTHON, '-m', 'compileall', '-b', '-f', dfn] else: args = [PYTHON, '-...
Creates expected build and symlinks system Python version. def build_arch(self, arch): """ Creates expected build and symlinks system Python version. """ self.ctx.hostpython = '/usr/bin/false' # creates the sub buildir (used by other recipes) # https://github.com/kivy/py...
Using jinja2, render `template` to the filename `dest`, supplying the keyword arguments as template parameters. def render(template, dest, **kwargs): '''Using jinja2, render `template` to the filename `dest`, supplying the keyword arguments as template parameters. ''' template = environment.get_...
Calculate the md5sum of a file. def md5sum(filen): '''Calculate the md5sum of a file. ''' with open(filen, 'rb') as fileh: md5 = hashlib.md5(fileh.read()) return md5.hexdigest()