U
    ¦y^¶9  ã                   @   sx   d dl mZ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m	Z	 ddl
mZmZmZmZmZmZ G dd„ deƒZdS )é    )ÚdivisionÚunicode_literalsNé   )Úcompat_os_name)ÚdecodeArgumentÚencodeFilenameÚerror_to_compat_strÚformat_bytesÚshell_quoteÚtimeconvertc                   @   s\  e Zd ZdZdZdZdd„ Zedd„ ƒZedd	„ ƒZ	ed
d„ ƒZ
edd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZedd„ ƒZdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ Zd2d3„ ZdKd5d6„Zd7d8„ Z d9d:„ Z!d;d<„ Z"d=d>„ Z#d?d@„ Z$dAdB„ Z%dCdD„ Z&dEdF„ Z'dGdH„ Z(dLdIdJ„Z)dS )MÚFileDownloadera6  File Downloader class.

    File downloader objects are the ones responsible of downloading the
    actual video file and writing it to disk.

    File downloaders accept a lot of parameters. In order not to saturate
    the object constructor with arguments, it receives a dictionary of
    options instead.

    Available options:

    verbose:            Print additional info to stdout.
    quiet:              Do not print messages to stdout.
    ratelimit:          Download speed limit, in bytes/sec.
    retries:            Number of times to retry for HTTP error 5xx
    buffersize:         Size of download buffer in bytes.
    noresizebuffer:     Do not automatically resize the download buffer.
    continuedl:         Try to continue downloads if possible.
    noprogress:         Do not print the progress bar.
    logtostderr:        Log messages to stderr instead of stdout.
    consoletitle:       Display progress in console window's titlebar.
    nopart:             Do not use temporary .part files.
    updatetime:         Use the Last-modified header to set output file timestamps.
    test:               Download only first bytes to test the downloader.
    min_filesize:       Skip files smaller than this size
    max_filesize:       Skip files larger than this size
    xattr_set_filesize: Set ytdl.filesize user xattribute with expected size.
    external_downloader_args:  A list of additional command-line arguments for the
                        external downloader.
    hls_use_mpegts:     Use the mpegts container for HLS videos.
    http_chunk_size:    Size of a chunk for chunk-based HTTP downloading. May be
                        useful for bypassing bandwidth throttling imposed by
                        a webserver (experimental)

    Subclasses of this one must re-define the real_download method.
    i(  Nc                 C   s"   || _ g | _|| _|  | j¡ dS )z6Create a FileDownloader object with the given options.N)ÚydlÚ_progress_hooksÚparamsÚadd_progress_hookÚreport_progress)Úselfr   r   © r   úOC:\Users\TaGoRe\Desktop\beinconnect-dl\binaries\youtube_dl\downloader\common.pyÚ__init__=   s    zFileDownloader.__init__c                 C   sN   t | dƒ\}}t |dƒ\}}|dkr(dS |dkr<d||f S d|||f S d S )Né<   éc   z--:--:--r   z	%02d:%02dz%02d:%02d:%02d)Údivmod)ZsecondsZminsZsecsZhoursr   r   r   Úformat_secondsD   s    zFileDownloader.format_secondsc                 C   s    |d krd S t | ƒt |ƒ d S )Ng      Y@©Úfloat)Úbyte_counterZdata_lenr   r   r   Úcalc_percentO   s    zFileDownloader.calc_percentc                 C   s   | d krdS dd|   S )Nz---.-%z%6sz%3.1f%%r   )Úpercentr   r   r   Úformat_percentU   s    zFileDownloader.format_percentc                 C   s\   |d krd S |d krt   ¡ }||  }|dks4|dk r8d S t|ƒ| }tt|ƒt|ƒ | ƒS ©Nr   çü©ñÒMbP?)Útimer   Úint)ÚstartÚnowÚtotalZcurrentÚdifÚrater   r   r   Úcalc_eta[   s    zFileDownloader.calc_etac                 C   s   | d krdS t  | ¡S )Nz--:--)r   r   )Úetar   r   r   Ú
format_etag   s    zFileDownloader.format_etac                 C   s(   ||  }|dks|dk rd S t |ƒ| S r    r   )r$   r%   Úbytesr'   r   r   r   Ú
calc_speedm   s    zFileDownloader.calc_speedc                 C   s    | d krdd S ddt | ƒ  S )Nz%10sz---b/sz%s/s)r	   )Úspeedr   r   r   Úformat_speedt   s    zFileDownloader.format_speedc                 C   s   | t dƒkrdS d|  S )NÚinfz%.0fr   )Úretriesr   r   r   Úformat_retriesz   s    zFileDownloader.format_retriesc                 C   sb   t |d dƒ}tt |d dƒdƒ}| dk r2t|ƒS ||  }||krJt|ƒS ||k rZt|ƒS t|ƒS )Ng       @g      ð?i  @ r!   )ÚmaxÚminr#   )Zelapsed_timer,   Znew_minZnew_maxr(   r   r   r   Úbest_block_size~   s    zFileDownloader.best_block_sizec                 C   sN   t  d| ¡}|dkrdS t| d¡ƒ}dd | d¡ ¡ ¡ }tt|| ƒƒS )z:Parse a string indicating a byte quantity into an integer.z"(?i)^(\d+(?:\.\d+)?)([kMGTPEZY]?)$Né   g      �@Z	bkmgtpezyr   )ÚreÚmatchr   ÚgroupÚindexÚlowerr#   Úround)ZbytestrZmatchobjÚnumberZ
multiplierr   r   r   Úparse_bytes‹   s    zFileDownloader.parse_bytesc                 O   s   | j j||Ž d S ©N©r   Ú	to_screen©r   ÚargsZkargsr   r   r   rA   •   s    zFileDownloader.to_screenc                 C   s   | j  |¡ d S r?   r@   ©r   Úmessager   r   r   Ú	to_stderr˜   s    zFileDownloader.to_stderrc                 C   s   | j  |¡ d S r?   )r   Úto_console_titlerD   r   r   r   rG   ›   s    zFileDownloader.to_console_titlec                 O   s   | j j||Ž d S r?   )r   ÚtroublerB   r   r   r   rH   ž   s    zFileDownloader.troublec                 O   s   | j j||Ž d S r?   )r   Úreport_warningrB   r   r   r   rI   ¡   s    zFileDownloader.report_warningc                 O   s   | j j||Ž d S r?   )r   Úreport_errorrB   r   r   r   rJ   ¤   s    zFileDownloader.report_errorc                 C   s~   | j  d¡}|dks|dkr dS |dkr0t ¡ }|| }|dkrDdS t|ƒ| }||krzt|ƒ| | }|dkrzt |¡ dS )z3Sleep if the download speed is over the rate limit.Ú	ratelimitNr   g        )r   Úgetr"   r   Úsleep)r   Z
start_timer%   r   Z
rate_limitÚelapsedr.   Z
sleep_timer   r   r   Ú	slow_down§   s    zFileDownloader.slow_downc                 C   sB   | j  dd¡s6|dks6tj t|ƒ¡r:tj t|ƒ¡s:|S |d S )z4Returns a temporary filename for the given filename.ÚnopartFú-ú.part)r   rL   ÚosÚpathÚexistsr   Úisfile©r   Úfilenamer   r   r   Ú	temp_name·   s    ÿÿzFileDownloader.temp_namec                 C   s    |  d¡r|d tdƒ … S |S )NrR   )ÚendswithÚlenrW   r   r   r   Úundo_temp_name¾   s    
zFileDownloader.undo_temp_namec                 C   s   |d S )Nz.ytdlr   rW   r   r   r   Úytdl_filenameÃ   s    zFileDownloader.ytdl_filenamec              
   C   sd   z&||krW d S t  t|ƒt|ƒ¡ W n8 ttfk
