
    'jK[              A       h   U 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 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 d dlZd dlZd dlmZmZ d d	lmZ d d
lmZ d dlmZ ddl m!Z!m"Z"m#Z# ddl$m%Z%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? eee@df         ee@         e@f         ZAeeBd<   ddddddZCdee@e@f         de@dee@ee@eDeEf         f         fdZFd\d ee         dee@e@f         fd!ZGd\dee@e@f         d ee         ddfd"ZHd#ed$e@deEfd%ZId&ee@ef         ded'         fd(ZJd)e@ded'         fd*ZKd\d+eeE         dee         fd,ZLd&ee@ef         d-e@ddfd.ZMd/eddfd0ZNd1eAddfd2ZOd3ee@ef         dee@ef         fd4ZPd5ee@ef         d6ee@ef         ddfd7ZQd5ee@ef         d8e@d#eddfd9ZRd&ee@ef         d:e@deEfd;ZSd&ee@ef         ddfd<ZT	 d\d=ed>ee;         defd?ZU	 d\d=ed>ee;         defd@ZVddddddddddddddddddddddddddddddAd&eee@ef                  d1eeA         dBeeE         dCeeE         dDeeE         dEeeE         dFeee@e@f                  dGeee@eEf                  dHeeeEeDf                  dIeee@ee@         f                  dJeee@                  dKeee@                  dLeeE         dMeee!                  dNee         dOeeeWeWf                  d/ee         dPeeW         d+eeE         dQeeE         dReee@ef                  dSeee@ef                  dTeee@e@f                  dUeeE         dVeee@                  dWeee@ee@eDeEf         f                  dXeeE         dYeeE         d>ee@         dZee@ef         dee@ef         f>d[ZXdS )]    N)environ)abspath)Path)pprint)randint	randrange)AnyDictListLiteralOptionalTupleUnioncast)FingerprintScreen)get_monitors)	TypeAlias)user_agent_parser   )DefaultAddonsadd_default_addonsconfirm_paths)	InvalidOSInvalidPropertyTypeNonFirefoxFingerprintUnknownProperty)from_browserforgegenerate_fingerprint)Proxy	public_ip
valid_ipv4
valid_ipv6)geoip_allowedget_geolocationhandle_locales)OS_NAMEget_pathinstalled_verstrlaunch_path)VirtualDisplay)LeakWarning)sample_webgl.ListOrString
   T)z"browser.sessionhistory.max_entriesz(browser.sessionhistory.max_total_viewerszbrowser.cache.memory.enablezbrowser.cache.disk_cache_sslz%browser.cache.disk.smart_size.enabled
config_mapuser_agent_osreturnc                 z   i }	 t          j        |           }nB# t           j        $ r0}t          d|            t	          j        d           Y d}~nd}~ww xY wt          dk    rdnd}|                    d          }t          dt          |          |          D ]`}||||z            }d	||z  dz    }		 |||	<   !# t          $ r3}t          d
|	 d|            t	          j        d           Y d}~Yd}~ww xY wt          dk    r2t          t          j                            d|                    }
|
|d<   |S )zB
    Gets a dictionary of environment variables for Camoufox.
    zError updating config: r   Nwini  i  zutf-8r   CAMOU_CONFIG_zError setting z: lin
fontconfigFONTCONFIG_PATH)orjsondumpsJSONEncodeErrorprintsysexitr'   decoderangelen	Exceptionr(   ospathjoin)r1   r2   env_varsupdated_config_datae
chunk_size
config_strichunkenv_namefontconfig_paths              R/home/ice/.hermes/hermes-agent/venv/lib/python3.11/site-packages/camoufox/utils.pyget_env_varsrQ   ,   s    46H$l:66!   +++,,,
 !E))uJ$++G44J1c*ooz22  1q:~-.:AOq#8::	!&HX 	 	 	2822q22333HQKKKKKKKK	 %"27<<m#L#LMM&5"#Os,    A&AA8B>>
C;)C66C;rE   c                    | rt          | j        dz            }nt          d          }t          |d          5 }t	          j        |                                          }ddd           n# 1 swxY w Y   d |D             S )z)
    Loads the properties.json file.
    zproperties.jsonrbNc                 ,    i | ]}|d          |d         S )propertytype ).0props     rP   
