
    Zf+I                       d Z ddlm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 ddlm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 dd
lmZ  ej2                  d      Zej6                  j9                  d      ZdZ ed       G d d             Z G d d      Z  e        Z! G d d      Z" ee!jF                        	 	 d	 	 	 	 	 	 	 dd       Z$ ee!jJ                        d        Z% G d d      Z&ddZ'y)aZ  `tldextract` accurately separates a URL's subdomain, domain, and public suffix.

It does this via the Public Suffix List (PSL).

    >>> import tldextract

    >>> tldextract.extract('http://forums.news.cnn.com/')
    ExtractResult(subdomain='forums.news', domain='cnn', suffix='com', is_private=False)

    >>> tldextract.extract('http://forums.bbc.co.uk/') # United Kingdom
    ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk', is_private=False)

    >>> tldextract.extract('http://www.worldbank.org.kg/') # Kyrgyzstan
    ExtractResult(subdomain='www', domain='worldbank', suffix='org.kg', is_private=False)

Note subdomain and suffix are _optional_. Not all URL-like inputs have a
subdomain or a valid suffix.

    >>> tldextract.extract('google.com')
    ExtractResult(subdomain='', domain='google', suffix='com', is_private=False)

    >>> tldextract.extract('google.notavalidsuffix')
    ExtractResult(subdomain='google', domain='notavalidsuffix', suffix='', is_private=False)

    >>> tldextract.extract('http://127.0.0.1:8080/deployed/')
    ExtractResult(subdomain='', domain='127.0.0.1', suffix='', is_private=False)

To rejoin the original hostname, if it was indeed a valid, registered hostname:

    >>> ext = tldextract.extract('http://forums.bbc.co.uk')
    >>> ext.registered_domain
    'bbc.co.uk'
    >>> ext.fqdn
    'forums.bbc.co.uk'
    )annotationsN)
CollectionSequence)	dataclass)wraps   )	DiskCacheget_cache_dir)lenient_netloclooks_like_iplooks_like_ipv6)get_suffix_lists
tldextractTLDEXTRACT_CACHE_TIMEOUT)z4https://publicsuffix.org/list/public_suffix_list.datzQhttps://raw.githubusercontent.com/publicsuffix/list/master/public_suffix_list.datT)orderc                      e Zd ZU dZded<   ded<   ded<   ded<   edd       Zedd	       Zedd
       Zedd       Z	y)ExtractResultzA URL's extracted subdomain, domain, and suffix.

    Also contains metadata, like a flag that indicates if the URL has a private suffix.
    str	subdomaindomainsuffixbool