r^ } z|  dt|ƒ ¡ W 5 d }~X Y nX d S )Nzunable to rename file: %s)rS   Úrenamer   ÚIOErrorÚOSErrorrJ   r   )r   Zold_filenameZnew_filenameÚerrr   r   r   Ú
try_renameÆ   s    zFileDownloader.try_renamec                 C   s‚   |dkrdS t j t|ƒ¡s dS |}|dkr0dS t|ƒ}|dkrD|S |dkrPdS zt  |t ¡ |f¡ W n tk
r|   Y nX |S )z4Try to set the last-modified time of the given file.Nr   )rS   rT   rV   r   r   Úutimer"   Ú	Exception)r   rX   Zlast_modified_hdrZtimestrZfiletimer   r   r   Ú	try_utimeÎ   s"    zFileDownloader.try_utimec                 C   s   |   d| ¡ dS )zReport destination filename.z[download] Destination: N©rA   rW   r   r   r   Úreport_destinationã   s    z!FileDownloader.report_destinationFc                 C   sž   d| }| j  dd¡r"|  |¡ njtdkrft| ddƒ}|t|ƒkrV|d|t|ƒ  7 }t|ƒ| _d}ntj 	¡ rtd	nd}| j|| | d
� |  
d| ¡ d S )Nz[download] Úprogress_with_newlineFÚntÚ!_report_progress_prev_line_lengthr   ú úz[K)Zskip_eolzyoutube-dl )r   rL   rA   r   Úgetattrr[   rj   ÚsysÚstderrÚisattyrG   )r   ÚmsgÚis_last_lineZfullmsgZprev_lenZ
clear_liner   r   r   Ú_report_progress_statusç   s    ÿ
z&FileDownloader._report_progress_statusc                 C   sL  |d dkrŠ| j  dd¡r&|  d¡ ndd}| d¡d k	rPt|d ƒ|d< |d	7 }| d
¡d k	rx|  |d
 ¡|d< |d7 }| j|| dd� | j  d¡ršd S |d dkrªd S | d¡d k	rÌ|  |d ¡|d< nd|d< | d¡�r| d¡d k	�r|  d|d  |d  ¡|d< nd| d¡�rL| d¡d k	�rL|  d|d  |d  ¡|d< n(| d¡dk�rl|  d¡|d< nd|d< | d¡d k	�r˜|  |d ¡|d< nd|d< | d¡d k	�rÆt|d ƒ|d< d}nt| d¡d k	�rìt|d ƒ|d< d}nN| d¡d k	�r6t|d ƒ|d< | d
