U
    ¦y^ø  ã                   @   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mZmZ ddl	m
Z
mZmZmZmZmZ dd„ Zdd	„ ZG d
d„ deƒZdS )é    )Úunicode_literalsNé   )Úcompat_urlparseÚcompat_kwargs)Úcheck_executableÚencodeArgumentÚExtractorErrorÚget_exe_versionÚis_outdated_versionÚstd_headersc                 C   s¾   | j | jdœ}| jr| j|d< | jr.| j|d< | jr>| j|d< | jd k	rR| j|d< | j	d k	rf| j	|d< | j
d k	rz| j
|d< z*|  d¡sš|  d	¡sš|  d
¡r¢d|d	< W n tk
r¸   Y nX |S )N)ÚnameÚvalueÚportÚdomainÚpathÚexpiresÚsecureÚdiscardÚhttpOnlyÚhttponlyÚHttpOnlyT)r   r   Úport_specifiedr   Údomain_specifiedr   Úpath_specifiedr   r   r   r   Úhas_nonstandard_attrÚ	TypeError)ÚcookieZcookie_dict© r   úPC:\Users\TaGoRe\Desktop\beinconnect-dl\binaries\youtube_dl\extractor\openload.pyÚcookie_to_dict   s2    þ









ÿþr   c                 C   s   dd„ | D ƒS )Nc                 S   s   g | ]}t |ƒ‘qS r   )r   )Ú.0r   r   r   r   Ú
<listcomp>3   s     z&cookie_jar_to_list.<locals>.<listcomp>r   )Z
cookie_jarr   r   r   Úcookie_jar_to_list2   s    r"   c                   @   sb   e Zd ZdZdZdddgZedd„ ƒZdd
d„Zdd„ Z	dd„ Z
dd„ Zddddi dfdd„ZdS )ÚPhantomJSwrapperz=PhantomJS wrapper class

    This class is experimental.
    aï  
        phantom.onError = function(msg, trace) {{
          var msgStack = ['PHANTOM ERROR: ' + msg];
          if(trace && trace.length) {{
            msgStack.push('TRACE:');
            trace.forEach(function(t) {{
              msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
                + (t.function ? ' (in function ' + t.function +')' : ''));
            }});
          }}
          console.error(msgStack.join('\n'));
          phantom.exit(1);
        }};
        var page = require('webpage').create();
        var fs = require('fs');
        var read = {{ mode: 'r', charset: 'utf-8' }};
        var write = {{ mode: 'w', charset: 'utf-8' }};
        JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
          phantom.addCookie(x);
        }});
        page.settings.resourceTimeout = {timeout};
        page.settings.userAgent = "{ua}";
        page.onLoadStarted = function() {{
          page.evaluate(function() {{
            delete window._phantom;
            delete window.callPhantom;
          }});
        }};
        var saveAndExit = function() {{
          fs.write("{html}", page.content, write);
          fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
          phantom.exit();
        }};
        page.onLoadFinished = function(status) {{
          if(page.url === "") {{
            page.setContent(fs.read("{html}", read), "{url}");
          }}
          else {{
            {jscode}
          }}
        }};
        page.open("");
    ÚscriptÚhtmlÚcookiesc                   C   s   t ddd�S )NÚ	phantomjsz	([0-9.]+))Ú
version_re)r	   r   r   r   r   Ú_versionj   s    zPhantomJSwrapper._versionNé'  c                 C   sŒ   i | _ tddgƒ| _| js&tddd�‚|| _|rT|  ¡ }t||ƒrT| jj d| ¡ d|i| _	| j
D ]"}tjdd	�}| ¡  || j |< qdd S )
Nr'   z-vzMPhantomJS executable not found in PATH, download it from http://phantomjs.orgT)ÚexpectedzaYour copy of PhantomJS is outdated, update it to version %s or newer if you encounter any errors.ÚtimeoutF)Údelete)Ú
_TMP_FILESr   Úexer   Ú	extractorr)   r
   Ú_downloaderÚreport_warningÚoptionsÚ_TMP_FILE_NAMESÚtempfileÚNamedTemporaryFileÚclose)Úselfr0   Úrequired_versionr,   Úversionr   Útmpr   r   r   Ú__init__n   s,    þ
