U
    ,^$                    @   s  d dl m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mZmZmZmZmZmZmZmZmZmZmZ ddlmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZL G dd deMZNG d	d
 d
eNZOdS )    )unicode_literalsN   )compat_cookiejarcompat_cookiescompat_etree_Elementcompat_etree_fromstringcompat_getpasscompat_integer_typescompat_http_clientcompat_os_name
compat_strcompat_urllib_errorcompat_urllib_parse_unquotecompat_urllib_parse_urlencodecompat_urllib_requestcompat_urlparsecompat_xml_parse_error)get_base_urlremove_encrypted_media)+
NO_DEFAULTage_restrictedbase_urlbug_reports_message
clean_htmlcompiled_regex_typedetermine_extdetermine_protocoldict_geterror_to_compat_strExtractorErrorextract_attributesfix_xml_ampersandsfloat_or_noneGeoRestrictedErrorGeoUtilsint_or_none
js_to_json
JSON_LD_REmimetype2ext
orderedSetparse_bitrateparse_codecsparse_durationparse_iso8601parse_m3u8_attributesparse_resolutionRegexNotFoundErrorsanitized_Requestsanitize_filenamestr_or_nonestrip_or_noneunescapeHTMLunified_strdateunified_timestampupdate_Requestupdate_url_queryurljoinurl_basenameurl_or_none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
dd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dd Zdd Zedd Zedd Zedd  Zddddi i dfd!d"Zdddddi i dfd#d$Zed%d& Zd'd( Zdd)d*Z dddd+d,ddi i df
d-d.Z!d/d0ddddi i df	d1d2Z"d/d0ddddi i df	d3d4Z#dd5d6Z$d7d8ddddi i df	d9d:Z%d7d8ddddi i df	d;d<Z&dd=d>Z'dd?d@Z(dAdB Z)dCdD Z*dEdF Z+dGdH Z,dIdJ Z-ed dLdMZ.eddOdPZ/eddQdRZ0ddSdTZ1eddUdVZ2e3ddWdfdXdYZ4e3ddWdfdZd[Z5dd\d]Z6dd`daZ7ddcddZ8ededf Z9edgdh Z:ddidjZ;dkdl Z<dmdn Z=dodp Z>d	drdsZ?dtdu Z@d
dvdwZAdxdy ZBdzd{ ZCd|d} ZDd~d ZEdd ZFdddZGdddZHedd ZIdd ZJdddZKdd ZLedd ZMdi fddZNdd ZOdddZPdddZQdddd dddi i fddZRdddd ddfddZSdddZTdddddddddi i fddZUdddZVedddZWdddZXdddZYdddZZdddZ[dd Z\dddZ]dddZ^dddZ_dddZ`ddddi di i fddZaddi dfddZbdddddi i fddZcdddĄZddddƄZei fddȄZfdg fdd˄Zgdehfdd̈́Ziddτ ZjdddфZkdddӄZlddՄ ZmdddׄZnd ddلZodddddi fdd܄Zpddބ Zqdd Zrd!ddZsdd Ztdd Zudd Zvedd Zwedd Zxdd Zydd Zzdd Z{dd Z|dd Z}dd Z~dd ZdS ("  InfoExtractoraD  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.

    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.
                    * 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.
                    * 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
                    * resolution Textual description of width and height
                    * tbr        Average bitrate of audio and video in KBit/s
                    * abr        Average audio bitrate in KBit/s
                    * acodec     Name of the audio codec in use
                    * asr        Audio sampling rate in Hertz
                    * vbr        Average video bitrate in KBit/s
                    * 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.
                                 "http", "https", "rtsp", "rtmp", "rtmpe",
                                 "m3u8", "m3u8_native" or "http_dash_segments".
                    * 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)
                    * 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.
                    * downloader_options  A dictionary of downloader options as
                                 described in FileDownloader

    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:

    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)
    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.
    creator:        The creator of the video.
    release_date:   The date (YYYYMMDD) when the video was released.
    timestamp:      UNIX timestamp of the moment the video became available.
    upload_date:    Video upload date (YYYYMMDD).
                    If not explicitly set, calculated from 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.
    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
                    "ext" will be calculated from URL if missing
    automatic_captions: Like 'subtitles', used by the YoutubeIE for
                    automatically generated captions
    duration:       Length of the video in seconds, as an integer or float.
    view_count:     How many users have watched 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 give 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
                        * "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.
    age_limit:      Age restriction for the video, as an integer (years)
    webpage_url:    The URL to the video webpage, if given to youtube-dl 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"]
    is_live:        True, False, or None (=unknown). Whether this video is a
                    live stream that goes on instead of a fixed-length video.
    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)

    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.
    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.
    artist:         Artist(s) of the track.
    genre:          Genre(s) 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_artist:   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.
    release_year:   Year (YYYY) when the album was released.

    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", "description", "uploader",
    "uploader_id", "uploader_url" attributes with the same semantics as videos
    (see above).


    _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 one should re-define the _real_initialize() and
    _real_extract() methods and define a _VALID_URL regexp.
    Probably, they should also be added to the list of extractors.

    _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.

    Finally, 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| _ d| _| | dS )z-Constructor. Receives an optional downloader.FN)_ready_x_forwarded_for_ipset_downloaderself
downloader rG   NC:\Users\TaGoRe\Desktop\beinconnect-dl\binaries\youtube_dl\extractor\common.py__init__  s    zInfoExtractor.__init__c                 C   s(   d| j krt| j| _| j|dk	S )z8Receives a URL and returns True if suitable for this IE._VALID_URL_REN)__dict__recompile
_VALID_URLrJ   matchclsurlrG   rG   rH   suitable  s    
zInfoExtractor.suitablec                 C   s:   d| j krt| j| _| j|}|s,tt|dS )NrJ   id)	rK   rL   rM   rN   rJ   rO   AssertionErrorr   group)rQ   rR   mrG   rG   rH   	_match_id  s
    
zInfoExtractor._match_idc                 C   s   | j S )zGetter method for _WORKING.)_WORKINGrQ   rG   rG   rH   working  s    zInfoExtractor.workingc                 C   s,   |  | j| jd | js(|   d| _dS )z.Initializes an instance (authentication, etc).)	countries	ip_blocksTN)_initialize_geo_bypass_GEO_COUNTRIES_GEO_IP_BLOCKSrA   _real_initializerE   rG   rG   rH   
initialize  s    zInfoExtractor.initializec                 C   s  | j s| jjddsdS |s$i }t|ttfr:d|i}| jjdd}|sl|d}| jrl|rlt	|}|rt
|| _ | jjddr| jd	| j   dS | jjd
d}|s|d}| jr|rt	|}|rt
|| _ | jjddr| jd| j | f  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\   geo_bypass_ip_blockr]   verboseFz,[debug] Using fake IP %s as X-Forwarded-For.geo_bypass_countryz1[debug] Using fake IP %s (%s) as X-Forwarded-For.)rB   _downloaderparamsget
isinstancelisttuple_GEO_BYPASSrandomchoicer$   random_ipv4	to_screenupper)rE   Zgeo_bypass_contextZip_blockr]   Zcountryr\   rG   rG   rH   r^     sH     





z$InfoExtractor._initialize_geo_bypassc                 C   s   zzt dD ]l}z.|   | |}| jr2| j|d< |W   W S  tk
rt } z| |jrbW Y q
 W 5 d}~X Y q
X q
W nv tk
r    Y nb tj	k
r } ztd|ddW 5 d}~X Y n2 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__x_forwarded_for_ipNzA network error has occurred.T)causeexpectedz An extractor error has occurred.rt   )rangerc   _real_extractrB   r#   '_InfoExtractor__maybe_fake_ip_and_retryr\   r   r
   IncompleteReadKeyErrorStopIteration)rE   rR   _Z	ie_resulterG   rG   rH   extract  s$    

zInfoExtractor.extractc                 C   sl   | j jdd sh| jrh| j jddrh| jsh|rht|}t|| _| jrh| 	d| j|
 f  dS dS )Nrg   rd   TzUVideo is geo restricted. Retrying extraction with fake IP %s (%s) as X-Forwarded-For.F)rh   ri   rj   rn   rB   ro   rp   r$   rq   report_warningrs   )rE   r\   Zcountry_coderG   rG   rH   Z__maybe_fake_ip_and_retry!  s&    
z'InfoExtractor.__maybe_fake_ip_and_retryc                 C   s
   || _ dS )z Sets the downloader for this IE.N)rh   rD   rG   rG   rH   rC   0  s    zInfoExtractor.set_downloaderc                 C   s   dS )z4Real initialization process. Redefine in subclasses.NrG   rb   rG   rG   rH   ra   4  s    zInfoExtractor._real_initializec                 C   s   dS )z0Real extraction process. Redefine in subclasses.NrG   rE   rR   rG   rG   rH   rx   8  s    zInfoExtractor._real_extractc                 C   s   t | jdd S )z>A string for getting the InfoExtractor with get_info_extractorN)r   __name__rZ   rG   rG   rH   ie_key<  s    zInfoExtractor.ie_keyc                 C   s   t t| jd d S )Nr   )r   typer   rb   rG   rG   rH   IE_NAMEA  s    zInfoExtractor.IE_NAMEc                 C   sj   t | tjst|d krdS t |tr0| j|kS t |ttfrH| j|kS t|r^|| jdkS dsftd S )NFT)	rk   r   	HTTPErrorrU   r	   coderl   rm   callable)errexpected_statusrG   rG   rH   Z__can_accept_status_codeE  s    


z&InfoExtractor.__can_accept_status_codec
              
   C   s  |dkr|  | n4|dk	rH|dkr6| d|f  n| d||f  | jr`d|kr`| j|d< t|tjr~t||||d}n&|rt||}|dk	s|rt|||}z| j	
|W S  tjtjtjfk
rz }
 zt|
tjr| |
|	r|
|
j_|
j W Y lS |dkrW Y ZdS |dkr&d}d|t|
f }|rTt|t d |
d	n| j	| 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.
        NFz%sz%s: %szX-Forwarded-For)dataheadersqueryzUnable to download webpager   rv   )report_download_webpagerr   rB   rk   r   Requestr8   r9   r1   rh   urlopenr   URLErrorr
   HTTPExceptionsocketerrorr   &_InfoExtractor__can_accept_status_codefp_errorr   r   sysexc_infor   )rE   url_or_requestvideo_idnoteerrnotefatalr   r   r   r   r   errmsgrG   rG   rH   _request_webpageS  sH    
   



zInfoExtractor._request_webpagec                 C   sl   t |ttfr|dd }| j||||||||	|
d	}|dkrL|rHtdS | j|||||||d}||fS )z
        Return a tuple (page content as string, URL handle).

        See _download_webpage docstring for arguments specification.
        #r   )r   r   r   r   F)encoding)rk   r   str	partitionr   rU   _webpage_read_content)rE   r   r   r   r   r   r   r   r   r   r   urlhcontentrG   rG   rH   _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)rL   rO   rV   searchdecode
startswith)content_typewebpage_bytesrW   r   rG   rG   rH   _guess_encoding_from_content  s    

z*InfoExtractor._guess_encoding_from_contentc                 C   s   |d d }d|krNd|krNd}| j d|dd d}|rB|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 %s for more detailsTru   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: "%s")
 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   replace)rE   r   Zfirst_blockmsgZblocked_iframeZ	block_msgrG   rG   rH   Z__check_blocked  sB        zInfoExtractor.__check_blockedc	              	   C   s  |j dd}	| }
|d k	r&||
 }
|s6| |	|
}| jjddrt| d|   t	|

d}| j| | jjddr@d|| f }t|d	krd
t|d  }|d d	t|  | }|d }t|dd}| d|  tdkr tj|}t|dkr d| }t|d}||
 W 5 Q R X z|

|d}W n" tk
rr   |

dd}Y nX | | |S )NzContent-Type dump_intermediate_pagesFzDumping request to r   write_pagesz%s_%s   Z___r   z.dumpT)
restrictedzSaving request to nti  z\\?\wbr   )r   rj   readr   rh   ri   rr   geturlbase64	b64encoder   lenhashlibmd5encode	hexdigestr2   r   ospathabspathopenwriteLookupError_InfoExtractor__check_blocked)rE   r   r   r   r   r   r   prefixr   r   r   dumpZbasenhZraw_filenamefilenameZabsfilepathoutfr   rG   rG   rH   r     s<    

z#InfoExtractor._webpage_read_contentr      c                 C   s   d}d}|dkr~z&| j |||||||	|
||d
}d}W q tjk
rz } z$|d7 }||kr^|| || W 5 d}~X Y qX q|dkr|S |\}}|S dS )a;  
        Return the data of the page as a string.

        Arguments:
        url_or_request -- plain text URL as a string or
            a compat_urllib_request.Requestobject
        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
        tries -- number of tries
        timeout -- sleep interval between tries
        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.
        Fr   )r   r   r   r   r   Tr   N)r   r
   rz   _sleep)rE   r   r   r   r   r   triestimeoutr   r   r   r   r   successZ	try_countresr~   r   r}   rG   rG   rH   _download_webpage  s4    &        zInfoExtractor._download_webpagezDownloading XMLzUnable to download XMLc                 C   sH   | j ||||||||	|
|d
}|dkr*|S |\}}| j||||d|fS )z
        Return a tuple (xml as an compat_etree_Element, URL handle).

        See _download_webpage docstring for arguments specification.
        r   r   r   r   r   r   Ftransform_sourcer   )r   
_parse_xml)rE   r   r   r   r   r   r   r   r   r   r   r   r   
xml_stringr   rG   rG   rH   _download_xml_handle'  s.    
         z"InfoExtractor._download_xml_handlec                 C   s4   | j |||||||||	|
|d}|dkr,|S |d S )z
        Return the xml as an compat_etree_Element.

        See _download_webpage docstring for arguments specification.
        	r   r   r   r   r   r   r   r   r   Fr   )r   rE   r   r   r   r   r   r   r   r   r   r   r   r   rG   rG   rH   _download_xml<  s    
       zInfoExtractor._download_xmlc              
   C   sp   |r||}zt |dW S  tk
rj } z0d| }|rHt||dn| |t|  W 5 d }~X Y nX d S )Nr   z%s: Failed to parse XML rv   )r   r   r   r   r   r   )rE   r   r   r   r   ver   rG   rG   rH   r   M  s    zInfoExtractor._parse_xmlzDownloading JSON metadataz Unable to download JSON metadatac                 C   sH   | j ||||||||	|
|d
}|dkr*|S |\}}| j||||d|fS )z
        Return a tuple (JSON object, URL handle).

        See _download_webpage docstring for arguments specification.
        r   Fr   )r   _parse_json)rE   r   r   r   r   r   r   r   r   r   r   r   r   json_stringr   rG   rG   rH   _download_json_handleY  s.    
         z#InfoExtractor._download_json_handlec                 C   s4   | j |||||||||	|
|d}|dkr,|S |d S )zy
        Return the JSON object as a dict.

        See _download_webpage docstring for arguments specification.
        r   Fr   )r   r   rG   rG   rH   _download_jsonn  s    
       zInfoExtractor._download_jsonc              
   C   sl   |r||}zt |W S  tk
rf } z0d| }|rDt||dn| |t|  W 5 d }~X Y nX d S )Nz%s: Failed to parse JSON rv   )jsonloads
ValueErrorr   r   r   )rE   r   r   r   r   r   r   rG   rG   rH   r     s    zInfoExtractor._parse_jsonc                 C   s0   |d krdnd| }| j d| j||f  d S )Nr   z%s: z	[%s] %s%s)rh   r   r   )rE   r   r   ZidstrrG   rG   rH   r     s    zInfoExtractor.report_warningc                 C   s   | j d| j|f  dS )z2Print msg to screen, prefixing it with '[ie_name]'z[%s] %sN)rh   rr   r   )rE   r   rG   rG   rH   rr     s    zInfoExtractor.to_screenc                 C   s   |  d|  dS )zReport information extraction.z%s: Extracting informationNrr   )rE   Z
id_or_namerG   rG   rH   report_extraction  s    zInfoExtractor.report_extractionc                 C   s   |  d|  dS )zReport webpage download.z%s: Downloading webpageNr   rE   r   rG   rG   rH   r     s    z%InfoExtractor.report_download_webpagec                 C   s   |  d dS )zReport attempt to confirm age.zConfirming ageNr   rb   rG   rG   rH   report_age_confirmation  s    z%InfoExtractor.report_age_confirmationc                 C   s   |  d dS )zReport attempt to log in.z
Logging inNr   rb   rG   rG   rH   report_login  s    zInfoExtractor.report_login1This video is only available for registered usersc                 C   s   t d|  ddd S )NzL%s. Use --username and --password or --netrc to provide account credentials.Tr   )r   )r   rG   rG   rH   raise_login_required  s    z"InfoExtractor.raise_login_requiredEThis video is not available from your location due to geo restrictionc                 C   s   t | |dd S )N)r\   )r#   )r   r\   rG   rG   rH   raise_geo_restricted  s    z"InfoExtractor.raise_geo_restrictedc                 C   s0   d| |d}|dk	r||d< |dk	r,||d< |S )z<Returns a URL that points to a page that should be processedrR   )_typerR   r   NrT   titlerG   )rR   ier   video_title
video_inforG   rG   rH   
url_result  s    zInfoExtractor.url_resultc                    s*   t  fdd|D }j|||dS )Nc                 3   s,   | ]$}  r |n|V  qd S N)r   _proto_relative_url).0rW   getterr   rE   rG   rH   	<genexpr>  s   z6InfoExtractor.playlist_from_matches.<locals>.<genexpr>)playlist_idplaylist_title)r)   playlist_result)rE   Zmatchesr  r  r  r   urlsrG   r  rH   playlist_from_matches  s      z#InfoExtractor.playlist_from_matchesc                 C   s2   d| d}|r||d< |r"||d< |r.||d< |S )zReturns a playlistplaylist)r   entriesrT   r   descriptionrG   )r
  r  r  Zplaylist_descriptionr   rG   rG   rH   r    s    zInfoExtractor.playlist_resultr   c                 C   s   t |tttfr t|||}n |D ]}	t|	||}|r$ q@q$| jjdsjt	dkrjt
j rjd| }
n|}
|r|dkrtdd | D S ||S n8|tk	r|S |rtd|
 n| j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.
        no_colorr   z[0;34m%s[0mNc                 s   s   | ]}|d k	r|V  qd S r   rG   )r   grG   rG   rH   r    s      z.InfoExtractor._search_regex.<locals>.<genexpr>zUnable to extract %szunable to extract %s)rk   r   r   r   rL   r   rh   ri   rj   r   r   stderrisattynextgroupsrV   r   r0   r   r   )rE   patternstringnamer   r   flagsrV   mobjp_namerG   rG   rH   _search_regex  s&     
zInfoExtractor._search_regexc           	   	   C   s.   |  |||||||}|r&t| S |S dS )zR
        Like _search_regex, but strips HTML tags and unescapes entities.
        N)r  r   strip)	rE   r  r  r  r   r   r  rV   r   rG   rG   rH   r     s    z InfoExtractor._html_search_regexc              
   C   s   d }d }|p| j }| jjddrz:t |}|d k	rL|d }|d }ntd| W n< ttjfk
r } z| jdt	|  W 5 d }~X Y nX ||fS )NusenetrcFr   r   zNo authenticators for %szparsing .netrc: %s)
Z_NETRC_MACHINErh   ri   rj   netrcZauthenticatorsZNetrcParseErrorIOErrorr   r   )rE   netrc_machineusernamepasswordinfor   rG   rG   rH   _get_netrc_login_info  s"    


z#InfoExtractor._get_netrc_login_infor  r   c                 C   sL   | j dkrdS | j j}||dk	r6|| }|| }n| |\}}||fS )ay  
        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
        available look in the netrc file using the netrc_machine or _NETRC_MACHINE
        value.
        If there's no info available, return (None, None)
        N)NN)rh   ri   rj   r"  )rE   Zusername_optionZpassword_optionr  downloader_paramsr  r   rG   rG   rH   _get_login_info  s    	

zInfoExtractor._get_login_infotwo-factor verification codec                 C   s8   | j dkrdS | j j}|ddk	r,|d S t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
        N	twofactorzType %s and press [Return]: )rh   ri   rj   r   )rE   r   r#  rG   rG   rH   _get_tfa_info'  s    
zInfoExtractor._get_tfa_infoc                 C   s2   d}ddt | i }d}|||f |||f gS )Nz8content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))zM(?:name|property)=(?:\'og[:-]%(prop)s\'|"og[:-]%(prop)s"|\s*og[:-]%(prop)s\b)propz<meta[^>]+?%s[^>]+?%srL   escape)r(  Z
content_reZproperty_retemplaterG   rG   rH   _og_regexes8  s    

zInfoExtractor._og_regexesc                 C   s   dt |  S )Nz(?isx)<meta
                    (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
                    [^>]+?content=(["\'])(?P<content>.*?)\2r)  )r(  rG   rG   rH   _meta_regexC  s    zInfoExtractor._meta_regexc                 K   sv   t |ttfs|g}|d kr(d|d  }g }|D ]}|| | q0| j|||fdtji|}|d krnd S t|S )NzOpenGraph %sr   r  )	rk   rl   rm   extendr,  r  rL   DOTALLr5   )rE   r(  htmlr  kargsZ
og_regexesr  escapedrG   rG   rH   _og_search_propertyI  s    z!InfoExtractor._og_search_propertyc                 K   s   | j d|dfddi|S )Nimagezthumbnail URLr   Fr3  rE   r0  r1  rG   rG   rH   _og_search_thumbnailV  s    z"InfoExtractor._og_search_thumbnailc                 K   s   | j d|fddi|S )Nr  r   Fr5  r6  rG   rG   rH   _og_search_descriptionY  s    z$InfoExtractor._og_search_descriptionc                 K   s   | j d|f|S )Nr   r5  r6  rG   rG   rH   _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   )rE   r0  r  securer1  ZregexesrG   rG   rH   _og_search_video_url_  s    z"InfoExtractor._og_search_video_urlc                 K   s   | j d|f|S NrR   r5  r6  rG   rG   rH   _og_search_urle  s    zInfoExtractor._og_search_urlc                    sN   t |ttfs|g}|d kr$|d } j fdd|D ||f|dd|S )Nr   c                    s   g | ]}  |qS rG   )r-  )r   nrb   rG   rH   
<listcomp>n  s     z3InfoExtractor._html_search_meta.<locals>.<listcomp>r   )r   rV   )rk   rl   rm   r   )rE   r  r0  Zdisplay_namer   kwargsrG   rb   rH   _html_search_metah  s      zInfoExtractor._html_search_metac                 C   s   |  d|dS )Nz
dc.creatoruploaderrC  rE   r0  rG   rG   rH   _dc_search_uploaderq  s    z!InfoExtractor._dc_search_uploaderc                 C   s   t d|rdS dS )NzG(?ix)<meta\s+name="rating"\s+     content="RTA-5042-1996-1400-1577-RTA"   r   )rL   r   rF  rG   rG   rH   _rta_searcht  s
    zInfoExtractor._rta_searchc                 C   s2   |  d|}|sd S dddddd}|| S )Nratingr               )zsafe for kidsgeneralz14 yearsZmaturer   rC  rj   lower)rE   r0  rJ  RATING_TABLErG   rG   rH   _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   rH  )1true0falserP  )rE   r0  Zfamily_friendlyrR  rG   rG   rH   _family_friendly_search  s      z%InfoExtractor._family_friendly_searchc                 C   s   |  d|dS )Nztwitter:playerztwitter card playerrE  rF  rG   rG   rH   _twitter_search_player  s    z$InfoExtractor._twitter_search_playerc                 K   sd   | j t|dfddi|}|dt}|s:|tk	r6|S i S |tkrN|ddnd}| j||||dS )	NzJSON-LDrV   json_ldr   r   TF)r   expected_type)r  r'   rj   r   _json_ld)rE   r0  r   r[  rB  rZ  r   r   rG   rG   rH   _search_json_ld  s      zInfoExtractor._search_json_ldc              
      s  t |tr| j|||d}|s"i S i t |tttfs:S t |trJ|g}ddddddddd  fddfd	d
}|D ]}t |dtrtd|dr|d}|d k	r||krʈ  S |dkrt	|d}
|t|dt	|dd ds"|r"|d< |d}	t |	trl|	ddkrl
t	|	dt|	dd |dp|d}
t |
trJ|
ddkrJt	|
dd< n|dkr
t	|dt	|dt|dt|dd nP|d kr6
t|d!t	|d"t	|d#d$ n|d%krJ|| q|d&}t |trx|dd%krx||  qqtd'd(  D S ))Nr   commentZlikeZdislikeview)ZCommentActionZAgreeActionZDisagreeActionZ
LikeActionZDislikeActionZListenActionZWatchActionZ
ViewActionc                    s   |  d}t|tsd S |D ]}t|ts,q| ddkr<q| d}t|tsRqt| d}|d krjq  |dd }|sqd| } |d k	rq||< qd S )	NZinteractionStatistic@typeZInteractionCounterZinteractionTypeZuserInteractionCount/z%s_count)rj   rk   rl   dictr   r%   split)r~   Zinteraction_statisticZis_eZinteraction_typeZinteraction_countZ
count_kindZ	count_key)INTERACTION_TYPE_MAPr!  rG   rH   extract_interaction_statistic  s*    




z=InfoExtractor._json_ld.<locals>.extract_interaction_statisticc                    s   | d dkst t| dt| dt| dt| dpL| dt| dt| d	t| d
t| dt| dt| dt| dd  |  d S )Nra  VideoObjectZ
contentUrlr  r  ZthumbnailUrlZthumbnailURLdurationZ
uploadDateZcontentSizebitratewidthheightZinteractionCount)rR   r   r  	thumbnailri  	timestampfilesizetbrrk  rl  Z
view_count)	rU   updater<   rj   r5   r,   r7   r"   r%   )r~   )rg  r!  rG   rH   extract_video_object  s    z4InfoExtractor._json_ld.<locals>.extract_video_objectz@contextz^https?://schema.org/?$ra  )Z	TVEpisodeZEpisoder  ZepisodeNumberr  )Zepisodeepisode_numberr  r   ZpartOfSeason)ZTVSeasonZSeasonZCreativeWorkSeasonZseasonNumber)Zseasonseason_numberZpartOfSeriesZpartOfTVSeries)ZTVSeriesZSeriesZCreativeWorkSeriesseriesZMovieri  ZdateCreated)r   r  ri  rn  )ZArticleZNewsArticleZdatePublishedZheadlineZarticleBody)rn  r   r  rh  r;  c                 s   s"   | ]\}}|d k	r||fV  qd S r   rG   )r   kvrG   rG   rH   r    s      z)InfoExtractor._json_ld.<locals>.<genexpr>)rk   r   r   rl   rm   rd  rj   rL   rO   r5   rq  r%   r,   r7   r-   items)rE   rZ  r   r   r[  rr  r~   Z	item_typeZepisode_nameZpart_of_seasonZpart_of_seriesr;  rG   )rf  rg  r!  rH   r\    s    


"








zInfoExtractor._json_ldc                 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<!--(?:(?!<!--).)*-->r   z(?i)(<input[^>]+>)r   )ZhiddenZsubmitr  rT   value)rL   subfindallr    rj   )r0  Zhidden_inputsinputattrsr  ry  rG   rG   rH   _hidden_inputs  s    

zInfoExtractor._hidden_inputsc                 C   s$   | j d| |d| dd}| |S )Nz8(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>z%s formform)rV   )r  r~  )rE   Zform_idr0  r  rG   rG   rH   _form_hidden_inputs'  s      z!InfoExtractor._form_hidden_inputsc                    sl   |st d|D ]<}d|kr|dd k	r|dd k	r|d |d  |d< q fdd}|j|d d S )NzNo video formats foundrp  abrvbrc                    s  ddl m}  ds.d kr.| d  d< tttfrRt fddD S  d}|d kr~d} dd	kr~|d
8 } dpt }|dkrdn|dkrdnd} ddkr(|d8 }jjdrddddddg}nddddddg}d}z|	 d }W n t
k
r$   d}Y nX np ddkr@|d8 }jjdr\dddg}n
dddg}z|	 d }W n t
k
r   d}Y nX d}| dd k	r dnd d d k	rЈ d nd d!d k	r d!nd d"d k	r d"nd d#d k	r$ d#nd d$d k	r@ d$nd d%d k	r\ d%nd|| d&d k	r| d&nd| d'd k	r d'nd d(d k	r d(nd d)d k	r҈ d)nd d*d k	r d*nd+fS ),Nr   )r   extrR   c                 3   s6   | ].}  |d k	r  |n|dkr*dndV  qd S )N	format_idr   rc  rj   )r   fieldfrG   rH   r  >  s   zDInfoExtractor._sort_formats.<locals>._formats_key.<locals>.<genexpr>
preferencer   )f4ff4mg      ?protocol)httphttpsrtspg      gvcodecnone2   prefer_free_formatsaacmp3m4awebmoggopusrc  acodec(   flvmp4Zlanguage_preferenceZqualityrp  ro  r  rl  rk  r  fpsZfilesize_approxZsource_preferencer  r   )utilsr   rj   rk   rl   rm   r   rh   ri   indexr   )r  r   r  r  Zproto_preferenceZORDERZext_preferenceZaudio_ext_preferencefield_preferencerE   r  rH   _formats_key7  sf    


z1InfoExtractor._sort_formats.<locals>._formats_key)key)r   rj   sort)rE   formatsr  r  r  rG   r  rH   _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 )NrR   r  z%s video formatr;  )item)_is_valid_urlrj   r  r   rG   rH   <lambda>|  s    z.InfoExtractor._check_formats.<locals>.<lambda>)filter)rE   r  r   rG   r   rH   _check_formatsy  s
    zInfoExtractor._check_formatsc                 C   sH   t  }g }| D ](}|d |kr||d  || q|| d d < d S r>  )setaddappend)r  Zformat_urlsZunique_formatsr  rG   rG   rH   _remove_duplicate_formats  s    z'InfoExtractor._remove_duplicate_formatsr;  c                 C   sp   | j |dd}|ds&|ds&dS z| j||d| |d W dS  tk
rj   | d||f  Y d	S X d S )
Nhttp:)schemehttp://https://TzChecking %s URL)r   z%s: %s URL is invalid, skippingF)r   r   r   r   rr   )rE   rR   r   r  r   rG   rG   rH   r    s    
zInfoExtractor._is_valid_urlc                 C   s   | j jddrdS dS )zA Either "http:" or "https:", depending on the user's preferences prefer_insecureFr  zhttps:rh   ri   rj   rb   rG   rG   rH   http_scheme  s    zInfoExtractor.http_schemec                 C   s6   |d kr|S | dr.|d kr&|  }|| S |S d S )Nz//)r   r  )rE   rR   r  rG   rG   rH   r     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   r   )rr   timesleep)rE   r   r   msg_templater   rG   rG   rH   r     s
    
zInfoExtractor._sleepc                 C   s   t |  S r   r!   r  srG   rG   rH   r        zInfoExtractor.<lambda>c                 C   sB   | j ||dd||||	|
d	}|dkr(g S | j||||||||dS )NzDownloading f4m manifestzUnable to download f4m manifest)r   r   r   r   r   F)r  f4m_idr   r   m3u8_id)r   _parse_f4m_formats)rE   manifest_urlr   r  r  r   r   r  r   r   r   manifestrG   rG   rH   _extract_f4m_formats  s.               z"InfoExtractor._extract_f4m_formatsc                 C   s   t |  S r   r  r  rG   rG   rH   r    r  c	                 C   s  t |ts|sg S |d}	|	d k	rNd|	jkrN|	jdd }
|
 dkrNg S g }d}|d}|srd}|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}dtd |t|d kr$|n|g}|d krrd }|dkrT|jd}|d krj|jd}|srq|ds|dr|n$|pd|dd d d | }t|}|dkrJ| j||||||d}t|dkr<|d }||dp||dp||dp ||s0|d n||d! || qn(|d"krr|| j||d#|||d$ q|||||d k	rd%nd d|||||d&
 q|S )'Nz#{http://ns.adobe.com/f4m/1.0}pv-2.0;r   r   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  rj  rk  rl  -ZhrefrR   r  r  rb  rc  r  )r  r  r   r   r   rp  r  )rp  rk  rl  r  r  m3u8r  )r  r  r   r  )
r  rR   r  r  r  rp  rk  rl  r  r  )rk   r   findtextre  r  r{  r   r   r=   r>   r   	enumerater%   attribrj   joinr  r   r   r  r   rq  r.  _extract_m3u8_formatsr  )rE   r  r  r   r  r  r   r   r  	akamai_pvZplayerVerificationChallenger  Zmanifest_versionZmedia_nodesZmanifest_base_urlZbootstrap_infor  	mime_typeiZmedia_elrp  rk  rl  r  	media_urlr  f4m_formatsr  rG   rG   rH   r    s    


    &


$
    

    
z InfoExtractor._parse_f4m_formatsc                 C   s0   d td |dg||d|r$|d nddddS )	Nr  metar  d   iZmultiplezQuality selection URL)r  rR   r  r  r  
resolutionformat_note)r  r  )rE   m3u8_urlr  r  r  rG   rG   rH   _m3u8_meta_format'  s    zInfoExtractor._m3u8_meta_formatr  c              
   C   sV   | j |||pd|pd|	|||d}|dkr.g S |\}}| }| j|||||||
dS )NzDownloading m3u8 informationz#Failed to download m3u8 informationr   r   r   r   r   r   F)r  entry_protocolr  r  live)r   r   _parse_m3u8_formats)rE   r  r   r  r  r  r  r   r   r   r  r   r   r   r   m3u8_docr   rG   rG   rH   r  2  s.             z#InfoExtractor._extract_m3u8_formatsc              
      s  d|krg S t d|rg S g fddd|krF dgS i i  fdd}fd	d
}	| D ]}
|
dr~||
 q~| D ]
}
|
drt|
q|
ds|
 sqqtdpddd}g } r| |	 }|s0||r|nd|r$|nt	  |
 }d
|||td d}d}|rt d|}|rt|d|d< t|d|d< t d|d }|r| \}}t|dt|d }}|||d td}|| d}|rV|rV|dd krV|}|rV|d! d"rVd |d#< | d$}|r| }|d%= ||d& d'd(d)|d* | i qS )+Nz#EXT-X-FAXS-CM:z!#EXT-X-SESSION-KEY:.*?URI="skd://c                    s   t d| r| S t | S )N
^https?://)rL   rO   r   r:   )u)r  rG   rH   r  R  s    
z3InfoExtractor._parse_m3u8_formats.<locals>.<lambda>z#EXT-X-TARGETDURATION)rR   r  r  r  r  c           	         s   t | }|d|d|d  }}}|r6|r6|s:d S |g | |dkrXd S |d}|rg }||fD ]}|rt|| qtd|||d d}|d	krd
|d< | d S )NZTYPEzGROUP-IDNAME)VIDEOAUDIOURIr  LANGUAGE)r  rR   r  languager  r  r  r  r  r  )r.   rj   
setdefaultr  r  )	Zx_media_linemedia
media_typeZgroup_idr  r  r  rw  r  )r  r  
format_urlr  r  r  r  r  rG   rH   extract_medias  s0    "
	z8InfoExtractor._parse_m3u8_formats.<locals>.extract_mediac                     sL    d} | r| S  d}|s$d S   |}|s6|S |d }| dpJ|S )Nr  r  r   r  )stream_nameZstream_group_idZstream_groupZ	rendition)r  last_stream_infrG   rH   build_stream_name  s    


z<InfoExtractor._parse_m3u8_formats.<locals>.build_stream_namez#EXT-X-MEDIA:z#EXT-X-STREAM-INF:r   zAVERAGE-BANDWIDTHZ	BANDWIDTH  )scalez%dr  z
FRAME-RATE)r  rR   r  rp  r  r  r  r  Z
RESOLUTIONz!(?P<width>\d+)[xX](?P<height>\d+)rk  rl  z2audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?rR   )r  r  ZCODECSr  r  r  r   r  r  zPROGRESSIVE-URIr  r  zhls-zhttp-r  )r  r  rR   )rL   r   
splitlinesr   r.   r  r"   rj   r  r   r  intrV   r  rq  r+   copyr   )rE   r  r  r  r  r  r  r  r  r  linerp  r  r  r  r  r  r  r  r  codecsZaudio_group_idZaudio_groupZprogressive_uriZhttp_frG   )	r  r  r  r  r  r  r  r  r  rH   r  G  s    




 
&

 






z!InfoExtractor._parse_m3u8_formatsc                 C   sP   |s| S g }|  dD ].}|r&|dkr2|| q|d||f  qd|S )Nrb  .z{%s}%s)re  r  r  )r   	namespaceoutcrG   rG   rH   	_xpath_ns  s    zInfoExtractor._xpath_nsc                 C   sD   | j ||||d}|dkr&|r"tg S | |}| j|||||dS )Nr   r   Fr  
f4m_params)_download_smilrU   _parse_smil_namespace_parse_smil_formats)rE   smil_urlr   r   r  r   smilr  rG   rG   rH   _extract_smil_formats  s    
    z#InfoExtractor._extract_smil_formatsc                 C   s.   | j |||d}|dkri S | j||||dS )Nr^  F)r  )r  _parse_smil)rE   r   r   r   r  r  rG   rG   rH   _extract_smil_info  s    z InfoExtractor._extract_smil_infoc                 C   s   | j ||dd||dS )NzDownloading SMIL filezUnable to download SMIL filer  )r   )rE   r   r   r   r   rG   rG   rH   r    s        zInfoExtractor._download_smilc                 C   s   |  |}| j|||||d}| j||d}tjt|d }d }d }	d }
|| d|D ]^}|j	
d}|j	
d}|r^|sq^|s|dkr|}q^|	s|dkr|}	q^|
s^|d	kr^t|}
q^d
d || d|D }||p||	|
|||dS )Nr  )r  r   ./head/metar  r   r   )r  Zabstractdatec              	   S   sD   g | ]<}| d r| d| d t| dt| ddqS )srcr   rk  rl  )rT   rR   rk  rl  )rj   r%   )r   r4  rG   rG   rH   rA  3  s    
z-InfoExtractor._parse_smil.<locals>.<listcomp>z.//image)rT   r   r  upload_date
thumbnailsr  	subtitles)r  r  _parse_smil_subtitlesr   r   splitextr;   r{  r  r  rj   r6   )rE   r  r   r   r  r  r  r
  r   r  r  r  r  r   r	  rG   rG   rH   r    sF    
    
zInfoExtractor._parse_smilc                 C   s   | j d|jdd dS )Nz(?i)^{([^}]+)?}smil$r  r   )r  tag)rE   r  rG   rG   rH   r  D  s       z#InfoExtractor._parse_smil_namespacec                 C   s&  |}| | d|D ]$}|dp,|d}	|	r|	} q<qg }
d}d}d}g }| | d|| | d| }|D ]}|d}|rx||krqx|| t|dp|d	d
}t|dp|d}t|d}t|d}|d}|d}t|}|dp|}|dks0|dr|d7 }|
||dd|d krR|n| ||||d |rx|||\}}|
d ||d qx|dr|n
t	
||}| }|dks|dkr,| j|||pdddd}t|dkr |d7 }|d d|d kr|n| |||d  |
| qx|d!kr|}|sJd"d#d$}|d%|krZd&nd%7 }|t|7 }|
| j||d'dd( qx|d)kr|
| j||d*dd+ qxtd,|r|
| j||d-dd. qx|drx| ||rx|d7 }|
||p|pdd/|p| ||||d0 qx|
S )1Nr  baseZhttpBaser   z.//videoz.//audior  zsystem-bitrateZsystemBitrater  sizeZfileSizerk  rl  protor  streamerrtmpr   r  zrtmp-%d)rR   	play_pathr  r  rp  ro  rk  rl  rc  rR   r  r  r  r  hlsFr  r   zhls-%d)r  rp  rk  rl  r  z3.2.0zflowplayer-3.2.0.1)ZhdcoreZplugin?&hdsr  r   mpddashmpd_idr   z\.ism/[Mm]anifestZmss)ism_idr   zhttp-%d)rR   r  r  rp  ro  rk  rl  )r{  r  rj   r  r"   r%   r   r   rq  r   r:   r  r  r   r.  r   r  _extract_mpd_formatsrL   r   _extract_ism_formatsr  )rE   r  r   r   r  r  Ztransform_rtmp_urlr  r  br  Z
rtmp_countZ
http_countZ
m3u8_countZsrcsr  Zmediumr  rj  ro  rk  rl  r  r  Zsrc_extr  Zsrc_urlZm3u8_formatsf4m_urlrG   rG   rH   r  H  s    $





    

   
   


z!InfoExtractor._parse_smil_formatsenc                 C   s   g }i }t || d|D ]\}}|d}|r||kr>q|| |dpft|dpft|}	|dp|dp|dp|}
||
g ||	d q|S )	Nz.//textstreamr  r  r   ZsystemLanguageZsystemLanguageNamelang)rR   r  )r  r{  r  rj   r  r(   r   r  )rE   r  r  Zsubtitles_langr  r
  numZ
textstreamr  r  r%  rG   rG   rH   r    s    

 "
z#InfoExtractor._parse_smil_subtitlesc                 C   s6   | j ||dd|d}|dkr g S | j|||t|dS )NzDownloading xpsf playlistz Unable to download xspf manifestr^  F)xspf_urlxspf_base_url)r   _parse_xspfr   )rE   r'  r  r   xspfrG   rG   rH   _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:annotationr  z./xspf:imagerm  z./xspf:durationri  r  z./xspf:locationzs1:labelzs1:widthz	s1:height)rR   r  r  rk  rl  )rT   r   r  rm  ri  r  )
r{  r?   r>   r"   r:   r  r  rj   r%   r  )rE   Zxspf_docr  r'  r(  ZNS_MAPr
  trackr   r  rm  ri  r  locationr  rG   rG   rH   r)    s^            


zInfoExtractor._parse_xspfc              
   C   sb   | j |||pd|pd|||	|
d}|dkr.g S |\}}|d krBg S t| }| j|||||dS )NzDownloading MPD manifestzFailed to download MPD manifestr  F)r  mpd_base_urlformats_dictmpd_url)r   r   r   _parse_mpd_formats)rE   r1  r   r  r   r   r   r0  r   r   r   r   mpd_docr   r/  rG   rG   rH   r     s.           z"InfoExtractor._extract_mpd_formatsr   c           *         s  | ddkrg S jd|jdddfdd d	d
 } fdd}t| d}g }	| dD ]b}
t|
 dp~|}||
ddd}|
 dD ]*}||rq|||}| dD ] }||rq|j }||j |d }|dd }|dkrq|dkrd}|||
|fD ]<}|	 d}|dk	r(|j
| }td|r( qfq(|rtd|s|ds|ds|d7 }|| }| d| d}|	 d}t|dk	r|j dnd}t| d|rd |f n|t|t| d!t| d"td#t| d$t| d%|d&krR|ndd'| |t|d( d)}|t| d* |||fd+d,}d-kr|d-d.}|d/i d0< d1d2 }d3krd4kr|d4d5|d6krvd7krvdd8krBd9krBtd9 d: ttt| d8< fd;d<td= d8 d=  D d>< ng d>< d
dd= 		
fd?d@}td7 D ]f\}}| dApȈ

|dB |  	d7 	t| dCdD ]} 
7 
|  	d7 	q
7 
qnd3krd7krg }!d}"d: }#d7 D ]Z}t|dB |#}$t| dCdd D ]0} d3 |" }%|!||%|%d|$i |"d7 }"qnqH|!d>< njd3krg }!d9krtd9 d: ndd3 D ]*}&||&|&i}'r|'d< |!|' q|!d>< d>kr||p.||g dDdE d0krxd0 }(| dFsb|(|dF< |d> ||(|(i |d> d>  n||dF< | i  })|)| |	|) qƈdG|  qqqh|	S )Ha4  
        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
        r   Zdynamicz(?i)^{([^}]+)?}MPD$r  Nr   c                    s    |  S r   )r  )r   )r  rE   rG   rH   _add_ns  s    z1InfoExtractor._parse_mpd_formats.<locals>._add_nsc                 S   s   dS )NFrG   )elementrG   rG   rH   is_drm_protected  s    z:InfoExtractor._parse_mpd_formats.<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_numberr  rr   td)r:  r;  r9  ZstartNumberstart_number	timescaleri  segment_duration)r  r{  r  rj   r  r  float)sourceZsegment_timelineZs_er  r9  r<  r=  r>  r4  ms_inforG   rH   extract_common  s.    



z[InfoExtractor._parse_mpd_formats.<locals>.extract_multisegment_info.<locals>.extract_commonc                    s(   |   d}|d k	r$|jd d< d S )NZInitializationZ	sourceURLinitialization_url)r  r  )r@  initializationrA  rG   rH   extract_Initialization/  s    zcInfoExtractor._parse_mpd_formats.<locals>.extract_multisegment_info.<locals>.extract_InitializationZSegmentListZ
SegmentURLc                 S   s   g | ]}|j d  qS )r  )r  )r   segmentrG   rG   rH   rA  :  s     zWInfoExtractor._parse_mpd_formats.<locals>.extract_multisegment_info.<locals>.<listcomp>segment_urlsZSegmentTemplater  rE  )r  r  r{  rj   )	r5  Zms_parent_inforC  rF  Zsegment_listZsegment_urls_eZsegment_templater  rE  )r4  )rB  rH   extract_multisegment_info  s*    


zCInfoExtractor._parse_mpd_formats.<locals>.extract_multisegment_infoZmediaPresentationDurationZPeriodri  r   )r<  r=  ZAdaptationSetZRepresentationZmimeTyperb  r   r  r;  audior   ZBaseURLr  rT   r%  z/{http://youtube.com/yt/2012/10/10}contentLength	bandwidthz%s-%srk  rl  r  ZaudioSamplingRateZ	frameRate)mulundZzxxZmiszDASH %sZ_dash)r  r  r  rk  rl  rp  asrr  r  r  ro  	containerr  c                    s   |  }d}d}|D ]0}||7 }|dkr0| }q|dkr|s||7 }q| d }tdd| d|}td	d| d
|}| dd |S )Nr   F$%z$RepresentationID$z\$(%s)\$|z%(\1)dz\$(%s)%%([^$]+)\$z%(\1)\2z$$)r   rL   rz  r  )Ztemplate_nameZidentifiersZtmplr:  Zin_templater  )representation_idrepresentation_ms_inforG   rH   prepare_template  s    
z:InfoExtractor._parse_mpd_formats.<locals>.prepare_templaterE  )	BandwidthrW  rD  c                 S   s   t d| rdS dS )Nr  rR   r   )rL   rO   )r.  rG   rG   rH   location_key  s    z6InfoExtractor._parse_mpd_formats.<locals>.location_keyrH  r  )NumberrW  Timez%(Numberr  r8  r>  r=  c                    s"   g | ]}| d  diqS ))rY  rW  ri  rG   )r   segment_number)rL  media_location_keymedia_templater>  rG   rH   rA    s     z4InfoExtractor._parse_mpd_formats.<locals>.<listcomp>r<  	fragmentsc               	      s4    d } d  | dtd i d S )N)rZ  rW  rY  r^  ri  r=  )r  r"   )segment_url)rL  r\  r]  rU  	segment_dr[  segment_timerG   rH   add_segment_url  s      z9InfoExtractor._parse_mpd_formats.<locals>.add_segment_urlr:  r;  r9  http_dash_segments)rR   fragment_base_urlr^  r  rR   z%Unknown MIME type %s in DASH manifest)rj   r  r  r,   r{  r  r  rq  re  r  r  rL   rO   endswithr   r%   r(   r"   r+   r  mathceilr?  rw   r  r  r.  r   )*rE   r3  r  r/  r0  r1  r6  rI  Zmpd_durationr  ZperiodZperiod_durationZperiod_ms_infoZadaptation_setZadaption_set_ms_infoZrepresentationZrepresentation_attribr  r   r   r5  Z
base_url_er%  Zurl_elro  r  rV  Zinitialization_templaterX  rb  r&  r  r9  r^  Zsegment_indexr=  ri  Zsegment_urir_  fragmentrD  Z	full_inforG   )r4  rL  r\  r]  r  rT  rU  r`  r>  r[  ra  rE   rH   r2    s.   :











 

  

 


z InfoExtractor._parse_mpd_formatsc
              
   C   sH   | j |||pd|pd||||	d}
