o
    5@Hh5                     @   s   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZ d dlmZ d dlmZ d dlmZ dZedG dd	 d	eZG d
d dZdS )    N)BytesIO)minidom)
deprecated)WebDriverExceptionzwebdriver_prefs.json/Addons must be added after starting the sessionc                   @   s   e Zd ZdZdS )AddonFormatErrorz4Exception for not well-formed add-on manifest files.N)__name__
__module____qualname____doc__ r   r   j/home/air/sanwanet/gpt-api/venv/lib/python3.10/site-packages/selenium/webdriver/firefox/firefox_profile.pyr   &   s    r   c                   @   s  e Zd ZdZd"ddZdd Zedd"ddZd	d
 Ze	dd Z
e	eddd Zejedd#ddZe	eddd Zejedd#ddZe	eddd Zejedd#ddZe	defddZdd Zedd$ddZedd d! ZdS )%FirefoxProfileNc                 C   s   i | _ |r'tjt d}tj||tdddd || _	t
| j	d d	S t | _	tjsTttjtjttdd}t|t_W d	   n1 sOw   Y  ttjd
 | _ tjd  D ]	\}}|| j |< qdd	S )a  Initialises a new instance of a Firefox Profile.

        :args:
         - profile_directory: Directory of profile that you want to use. If a
           directory is passed in it will be cloned and the cloned directory
           will be used by the driver when instantiated.
           This defaults to None and will create a new
           directory when object is created.
        zwebdriver-py-profilecopyzparent.locklockz.parentlock)ignore  utf-8encodingNmutablefrozen)_desired_preferencesospathjointempfilemkdtempshutilcopytreeignore_patterns_profile_dirchmodr   DEFAULT_PREFERENCESopendirname__file__WEBDRIVER_PREFERENCESjsonloadcopydeepcopyitems)selfprofile_directorynewprofdefault_prefskeyvaluer   r   r   __init__.   s(   

zFirefoxProfile.__init__c                 C   s   || j |< dS )z0Sets the preference that we want in the profile.Nr   )r,   r0   r1   r   r   r   set_preferenceM      zFirefoxProfile.set_preferencer   c                 C   s   |  | d S N)_install_extension)r,   	extensionr   r   r   add_extensionQ   r5   zFirefoxProfile.add_extensionc              
   C   s   t j| jd}t j|rt |d | | t|ddd"}| j	 D ]\}}|
d| dt| d q&W d	   d	S 1 sEw   Y  d	S )
z&Writes the desired user prefs to disk.zuser.jsi  wr   r   zuser_pref("z", z);
N)r   r   r   r    isfiler!   _read_existing_userjsr#   r   r+   writer'   dumps)r,   
user_prefsfr0   r1   r   r   r   update_preferencesU   s   
 "z!FirefoxProfile.update_preferencesc                 C      | j S )z8Gets the profile directory that is currently being used.)r    r,   r   r   r   r   a   s   zFirefoxProfile.pathz'The port is stored in the Service classc                 C   rB   )z+Gets the port that WebDriver is working on.)_portrC   r   r   r   portf   s   zFirefoxProfile.portreturnc              	   C   sj   t |ts	tdzt|}|dk s|dkrtdW n ttfy(   tdw || _| d| j dS )z0Sets the port that WebDriver will be running on.zPort needs to be an integer   i  z)Port number must be in the range 1..65535webdriver_firefox_portN)
isinstanceintr   
ValueError	TypeErrorrD   r4   )r,   rE   r   r   r   rE   l   s   
z8Allowing untrusted certs is toggled in the Options classc                 C   
   | j d S )N webdriver_accept_untrusted_certsr3   rC   r   r   r   accept_untrusted_certs{      
z%FirefoxProfile.accept_untrusted_certsc                 C   "   t |ts	td| d| d S )N%Please pass in a Boolean to this callrN   rI   boolr   r4   r,   r1   r   r   r   rO      s   
c                 C   rM   )N!webdriver_assume_untrusted_issuerr3   rC   r   r   r   assume_untrusted_cert_issuer   rP   z+FirefoxProfile.assume_untrusted_cert_issuerc                 C   rQ   )NrR   rV   rS   rU   r   r   r   rW      s   
c           	   	   C   s   | j r|   t }tj|dtjdd1}t| jd }t	| jD ]\}}}|D ]}tj
||}||||d  q)q"W d   n1 sHw   Y  t| dS )z]Updates preferences and creates a zipped, base64 encoded string of
        profile directory.r:   F)strict_timestampsrG   NzUTF-8)r   rA   r   zipfileZipFileZIP_DEFLATEDlenr   r   walkr   r=   base64	b64encodegetvaluedecode)	r,   fpzipped	path_rootbase_filesfylefilenamer   r   r   encoded   s   zFirefoxProfile.encodedc                 C   s   t d}t|dd<}|D ]0}||}zt|d| j|d< W q ty>   t	
