
    hi                       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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j4                  j7                  d      ZdZ ed       G d d             Z G d d      Z e       Z  G d d      Z! ee jD                        	 	 d	 	 	 	 	 	 	 dd       Z# ee jH                        d        Z$ G d d      Z%ddZ&y)ai  `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.top_domain_under_public_suffix
    'bbc.co.uk'
    >>> ext.fqdn
    'forums.bbc.co.uk'
    )annotationsN)
CollectionSequence)	dataclassfield)wraps   )	DiskCacheget_cache_dir)lenient_netloclooks_like_iplooks_like_ipv6)get_suffix_lists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	      Zded
<   	 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y)ExtractResulta  A URL's extracted subdomain, domain, and suffix.

    These first 3 fields are what most users of this library will care about.
    They are the split, non-overlapping hostname components of the input URL.
    They can be used to rebuild the original URL's hostname.

    Beyond the first 3 fields, the class contains metadata fields, like a flag
    that indicates if the input URL's suffix is from a private domain.
    str	subdomaindomainsuffixbool
is_privateF)reprregistry_suffixc                    | j                   rQ| j                  s| j                  r9dj                  d | j                  | j                  | j                   fD              S y)a  The Fully Qualified Domain Name (FQDN), if there is a proper `domain` and `suffix`, or else the empty string.

        >>> extract("http://forums.bbc.co.uk/path/to/file").fqdn
        'forums.bbc.co.uk'
        >>> extract("http://localhost:8080").fqdn
        ''
        .c              3  &   K   | ]	  }|s|  y wN ).0is     X/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/tldextract/tldextract.py	<genexpr>z%ExtractResult.fqdn.<locals>.<genexpr>y   s     W!UVAWs    )r   r   r   joinr   selfs    r#   fqdnzExtractResult.fqdno   sB     ;;DKK4??88WT[['QWWW    c                    | j                   r9| j                  s-| j                  s!t        | j                         r| j                   S y)a,  The IPv4 address, if that is what the input domain/URL was, or else the empty string.

        >>> 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.ipv4|   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  The IPv6 address, if that is what the input domain/URL was, or else the empty string.

        >>> 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.ipv6   sj      22A#%B3&[[DNN++a+K{+""r*   c                R    t        j                  dt        d       | j                  S )a  The `domain` and `suffix` fields joined with a dot, if they're both set, or else the empty string.

        >>> extract("http://forums.bbc.co.uk").registered_domain
        'bbc.co.uk'
        >>> extract("http://localhost:8080").registered_domain
        ''

        .. deprecated:: 6.0.0
           This property is deprecated and will be removed in the next major
           version. Use `top_domain_under_public_suffix` instead, which has the
           same behavior but a more accurate name.

        This is an alias for the `top_domain_under_public_suffix` property.
        `registered_domain` is so called because is roughly the domain the
        owner paid to register with a registrar or, in the case of a private
        domain, "registered" with the domain owner. If the input was not
        something one could register, this property returns the empty string.

        To distinguish the case of private domains, consider Blogspot, which is
        in the PSL's private domains. If `include_psl_private_domains` was set
        to `False`, the `registered_domain` property of a Blogspot URL
        represents the domain the owner of Blogspot registered with a
        registrar, i.e. Google registered "blogspot.com". If
        `include_psl_private_domains=True`, the `registered_domain` property
        represents the "blogspot.com" _subdomain_ the owner of a blog
        "registered" with Blogspot.

        >>> extract(
        ...     "http://waiterrant.blogspot.com", include_psl_private_domains=False
        ... ).registered_domain
        'blogspot.com'
        >>> extract(
        ...     "http://waiterrant.blogspot.com", include_psl_private_domains=True
        ... ).registered_domain
        'waiterrant.blogspot.com'

        To always get the same joined string, regardless of the
        `include_psl_private_domains` setting, consider the
        `top_domain_under_registry_suffix` property.
        zThe 'registered_domain' property is deprecated and will be removed in the next major version. Use 'top_domain_under_public_suffix' instead, which has the same behavior but a more accurate name.   )