|
dkr.g S |
\}}| || |S )NzDownloading ISM manifestzFailed to download ISM manifestr  F)r   _parse_ism_formatsr   )rE   ism_urlr   r  r   r   r   r   r   r   r   ism_docr   rG   rG   rH   r!  	  s        z"InfoExtractor._extract_ism_formatsc                 C   s0  | ddks|ddk	r g S t|jd }t| dp>d}g }|dD ]}| d	}|d
krhqN|jd }	t| dp|}
| d}|dD ]}| d| ddkrdnd}|dkr| d|  qt|jd d }t| dp| d}t| dp| d}t| d}td|jd |	}t	
||}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
qdg }|rh|| |rx|| |t| |d&||||d'krd(nd)|||||d*krd+n||d'krd+n|d,|||
|pd|pd|| d-|t| d.d/t| d0d1t| d2d3d4
d5 qqN|S )6z
        Parse formats from ISM manifest.
        References:
         1. [MS-SSTR]: Smooth Streaming Protocol,
            https://msdn.microsoft.com/en-us/library/ff469518.aspx
        ZIsLiveTRUEZ
ProtectionNZDurationZ	TimeScalei ZStreamIndexZTyperJ  ZUrlNameZQualityLevelZFourCCZAudioTagZ255AACL)H264AVC1rn  z%s is not a supported codecZBitrater  ZMaxWidthZWidthZ	MaxHeightZHeightZSamplingRatez{[Bb]itrate}r  r   r  r:  r9  r   r;  ri  z{start[ _]time})rR   ri  r  r;  ZismvZismarK  r  ismZCodecPrivateDataZChannelsr   ZBitsPerSample   ZNALUnitLengthField   )
ri  r=  rk  rl  fourcccodec_private_datasampling_ratechannelsbits_per_samplenal_unit_length_field)r  rR   r  r  rk  rl  rp  rO  r  r  r  r^  _download_params)rj   r  r  r  r%   r{  r   rL   rz  r   r:   r  
IndexErrorrw   r  r   r  )rE   rk  rj  r  ri  r=  r  streamZstream_typeZurl_patternZstream_timescaler  r-  rt  rp  rk  rl  rv  Ztrack_url_patternr^  Zfragment_ctxZstream_fragmentsZstream_fragment_indexZstream_fragmentZfragment_repeatZnext_fragment_timer}   r  rG   rG   rH   ri  +	  s    


 





