U
    5d;                     @   s   d Z ddlZddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZmZ dd	lmZmZ dd
lmZ ddlmZ eeZG dd dZdS )a/  
This module contains a container for stream manifest data.

A container object for the media stream (video only / audio only / video+audio
combined). This was referred to as ``Video`` in the legacy pytube version, but
has been renamed to accommodate DASH (which serves the audio and video
separately).
    N)ceil)datetime)BinaryIODictOptionalTuple)	HTTPError)parse_qs)extractrequest)safe_filenametarget_directory)get_format_profile)	Monostatec                	   @   s  e Zd ZdZeedddZeedddZ	eeddd	Z
eedd
dZeedddZeee ee f dddZeedddZeedddZeedddZeedddZeedddZeedddZeedddZeedddZd7ee ee ee eee ee ed#d$d%Zd8ee ee ee ed&d'd(Zeed)d*d+Zed d,d-d.Z e!eed/d0d1Z"ee d2d3d4Z#edd5d6Z$d S )9Streamz#Container for stream manifest data.)stream	monostatec                 C   sZ  || _ |d | _t|d | _t|d \| _| _| jd\| _	| _
|  \| _| _|d | _|d | _t|dd| _ttt|ddd	 d
 d
 | _ttt|ddd	 d	 d
 d
 | _ttt|ddd	 d	 d	 d
 d
 | _t| j}|d | _|d | _d|kr.|d | _|d | _|d | _|d | _|d | _dS )a  Construct a :class:`Stream <Stream>`.

        :param dict stream:
            The unscrambled data extracted from YouTube.
        :param dict monostate:
            Dictionary of data shared across all instances of
            :class:`Stream <Stream>`.
        urlitagZmimeType/is_otfbitrateZcontentLengthr        is_dashabrfps
resolutionis_3dis_hdris_liveN)
_monostater   intr   r
   Zmime_type_codecZ	mime_typecodecssplittypesubtypeparse_codecsZvideo_codecZaudio_codecr   r   get	_filesizefloatr   _filesize_kb_filesize_mb_filesize_gbr   r   r   r   r   r   r   r    )selfr   r   Zitag_profile r/   2/tmp/pip-unpacked-wheel-qmwpt_in/pytube/streams.py__init__   s2    


&*.






zStream.__init__)returnc                 C   s   t t| jd S )z:Whether the stream is DASH.

        :rtype: bool
           )boollenr#   r.   r/   r/   r0   is_adaptiveZ   s    zStream.is_adaptivec                 C   s   | j  S )zAWhether the stream is progressive.

        :rtype: bool
        )r7   r6   r/   r/   r0   is_progressived   s    zStream.is_progressivec                 C   s   | j p| jdkS )zFWhether the stream only contains audio.

        :rtype: bool
        audior8   r%   r6   r/   r/   r0   includes_audio_trackl   s    zStream.includes_audio_trackc                 C   s   | j p| jdkS )zFWhether the stream only contains video.

        :rtype: bool
        videor:   r6   r/   r/   r0   includes_video_trackt   s    zStream.includes_video_trackc                 C   sD   d}d}| j s| j\}}n"| jr,| jd }n| jr<| jd }||fS )a  Get the video/audio codecs from list of codecs.

        Parse a variable length sized list of codecs and returns a
        constant two element tuple, with the video codec as the first element
        and audio as the second. Returns None if one is not available
        (adaptive only).

        :rtype: tuple
        :returns:
            A two element tuple with audio and video codecs.

        Nr   )r7   r#   r=   r;   )r.   r<   r9   r/   r/   r0   r'   |   s    
