U
    g                    @   s\  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZddlmZmZmZmZ ddlm Z  ddl!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( ddl)m*Z*m+Z+m,Z,m-Z- dd	l.m/Z/ dd
l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZbmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZk G dd dZlG dd delZmG dd delZneoepZqdS )    N   )compat_etree_fromstringcompat_expandusercompat_os_nameurllib_req_to_req)LenientSimpleCookie)get_base_urlremove_encrypted_media)HlsFD)HEADRequestRequest)	HTTPErrorIncompleteReadTransportErrornetwork_exceptions)ImpersonateTarget);IDENTITY
JSON_LD_RE
NO_DEFAULTExtractorErrorFormatSorterGeoRestrictedErrorGeoUtilsLenientJSONDecoderPopenRegexNotFoundErrorRetryManagerUnsupportedErrorage_restrictedbase_urlbug_reports_messageclassproperty
clean_htmldeprecation_warningdetermine_extdict_getencode_data_uriextract_attributesfilter_dictfix_xml_ampersandsfloat_or_noneformat_fieldint_or_nonejoin_nonempty
js_to_jsonmimetype2extnetrc_from_content
orderedSetparse_bitrateparse_codecsparse_durationparse_iso8601parse_m3u8_attributesparse_resolutionsanitize_filenamesanitize_urlsmuggle_urlstr_or_none
str_to_intstrip_or_nonetraverse_objtruncate_stringtry_calltry_getunescapeHTMLunified_strdateunified_timestampurl_basenameurl_or_noneurlhandle_detect_exturljoinvariadicxpath_element
xpath_textxpath_with_nsc                       s"
  e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZg ZedfddZdddZed	d
 Zedd Zedd Zedd Zedd Zedd Zdd Zdd Zdd Zdd Zdd Ze dd  Z!e d!d" Z"d#d$ Z#d%d& Z$d'd( Z%d)d* Z&ed+d, Z'e(d-d. Z)e*d/d0 Z+dd1d2Z,dd3d4Z-dddddi i dddf