ÿÿ ÿ
zPhantomJSwrapper.__init__c                 C   sB   | j D ]6}zt | j| j¡ W q tttfk
r:   Y qX qd S )N)r4   ÚosÚremover.   r   ÚIOErrorÚOSErrorÚKeyError)r8   r   r   r   r   Ú__del__ˆ   s
    
zPhantomJSwrapper.__del__c              	   C   sx   t | jjjƒ}|D ],}d|kr&d|d< d|krt |¡j|d< qt| jd j	dƒ�}| 
t |¡ d¡¡ W 5 Q R X d S )Nr   ú/r   r&   Úwbúutf-8)r"   r0   r1   Ú	cookiejarr   ÚurlparseÚnetlocÚopenr.   r   ÚwriteÚjsonÚdumpsÚencode)r8   Úurlr&   r   Úfr   r   r   Ú_save_cookies�   s    zPhantomJSwrapper._save_cookiesc              	   C   s~   t | jd jdƒ�}t | ¡  d¡¡}W 5 Q R X |D ]B}|d dkrRdd i|d< d|krf|d |d	< | jjf t	|ƒŽ q6d S )
Nr&   ÚrbrE   r   Tr   ÚrestZexpiryÚexpire_time)
rI   r.   r   rK   ÚloadsÚreadÚdecoder0   Ú_set_cookier   )r8   rO   r&   r   r   r   r   Ú_load_cookies™   s    zPhantomJSwrapper._load_cookieszExecuting JS on webpageúsaveAndExit();c              	   C   sº  d|krt dƒ‚|s(| jj||||d�}t| jd jdƒ�}| | d¡¡ W 5 Q R X |  |¡ | j	}	||	d< | 
d¡p~td }
|
 d	d
¡|	d< ||	d< | jD ]$}| j| j dd¡ d	d
¡|	|< qžt| jd jdƒ� }| | jjf |	Ž d¡¡ W 5 Q R X |dk�r| j d|f ¡ n| j d||f ¡ tj| jd| jd jgtjtjd�}| ¡ \}}|jdk�rzt dt|ƒ ƒ‚t| jd jdƒ�}| ¡  d¡}W 5 Q R X |  ¡  |t|ƒfS )a	  
        Downloads webpage (if needed) and executes JS

        Params:
            url: website url
            html: optional, html code of website
            video_id: video id
            note: optional, displayed when downloading webpage
            note2: optional, displayed when executing JS
            headers: custom http headers
            jscode: code to be executed when page is loaded

        Returns tuple with:
            * downloaded website (after JS execution)
            * anything you print with `console.log` (but not inside `page.execute`!)

        In most cases you don't need to add any `jscode`.
        It is executed in `page.onLoadFinished`.
        `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
        It is possible to wait for some element on the webpage, for example:
            var check = function() {
              var elementFound = page.evaluate(function() {
                return document.querySelector('#b.done') !== null;
              });
              if(elementFound)
                saveAndExit();
              else
                window.setTimeout(check, 500);
            }

            page.evaluate(function(){
              document.querySelector('#a').click();
            });
            check();
        rY   z&`saveAndExit();` not found in `jscode`)ÚnoteÚheadersr%   rD   rE   rN   z
User-Agentú"z\"ÚuaÚjscodeú\z\\r$   Nz%sz%s: %sz--ssl-protocol=any)ÚstdoutÚstderrr   zExecuting JS failed
:rQ   )r   r0   Ú_download_webpagerI   r.   r   rJ   rM   rP   r3   Úgetr   Úreplacer4   Ú	_TEMPLATEÚformatÚ	to_screenÚ
subprocessÚPopenr/   ÚPIPEÚcommunicateÚ
returncoder   rU   rV   rX   )r8   rN   r%   Úvideo_idrZ   Znote2r[   r^   rO   ZreplacesÚ
user_agentÚxÚpÚoutÚerrr   r   r   rc   £   sH    $

"$
 
þ ý
ÿzPhantomJSwrapper.get)Nr*   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__re   r4   Ústaticmethodr)   r<   rB   rP   rX   rc   r   r   r   r   r#   6   s   ,




r#   )Ú
__future__r   rK   r=   rh   r5   Úcompatr   r   Úutilsr   r   r   r	   r
   r   r   r"   Úobjectr#   r   r   r   r   Ú<module>   s    