z InfoExtractor._parse_ism_formatsc           !   
      s  fdd dd }i f fdd	}	g }
dd t d	|D }|t d
| |D ]~\}}}g i d}t|}t|d}|r|	||\}}|d |  |d|d< |rt d|D ]B}t|ttd}|sq|d}|	|||\}}|rfdddD }td}tdpRtd}|r`|s|D ]8}t|}|szqd|p|d}|p|d}qd|D ]}t	|}|r qqd }|
|||dpdd |
|d  |d | q|d | qt d|D ]}t|}|d}|rH|dkr"t|d}|s`q"|dp|d p|d} |d! | g d" |i q"|d D ]}|d#i d$< q|d s|d! r`|
| q`|
S )%Nc                    s
   t  | S r   )r:   )Zitem_url)r   rG   rH   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  )rL   r   r  r+   r(   )r   Zctrmimetyper  r  rG   rG   rH   parse_content_type	  s    zDInfoExtractor._parse_html5_media_entries.<locals>.parse_content_typec              	      s    | }| dpt|}|dkr@d}j|ddd}n<|dkr`d}j|dd}nd}||d	krrd
nd dg}||fS )Nr  r  Fr  )r  r  r  r  r   r  r  TrK  r  )rR   r  )rj   r   r  r   )r  Zcur_media_typeZ	type_infofull_urlr  is_plain_urlr  )r}  m3u8_entry_protocolr  r  r  rE   r   rG   rH   _media_formats	  s4           z@InfoExtractor._parse_html5_media_entries.<locals>._media_formatsc                 S   s   g | ]\}}||d fqS )r   rG   )r   	media_tagr  rG   rG   rH   rA  	  s   z<InfoExtractor._parse_html5_media_entries.<locals>.<listcomp>z$(?s)(<(?:amp-)?(video|audio)[^>]*/>)zF(?s)(<(?P<tag>(?:amp-)?(?:video|audio))(?:\s+[^>]*)?>)(.*?)</(?P=tag)>)r  r
  r  r  Zposterrm  z<source[^>]+>)r  zdata-video-srczdata-srcr   c                    s$   g | ]}t  |r |qS rG   )r3   rj   )r   lbl)s_attrrG   rH   rA  	  s   )labelr   rk  rl  r   r  r   )rk  rl  rp  r  r   z<track[^>]+>kind)r
  captionsZsrclangr%  r
  rR   http_headersReferer)rL   r{  r.  r    r4   rj   r   r%   r/   r*   rq  r  r  )!rE   r   webpager   r  r  r  r  r  r  r
  Z