d5d6Z.e*d7d8 Z/d9d: Z0dd;d<Z1d=d> Z2dd?d@Z3dAdB Z4ddCdDZ5ddEdFZ6dGdH Z7dIdJ Z8e8dKdLdMdNdO\Z9Z:e8dPdQdRdSdT\Z;Z<e8dUdVdWdXdT\Z=Z>e8dYddddZd[ Z?dddd[efd\d]Z@ddd^d_d`ZAdadb ZBdcdd ZCddedfZDefdgdhZEdidj ZFdkdl ZGdmdn ZHdodp ZIdqdefdrdsZJddudvZKddwdxZLe*dddydzd{ZMeddeNddfd|d}ZOe*ddd~ddZPedddfddZQdddedddZRedddfddZSdddZTdddZUdddZVe*dd ZWe*dd ZXdddZYdd ZZdd Z[ddddZ\dddZ]dd Z^dddddZ_dddZ`dd Zae*dd Zbdd Zcdd Zddd ZededddZfddedddZgdddZhdedddZiddddddZje*ddĄ ZkddƄ Zle(ddǍddɄ Zmg fdd˄Zndd̈́ Zoe*ddτ Zpdi fdd҄ZqddԄ ZrdddքZsddd؄Ztdddddڄ dddi i f	dd܄Zudddddڄ ddfdd߄ZvdddZwdd Zxdd Zyddddddddddi i fddZzdddddddddddi i dfddZ{dddi i fddZ|dd Z}dddi i fddZ~e*dddZdddZdd ZdddZdddZdddZdd Zdd  ZdddZdddZdddZddd	Zd
d Zdd Zdddddi i fddZdd Zdd Zdd ZdddZdd Zdddddi i fddZdddZdddZd d! Zi fd"d#Zdg fd$d%Zdefd&d'Zed(d)d*Zdd+d,Zdd-d.Zd/d0 Zdd1d2Zdd3d4Zddd5ddi fd6d7Zd8d9 Zd:d; Zedd<d=Zed>d? Ze(ddǍd@dA Ze(ddǍdBdC ZedDdE ZedFdG ZedddHdIdJZdKdL ZdMdN ZG dOdP dPeZdQdR ZdSdT Ze*dUdV ZeddWdXdYZdZd[ Zd\d] Zejd^d_ Zd`da Zdbdc Zddde Ze*dfdg ZdddhdidjZddkdlZdmdn Ze*ddodpZefdddqdrdsZddtdАdudvdwZddddxdyZdzd{ Zi d|d}d~dZedd Zedd Zedd ZG dd deZedd Zedd fdd
Zʇ  ZS (  InfoExtractoram  Information Extractor class.

    Information extractors are the classes that, given a URL, extract
    information about the video (or videos) the URL refers to. This
    information includes the real video URL, the video title, author and
    others. The information is stored in a dictionary which is then
    passed to the YoutubeDL. The YoutubeDL processes this
    information possibly downloading the video to the file system, among
    other possible outcomes.

    The type field determines the type of the result.
    By far the most common value (and the default if _type is missing) is
    "video", which indicates a single video.

    For a video, the dictionaries must include the following fields:

    id:             Video identifier.
    title:          Video title, unescaped. Set to an empty string if video has
                    no title as opposed to "None" which signifies that the
                    extractor failed to obtain a title

    Additionally, it must contain either a formats entry or a url one:

    formats:        A list of dictionaries for each format available, ordered
                    from worst to best quality.

                    Potential fields:
                    * url        The mandatory URL representing the media:
                                   for plain file media - HTTP URL of this file,
                                   for RTMP - RTMP URL,
                                   for HLS - URL of the M3U8 media playlist,
                                   for HDS - URL of the F4M manifest,
                                   for DASH
                                     - HTTP URL to plain file media (in case of
                                       unfragmented media)
                                     - URL of the MPD manifest or base URL
                                       representing the media if MPD manifest
                                       is parsed from a string (in case of
                                       fragmented media)
                                   for MSS - URL of the ISM manifest.
                    * request_data  Data to send in POST request to the URL
                    * manifest_url
                                 The URL of the manifest file in case of
                                 fragmented media:
                                   for HLS - URL of the M3U8 master playlist,
                                   for HDS - URL of the F4M manifest,
                                   for DASH - URL of the MPD manifest,
                                   for MSS - URL of the ISM manifest.
                    * manifest_stream_number  (For internal use only)
                                 The index of the stream in the manifest file
                    * ext        Will be calculated from URL if missing
                    * format     A human-readable description of the format
                                 ("mp4 container with h264/opus").
                                 Calculated from the format_id, width, height.
                                 and format_note fields if missing.
                    * format_id  A short description of the format
                                 ("mp4_h264_opus" or "19").
                                Technically optional, but strongly recommended.
                    * format_note Additional info about the format
                                 ("3D" or "DASH video")
                    * width      Width of the video, if known
                    * height     Height of the video, if known
                    * aspect_ratio  Aspect ratio of the video, if known
                                 Automatically calculated from width and height
                    * resolution Textual description of width and height
                                 Automatically calculated from width and height
                    * dynamic_range The dynamic range of the video. One of:
                                 "SDR" (None), "HDR10", "HDR10+, "HDR12", "HLG, "DV"
                    * tbr        Average bitrate of audio and video in kbps (1000 bits/sec)
                    * abr        Average audio bitrate in kbps (1000 bits/sec)
                    * acodec     Name of the audio codec in use
                    * asr        Audio sampling rate in Hertz
                    * audio_channels  Number of audio channels
                    * vbr        Average video bitrate in kbps (1000 bits/sec)
                    * fps        Frame rate
                    * vcodec     Name of the video codec in use
                    * container  Name of the container format
                    * filesize   The number of bytes, if known in advance
                    * filesize_approx  An estimate for the number of bytes
                    * player_url SWF Player URL (used for rtmpdump).
                    * protocol   The protocol that will be used for the actual
                                 download, lower-case. One of "http", "https" or
                                 one of the protocols defined in downloader.PROTOCOL_MAP
                    * fragment_base_url
                                 Base URL for fragments. Each fragment's path
                                 value (if present) will be relative to
                                 this URL.
                    * fragments  A list of fragments of a fragmented media.
                                 Each fragment entry must contain either an url
                                 or a path. If an url is present it should be
                                 considered by a client. Otherwise both path and
                                 fragment_base_url must be present. Here is
                                 the list of all potential fields:
                                 * "url" - fragment's URL
                                 * "path" - fragment's path relative to
                                            fragment_base_url
                                 * "duration" (optional, int or float)
                                 * "filesize" (optional, int)
                    * is_from_start  Is a live format that can be downloaded
                                from the start. Boolean
                    * preference Order number of this format. If this field is
                                 present and not None, the formats get sorted
                                 by this field, regardless of all other values.
                                 -1 for default (order by other properties),
                                 -2 or smaller for less than default.
                                 < -1000 to hide the format (if there is
                                    another one which is strictly better)
                    * language   Language code, e.g. "de" or "en-US".
                    * language_preference  Is this in the language mentioned in
                                 the URL?
                                 10 if it's what the URL is about,
                                 -1 for default (don't know),
                                 -10 otherwise, other values reserved for now.
                    * quality    Order number of the video quality of this
                                 format, irrespective of the file format.
                                 -1 for default (order by other properties),
                                 -2 or smaller for less than default.
                    * source_preference  Order number for this video source
                                  (quality takes higher priority)
                                 -1 for default (order by other properties),
                                 -2 or smaller for less than default.
                    * http_headers  A dictionary of additional HTTP headers
                                 to add to the request.
                    * stretched_ratio  If given and not 1, indicates that the
                                 video's pixels are not square.
                                 width : height ratio as float.
                    * no_resume  The server does not support resuming the
                                 (HTTP or RTMP) download. Boolean.
                    * has_drm    True if the format has DRM and cannot be downloaded.
                                 'maybe' if the format may have DRM and has to be tested before download.
                    * extra_param_to_segment_url  A query string to append to each
                                 fragment's URL, or to update each existing query string
                                 with. If it is an HLS stream with an AES-128 decryption key,
                                 the query paramaters will be passed to the key URI as well,
                                 unless there is an `extra_param_to_key_url` given,
                                 or unless an external key URI is provided via `hls_aes`.
                                 Only applied by the native HLS/DASH downloaders.
                    * extra_param_to_key_url  A query string to append to the URL
                                 of the format's HLS AES-128 decryption key.
                                 Only applied by the native HLS downloader.
                    * hls_aes    A dictionary of HLS AES-128 decryption information
                                 used by the native HLS downloader to override the
                                 values in the media playlist when an '#EXT-X-KEY' tag
                                 is present in the playlist:
                                 * uri  The URI from which the key will be downloaded
                                 * key  The key (as hex) used to decrypt fragments.
                                        If `key` is given, any key URI will be ignored
                                 * iv   The IV (as hex) used to decrypt fragments
                    * downloader_options  A dictionary of downloader options
                                 (For internal use only)
                                 * http_chunk_size Chunk size for HTTP downloads
                                 * ffmpeg_args     Extra arguments for ffmpeg downloader (input)
                                 * ffmpeg_args_out Extra arguments for ffmpeg downloader (output)
                    * is_dash_periods  Whether the format is a result of merging
                                 multiple DASH periods.
                    RTMP formats can also have the additional fields: page_url,
                    app, play_path, tc_url, flash_version, rtmp_live, rtmp_conn,
                    rtmp_protocol, rtmp_real_time

    url:            Final video URL.
    ext:            Video filename extension.
    format:         The video format, defaults to ext (used for --get-format)
    player_url:     SWF Player URL (used for rtmpdump).

    The following fields are optional:

    direct:         True if a direct video file was given (must only be set by GenericIE)
    alt_title:      A secondary title of the video.
    display_id:     An alternative identifier for the video, not necessarily
                    unique, but available before title. Typically, id is
                    something like "4234987", title "Dancing naked mole rats",
                    and display_id "dancing-naked-mole-rats"
    thumbnails:     A list of dictionaries, with the following entries:
                        * "id" (optional, string) - Thumbnail format ID
                        * "url"
                        * "preference" (optional, int) - quality of the image
                        * "width" (optional, int)
                        * "height" (optional, int)
                        * "resolution" (optional, string "{width}x{height}",
                                        deprecated)
                        * "filesize" (optional, int)
                        * "http_headers" (dict) - HTTP headers for the request
    thumbnail:      Full URL to a video thumbnail image.
    description:    Full video description.
    uploader:       Full name of the video uploader.
    license:        License name the video is licensed under.
    creators:       List of creators of the video.
    timestamp:      UNIX timestamp of the moment the video was uploaded
    upload_date:    Video upload date in UTC (YYYYMMDD).
                    If not explicitly set, calculated from timestamp
    release_timestamp: UNIX timestamp of the moment the video was released.
                    If it is not clear whether to use timestamp or this, use the former
    release_date:   The date (YYYYMMDD) when the video was released in UTC.
                    If not explicitly set, calculated from release_timestamp
    release_year:   Year (YYYY) as integer when the video or album was released.
                    To be used if no exact release date is known.
                    If not explicitly set, calculated from release_date.
    modified_timestamp: UNIX timestamp of the moment the video was last modified.
    modified_date:   The date (YYYYMMDD) when the video was last modified in UTC.
                    If not explicitly set, calculated from modified_timestamp
    uploader_id:    Nickname or id of the video uploader.
    uploader_url:   Full URL to a personal webpage of the video uploader.
    channel:        Full name of the channel the video is uploaded on.
                    Note that channel fields may or may not repeat uploader
                    fields. This depends on a particular extractor.
    channel_id:     Id of the channel.
    channel_url:    Full URL to a channel webpage.
    channel_follower_count: Number of followers of the channel.
    channel_is_verified: Whether the channel is verified on the platform.
    location:       Physical location where the video was filmed.
    subtitles:      The available subtitles as a dictionary in the format
                    {tag: subformats}. "tag" is usually a language code, and
                    "subformats" is a list sorted from lower to higher
                    preference, each element is a dictionary with the "ext"
                    entry and one of:
                        * "data": The subtitles file contents
                        * "url": A URL pointing to the subtitles file
                    It can optionally also have:
                        * "name": Name or description of the subtitles
                        * "http_headers": A dictionary of additional HTTP headers
                                  to add to the request.
                    "ext" will be calculated from URL if missing
    automatic_captions: Like 'subtitles'; contains automatically generated
                    captions instead of normal subtitles
    duration:       Length of the video in seconds, as an integer or float.
    view_count:     How many users have watched the video on the platform.
    concurrent_view_count: How many users are currently watching the video on the platform.
    like_count:     Number of positive ratings of the video
    dislike_count:  Number of negative ratings of the video
    repost_count:   Number of reposts of the video
    average_rating: Average rating given by users, the scale used depends on the webpage
    comment_count:  Number of comments on the video
    comments:       A list of comments, each with one or more of the following
                    properties (all but one of text or html optional):
                        * "author" - human-readable name of the comment author
                        * "author_id" - user ID of the comment author
                        * "author_thumbnail" - The thumbnail of the comment author
                        * "author_url" - The url to the comment author's page
                        * "author_is_verified" - Whether the author is verified
                                                 on the platform
                        * "author_is_uploader" - Whether the comment is made by
                                                 the video uploader
                        * "id" - Comment ID
                        * "html" - Comment as HTML
                        * "text" - Plain text of the comment
                        * "timestamp" - UNIX timestamp of comment
                        * "parent" - ID of the comment this one is replying to.
                                     Set to "root" to indicate that this is a
                                     comment to the original video.
                        * "like_count" - Number of positive ratings of the comment
                        * "dislike_count" - Number of negative ratings of the comment
                        * "is_favorited" - Whether the comment is marked as
                                           favorite by the video uploader
                        * "is_pinned" - Whether the comment is pinned to
                                        the top of the comments
    age_limit:      Age restriction for the video, as an integer (years)
    webpage_url:    The URL to the video webpage, if given to yt-dlp it
                    should allow to get the same result again. (It will be set
                    by YoutubeDL if it's missing)
    categories:     A list of categories that the video falls in, for example
                    ["Sports", "Berlin"]
    tags:           A list of tags assigned to the video, e.g. ["sweden", "pop music"]
    cast:           A list of the video cast
    is_live:        True, False, or None (=unknown). Whether this video is a
                    live stream that goes on instead of a fixed-length video.
    was_live:       True, False, or None (=unknown). Whether this video was
                    originally a live stream.
    live_status:    None (=unknown), 'is_live', 'is_upcoming', 'was_live', 'not_live',
                    or 'post_live' (was live, but VOD is not yet processed)
                    If absent, automatically set from is_live, was_live
    start_time:     Time in seconds where the reproduction should start, as
                    specified in the URL.
    end_time:       Time in seconds where the reproduction should end, as
                    specified in the URL.
    chapters:       A list of dictionaries, with the following entries:
                        * "start_time" - The start time of the chapter in seconds
                        * "end_time" - The end time of the chapter in seconds
                        * "title" (optional, string)
    heatmap:        A list of dictionaries, with the following entries:
                        * "start_time" - The start time of the data point in seconds
                        * "end_time" - The end time of the data point in seconds
                        * "value" - The normalized value of the data point (float between 0 and 1)
    playable_in_embed: Whether this video is allowed to play in embedded
                    players on other sites. Can be True (=always allowed),
                    False (=never allowed), None (=unknown), or a string
                    specifying the criteria for embedability; e.g. 'whitelist'
    availability:   Under what condition the video is available. One of
                    'private', 'premium_only', 'subscriber_only', 'needs_auth',
                    'unlisted' or 'public'. Use 'InfoExtractor._availability'
                    to set it
    media_type:     The type of media as classified by the site, e.g. "episode", "clip", "trailer"
    _old_archive_ids: A list of old archive ids needed for backward compatibility
    _format_sort_fields: A list of fields to use for sorting formats
    __post_extractor: A function to be called just before the metadata is
                    written to either disk, logger or console. The function
                    must return a dict which will be added to the info_dict.
                    This is usefull for additional information that is
                    time-consuming to extract. Note that the fields thus
                    extracted will not be available to output template and
                    match_filter. So, only "comments" and "comment_count" are
                    currently allowed to be extracted via this method.

    The following fields should only be used when the video belongs to some logical
    chapter or section:

    chapter:        Name or title of the chapter the video belongs to.
    chapter_number: Number of the chapter the video belongs to, as an integer.
    chapter_id:     Id of the chapter the video belongs to, as a unicode string.

    The following fields should only be used when the video is an episode of some
    series, programme or podcast:

    series:         Title of the series or programme the video episode belongs to.
    series_id:      Id of the series or programme the video episode belongs to, as a unicode string.
    season:         Title of the season the video episode belongs to.
    season_number:  Number of the season the video episode belongs to, as an integer.
    season_id:      Id of the season the video episode belongs to, as a unicode string.
    episode:        Title of the video episode. Unlike mandatory video title field,
                    this field should denote the exact title of the video episode
                    without any kind of decoration.
    episode_number: Number of the video episode within a season, as an integer.
    episode_id:     Id of the video episode, as a unicode string.

    The following fields should only be used when the media is a track or a part of
    a music album:

    track:          Title of the track.
    track_number:   Number of the track within an album or a disc, as an integer.
    track_id:       Id of the track (useful in case of custom indexing, e.g. 6.iii),
                    as a unicode string.
    artists:        List of artists of the track.
    composers:      List of composers of the piece.
    genres:         List of genres of the track.
    album:          Title of the album the track belongs to.
    album_type:     Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
    album_artists:  List of all artists appeared on the album.
                    E.g. ["Ash Borer", "Fell Voices"] or ["Various Artists"].
                    Useful for splits and compilations.
    disc_number:    Number of the disc or other physical medium the track belongs to,
                    as an integer.

    The following fields should only be set for clips that should be cut from the original video:

    section_start:  Start time of the section in seconds
    section_end:    End time of the section in seconds

    The following fields should only be set for storyboards:
    rows:           Number of rows in each storyboard fragment, as an integer
    columns:        Number of columns in each storyboard fragment, as an integer

    The following fields are deprecated and should not be set by new code:
    composer:       Use "composers" instead.
                    Composer(s) of the piece, comma-separated.
    artist:         Use "artists" instead.
                    Artist(s) of the track, comma-separated.
    genre:          Use "genres" instead.
                    Genre(s) of the track, comma-separated.
    album_artist:   Use "album_artists" instead.
                    All artists appeared on the album, comma-separated.
    creator:        Use "creators" instead.
                    The creator of the video.

    Unless mentioned otherwise, the fields should be Unicode strings.

    Unless mentioned otherwise, None is equivalent to absence of information.


    _type "playlist" indicates multiple videos.
    There must be a key "entries", which is a list, an iterable, or a PagedList
    object, each element of which is a valid dictionary by this specification.

    Additionally, playlists can have "id", "title", and any other relevant
    attributes with the same semantics as videos (see above).

    It can also have the following optional fields:

    playlist_count: The total number of videos in a playlist. If not given,
                    YoutubeDL tries to calculate it from "entries"


    _type "multi_video" indicates that there are multiple videos that
    form a single show, for examples multiple acts of an opera or TV episode.
    It must have an entries key like a playlist and contain all the keys
    required for a video at the same time.


    _type "url" indicates that the video must be extracted from another
    location, possibly by a different extractor. Its only required key is:
    "url" - the next URL to extract.
    The key "ie_key" can be set to the class name (minus the trailing "IE",
    e.g. "Youtube") if the extractor class is known in advance.
    Additionally, the dictionary may have any properties of the resolved entity
    known in advance, for example "title" if the title of the referred video is
    known ahead of time.


    _type "url_transparent" entities have the same specification as "url", but
    indicate that the given additional information is more precise than the one
    associated with the resolved URL.
    This is useful when a site employs a video service that hosts the video and
    its technical metadata, but that video service does not embed a useful
    title, description etc.


    Subclasses of this should also be added to the list of extractors and
    should define _VALID_URL as a regexp or a Sequence of regexps, and
    re-define the _real_extract() and (optionally) _real_initialize() methods.

    Subclasses may also override suitable() if necessary, but ensure the function
    signature is preserved and that this function imports everything it needs
    (except other extractors), so that lazy_extractors works correctly.

    Subclasses can define a list of _EMBED_REGEX, which will be searched for in
    the HTML of Generic webpages. It may also override _extract_embed_urls
    or _extract_from_webpage as necessary. While these are normally classmethods,
    _extract_from_webpage is allowed to be an instance method.

    _extract_from_webpage may raise self.StopExtraction to stop further
    processing of the webpage and obtain exclusive rights to it. This is useful
    when the extractor cannot reliably be matched using just the URL,
    e.g. invidious/peertube instances

    Embed-only extractors can be defined by setting _VALID_URL = False.

    To support username + password (or netrc) login, the extractor must define a
    _NETRC_MACHINE and re-define _perform_login(username, password) and
    (optionally) _initialize_pre_login() methods. The _perform_login method will
    be called between _initialize_pre_login and _real_initialize if credentials
    are passed by the user. In cases where it is necessary to have the login
    process as part of the extraction rather than initialization, _perform_login
    can be left undefined.

    _GEO_BYPASS attribute may be set to False in order to disable
    geo restriction bypass mechanisms for a particular extractor.
    Though it won't disable explicit geo restriction bypass based on
    country code provided with geo_bypass_country.

    _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
    countries for this extractor. One of these countries will be used by
    geo restriction bypass mechanism right away in order to bypass
    geo restriction, of course, if the mechanism is not disabled.

    _GEO_IP_BLOCKS attribute may contain a list of presumably geo unrestricted
    IP blocks in CIDR notation for this extractor. One of these IP blocks
    will be used by geo restriction bypass mechanism similarly
    to _GEO_COUNTRIES.

    The _ENABLED attribute should be set to False for IEs that
    are disabled by default and must be explicitly enabled.

    The _WORKING attribute should be set to False for broken IEs
    in order to warn the users and skip the tests.
    FNTc                 C   s`   d|p
| j  d}d}dd| d| d| d| d	| d
|tk	rN|n|  rZdnd S )Nz4--username and --password, --netrc-cmd, or --netrc (z ) to provide account credentialszpSee  https://github.com/yt-dlp/yt-dlp/wiki/FAQ#how-do-i-pass-cookies-to-yt-dlp  for how to manually pass cookies z'Use --cookies, --cookies-from-browser, z. zUse z@Use --cookies-from-browser or --cookies for the authentication. zNUse --cookies for the authentication (--cookies-from-browser might not work). )NanypasswordcookiesZsession_cookiesrO   rQ   )_NETRC_MACHINEr   supports_login)selfmethodnetrcZpassword_hintZcookies_hint rW   ;/tmp/pip-unpacked-wheel-q5ljy6pj/yt_dlp/extractor/common.py_login_hint>  s    zInfoExtractor._login_hintc                 C   s"   d| _ d| _t | _| | dS )zConstructor. Receives an optional downloader (a YoutubeDL instance).
        If a downloader is not passed during initialization,
        it must be set using "set_downloader()" before "extract()" is calledFN)_ready_x_forwarded_for_ipset_printed_messagesset_downloaderrT   
downloaderrW   rW   rX   __init__I  s    zInfoExtractor.__init__c                    sP   | j dkrd S d| jkr0tttjt| j | _tt	d  fdd| jD d S )NF_VALID_URL_REc                 3   s   | ]}|  V  qd S N)match).0regexurlrW   rX   	<genexpr>[  s     z1InfoExtractor._match_valid_url.<locals>.<genexpr>)

_VALID_URL__dict__tuplemaprecompilerI   rb   nextfilterclsrh   rW   rg   rX   _match_valid_urlR  s
    

zInfoExtractor._match_valid_urlc                 C   s   |  |dk	S )z8Receives a URL and returns True if suitable for this IE.N)rt   rr   rW   rW   rX   suitable]  s    zInfoExtractor.suitablec                 C   s   |  |dS )Nid)rt   grouprr   rW   rW   rX   	_match_idd  s    zInfoExtractor._match_idc              	   C   s,   z|  |W S  ttfk
r&   Y d S X d S rc   )rx   
IndexErrorAttributeErrorrr   rW   rW   rX   get_temp_idh  s    zInfoExtractor.get_temp_idc                 C   s   | j S )zGetter method for _WORKING.)_WORKINGrs   rW   rW   rX   workingo  s    zInfoExtractor.workingc                 C   s
   t | jS rc   )boolrR   r}   rW   rW   rX   rS   t  s    zInfoExtractor.supports_loginc                 C   s   t  | _| | j| jd | js|   |  rP|  \}}|r| 	|| n0| 
drd| j| jfkr| d| d  |   d| _dS )z.Initializes an instance (authentication, etc).)	countries	ip_blocksusernameFz7Login with password is not supported for this website. rQ   TN)r\   r]   _initialize_geo_bypass_GEO_COUNTRIES_GEO_IP_BLOCKSrZ   _initialize_pre_loginrS   _get_login_info_perform_login	get_paramIE_DESCrR   report_warningrY   _real_initializerT   r   rP   rW   rW   rX   
initializex  s    zInfoExtractor.initializec                 C   s   | j s| ddsdS |si }t|ttfr4d|i}| dd}|sb|d}| jrb|rbt|}|rt	
|| _ | d| j  d dS | d	d}|s|d}| jr|rt|}|rt	
|| _ | jd| j  d
|  d dS )aq  
        Initialize geo restriction bypass mechanism.

        This method is used to initialize geo bypass mechanism based on faking
        X-Forwarded-For HTTP header. A random country from provided country list
        is selected and a random IP belonging to this country is generated. This
        IP will be passed as X-Forwarded-For HTTP header in all subsequent
        HTTP requests.

        This method will be used for initial geo bypass mechanism initialization
        during the instance initialization with _GEO_COUNTRIES and
        _GEO_IP_BLOCKS.

        You may also manually call it from extractor's code if geo bypass
        information is not available beforehand (e.g. obtained during
        extraction) or due to some other reason. In this case you should pass
        this information in geo bypass context passed as first argument. It may
        contain following fields:

        countries:  List of geo unrestricted countries (similar
                    to _GEO_COUNTRIES)
        ip_blocks:  List of geo unrestricted IP blocks in CIDR notation
                    (similar to _GEO_IP_BLOCKS)

        
geo_bypassTNr   Zgeo_bypass_ip_blockr   zUsing fake IP z as X-Forwarded-Forgeo_bypass_country (z) as X-Forwarded-For)r[   r   
isinstancelistrl   get_GEO_BYPASSrandomchoicer   random_ipv4write_debug_downloaderupper)rT   Zgeo_bypass_contextZip_blockr   Zcountryr   rW   rW   rX   r     s8     





z$InfoExtractor._initialize_geo_bypassc                 C   s  zt dD ]}z|   | d| dr,|n
t|dd  | |}|dkrXW  W dS | jrh| j|d< |dpti }d	| d
krdD ]}||d q|W   W S  t	k
r } z| 
|jrW Y q
 W 5 d}~X Y q
X q
W n tk
r    Y n tk
rV } z@|jp| ||_|jp*| j|_|jp@t d |_ W 5 d}~X Y nt tk
r } ztd|d| |dW 5 d}~X Y n< ttfk
r } ztd|| |dW 5 d}~X Y nX dS )z9Extracts URL information and returns it in list of dicts.r   zExtracting URL: %sverbosed      NZ__x_forwarded_for_ip	subtitleszno-live-chatZcompat_opts)Z	live_chatcommentsZdanmakuzA network error has occurred.T)causeexpectedvideo_idz An extractor error has occurred.r   r   )ranger   	to_screenr   r?   _real_extractr[   r   popr   '_InfoExtractor__maybe_fake_ip_and_retryr   r   r   r   r{   ieIE_NAME	tracebacksysexc_infor   KeyErrorStopIteration)rT   rh   _Z	ie_resultr   langerW   rW   rX   extract  s@    


&zInfoExtractor.extractc                 C   sj   |  dd sf| jrf|  ddrf| jsf|rft|}t|| _| jrf| d| j d|  d dS dS )Nr   r   Tz:Video is geo restricted. Retrying extraction with fake IP r   z) as X-Forwarded-For.F)	r   r   r[   r   r   r   r   r   r   )rT   r   Zcountry_coderW   rW   rX   Z__maybe_fake_ip_and_retry  s"    

z'InfoExtractor.__maybe_fake_ip_and_retryc                 C   s
   || _ dS )z8Sets a YoutubeDL instance as the downloader for this IE.N)r   r_   rW   rW   rX   r^     s    zInfoExtractor.set_downloaderc                 C   s   | j jS rc   )r   cacherT   rW   rW   rX   r     s    zInfoExtractor.cachec                 C   s   | j jS rc   )r   	cookiejarr   rW   rW   rX   r     s    zInfoExtractor.cookiejarc                 C   s   dS )z5 Initialization before login. Redefine in subclasses.NrW   r   rW   rW   rX   r     s    z#InfoExtractor._initialize_pre_loginc                 C   s   dS )z: Login with username and password. Redefine in subclasses.NrW   r   rW   rW   rX   r     s    zInfoExtractor._perform_loginc                 C   s   dS )z4Real initialization process. Redefine in subclasses.NrW   r   rW   rW   rX   r   "  s    zInfoExtractor._real_initializec                 C   s   t ddS )z0Real extraction process. Redefine in subclasses.-This method must be implemented by subclassesNNotImplementedErrorrT   rh   rW   rW   rX   r   &  s    zInfoExtractor._real_extractc                 C   s   | j dd S )z>A string for getting the InfoExtractor with get_info_extractorN__name__r}   rW   rW   rX   ie_key*  s    zInfoExtractor.ie_keyc                 C   s   | j d d S )Nr   r   r}   rW   rW   rX   r   /  s    zInfoExtractor.IE_NAMEc                 C   sB   t | tst|d krdS t|r0|| jdkS | jt|kS d S )NFT)r   r   AssertionErrorcallablestatusrI   )errexpected_statusrW   rW   rX   Z__can_accept_status_code3  s    z&InfoExtractor.__can_accept_status_codec                 C   sL   t |tjjr$| jd t|}nt |ts6t|}|j||||d |S )NzrPassing a urllib.request.Request to _create_request() is deprecated. Use yt_dlp.networking.common.Request instead.)dataheadersquery
extensions)r   urllibrequestr   r   r#   r   update)rT   url_or_requestr   r   r   r   rW   rW   rX   _create_request=  s    

zInfoExtractor._create_requestc              
   C   s,  | j js<| dpd}|dkrD| d| d t| nd| j _|dkrX| | n4|dk	r|dkrx| t| n| | d|  | jr|pi 	 }|
d| j i }|
d	krt }
|
rd
d t|
D ng }tt| j j|d}|r||d< nl|rfd}|t|
sdnddtt| d7 }d}|rNt| d| dd| j| d| dd z| j | |||||W S  tk
r& } zt|tr| ||	r|j W Y ^S |dkrW Y LdS |dkrd}| d| }|rt||dn| | W Y dS W 5 d}~X Y nX dS )zs
        Return the response handle.

        See _download_webpage docstring for arguments specification.
        Zsleep_interval_requestsr   z	Sleeping z seconds ...FN: zX-Forwarded-For)TrN   c                 S   s$   g | ]}t |tr|nt|qS rW   )r   r   Zfrom_str)re   trW   rW   rX   
<listcomp>m  s   z2InfoExtractor._request_webpage.<locals>.<listcomp>impersonatez/The extractor is attempting impersonation, but z"no impersonate target is availablez2none of these impersonate targets are available: "z, "zlsee  https://github.com/yt-dlp/yt-dlp#impersonation  for information on installing the required dependenciesz; Tr   z ; if you encounter errors, then 	only_oncezUnable to download webpager   )r   Z_first_webpage_requestr   r   timesleepreport_download_webpagestrr[   copy
setdefaultr   rI   rp   rq   Z_impersonate_target_availablejoinrm   r   r   urlopenr   r   r   r   &_InfoExtractor__can_accept_status_coderesponse)rT   r   r   noteerrnotefatalr   r   r   r   r   require_impersonationZsleep_intervalr   Zrequested_targetsZavailable_targetmessageZinfo_msgr   errmsgrW   rW   rX   _request_webpageI  sh    




zInfoExtractor._request_webpagec                 C   s   t |tr|dd }| j||||||||	|
||d}|dkrL|rHtdS | j||||||||d}|dkrz|rvtdS ||fS )a  
        Return a tuple (page content as string, URL handle).

        Arguments:
        url_or_request -- plain text URL as a string or
            a yt_dlp.networking.Request object
        video_id -- Video/playlist/item identifier (string)

        Keyword arguments:
        note -- note printed before downloading (string)
        errnote -- note printed in case of an error (string)
        fatal -- flag denoting whether error should be considered fatal,
            i.e. whether it should cause ExtractionError to be raised,
            otherwise a warning will be reported and extraction continued
        encoding -- encoding for a page content decoding, guessed automatically
            when not explicitly specified
        data -- POST data (bytes)
        headers -- HTTP headers (dict)
        query -- URL query (dict)
        expected_status -- allows to accept failed HTTP requests (non 2xx
            status code) by explicitly specifying a set of accepted status
            codes. Can be any of the following entities:
                - an integer type specifying an exact failed status code to
                  accept
                - a list or a tuple of integer types specifying a list of
                  failed status codes to accept
                - a callable accepting an actual failed status code and
                  returning True if it should be accepted
            Note that this argument does not affect success status codes (2xx)
            which are always accepted.
        impersonate -- the impersonate target. Can be any of the following entities:
                - an instance of yt_dlp.networking.impersonate.ImpersonateTarget
                - a string in the format of CLIENT[:OS]
                - a list or a tuple of CLIENT[:OS] strings or ImpersonateTarget instances
                - a boolean value; True means any impersonate target is sufficient
        require_impersonation -- flag to toggle whether the request should raise an error
            if impersonation is not possible (bool, default: False)
        #r   )r   r   r   r   r   r   F)encodingr   )r   r   	partitionr   r   _webpage_read_content)rT   r   r   r   r   r   r   r   r   r   r   r   r   urlhcontentrW   rW   rX   _download_webpage_handle  s(    +
    z&InfoExtractor._download_webpage_handlec                 C   s^   t d| }|r|d}n>t d|d d }|rF|dd}n|drVd}nd}|S )	Nz2[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)   s*   <meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]i   asciis   zutf-16utf-8)rn   rd   rw   searchdecode
startswith)content_typewebpage_bytesmr   rW   rW   rX   _guess_encoding_from_content  s    

z*InfoExtractor._guess_encoding_from_contentc                 C   s   |d d }d|krRd|krRd}| j d|dd d}|rF|d| d	7 }t|d
dd|krd}| j d|dd d}|r|d|dd7 }t|d
dd|krd|krtdd
dd S )Ni   z-<title>Access to this site is blocked</title>ZWebsensezWAccess to this webpage has been blocked by Websense filtering software in your network.z<iframe src="([^"]+)"zWebsense information URLdefaultz Visit z for more detailsTr   z5<title>The URL you requested has been blocked</title>zzAccess to this webpage has been blocked by Indian censorship. Use a VPN or proxy server (with --proxy) to route around it.z</h1><p>(.*?)</p>zblock messagez (Message: "{}")
 uG   <title>TTK :: Доступ к ресурсу ограничен</title>zblocklist.rkn.gov.ruzAccess to this webpage has been blocked by decision of the Russian government. Visit http://blocklist.rkn.gov.ru/ for a block reason.)_html_search_regexr   formatreplace)rT   r   Zfirst_blockmsgZblocked_iframeZ	block_msgrW   rW   rX   Z__check_blocked  sB        zInfoExtractor.__check_blockedc           	      C   s   |d k	rt | }t|||dd}| dp2d}t||krndt |   }|d |t|  | }t| ddd}td	krt	j
|}t|d
krd| }|S )Nr   )delimZtrim_file_name   Z___z.dumpT)
restrictednti  z\\?\)hashlibmd5	hexdigestr-   r   lenencoder8   r   ospathabspath)	rT   rh   r   r   ZbasenZtrim_lengthhfilenameZabsfilepathrW   rW   rX   _request_dump_filename  s    
z$InfoExtractor._request_dump_filenamec                 C   sL   |s|  |dd|}z||dW S  tk
rF   |dd Y S X d S )NzContent-TyperN   r   r   )r   r   r   LookupError)rT   r   r   r   rW   rW   rX   Z__decode_webpage  s    zInfoExtractor.__decode_webpagec
              
   C   s*  z|  }
W nR tk
r^ } z4| d|j }|r>t||d| | W Y dS d }~X Y nX |d k	rp||
 }
| ddr| d|j  t	|

d}| j| | drt|tr| ||	j}	| |j||	}| d|  t|d	}||
 W 5 Q R X | |
||j}| | |S )
Nz: Error reading response: r   FZdump_intermediate_pageszDumping request to r   Zwrite_pageszSaving request to wb)readr   r   r   r   r   r   rh   base64	b64encoder   r   r   r   r   r   r  openwrite_InfoExtractor__decode_webpager   _InfoExtractor__check_blocked)rT   r   r   r   r   r   r   prefixr   r   r   r   r   dumpr  outfr   rW   rW   rX   r     s0    


z#InfoExtractor._webpage_read_contentc                 C   s>   |rt | d| |dn|r:| | d| d|  d S )Nr   r   )r   r   )rT   r   r   r   r   rW   rW   rX   Z__print_error2  s    zInfoExtractor.__print_errorc              
   C   sd   |r||}zt | W S  tjjjk
r^ } z | |d krBdn|||| W 5 d }~X Y nX d S )NzFailed to parse XML)r   r	  xmletreeElementTree
ParseError_InfoExtractor__print_error)rT   Z
xml_stringr   transform_sourcer   r   verW   rW   rX   
_parse_xml8  s    zInfoExtractor._parse_xmlc              
   K   s`   zt j|ftd|d|W S  tk
rZ } z | |d kr>dn|||| W 5 d }~X Y nX d S )NF)rs   strictr!  zFailed to parse JSON)jsonloadsr   
ValueErrorr   )rT   json_stringr   r!  r   r   Zparser_kwargsr"  rW   rW   rX   _parse_json@  s      zInfoExtractor._parse_jsonc                 O   s*   | j ||d|dd  f||S )N{}r   )r)  findrfind)rT   r   argskwargsrW   rW   rX   _parse_socket_response_as_jsonG  s    z,InfoExtractor._parse_socket_response_as_jsonc                    s   |dfdd
||d dd d i i d d dffdd	 ||d dd d i i d d df fdd		}d
d }| d|  dd| d ||d|  |   |fS )N)r   c                   s2    d kr|S |dkr||d< t |  |f||S )NFr   )getattr)r   r   r   r.  r/  )parserrW   rX   parseL  s
    z6InfoExtractor.__create_download_methods.<locals>.parseTFc                    sN   | j ||||||||	|