¡�r0|  |d
 ¡|d< d }nd!}nd"}|  || ¡ d S )#NÚstatusÚfinishedÚ
noprogressFz[download] Download completedz100%%Útotal_bytesZ_total_bytes_strz of %(_total_bytes_str)srN   Z_elapsed_strz in %(_elapsed_str)sT)rr   Zdownloadingr*   Z_eta_strzUnknown ETAZdownloaded_byteséd   Z_percent_strZtotal_bytes_estimater   z	Unknown %r.   Z
_speed_strzUnknown speedzK%(_percent_str)s of %(_total_bytes_str)s at %(_speed_str)s ETA %(_eta_str)sZ_total_bytes_estimate_strzU%(_percent_str)s of ~%(_total_bytes_estimate_str)s at %(_speed_str)s ETA %(_eta_str)sZ_downloaded_bytes_strz>%(_downloaded_bytes_str)s at %(_speed_str)s (%(_elapsed_str)s)z+%(_downloaded_bytes_str)s at %(_speed_str)sz5%(_percent_str)s % at %(_speed_str)s ETA %(_eta_str)s)	r   rL   rA   r	   r   rs   r+   r   r/   )r   ÚsZmsg_templater   r   r   r   ø   sZ     ÿ  zFileDownloader.report_progressc                 C   s   |   d| ¡ dS )z'Report attempt to resume at given byte.z'[download] Resuming download at byte %sNrf   )r   Z
resume_lenr   r   r   Úreport_resuming_byte4  s    z#FileDownloader.report_resuming_bytec                 C   s"   |   dt|ƒ||  |¡f ¡ dS )z&Report retry in case of HTTP error 5xxzD[download] Got server HTTP error: %s. Retrying (attempt %d of %s)...N)rA   r   r2   )r   ra   Úcountr1   r   r   r   Úreport_retry8  s
    ÿÿzFileDownloader.report_retryc                 C   s6   z|   d| ¡ W n tk
