o
    ~hj                     @   s~  d Z ddlZddlZddlZddlZddlZddlZddlZddlZ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mZmZmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZmZ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+m,Z,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z7 ddl8m9Z: ddl;m<Z< ddl=m>Z> G dd dZ?dS )z5A Python module for interacting with Slack's Web API.    N)	b64encode)HTTPResponse)
SSLContext)BinaryIODictListAny)OptionalUnion)	HTTPError)	urlencode)RequesturlopenOpenerDirectorProxyHandlerHTTPSHandler)SlackRequestError   )show_deprecation_warning_if_any)FileUploadV2Result)convert_bool_to_0_or_1get_user_agent_get_url_build_req_args$_build_unexpected_body_error_message_upload_file_via_v2_url)SlackResponse)default_retry_handlers)RetryHandler)HttpRequest)HttpResponse)
RetryState)load_http_proxy_from_envc                   @   s6  e Zd ZdZdedddddddddfdee dededee dee d	ee d
ee dee dee dee	j
 deee  fddZdddddddddededee dee dee dee d	ee dee defddZdefddZded eeeeef f deeef fd!d"Zdd#dee d$ed%eeef d&ed'eeef deeejf d(eeef defd)d*Zd$ed+eeeeef f deeef fd,d-Zd$ed.edeeef fd/d0Zded1ed2ed(edeeef f
d3d4Zd$edede	j
dedee dee defd5d6Zed7eded8ed9edef
d:d;Z dS )<
BaseClientzhttps://slack.com/api/N   tokenbase_urltimeoutsslproxyheadersuser_agent_prefixuser_agent_suffixteam_idloggerretry_handlersc                 C   s   |d u rd n|  | _	 || _	 || _	 || _	 || _	 |pi | _	 t||| jd< i | _|	d ur6|	| jd< |
d ur<|
nt	
t| _|d urH|nt | _| jd u sZt| j  dkrjt| j}|d urh|| _d S d S d S )Nz
User-Agentr-   r   )stripr%   r&   r'   r(   r)   r*   r   default_paramslogging	getLogger__name___loggerr   r/   lenr"   )selfr%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   env_variable r9   Q/var/www/html/zoom/venv/lib/python3.10/site-packages/slack_sdk/web/base_client.py__init__-   s0   



zBaseClient.__init__POST)	http_verbfilesdataparamsjsonr*   auth
api_methodr=   r>   r?   r@   rA   rB   returnc                C   s\   t | j|}	|p	i }|| j t| j|||| j||||| j| jd}
t	| | j
|	|
dS )a  Create a request and execute the API call to Slack.

        Args:
            api_method (str): The target Slack API method.
                e.g. 'chat.postMessage'
            http_verb (str): HTTP Verb. e.g. 'POST'
            files (dict): Files to multipart upload.
                e.g. {image OR file: file_object OR file_path}
            data: The body to attach to the request. If a dictionary is
                provided, form-encoding will take place.
                e.g. {'key1': 'value1', 'key2': 'value2'}
            params (dict): The URL parameters to append to the URL.
                e.g. {'key1': 'value1', 'key2': 'value2'}
            json (dict): JSON for the body to attach to the request
                (if files or data is not specified).
                e.g. {'key1': 'value1', 'key2': 'value2'}
            headers (dict): Additional request headers
            auth (dict): A dictionary that consists of client_id and client_secret

        Returns:
            (SlackResponse)
                The server's response to an HTTP request. Data
                from the response can be accessed like a dict.
                If the response included 'next_cursor' it can
                be iterated on to execute subsequent requests.

        Raises:
            SlackApiError: The following Slack API call failed:
                'chat.postMessage'.
            SlackRequestError: Json data can only be submitted as
                POST requests.
        )r%   r=   r>   r?   r1   r@   rA   r*   rB   r(   r)   )api_urlreq_args)r   r&   updater*   r   r%   r1   r(   r)   r   