<dictcomp>z$_load_properties.<locals>.<dictcomp>X   s#    AAAtDd6lAAA    )strparentr(   openr:   loadsread)rE   	prop_filef	prop_dicts       rP   _load_propertiesrd   M   s      0&7788		.//		i		 +!L**	+ + + + + + + + + + + + + + + BAyAAAAs   'A--A14A1c                 "   t          |          }|                                 D ]i\  }}|                    |          }|st          d| d          t	          ||          s*t          d| d| dt          |          j                   jdS )z#
    Validates the config map.
    rE   zUnknown property z
 in configzInvalid type for property z. Expected z, got N)rd   itemsgetr   validate_typer   rV   __name__)r1   rE   property_typeskeyvalueexpected_types         rP   validate_configro   [   s     &4000N &&((  
U&**3// 	G!"Ec"E"E"EFFFUM22 	%hShh]hhRVW\R]R]Rfhh  	 r[   rm   rn   c                 >   |dk    rt          | t                    S |dk    r>t          | t                    p(t          | t                    o|                                 S |dk    rDt          | t                    p(t          | t                    o|                                 o| dk    S |dk    rt          | t          t          f          S |dk    rt          | t
                    S |dk    rt          | t                    S |dk    rt          | t                    S d	S )
z*
    Validates the type of the value.
    r\   intuintr   doubleboolarraydictF)
isinstancer\   rq   float
is_integerrt   listrv   )rm   rn   s     rP   ri   ri   l   s    %%%%	%		%%%Z*UE*B*B*YuGWGWGYGYZ	&	 	 uc""Wz%'?'?'VEDTDTDVDVqj	 
(	"	"%%...	&	 	 %&&&	'	!	!%&&&	&	 	 %&&&ur[   config)macr5   r7   c                 d    |                      d          rt          | d                   S t          S )zs
    Gets the OS from the config if the user agent is set,
    otherwise returns the OS of the current system.
    znavigator.userAgent)rh   determine_ua_osr'   r{   s    rP   get_target_osr      s2    
 zz'(( >v&;<===Nr[   
user_agentc                     t          j        |                               d          }|st          d          |                    d          rdS |                    d          rdS dS )z7
    Determines the OS from the user agent string.
    familyz&Could not determine OS from user agentMacr|   Windowsr5   r7   )r   ParseOSrh   
ValueError
startswith)r   	parsed_uas     rP   r~   r~      su     ")*5599(CCI CABBBE"" uI&& u5r[   headlessc                     | du rdS 	 t                      }n# t          $ r Y dS w xY w|sdS t          |d           }t          |j        |j                  S )zT
    Determines a sane viewport size for Camoufox if being ran in headful mode.
    FNc                      | j         | j        z  S N)widthheight)ms    rP   <lambda>z!get_screen_cons.<locals>.<lambda>   s    !'AH*< r[   )rl   )	max_width
max_height)r   rC   maxr   r   r   )r   monitorsmonitors      rP   get_screen_consr      s     5t>>   tt t ( < <===GGMgnEEEEs    
%%	target_osc                    t          t          j                            t          j                            t
                    d          d          5 }t          j        |                                          |         }ddd           n# 1 swxY w Y   d| v r4t          j
        || d         z                                             | d<   dS || d<   dS )z.
    Updates the fonts for the target OS.
    z