is_privatec                j    | j                   r'| j                  r| j                   d| j                    S y)zJoins the domain and suffix fields with a dot, if they're both set.

        >>> extract('http://forums.bbc.co.uk').registered_domain
        'bbc.co.uk'
        >>> extract('http://localhost:8080').registered_domain
        ''
        . )r   r   selfs    5lib/python3.12/site-packages/tldextract/tldextract.pyregistered_domainzExtractResult.registered_domainL   s-     ;;4;;kk]!DKK=11    c                    | j                   rQ| j                  s| j                  r9dj                  d | j                  | j                  | j                   fD              S y)zReturns a Fully Qualified Domain Name, if there is a proper domain/suffix.

        >>> extract('http://forums.bbc.co.uk/path/to/file').fqdn
        'forums.bbc.co.uk'
        >>> extract('http://localhost:8080').fqdn
        ''
        r   c              3  &   K   | ]	  }|s|  y wN ).0is     r   	<genexpr>z%ExtractResult.fqdn.<locals>.<genexpr>c   s     W!UVAWs   r   )r   r   r   joinr   r   s    r   fqdnzExtractResult.fqdnY   sB     ;;DKK4??88WT[['QWWWr!   c                    | j                   r9| j                  s-| j                  s!t        | j                         r| j                   S y)a  Returns the ipv4 if that is what the presented domain/url is.

        >>> extract('http://127.0.0.1/path/to/file').ipv4
        '127.0.0.1'
        >>> extract('http://127.0.0.1.1/path/to/file').ipv4
        ''
        >>> extract('http://256.1.1.1').ipv4
        ''
        r   )r   r   r   r   r   s    r   ipv4zExtractResult.ipv4f   s1     KK[[DNNdkk*;;r!   c                    d}t        | j                        |k\  rX| j                  d   dk(  rF| j                  d   dk(  r4| j                  s(| j                  s| j                  dd }t	        |      r|S y)a  Returns the ipv6 if that is what the presented domain/url is.

        >>> extract('http://[aBcD:ef01:2345:6789:aBcD:ef01:127.0.0.1]/path/to/file').ipv6
        'aBcD:ef01:2345:6789:aBcD:ef01:127.0.0.1'
        >>> extract('http://[aBcD:ef01:2345:6789:aBcD:ef01:127.0.0.1.1]/path/to/file').ipv6
        ''
        >>> extract('http://[aBcD:ef01:2345:6789:aBcD:ef01:256.0.0.1]').ipv6
        ''
           r   []r   r   )lenr   r   r   r   )r   min_num_ipv6_charsdebracketeds      r   ipv6zExtractResult.ipv6y   sj      22A#%B3&[[DNN++a+K{+""r!   N)returnr   )
__name__
__module____qualname____doc____annotations__propertyr    r*   r,   r5   r%   r!   r   r   r   @   sl    
 NKK
 
 
 
  $  r!   r   c                      e Zd ZdZ e       edddef	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 ddZ		 	 d	 	 	 	 	 	 	 dd	Z
	 d	 	 	 	 	 	 	 dd
Z	 d	 	 	 	 	 ddZeddd       Z	 d	 	 	 ddZy)
TLDExtractzOA callable for extracting, subdomain, domain, and suffix components from a URL.TFr%   c                $   |xs d}t        d |D              | _        || _        | j                  s|s| j                  st        d      || _        || _        d| _        t        |t              rt        |      n|| _
        t        |      | _        y)a  Construct a callable for extracting subdomain, domain, and suffix components from a URL.

        Upon calling it, it first checks for a JSON in `cache_dir`. By default,
        the `cache_dir` will live in the tldextract directory. You can disable
        the caching functionality of this module by setting `cache_dir` to `None`.

        If the cached version does not exist (such as on the first run), HTTP request the URLs in
        `suffix_list_urls` in order, until one returns public suffix list data. To disable HTTP
        requests, set this to an empty sequence.

        The default list of URLs point to the latest version of the Mozilla Public Suffix List and
        its mirror, but any similar document could be specified. Local files can be specified by
        using the `file://` protocol. (See `urllib2` documentation.)

        If there is no cached version loaded and no data is found from the `suffix_list_urls`,
        the module will fall back to the included TLD set snapshot. If you do not want
        this behavior, you may set `fallback_to_snapshot` to False, and an exception will be
        raised instead.

        The Public Suffix List includes a list of "private domains" as TLDs,
        such as blogspot.com. These do not fit `tldextract`'s definition of a
        suffix, so these domains are excluded by default. If you'd like them
        included instead, set `include_psl_private_domains` to True.

        You can pass additional suffixes in `extra_suffixes` argument without changing list URL

        cache_fetch_timeout is passed unmodified to the underlying request object
        per the requests documentation here:
        http://docs.python-requests.org/en/master/user/advanced/#timeouts

        cache_fetch_timeout can also be set to a single value with the
        environment variable TLDEXTRACT_CACHE_TIMEOUT, like so:

        TLDEXTRACT_CACHE_TIMEOUT="1.2"

        When set this way, the same timeout value will be used for both connect
        and read timeouts
        r%   c              3  ^   K   | ]%  }|j                         s|j                          ' y wr$   )strip)r&   urls     r   r(   z&TLDExtract.__init__.<locals>.<genexpr>   s#      &