|||d}|dkr.|S |\}} | |||||d|fS )N)
r   r   r   r   r   r   r   r   r   r   Fr!  r   r   )r   )rT   r   r   r   r   r!  r   r   r   r   r   r   r   r   resr   r   )r3  rW   rX   download_handleT  s$             z@InfoExtractor.__create_download_methods.<locals>.download_handlec                    s  |  dr| |||	|
}| |j||j}| d|  z"t|d}| }W 5 Q R X W n2 tk
r } z| 	d|  W 5 d }~X Y n&X | 
|||j}| |||||dS |||||||	|
|||d}d kr|d t|  j||f|}|dkr|S |d	 S )
NZ
load_pageszLoading request from rbz"Unable to load request from disk: r4  )r   r   r!  r   r   r   r   r   r   r   r   r!  Fr   )r   r   r  rh   r   r   r  r  OSErrorr   r  r   r   r1  r   )rT   r   r   r   r   r!  r   r   r   r   r   r   r   r   r  Zdumpfr   r   r   r/  r5  r6  r3  r2  rW   rX   download_content`  s6    
"
zAInfoExtractor.__create_download_methods.<locals>.download_contentc                 S   s&   |d|  | _ | _d| d| _d S )NzInfoExtractor.z
                @param transform_source     Apply this transformation before parsing
                @returns                    zg

                See _download_webpage_handle docstring for other arguments specification
            )r   __qualname____doc__)funcnamereturn_valuerW   rW   rX   r     s    z<InfoExtractor.__create_download_methods.<locals>.impersonateZ
_download__handle(z, URL handle)rW   )r>  r2  r   r   r?  r:  r   rW   r9  rX   Z__create_download_methodsJ  s2                "	z'InfoExtractor.__create_download_methodsr  r#  zDownloading XMLzUnable to download XMLz'xml as an xml.etree.ElementTree.Elementr%  r)  zDownloading JSON metadataz Unable to download JSON metadatazJSON object as a dictZsocket_jsonr0  zPolling socketzUnable to poll socketwebpagezdata of the page as a stringr   c              
   O   sl   d}
z| j ||||d|f||	W S  tk
rd } z$|
d7 }
|
|krH|| || W 5 d}~X Y qX qdS )z
        Return the data of the page as a string.

        Keyword arguments:
        tries -- number of tries
        timeout -- sleep interval between tries

        See _download_webpage_handle docstring for other arguments specification.
        r   Nr   ) _InfoExtractor__download_webpager   _sleep)rT   r   r   r   r   r   triestimeoutr.  r/  Z	try_countr   rW   rW   rX   _download_webpage  s    zInfoExtractor._download_webpager   c                O   sd   t |d d}d| j d| | }|rLd| | jkr:d S | jd|  | jj|f|| d S )N%s: [] z	WARNING: )r+   r   r]   addr   r   )rT   r   r   r   r.  r/  ZidstrrW   rW   rX   r     s    zInfoExtractor.report_warningc                 O   s&   | j jd| j d| f|| dS )z2Print msg to screen, prefixing it with '[ie_name]'rI  rJ  N)r   r   r   rT   r   r.  r/  rW   rW   rX   r     s    zInfoExtractor.to_screenc                 O   s&   | j jd| j d| f|| d S )NrI  rJ  )r   r   r   rL  rW   rW   rX   r     s    zInfoExtractor.write_debugc                 O   s"   | j r| j jj||f||S |S rc   )r   paramsr   )rT   r>  r   r.  r/  rW   rW   rX   r     s    zInfoExtractor.get_paramc                 C   s(   |t k	r| jd | jdd|d d S )Nz?InfoExtractor.report_drm no longer accepts the argument partialzThis video is DRM protectedTr   r   )r   r   r#   raise_no_formats)rT   r   partialrW   rW   rX   
report_drm  s    zInfoExtractor.report_drmc                 C   s   |  | d dS )zReport information extraction.z: Extracting informationNr   )rT   Z
id_or_namerW   rW   rX   report_extraction  s    zInfoExtractor.report_extractionc                 C   s   |  | d dS )zReport webpage download.z: Downloading webpageNrR  rT   r   rW   rW   rX   r     s    z%InfoExtractor.report_download_webpagec                 C   s   |  d dS )zReport attempt to confirm age.zConfirming ageNrR  r   rW   rW   rX   report_age_confirmation  s    z%InfoExtractor.report_age_confirmationc                 C   s   |  d dS )zReport attempt to log in.z
Logging inNrR  r   rW   rW   rX   report_login  s    zInfoExtractor.report_loginz1This video is only available for registered usersc                 C   sL   |r&|  ds|  dr&| | d S |t| |d d7 }t|ddd S )Nignore_no_formats_errorwait_for_videoz. %sTr   )r   r   r+   rY   r   )rT   r   metadata_availablerU   rW   rW   rX   raise_login_required  s    
z"InfoExtractor.raise_login_requiredEThis video is not available from your location due to geo restrictionc                 C   s4   |r$|  ds|  dr$| | nt||dd S )NrW  rX  )r   )r   r   r   )rT   r   r   rY  rW   rW   rX   raise_geo_restricted  s    z"InfoExtractor.raise_geo_restrictedc                 C   sH   |r&|  ds|  dr&| || nt|tr6|nt|||dd S )NrW  rX  rN  )r   r   r   r   )rT   r   r   r   rW   rW   rX   rO    s    
zInfoExtractor.raise_no_formats)url_transparentc                K   sX   |dk	r"t |tr|n| |d< |dk	r2||d< |dk	rB||d< ||rLdnd| dS )z<Returns a URL that points to a page that should be processedNr   rv   titler]  rh   _typerh   )r   r   r   )rh   r   r   Zvideo_titler]  r/  rW   rW   rX   
url_result  s    
zInfoExtractor.url_resultc                    s2    j  fddtt||ddD ||f|S )Nc                 3   s"   | ]} j |fpi V  qd S rc   )ra  )re   r   rs   r   video_kwargsrW   rX   ri     s     z6InfoExtractor.playlist_from_matches.<locals>.<genexpr>TZlazy)playlist_resultr1   rm   )rs   matchesplaylist_idplaylist_titlegetterr   rc  r/  rW   rb  rX   playlist_from_matches  s    " z#InfoExtractor.playlist_from_matches)multi_videoc                K   s>   |r||d< |r||d< |dk	r(||d< ||r2dnd| dS )zReturns a playlistrv   r^  Ndescriptionrk  playlist)r`  entriesrW   )rn  rg  rh  Zplaylist_descriptionrk  r/  rW   rW   rX   re    s    
zInfoExtractor.playlist_resultr   c           
         s   |dkrd n@t |ttjfr.t||| n |D ]}t|||  r2 qNq2| j|| jjj}	 r|dkrt	dd  
 D S t |ttfrt fdd|D S  |S n:|tk	r|S |rtd|	 n| d|	 t   dS dS )a#  
        Perform a regex search on the given string, using a single or a list of
        patterns returning the first matching group.
        In case of failure return a default value or raise a WARNING or a
        RegexNotFoundError, depending on fatal, specifying the field name.
        Nc                 s   s   | ]}|d k	r|V  qd S rc   rW   re   grW   rW   rX   ri   9  s      z.InfoExtractor._search_regex.<locals>.<genexpr>c                 3   s   | ]}  |V  qd S rc   rw   ro  mobjrW   rX   ri   ;  s     Unable to extract zunable to extract )r   r   rn   Patternr   r   _format_errStylesEMPHASISrp   groupsr   rl   rw   r   r   r   r    )
rT   patternstringr>  r   r   flagsrw   p_namerW   rr  rX   _search_regex#  s*    zInfoExtractor._search_regexrN   z	{(?s:.+)})end_patterncontains_patternr   r   c             
   K   s   |t kri d }}