zStream.parse_codecsc              
   C   s`   | j dkrZzt| j| _ W n< tk
rX } z|jdkr: t| j| _ W 5 d}~X Y nX | j S )zFile size of the media stream in bytes.

        :rtype: int
        :returns:
            Filesize (in bytes) of the stream.
        r     N)r)   r   filesizer   r   codeseq_filesizer.   er/   r/   r0   r?      s    

 zStream.filesizec              
   C   s   | j dkrz&ttt| jd d d | _ W nP tk
r } z2|jdkrN ttt| jd d d | _ W 5 d}~X Y nX | j S )zFile size of the media stream in kilobytes.

        :rtype: float
        :returns:
            Rounded filesize (in kilobytes) of the stream.
        r   r   r   r>   N)	r+   r*   r   r   r?   r   r   r@   rA   rB   r/   r/   r0   filesize_kb   s    
&
4zStream.filesize_kbc              
   C   s   | j dkrz*ttt| jd d d d | _ W nT tk
r } z6|jdkrR ttt| jd d d d | _ W 5 d}~X Y nX | j S )zFile size of the media stream in megabytes.

        :rtype: float
        :returns:
            Rounded filesize (in megabytes) of the stream.
        r   r   r   r>   N)	r,   r*   r   r   r?   r   r   r@   rA   rB   r/   r/   r0   filesize_mb   s    
*
8zStream.filesize_mbc              
   C   s   | j dkrz.ttt| jd d d d d | _ W nX tk
r } z:|jdkrV ttt| jd d d d d | _ W 5 d}~X Y nX | j S )zFile size of the media stream in gigabytes.

        :rtype: float
        :returns:
            Rounded filesize (in gigabytes) of the stream.
        r   r   r   r>   N)	r-   r*   r   r   r?   r   r   r@   rA   rB   r/   r/   r0   filesize_gb   s    
.
<zStream.filesize_gbc                 C   s   | j jp
dS )zbGet title of video

        :rtype: str
        :returns:
            Youtube video title
        zUnknown YouTube Video Title)r!   titler6   r/   r/   r0   rG      s    zStream.titlec                 C   s.   | j jr(| jr(d}t| j j| j | S | jS )zGet approximate filesize of the video

        Falls back to HTTP call if there is not sufficient information to approximate

        :rtype: int
        :returns: size of video in bytes
           )r!   durationr   r"   r?   )r.   Zbits_in_byter/   r/   r0   filesize_approx   s    	zStream.filesize_approxc                 C   s*   t | jdd d d }tt|S )N?   expirer   )r	   r   r$   r   utcfromtimestampr"   )r.   rM   r/   r/   r0   
expiration   s    zStream.expirationc                 C   s   t | j}| d| j S )zGenerate filename based on the video title.

        :rtype: str
        :returns:
            An os file system compatible filename.
        .)r   rG   r&   )r.   filenamer/   r/   r0   default_filename   s    
zStream.default_filenameNTr   )output_pathrQ   filename_prefixskip_existingtimeoutmax_retriesr2   c                 C   s  | j |||d}|r>| |r>td| d | | |S | j}td| j d|  t|d}	z6tj| j	||dD ]}
|t
|
8 }| |
|	| q|W n` tk
r } zB|jdkr tj| j	||dD ]}
|t
|
8 }| |
|	| qW 5 d	}~X Y nX W 5 Q R X | | |S )
a-  Write the media stream to disk.

        :param output_path:
            (optional) Output path for writing media file. If one is not
            specified, defaults to the current working directory.
        :type output_path: str or None
        :param filename:
            (optional) Output filename (stem only) for writing media file.
            If one is not specified, the default filename is used.
        :type filename: str or None
        :param filename_prefix:
            (optional) A string that will be prepended to the filename.
            For example a number in a playlist or the name of a series.
            If one is not specified, nothing will be prepended
            This is separate from filename so you can use the default
            filename but still add a prefix.
        :type filename_prefix: str or None
        :param skip_existing:
            (optional) Skip existing files, defaults to True
        :type skip_existing: bool
        :param timeout:
            (optional) Request timeout length in seconds. Uses system default.
        :type timeout: int
        :param max_retries:
            (optional) Number of retries to attempt after socket timeout. Defaults to 0.
        :type max_retries: int
        :returns:
            Path to the saved video
        :rtype: str

        )rQ   rS   rT   zfile z already exists, skippingzdownloading (z total bytes) file to wb)rV   rW   r>   N)get_file_pathexists_at_pathloggerdebugon_completer?   openr   r   r   r5   on_progressr   r@   Z