syy{CIIK&
s   --zThe arguments you have provided disable all ways for tldextract to obtain data. Please provide a suffix list data, a cache_dir, or set `fallback_to_snapshot` to `True`.N)tuplesuffix_list_urlsfallback_to_snapshot
ValueErrorinclude_psl_private_domainsextra_suffixes
_extractor
isinstancer   floatcache_fetch_timeoutr	   _cache)r   	cache_dirrD   rE   rG   rH   rL   s          r   __init__zTLDExtract.__init__   s    ^ ,1r % &
#3&
 !
 %9!%%d6O6O;  ,G(,@D -s3 %&$ 	 
  	*r!   Nc                *    | j                  |||      S )zAlias for `extract_str`.session)extract_strr   rB   rG   rR   s       r   __call__zTLDExtract.__call__   s     %@'RRr!   c                <    | j                  t        |      ||      S )a  Take a string URL and splits it into its subdomain, domain, and suffix components.

        I.e. its effective TLD, gTLD, ccTLD, etc. components.

        >>> extractor = TLDExtract()
        >>> extractor.extract_str('http://forums.news.cnn.com/')
        ExtractResult(subdomain='forums.news', domain='cnn', suffix='com', is_private=False)
        >>> extractor.extract_str('http://forums.bbc.co.uk/')
        ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk', is_private=False)

        Allows configuring the HTTP request via the optional `session`
        parameter. For example, if you need to use a HTTP proxy. See also
        `requests.Session`.

        >>> import requests
        >>> session = requests.Session()
        >>> # customize your session here
        >>> with session:
        ...     extractor.extract_str("http://forums.news.cnn.com/", session=session)
        ExtractResult(subdomain='forums.news', domain='cnn', suffix='com', is_private=False)
        rQ   )_extract_netlocr   rT   s       r   rS   zTLDExtract.extract_str   s)    6 ##3!<g $ 
 	
r!   c                >    | j                  |j                  ||      S )a  Take the output of urllib.parse URL parsing methods and further splits the parsed URL.

        Splits the parsed URL into its subdomain, domain, and suffix
        components, i.e. its effective TLD, gTLD, ccTLD, etc. components.

        This method is like `extract_str` but faster, as the string's domain
        name has already been parsed.

        >>> extractor = TLDExtract()
        >>> extractor.extract_urllib(urllib.parse.urlsplit('http://forums.news.cnn.com/'))
        ExtractResult(subdomain='forums.news', domain='cnn', suffix='com', is_private=False)
        >>> extractor.extract_urllib(urllib.parse.urlsplit('http://forums.bbc.co.uk/'))
        ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk', is_private=False)
        rQ   )rW   netlocrT   s       r   extract_urllibzTLDExtract.extract_urllib  s(    ( ##JJ3W $ 
 	
r!   c                j   |j                  dd      j                  dd      j                  dd      }d}t        |      |k\  r-|d   dk(  r%|d   d	k(  rt        |d
d       rt        d|dd      S |j	                  d      }| j                  |      j                  ||      \  }}d}	|t        |      cxk(  r|	k(  rn nt        |      rt        d|d|      S |t        |      k7  rdj                  ||d        nd}
|dk\  rdj                  |d |d
z
         nd}|r||d
z
     nd}t        |||