nd\}}
| jd| d| d| d||d||
rFdnt d	}|sV|S | j|| jjj}z| j||fd
di|	W S  tk
r } z@|rtd| d|j|dn|
s| j	d| d| |d W 5 d}~X Y nX |S )z>Searches string for the JSON object specified by start_patternF)FTz(?:z)\s*(?P<json>z)\s*(?:)r%  N)rw   r   r   Zignore_extraTrt  z - Failed to parse JSONr   z - Failed to parse JSON: r   )
r   r  r   rv  rw  rx  r)  r   r   r   )rT   Zstart_patternr{  r>  r   r  r  r   r   r/  Zhas_defaultr(  r~  r   rW   rW   rX   _search_jsonF  s:        

   zInfoExtractor._search_jsonc           	   	   C   s6   |  |||||||}t|tr.ttt|S t|S )zR
        Like _search_regex, but strips HTML tags and unescapes entities.
        )r  r   rl   rm   r"   )	rT   rz  r{  r>  r   r   r|  rw   r5  rW   rW   rX   r   a  s    
z InfoExtractor._html_search_regexc                 C   s   |p| j }| d}|rt|d|}| d|  tj|ddtjd\}}}|dkrdtd| t	|
|}nN| dd	rt| d
pd}tj|rtj|d}t|
|}ndS |s| d|  dS | d| d |d |d fS )NZ	netrc_cmd{}zExecuting command: T)textshellstdoutr   zCommand returned error code ZusenetrcFZnetrc_location~z.netrcNNzNo authenticators for zUsing netrc for z authenticationr   )rR   r   r   r   r   run
subprocessPIPEr8  r0   authenticatorsr   r
  r  isdirr   rV   r   )rT   netrc_machinecmdr  r   retinfoZ
netrc_filerW   rW   rX   _get_netrc_login_infoj  s(    

z#InfoExtractor._get_netrc_login_infor   rP   c              
   C   sx   |  |}|dk	r|  |}nRz| |\}}W n> ttjfk
rn } z| d|  W Y dS d}~X Y nX ||fS )a  
        Get the login info as (username, password)
        First look for the manually specified credentials using username_option
        and password_option as keys in params dictionary. If no such credentials
        are available try the netrc_cmd if it is defined or look in the
        netrc file using the netrc_machine or _NETRC_MACHINE value.
        If there's no info available, return (None, None)
        NzFailed to parse .netrc: r  )r   r  r8  rV   NetrcParseErrorr   )rT   Zusername_optionZpassword_optionr  r   rP   r   rW   rW   rX   r     s    

zInfoExtractor._get_login_infotwo-factor verification codec                 C   s(   |  d}|dk	r|S td| dS )z
        Get the two-factor authentication info
        TODO - asking the user will be required for sms/phone verify
        currently just uses the command line option
        If there's no info available, return None
        Z	twofactorNzType z and press [Return]: )r   getpass)rT   r   ZtfarW   rW   rX   _get_tfa_info  s    
zInfoExtractor._get_tfa_infoc                 C   s4   d}dj t| dd}d}|||f |||f gS )NzBcontent=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?)(?=\s|/?>))zJ(?:name|property)=(?:\'og{sep}{prop}\'|"og{sep}{prop}"|\s*og{sep}{prop}\b)z(?:&#x3A;|[:-]))propsepz<meta[^>]+?%s[^>]+?%s)r   rn   escape)r  Z
content_reZproperty_retemplaterW   rW   rX   _og_regexes  s     

zInfoExtractor._og_regexesc                 C   s   dt |  dS )NzY(?isx)<meta
                    (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)z?\1)
                    [^>]+?content=(["\'])(?P<content>.*?)\2)rn   r  )r  rW   rW   rX   _meta_regex  s    zInfoExtractor._meta_regexc                 K   sl   t |}|d krd|d  }g }|D ]}|| | q&| j|||fdtji|}|d krdd S t|S )Nz
OpenGraph r   r|  )rI   extendr  r  rn   DOTALLrB   )rT   r  htmlr>  kargsZ
og_regexesr}  escapedrW   rW   rX   _og_search_property  s    z!InfoExtractor._og_search_propertyc                 K   s   | j d|dfddi|S )Nimagezthumbnail URLr   Fr  rT   r  r  rW   rW   rX   _og_search_thumbnail  s    z"InfoExtractor._og_search_thumbnailc                 K   s   | j d|fddi|S )Nrl  r   Fr  r  rW   rW   rX   _og_search_description  s    z$InfoExtractor._og_search_descriptionr   c                K   s   | j d|fd|i|S )Nr^  r   r  )rT   r  r   r  rW   rW   rX   _og_search_title  s    zInfoExtractor._og_search_title	video urlc                 K   s8   |  d|  d }|r&|  d| }| j|||f|S )Nvideoz	video:urlzvideo:secure_url)r  r   )rT   r  r>  securer  ZregexesrW   rW   rX   _og_search_video_url  s    z"InfoExtractor._og_search_video_urlc                 K   s   | j d|f|S Nrh   r  r  rW   rW   rX   _og_search_url  s    zInfoExtractor._og_search_urlr^  c                K   s   | j d||fd|i|S )Nz!(?s)<title\b[^>]*>([^<]+)</title>r   )r   )rT   r  r>  r   r/  rW   rW   rX   _html_extract_title  s    z!InfoExtractor._html_extract_titlec                    sB   t |}|d kr|d } j fdd|D ||f|dd|S )Nr   c                    s   g | ]}  |qS rW   )r  )re   nr   rW   rX   r     s     z3InfoExtractor._html_search_meta.<locals>.<listcomp>r   )r   rw   )rI   r   )rT   r>  r  Zdisplay_namer   r/  rW   r   rX   _html_search_meta  s      zInfoExtractor._html_search_metac                 C   s   |  d|dS )Nz
dc.creatoruploaderr  rT   r  rW   rW   rX   _dc_search_uploader  s    z!InfoExtractor._dc_search_uploaderc              	   C   sT   t d| rdS dddg}d}|D ],}t || }|r"t|tt|ddd}q"|S )	NzG(?ix)<meta\s+name="rating"\s+     content="RTA-5042-1996-1400-1577-RTA"   zYProudly Labeled <a href="http://www\.rtalabel\.org/" title="Restricted to Adults">RTA</a>z6>[^<]*you acknowledge you are at least (\d+) years oldu2   >\s*(?:18\s+U(?:\.S\.C\.|SC)\s+)?(?:§+\s*)?2257\br   r   r   )rn   r   maxintr>   )r  ZAGE_LIMIT_MARKERS	age_limitmarkerrs  rW   rW   rX   _rta_search  s    zInfoExtractor._rta_searchc                 C   s2   |  d|}|sd S dddddd}|| S )Nratingr               )zsafe for kidsZgeneralz14 yearsZmaturer  r  r   lower)rT   r  r  RATING_TABLErW   rW   rX   _media_rating_search  s    z"InfoExtractor._media_rating_searchc                 C   s4   | j d|d d}|sd S ddddd}|| S )NZisFamilyFriendlyr   r   r  )1true0falser  )rT   r  Zfamily_friendlyr  rW   rW   rX   _family_friendly_search  s      z%InfoExtractor._family_friendly_searchc                 C   s   |  d|dS )Nztwitter:playerztwitter card playerr  r  rW   rW   rX   _twitter_search_player  s    z$InfoExtractor._twitter_search_playerr   r   c                c   sV   |t k	rd}tt|D ]8}| j|d||d}t|D ]}t|tr:|V  q:qdS )z%Yield all json ld objects in the htmlFjson_ldr  N)	r   rn   finditerr   r)  rw   rI   r   dict)rT   r  r   r   r   rs  Zjson_ld_itemr  rW   rW   rX   _yield_json_ld   s    
zInfoExtractor._yield_json_ldc                C   sl   |t k	rd}| jt| j||||d|||d}|r8|S |t k	rD|S |rRtdn| dt   i S dS )z-Search for a video in any json ld in the htmlFr  )r   expected_typezUnable to extract JSON-LDzunable to extract JSON-LD N)r   _json_ldr   r  r   r   r    )rT   r  r   r  r   r   r  rW   rW   rX   _search_json_ld*  s       
zInfoExtractor._search_json_ldc              	      s   t |trj|||d}|s"i S i ddddddddd dd d	d
  fddfddfddd	fdd			| tS )Nr  commentlikeZdislikeview)ZCommentActionZAgreeActionZDisagreeActionZ
LikeActionZDislikeActionZListenActionZWatchActionZ
ViewActionc                    s$   t t| d t fdd|D S )N@typec                 3   s   | ]}| kV  qd S rc   rW   re   xtype_rW   rX   ri   O  s     z:InfoExtractor._json_ld.<locals>.is_type.<locals>.<genexpr>)rI   r>   rO   )r   Zexpected_typesrW   r  rX   is_typeM  s    z'InfoExtractor._json_ld.<locals>.is_typec                 S   s&   |  d}t|tr| d}t|S )NZinteractionTyper  )r   r   r  r;   )r   interaction_typerW   rW   rX   extract_interaction_typeQ  s    


z8InfoExtractor._json_ld.<locals>.extract_interaction_typec                    s   |  d}t|tr|g}t|ts(d S |D ]r}|ds<q,|}|sJq,t| d}|d krbq,  |dd }|s|q,| d} |d k	rq,||< q,d S )NZinteractionStatisticZInteractionCounterZuserInteractionCount/_count)r   r   r  r   r<   split)r   Zinteraction_statisticZis_er  Zinteraction_countZ
count_kindZ	count_key)INTERACTION_TYPE_MAPr  r  r  rW   rX   extract_interaction_statisticW  s*    




z=InfoExtractor._json_ld.<locals>.extract_interaction_statisticc                    s   dd t | dpg D }ttddif|||dd  D ]Z\}\}}}|d pZ|d |d< |d pn|d |d< d | kr>d| d	  d S q>|r|d
 d p d |d
 d< | d< d S )Nc                 S   s8   g | ]0}| d dkr| d| d| ddqS )r  ZClipr>  startOffsetZ	endOffset)r^  
start_timeend_timer   )re   partrW   rW   rX   r   r  s    zOInfoExtractor._json_ld.<locals>.extract_chapter_information.<locals>.<listcomp>ZhasPartr  r   r   r  zChapter z. contains broken data. Not extracting chaptersr  durationchapters)rI   r   	enumeratezipvaluesr   )r   r  idxZlast_cZ	current_cZnext_c)r  rT   rW   rX   extract_chapter_informationq  s       
z;InfoExtractor._json_ld.<locals>.extract_chapter_informationc                    s.    d}t  dt  dt  dt  ddd tt dd	D t  d
t  dt	|t
r| dnt	|tr|nd t dtdtt  dt  dt  dt  dt  dt fddd  drdt  dd     d S )NauthorZ
contentUrlZencodingFormatr>  rl  c                 S   s    g | ]}t |rd t|iqS rg   )rF   rB   )re   rh   rW   rW   rX   r     s   zHInfoExtractor._json_ld.<locals>.extract_video_object.<locals>.<listcomp>ZthumbnailUrlZthumbnailURLr  Z
uploadDate)ZbyArtistr>  r  ZcontentSizebitratewidthheightZinteractionCountc                      s     ddS )Nkeywords,)r   r  rW   r   rW   rX   <lambda>      zFInfoExtractor._json_ld.<locals>.extract_video_object.<locals>.<lambda>)rh   extr^  rl  
thumbnailsr  	timestampr  Zartistfilesizetbrr  r  Z
view_counttagsAudioObjectnone)vcodecabr)r   r   rF   r/   rB   rI   r>   r4   rD   r   r  r   r,   r*   r@   )r   r  )r  r  r  r  r  rX   extract_video_object  s6    
$z4InfoExtractor._json_ld.<locals>.extract_video_objectTc              
      s  t | D ]}t|tsq|r(d|kr(q|rRt| ddhkrR|d dd q d k	rf| sfqt|dtd}|d k	r|d< |dd	d
rXt|d}	|t
|dt|dd ds|r|d< |d}|dddr	t|dt
|dd |dp0|d}|dddr^t|dd< n|dr	t|dt|dt|dt|dd n|d d!r4	t|d"t|d#t|d$p|dd% t|d&d'r|d( d)  n"t|d*d'r^|d+ d)  n*|d'd,r^|  d krXqn q|d(}|d'r||  d krqq qqd S )-Nz@contextz@graphF)at_top_level)ZaggregateRatingZratingValuer  Zaverage_ratingZ	TVEpisodeZEpisodeZPodcastEpisoder>  ZepisodeNumberrl  )episodeepisode_numberrl  r^  ZpartOfSeasonZTVSeasonZSeasonZCreativeWorkSeasonZseasonNumber)seasonseason_numberZpartOfSeriesZpartOfTVSeriesZTVSeriesZSeriesZCreativeWorkSeriesZseriesZMovier  ZdateCreated)r^  rl  r  r  ZArticleZNewsArticleZdatePublishedZheadlineZarticleBody)r  r^  rl  )r  r   ZVideoObjectr  r   )	subjectOfr   r  r  )rI   r   r  r\   keysr>   r*   rB   r   r   r,   r4   rD   r5   )r  r  r   r  Zepisode_nameZpart_of_seasonZpart_of_seriesr  )r  r  r  r  traverse_json_ldrW   rX   r    sv    





z0InfoExtractor._json_ld.<locals>.traverse_json_ld)T)r   r   r)  r(   )rT   r  r   r   r  rW   )
r  r  r  r  r  r  r  r  rT   r  rX   r  ;  s,    
!?zInfoExtractor._json_ldc                K   sD   |dkr| j d i }|tk	r$d}| jd|d|fd||d|S )Nr  z<using `default='{}'` is deprecated, use `default={}` insteadFz,<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>znext.js dataz	</script>)r  r   r   )r   r#   r   r  )rT   rB  r   r   r   kwrW   rW   rX   _search_nextjs_data  s"        z!InfoExtractor._search_nextjs_data__NUXT__)r   r   )r   traversec                C   s   t |}d}| jd| d| d| d| f||d|r>tndd\}}	}
|d	krXi S tt|	d
ttj	| j
d|
 d|t|dpd}| j
||tjt|d|d}t||pi S )z_Parses Nuxt.js metadata. This works as long as the function __NUXT__ invokes is a pure functionzY\(function\((?P<arg_keys>.*?)\){.*?\breturn\s+(?P<js>{.*?})\s*;?\s*}\((?P<arg_vals>.*?)\)z<script>\s*window\.=z\s*\)\s*;?\s*</script>z\(.*?)jsarg_keysarg_vals)NNN)rw   r   Nr  rI  ])r!  r   rW   )vars)rn   r  r  r   r  r  r  rm   r%  dumpsr)  r.   	functoolsrP  r>   )rT   rB  r   Zcontext_namer   r  ZrectxZFUNCTION_REr  r  r  r.  r  rW   rW   rX   _search_nuxt_data  s*    
  

   zInfoExtractor._search_nuxt_datac                 C   sx   t dd| } i }t d| D ]T}t|}|s0q|ddkr@q|dpR|d}|d}|r|d k	r|||< q|S )	Nz<!--(?:(?!<!--).)*-->rN   z(?i)(<input[^>]+>)type)hiddenZsubmitr>  rv   value)rn   subfindallr'   r   )r  Zhidden_inputsZinput_elattrsr>  r  rW   rW   rX   _hidden_inputs  s    

zInfoExtractor._hidden_inputsc                 C   s*   | j d| d|| ddd}| |S )Nz(?is)<form[^>]+?id=(["\'])z\1[^>]*>(?P<form>.+?)</form>z formformrq  )r  r#  )rT   Zform_idr  r$  rW   rW   rX   _form_hidden_inputs  s    
  z!InfoExtractor._form_hidden_inputs)r   c                 C   s   G dd dt }td |S )Nc                       s   e Zd Z fddZ  ZS )z,InfoExtractor.FormatSort.<locals>.FormatSortc                    s   t  j| jf|| d S rc   )superra   r   )r   r.  r/  	__class__rW   rX   ra     s    z5InfoExtractor.FormatSort.<locals>.FormatSort.__init__)r   
