
    bf-O                         d dl Z d dlmZ d dlZd dlZd dlZd dlZddlmZm	Z	m
Z
mZ ddl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  G d	 d
e          ZdS )    N)	urlencode   )MastodonIllegalArgumentErrorMastodonNetworkErrorMastodonVersionErrorMastodonAPIError)_DICT_VERSION_APPLICATION)_DEFAULT_SCOPES_SCOPE_SETS_DEFAULT_TIMEOUT_DEFAULT_USER_AGENT)parse_version_stringapi_version)Mastodonc                       e Zd Zeeddddedefd            ZdddddddeddddedfdZdd	edddfd
Z	dddd	dedfdZ
d Z edde          d             ZdS )r   Nc	                    |t          d          t                              |          }| d                    |          d}	d|i}
|Dt	          |t
          t          f          r"d                    t          |                    }||	d<   nd|	d<   |||	d	<   	 |r1|                    | d
|	|
|          }|                                }n/t          j        | d
|	|
|          }|                                }n$# t          $ r}t          d|           d}~ww xY w|t          |d          5 }|                    |d         dz              |                    |d         dz              |                    |dz              |                    | dz              ddd           n# 1 swxY w Y   |d         |d         fS )a  
        Create a new app with given `client_name` and `scopes` (The basic scopes are "read", "write", "follow" and "push"
        - more granular scopes are available, please refer to Mastodon documentation for which) on the instance given
        by `api_base_url`.

        Specify `redirect_uris` if you want users to be redirected to a certain page after authenticating in an OAuth flow.
        You can specify multiple URLs by passing a list. Note that if you wish to use OAuth authentication with redirects,
        the redirect URI must be one of the URLs specified here.

        Specify `to_file` to persist your app's info to a file so you can use it in the constructor.
        Specify `website` to give a website for your app.

        Specify `session` with a requests.Session for it to be used instead of the default. This can be
        used to, amongst other things, adjust proxy or SSL certificate settings.

        Specify `user_agent` if you want to use a specific name as `User-Agent` header, otherwise "mastodonpy" will be used.

        Presently, app registration is open by default, but this is not guaranteed to be the case for all
        Mastodon instances in the future.


        Returns `client_id` and `client_secret`, both as strings.
        NAPI base URL is required. )client_namescopesz
User-Agent
redirect_urisurn:ietf:wg:oauth:2.0:oobwebsitez/api/v1/apps)dataheaderstimeoutzCould not complete request: w	client_idclient_secret)r   r   _Mastodon__protocolizejoin
isinstancelisttuplepostjsonrequests	Exceptionr   openwrite)r   r   r   r   to_fileapi_base_urlrequest_timeoutsession
user_agentrequest_datar   retresponseesecret_files                  e/home/feoh/.local/pipx/venvs/mastodon-archive/lib/python3.11/site-packages/mastodon/authentication.py
create_appzMastodon.create_app   s`   4 ./JKKK--l;; 'hhv&&
 

 *
 $-$77 ? $		$}*=*= > >,9L)),GL)&-L#	K +lll#@#@#@|]dn}l~~88::#=L)F)F)F\cj  uD  E  E  E#==?? 	K 	K 	K&'Ia'I'IJJJ	K gs## 6{!!(;"7$">???!!(?";d"BCCC!!,"5666!!+"4555	6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 %x'@AAs,   A"C> >
DDD4A-F--F14F1Fwaitg?createdmainlinec                 	   || _         | j         |                     | j                   | _         || _        || _        || _        || _        || _        t          j                                        | _	        d| _
        d| _        d| _        t          j                    | _        d| _        t          j                    | _        || _        || _        |r|| _        nt)          j                    | _        || _        | j        dvrt/          d          || _        || _        | j        rt4          j                            | j                  r7t;          | j        d          5 }|                                                                | _        |                                                                | _        |                                                                }|UtA          |          dk    rBtB                              |          }| j         || j         k    st/          d          || _         |                                }|r | j        |                                | _        ddd           n# 1 swxY w Y   n| j        t/          d          | j        `t4          j                            | j                  r;t;          | j        d          5 }|                                                                | _        |                                                                }|UtA          |          dk    rBtB                              |          }| j         || j         k    st/          d          || _         | j        _	 |                                                                | _        |                                                                | _        n#  Y nxY wddd           n# 1 swxY w Y   | j         t/          d	          tB                              | j                   | _         |