stacklevel)warningswarnDeprecationWarningtop_domain_under_public_suffixr'   s    r#   registered_domainzExtractResult.registered_domain   s+    T 	r		
 222r*   c                    | j                   | j                  g}| j                  r3|j                  t	        | j                  j                  d                   dj                  |      S )aX  The domain name in Reverse Domain Name Notation.

        Joins extracted components of the input URL in reverse domain name
        notation. The suffix is used as the leftmost component, followed by the
        domain, then followed by the subdomain with its parts reversed.

        Reverse Domain Name Notation is typically used to organize namespaces
        for packages and plugins. Technically, a full reversal would reverse
        the parts of the suffix, e.g. "co.uk" would become "uk.co", but this is
        not done in practice when Reverse Domain Name Notation is called for.
        So this property leaves the `suffix` part in its original order.

        >>> extract("login.example.com").reverse_domain_name
        'com.example.login'

        >>> extract("login.example.co.uk").reverse_domain_name
        'co.uk.example.login'
        r   )r   r   r   extendreversedsplitr&   )r(   stacks     r#   reverse_domain_namez!ExtractResult.reverse_domain_name   sK    ( dkk*>>LL$.."6"6s";<=xxr*   c                    | j                   }|r| j                  s|S | j                  j                  d      dz   }dj	                  |j                  d      | d       S )a  The rightmost domain label and `registry_suffix` joined with a dot, if such a domain is available and `registry_suffix` is set, or else the empty string.

        The rightmost domain label might be in the `domain` field, or, if the
        input URL's suffix is a PSL private domain, in the public suffix
        `suffix` field.

        If the input was not in the PSL's private domains, this property is
        equivalent to `top_domain_under_public_suffix`.

        >>> extract(
        ...     "http://waiterrant.blogspot.com", include_psl_private_domains=False
        ... ).top_domain_under_registry_suffix
        'blogspot.com'
        >>> extract(
        ...     "http://waiterrant.blogspot.com", include_psl_private_domains=True
        ... ).top_domain_under_registry_suffix
        'blogspot.com'
        >>> extract("http://localhost:8080").top_domain_under_registry_suffix
        ''
        r   r7   N)r<   r   r   countr&   rA   )r(   r<   
num_labelss      r#    top_domain_under_registry_suffixz.ExtractResult.top_domain_under_registry_suffix   s^    , *.)L)L&-T__11))//4q8
xx6<<SA:+,OPPr*   c                j    | j                   r'| j                  r| j                   d| j                    S y)a%  The `domain` and `suffix` fields joined with a dot, if they're both set, or else the empty string.

        >>> extract("http://forums.bbc.co.uk").top_domain_under_public_suffix
        'bbc.co.uk'
        >>> extract("http://localhost:8080").top_domain_under_public_suffix
        ''
        r   r%   )r   r   r'   s    r#   r<   z,ExtractResult.top_domain_under_public_suffix  s-     ;;4;;kk]!DKK=11r*   N)returnr   )__name__
__module____qualname____doc____annotations__r   r   propertyr)   r,   r5   r=   rC   rG   r<   r    r*   r#   r   r   =   s     N|K K  !e,OS, 
 
  $  4 /3 /3b  0 Q Q8 
 
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, and use the first
        successful response for public suffix definitions. Subsequent, untried
        URLs are ignored. The default URLs are the latest version of the
        Mozilla Public Suffix List and its mirror, but any similar document URL
        could be specified. Local files can be specified by using the `file://`
        protocol (see `urllib2` documentation). To disable HTTP requests, set
        this to an empty sequence.

        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 specify additional suffixes in the `extra_suffixes` argument.
        These will be merged into whatever public suffix definitions are
        already in use by `tldextract`, above.

        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>W  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_dirrW   rX   rZ   r[   r_   s          r#   __init__zTLDExtract.__init__$  s    d ,1r % &
#3&
 !
 %9!%%d6O6O;  ,G(,@D -s3 %&$ 	 
  	*r*   Nc                *    | j                  |||      S )zAlias for `extract_str`.session)extract_strr(   rU   rZ   re   s       r#   __call__zTLDExtract.__call__n  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)
        rd   )_extract_netlocr   rg   s       r#   rf   zTLDExtract.extract_strw  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)
        rd   )rj   netlocrg   s       r#   extract_urllibzTLDExtract.extract_urllib  s(    , ##JJ3W $ 
 	
r*   c                    |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d      S |j	                  d      }| j                  |      j                  ||      }d}|s)t        |      |k(  rt        |      rt        d|ddd      S |s%t        dj                  |d d       |d   ddd      S |\  \  }	}
\  }}|	dk\  rdj                  |d |	d
z
         nd}|	dkD  r||	d
z
     nd}dj                  ||	d        }|