_sync_send)r7   rC   r=   r>   r?   r@   rA   r*   rB   rE   rF   r9   r9   r:   api_call^   s$   -zBaseClient.api_callc              	   C   sR  d|v r|d nd }d|v r|d nd }d|v r|d nd }d|v r&|d nd }d|v r0|d nd }|r=d|v r=| dnd }d|v rG|d nd }	|	d uri }t|	trY|	|d< n4t|	tr~|	d	 |	d
 }
}t|
 d| dd}d| |d< n| jd|	 dt	|	 d i }|r|
| |r|
| | j||i ||||dS )Nr@   r?   r>   rA   r*   r%   rB   Authorization	client_idclient_secret:utf-8asciizBasic zAs the auth: z: z is unsupported, skipped)r%   urlquery_paramsbody_paramsr>   	json_bodyadditional_headers)get
isinstancestrdictr   encodedecoder5   warningtyperG   _urllib_api_call)r7   rE   rF   r@   r?   r>   _jsonr*   r%   rB   rK   rL   valuerR   r9   r9   r:   rH      s<   




zBaseClient._sync_sendrE   rF   c                 C   s4   | j ||d}t|d t|d t|d dS )a  This method is supposed to be used only for SlackResponse pagination

        You can paginate using Python's for iterator as below:

          for response in client.conversations_list(limit=100):
              # do something with each response here
        rP   argsstatusr*   bodystatus_coder*   r?   )_perform_urllib_http_requestintrX   rA   loads)r7   rE   rF   responser9   r9   r:   _request_for_pagination   s
   

z"BaseClient._request_for_pagination)r%   rP   rQ   rS   rR   rT   c                C   s  g }zOt |}t |}| jjtjkrCdtdtfdd}	dd | D }
| jd| d|	| d	|	| d
|	| d| d|
  i }|durt|trt	|dkr|rf| D ]\}}|
||i qZ| D ]8\}}t|trt|ddd}|| |
||i qjt|ttfr|
|t|i qj|
||i qj| j|p| jtdu|du|d}|||||d}|rt|}d|v r| d| n| d| }| j||d}|dd}|}|durt|tsz	t|d }W n" tjjy   t|dd}| jd|  d|d}Y nw |dur#t|ni }|r-|
| ||d< t| d|||t|d |d d   W |D ]}|j!sP|"  qFS |D ]}|j!s_|"  qUw )!aU  Performs a Slack API request and returns the result.

        Args:
            token: Slack API Token (either bot token or user token)
            url: Complete URL (e.g., https://slack.com/api/chat.postMessage)
            query_params: Query string
            json_body: JSON data structure (it's still a dict at this point),
                if you give this argument, body_params and files will be skipped
            body_params: Form body params
            files: Files to upload
            additional_headers: Request headers to append

        Returns:
            API response
        valuesrD   c                 S   s$   | rt | ts	i S dd |  D S )Nc                 S   s$   i | ]\}}|t |trd n|qS )z(bytes))rV   bytes.0kvr9   r9   r:   