d
vrt/          d          |
| _"        d| _#        d| _$        d| _%        d| _&        |	 | j"        dk    r| '                                 nC| j"        dk    r8	 tQ          |	          \  | _#        | _$        | _%        n#  tS          d          xY w|dvrt/          d          dS )a  
        Create a new API wrapper instance based on the given `client_secret` and `client_id` on the
        instance given by `api_base_url`. If you give a `client_id` and it is not a file, you must
        also give a secret. If you specify an `access_token` then you don't need to specify a `client_id`.
        It is allowed to specify neither - in this case, you will be restricted to only using endpoints
        that do not require authentication. If a file is given as `client_id`, client ID, secret and
        base url are read from that file.

        You can also specify an `access_token`, directly or as a file (as written by :ref:`log_in() <log_in()>`). If
        a file is given, Mastodon.py also tries to load the base URL from this file, if present. A
        client id and secret are not required in this case.

        Mastodon.py can try to respect rate limits in several ways, controlled by `ratelimit_method`.
        "throw" makes functions throw a `MastodonRatelimitError` when the rate
        limit is hit. "wait" mode will, once the limit is hit, wait and retry the request as soon
        as the rate limit resets, until it succeeds. "pace" works like throw, but tries to wait in
        between calls so that the limit is generally not hit (how hard it tries to avoid hitting the rate
        limit can be controlled by ratelimit_pacefactor). The default setting is "wait". Note that
        even in "wait" and "pace" mode, requests can still fail due to network or other problems! Also
        note that "pace" and "wait" are NOT thread safe.

        By default, a timeout of 300 seconds is used for all requests. If you wish to change this,
        pass the desired timeout (in seconds) as `request_timeout`.

        For fine-tuned control over the requests object use `session` with a requests.Session.

        The `mastodon_version` parameter can be used to specify the version of Mastodon that Mastodon.py will
        expect to be installed on the server. The function will throw an error if an unparseable
        Version is specified. If no version is specified, Mastodon.py will set `mastodon_version` to the
        detected version.

        The version check mode can be set to "created" (the default behaviour), "changed" or "none". If set to
        "created", Mastodon.py will throw an error if the version of Mastodon it is connected to is too old
        to have an endpoint. If it is set to "changed", it will throw an error if the endpoint's behaviour has
        changed after the version of Mastodon that is connected has been released. If it is set to "none",
        version checking is disabled.

        `feature_set` can be used to enable behaviour specific to non-mainline Mastodon API implementations.
        Details are documented in the functions that provide such functionality. Currently supported feature
        sets are `mainline`, `fedibird` and `pleroma`.

        For some Mastodon instances a `User-Agent` header is needed. This can be set by parameter `user_agent`. Starting from
        Mastodon.py 1.5.2 `create_app()` stores the application name into the client secret file. If `client_id` points to this file,
        the app name will be used as `User-Agent` header as default. It is possible to modify old secret files and append
        a client app name to use it as a `User-Agent` name.

        `lang` can be used to change the locale Mastodon will use to generate responses. Valid parameters are all ISO 639-1 (two letter)
        or for a language that has none, 639-3 (three letter) language codes. This affects some error messages (those related to validation) and 
        trends. You can change the language using :ref:`set_language()`.

        If no other `User-Agent` is specified, "mastodonpy" will be used.
        Ni,  )r:   fedibirdpleromazRequested invalid feature setrr   z4Mismatch in base URLs between files and/or specifiedz7Specified client id directly, but did not supply secretr   )r9   changednonezInvalid version check method.r   r@   zBad version specified)throwr8   pacezInvalid ratelimit method.)*r-   r!   r   r    access_tokendebug_requestsratelimit_methoddatetimenow_token_expired_refresh_token_Mastodon__logged_in_idratelimit_limittimeratelimit_resetratelimit_remainingratelimit_lastcallratelimit_pacefactorr.   r/   r(   Sessionfeature_setr   r0   langospathisfiler*   readlinerstriplenr   version_check_modemastodon_majormastodon_minormastodon_patchversion_check_workedretrieve_mastodon_versionr   r   )selfr   r    rC   r-   rD   rE   rP   r.   mastodon_versionrZ   r/   rR   r0   rS   r5   try_base_urlr   
