
    gj/                        d Z ddlZddlmZ ddlmZmZ ddlZddlm	Z	 ddl
mZmZ dd	lmZmZ d
ZdZ G d de          Z G d ded          ZdefdZdddedeg df         dz  defdZdedefdZdej        defdZdS )aA  Device Code OAuth (RFC 8628) for browser-based login, plus access token refresh.

The flow: the client requests a device code, displays a URL and a short user code, the user
authorizes in a browser, and the client polls ``POST {ENDPOINT}/oauth/token`` until a token is
issued. Access tokens may come with a refresh token, used to renew them transparently (see
``utils/_auth.py::get_token``).

This module is self-contained protocol logic: no printing, no persistence. Interactive flows
live in ``_login.py`` (human/library) and ``cli/auth.py`` (machine-readable event stream).
    N)Callable)	TypedDictcast   )	constants)DeviceCodeErrorOAuthErrorCode   )get_sessionhf_raise_for_statusz,urn:ietf:params:oauth:grant-type:device_coderefresh_tokenc                   L    e Zd ZU eed<   eed<   eed<   eed<   eed<   eed<   dS )DeviceCodeInfodevice_code	user_codeverification_uriverification_uri_completeinterval
expires_inN__name__
__module____qualname__str__annotations__int     g/var/www/app.qaans.com/backend/venv/lib/python3.11/site-packages/huggingface_hub/utils/_oauth_device.pyr   r   (   sO         NNN""""MMMOOOOOr   r   c                   8    e Zd ZU eed<   eed<   eed<   eed<   dS )OAuthTokenResponseaccess_tokenr   r   
token_typeNr   r   r   r   r!   r!   1   s:         OOOOOOOOr   r!   F)totalreturnc                  
   	 t                                          t          j         ddt          j        it          j                  } t          |            n7# t          j        $ r%}t          dt          j         d|           |d}~ww xY w| 
                                }|                    dd           |                    d	d
           |                    d          s|d         |d<   t          t          |          S )a'  Request a device code from the Hub's OAuth device authorization endpoint.

    The returned dict is normalized: `interval`, `expires_in` and `verification_uri_complete`
    are always set (server values, or sensible defaults).

    Raises:
        [`DeviceCodeError`]: If the request fails.
    z/oauth/device	client_iddatatimeoutz#Failed to request device code from z/oauth/device: Nr      r   i  r   r   )r   postr   ENDPOINTDEVICE_CODE_OAUTH_CLIENT_IDHF_HUB_DOWNLOAD_TIMEOUTr   httpx	HTTPErrorr   json
setdefaultgetr   r   )responseeinfos      r   request_device_coder8   8   s   s==%%!000yDE5 & 
 

 	H%%%%? s s sjIDVjjghjjkkqrrs==??D 	OOJ"""OOL#&&&88/00 E,01C,D()%%%s   AA B( BB)
on_pendingdevice_infor9   c          	         | d         }t          j                    | d         z   }t          j                    |k     rd}	 t                                          t          j         dt          | d         t          j        dt          j                  }|j	        dk     r|
                                }n# t          j        t          f$ r Y nw xY w|d	|v rt          t          |          S |                    d
          x nxt"          j        k    r |
 |             nxt"          j        k    r |dz  }nxt"          j        k    r t+          dt"          j                  xt"          j        k    r t+          dt"          j                  }t+          d| d|                    dd           |          t          j        |           t          j                    |k     t+          dt"          j                  )aw  Poll the token endpoint until the user authorizes the device.

    Args:
        device_info (`DeviceCodeInfo`):
            The device authorization response from [`request_device_code`].
        on_pending (`Callable`, *optional*):
            Called after each "authorization pending" response (e.g. to print a progress dot).

    Returns:
        `OAuthTokenResponse`: the full token response: `access_token`, and optionally
        `refresh_token` and `expires_in`.

    Raises:
        [`DeviceCodeError`]: If authorization is denied, the device code expires, or the server
            returns an unexpected OAuth error.
    r   r   N/oauth/tokenr   )
grant_typer   r'   r(     r"   errorr+   z&Device code expired. Please try again.
error_codez+Authorization was denied. Please try again.zOAuth error:  - error_description z0Device code expired (timeout). Please try again.)time	monotonicr   r,   r   r-   _DEVICE_CODE_GRANT_TYPEr.   r/   status_coder2   r0   r1   
ValueErrorr   r!   r4   r	   AUTHORIZATION_PENDING	SLOW_DOWNEXPIRED_TOKENr   ACCESS_DENIEDsleep)r:   r9   r   deadliner)   r5   r?   s          r   poll_device_tokenrP   T   s=   & :&H~+l";;H
.

X
%
% 	"}}))%333"9#.}#=!*!F 
 "9 *  H #c))}}, 	 	 	D	 %%.555((7##TT9^9999!-"
-^----MHH1^1111)@^Mi    2^1111)ER`Rn    )UUU$((;NPR2S2SUUbg    	
8[ .

X
%
%^ LYgYu
v
v
vvs    A3B4 4CCc           	         	 t                                          t          j         dt          | t          j        dt          j                  }n*# t          j        $ r}t          d|           |d}~ww xY wt          |          }d|v rt          t          |          S |                    d          }t          d|p|j         d|                    d	d
           |          )a  Exchange a refresh token for a new access token.

    Returns:
        `OAuthTokenResponse`: the full token response: `access_token`, and optionally a rotated
        `refresh_token` and `expires_in`.

    Raises:
        [`DeviceCodeError`]: If the server rejects the refresh (`error_code="invalid_grant"` when
            the refresh token is expired or revoked) or returns an unexpected response.
    r<   )r=   r   r'   r(   z Failed to refresh access token: Nr"   r?   rB   rC   rD   r@   )r   r,   r   r-   _REFRESH_TOKEN_GRANT_TYPEr.   r/   r0   r1   r   _parse_token_responser   r!   r4   rH   )r   r5   r6   r)   r?   s        r   refresh_access_tokenrT      s   M==%%!///7!.&B  5 & 

 

 ? M M MDDDEE1LM **D&---HHWE
p5+HH4HppTXXVikmMnMnpp   s   AA A8 A33A8r5   c                     	 |                                  S # t          $ r:}t          dt          j         d| j         d| j        d d                    |d }~ww xY w)NzFailed to parse response from z/oauth/token (status z): r>   )r2   rI   r   r   r-   rH   text)r5   r6   s     r   rS   rS      s    }}   FY-? F F+F F08dsd0CF F
 
 	s    
A5AA)__doc__rE   collections.abcr   typingr   r   r0   rD   r   errorsr   r	   _httpr   r   rG   rR   r   r!   r8   rP   r   rT   ResponsedictrS   r   r   r   <module>r^      s  	 	  $ $ $ $ $ $ " " " " " " " "        4 4 4 4 4 4 4 4 3 3 3 3 3 3 3 3 I +     Y       %    &^ & & & &: MQDw Dw DwDw08T0BT0IDwDw Dw Dw DwN   0B        FEN t      r   