d|d|d   Y qw W d   dS 1 sJw   Y  dS )zRReads existing preferences and adds them to desired preference
        dictionary.zuser_pref\("(.*)",\s(.*)\)r   r      rG   z5(skipping) failed to json.loads existing preference: N)recompiler#   searchr'   loadsgroupr   	Exceptionwarningswarn)r,   userjspref_patternr@   usrmatchesr   r   r   r<      s   

 "z$FirefoxProfile._read_existing_userjsTc              	   C   s  d}d}| drtjdtj|d  d}t|d}| D ]^}| dr>tj	tj
||s=ttj
|| q!tj	tjtj
||s[ttjtj
|| ||}ttj
||d}|| W d   n1 szw   Y  q!|}|}| |}	|	d	}
|
sJ d
| tj
| jd}tj
||
}|s|	d s|rtj|st| t|d t||d  ntj|stj||dd |rt| dS dS )zInstalls addon from a filepath, url or directory of addons in the
        profile.

        - path: url, absolute path to .xpi, or directory of addons
        - unpack: whether to unpack unless specified otherwise in the install.rdf
        Nz.xpi.)suffixr/wbidz!The addon id could not be found: 
extensionsunpackr   T)symlinks)endswithr   r   r   r   splitrY   rZ   namelistisdirr   makedirsr$   readr#   r=   _addon_detailsgetr    existsr!   r   r)   r   rmtree)r,   addonr   tmpdirxpifilecompressed_filenamedatar@   addon_detailsaddon_idextensions_dir
addon_pathr   r   r   r7      sD   





z!FirefoxProfile._install_extensionc              
   C   s  ddddd}dd }dd }dd	 }t j|s td
| zt|rWt|d"}d| v rB||dW  d   W S |d}W d   n1 sQw   Y  nWt j	|rt j
|d}t j|rt|dd}	||	 W  d   W S 1 sw   Y  tt j
|ddd}	|	 }W d   n1 sw   Y  ntd| W n ttfy }
 ztt|
t d d}
~
ww zft|}||d}||d}||d d}|s|dd}|jD ]}|j|d}||v r||||i q|ds.t|jjD ]}|j|}|j|d kr,|d|ji qW n tyG }
 ztt|
t d d}
~
ww t |d trZ|d ! dk|d< |dsdtd|S )a  Returns a dictionary of details about the addon.

        :param addon_path: path to the add-on directory or XPI

        Returns::

            {
                "id": "rainbow@colors.org",  # id of the addon
                "version": "1.4",  # version of the addon
                "name": "Rainbow",  # name of the addon
                "unpack": False,
            }  # whether to unpack the addon
        NF)r~   r   r   versionc                 S   s`   | j j}d}t|jD ]"}||j|kr-d||jv r-||jdd d } |S q|S )N :rG   )documentElement
attributesrangelengthitemr1   r   r   )docurlr   	namespaceir   r   r   get_namespace_id   s    z7FirefoxProfile._addon_details.<locals>.get_namespace_idc                 S   s6   g }| j D ]}|j|jkr||j qd| S )z(Retrieve the text value of a given node.r   )
childNodesnodeType	TEXT_NODEappendr   r   strip)elementrcnoder   r   r   get_text   s   
z/FirefoxProfile._addon_details.<locals>.get_textc                 S   sd   t | }z
|d d d }W n ty&   |d ddd |d  }Y nw ||d |d d	d
S )z[Extracts the details from the contents of a WebExtensions
            `manifest.json` file.applicationsgeckor~   r    r   @r   F)r~   r   r   r   )r'   ro   KeyErrorreplace)contentmanifestr~   r   r   r   parse_manifest_json  s   
 z:FirefoxProfile._addon_details.<locals>.parse_manifest_jsonzAdd-on path does not exist: r{   zmanifest.jsonzinstall.rdfr   r   z/Add-on path is neither an XPI nor a directory: rk   z#http://www.mozilla.org/2004/em-rdf#z+http://www.w3.org/1999/02/22-rdf-syntax-ns#Descriptionr   r   r~   r   truezAdd-on id could not be found.)"r   r   r   OSErrorrY   
is_zipfilerZ   r   r   r   r   r#   r   r   strsysexc_infor   parseStringgetElementsByTagNamer   r   nodeNamer   updater   r   r   r   r   r1   rq   rI   lower)r,   r   detailsr   r   r   r   r   manifest_json_filenamer@   er   emrdfdescriptionr   entryr   	attributer   r   r   r      st   

"





zFirefoxProfile._addon_detailsr6   )rF   N)T)r   r	   r
   r"   r2   r4   r   r9   rA   propertyr   rE   setterrO   rW   r   rj   r<   r7   r   r   r   r   r   r   +   sD    

.r   )r^   r)   r'   r   rl   r   r   r   rr   rY   ior   xml.domr   typing_extensionsr   selenium.common.exceptionsr   r&   rq   r   r   r   r   r   r   <module>   s$   