media_tagsr  r  Zmedia_contentZ
media_infoZmedia_attributesr  r}   r  Z
source_tagr  r  labelsrk  rl  r  r  rp  Z	track_tagZtrack_attributesr  r%  rG   )	r}  r   r  r  r  r  r  rE   r   rH   _parse_html5_media_entries	  s    
 


" 
z(InfoExtractor._parse_html5_media_entriesc              
   C   s   g }d}t dd|dd}|d}|r>t dd| |}d	|kr^|d
|krTdnd
| 7 }| j||ddd}|D ]}	|	d|i qt|| t dd|dd}
|d}|rt dd| |
}
|| j|
|ddddd |S )Nzhdcore=3.7.0z(https?://[^/]+)/i/z\1/z/z/master.m3u8z/manifest.f4mr  z(https?://)[^/]+z\1zhdcore=r  r  Fr  extra_param_to_segment_urlz(https?://[^/]+)/z/z\1/i/r  r  m3u8_nativer  )rL   rz  r   rj   r  rq  r.  r  )rE   r  r   Zhostsr  Zhdcore_signr#  Zhds_hostr  entryr  Zhls_hostrG   rG   rH   _extract_akamai_formats
  s<    
   

    z%InfoExtractor._extract_akamai_formatsr  c              
      s  t |jtdd|}td|}|d}dd|dp@d|f  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|rfd|kr| j|d|dd}	|	D ]h}