__module__r;  ra   __classcell__rW   rW   r'  rX   
FormatSort  s   r+  zuyt_dlp.InfoExtractor.FormatSort is deprecated and may be removed in the future. Use yt_dlp.utils.FormatSorter instead)r   r#   )rs   r+  rW   rW   rX   r+    s
    zInfoExtractor.FormatSortc                 C   s4   |s| j d d S | j d |r0||d d< d S )NzJyt_dlp.InfoExtractor._sort_formats is deprecated and is no longer requiredzyt_dlp.InfoExtractor._sort_formats is deprecated and no longer works as expected. Return _format_sort_fields in the info_dict insteadr   Z__sort_fieldsr   r#   )rT   formatsZfield_preferencerW   rW   rX   _sort_formats"  s    zInfoExtractor._sort_formatsc                    s$   |r t  fdd||d d < d S )Nc                    s.    j | d | dr&d| dnddS )Nrh   	format_idz{} video formatr  )item)_is_valid_urlr   r   )frT  rW   rX   r  0  s    z.InfoExtractor._check_formats.<locals>.<lambda>)rq   )rT   r-  r   rW   rT  rX   _check_formats-  s
    zInfoExtractor._check_formatsc                 C   sH   t  }g }| D ](}|d |kr||d  || q|| d d < d S r  )r\   rK  append)r-  Zformat_urlsZunique_formatsr2  rW   rW   rX   _remove_duplicate_formats5  s    z'InfoExtractor._remove_duplicate_formatsr  c              
   C   s   | j |dd}|dsdS z | j||d| d|d W dS  tk
r } z&| | d| d	|j W Y d
S d }~X Y nX d S )Nhttp:schemezhttp://zhttps://Tz	Checking z URL)r   r   z URL is invalid, skipping: F)_proto_relative_urlr   r   r   r   r   )rT   rh   r   r0  r   r   rW   rW   rX   r1  ?  s    
zInfoExtractor._is_valid_urlc                 C   s   |  ddrdS dS )zA Either "http:" or "https:", depending on the user's preferences Zprefer_insecureFr6  zhttps:r   r   rW   rW   rX   http_schemeL  s    
zInfoExtractor.http_schemec                 C   s.   |p
|   }|dstt||d d dS )N:r  r7  )r<  endswithr   r9   )rT   rh   r8  rW   rW   rX   r:  S  s    z!InfoExtractor._proto_relative_urlc                 C   s2   |d krd}|||d }|  | t| d S )Nz-%(video_id)s: Waiting for %(timeout)s seconds)r   rF  )r   r   r   )rT   rF  r   Zmsg_templater   rW   rW   rX   rD  X  s
    
zInfoExtractor._sleepc                 C   s   t |  S rc   r)   stripsrW   rW   rX   r  `  r  zInfoExtractor.<lambda>c                 C   s`   |  drd}| j||dd|||	|
|d	}|dkr6g S |\}}|j}| j|||||||||d	S )NrW  FzDownloading f4m manifestzUnable to download f4m manifest)r!  r   r   r   r   )
preferencequalityf4m_idr!  r   m3u8_id)r   _download_xml_handlerh   _parse_f4m_formats)rT   manifest_urlr   rC  rD  rE  r!  r   rF  r   r   r   r5  manifestr   rW   rW   rX   _extract_f4m_formats_  s8    
            z"InfoExtractor._extract_f4m_formatsc                 C   s   t |  S rc   r?  rA  rW   rW   rX   r  w  r  c
                 C   s  t |tjjjs|sg S |d}
|
d k	rTd|
jkrT|
jdd }| dkrTg S g }d}|	d}|sxd}|	d}t
|}|s|S t|}t|d	d
gdd d}d }t|ddgdd d}|r|drd}t|D ]\}}t|jd}t|jd}t|jd}t||p|}|d krZd }|dkrD|jd}|d krZ|jd}|sbq|drr|n$|pd|dd d d | }t|}|dkr0| j|||||||d}t|dkr"|d }||dp||dp||dp||s|dn||d || qn*|d krZ|| j||d!|||	|d" q|||||d k	rrd#nd d||||||d$ q|S )%Nz#{http://ns.adobe.com/f4m/1.0}pv-2.0;r   rN   z1.0z"{http://ns.adobe.com/f4m/1.0}mediaz2.0z"{http://ns.adobe.com/f4m/2.0}mediaz*{http://ns.adobe.com/f4m/1.0}bootstrapInfoz*{http://ns.adobe.com/f4m/2.0}bootstrapInfozbootstrap infor   z%{http://ns.adobe.com/f4m/1.0}mimeTypez%{http://ns.adobe.com/f4m/2.0}mimeTypezbase URLzaudio/r  r  r  r  hrefrh   r9  r  r  f4m)rC  rD  rE  r!  r   r   r  r/  )r  r  r  r/  r  m3u8mp4)rC  rD  rF  r   flv)r/  rh   rI  r  protocolr  r  r  r  rC  rD  )r   r  r  r  Elementr,  r  r  r@  r!  r	   r   rJ   rK   r   r  r,   attribr   r-   r   r$   rK  r  r   r  _extract_m3u8_formatsr4  )rT   rJ  rI  r   rC  rD  rE  r!  r   rF  Z	akamai_pvZplayer_verification_challenger-  Zmanifest_versionZmedia_nodesZmanifest_base_urlZbootstrap_infor  	mime_typeiZmedia_elr  r  r  r/  	media_urlr  f4m_formatsr2  rW   rW   rX   rH  v  s    


    


$
     

     
z InfoExtractor._parse_f4m_formatsc              	   C   s(   t |d||d|r|d nd|dddS )NmetarO  r   imultiplezQuality selection URL)r/  rh   r  rR  rC  rD  
resolutionformat_note)r-   )rT   m3u8_urlr  rC  rD  rF  rW   rW   rX   _m3u8_meta_format  s    zInfoExtractor._m3u8_meta_formatc                 C   s   | j td| ddd d S )Nz&Ignoring subtitle tracks found in the z. manifest; if any subtitle tracks are missing,Tr   )r   r    rT   r>  rW   rW   rX   _report_ignoring_subs  s
    
z#InfoExtractor._report_ignoring_subsc                 O   s"   | j ||\}}|r| d |S )NZHLS)#_extract_m3u8_formats_and_subtitlesra  rT   r.  r/  ZfmtssubsrW   rW   rX   rU    s    
z#InfoExtractor._extract_m3u8_formatsm3u8_nativec                 C   s   |  drd}
|sN|	dk	rF|	p d}	|
r2t|	|d| |	 t   g i fS | j|||d krbdn||	d krpdn|	|
|||d}|dkrg i fS |\}}|j}| j|||||||||	|
|||||dS )	NrW  FzFailed to obtain m3u8 URLr  zDownloading m3u8 informationz#Failed to download m3u8 informationr   r   r   r   r   r   )r  entry_protocolrC  rD  rF  r   r   r   liver   r   r   r   )r   r   r   r    r   rh   !_parse_m3u8_formats_and_subtitles)rT   r^  r   r  rg  rC  rD  rF  r   r   r   rh  r   r   r   r5  m3u8_docr   rW   rW   rX   rb    sP    
               z1InfoExtractor._extract_m3u8_formats_and_subtitlesc           #         sJ  g i  t fddddrDd6	fdd	 ndd  dkrfd	d
 dD fS i i 
 fdd}
fdd} D ]}|dr|| q D ]\}|d rt|
q|ds| sqqt
dp,
ddd}| } |D ]}d |g}|s| }|pzd|pxt	 |d< t
| |||t
dd}
d }r|dd |d< 
d}|rtd |}|rt|d!|d!< t|d"|d"< td#|d$ }|rZ| \}}t|dt|d }}|||d% t
d&}|| 
d'}|r|r|d(d)kr|} | r| d d*rd)|d+< |d,s|d(d)krd-nd.|d,< | 
d/}!|!rH| }"|"d0= |"|d1 d2d3d4|!d5 |" qHi 
qfS )7Nc                    s   t d| r| S tj | S )N	https?://)rn   rd   r   r3  rH   rg   )r^  rW   rX   
format_url  s    zCInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>.format_urlZhls_split_discontinuityFc              	      sN   |s0| sg S j |  ddd}|dkr0g S tdtdd | D  S )NFz,Failed to download m3u8 playlist information)r   r   r   r   r   r   c                 s   s   | ]}| d V  qdS )z#EXT-X-DISCONTINUITYNr   re   linerW   rW   rX   ri   ,  s     zjInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>._extract_m3u8_playlist_indices.<locals>.<genexpr>)rG  r   sum
splitlines)rI  rj  )r   r   r   rT   r   rW   rX   _extract_m3u8_playlist_indices#  s         zWInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>._extract_m3u8_playlist_indicesc                  _   s   d gS rc   rW   )r.  r/  rW   rW   rX   rr  /  s    z#EXT-X-TARGETDURATIONc                    s6   g | ].}t ||p"t d  dqS )zapplication/x-mpegurl)r/  format_indexrh   r  rR  rC  rD  has_drm)r-   r&   r	  re   r  )rg  r  rt  rj  rF  r^  rC  rD  rW   rX   r   C  s   	zCInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>.<listcomp>)rj  c                    s  t | ddd   r6 r6s:d S 
 g  dkrdsbd S d }|t|d}|d dkrd	|d< d
|d< dpd}|g | dkrd S d}|r|	 fddD  d S )NZTYPEzGROUP-IDNAMEZ	SUBTITLESURIrh   r  r  rO  Zvttre  rR  LANGUAGEund)VIDEOAUDIOc                 3   sH   | ]@}t 	|	|d  
dkr8dnddV  qdS )ry  r|  r  N)r/  r]  rs  rh   rI  languager  rR  rC  rD  rt  r  )r-   r   ru  )rg  r  group_idrt  rF  r^  rI  media
media_typer>  rC  rD  rW   rX   ri   t  s   zYInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>.extract_media.<locals>.<genexpr>)r6   r   r   r4  r$   r  )Zx_media_linerh   sub_infor   rX  )rr  rg  r  rl  r-  ry  rt  rF  r^  rC  rD  r   )r~  rI  r  r  r>  rX   extract_mediaS  s2    "

$zFInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>.extract_mediac                     sL    d} | r| S  d}|s$d S   |}|s6|S |d }| dpJ|S )Nrv  r{  r   r  )stream_nameZstream_group_idZstream_groupZ	rendition)ry  last_stream_infrW   rX   build_stream_name  s    


zJInfoExtractor._parse_m3u8_formats_and_subtitles.<locals>.build_stream_namez#EXT-X-MEDIA:z#EXT-X-STREAM-INF:r   zAVERAGE-BANDWIDTH	BANDWIDTH  Zscalez%dr   z
FRAME-RATE)r/  rs  rh   rI  r  r  fpsrR  rC  rD  rt  zYT-EXT-AUDIO-CONTENT-ID.r   r}  Z
RESOLUTIONz!(?P<width>\d+)[xX](?P<height>\d+)r  r  z2audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?rh   )vbrr  ZCODECSr|  r  r  rw  acodecr  Zm4arP  zPROGRESSIVE-URIrI  r/  hls-zhttp-http)r/  rR  rh   )NN)r
   Z_has_drmr   rq  r   r6   r@  r*   r   r  r-   r  rn   r   r  rw   ry  r   r3   r4  r   r   )#rT   rj  r^  r  rg  rC  rD  rF  rh  r   r   r   r   r   r   r   r  r  ro  r  rI  r  r/  r  r2  Zyt_audio_content_idr\  rs  r  r  codecsZaudio_group_idZaudio_groupZprogressive_urihttp_frW   )rr  r   rg  r  r   rl  r-  ry  rt  r   r  rj  rF  r^  rC  rD  rT   r   r   rX   ri    s    

	"0


 

 





z/InfoExtractor._parse_m3u8_formats_and_subtitlesc           	   
   C   sB   | j |||d krdn||d kr"dn|d|||d}| |p<d|S )NzDownloading m3u8 VOD manifestFailed to download VOD manifestFrf  rN   )rG  _parse_m3u8_vod_duration)	rT   Zm3u8_vod_urlr   r   r   r   r   r   m3u8_vodrW   rW   rX   _extract_m3u8_vod_duration  s        z(InfoExtractor._extract_m3u8_vod_durationc                 C   s*   d|krd S t tdd | D p(d S )Nz#EXT-X-ENDLISTc                 s   s6   | ].}| d rt|td d dd V  qdS )z#EXTINF:Nr  r   )r   floatr  r  rn  rW   rW   rX   ri   	  s    
z9InfoExtractor._parse_m3u8_vod_duration.<locals>.<genexpr>)r  rp  rq  )rT   r  r   rW   rW   rX   r  	  s    

z&InfoExtractor._parse_m3u8_vod_durationc           	   
   C   sX   | j |||d krdn||d kr"dn|d|||d}t|tjjjsFd S tt|dS )NzDownloading MPD VOD manifestr  Frf  mediaPresentationDuration)	_download_xmlr   r  r  r  rS  r,   r4   r   )	rT   mpd_urlr   r   r   r   r   r   mpd_docrW   rW   rX   _extract_mpd_vod_duration
	  s        z'InfoExtractor._extract_mpd_vod_durationc                 C   sT   |s| S g }|  dD ]2}|r&|dkr2|| q|d| d|  qd|S )Nr  r  r*  r+  )r  r4  r   )r  	namespaceoutcrW   rW   rX   	_xpath_ns	  s    zInfoExtractor._xpath_nsc           	      C   s\   |  drd}| j||||d}|dkr8|r0tg i fS |\}}| j||j||| |dS )NrW  Fr   r!  )
f4m_paramsr  )r   _download_smilr   !_parse_smil_formats_and_subtitlesrh   _parse_smil_namespace)	rT   smil_urlr   r   r  r!  r5  smilr   rW   rW   rX   #_extract_smil_formats_and_subtitles"	  s    
z1InfoExtractor._extract_smil_formats_and_subtitlesc                 O   s"   | j ||\}}|r| d |S NZSMIL)r  ra  rc  rW   rW   rX   _extract_smil_formats/	  s    
z#InfoExtractor._extract_smil_formatsc                 C   s<   | j |||d}|dkri S |\}}|j}| j||||dS )Nr  F)r  )r  rh   _parse_smil)rT   r  r   r   r  r5  r  r   rW   rW   rX   _extract_smil_info5	  s    z InfoExtractor._extract_smil_infoc                 C   s   | j ||dd||dS )NzDownloading SMIL filezUnable to download SMIL filer  )rG  )rT   r  r   r   r!  rW   rW   rX   r  ?	  s        zInfoExtractor._download_smilc                 C   s   |  |}| j|||||d\}}tjt|d }d }d }	d }
|| d|D ]^}|j	d}|j	d}|rT|szqT|s|dkr|}qT|	s|dkr|}	qT|
sT|dkrTt
|}
qTd	d
 || d|D }||p||	|
|||dS )N)r  r  r   ./head/metar>  r   r^  )rl  Zabstractdatec              	   S   sD   g | ]<}| d r| d| d t| dt| ddqS )srcr  r  r  )rv   rh   r  r  )r   r,   )re   r  rW   rW   rX   r   Z	  s    
z-InfoExtractor._parse_smil.<locals>.<listcomp>z.//image)rv   r^  rl  upload_dater  r-  r   )r  r  r
  r  splitextrE   r!  r  rT  r   rC   )rT   r  r  r   r  r  r-  r   r^  rl  r  rZ  r>  r   r  rW   rW   rX   r  D	  sD    
    