r0   |   d¡ Y nX dS )z.Report file has already been fully downloaded.z)[download] %s has already been downloadedz/[download] The file has already been downloadedN)rA   ÚUnicodeEncodeError)r   Ú	file_namer   r   r   Úreport_file_already_downloaded>  s    z-FileDownloader.report_file_already_downloadedc                 C   s   |   d¡ dS )z,Report it was impossible to resume download.z[download] Unable to resumeNrf   )r   r   r   r   Úreport_unable_to_resumeE  s    z&FileDownloader.report_unable_to_resumec                 C   sô   | j  dd¡otj t|ƒ¡}t|dƒs’| j  dd¡oTtj t|ƒ¡oT| j  dd¡ }|dkr’|sf|r’|  |¡ |  	|dtj 
t|ƒ¡d	œ¡ dS | j  d
¡}|rè| j  d|¡}t ||¡}|  d| ¡ rÒt|ƒnd|  ¡ t |¡ |  ||¡S )zpDownload to a filename using the info from info_dict
        Return True on success and False otherwise
        ÚnooverwritesFÚwriteÚ
continuedlTrP   rQ   ru   )rX   rt   rw   Úsleep_intervalÚmax_sleep_intervalz![download] Sleeping %s seconds...z%.2f)r   rL   rS   rT   rU   r   ÚhasattrrV   r   Ú_hook_progressÚgetsizeÚrandomÚuniformrA   Ú
is_integerr#   r"   rM   Úreal_download)r   rX   Ú	info_dictZnooverwrites_and_existsZcontinuedl_and_existsZmin_sleep_intervalr…   r„   r   r   r   ÚdownloadI  s:    þ
ÿý
ýþÿ
zFileDownloader.downloadc                 C   s   t dƒ‚dS )z.Real download process. Redefine in subclasses.z-This method must be implemented by subclassesN)ÚNotImplementedError)r   rX   r�   r   r   r   rŒ   p  s    zFileDownloader.real_downloadc                 C   s   | j D ]}||ƒ qd S r?   )r   )r   rt   Úphr   r   r   r‡   t  s    
zFileDownloader._hook_progressc                 C   s   | j  |¡ d S r?   )r   Úappend)r   r�   r   r   r   r   x  s    z FileDownloader.add_progress_hookc                 C   sR   | j  dd¡sd S dd„ |D ƒ}|d kr8tj |d ¡}|  d|t|ƒf ¡ d S )NÚverboseFc                 S   s   g | ]}t |ƒ‘qS r   )r   )Ú.0Úar   r   r   Ú
<listcomp>�  s     z-FileDownloader._debug_cmd.<locals>.<listcomp>r   z[debug] %s command line: %s)r   rL   rS   rT   ÚbasenamerA   r
   )r   rC   ZexeZstr_argsr   r   r   Ú
_debug_cmd}  s     ÿzFileDownloader._debug_cmd)F)N)*Ú__name__Ú
__module__Ú__qualname__Ú__doc__Z_TEST_FILE_SIZEr   r   Ústaticmethodr   r   r   r)   r+   r-   r/   r2   r5   r>   rA   rF   rG   rH   rI   rJ   rO   rY   r\   r]   rb   re   rg   rs   r   rz   r|   r   r€   rŽ   rŒ   r‡   r   r—   r   r   r   r   r      s`   %










	
<'r   )Ú
__future__r   r   rS   r7   rn   r"   r‰   Úcompatr   Úutilsr   r   r   r	   r
   r   Úobjectr   r   r   r   r   Ú<module>   s    