j                  rdj                  ||d        n|}t        ||||
j                  |      S )Nu   。r   u   ．u   ｡r.   r   r/   r0   r1   r	   r%   F)r   r   )rZ   )r   r   r   r   r   r7   )
replacer2   r   r   rA   _get_tld_extractorsuffix_indexr   r&   r   )r(   rl   rZ   re   netloc_with_ascii_dotsr3   labelsmaybe_indexesnum_ipv4_labelspublic_suffix_indexpublic_suffix_noderegistry_suffix_indexregistry_suffix_noder   r   public_suffixr   s                    r#   rj   zTLDExtract._extract_netloc  s    NN8X.WXx(WXx( 	 &'+==&q)S0&r*c1 6q <= *B5RT  (--c2//8EE0K F 
 F.45 *B5RT   ((6#2;/bz  "  	
5 "49"$8
 #a' HHV51A567 	
 5H!4K+a/0QS(;(<!=> ",, HHV1234 	
  )44+
 	
r*   c                p    d| _         | j                  j                          |r| j                  |       yy)z/Force fetch the latest suffix list definitions.Nrd   )r\   r`   clearrp   )r(   	fetch_nowre   s      r#   updatezTLDExtract.update  s4     ##G#4 r*   c                T    t        | j                  |      j                               S )zThe list of TLDs used by default.

        This will vary based on `include_psl_private_domains` and `extra_suffixes`.
        rd   )listrp   tlds)r(   re   s     r#   r   zTLDExtract.tlds  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urlsr_   rX   re   z)No tlds set. Cannot proceed without tlds.)public_tldsprivate_tlds
extra_tldsrZ   )r\   r   r`   rW   r_   rX   anyr[   rY   _PublicSuffixListTLDExtractorr   rZ   )r(   re   r   r   s       r#   rp   zTLDExtract._get_tld_extractor	  s     ????"$4++&& $ 8 8!%!:!:%
!\ Kt/B/BCDHII7#%D//0(,(H(H	
 r*   )ra   z
str | NonerW   Sequence[str]rX   r   rZ   r   r[   r   r_   zstr | float | NonerI   None)NNrU   r   rZ   bool | Nonere   requests.Session | NonerI   r   )rU   z3urllib.parse.ParseResult | urllib.parse.SplitResultrZ   r   re   r   rI   r   r   )rl   r   rZ   r   re   r   rI   r   FN)r}   r   re   r   rI   r   )re   r   rI   	list[str])re   r   rI   r   )rJ   rK   rL   rM   r   PUBLIC_SUFFIX_LIST_URLSCACHE_TIMEOUTrb   rh   rf   rm   rj   r~   rO   r   rp   r    r*   r#   rQ   rQ      s   Y
 !.*A%),1(*2?H+H+ (H+ #	H+
 &*H+ &H+ 0H+ 
H+Z 48+/	SS &1S )	S
 
S 48+/	

 &1
 )	

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

 

< ,0	F
F
 &1F
 )	F

 
F
R KO550G5	5 E E 26!.!	&!r*   rQ   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#   rb   zTrie.__init__3  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)rA   reverser   r   r   r   )r(   r   r   noders   labels         r#   r   zTrie.add_suffixQ  sh    c" 	'EDLL(&*fU#<<&D	'
 $r*   )NFF)r   zdict[str, Trie] | Noner   r   r   r   rI   r   r   )r   zCollection[str]r   zCollection[str] | NonerI   r   F)r   r   r   r   rI   r   )rJ   rK   rL   rM   rb   staticmethodr   r   r    r*   r#   r   r   0  ss    D +/ 		%'	% 	% 		%
 
	%  48(0 
 $%r*   r   c                    t        | ||      S )N)rZ   re   )TLD_EXTRACTOR)rU   rZ   re   s      r#   extractr   a  s     )Dg r*   c                 ,    t        j                  | i |S r   )r   r~   )argskwargss     r#   r~   r~   l  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)r   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   )
rZ   r   r   	frozensettlds_incl_privatetlds_excl_privater   r   tlds_incl_private_trietlds_excl_private_trie)r(   r   r   r   rZ   s        r#   rb   z&_PublicSuffixListTLDExtractor.__init__t  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.)rZ   r   r   )r(   rZ   s     r#   r   z"_PublicSuffixListTLDExtractor.tlds  s9    &.*.*J*J' + ""	
 ''	
r*   c                   || j                   }|r| j                  n| j                  x}}t        |      x}x}}t	        |      D ]  }t        |      }	|	|j                  v r3|dz  }|j                  |	   }|j                  r|}|j                  s|}|}Od|j                  v }
|
r/d|	z   |j                  v }|r|n|dz
  |j                  d   f||ffc S  n |t        |      k(  ry||f||ffS )zReturn the index of the first public suffix label, the index of the first registry suffix label, and their corresponding trie nodes.

        Returns `None` if no suffix is found.
        Nr	   *!)	rZ   r   r   r2   r@   _decode_punycoder   r   r   )r(   splrZ   r   reg_node
suffix_idxreg_idx	label_idxr   decoded_labelis_wildcardis_wildcard_exceptions               r#   rq   z*_PublicSuffixListTLDExtractor.suffix_index  s0    '.*.*J*J' + '',,	
x
 ,/s83
3Wyc] 	E,U3M,Q	||M288!*J??#'"+-K(+m(;t||(K%!6IIMLL%   /	2 S!T"Wh$788r*   r   )r   r   r   r   r   r   rZ   r   r   )rZ   r   rI   zfrozenset[str])r   r   rZ   r   rI   z0tuple[tuple[int, Trie], tuple[int, Trie]] | None)rJ   rK   rL   rM   rb   r   rq   r    r*   r#   r   r   q  sc    B -2JJ  J 	J
 &*J$	
 JN,9,9;F,9	9,9r*   r   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r   r   )r   r   rI   r   )'rM   
__future__r   osurllib.parseurllibr9   collections.abcr   r   dataclassesr   r   	functoolsr   r   requestsr   r
   r   remoter   r   r   suffix_listr   environgetr   r   r   rQ   r   r   rh   r   r~   r   r   r    r*   r#   <module>r      s  "H # 	   0 (    + B B )

9:  _ _ _DJ JZ .% .%b } 05'+	!, % 	  }1 1L9 L9^r*   