zInfoExtractor._parse_smilc                 C   s   | j d|jdd dS )Nz(?i)^{([^}]+)?}smil$r  r   )r  tag)rT   r  rW   rW   rX   r  k	  s       z#InfoExtractor._parse_smil_namespacec                 O   s"   | j ||\}}|r| d |S r  )r  ra  rc  rW   rW   rX   _parse_smil_formatso	  s    
z!InfoExtractor._parse_smil_formatsc           %         sF  |} d D ]$}|dp,|d}	|	r|	} q<qg i  }
}d}d}d}d}t }tj fdddD }|D ]}|d}|r~||krq~|| t|d	p|d
d}t	|dp|d}t	|d}t	|d}|d}|d}t
|d dp4|p4tjt||ddd}|dpD|}|dks\|dr|d7 }|
||dd|d kr~|n| ||||d |r~|||\}}|
d ||d q~|dr|ntj| d|}| }|d ks|d krrj|||p
d!d"dd#\}}j||d$ t|dkrf|d7 }|d d%|d krT|n| |||d& |
| q~|d'kr|}|sd(d)d*}|d+|krd,nd+7 }|tj|7 }|
j||d-dd. q~|d/kr
j||d0dd1\} }!|
|  j|!|d$ q~td2|rHj||d3dd4\}"}#|
|" j|#|d$ q~|dr~||r~|d7 }|
||pz|pzdd5|p| ||||d6 q~ d7 D ]v}|d}|r||kr̐q|| |d7 }|
d8| |t |d9d:d:t	|dt	|dd;d< qj! d=}$j|$|d$ |
|fS )>Nr  baseZhttpBaser   c                 3   s    | ]} | V  qd S rc   )r!  r  )re   argr  rT   r  rW   rX   ri   	  s   zBInfoExtractor._parse_smil_formats_and_subtitles.<locals>.<genexpr>)z.//videoz.//audioz.//mediar  zsystem-bitrateZsystemBitrater  sizeZfileSizer  r  protor  Zdefault_extzRequesting extension infoF)r   r   streamerrtmpr   rQ  zrtmp-%d)rh   	play_pathr  r/  r  r   r  r  r  rh   r  r  r  rO  rP  hlsrF  r   targetzhls-%d)r/  r  r  r  rN  z3.2.0zflowplayer-3.2.0.1)ZhdcoreZplugin?&hdsrE  r   mpddashmpd_idr   z\.ism/[Mm]anifestZmss)ism_idr   zhttp-%d)rh   r  r/  r  r   r  r  z.//imagestreamzimagestream-r  r  zSMIL storyboards)r/  rh   r  r  r  r  r  r]  )r  )"r!  r  r   r\   	itertoolschainfrom_iterablerK  r*   r,   r$   rG   r   r   r   r4  r   r   r3  rH   r@  rb  _merge_subtitlesr  r  	urlencoderK  "_extract_mpd_formats_and_subtitlesrn   r   "_extract_ism_formats_and_subtitlesr1  r/   _parse_smil_subtitles)%rT   r  r  r   r  r  Ztransform_rtmp_urlr  rZ  br-  r   Z
rtmp_countZ
http_countZ
m3u8_countZ
imgs_countZsrcsr  Zmediumr  r  r   r  r  r  r  Zsrc_extr  Zsrc_urlm3u8_formatsZ	m3u8_subsf4m_urlZmpd_formatsZmpd_subsZism_formatsZism_subsZ	smil_subsrW   r  rX   r  u	  s    






$    


   

   





z/InfoExtractor._parse_smil_formats_and_subtitlesenc           
      C   s   g }i }| | d|D ]}|d}|r||kr6q|| |dp^t|dp^t|}|dp|dp|dp|}	||	g ||d q|S )	Nz.//textstreamr  r  r  systemLanguageZsystemLanguageNamer   rx  )r!  r  r   r4  r/   r$   r   )
rT   r  r  Zsubtitles_langurlsr   Z
textstreamr  r  r   rW   rW   rX   r  	  s    

 "
z#InfoExtractor._parse_smil_subtitlesc                 C   sD   | j ||dd|d}|dkr g S |\}}|j}| j|||t|dS )NzDownloading xpsf playlistz Unable to download xspf manifestr  F)xspf_urlxspf_base_url)rG  rh   _parse_xspfr   )rT   r  rg  r   r5  xspfr   rW   rW   rX   _extract_xspf_playlist
  s"         z$InfoExtractor._extract_xspf_playlistc                 C   s   ddd}g }| td|D ]}t|td|d|d}t|td|d	}	t|td
|d}
tt|td|dd}g }| td|D ]X}t||j}|sq||||td|t|td|t|td|d q||||	|
||d q|S )Nzhttp://xspf.org/ns/0/z&http://static.streamone.nl/player/ns/0)r  s1z./xspf:trackList/xspf:trackz./xspf:titler^  r   z./xspf:annotationrl  z./xspf:image	thumbnailz./xspf:durationr  r  z./xspf:locationzs1:labelzs1:widthz	s1:height)rh   rI  r/  r  r  )rv   r^  rl  r  r  r-  )	r!  rL   rK   r*   rH   r  r4  r   r,   )rT   Zxspf_docrg  r  r  ZNS_MAPrn  trackr^  rl  r  r  r-  locationrl  rW   rW   rX   r  
  s\            

zInfoExtractor._parse_xspfc                 O   s"   | j ||\}}|r| d |S NZDASH)r  ra  rc  rW   rW   rX   _extract_mpd_formats9
  s    
z"InfoExtractor._extract_mpd_formatsc                 O   s   | j ||}| |S rc   )_extract_mpd_periods_merge_mpd_periodsrT   r.  r/  periodsrW   rW   rX   r  ?
  s    z0InfoExtractor._extract_mpd_formats_and_subtitlesc
              
   C   s~   |  drd}| j|||d kr"dn||d kr0dn|||||	d}
|
dkrLg S |
\}}|d kr`g S |j}t|}| ||||S )NrW  FzDownloading MPD manifestzFailed to download MPD manifestrf  )r   rG  rh   r   _parse_mpd_periods)rT   r  r   r  r   r   r   r   r   r   r5  r  r   mpd_base_urlrW   rW   rX   r  C
  s(    
    z"InfoExtractor._extract_mpd_periodsc                 O   s"   | j ||\}}|r| d |S r  ) _parse_mpd_formats_and_subtitlesra  rc  rW   rW   rX   _parse_mpd_formats[
  s    
z InfoExtractor._parse_mpd_formatsc                 O   s   | j ||}| |S rc   )r  r  r  rW   rW   rX   r  a
  s    z.InfoExtractor._parse_mpd_formats_and_subtitlesc           	      C   s   i i  }}|D ]}|d D ]f}d|ks.t dd|d< tdd | D }||kr^|||< qd|kr|| dg |d  q|r|d r| jtd	dd
 |d  D ]\}}||g | qqt| |fS )z
        Combine all formats and subtitles from an MPD manifest into a single list,
        by concatenate streams with similar formats.
        r-  Zis_dash_periodszformat already processedTc                 s   s   | ]\}}|d kr|V  qdS ))r/  	fragmentsmanifest_stream_numberNrW   )re   kvrW   rW   rX   ri   o
  s
      z3InfoExtractor._merge_mpd_periods.<locals>.<genexpr>r  r   z_Found subtitles in multiple periods in the DASH manifest; if part of the subtitles are missing,r   )	r   rl   itemsr   r  r   r    r   r  )	rT   r  r-  r   periodr2  Z
format_keyZsub_langr  rW   rW   rX   r  e
  s&    

z InfoExtractor._merge_mpd_periodsc           +      #   sz   dds"|ddkr"g i fS jd|jdddfd	d
  fdd} fdd}t|d}tt}t|	 dD ]\}	}
|
dd|	 g tt
d}t|
dp|}||
ddd}|
	 dD ]}|||}|	 dD ]j}|j }||j |d }|d|dd }|dd}|dkrXd |i}nt|}|d!kr|d"krz|}np|d#d$d$krd%}nX|d&d$d$krd'}n@|d d$d$krd(}n(t|d)krd(}nd*| d+ qd}|||
|fD ]H}| d,tfd-d.dk	rj| }td/|r qDq|rf|drftj||}n0|rtd/|s|ds|d7 }|| }|d|d0}| d,}t|dk	r|jd1nd}t|d2dk	r}n|}|r
|d3 | }|d4kr||t|t|d5t|d6td7t|d8t|d9|d:krd|ndd;| |t|d< d=|}n8|d(krt|||d>}n|d"kr|d?|d@d$d$dA}||s||rd|dB< |||fdCdD}dEkr|dEdF}|dGi dH< dIdJ }dKkrpdLkrp|dLdM|dNkrdOkrd	dPkrdQkrtdQ dR 	ttt|	dddP< 	fdSdTt dU dP dU  D dV< ng dV< dddU 

fdWdX} dO D ]b}!|!dYp|!dZ |   
d7 
t |!d[dD ]}"7 |   
d7 
qD7 q
ndKkrdOkrg }#d}$dR }%dO D ]Z}!t|!dZ |%}&t |!d[dd D ]0}"dK |$ }'|#!||'|'d|&i |$d7 }$qq|#dV< njdKkrlg }#dQkr,tdQ dR nd	dK D ]*}(||(|(i})	rV	|)d< |#!|) q8|#dV< dVkr||p||g |d"krd\nd?d] dHkrڈdH }*|d^s|*|d^< |dV !||*|*i |dV "dV  |st#d_d. t$}n||d^< |d`krJ||d^  |da< ||d^   d7  < |db !| q|d(kr|dc |p`dd !| qq|V  qdS )ea4  
        Parse formats from MPD manifest.
        References:
         1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
            http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
         2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
        Zdynamic_mpdTr  Zdynamicz(?i)^{([^}]+)?}MPD$r  Nr   c                    s    |  S rc   )r  )r  )r  rT   rW   rX   _add_ns
  s    z1InfoExtractor._parse_mpd_periods.<locals>._add_nsc                    s   |   dd k	S )NZContentProtection)r,  )elementr  rW   rX   is_drm_protected
  s    z:InfoExtractor._parse_mpd_periods.<locals>.is_drm_protectedc           	         s   |    fdd} fdd}| d}|d k	rp|| || |d}|rdd |D  d	< nT| d
}|d k	r|| |d}|r| d< |d}|r| d< n||  S )Nc                    s   |   d}|d k	r| d}|rdd< g d< |D ]T}t|dd}d  d| 7  < d t|ddt|jd	 |d
 q<| d}|rt|d< | d}|rt|d< | d}|rt|d< d S )NZSegmentTimelineSr   total_numberrB  rr   r   d)r   r  r  ZstartNumberstart_number	timescaler  segment_duration)r,  r!  r  r   r4  rT  r  )sourceZsegment_timelineZs_erB  r  r  r  r  r  ms_inforW   rX   extract_common
  s.    



z[InfoExtractor._parse_mpd_periods.<locals>.extract_multisegment_info.<locals>.extract_commonc                    s(   |   d}|d k	r$|jd d< d S )NZInitializationZ	sourceURLinitialization_url)r,  rT  )r  initializationr  rW   rX   extract_Initialization
  s    zcInfoExtractor._parse_mpd_periods.<locals>.extract_multisegment_info.<locals>.extract_InitializationZSegmentListZ
SegmentURLc                 S   s   g | ]}|j d  qS )r  )rT  )re   segmentrW   rW   rX   r   
  s     zWInfoExtractor._parse_mpd_periods.<locals>.extract_multisegment_info.<locals>.<listcomp>segment_urlsZSegmentTemplater  r   )r   r,  r!  r   )	r  Zms_parent_infor  r  Zsegment_listZsegment_urls_eZsegment_templater  r   r  )r  rX   extract_multisegment_info
  s*    


zCInfoExtractor._parse_mpd_periods.<locals>.extract_multisegment_infor  ZPeriodrv   zperiod-)rv   r-  r   r  r   )r  r  ZAdaptationSetZRepresentationZmimeTypecontentTyper  r   r  rN   zapplication/x-rawccZscodecr  audior  
image/jpegr  r  r  r  r  r  )ttZdfxpZttmlr  r%  zUnknown MIME type z in DASH manifestZBaseURLc                      s    j S rc   )r  rW   )
base_url_erW   rX   r  
  r  z2InfoExtractor._parse_mpd_periods.<locals>.<lambda>rk  r   z/{http://youtube.com/yt/2012/10/10}contentLength	bandwidth-r  r  r  r  r  ZaudioSamplingRateZ	frameRate)mulrz  ZzxxZmiszDASH Z_dash)r/  rI  r  r  r  r  asrr  r}  r]  r   	container)r  rI  r   ZmhtmlzDASH storyboards (jpeg))r/  r  rI  r]  r  r  rt  c                    s   |  } d k	r| d }d}d}|D ]0}||7 }|dkrD| }q(|dkr(|s(||7 }q(tdd|d|}td	d|d
|}| dd |S )Nz$RepresentationID$rN   F$%z\$({})\$|z%(\1)dz\$({})%([^$]+)\$z%(\1)\2z$$)r   rn   r   r   r   )Ztemplate_nameZidentifierstmplr   Zin_templater  )representation_idrepresentation_ms_inforW   rX   prepare_template7  s    
z:InfoExtractor._parse_mpd_periods.<locals>.prepare_templater   )	Bandwidthr  r  c                 S   s   t d| rdS dS )Nrk  rh   r  )rn   rd   )r  rW   rW   rX   location_key\  s    z6InfoExtractor._parse_mpd_periods.<locals>.location_keyr  r  )Numberr  Timez%(NumberrB  r  r  r  c                    s"   g | ]}| d  diqS ))r  r  r  rW   )re   segment_number)r  media_location_keymedia_templater  rW   rX   r   l  s     z4InfoExtractor._parse_mpd_periods.<locals>.<listcomp>r  r  c               	      s4    d } d  | dtd i d S )N)r  r  r  r  r  r  )r4  r*   )segment_url)r  r  r  r  	segment_dr  segment_timerW   rX   add_segment_url~  s      z9InfoExtractor._parse_mpd_periods.<locals>.add_segment_urlr   r  r  Zhttp_dash_segments)rh   Zfragment_base_urlr  rR  rh   c                 S   s   t dd | d D S )Nc                 s   s   | ]}|d  V  qdS )r  NrW   )re   fragrW   rW   rX   ri     s     zEInfoExtractor._parse_mpd_periods.<locals>.<lambda>.<locals>.<genexpr>r  )rp  )r  rW   rW   rX   r    r  )r  r  r  r  r-  r   rz  )%r   r   r  r  r4   collectionsdefaultdictr  r  r!  r   rT  r   r   r  r3   r/   r   r,  r@   r  rn   rd   r   r   r3  rH   r>  r,   r*   mathceilr   r4  r  rA   r  )+rT   r  r  r  r  r  r  Zmpd_durationZstream_numbersZ
period_idxr  Zperiod_entryZperiod_durationZperiod_ms_infoZadaptation_setZadaption_set_ms_infoZrepresentationZrepresentation_attribrV  r   Z	codec_strr  r   r  r   Zurl_elr   r/  r2  r  Zinitialization_templater  r"  rB  r   r  Zsegment_indexr  r  Zsegment_urir  fragmentr  rW   )r  r  r
  r  r  r  r  r  r   r  r  r!  rT   rX   r  
  s   :

















 


  

 

 
z InfoExtractor._parse_mpd_periodsc                 O   s"   | j ||\}}|r| d |S )NZISM)r  ra  rc  rW   rW   rX   _extract_ism_formats  s    
z"InfoExtractor._extract_ism_formatsc
              
   C   sx   |  drd}| j|||d kr"dn||d kr0dn|||||	d}
|
dkrPg i fS |
\}}|d krhg i fS | ||j|S )NrW  FzDownloading ISM manifestzFailed to download ISM manifestrf  )r   rG   _parse_ism_formats_and_subtitlesrh   )rT   ism_urlr   r  r   r   r   r   r   r   r5  ism_docr   rW   rW   rX   r    s$    
    z0InfoExtractor._extract_ism_formats_and_subtitlesc              #   C   s|  | ddkrg i fS t|jd }t| dp4d}g }i }|dD ](}| d}	|	dkrbqH|jd	 }
t| dp||}| d
}| dd}|dD ]}ddd}| dp| | d}|dkr| | d qt|jd d }t| dp
| d}t| dp$| d}t| d}td|jd |
}tj	
||}g }ddi}|d}t|D ]\}}t| d p|d |d< t| d!pd"}t| d#|d$< |d$ szt||d"  jd  }W n tk
r   |}Y nX ||d  | |d$< t|D ]D}|td%t|d ||d$ | d& |d  |d$ 7  < qqv|	d'kr||g d(d)||||	||||| d*d+d, q|	d-kr|t||||||	d.krd/nd0|||||	d1krd2n||	d.krd2n|d)||d3d4k	|t| d5|	|||p$d|p,d||| d*|t| d5d6t| d7d8t| d9d:d;d< qqH||fS )=z
        Parse formats from ISM manifest.
        References:
         1. [MS-SSTR]: Smooth Streaming Protocol,
            https://msdn.microsoft.com/en-us/library/ff469518.aspx
        ZIsLiveTRUEZDurationZ	TimeScalei ZStreamIndexTyper  UrlNameZLanguagerz  ZQualityLevelAACLEC-3)Z255Z65534ZFourCCZAudioTag)ZH264ZAVC1r1  ZTTMLr2  z is not a supported codecZBitrater  ZMaxWidthZWidthZ	MaxHeightZHeightZSamplingRatez{[Bb]itrate}r   r   r  r   r  r   r  r  z{start[ _]time})rh   r  r  ZismtZismZCodecPrivateData)stream_typer  r  fourccr}  codec_private_data)r  rR  rh   rI  r  _download_paramsr  r  ZismvZismar  r  Z
ProtectionNZChannelsr   ZBitsPerSample   ZNALUnitLengthField   )r3  r  r  r  r  r4  r}  r5  sampling_rateZchannelsZbits_per_sampleZnal_unit_length_field)r/  rh   rI  r  r  r  r  r  r  r  rR  r  rt  r}  Zaudio_channelsr6  )r   r  rT  r,   r!  r   rn   r   r   r3  rH   r  ry   r   r4  r   r   r-   r,  )rT   r,  r+  r  r  r  r-  r   streamr3  Zurl_patternZstream_timescaler  Zstream_languager  Z
KNOWN_TAGSr4  r  r  r  r9  Ztrack_url_patternr  Zfragment_ctxZstream_fragmentsZstream_fragment_indexZstream_fragmentZfragment_repeatZnext_fragment_timer   rW   rW   rX   r*    s    



 






z.InfoExtractor._parse_ism_formats_and_subtitlesc
           $   
      s$  fdddd }
d( 	
f	dd	}g }d}dd	 t d
| d|D }|t d| d| |D ]\}}}}g i d}t|}tt|d}|r|
|d}||||\}}|d | |d|d< |rt d|D ]D}t|ttd}|sq|
d}||||\}}|r0fdd	dD }td}tdp|td}|r|s|D ]8}t|}|sq|p|d}|p|d}q|D ]}t	|}|r qqd }|
|||dp
dd |
|d  |d | q|d | qt d|D ]} t| }!|!d}"|"rr|"d krLt|!d!}|sqL|!d"p|!d#p|!d}#|d$ |#g d%|i qL|d D ]*}|d&i d'<  r|d& 
  q|d s|d$ rv|| qv|S ))Nc                    s
   t  | S rc   )rH   )Zitem_url)r   rW   rX   absolute_url^  s    z>InfoExtractor._parse_html5_media_entries.<locals>.absolute_urlc                 S   s@   | si S t d| }|r<| \}}t|}t||d< |S i S )Nz<(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?r  )rn   r   ry  r3   r/   )r   Zctrmimetyper  r2  rW   rW   rX   parse_content_typea  s    zDInfoExtractor._parse_html5_media_entries.<locals>.parse_content_typec                    s   |pi }| }| dp t|}|dkrLd}j|dd d	}n@|dkrnd}j|d d}nd}||d	krd
nd |dg}||fS )Nr  rO  FrP  )r  rg  rF  rC  rD  r   r   r  )r  r   r   Tr  r  rh   r  r  )r   r$   rU  r  )r  Zcur_media_typeZ	type_infofull_urlr  is_plain_urlr-  )	_headersr;  m3u8_entry_protocolrF  r  rC  rD  rT   r   rW   rX   _media_formatsl  s>              z@InfoExtractor._parse_html5_media_entries.<locals>._media_formatsz((?:(?:amp|dl8(?:-live)?)-)?(video|audio)c                 S   s   g | ]\}}}|||d fqS )rN   rW   )re   	media_tagZmedia_tag_namer  rW   rW   rX   r     s   z<InfoExtractor._parse_html5_media_entries.<locals>.<listcomp>z(?s)(<(z	)[^>]*/>)z(?s)(<(?P<tag>z )(?:\s+[^>]*)?>)(.*?)</(?P=tag)>)r-  r   )r  zdata-video-srczdata-srczdata-sourcer  r-  Zposterr  z<source[^>]+>c                    s$   g | ]}t  |r |qS rW   )r;   r   )re   lbl)s_attrrW   rX   r     s   )labelr^  r  r  r5  rG  r^  )r  r  r  r/  r   z<track[^>]+>kind)r   captionsr  Zsrclangr   r   rh   Zhttp_headersZReferer)N)rn   r!  r  r'   r=   r%   r   r,   r7   r2   r   r4  r   )$rT   r   rB  r   rF  rB  r  rC  rD  rA  r=  rC  rn  Z_MEDIA_TAG_NAME_REZ
media_tagsrD  r   r  Zmedia_contentZ
media_infoZmedia_attributesr  r2  r-  Z
source_tagr@  labelsr  r  rE  r\  r  Z	track_tagZtrack_attributesrH  r   rW   )rA  r;  r   rB  rF  r  rC  rD  rF  rT   r   rX   _parse_html5_media_entries]  s    
 


" 
z(InfoExtractor._parse_html5_media_entriesc                 O   s"   | j ||\}}|r| d |S )NZakamai)%_extract_akamai_formats_and_subtitlesra  rc  rW   rW   rX   _extract_akamai_formats  s    
z%InfoExtractor._extract_akamai_formatsc                 C   s  d|k}|s t dd|d}g }i }d}t dd|dd	}|d
}	|	rbt dd|	 |}d|kr|d|krxdnd| 7 }| j||d
dd}
|
D ]}|d|i q||
 t dd|d	d}|d}|rt dd| |}| j||ddddd\}}|| | 	||}|d}|r|r|sd}t 
||dd}t|}t|||d fkrd}|D ]}|d dkrzd D ]h}| }|d!= t ||d"| d#||  d$ |d% }||d& d'|d( ||d) || q|d7 }qz||fS )*Nzhdnea=z2(?:b=[\d,-]+|(?:__a__|attributes)=off|__b__=\d+)&?rN   r  zhdcore=3.7.0z(https?://[^/]+)/i/z\1/z/z/master.m3u8z/manifest.f4mr  z(https?://)[^/]+z\1zhdcore=r  Fr  Zextra_param_to_segment_urlz(https?://[^/]+)/z/z\1/i/r  rP  re  r  r  z2https?://[^/]+/i/([^,]+),([^/]+),([^/]+)\.csmil/.+r   r  r   r   r  r  )r  httpsrI  z://z/\g<1>z\3rh   r/  r  r  )r/  rh   rR  )rn   r   r@  r   r   rK  r   r  rb  r  rd   rw   r  r  r   r4  )rT   rI  r   hostssignedr-  r   Zhdcore_signr  Zhds_hostrY  entryr^  Zhls_hostr  Zm3u8_subtitlesZ	http_hostZ
REPL_REGEXZ	qualitiesZqualities_lengthrW  r2  rR  r  Zhttp_urlrW   rW   rX   rL    s     
   

    


  z3InfoExtractor._extract_akamai_formats_and_subtitlesc              
      s  t j|jtdd|}td|}|d}dd|dpDd| g } fdd	}d
|kr|	| j
|d|d|ddd d|kr|	| j|d|ddd d|kr|	| j|d|ddd td|rhd|kr| j|d|dd}	|	D ]h}
|
 }d|
d |
d |d< |d= |d= ||d dd|
d  d!d"d"d# |	|
|g qn2d$D ],}||krl|| d%| ||d# ql|S )&Nz6/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)rN   z1(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)rh   z{}{}:{}r  rB  c                    s$     d|  }r |d 7 }|S )Nr  r  rW   )rJ  Zm_urlZhttp_base_urlr   rW   rX   rI  &  s    z:InfoExtractor._extract_wowza_formats.<locals>.manifest_urlrO  zplaylist.m3u8rP  r  Fr  rN  zmanifest.f4mr  r  r  zmanifest.mpdr  z(?:/smil:|\.smil)r  zjwplayer.smilr  z{}/{}r  r  zrtmp://zrtsp://r/  r  rtsp)rh   r/  rR  )r  rS  r=  )r   r3  urlparser   rn   r   r   rw   r   r  rU  rK  r  r  r   r   r   r4  )rT   rh   r   rB  Zskip_protocolsrs  Zurl_baser-  rI  Zrtmp_formatsZrtmp_formatZrtsp_formatrR  rW   rR  rX   _extract_wowza_formats  sv     
        
 
z$InfoExtractor._extract_wowza_formatsc              
   C   s   | j d|d|dd|d dS )Nzy(?<!-)\bjwplayer\s*\(\s*(?P<q>'|")(?!(?P=q)).+(?P=q)\s*\)(?:(?!</script>).)*?\.\s*(?:setup\s*\(|(?P<load>load)\s*\(\s*\[)zJWPlayer dataz)\{(?s:.*)}(?(load)(?:\s*,\s*\{(?s:.*)})*)z(?(load)\]|\)))r  r  r!  r   )r  )rT   rB  r   r!  rW   rW   rX   _find_jwplayer_dataR  s        z!InfoExtractor._find_jwplayer_datar!  c                O   s$   | j |||d}| j||f||S )NrW  )rV  _parse_jwplayer_data)rT   rB  r   r!  r.  r/  jwplayer_datarW   rW   rX   _extract_jwplayer_dataZ  s       z$InfoExtractor._extract_jwplayer_datac                 C   s  g }t |ts|S |d}	t |	ts0|	p,|f}	|	D ]}
t |
tsFq4d|
krX|
g|
d< |pb|
d }| j|
d |||||d}i }t|
ddd fD ]@}t||d}|sq||d	pd
g d| 	|i q|t
|r|
d n|
dt|
dt|| 	|
dt|
dt|dp2|
d|t|
dt|
dtt|
dt|
dt|
dt|
dt|
dd}t|dkrtd|d d r|d|d d d n||d< || q4t|dkr|d S | |S d S )Nrm  sourcesZmediaid)r   rF  r  rtmp_paramsr   Ztracksc                 S   s   |d   dkS )NrH  )rI  r   r  )r   r  rW   rW   rX   r  }  r  z4InfoExtractor._parse_jwplayer_data.<locals>.<lambda>filerG  r  rh   r^  rl  r  Zpubdater  Zsubtitlegenre)categorychannelr  r	  ZreleasedateZage_restriction)rv   r^  rl  r  r  r  r   Z	alt_titler_  ra  r  r
  Zrelease_yearr  r   z+^(?:http|//).*(?:youtube\.com|youtu\.be)/.+r   r]  r_  r-  )r   r  r   r   _parse_jwplayer_formatsr>   rH   r   r4  r:  rB   r"   r,   r*   r%   r  rn   r   r   re  )rT   rY  r   Zrequire_titlerF  r  r\  r   rn  Zplaylist_itemsZ
video_dataZthis_video_idr-  r   r  Z	track_urlrQ  rW   rW   rX   rX  `  sr    






     
 $

z"InfoExtractor._parse_jwplayer_datac                 C   s  t  }g }|D ]}	t|	ts qt|| |	d}
|
r|
|krDq||
 |	dpZd}t|