fonts.jsonrS   Nfonts)r^   rD   rE   rF   dirname__file__r:   r_   r`   npuniquetolist)r{   r   rb   r   s       rP   update_fontsr      s     
bgll27??844lCCT	J	J 2aQVVXX&&y12 2 2 2 2 2 2 2 2 2 2 2 2 2 2 &)EF7O$;<<CCEEwws   -B

BBfingerprintc                     t          j        | j        j                                      dd          }|dk    rt          d| d          t          j        dd           dS )	z
    Asserts that the passed BrowserForge fingerprint is a valid Firefox fingerprint.
    and warns the user that passing their own fingerprint is not recommended.
    r   zNon-FirefoxFirefox"z" fingerprints are not supported in Camoufox. Using fingerprints from a browser other than Firefox WILL lead to detection. If this is intentional, pass `i_know_what_im_doing=True`.custom_fingerprintFN)r   ParseUserAgent	navigator	userAgentrh   r   r,   warn)r   browser_names     rP   check_custom_fingerprintr      s     %3K4I4STTXX- L y  #H H H H
 
 	
 )511111r[   rD   c                     t          | t                    s| D ]}t          |           dS  | j                    st	          d|  d          | dvrt	          d|  d          dS )z+
    Checks if the target OS is valid.
    NzOS values must be lowercase: '')windowsmacoslinuxz#Camoufox does not support the OS: ')rw   r\   check_valid_osislowerr   )rD   os_names     rP   r   r      s     b#  	$ 	$G7####2:<< @>>>>???	...CbCCCDDD /.r[   datac                     | d= | d= | S )zB
    Gets the launch options from the locals of the function.
    
playwrightpersistent_contextrW   )r   s    rP   _clean_localsr      s     	\!"Kr[   targetsourcec                 L    |                                 D ]\  }}|| vr|| |<   dS )z
    Merges new keys/values from the source dictionary into the target dictionary.
    Given that the key does not exist in the target dictionary.
    N)rg   )r   r   rl   rm   s       rP   
merge_intor      s>    
 llnn    
UfF3K   r[   rl   c                     || vr|| |<   dS dS )zz
    Sets a new key/value into the target dictionary.
    Given that the key does not exist in the target dictionary.
    NrW   )r   rl   rm   s      rP   set_intor      s$    
 &s r[   
propertiesc                 r    |D ]2d         dv rt          fd| D                       r dS +| v r dS 3dS )z2
    Checks if a domain is set in the config.
    r0   ).:c              3   B   K   | ]}|                               V  d S r   )r   )rX   rl   rY   s     rP   	<genexpr>z is_domain_set.<locals>.<genexpr>  s/      ::C3>>$''::::::r[   TF)any)r{   r   rY   s     @rP   is_domain_setr      sp       8z!!::::6::::: tt v~~tt 5r[   c                    t          | dddd          rt          j        dd           t          | dd          rt          j        d	d           t          | d
          rt          j        dd           t          | d          rt          j        dd           t          | ddd          rt          j        dd           dS dS )zg
    Warns the user if they are manually setting properties that Camoufox already sets internally.
    znavigator.languageznavigator.languageszheaders.Accept-Languagezlocale:localeFzgeolocation:timezonegeolocationzheaders.User-Agentz	header-uaz
navigator.r   zscreen.zwindow.zdocument.body.viewportN)r   r,   r   r   s    rP   warn_manual_configr     s    
 $&;=VXa  * 	5)))V^Z88 /...V122 -e,,,V\** -e,,,VY	3CDD ,U+++++, ,r[   browservirtual_displayc                 j   K   s| S | j         dt          dt          ffd}|| _         | _        | S )zC
    Attaches the virtual display to the async browser cleanup
    argskwargsc                  X   K    | i | d {V  r                                  d S d S r   killr   r   _closer   s     rP   	new_closez"async_attach_vd.<locals>.new_close0  sX      fd%f%%%%%%%%% 	#  """""	# 	#r[   closer	   _virtual_displayr   r   r   r   s    ` @rP   async_attach_vdr   %  se        ]F#s #c # # # # # # #
 GM.GNr[   c                 f    s| S | j         dt          dt          ffd}|| _         | _        | S )zB
    Attaches the virtual display to the sync browser cleanup
    r   r   c                  H     | i | r                                  d S d S r   r   r   s     rP   r   z!sync_attach_vd.<locals>.new_closeF  sB     	#  """""	# 	#r[   r   r   s    ` @rP   sync_attach_vdr   ;  sa      ]F# # # # # # # # #
 GM.GNr[   )r{   rD   block_imagesblock_webrtcblock_webgldisable_coopwebgl_configgeoiphumanizer   addonsr   custom_fonts_onlyexclude_addonsscreenwindowr   
ff_versionr   main_world_evalexecutable_pathfirefox_user_prefsproxyenable_cacher   envi_know_what_im_doingdebugr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   launch_optionsc                 *
   | i } |d}|
g }
|g }|i }|d}|d}|Dt          t          t          t          t          t          t
          f         f         t                    }t          |t                    rt          t          |                    }|r||d<   |st          |            |rt          |           n|rt          d          t          |
|           |
rt          |
           |