token_files                      r6   __init__zMastodon.__init__Z   s*   n )( $ 2 243D E ED"*(, 0&/3355"""#y{{#& "&)++$8!. 	."DLL#+--DL&#FFF./NOOO % 	 >%w~~dn-- r$.#.. ?+%0%9%9%;%;%B%B%D%DDN)4)=)=)?)?)F)F)H)HD&#.#7#7#9#9#@#@#B#BL#/C4E4E4J4J'/'='=l'K'K $ 1 9\TM^=^=^">?u"v"vv,8) #."6"6"8"8K" ?t'>*5*<*<*>*>? ? ? ? ? ? ? ? ? ? ? ? ? ? ?  %-67pqqq(RW^^D<M-N-N(d'-- $.$7$7$9$9$@$@$B$B!  *2244;;==+L0A0AQ0F0F#+#9#9,#G#GL -5IZ9Z9Z:;qrrr(4D% >))3)<)<)>)>)E)E)G)G-7-@-@-B-B-I-I-K-K**#              ( $./JKKK$2243DEE!%CCC./NOOO"4$(! #(?6(I(I**,,,,$..DPdeuPvPvM#T%8$:M:MD*+BCCC #<<<./JKKK =<sK   D
I55I9<I9B0O4
AO! O4!O%#O44O8;O8"S   Sr   c                    || j         }nmt          j                            |          rNt	          |d          5 }|                                                                }ddd           n# 1 swxY w Y   t                      }||d<   d|d<   ||d<   d                    |          |d<   ||d	<   ||d
<   ||d<   t          |          }	d                    | j
        d|	g          S )a  
        Returns the URL that a client needs to request an OAuth grant from the server.

        To log in with OAuth, send your user to this URL. The user will then log in and
        get a code which you can pass to :ref:`log_in() <log_in()>`.

        `scopes` are as in :ref:`log_in() <log_in()>`, redirect_uris is where the user should be redirected to
        after authentication. Note that `redirect_uris` must be one of the URLs given during
        app registration. When using urn:ietf:wg:oauth:2.0:oob, the code is simply displayed,
        otherwise it is added to the given URL as the "code" request parameter.

        Pass force_login if you want the user to always log in even when already logged
        into web Mastodon (i.e. when registering multiple different accounts in an app).

        `state` is the oauth `state` parameter to pass to the server. It is strongly suggested
        to use a random, nonguessable value (i.e. nothing meaningful and no incrementing ID)
        to preserve security guarantees. It can be left out for non-web login flows.

        Pass an ISO 639-1 (two letter) or, for languages that do not have one, 639-3 (three letter)
        language code as `lang` to control the display language for the oauth form.
        Nr>   r   coderesponse_typeredirect_urir   scopeforce_loginstaterS    z/oauth/authorize?)r   rT   rU   rV   r*   rW   rX   dictr"   r   r-   )