t|d}|dks|dksd|
kr|	| j
|
|dd	|d
d q|dks|dksd|
kr|	| j|
||d
d q|dkr|	| j|
|d
d q|ds
|dkr||
d|d qt|	d}t|	d}|d krX|rXt|d}|
t|	d|t|	dddt|	d||d}|
drd|d < tjd!|
d"d#}t|d$kr|\}}}|||| d% |r|| || q|S )&Nr^  r  rN   r  r  rO  zformat=m3u8-aaplrP  re  F)rg  rF  r   r  r  zformat=mpd-time-csfr  r  r  r  )ZogaZaacZmp3ZmpegZvorbisr  r>  rG  r  r  r  r  r  r   )rh   r  r  r  r   r  r/  r  rQ  r  z((?:mp4|mp3|flv):)r   )maxsplit   r  )r\   r   r  rH   r:  r   rK  r$   r/   r  rU  r  r  r   r4  r;   r,   r7   rn   r  r  r   )rT   Zjwplayer_sources_datar   rF  r  r\  r   r  r-  r  
source_urlZsource_typer  r/  r  Za_formatZrtmp_url_partsZrtmp_urlr  r  rW   rW   rX   rb    s    

 
    
   
  

	  

z%InfoExtractor._parse_jwplayer_formatsc                 C   s   | j d |S )NzLyt_dlp.InfoExtractor._live_title is deprecated and does not work as expectedr,  r`  rW   rW   rX   _live_title  s    zInfoExtractor._live_titlec                 K   s@   t |f|}|d kr<d| d|}|r2t|n
| | |S NzFailed to extract z: Could not parse value )r,   r   r   rT   r  r>  r   r/  r5  r   rW   rW   rX   _int  s    

zInfoExtractor._intc                 K   s@   t |f|}|d kr<d| d|}|r2t|n
| | |S rg  )r*   r   r   rh  rW   rW   rX   _float  s    

zInfoExtractor._floatr  c
                 K   sD   t jd||||d k	|d|d|d|||d d |	}| j| d S )Nr   Tr  )r  r   Cookier   
set_cookie)rT   domainr>  r  expire_timeportr  r  discardrestr/  cookierW   rW   rX   _set_cookie  s&                 zInfoExtractor._set_cookiec                 C   s   t | jj|S )zA Return a http.cookies.SimpleCookie with the cookies for the url )r   r   r   get_cookie_headerr   rW   rW   rX   _get_cookies  s    zInfoExtractor._get_cookiesc                 C   sj   |j  D ]Z\}}| dkr q
|dd}t| d|}|r
| \}}| |||  qfq
dS )an  
        Apply first Set-Cookie header instead of the last. Experimental.

        Some sites (e.g. [1-3]) may serve two cookies under the same name
        in Set-Cookie header and expect the first (old) one to be set rather
        than second (new). However, as of RFC6265 the newer one cookie
        should be set into cookie store what actually happens.
        We will workaround this issue by resetting the cookie to
        the first one manually.
        1. https://new.vk.com/
        2. https://github.com/ytdl-org/youtube-dl/issues/9841#issuecomment-227871201
        3. https://learning.oreilly.com/
        z
set-cookiez
iso-8859-1r   z%=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)N)	r   r  r  r	  r   rn   r   ry  rs  )rT   Z
url_handlerr  headerrQ   Zcookie_valuer  rm  rW   rW   rX   _apply_first_set_cookie_header  s     z,InfoExtractor._apply_first_set_cookie_headerc                 c   s   t | d}|r6t| dr.t|   d|g}nt | dg }|D ](}|s`|ddr`qJ|  |d< |V  qJt| dd r| j|E d H  d S )NZ_TESTZ_TESTSzIE has _TEST and _TESTSZonly_matchingFr>  __wrapped__)r  r   hasattrr   r   r1  rx  get_testcases)rs   include_onlymatchingr   testsrW   rW   rX   rz  !  s    zInfoExtractor.get_testcasesc                 c   sL   t | dg }|D ]}|  |d< |V  qt| dd rH| j E d H  d S )NZ_WEBPAGE_TESTSr>  rx  )r  r   r   r1  rx  get_webpage_testcases)rs   r|  r   rW   rW   rX   r}  2  s    z#InfoExtractor.get_webpage_testcasesc                 C   s$   t t| jdd|  dp dgS )z Get age limit from the testcasesFr{  ).))rm  r   N	info_dictr  r   )r  r>   rz  r}  r}   rW   rW   rX   r  ;  s    zInfoExtractor.age_limitc                 C   sH   t | jdd}|sdS tdd |D s.dS tdd |D rDdS d	S )
zIWhat the extractor returns: "video", "playlist", "any", or None (Unknown)Fr~  Nc                 s   s"   | ]}|D ]}| d V  q
qdS rm  Nrm  )re   testr  rW   rW   rX   ri   H  s       z-InfoExtractor._RETURN_TYPE.<locals>.<genexpr>r  c                 s   s    | ]}t d d |D V  qdS )c                 s   s   | ]}| d V  qdS r  rm  )re   r  rW   rW   rX   ri   J  s     z7InfoExtractor._RETURN_TYPE.<locals>.<genexpr>.<genexpr>N)rO   )re   r  rW   rW   rX   ri   J  s     rm  rO   )rl   rz  rO   all)rs   r|  rW   rW   rX   _RETURN_TYPEB  s    zInfoExtractor._RETURN_TYPEc                 C   s    |  |rddd| jS dS )z=Returns whether the URL is of a single video, None if unknownTF)r  rm  N)ru   r   r  rr   rW   rW   rX   is_single_videoN  s    
zInfoExtractor.is_single_videoc                 C   s   t | j| S )zHTest whether the extractor is generally suitable for the given age limit)r   r  )rs   r  rW   rW   rX   is_suitableT  s    zInfoExtractor.is_suitable)markdownsearch_examplesc                C   s  d}| j r4|r"|d| j  d7 }n|d| j  d7 }| jdkrH|d7 }n| jr^|d| j 7 }| jr|| jrpd	nd d
| j d7 }|rd}|d| j t| dt| d7 }|  s||rdnd7 }|rdtdd| j	n| j	}|r| d| S |S )zDescription of the extractorrN   z [*z*](## "netrc machine")z [r  Fz	 [HIDDEN]r   rL  z "z	:" prefix)rN   510r  z (e.g. "r=  z")z (**Currently broken**)z (Currently broken)z	 - **{}**z:(\w+:)u	   :​\g<1>)
rR   r   
SEARCH_KEYr   r   r~   r   rn   r   r   )rs   r  r  descZ_COUNTSr>  rW   rW   rX   rl  Y  s$    

 ( zInfoExtractor.descriptionc                 O   s&   |  dds|  dr"| j||S i S )NZwritesubtitlesFlistsubtitles)r   _get_subtitlesrT   r.  r/  rW   rW   rX   extract_subtitlesr  s
    zInfoExtractor.extract_subtitlesc                 O   s   t dd S Nr   r   r  rW   rW   rX   r  x  s    zInfoExtractor._get_subtitlesc                   @   s   e Zd ZdZdS )zInfoExtractor.CommentsDisabledz=Raise in _get_comments if comments are disabled for the videoN)r   r)  r;  r<  rW   rW   rW   rX   CommentsDisabled{  s   r  c                    s,    dsd S j||  fdd}|S )Ngetcommentsc               
      s   g } d}z|  t  q
W n tk
r4   d}Y nx tk
rP   d Y n\ jk
rn   d d d Y S  tk
r } z ddk	r j	| W 5 d }~X Y nX t
| }d| d | |rd n|dS )NTFzInterrupted by user)r   comment_countZignoreerrorsz
Extracted z	 comments)r4  rp   r   KeyboardInterruptr   r  	Exceptionr   r   Zreport_errorr  )r   interruptedr   r  	generatorrT   rW   rX   	extractor  s&    
z1InfoExtractor.extract_comments.<locals>.extractor)r   _get_comments)rT   r.  r/  r  rW   r  rX   extract_comments~  s
    
zInfoExtractor.extract_commentsc                 O   s   t dd S r  r   r  rW   rW   rX   r    s    zInfoExtractor._get_commentsc                    s2   dd | D  t | }| fdd|D  |S )za Merge subtitle items for one language. Items with duplicated URLs/data
        will be dropped. c                 S   s    h | ]}| d | dfqS )rh   r   r  re   r0  rW   rW   rX   	<setcomp>  s     z6InfoExtractor._merge_subtitle_items.<locals>.<setcomp>c                 3   s*   | ]"}| d | df kr|V  qdS )rh   r   Nr  r  Z
list1_datarW   rX   ri     s      z6InfoExtractor._merge_subtitle_items.<locals>.<genexpr>)r   r  )Zsubtitle_list1Zsubtitle_list2r  rW   r  rX   _merge_subtitle_items  s    z#InfoExtractor._merge_subtitle_itemsr  c                G   sD   |dkri }|D ].}|  D ] \}}| ||g |||< qq|S )z4 Merge subtitle dictionaries, language by language. N)r  r  r   )rs   r  Zdictsr  r   rd  rW   rW   rX   r    s    zInfoExtractor._merge_subtitlesc                 O   s&   |  dds|  dr"| j||S i S )NZwriteautomaticsubFr  )r   _get_automatic_captionsr  rW   rW   rX   extract_automatic_captions  s
    z(InfoExtractor.extract_automatic_captionsc                 O   s   t dd S r  r   r  rW   rW   rX   r    s    z%InfoExtractor._get_automatic_captionsc                 C   s   |  ddk	p|  ddk	S )z-Whether cookies have been passed to YoutubeDLZ
cookiefileNZcookiesfrombrowserr;  r   rW   rW   rX   _cookies_passed  s    zInfoExtractor._cookies_passedc                 O   s>   |  ddsd S |  r(|  d d k	s.| jr:| j|| d S )Nmark_watchedFr   )r   rS   r   r  _mark_watchedr  rW   rW   rX   r    s    zInfoExtractor.mark_watchedc                 O   s   t dd S r  r   r  rW   rW   rX   r    s    zInfoExtractor._mark_watchedc                 C   s   i }|  d}|r||d< |S )Ngeo_verification_proxyzYtdl-request-proxyr;  )rT   r   r  rW   rW   rX   geo_verification_headers  s
    
z&InfoExtractor.geo_verification_headersc                 C   s(   t jtj| ddd d S )Nr  r  r   )r   r3  unquoter
  r  r  rstripr  rg   rW   rW   rX   _generic_id  s    zInfoExtractor._generic_idr   c                C   s<   | j |d dp:| j|d dp:tjtjt|d p:|S )Nr   r   )	r  r  r   r3  r  r
  r  r  rE   )rT   rh   rB  r   rW   rW   rX   _generic_title  s    zInfoExtractor._generic_titlec                    s  |sd S  fdd|pg D }|r,| j }n| j}|jdd d ddig}t|D ]\}}	|	d d krx|d|  qT|d	 d |	d   kr|krn n||	 qT|	|krT|	d |kr|	d  d
| n|	d  d|d	 d  }
|d|
 d|	d  d qT|dd  S )Nc                    s   g | ]} ||d qS ))r  r^  rW   )re   chapterstart_functiontitle_functionrW   rX   r     s   z:InfoExtractor._extract_chapters_helper.<locals>.<listcomp>c                 S   s   | d p
dS )Nr  r   rW   )r  rW   rW   rX   r    r  z8InfoExtractor._extract_chapters_helper.<locals>.<lambda>)keyr  r   zIncomplete chapter r  z > z < zInvalid start time (z) for chapter "r^  r   r   )r   r   sortr  r4  )rT   Zchapter_listr  r  r  r$  warnr  r  r  issuerW   r  rX   _extract_chapters_helper  s*    
$z&InfoExtractor._extract_chapters_helperc                 C   sh   d}d}| j t||df |p ddd dd |dd	pf| j t|d|f |pPdd
d dd |dd	S )Nz(?:\d+:)?\d{1,2}:\d{2}z(?m)^\s*(%s)\b\W*\s(%s)\s*$z.+?rN   c                 S   s   t | d S Nr   r4   r  rW   rW   rX   r    r  zBInfoExtractor._extract_chapters_from_description.<locals>.<lambda>c                 S   s   | d S Nr   rW   r  rW   rW   rX   r    r  F)r  r  r  r$  c                 S   s   t | d S r  r  r  rW   rW   rX   r    r  c                 S   s   | d S r  rW   r  rW   rW   rX   r    r  )r  rn   r!  )rT   rl  r  Zduration_reZsep_rerW   rW   rX   "_extract_chapters_from_description  s"        z0InfoExtractor._extract_chapters_from_descriptionc                 C   sP   t dd | ||||fD }| r$dS |r,dS |r4dS |r<dS |rDdS |rLdS d S )	Nc                 s   s   | ]}|d k	V  qd S rc   rW   r  rW   rW   rX   ri     s    z.InfoExtractor._availability.<locals>.<genexpr>privateZpremium_onlyZsubscriber_only
needs_authZunlistedpublic)r  )
is_privateZneeds_premiumZneeds_subscriptionr  Zis_unlistedZ	all_knownrW   rW   rX   _availability  s    zInfoExtractor._availability)r   	casesensec                C   sd   t |tr|n
|p|  }t| jjd| |f}|dkrJ|tkrFg S |S |rVt|S dd |D S )aT  
        @returns            A list of values for the extractor argument given by "key"
                            or "default" if no such key is present
        @param default      The default value to return when the key is not present (default: [])
        @param casesense    When false, the values are converted to lower case
        Zextractor_argsNc                 S   s   g | ]}|  qS rW   r]  r  rW   rW   rX   r     s     z4InfoExtractor._configuration_arg.<locals>.<listcomp>)	r   r   r   r>   r   rM  r  r   r   )rT   r  r   r   r  valrW   rW   rX   _configuration_arg  s
    z InfoExtractor._configuration_argrm  )playlist_labelvideo_labelc                C   s   |r|s| S |pi  d}|d k	r*| S |dkr6dnd| }|dkrLdnd| }| drz| d| | d dS | d	| | d
| |  dS )NZforce_noplaylistTrN   r   Z
noplaylistzDownloading just the z because of --no-playlistFzDownloading z* - add --no-playlist to download just the )r   r   r   )rT   rg  r   Zsmuggled_datar  r  Zno_playlistrW   rW   rX   _yes_playlist  s    
zInfoExtractor._yes_playlistc                C   s@   t j||pt||| j| j|r"d n| j| di dd d S )NZretry_sleep_functionsr  )r  r  errorZ
sleep_func)r   Zreport_retryr  r   r   r   r   )rT   r   r  Z_retriesr   rW   rW   rX   _error_or_warning(  s     
   zInfoExtractor._error_or_warningc                 K   s   t | dd| jf|S )NZextractor_retriesrd  )r   r   r  )rT   r/  rW   rW   rX   r   .  s    zInfoExtractor.RetryManagerzExtracting generic embeds)r  r   c                O   sP   t |dd}| t|d d |  | jdjt|d|  gif||S )N
display_idrv   rH  GenericZ	block_ies)r>   r   r+   r   get_info_extractorZ_extract_embedsr:   r   )rT   rh   r  r   r.  r/  r  rW   rW   rX   _extract_generic_embeds1  s    z%InfoExtractor._extract_generic_embedsc                 c   sN   t | jtjr| n||  }|||p.g D ]}|||d  |V  q0d S rc   )r   _extract_from_webpagetypes
MethodTyper  r   Zadd_default_extra_info)rs   Zydlrh   rB  r   r  rW   rW   rX   extract_from_webpage7  s    z"InfoExtractor.extract_from_webpagec                 c   s>   t | ||pg ddD ] }| || jdkr0d n| V  qd S )NTrd  F)r1   _extract_embed_urlsra  rj   )rs   rh   rB  	embed_urlrW   rW   rX   r  @  s
     
z#InfoExtractor._extract_from_webpagec              	   c   s   d| j krnt| jttfstt| jD ]0\}}|ddks(t| j d| d| q(tt	t
j| j| _| jD ]F}||D ]6}tj|t|d}| jdks| |r|V  qqtdS )	z*@returns all the embed urls on the webpage_EMBED_URL_REz(?P<url>r   z._EMBED_REGEX[z!] must have exactly 1 url group
	rh   FN)rk   r   _EMBED_REGEXr   rl   r   r  countr   rm   rn   ro   r  r  r   r3  rH   rB   rw   rj   ru   )rs   rh   rB  r  rf   rs  r  rW   rW   rX   r  F  s    

z!InfoExtractor._extract_embed_urlsc                   @   s   e Zd ZdS )zInfoExtractor.StopExtractionN)r   r)  r;  rW   rW   rW   rX   StopExtractionV  s   r  c                 C   s   t t| d|pg dS )z1Only for compatibility with some older extractorsN)rp   iterr  )rs   rB  rW   rW   rX   _extract_urlY  s    zInfoExtractor._extract_url)plugin_namec                   s   |rt | }||| d   }| _||j | _| _|j d| | _t|dd r\|j}qHtt	j
|j |j|  t| |  t jf |S )Nr   +rx  )inspectgetmroindexrx  r   ZPLUGIN_NAMEr   r1  setattrr   modulesr)  r   _PLUGIN_OVERRIDESr4  r&  __init_subclass__)rs   r  r/  mroZsuper_classr'  rW   rX   r  ^  s    
zInfoExtractor.__init_subclass__)N)NNNN)	NNTNNNNNF)N)NNTNNN)NTN)NTN)N)N)r[  NF)FN)NNN)NNN)N)r   rP   N)r  )N)r  T)r^  )NF)N)TN)r  )N)N)NNNN)N)TNN)TN)TN)N)NNN)Nr  )T)NN)NrN   N)N)Nre  NNNN)NTNNNN)NNNNN)F)F)F)rN   rN   )T)NNNNN)N)Nr   )r   r)  r;  r<  rZ   r   r[   r   r   r   r|   _ENABLEDrR   r   r  rj   r  r   rY   ra   classmethodrt   ru   rx   r{   r~   rS   r   r   r   r   r^   propertyr   r   r   r   r   r   r   r!   r   staticmethodr   r   r   r   r   r  r  r  r   r   r#  r)  r0  Z'_InfoExtractor__create_download_methodsrG  r  Z_download_json_handleZ_download_jsonZ_download_socket_json_handleZ_download_socket_jsonrC  rG  r   r   r   r   rQ  rS  r   rU  rV  rZ  r\  rO  ra  r   rj  re  r  r  r   r  r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r#  r%  r+  r.  r3  r5  r1  r<  r:  rD  rK  rH  r_  ra  rU  rb  ri  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r)  r  r*  rK  rM  rL  rU  r.   rV  rZ  rX  rb  rf  ri  rj  rs  ru  rw  rz  r}  r  r  r  r  rl  r  r  r  r  r  r  r  r  r  r  r  cached_propertyr  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r*  rW   rW   r'  rX   rM   i   s     I	






S"




	         
J     
;
     
E               
 	 
   
	
  #  	




 +



	    
 
f        
$          
 b    
	    

'
    ~(       Vq :5       C       A

   	rM   c                   @   sL   e Zd ZdZedZdZedd Zdd Z	dd	 Z
d
d Zedd ZdS )SearchInfoExtractorz
    Base class for paged search queries extractors.
    They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
    Instances should define _SEARCH_KEY and optionally _MAX_RESULTS
    infrm  c                 C   s   | j  dS )Nz/(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)_SEARCH_KEYr}   rW   rW   rX   rj   w  s    zSearchInfoExtractor._VALID_URLc                 C   s   |  |dd\}}|dkr*| |dS |dkr@| || jS t|}|dkrhtd| d| d	n(|| jkr| d
| j| j|f  | j}| ||S d S )Nr  r   rN   r   r  r   zinvalid download number z for query "r   z,%s returns max %i results (you requested %i))rt   rw   _get_n_results_MAX_RESULTSr  r   r   r  )rT   r   r  r  rW   rW   rX   r   {  s    
z!SearchInfoExtractor._real_extractc              	   C   s.   |  t| |d|tdkr"dn|||S )zGet a specified number of results for a query.
        Either this function or _search_results must be overridden by subclasses r   r  N)re  r  islice_search_resultsr  )rT   r   r  rW   rW   rX   r    s
    " z"SearchInfoExtractor._get_n_resultsc                 C   s   t ddS )z%Returns an iterator of search resultsr   Nr   )rT   r   rW   rW   rX   r    s    z#SearchInfoExtractor._search_resultsc                 C   s   | j S rc   r  r}   rW   rW   rX   r    s    zSearchInfoExtractor.SEARCH_KEYN)r   r)  r;  r<  r  r  r  r!   rj   r   r  r  r  rW   rW   rW   rX   r  m  s   
r  c                   @   s    e Zd ZdZdZdZdd ZdS )UnsupportedURLIEz.*Fc                 C   s   t |d S rc   )r   r   rW   rW   rX   r     s    zUnsupportedURLIE._real_extractN)r   r)  r;  rj   r  r   r   rW   rW   rW   rX   r    s   r  )rr  r$  r  r  r  http.clientr  http.cookiejarhttp.cookiesr  r  r%  r&  rV   r
  r   rn   r  r   r   r  urllib.parser   urllib.requestxml.etree.ElementTreer  compatr   r   r   r   rQ   r   Zdownloader.f4mr   r	   Zdownloader.hlsr
   Z
networkingr   r   Znetworking.exceptionsr   r   r   r   Znetworking.impersonater   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   r  r  r%  r   r  rW   rW   rW   rX   <module>   s   ?                              "-	