| d<   |r%t          |          }t          j        d|           n(t#                                          dd          d	         }|&t'          |pt)          |pd|v           ||
          }n|st+          |           t-          | t/          ||                     t1          |           }t3          | dt5          dd                     |r|| d<   |r+d	|d<   |rt          j        d           nt          d          t7          | |           t3          | dt9          d	d                     |rt;                       |du r<|r,t=          t?          d0i |                                           }nt=                      }|sFtC          |          rt3          | d|           d|d<   n tE          |          rt3          | d|           tG          |          } | $                    | %                                           n>|r<d|&                    dd          vr$tO          | d          st          j        d           |	rtQ          |	|            |r>t3          | dd           t          |tR          t          f          rt3          | d|           |rt3          | dd           |rt          j        d|           d |d!<   |rd|d"<   |rt          j        d#|           d|d$<   |s|*                    d%d          du rd|d&<   t          j        d'|           nW|rtW          |g|R  }!ntW          |          }!|!*                    d(          }"t-          | |!           t-          ||"dd)           t-          | t9          d*d+          dd,           |rt-          |tX                     |rt[          d-           t]          |            t_          | |.           i ta          | |          |}#|rt          |          }ntc                      }|||#|||d/||ni S )1a  
    Launches a new browser instance for Camoufox.
    Accepts all Playwright Firefox launch options, along with the following:

    Parameters:
        config (Optional[Dict[str, Any]]):
            Camoufox properties to use. (read https://github.com/daijro/camoufox/blob/main/README.md)
        os (Optional[ListOrString]):
            Operating system to use for the fingerprint generation.
            Can be "windows", "macos", "linux", or a list to randomly choose from.
            Default: ["windows", "macos", "linux"]
        block_images (Optional[bool]):
            Whether to block all images.
        block_webrtc (Optional[bool]):
            Whether to block WebRTC entirely.
        block_webgl (Optional[bool]):
            Whether to block WebGL. To prevent leaks, only use this for special cases.
        disable_coop (Optional[bool]):
            Disables the Cross-Origin-Opener-Policy, allowing elements in cross-origin iframes,
            such as the Turnstile checkbox, to be clicked.
        geoip (Optional[Union[str, bool]]):
            Calculate longitude, latitude, timezone, country, & locale based on the IP address.
            Pass the target IP address to use, or `True` to find the IP address automatically.
        humanize (Optional[Union[bool, float]]):
            Humanize the cursor movement.
            Takes either `True`, or the MAX duration in seconds of the cursor movement.
            The cursor typically takes up to 1.5 seconds to move across the window.
        locale (Optional[Union[str, List[str]]]):
            Locale(s) to use in Camoufox. The first listed locale will be used for the Intl API.
        addons (Optional[List[str]]):
            List of Firefox addons to use.
        fonts (Optional[List[str]]):
            Fonts to load into Camoufox (in addition to the default fonts for the target `os`).
            Takes a list of font family names that are installed on the system.
        custom_fonts_only (Optional[bool]):
            If enabled, OS-specific system fonts will be not be passed to Camoufox.
        exclude_addons (Optional[List[DefaultAddons]]):
            Default addons to exclude. Passed as a list of camoufox.DefaultAddons enums.
        screen (Optional[Screen]):
            Constrains the screen dimensions of the generated fingerprint.
            Takes a browserforge.fingerprints.Screen instance.
        window (Optional[Tuple[int, int]]):
            Set a fixed window size instead of generating a random one
        fingerprint (Optional[Fingerprint]):
            Use a custom BrowserForge fingerprint. Note: Not all values will be implemented.
            If not provided, a random fingerprint will be generated based on the provided
            `os` & `screen` constraints.
        ff_version (Optional[int]):
            Firefox version to use. Defaults to the current Camoufox version.
            To prevent leaks, only use this for special cases.
        headless (Optional[bool]):
            Whether to run the browser in headless mode. Defaults to False.
            Note: If you are running linux, passing headless='virtual' to Camoufox & AsyncCamoufox
            will use Xvfb.
        main_world_eval (Optional[bool]):
            Whether to enable running scripts in the main world.
            To use this, prepend "mw:" to the script: page.evaluate("mw:" + script).
        executable_path (Optional[Union[str, Path]]):
            Custom Camoufox browser executable path.
        firefox_user_prefs (Optional[Dict[str, Any]]):
            Firefox user preferences to set.
        proxy (Optional[Dict[str, str]]):
            Proxy to use for the browser.
            Note: If geoip is True, a request will be sent through this proxy to find the target IP.
        enable_cache (Optional[bool]):
            Cache previous pages, requests, etc (uses more memory).
        args (Optional[List[str]]):
            Arguments to pass to the browser.
        env (Optional[Dict[str, Union[str, float, bool]]]):
            Environment variables to set.
        debug (Optional[bool]):
            Prints the config being sent to Camoufox.
        virtual_display (Optional[str]):
            Virtual display number. Ex: ':99'. This is handled by Camoufox & AsyncCamoufox.
        webgl_config (Optional[Tuple[str, str]]):
            Use a specific WebGL vendor/renderer pair. Passed as a tuple of (vendor, renderer).
        **launch_options (Dict[str, Any]):
            Additional Firefox launch options.
    NFDISPLAYz&OS must be set when using webgl_configr   r   r   r   r   )r   r   rD   zwindow.history.length   r   zgfx.bundled-fonts.activater   z@No custom fonts were passed, but `custom_fonts_only` is enabled.zfonts:spacing_seedi?Tzwebrtc:ipv4znetwork.dns.disableIPv6zwebrtc:ipv6	localhostserver r   proxy_without_geoipr   zhumanize:maxTimeallowMainWorldr      zpermissions.default.imagezmedia.peerconnection.enabledr   z.browser.tabs.remote.useCrossOriginOpenerPolicyallow_webglzwebgl.disabledr   webGl2Enabled)zwebgl.enable-webgl2zwebgl.force-enabledi2   )zcanvas:aaOffsetzcanvas:aaCapOffsetz[DEBUG] Config:rf   )r   r   r   r   r   r   rW   )2r   r
   r\   r   rx   rt   r   rw   r   r   r   r   r   r   r   r,   r   r)   splitr   r   r   r   r   r   r   r   r   r   r$   r!   r    	as_stringr"   r#   r%   update	as_configrh   r   r&   rq   popr-   CACHE_PREFSr=   r   ro   rQ   r*   )$r{   rD   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   ff_version_strr   r   webgl_fpenable_webgl2rG   s$                                       rP   r   r   Q  sv   b ~ ~|! !#$
{4U3t#3445w??/3'' 9w7788  )(I   #6""" 
 Cr 
 CABBB v~...  "f!x  =Z';<<<<)++11#q99!< *J_X-Ic9IJJ
 
 
 $ 	2$[111 +~66  
 f%%I V,i1oo>>>   w 	(;<78 	a01111 _```VY''' V)71m+D+DEEE  0D== $!%..%..":":"<"<==!  	7%   7666@D"#<==E"" 7666%e,,k++--....
 	0uyy26666fm44 7 	.///  'vv&&&  ;T***he-- 	;V/:::  1)4000  <)=>>>:;67 C=B9: U)=>>>OTKL  
n((==FF/3+,(<====  	/#I====HH#I..H _55 	68$$$'4'+ 	
 	
 	
 &sB//"&	
 	
    4%{333     v F1111
vy
)
)
H
  (o..%-- +0  ,7>>R r[   r   )YrD   r>   r   os.pathr   pathlibr   r   randomr   r   typingr	   r
   r   r   r   r   r   r   numpyr   r:   browserforge.fingerprintsr   r   
screeninfor   typing_extensionsr   	ua_parserr   r   r   r   r   
exceptionsr   r   r   r   fingerprintsr   r   ipr    r!   r"   r#   r   r$   r%   r&   pkgmanr'   r(   r)   r*   virtdisplayr+   warningsr,   webglr-   r\   r.   __annotations__r  rx   rt   rQ   rd   ro   ri   r   r~   r   r   r   r   r   r   r   r   r   r   r   rq   r   rW   r[   rP   <module>r     s   					 



                         % % % % % % % % I I I I I I I I I I I I I I I I I I I I      9 9 9 9 9 9 9 9 # # # # # # ' ' ' ' ' ' ' ' ' ' ' ' D D D D D D D D D D            B A A A A A A A 8 8 8 8 8 8 8 8 8 8 8 8 B B B B B B B B B B D D D D D D D D D D D D ' ' ' ' ' ' ! ! ! ! ! !      c3hcC ?@i @ @ @ +-02#'$(-1 S#X/2	#uS%%&
&'   BB B8D> BT#s(^ B B B B S#X htn PT    " S T    0$sCx. W5H-I     0C(D    F Fhtn F8H F F F F$ c3h  C  D        2+ 2$ 2 2 2 2&E| E E E E E S#X 4S>     tCH~  tCH~  $        T#s(^ # c d    cN 
   &,tCH~ ,$ , , , ,0 ?C #+N#;   . ?C #+N#;   0 (,!%#'#'"&#'.2(,-1.2"&!%(,48#(,)- $#&*2637&*#' $8<+/ %)=E E ET#s(^$E 	E 4.	E
 4.E $E 4.E 5c?+E E#t)$%E uT5[)*E U3S	>*+E T#YE DIE  ~E T-01E  V!E" U38_%#E$ +&%E& 'E( tn)E* d^+E, eCI./-E. !c3h0/E0 DcN#1E2 4.3E4 49
5E6 
$sE#ud"2334	57E8 #4.9E: D>;E< c]=E> 38n?E@ 
#s(^AE E E E E Er[   