|
 }d|
d |
d f |d< |d= |d= ||d dd|
d  d!d"d"d# ||
|g qn0d$D ]*}||krj|d%||f ||d# qj|S )&Nz6/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)r   z1(?:(?:http|rtmp|rtsp)(?P<s>s)?:)?(?P<url>//[^?]+)rR   z%s%s:%sr  r  c                    s    d | f }r|d 7 }|S )N%s/%sz?%srG   )r  Zm_urlZhttp_base_urlr   rG   rH   r  #
  s    z:InfoExtractor._extract_wowza_formats.<locals>.manifest_urlr  zplaylist.m3u8r  r  Fr  r  zmanifest.f4mr  r  r  zmanifest.mpdr  z(?:/smil:|\.smil)r  zjwplayer.smilr^  r  r  r  zrtmp://zrtsp://r  r  r  )rR   r  r  )r  r  z%s:%s)r   urlparser   rL   rz  r   rV   r.  r  r  r   r  r  rq  r   r  )rE   rR   r   r  Zskip_protocolsr  Zurl_baser  r  Zrtmp_formatsZrtmp_formatZrtsp_formatr  rG   r  rH   _extract_wowza_formats
  sv     
        
 

z$InfoExtractor._extract_wowza_formatsc                 C   sR   t d|}|rNz| j|d||d}W n tk
r>   Y nX t|trN|S d S )Nzb(?s)jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)(?!</script>).*?\.setup\s*\((?P<options>[^)]+)\)options)r   r   )rL   r   r   rV   r   rk   rd  )rE   r  r   r   r  jwplayer_datarG   rG   rH   _find_jwplayer_dataO
  s    

