INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Puts a value into a queue but aborts if this thread is closed.
def queue(self, queue_, value): """Puts a value into a queue but aborts if this thread is closed.""" while not self.closed: try: queue_.put(value, block=True, timeout=1) return except queue.Full: continue
Parses a HDS manifest and returns its substreams.
def parse_manifest(cls, session, url, timeout=60, pvswf=None, is_akamai=False, **request_params): """Parses a HDS manifest and returns its substreams. :param url: The URL to the manifest. :param timeout: How long to wait for data to be returned from ...
Returns any parameters needed for Akamai HD player verification.
def _pv_params(cls, session, pvswf, pv, **request_params): """Returns any parameters needed for Akamai HD player verification. Algorithm originally documented by KSV, source: http://stream-recorder.com/forum/showpost.php?p=43761&postcount=13 """ try: data, hdntl = p...
Given an HTTP response from the sessino endpoint extract the nonce so we can sign requests with it. We don t really sign the requests in the traditional sense of a nonce we just incude them in the auth requests.
def _extract_nonce(cls, http_result): """ Given an HTTP response from the sessino endpoint, extract the nonce, so we can "sign" requests with it. We don't really sign the requests in the traditional sense of a nonce, we just incude them in the auth requests. :param http_result: HTTP res...
Find the Video Packet ID in the HTML for the provided URL
def find_vpid(self, url, res=None): """ Find the Video Packet ID in the HTML for the provided URL :param url: URL to download, if res is not provided. :param res: Provide a cached version of the HTTP response to search :type url: string :type res: requests.Response ...
Create session using BBC ID. See https:// www. bbc. co. uk/ usingthebbc/ account/
def login(self, ptrt_url): """ Create session using BBC ID. See https://www.bbc.co.uk/usingthebbc/account/ :param ptrt_url: The snapback URL to redirect to after successful authentication :type ptrt_url: string :return: Whether authentication was successful :rtype: bool ...
Remove the PKCS#7 padding
def pkcs7_decode(paddedData, keySize=16): ''' Remove the PKCS#7 padding ''' # Use ord + [-1:] to support both python 2 and 3 val = ord(paddedData[-1:]) if val > keySize: raise StreamError("Input is not padded or padding is corrupt, got padding size of {0}".format(val)) return padded...
Attempts to parse a variant playlist and return its streams.
def parse_variant_playlist(cls, session_, url, name_key="name", name_prefix="", check_streams=False, force_restart=False, name_fmt=None, start_offset=0, duration=None, **request_params): "...
Changes google. com to www. google. com
def prepend_www(url): """Changes google.com to www.google.com""" parsed = urlparse(url) if parsed.netloc.split(".")[0] != "www": return parsed.scheme + "://www." + parsed.netloc + parsed.path else: return url
Wrapper around json. loads.
def parse_json(data, name="JSON", exception=PluginError, schema=None): """Wrapper around json.loads. Wraps errors in custom exception with a snippet of the data in the message. """ try: json_data = json.loads(data) except ValueError as err: snippet = repr(data) if len(snippe...
Wrapper around ElementTree. fromstring with some extras.
def parse_xml(data, name="XML", ignore_ns=False, exception=PluginError, schema=None, invalid_char_entities=False): """Wrapper around ElementTree.fromstring with some extras. Provides these extra features: - Handles incorrectly encoded XML - Allows stripping namespace information - Wraps errors i...
Parses a query string into a dict.
def parse_qsd(data, name="query string", exception=PluginError, schema=None, **params): """Parses a query string into a dict. Unlike parse_qs and parse_qsl, duplicate keys are not preserved in favor of a simpler return value. """ value = dict(parse_qsl(data, **params)) if schema: value...
Search for a key in a nested dict or list of nested dicts and return the values.
def search_dict(data, key): """ Search for a key in a nested dict, or list of nested dicts, and return the values. :param data: dict/list to search :param key: key to find :return: matches for key """ if isinstance(data, dict): for dkey, value in data.items(): if dkey ==...
Get the live stream in a particular language: param lang:: param path:: return:
def _get_live_streams(self, lang, path): """ Get the live stream in a particular language :param lang: :param path: :return: """ res = self.session.http.get(self._live_api_url.format(lang, path)) live_res = self.session.http.json(res)['default']['uid'] ...
Find the streams for OlympicChannel: return:
def _get_streams(self): """ Find the streams for OlympicChannel :return: """ match = self._url_re.match(self.url) type_of_stream = match.group('type') lang = re.search(r"/../", self.url).group(0) if type_of_stream == 'tv': path = re.search(r"t...
Returns LOW priority if the URL is not prefixed with hls:// but ends with. m3u8 and return NORMAL priority if the URL is prefixed.: param url: the URL to find the plugin priority for: return: plugin priority for the given URL
def priority(cls, url): """ Returns LOW priority if the URL is not prefixed with hls:// but ends with .m3u8 and return NORMAL priority if the URL is prefixed. :param url: the URL to find the plugin priority for :return: plugin priority for the given URL """ m = cl...
Spawn the process defined in cmd
def spawn(self, parameters=None, arguments=None, stderr=None, timeout=None, short_option_prefix="-", long_option_prefix="--"): """ Spawn the process defined in `cmd` parameters is converted to options the short and long option prefixes if a list is given as the value, the parameter is r...
Brute force regex based HTML tag parser. This is a rough - and - ready searcher to find HTML tags when standards compliance is not required. Will find tags that are commented out or inside script tag etc.
def itertags(html, tag): """ Brute force regex based HTML tag parser. This is a rough-and-ready searcher to find HTML tags when standards compliance is not required. Will find tags that are commented out, or inside script tag etc. :param html: HTML page :param tag: tag name to find :return: gen...
Attempt to parse a DASH manifest file and return its streams
def parse_manifest(cls, session, url_or_manifest, **args): """ Attempt to parse a DASH manifest file and return its streams :param session: Streamlink session instance :param url_or_manifest: URL of the manifest file or an XML manifest string :return: a dict of name -> DASHStrea...
Determine which Unicode encoding the JSON text sample is encoded with
def determine_json_encoding(cls, sample): """ Determine which Unicode encoding the JSON text sample is encoded with RFC4627 (http://www.ietf.org/rfc/rfc4627.txt) suggests that the encoding of JSON text can be determined by checking the pattern of NULL bytes in first 4 octets of the text...
Parses JSON from a response.
def json(cls, res, *args, **kwargs): """Parses JSON from a response.""" # if an encoding is already set then use the provided encoding if res.encoding is None: res.encoding = cls.determine_json_encoding(res.content[:4]) return parse_json(res.text, *args, **kwargs)
Parses XML from a response.
def xml(cls, res, *args, **kwargs): """Parses XML from a response.""" return parse_xml(res.text, *args, **kwargs)
Parses a semi - colon delimited list of cookies.
def parse_cookies(self, cookies, **kwargs): """Parses a semi-colon delimited list of cookies. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(cookies): self.cookies.set(name, value, **kwargs)
Parses a semi - colon delimited list of headers.
def parse_headers(self, headers): """Parses a semi-colon delimited list of headers. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(headers): self.headers[name] = value
Parses a semi - colon delimited list of query parameters.
def parse_query_params(self, cookies, **kwargs): """Parses a semi-colon delimited list of query parameters. Example: foo=bar;baz=qux """ for name, value in _parse_keyvalue_list(cookies): self.params[name] = value
Finds the streams from tvcatchup. com.
def _get_streams(self): """ Finds the streams from tvcatchup.com. """ token = self.login(self.get_option("username"), self.get_option("password")) m = self._url_re.match(self.url) scode = m and m.group("scode") or self.get_option("station_code") res = self.sessio...
Randomly generated deviceId.: return:
def device_id(self): """ Randomly generated deviceId. :return: """ if self._device_id is None: self._device_id = "".join( random.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(50)) return self._device_id
Return the message for this LogRecord.
def getMessage(self): """ Return the message for this LogRecord. Return the message for this LogRecord after merging any user-supplied arguments with the message. """ msg = self.msg if self.args: msg = msg.format(*self.args) return maybe_encod...
A factory method which can be overridden in subclasses to create specialized LogRecords.
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ if name.startswith("streamlink"): rv = _LogRecord(na...
Wraps a file described in request in a Response object.
def send(self, request, **kwargs): """ Wraps a file, described in request, in a Response object. :param request: The PreparedRequest` being "sent". :returns: a Response object containing the file """ # Check that the method makes sense. Only support GET if reque...
Get the info about the content based on the ID: param content_id:: return:
def _get_media_info(self, content_id): """ Get the info about the content, based on the ID :param content_id: :return: """ params = {"identityPointId": self._session_attributes.get("ipid"), "fingerprint": self._session_attributes.get("fprt"), ...
Find the streams for vk. com: return:
def _get_streams(self): """ Find the streams for vk.com :return: """ self.session.http.headers.update({'User-Agent': useragents.IPHONE_6}) # If this is a 'videos' catalog URL # with an video ID in the GET request, get that instead url = self.follow_vk_red...
Find the streams for web. tv: return:
def _get_streams(self): """ Find the streams for web.tv :return: """ headers = {} res = self.session.http.get(self.url, headers=headers) headers["Referer"] = self.url sources = self._sources_re.findall(res.text) if len(sources): sdata ...
Attempt a login to LiveEdu. tv
def login(self): """ Attempt a login to LiveEdu.tv """ email = self.get_option("email") password = self.get_option("password") if email and password: res = self.session.http.get(self.login_url) csrf_match = self.csrf_re.search(res.text) ...
Get the config object from the page source and call the API to get the list of streams: return:
def _get_streams(self): """ Get the config object from the page source and call the API to get the list of streams :return: """ # attempt a login self.login() res = self.session.http.get(self.url) # decode the config for the page matches =...
Loads a plugin from the same directory as the calling plugin.
def load_support_plugin(name): """Loads a plugin from the same directory as the calling plugin. The path used is extracted from the last call in module scope, therefore this must be called only from module level in the originating plugin or the correct plugin path will not be found. """ # Get...
Take the scheme from the current URL and applies it to the target URL if the target URL startswith// or is missing a scheme: param current: current URL: param target: target URL: return: target URL with the current URLs scheme
def update_scheme(current, target): """ Take the scheme from the current URL and applies it to the target URL if the target URL startswith // or is missing a scheme :param current: current URL :param target: target URL :return: target URL with the current URLs scheme """ target_p = urlpa...
Compare two URLs and return True if they are equal some parts of the URLs can be ignored: param first: URL: param second: URL: param ignore_scheme: ignore the scheme: param ignore_netloc: ignore the netloc: param ignore_path: ignore the path: param ignore_params: ignore the params: param ignore_query: ignore the query ...
def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False, ignore_query=False, ignore_fragment=False): """ Compare two URLs and return True if they are equal, some parts of the URLs can be ignored :param first: URL :param second: URL ...
Join extra paths to a URL does not join absolute paths: param base: the base URL: param parts: a list of the parts to join: param allow_fragments: include url fragments: return: the joined URL
def url_concat(base, *parts, **kwargs): """ Join extra paths to a URL, does not join absolute paths :param base: the base URL :param parts: a list of the parts to join :param allow_fragments: include url fragments :return: the joined URL """ allow_fragments = kwargs.get("allow_fragments"...
Update or remove keys from a query string in a URL
def update_qsd(url, qsd=None, remove=None): """ Update or remove keys from a query string in a URL :param url: URL to update :param qsd: dict of keys to update, a None value leaves it unchanged :param remove: list of keys to remove, or "*" to remove all note: updated keys are nev...
Find all the streams for the ITV url: return: Mapping of quality to stream
def _get_streams(self): """ Find all the streams for the ITV url :return: Mapping of quality to stream """ self.session.http.headers.update({"User-Agent": useragents.FIREFOX}) video_info = self.video_info() video_info_url = video_info.get("data-html5-playl...
Reads FLV tags from fd or buf and returns them with adjusted timestamps.
def iter_chunks(self, fd=None, buf=None, skip_header=None): """Reads FLV tags from fd or buf and returns them with adjusted timestamps.""" timestamps = dict(self.timestamps_add) tag_iterator = self.iter_tags(fd=fd, buf=buf, skip_header=skip_header) if not self.flv_header_writ...
Find all the arguments required by name
def requires(self, name): """ Find all the arguments required by name :param name: name of the argument the find the dependencies :return: list of dependant arguments """ results = set([name]) argument = self.get(name) for reqname in argument.requires: ...
Checks if file already exists and ask the user if it should be overwritten if it does.
def check_file_output(filename, force): """Checks if file already exists and ask the user if it should be overwritten if it does.""" log.debug("Checking file output") if os.path.isfile(filename) and not force: if sys.stdin.isatty(): answer = console.ask("File {0} already exists! Ov...
Decides where to write the stream.
def create_output(plugin): """Decides where to write the stream. Depending on arguments it can be one of these: - The stdout pipe - A subprocess' stdin pipe - A named pipe that the subprocess reads from - A regular file """ if (args.output or args.stdout) and (args.record or args....
Creates a HTTP server listening on a given host and port.
def create_http_server(host=None, port=0): """Creates a HTTP server listening on a given host and port. If host is empty, listen on all available interfaces, and if port is 0, listen on a random high port. """ try: http = HTTPServer() http.bind(host=host, port=port) except OSEr...
Repeatedly accept HTTP connections on a server.
def iter_http_requests(server, player): """Repeatedly accept HTTP connections on a server. Forever if the serving externally, or while a player is running if it is not empty. """ while not player or player.running: try: yield server.open(timeout=2.5) except OSError: ...
Continuously output the stream over HTTP.
def output_stream_http(plugin, initial_streams, external=False, port=0): """Continuously output the stream over HTTP.""" global output if not external: if not args.player: console.exit("The default player (VLC) does not seem to be " "installed. You must specify ...
Prepares a filename to be passed to the player.
def output_stream_passthrough(plugin, stream): """Prepares a filename to be passed to the player.""" global output title = create_title(plugin) filename = '"{0}"'.format(stream_to_url(stream)) output = PlayerOutput(args.player, args=args.player_args, filename=filename, cal...
Opens a stream and reads 8192 bytes from it.
def open_stream(stream): """Opens a stream and reads 8192 bytes from it. This is useful to check if a stream actually has data before opening the output. """ global stream_fd # Attempts to open the stream try: stream_fd = stream.open() except StreamError as err: raise ...
Open stream create output and finally write the stream to output.
def output_stream(plugin, stream): """Open stream, create output and finally write the stream to output.""" global output success_open = False for i in range(args.retry_open): try: stream_fd, prebuffer = open_stream(stream) success_open = True break e...
Reads data from stream and then writes it to the output.
def read_stream(stream, output, prebuffer, chunk_size=8192): """Reads data from stream and then writes it to the output.""" is_player = isinstance(output, PlayerOutput) is_http = isinstance(output, HTTPServer) is_fifo = is_player and output.namedpipe show_progress = isinstance(output, FileOutput) an...
Decides what to do with the selected stream.
def handle_stream(plugin, streams, stream_name): """Decides what to do with the selected stream. Depending on arguments it can be one of these: - Output internal command-line - Output JSON represenation - Continuously output the stream over HTTP - Output stream data to selected output ...
Fetches streams using correct parameters.
def fetch_streams(plugin): """Fetches streams using correct parameters.""" return plugin.streams(stream_types=args.stream_types, sorting_excludes=args.stream_sorting_excludes)
Attempts to fetch streams repeatedly until some are returned or limit hit.
def fetch_streams_with_retry(plugin, interval, count): """Attempts to fetch streams repeatedly until some are returned or limit hit.""" try: streams = fetch_streams(plugin) except PluginError as err: log.error(u"{0}", err) streams = None if not streams: log.info(...
Returns the real stream name of a synonym.
def resolve_stream_name(streams, stream_name): """Returns the real stream name of a synonym.""" if stream_name in STREAM_SYNONYMS and stream_name in streams: for name, stream in streams.items(): if stream is streams[stream_name] and name not in STREAM_SYNONYMS: return name ...
Formats a dict of streams.
def format_valid_streams(plugin, streams): """Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight). """ delimiter = ", " validstreams = [] for name, strea...
The URL handler.
def handle_url(): """The URL handler. Attempts to resolve the URL to a plugin and then attempts to fetch a list of available streams. Proceeds to handle stream if user specified a valid one, otherwise output list of valid streams. """ try: plugin = streamlink.resolve_url(args.url...
Outputs a list of all plugins Streamlink has loaded.
def print_plugins(): """Outputs a list of all plugins Streamlink has loaded.""" pluginlist = list(streamlink.get_plugins().keys()) pluginlist_formatted = ", ".join(sorted(pluginlist)) if console.json: console.msg_json(pluginlist) else: console.msg("Loaded plugins: {0}", pluginlist_...
Opens a web browser to allow the user to grant Streamlink access to their Twitch account.
def authenticate_twitch_oauth(): """Opens a web browser to allow the user to grant Streamlink access to their Twitch account.""" client_id = TWITCH_CLIENT_ID redirect_uri = "https://streamlink.github.io/twitch_oauth.html" url = ("https://api.twitch.tv/kraken/oauth2/authorize" "?respon...
Attempts to load plugins from a list of directories.
def load_plugins(dirs): """Attempts to load plugins from a list of directories.""" dirs = [os.path.expanduser(d) for d in dirs] for directory in dirs: if os.path.isdir(directory): streamlink.load_plugins(directory) else: log.warning("Plugin path {0} does not exist o...
Parses arguments.
def setup_args(parser, config_files=[], ignore_unknown=False): """Parses arguments.""" global args arglist = sys.argv[1:] # Load arguments from config files for config_file in filter(os.path.isfile, config_files): arglist.insert(0, "@" + config_file) args, unknown = parser.parse_known_...
Console setup.
def setup_console(output): """Console setup.""" global console # All console related operations is handled via the ConsoleOutput class console = ConsoleOutput(output, streamlink) console.json = args.json # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_han...
Sets the global HTTP settings such as proxy and headers.
def setup_http_session(): """Sets the global HTTP settings, such as proxy and headers.""" if args.http_proxy: streamlink.set_option("http-proxy", args.http_proxy) if args.https_proxy: streamlink.set_option("https-proxy", args.https_proxy) if args.http_cookie: streamlink.set_opt...
Loads any additional plugins.
def setup_plugins(extra_plugin_dir=None): """Loads any additional plugins.""" if os.path.isdir(PLUGINS_DIR): load_plugins([PLUGINS_DIR]) if extra_plugin_dir: load_plugins(extra_plugin_dir)
Sets Streamlink options.
def setup_options(): """Sets Streamlink options.""" if args.hls_live_edge: streamlink.set_option("hls-live-edge", args.hls_live_edge) if args.hls_segment_attempts: streamlink.set_option("hls-segment-attempts", args.hls_segment_attempts) if args.hls_playlist_reload_attempts: str...
Sets Streamlink plugin options.
def setup_plugin_args(session, parser): """Sets Streamlink plugin options.""" plugin_args = parser.add_argument_group("Plugin options") for pname, plugin in session.plugins.items(): defaults = {} for parg in plugin.arguments: plugin_args.add_argument(parg.argument_name(pname), *...
Sets Streamlink plugin options.
def setup_plugin_options(session, plugin): """Sets Streamlink plugin options.""" pname = plugin.module required = OrderedDict({}) for parg in plugin.arguments: if parg.options.get("help") != argparse.SUPPRESS: if parg.required: required[parg.name] = parg v...
Show current installed versions
def log_current_versions(): """Show current installed versions""" if logger.root.isEnabledFor(logging.DEBUG): # MAC OS X if sys.platform == "darwin": os_version = "macOS {0}".format(platform.mac_ver()[0]) # Windows elif sys.platform.startswith("win"): os_v...
Try to find a stream_id
def _get_stream_id(self, text): """Try to find a stream_id""" m = self._image_re.search(text) if m: return m.group("stream_id")
Fallback if no stream_id was found before
def _get_iframe(self, text): """Fallback if no stream_id was found before""" m = self._iframe_re.search(text) if m: return self.session.streams(m.group("url"))
Sets general options used by plugins and streams originating from this session object.
def set_option(self, key, value): """Sets general options used by plugins and streams originating from this session object. :param key: key of the option :param value: value to set the option to **Available options**: ======================== =========================...
Returns current value of specified option.
def get_option(self, key): """Returns current value of specified option. :param key: key of the option """ # Backwards compatibility if key == "rtmpdump": key = "rtmp-rtmpdump" elif key == "rtmpdump-proxy": key = "rtmp-proxy" elif key == ...
Sets plugin specific options used by plugins originating from this session object.
def set_plugin_option(self, plugin, key, value): """Sets plugin specific options used by plugins originating from this session object. :param plugin: name of the plugin :param key: key of the option :param value: value to set the option to """ if plugin in self...
Returns current value of plugin specific option.
def get_plugin_option(self, plugin, key): """Returns current value of plugin specific option. :param plugin: name of the plugin :param key: key of the option """ if plugin in self.plugins: plugin = self.plugins[plugin] return plugin.get_option(key)
Attempts to find a plugin that can use this URL.
def resolve_url(self, url, follow_redirect=True): """Attempts to find a plugin that can use this URL. The default protocol (http) will be prefixed to the URL if not specified. Raises :exc:`NoPluginError` on failure. :param url: a URL to match against loaded plugins :pa...
Attempts to find a plugin and extract streams from the * url *.
def streams(self, url, **params): """Attempts to find a plugin and extract streams from the *url*. *params* are passed to :func:`Plugin.streams`. Raises :exc:`NoPluginError` if no plugin is found. """ plugin = self.resolve_url(url) return plugin.streams(**params)
Attempt to load plugins from the path specified.
def load_plugins(self, path): """Attempt to load plugins from the path specified. :param path: full path to a directory where to look for plugins """ for loader, name, ispkg in pkgutil.iter_modules([path]): file, pathname, desc = imp.find_module(name, [path]) # ...
Get the VOD data path and the default VOD ID: return:
def vod_data(self, vid=None): """ Get the VOD data path and the default VOD ID :return: """ page = self.session.http.get(self.url) m = self._vod_re.search(page.text) vod_data_url = m and urljoin(self.url, m.group(0)) if vod_data_url: self.logge...
converts a timestamp to seconds
def hours_minutes_seconds(value): """converts a timestamp to seconds - hours:minutes:seconds to seconds - minutes:seconds to seconds - 11h22m33s to seconds - 11h to seconds - 20h15m to seconds - seconds to seconds :param value: hh:mm:ss ; 00h00m00s ; seconds :return: se...
Checks value for minimum length using len ().
def length(length): """Checks value for minimum length using len().""" def min_len(value): if not len(value) >= length: raise ValueError( "Minimum length is {0} but value is {1}".format(length, len(value)) ) return True return min_len
Checks if the string value starts with another string.
def startswith(string): """Checks if the string value starts with another string.""" def starts_with(value): validate(text, value) if not value.startswith(string): raise ValueError("'{0}' does not start with '{1}'".format(value, string)) return True return starts_with
Checks if the string value ends with another string.
def endswith(string): """Checks if the string value ends with another string.""" def ends_with(value): validate(text, value) if not value.endswith(string): raise ValueError("'{0}' does not end with '{1}'".format(value, string)) return True return ends_with
Checks if the string value contains another string.
def contains(string): """Checks if the string value contains another string.""" def contains_str(value): validate(text, value) if string not in value: raise ValueError("'{0}' does not contain '{1}'".format(value, string)) return True return contains_str
Get item from value ( value [ item ] ).
def get(item, default=None): """Get item from value (value[item]). If the item is not found, return the default. Handles XML elements, regex matches and anything that has __getitem__. """ def getter(value): if ET.iselement(value): value = value.attrib try: ...
Get a named attribute from an object.
def getattr(attr, default=None): """Get a named attribute from an object. When a default argument is given, it is returned when the attribute doesn't exist. """ def getter(value): return _getattr(value, attr, default) return transform(getter)
Filters out unwanted items using the specified function.
def filter(func): """Filters out unwanted items using the specified function. Supports both dicts and sequences, key/value pairs are expanded when applied to a dict. """ def expand_kv(kv): return func(*kv) def filter_values(value): cls = type(value) if isinstance(value,...
Apply function to each value inside the sequence or dict.
def map(func): """Apply function to each value inside the sequence or dict. Supports both dicts and sequences, key/value pairs are expanded when applied to a dict. """ # text is an alias for basestring on Python 2, which cannot be # instantiated and therefore can't be used to transform the valu...
Parses an URL and validates its attributes.
def url(**attributes): """Parses an URL and validates its attributes.""" def check_url(value): validate(text, value) parsed = urlparse(value) if not parsed.netloc: raise ValueError("'{0}' is not a valid URL".format(value)) for name, schema in attributes.items(): ...
Find a XML element via xpath.
def xml_find(xpath): """Find a XML element via xpath.""" def xpath_find(value): validate(ET.iselement, value) value = value.find(xpath) if value is None: raise ValueError("XPath '{0}' did not return an element".format(xpath)) return validate(ET.iselement, value) ...
Find a list of XML elements via xpath.
def xml_findall(xpath): """Find a list of XML elements via xpath.""" def xpath_findall(value): validate(ET.iselement, value) return value.findall(xpath) return transform(xpath_findall)
Finds playlist info ( type id ) in HTTP response.
def _find_playlist_info(response): """ Finds playlist info (type, id) in HTTP response. :param response: Response object. :returns: Dictionary with type and id. """ values = {} matches = _playlist_info_re.search(response.text) if matches: values['type'] = matches.group(1) ...
Finds embedded player url in HTTP response.
def _find_player_url(response): """ Finds embedded player url in HTTP response. :param response: Response object. :returns: Player url (str). """ url = '' matches = _player_re.search(response.text) if matches: tmp_url = matches.group(0).replace('&', '&') if 'hash' no...
Find the VOD video url: return: video url
def _get_vod_stream(self): """ Find the VOD video url :return: video url """ res = self.session.http.get(self.url) video_urls = self._re_vod.findall(res.text) if len(video_urls): return dict(vod=HTTPStream(self.session, video_urls[0]))
Get the live stream in a particular language: param match:: return:
def _get_live_streams(self, match): """ Get the live stream in a particular language :param match: :return: """ live_url = self._live_api_url.format(match.get("subdomain")) live_res = self.session.http.json(self.session.http.get(live_url), schema=self._live_schema...
Find the streams for euronews: return:
def _get_streams(self): """ Find the streams for euronews :return: """ match = self._url_re.match(self.url).groupdict() if match.get("path") == "live": return self._get_live_streams(match) else: return self._get_vod_stream()
Attempts to parse a M3U8 playlist from a string of data.
def load(data, base_uri=None, parser=M3U8Parser, **kwargs): """Attempts to parse a M3U8 playlist from a string of data. If specified, *base_uri* is the base URI that relative URIs will be joined together with, otherwise relative URIs will be as is. If specified, *parser* can be a M3U8Parser subclass t...
Check if the current player supports adding a title
def supported_player(cls, cmd): """ Check if the current player supports adding a title :param cmd: command to test :return: name of the player|None """ if not is_win32: # under a POSIX system use shlex to find the actual command # under windows t...
Login to the schoolism account and return the users account: param email: ( str ) email for account: param password: ( str ) password for account: return: ( str ) users email
def login(self, email, password): """ Login to the schoolism account and return the users account :param email: (str) email for account :param password: (str) password for account :return: (str) users email """ if self.options.get("email") and self.options.get("pa...
Get the livestream videoid from a username. https:// developer. dailymotion. com/ tools/ apiexplorer#/ user/ videos/ list
def get_live_id(self, username): """Get the livestream videoid from a username. https://developer.dailymotion.com/tools/apiexplorer#/user/videos/list """ params = { "flags": "live_onair" } api_user_videos = USER_INFO_URL.format(username) + "/videos" ...