|      S )Nu   。r   u   ．u   ｡r.   r   r/   r0   r1   r   r   F)r   rQ   )rG      )	replacer2   r   r   split_get_tld_extractorsuffix_indexr   r)   )r   rY   rG   rR   netloc_with_ascii_dotsr3   labelsr`   r   num_ipv4_labelsr   r   r   s                r   rW   zTLDExtract._extract_netloc  sc    NN8X.WXx(WXx( 	 &'+==&q)S0&r*c15a;<$R)?PUVV'--c2#'#:#: $; $

,v;V,
W 	!j 3v;9/9m"?
 !%;RLL4@CK4O&/0UW<HA<MCHHV$6lQ&678SU	-9q()rY
CCr!   c                p    d| _         | j                  j                          |r| j                  |       yy)z/Force fetch the latest suffix list definitions.NrQ   )rI   rM   clearr_   )r   	fetch_nowrR   s      r   updatezTLDExtract.updateB  s4     ##G#4 r!   c                T    t        | j                  |      j                               S )zReturns the list of tld's used by default.

        This will vary based on `include_psl_private_domains` and `extra_suffixes`
        rQ   )listr_   tlds)r   rR   s     r   rj   zTLDExtract.tldsK  s&     D++G+<AACDDr!   c                h   | j                   r| j                   S t        | j                  | j                  | j                  | j
                  |      \  }}t        ||| j                  g      st        d      t        ||t        | j                        | j                        | _         | j                   S )a1  Get or compute this object's TLDExtractor.

        Looks up the TLDExtractor in roughly the following order, based on the
        settings passed to __init__:

        1. Memoized on `self`
        2. Local system _cache file
        3. Remote PSL, over HTTP
        4. Bundled PSL snapshot file
        )cacheurlsrL   rE   rR   z)No tlds set. Cannot proceed without tlds.)public_tldsprivate_tlds
extra_tldsrG   )rI   r   rM   rD   rL   rE   anyrH   rF   _PublicSuffixListTLDExtractorri   rG   )r   rR   rn   ro   s       r   r_   zTLDExtract._get_tld_extractorS  s     ????"$4++&& $ 8 8!%!:!:%
!\ Kt/B/BCDHII7#%D//0(,(H(H	
 r!   )rN   z
str | NonerD   Sequence[str]rE   r   rG   r   rH   rs   rL   zstr | float | Noner6   None)NNrB   r   rG   bool | NonerR   requests.Session | Noner6   r   )rB   z3urllib.parse.ParseResult | urllib.parse.SplitResultrG   rv   rR   rw   r6   r   r$   )rY   r   rG   rv   rR   rw   r6   r   FN)rf   r   rR   rw   r6   rt   )rR   rw   r6   	list[str])rR   rw   r6   rr   )r7   r8   r9   r:   r
   PUBLIC_SUFFIX_LIST_URLSCACHE_TIMEOUTrO   rU   rS   rZ   rW   rg   r<   rj   r_   r%   r!   r   r>   r>      s   Y
 !.*A%),1(*2?E+E+ (E+ #	E+
 &*E+ &E+ 0E+ 
E+T 48+/	SS &1S )	S
 
S 48+/	

 &1
 )	

 

D 48+/	
@
 &1
 )	

 

8 ,0	$D$D &1$D )	$D
 
$DN KO550G5	5 E E 26!.!	&!r!   r>   c                  X    e Zd ZdZ	 	 	 d	 	 	 	 	 	 	 ddZe	 d	 	 	 	 	 d	d       Zd
ddZy)Triez:Trie for storing eTLDs with their labels in reverse-order.Nc                6    |r|ni | _         || _        || _        y)zTODO.N)matchesendr   )r   r   r   r   s       r   rO   zTrie.__init__}  s     #*wr$r!   c                    t               }| D ]  }|j                  |        |g }|D ]  }|j                  |d        |S )z?Create a Trie from a list of suffixes and return its root node.T)r}   
add_suffix)public_suffixesprivate_suffixes	root_noder   s       r   createzTrie.create  s]     F	% 	)F  (	) #!& 	/F  .	/ r!   c                    | }|j                  d      }|j                          |D ]6  }||j                  vrt               |j                  |<   |j                  |   }8 d|_        ||_        y)z+Append a suffix's labels to this Trie node.r   TN)r^   reverser   r}   r   r   )r   r   r   noderb   labels         r   r   zTrie.add_suffix  sh    c" 	'EDLL(&*fU#<<&D	'
 $r!   )NFF)r   zdict[str, Trie] | Noner   r   r   r   r6   rt   r$   )r   zCollection[str]r   zCollection[str] | Noner6   r}   F)r   r   r   r   r6   rt   )r7   r8   r9   r:   rO   staticmethodr   r   r%   r!   r   r}   r}   z  ss    D +/ 		%'	% 	% 		%
 
	%  48(0 
 $%r!   r}   c                    t        | ||      S )N)rG   rR   )TLD_EXTRACTOR)rB   rG   rR   s      r   extractr     s     )Dg r!   c                 ,    t        j                  | i |S r$   )r   rg   )argskwargss     r   rg   rg     s    000r!   c                  J    e Zd ZdZ	 d	 	 	 	 	 	 	 ddZdd	dZ	 d	 	 	 	 	 d
dZy)rr   z8Wrapper around this project's main algo for PSL lookups.c                $   || _         || _        || _        t        ||z   |z         | _        t        ||z         | _        t        j                  | j
                  t        |            | _        t        j                  | j
                        | _	        y r$   )
rG   rn   ro   	frozensettlds_incl_privatetlds_excl_privater}   r   tlds_incl_private_trietlds_excl_private_trie)r   rn   ro   rp   rG   s        r   rO   z&_PublicSuffixListTLDExtractor.__init__  s     ,G(&(!*;+E
+R!S!*;+C!D&*kk""Il$;'
# '+kk$2H2H&I#r!   Nc                R    || j                   }|r| j                  S | j                  S )z,Get the currently filtered list of suffixes.)rG   r   r   )r   rG   s     r   rj   z"_PublicSuffixListTLDExtractor.tlds  s9    &.*.*J*J' + ""	
 ''	
r!   c                   || j                   }|r| j                  n| j                  }t        |      }|}t	        |      D ]  }t        |      }||j                  v r#|dz  }|j                  |   }|j                  r|}?d|j                  v }|rPd|z   |j                  v }	|	r||j                  d   j                  fc S |dz
  |j                  d   j                  fc S  n ||j                  fS )zReturn the index of the first suffix label, and whether it is private.

        Returns len(spl) if no suffix is found.
        r   *!)	rG   r   r   r2   reversed_decode_punycoder   r   r   )
r   splrG   r   r'   jr   decoded_labelis_wildcardis_wildcard_exceptions
             r   r`   z*_PublicSuffixListTLDExtractor.suffix_index  s    '.*.*J*J' + '',, 	
 Hc] 	E,U3M,Q||M288A-K(+m(;t||(K%(dll3/::::1udll3/::::!	$ $//!!r!   r   )rn   ry   ro   ry   rp   ry   rG   r   r$   )rG   rv   r6   zfrozenset[str])r   ry   rG   rv   r6   ztuple[int, bool])r7   r8   r9   r:   rO   rj   r`   r%   r!   r   rr   rr     sc    B -2JJ  J 	J
 &*J$	
 JN#"#";F#"	#"r!   rr   c                    | j                         }|j                  d      }|r	 t        j                  |      S |S # t        t
        f$ r Y |S w xY w)Nzxn--)lower
startswithidnadecodeUnicodeError
IndexError)r   loweredlooks_like_punys      r   r   r     sY    kkmG((0O	;;w'' N j) 	N	s   < AArx   ru   )r   r   r6   r   )(r:   
__future__r   loggingosurllib.parseurllibcollections.abcr   r   dataclassesr   	functoolsr   r   requestsrl   r	   r
   remoter   r   r   suffix_listr   	getLoggerLOGenvirongetr{   rz   r   r>   r   r}   rU   r   rg   rr   r   r%   r!   r   <module>r      s"  "H #  	  0 !    + B B )g% 

9:  M M M`c cL .% .%b } 05'+	!, % 	  }1 1C" C"Lr!   