z!InfoExtractor._find_jwplayer_datac                 O   s$   | j ||td}| j||f||S )N)r   )r  r&   _parse_jwplayer_data)rE   r  r   argsrB  r  rG   rG   rH   _extract_jwplayer_data^
  s       z$InfoExtractor._extract_jwplayer_datac                 C   s  d|krd|gi}g }t |d ts2|d g|d< |d D ]}	d|	krR|	g|	d< |p\|	d }
| j|	d |
||||d}i }|	d}|rt |tr|D ]t}t |tsq|d}|rt |tsq| dkrqt||d}|sq||d	pd
g 	d| 
|i q|
t|r$|	d n|	dt|	dt|| 
|	dt|	dt|dpp|	d|d}t|dkrtd|d d r|d|d d d n| | ||d< |	| q:t|dkr|d S | |S d S )Nr	  ZsourcesZmediaid)r   r  r  rtmp_paramsr   tracksr  )r  r
  filer  r$  rR   r   r  r4  Zpubdateri  )rT   r   r  rm  rn  ri  r
  r   z+^(?:http|//).*(?:youtube\.com|youtu\.be)/.+r   Zurl_transparent)r   rR   r  )rk   rl   _parse_jwplayer_formatsrj   rd  r   rQ  r:   r  r  r   r5   r   r%   r"   r   rL   r   rq  r  r  )rE   r  r   Zrequire_titler  r  r  r   r
  Z
video_dataZthis_video_idr  r
  r  r-  Z
track_kindZ	track_urlr  rG   rG   rH   r  d
  sl    

    


 
$


z"InfoExtractor._parse_jwplayer_datac                 C   s  g }g }|D ]}	t |	tsqt|| |	d}
|
r|
|krBq||
 |	dpXd}t|pht|
}|dksz|dkr|| j	|
|dd|dd	 q|d
ks|dkr|| j
|
||dd q|dkr|| j|
|dd q|ds|dkr
||
d|d qt|	d}|d krHt| jdt|	dp:ddd d}|
t|	d|t|	d|d}|
drd|d< td|
d}t|dkr|\}}}|||| d  |r|| || q|S )!Nr  r   r   r  r  r  r  F)r  r  r   r  r  r  r  r^  rK  )ogar  r  mpegvorbisr  )rR   r  r  rl  z^(\d{3,4})[pP]?(?:\b|$)r  r   rk  rj  )rR   rk  rl  rp  r  r  r  r  z((?:mp4|mp3|flv):)r      r  )rk   rd  r:   r   rj   r  r(   r   r.  r  r   r  r   r%   r  r   rL   re  r   rq  )rE   Zjwplayer_sources_datar   r  r  r  r   r  r  r@  Z
source_urlZsource_typer  rl  Za_formatZrtmp_url_partsZrtmp_urlr   r  rG   rG   rH   r  
  s    

 
    
   
  


    