<dictcomp>   s   $ zGBaseClient._urllib_api_call.<locals>.convert_params.<locals>.<dictcomp>)rV   rX   items)rk   r9   r9   r:   convert_params   s   z3BaseClient._urllib_api_call.<locals>.convert_paramsc                 S   s&   i | ]\}}||  d krdn|qS )authorizationz
(redacted))lowerrm   r9   r9   r:   rq      s   & z/BaseClient._urllib_api_call.<locals>.<dictcomp>zSending a request - url: z, query_params: z, body_params: z	, files: z, json_body: , headers: Nr   rN   ignorerb)r%   has_json	has_filesrT   )r*   r?   r@   r>   rA   ?&r`   rc    z%Failed to decode Slack API response: F)okerrorr@   r<   r*   rb   )clientr=   rE   rF   r?   r*   re   )#r   r5   levelr2   DEBUGrX   rr   debugrV   r6   rG   rW   openrY   append	bytearrayrl   ioBytesIO_build_urllib_request_headersr%   rA   r   rf   rU   rh   decoderJSONDecodeErrorr   r   copyr   validateclosedclose)r7   r%   rP   rQ   rS   rR   r>   rT   files_to_closers   r*   request_dataro   rp   frequest_headersrequest_argsqri   response_bodyresponse_body_datamessage
all_paramsr9   r9   r:   r]      s   	

$



zBaseClient._urllib_api_callra   c                C   s  |d }|d rt |d }d|d< n|d rdt  }d|d }|d	 }t }|d }| D ]o\}	}
t|
d
d}|r|
	 rd}t|
dd}|r\t
|trZ|dn|}d|v rd|d }t|d pld}d|	 d| dd| d }|
 }
nd|	 d}t|
d}
|| ||d |d ||
 q6|| | }d| |d< t||d< n|d rt|d }d|d< nd}t
|tr|d}td|||d}d}d}t }d}|dk r|d7 }d |_z| ||}t| jdkryt|}t
|d! tr|d! nd}|dur!|dn|d! }|dur5|d"r5t |ni }t|d# |d ||d$}| jD ]2}|j|||d%rw| j j!t"j#krm| j $d&t%|j& d'|j' d(|j(  |j)|||d%  nqF|jd u r|W S W n3 t*yD } zt+|j, }|j-|d)}|j-d*krd+|vrd,|v r|d, |d+< d,|vrd+|v r|d+ |d,< |j,. pd}| |}||d!< t|}t|j-d-d. | D |dur|dndd/}| jD ]7}|j||||d0r*| j j!t"j#kr| j $d&t%|j& d'|j' d(|j( d1|  |j)||||d0  nq|jd u r:|W  Y d}~S W Y d}~nxd}~w t/y } zg|}| j 0d2|  t|}| jD ]E}|j||d|d0r| j j!t"j#kr| j $d&t%|j& d'|j' d(|j( d1|  |j)||d|d0 | j $d3|j' d(|j(   nq_|jd u r|W Y d}~nd}~ww |dk s|dur|S |)4a  Performs an HTTP request and parses the response.

        Args:
            url: Complete URL (e.g., https://slack.com/api/chat.postMessage)
            args: args has "headers", "data", "params", and "json"
                "headers": Dict[str, str]
                "data": Dict[str, Any]
                "params": Dict[str, str],
                "json": Dict[str, Any],

        Returns:
            dict {status: int, headers: Headers, body: str}
        r*   rA   application/json;charset=utf-8Content-Typer?   z--------------s   
--rO   s   --
readableNzUploaded filenamerN   filenamer   zapplication/octet-streamz(
Content-Disposition: form-data; name="z"; filename="z"
zContent-Type: z
s   
zmultipart/form-data; boundary=zContent-Lengthr@   !application/x-www-form-urlencodedr<   )methodrP   r?   r*   d   r   Frc   {rb   )re   r*   rc   r?   )staterequestri   zA retry handler found: z for  )rb   r*   i  zretry-afterzRetry-Afterc                 S   s   i | ]\}}||gqS r9   r9   rm   r9   r9   r:   rq     s    z;BaseClient._perform_urllib_http_request.<locals>.<dictcomp>rd   )r   r   ri   r   z - z.Failed to send a request to Slack API server: z!Going to retry the same request: )1rA   dumpsuuiduuid4rY   r   r   rr   getattrr   rV   rl   rZ   	mimetypes
guess_typereadrW   writegetvaluer6   r   r   r!   next_attempt_requested%_perform_urllib_http_request_internalr/   RetryHttpRequestfrom_urllib_http_request
startswithrh   RetryHttpResponse	can_retryr5   r   r2   r   infor\   r4   r   full_urlprepare_for_next_attemptr   rX   r*   codeget_content_charset	Exceptionr   )r7   rP   ra   r*   rc   boundarysep_boundaryend_boundaryr?   keyr_   r   r   	name_attrmimetypetitlereqresp
last_errorretry_statecounter_for_safetyretry_requestbody_string
body_bytesretry_responsehandlereresponse_headerscharsetr   errr9   r9   r:   rf   E  s*  










$
	

$

$
jz'BaseClient._perform_urllib_http_requestr   c                 C   sP  |  drd }| jd ur0t| jtr'tjt| j| jdt	| j
d}n	td| j dd }|r=|j|| jd}n	t|| j
| jd}|j dkrq| }| jjtjkri| jd	|j d
t|j d |j|j|dS |j pwd}| |}| jjtjkr| jd	|j d
t|j d|  |j|j|dS td| )Nhttp)r   https)contextzInvalid proxy detected: z must be a str value)r'   )r   r'   zapplication/gzipz*Received the following response - status: rv   z, body: (binary))rb   r*   rc   rN   z, body: zInvalid URL detected: )ru   r   r)   rV   rW   urllibr   build_openerr   r   r(   r   r   r'   r   r*   get_content_typer   r5   r   r2   r   r   r   rX   r   rZ   )r7   rP   r   openerr   rc   r   r9   r9   r:   r     sL   	

z0BaseClient._perform_urllib_http_request_internalry   rz   c                 C   s`   ddi}| | j |r| dd|i |r| | |r&| ddi |r.|dd  |S )Nr   r   rJ   z	Bearer {}r   )rG   r*   formatpop)r7   r%   ry   rz   rT   r*   r9   r9   r:   r   )  s   
z(BaseClient._build_urllib_request_headersc                C   s,   t ||||||d}t|d|ddS )z)Upload a file using the issued upload URL)rP   r?   r.   r'   r)   r(   rb   rc   )rb   rc   )r   r   rU   )r7   rP   r?   r.   r'   r)   r(   resultr9   r9   r:   _upload_file9  s   zBaseClient._upload_filesigning_secret	timestamp	signaturec                 C   sV   t dt td| d| }t| }t||tj	 }d| }t
||S )a  
        Slack creates a unique string for your app and shares it with you. Verify
        requests from Slack with confidence by verifying signatures using your
        signing secret.

        On each HTTP request that Slack sends, we add an X-Slack-Signature HTTP
        header. The signature is created by combining the signing secret with the
        body of the request we're sending using a standard HMAC-SHA256 keyed hash.

        https://api.slack.com/docs/verifying-requests-from-slack#how_to_make_a_request_signature_in_4_easy_steps__an_overview

        Args:
            signing_secret: Your application's signing secret, available in the
                Slack API dashboard
            data: The raw body of the incoming request - no headers, just the body.
            timestamp: from the 'X-Slack-Request-Timestamp' header
            signature: from the 'X-Slack-Signature' header - the calculated signature
                should match this.

        Returns:
            True if signatures matches
        zqAs this method is deprecated since slackclient 2.6.0, use `from slack.signature import SignatureVerifier` insteadzv0:rM   zv0=)warningswarnDeprecationWarningrW   rY   hmacnewhashlibsha256	hexdigestcompare_digest)r   r?   r   r   
format_reqencoded_secretrequest_hashcalculated_signaturer9   r9   r:   validate_slack_signatureS  s   

z#BaseClient.validate_slack_signature)!r4   
__module____qualname__BASE_URLr	   rW   rg   r   rX   r2   Loggerr   r   r;   r   rI   rH   r   r   rj   r   r   r]   rf   r   r   boolr   rl   r   r   staticmethodr   r9   r9   r9   r:   r#   *   s    	

5	

E.#


	

.p 3

2

	
$r#   )@__doc__r   r   r   r   rA   r2   r   r   r   r   base64r   http.clientr   r(   r   typingr   r   r   r   r	   r
   urllib.errorr   urllib.parser   urllib.requestr   r   r   r   r   slack_sdk.errorsr   deprecationr   file_upload_v2_resultr   internal_utilsr   r   r   r   r   r   slack_responser   slack_sdk.http_retryr   slack_sdk.http_retry.handlerr   slack_sdk.http_retry.requestr   r   slack_sdk.http_retry.responser    r   slack_sdk.http_retry.stater!   #slack_sdk.proxy_env_variable_loaderr"   r#   r9   r9   r9   r:   <module>   s>     