seq_stream)r.   rS   rQ   rT   rU   rV   rW   	file_pathbytes_remainingfhchunkrC   r/   r/   r0   download  s@    (



,
zStream.download)rQ   rS   rT   r2   c                 C   s,   |s
| j }|r| | }tjt||S N)rR   ospathjoinr   )r.   rQ   rS   rT   r/   r/   r0   rY   S  s
    zStream.get_file_path)r`   r2   c                 C   s   t j|ot j|| jkS re   )rf   rg   isfilegetsizer?   )r.   r`   r/   r/   r0   rZ   _  s    zStream.exists_at_path)bufferr2   c                 C   sN   | j }td| j  t| jD ]}|t|8 }| ||| q | d dS )zLWrite the media stream to buffer

        :rtype: io.BytesIO buffer
        z+downloading (%s total bytes) file to bufferN)	r?   r[   infor   r   r   r5   r_   r]   )r.   rk   ra   rc   r/   r/   r0   stream_to_buffere  s     zStream.stream_to_buffer)rc   file_handlerra   c                 C   s2   | | td| | jjr.| j| || dS )a  On progress callback function.

        This function writes the binary data to the file, then checks if an
        additional callback is defined in the monostate. This is exposed to
        allow things like displaying a progress bar.

        :param bytes chunk:
            Segment of media file binary data, not yet written to disk.
        :param file_handler:
            The file handle where the media is being written to.
        :type file_handler:
            :py:class:`io.BufferedWriter`
        :param int bytes_remaining:
            The delta between the total file size in bytes and amount already
            downloaded.

        :rtype: None

        zdownload remaining: %sN)writer[   r\   r!   r_   )r.   rc   rn   ra   r/   r/   r0   r_   v  s    
zStream.on_progress)r`   c                 C   s0   t d | jj}|r,t d| || | dS )zOn download complete handler function.

        :param file_path:
            The file handle where the media is being written to.
        :type file_path: str

        :rtype: None

        zdownload finishedzcalling on_complete callback %sN)r[   r\   r!   r]   )r.   r`   r]   r/   r/   r0   r]     s
    

zStream.on_completec                 C   sv   ddg}| j r@|ddg | js2|ddg qN|dg n|ddg |dd	g d
d|j| d dS )zPrintable object representation.

        :rtype: str
        :returns:
            A string representation of a :class:`Stream <Stream>` object.
        zitag="{s.itag}"zmime_type="{s.mime_type}"zres="{s.resolution}"zfps="{s.fps}fps"zvcodec="{s.video_codec}"zacodec="{s.audio_codec}"zabr="{s.abr}"z progressive="{s.is_progressive}"ztype="{s.type}"z	<Stream:  )s>)r=   extendr7   rh   format)r.   partsr/   r/   r0   __repr__  s    zStream.__repr__)NNNTNr   )NNN)%__name__
__module____qualname____doc__r   r   r1   propertyr4   r7   r8   r;   r=   r   r   strr'   r"   r?   r*   rD   rE   rF   rG   rJ   r   rO   rR   rd   rY   rZ   r   rm   bytesr_   r]   rv   r/   r/   r/   r0   r      sz    =		      S     r   )rz   loggingrf   mathr   r   typingr   r   r   r   urllib.errorr   urllib.parser	   Zpytuber
   r   Zpytube.helpersr   r   Zpytube.itagsr   Zpytube.monostater   	getLoggerrw   r[   r   r/   r/   r/   r0   <module>   s   