z%InfoExtractor._parse_jwplayer_formatsc                 C   s    t j  }|d}|d | S )z% Generate the title for a live video z%Y-%m-%d %H:%Mr   )datetimenowstrftime)rE   r  r  Znow_strrG   rG   rH   _live_title
  s    

zInfoExtractor._live_titlec                 K   sX   t |f|}d|kr&tt||d  |d krTd||f }|rHt|n| j| |S )Nget_attr.Failed to extract %s: Could not parse value %r)r%   printgetattrr   rh   r   rE   rw  r  r   rB  r   r   rG   rG   rH   _int
  s    
zInfoExtractor._intc                 K   s>   t |f|}|d kr:d||f }|r.t|n| j| |S )Nr  )r"   r   rh   r   r  rG   rG   rH   _float
  s    
zInfoExtractor._floatrb  c
                 K   sD   t d||||d k	|d|d|d|||d d |	}| jj| d S )Nr   Tr  )r   Cookier   rh   	cookiejar
set_cookie)rE   domainr  ry  Zexpire_timeportr   r<  discardrestrB  cookierG   rG   rH   _set_cookie  s&                 zInfoExtractor._set_cookiec                 C   s&   t |}| jj| t|dS )zC Return a compat_cookies.SimpleCookie with the cookies for the url r  )r1   rh   r  add_cookie_headerr   SimpleCookie
get_header)rE   rR   reqrG   rG   rH   _get_cookies  s    zInfoExtractor._get_cookiesc                 C   sz   |j  D ]j\}}| dkr q
tjd dkr8|d}|d}td| |}|r
|	 \}}| 
|||  qvq
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-cookier   r  z
iso-8859-1r   z'%s=(.+?);.*?\b[Dd]omain=(.+?)(?:[,;]|$)N)r   rx  rQ  r   version_infor   r   rL   r   r  r  )rE   
url_handler  headercookiesZcookie_valuery  r  rG   rG   rH   _apply_first_set_cookie_header  s    

 z,InfoExtractor._apply_first_set_cookie_headerc                 c   s   t | dd }|r4t| dr,tdt| j |g}nt | dg }|D ]8}|sZ|ddrZqDt| jd td  |d< |V  qDd S )NZ_TEST_TESTSz%s has _TEST and _TESTSonly_matchingFIEr  )r  hasattrrU   r   r   rj   r   )rE   include_onlymatchingr:  ZtestsrG   rG   rH   get_testcases-  s    zInfoExtractor.get_testcasesc                 C   s^   d}| j ddD ]F}|dg r,|d d }t|di d|}|sN dS |pT|}q| S )z Test whether the extractor is generally suitable for the given
        age limit (i.e. pornographic sites are not, all others usually are) F)r  r	  r   	info_dict	age_limitT)r  rj   r   )rE   r  Zany_restrictedZtcZis_restrictedrG   rG   rH   is_suitable;  s     