r`   r   r   r   rj   rk   rS   r5   paramsformatted_paramss
             r6   auth_request_urlzMastodon.auth_request_url   s?   , IIw~~i(( @)S)) @[ + 4 4 6 6 = = ? ?I@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ '{"(!.~((6**w +}wv$V,,ww)+>@PQRRRs   'A--A14A1c                 
   |,|*|                      t                      g d          }d|d<   ng|*|                      t                      g d          }d|d<   n;|*|                      t                      g d          }d|d<   nt          d	          | j        |d
<   | j        |d<   d                    |          |d<   	 |                     dd|d          }	|	d         | _        |                     |		                    d                     | 
                    t          |		                    dd                               nN# t          $ rA}
||t          d|
           |t          d|
           t          d|
           d}
~
ww xY w|	d                             d          }t          j                    D ]}||v r|t          |         z  }t!          |          t!          |          k    sAt#          dd                    |          z   dz   d                    |          z   dz             |t%          |d          5 }|                    |	d         dz              |                    | j        dz              |                    | j        dz              |                    | j        dz              ddd           n# 1 swxY w Y   d| _        | j        s|                                  |	d         S )aK  
        Get the access token for a user.

        The username is the email address used to log in into Mastodon.

        Can persist access token to file `to_file`, to be used in the constructor.

        Handles password and OAuth-based authorization.

        Will throw a `MastodonIllegalArgumentError` if the OAuth flow data or the
        username / password credentials given are incorrect, and
        `MastodonAPIError` if all of the requested scopes were not granted.

        For OAuth 2, obtain a code via having your user go to the URL returned by
        :ref:`auth_request_url() <auth_request_url()>` and pass it as the code parameter. In this case,
        make sure to also pass the same redirect_uri parameter as you used when
        generating the auth request URL.

        Returns the access token as a string.
        N)r   r,   rf   refresh_tokenpassword
grant_type)r   r,   usernamers   rr   authorization_code)r   r,   ru   rs   rf   rr   zDInvalid arguments given. username and password or code are required.r   r    r   ri   POSTz/oauth/tokenF)do_ratelimitingrC   
expires_inr   z/Invalid user name, password, or redirect_uris: z'Invalid access token or redirect_uris: zInvalid request: zGranted scopes "z." do not contain all of the requested scopes "z".r   r   )_Mastodon__generate_paramslocalsr   r   r    r"   _Mastodon__api_requestrC   _Mastodon__set_refresh_tokenget_Mastodon__set_token_expiredintr)   splitr   keyssetr   r*   r+   r-   rJ   r^   r_   )r`   ru   rs   rf   rh   rr   r   r,   rn   r3   r4   received_scopes	scope_setrc   s                 r6   log_inzMastodon.log_in"  s   * H$8++FHH6d6d6deeF#-F<  ++FHH6t6t6tuuF#7F<  &++FHH6k6k6kllF#2F<  ./uvvv"n{"&"4((6**w	L))&.&Z_)``H ( 8D$$X\\/%B%BCCC$$SlA)F)F%G%GHHHH 	L 	L 	L#x';23hef3h3hiii!23`]^3`3`aaa23Jq3J3JKKK	L #7+11#66$)++ 	: 	:IO++;y#996{{c/2222"#58Q8Q#Q  UE  $E  HK  HP  HP  QW  HX  HX  $X  [_  $_  `  `  `gs## <z  .!9D!@AAA  !2T!9:::  $!6777  !3d!:;;;	< < < < < < < < < < < < < < < # ( 	-**,,,''s,   BE 
F<FFA6KKKc                    | j         t          d          | j        | j        t          d          t	          j        g           }| j        |d<   | j        |d<   | j         |d<   |                     dd|           d| _         d| _        dS )	z
        Revoke the oauth token the user is currently authenticated with, effectively removing
        the apps access and requiring the user to log in again.
        Nz-Not logged in, do not have a token to revoke.zAClient authentication (id + secret) is required to revoke tokens.r   r    tokenrw   z/oauth/revoke)rC   r   r   r    collectionsOrderedDictr|   rJ   )r`   rn   s     r6   revoke_access_tokenzMastodon.revoke_access_tokenk  s    
 $./^___>!T%7%?./rsss(,,"n{"&"4+w6?F;;; !"    z2.0.0z2.7.2c                 .    |                      dd          S )z
        Fetch information about the current application.

        Returns an :ref:`application dict <application dict>`.
        GETz/api/v1/apps/verify_credentials)r|   )r`   s    r6   app_verify_credentialszMastodon.app_verify_credentials  s     !!%)JKKKr   )__name__
__module____qualname__staticmethodr
   r   r   r7   rd   rp   r   r   r   r	   r    r   r6   r   r      sB        '6dTXbf $6FPTat>B >B >B \>BF "&T[_pu"(sTdw{$-t`sz~^L ^L ^L ^L@ *.=Xap  D  LP  W[ &S &S &S &SP #TKfvz  DS  ]a G( G( G( G(R# # #, ['#<==L L >=L L Lr   r   )r(   requests.modelsr   rF   rT   rL   r   errorsr   r   r   r   versionsr	   defaultsr
   r   r   r   utilityr   r   	internalsr   	Internalsr   r   r6   <module>r      s    % % % % % %  				      n n n n n n n n n n n n / / / / / / Y Y Y Y Y Y Y Y Y Y Y Y 6 6 6 6 6 6 6 6 , , , , , ,vL vL vL vL vLy vL vL vL vL vLr   