zInfoExtractor.is_suitablec                 O   s.   | j jdds| j jdr*| j||S i S )NwritesubtitlesFlistsubtitles)rh   ri   rj   _get_subtitlesrE   r  rB  rG   rG   rH   extract_subtitlesJ  s
    zInfoExtractor.extract_subtitlesc                 O   s   t dd S N-This method must be implemented by subclassesNotImplementedErrorr  rG   rG   rH   r  P  s    zInfoExtractor._get_subtitlesc                    s6   t dd | D  t| }| fdd|D  |S )z\ Merge subtitle items for one language. Items with duplicated URLs
        will be dropped. c                 S   s   g | ]}|d  qS rR   rG   r   r  rG   rG   rH   rA  W  s     z7InfoExtractor._merge_subtitle_items.<locals>.<listcomp>c                    s   g | ]}|d   kr|qS r  rG   r  Z
list1_urlsrG   rH   rA  Y  s      )r  rl   r.  )Zsubtitle_list1Zsubtitle_list2retrG   r  rH   _merge_subtitle_itemsS  s    z#InfoExtractor._merge_subtitle_itemsc                 C   s2   t |}|D ] }| ||g || ||< q|S )z8 Merge two subtitle dictionaries, language by language. )rd  r  rj   )rQ   Zsubtitle_dict1Zsubtitle_dict2r  r%  rG   rG   rH   _merge_subtitles\  s    zInfoExtractor._merge_subtitlesc                 O   s.   | j jdds| j jdr*| j||S i S )NwriteautomaticsubFr  )rh   ri   rj   _get_automatic_captionsr  rG   rG   rH   extract_automatic_captionsd  s
    z(InfoExtractor.extract_automatic_captionsc                 O   s   t dd S r  r  r  rG   rG   rH   r  j  s    z%InfoExtractor._get_automatic_captionsc                 O   sB   | j jddr>|  d d k	s2| j jdd k	r>| j|| d S )Nmark_watchedFr   
cookiefile)rh   ri   rj   r$  _mark_watchedr  rG   rG   rH   r  m  s    zInfoExtractor.mark_watchedc                 O   s   t dd S r  r  r  rG   rG   rH   r  s  s    zInfoExtractor._mark_watchedc                 C   s"   i }| j jd}|r||d< |S )Ngeo_verification_proxyzYtdl-request-proxyr  )rE   r   r  rG   rG   rH   geo_verification_headersv  s
    z&InfoExtractor.geo_verification_headersc                 C   s$   t tj|ddd d S )Nrb  rc  r   )r   r   r   r  rstripre  r   rG   rG   rH   _generic_id}  s    zInfoExtractor._generic_idc                 C   s   t tjt|d S )Nr   )r   r   r   r  r;   r   rG   rG   rH   _generic_title  s    zInfoExtractor._generic_title)N)NNTNN)NT)NT)N)r   )r   N)NNN)NNNN)NNN)N)r  r   N)r%  )N)r:  T)NF)N)TN)N)N)N)NNN)Nr  NNF)N)TNN)TN)TN)N)NNN)Nr$  )T)NN)N)Nr  NN)NTNNNN)NNNNN)F)F)F)r   
__module____qualname____doc__rA   rh   rB   rn   r_   r`   rY   rI   classmethodrS   rX   r[   rc   r^   r   ry   rC   ra   rx   r   propertyr   staticmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   r   r   r   r   r   r   r   r  r  r   r  r   r"  r$  r'  r,  r-  r3  r7  r8  r9  r=  r?  rC  rG  rI  rS  rX  rY  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   r2  r!  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  r  r  rG   rG   rG   rH   r@   U   s    0





X


7

&       
;     
      

     
     


"



	k
L
	
    
 
e      
      
 3(_
)  &_y5       
D       
@
   


r@   c                   @   sD   e Zd ZdZedd Ze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 _MAX_RESULTS.
    c                 C   s
   d| j  S )Nz1%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)_SEARCH_KEYrZ   rG   rG   rH   _make_valid_url  s    z#SearchInfoExtractor._make_valid_urlc                 C   s   t |  |d k	S r   )rL   rO   r  rP   rG   rG   rH   rS     s    zSearchInfoExtractor.suitablec                 C   s   t |  |}|d kr$td| |d}|d}|dkrL| |dS |dkrb| || jS t|}|dkrtd||f n*|| jkr| j	d	| j
| j|f  | j}| ||S d S )
NzInvalid search query "%s"r   r   r   r   allr   z)invalid download number %s for query "%s"z,%s returns max %i results (you requested %i))rL   rO   r  r   rV   _get_n_resultsZ_MAX_RESULTSr  rh   r   r  )rE   r   r  r   r@  rG   rG   rH   rx     s     


z!SearchInfoExtractor._real_extractc                 C   s   t ddS )z-Get a specified number of results for a queryr  Nr  )rE   r   r@  rG   rG   rH   r    s    z"SearchInfoExtractor._get_n_resultsc                 C   s   | j S r   r  rb   rG   rG   rH   
SEARCH_KEY  s    zSearchInfoExtractor.SEARCH_KEYN)r   r  r  r  r  r  rS   rx   r  r  r  rG   rG   rG   rH   r    s   

r  )P
__future__r   r   r  r   r   r  r   ro   rL   r   r   r  rf  compatr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   Zdownloader.f4mr   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?   objectr@   r  rG   rG   rG   rH   <module>   sN   D/                      E