U
    #i:                     @  s  d dl m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mZ d dlmZmZmZmZmZ d dlmZmZ d	d
lmZmZ d	dlmZmZmZmZmZm Z m!Z!m"Z" d	dl#m$Z$m%Z% dgZ&G dd dZ'eddG dd dee'Z(eG dd de'Z)dS )    )annotationsN)	dataclassfield)BufferedReaderFileIO)JSONDecodeError)Path)AnyLiteralOptionalUnioncast)	HTTPErrorResponse   )DEFAULT_FILE_OPTIONSDEFAULT_SEARCH_OPTIONS)
BaseBucketCreateSignedURLsOptionsDownloadOptionsFileOptionsListBucketFilesOptionsRequestMethodSignedUploadURL
URLOptions)StorageException
SyncClient
SyncBucketc                	   @  s^  e Zd ZU dZded< ded< dEdddd	d
dddddZdddddZdFddddddddZi fdddddddZi fddd d!d"d#d$Z	i fdddd%d&d'Z
dddd(d)d*Zdddd(d+d,Zd-d.d/d0d1ZdGd2d3d!d%d4d5Zi fdd6d7d%d8d9ZdHd:ddddd;d<d=ZdIddddd>d?d@ZdJddddd>dAdBZddddCdDZdS )KSyncBucketActionsMixinz(Functions needed to access the file API.stridr   _clientNr   zOptional[dict[str, Any]]zOptional[dict[Any, Any]]zOptional[Any]r	   r   )methodurlheadersjsonfileskwargsreturnc           	      K  s   z.| j j||f|pi ||d|}|  W nV tk
r   z| }t|d|jiW n" tk
r~   td|jiY nX Y nX |S )N)r$   r%   r&   Z
statusCode)r!   requestraise_for_statusr   r%   r   status_coder   )	selfr"   r#   r$   r%   r&   r'   responseresp r/   ;/tmp/pip-unpacked-wheel-7lsqp372/storage3/_sync/file_api.py_request"   s&    	   zSyncBucketActionsMixin._requestr   )pathr(   c                 C  sx   |  |}| dd| }| }tjt| jj|d  }tj	|j
}|ds`td| |d d |dS )z
        Creates a signed upload URL.

        Parameters
        ----------
        path
            The file path, including the file name. For example `folder/image.png`.
        POST/object/upload/sign/r#   tokenzNo token sent by the APIr   )Z
signed_urlr5   r2   )_get_final_pathr1   r%   urllibparseurlparser   r!   base_urlparse_qsquerygetr   geturl)r,   r2   _pathr-   datafull_urlquery_paramsr/   r/   r0   create_signed_upload_url9   s    	


z/SyncBucketActionsMixin.create_signed_upload_urlz/Union[BufferedReader, bytes, FileIO, str, Path]zOptional[FileOptions])r2   r5   filefile_optionsr(   c                 C  s   |  |}tjd| }tjd|i}|  d| }|dkrJi }|d}	i }
|	rrd|	 |d< d|	i}
| jjt	|}|j
dd	d
d }t|tst|tst|trd|||dfi}nd|t|d|dfi}| jd||||
dS )a  
        Upload a file with a token generated from :meth:`.create_signed_url`

        Parameters
        ----------
        path
            The file path, including the file name
        token
            The token generated from :meth:`.create_signed_url`
        file
            The file contents or a file-like object to upload
        file_options
            Additional options for the uploaded file
        r4   r5   ?Ncache-controlmax-age=cacheControl/   maxsplitrD   content-typerbPUTr&   r$   r@   )r6   r7   r8   r9   	urlencoder>   r=   r!   r$   r   rsplit
isinstancer   bytesr   popopenr1   )r,   r2   r5   rD   rE   r?   _urlrB   Z	final_urlcache_control_datar$   filename_filer/   r/   r0   upload_to_signed_urlQ   s<    

z+SyncBucketActionsMixin.upload_to_signed_urlintr   zdict[str, str])r2   
expires_inoptionsr(   c                 C  s   dt |i}|dr(|d|d i |drD|d|d i | |}| jdd| |d}| }| jj tt |d 	d |d< |S )	a/  
        Parameters
        ----------
        path
            file path to be downloaded, including the current file name.
        expires_in
            number of seconds until the signed URL expires.
        options
            options to be passed for downloading or transforming the file.
        	expiresIndownload	transformr3   /object/sign/r%   	signedURLrJ   )
r   r=   updater6   r1   r%   r!   r:   r   lstrip)r,   r2   r`   ra   r%   r-   r@   r/   r/   r0   create_signed_url   s    


z(SyncBucketActionsMixin.create_signed_urlz	list[str]r   zlist[dict[str, str]])pathsr`   ra   r(   c                 C  s~   |t |d}|dr,|d|di | jdd| j |d}| }|D ](}| jj tt |d 	d |d< qP|S )a  
        Parameters
        ----------
        path
            file path to be downloaded, including the current file name.
        expires_in
            number of seconds until the signed URL expires.
        options
            options to be passed for downloading the file.
        )rk   rb   rc   r3   re   rf   rg   rJ   )
r   r=   rh   r1   r    r%   r!   r:   r   ri   )r,   rk   r`   ra   r%   r-   r@   itemr/   r/   r0   create_signed_urls   s    

z)SyncBucketActionsMixin.create_signed_urls)r2   ra   r(   c           	      C  s   g }d}| dr4| ddkr$dnd| d }|rB|| | drPdnd}| drptj| dnd}|r|| d|}d	| }| |}| jj | d
| | S )z
        Parameters
        ----------
        path
            file path, including the path and file name. For example `folder/image.png`.
        Nrc   Tz	download=rd   zrender/imageobject&rF   z/public/)	r=   appendr7   r8   rS   joinr6   r!   r:   )	r,   r2   ra   Z_query_stringZdownload_queryrender_pathtransformation_queryquery_stringr?   r/   r/   r0   get_public_url   s(    





z%SyncBucketActionsMixin.get_public_url)	from_pathto_pathr(   c                 C  s"   | j dd| j||dd}| S )aa  
        Moves an existing file, optionally renaming it at the same time.

        Parameters
        ----------
        from_path
            The original file path, including the current file name. For example `folder/image.png`.
        to_path
            The new file path, including the new file name. For example `folder/image-copy.png`.
        r3   z/object/moveZbucketIdZ	sourceKeyZdestinationKeyrf   r1   r    r%   r,   rv   rw   resr/   r/   r0   move   s    	zSyncBucketActionsMixin.movec                 C  s"   | j dd| j||dd}| S )aZ  
        Copies an existing file to a new path in the same bucket.

        Parameters
        ----------
        from_path
            The original file path, including the current file name. For example `folder/image.png`.
        to_path
            The new file path, including the new file name. For example `folder/image-copy.png`.
        r3   z/object/copyrx   rf   ry   rz   r/   r/   r0   copy  s    	zSyncBucketActionsMixin.copylistzlist[dict[str, Any]])rk   r(   c                 C  s$   | j dd| j d|id}| S )z
        Deletes files within the same bucket

        Parameters
        ----------
        paths
            An array or list of files to be deletes, including the path and file name. For example [`folder/image.png`].
        DELETE/object/prefixesrf   ry   )r,   rk   r-   r/   r/   r0   remove  s    	
zSyncBucketActionsMixin.removezOptional[str]z Optional[ListBucketFilesOptions]c                 C  sD   |pi }ddi}t |d|pdi}| jdd| j ||d}| S )z
        Lists all the files within a bucket.

        Parameters
        ----------
        path
            The folder path.
        options
            Search options, including `limit`, `offset`, and `sortBy`.
        zContent-Typezapplication/jsonprefix r3   z/object/list/)r%   r$   )r   r1   r    r%   )r,   r2   ra   Zextra_optionsextra_headersbodyr-   r/   r/   r0   r~   (  s     
zSyncBucketActionsMixin.listr   rV   c                 C  sd   | drdnd}tj| dp$i }|r6d| nd}| |}| d| d| | }|jS )z
        Downloads a file.

        Parameters
        ----------
        path
            The file path to be downloaded, including the path and file name. For example `folder/image.png`.
        rd   zrender/image/authenticatedrn   rF   r   GETrJ   )r=   r7   r8   rS   r6   r1   content)r,   r2   ra   rr   rs   rt   r?   r-   r/   r/   r0   rc   F  s    

zSyncBucketActionsMixin.downloadzLiteral[('POST', 'PUT')])r"   r2   rD   rE   r(   c                 C  s   |dkri }| d}i }| dr>|d| di |d= | jjt|}|dkrZ|d= |jdddd	 }|rd
| |d< d|i}t|tst|tst|t	rd|||
dfi}	nd|t|d|
dfi}	| |}
| j|d|
 |	||dS )  
        Uploads a file to an existing bucket.

        Parameters
        ----------
        path
            The relative file path including the bucket ID. Should be of the format `bucket/folder/subfolder/filename.png`.
            The bucket must already exist before attempting to upload.
        file
            The File object to be stored in the bucket. or a async generator of chunks
        file_options
            HTTP headers.
        NrG   Zupsertzx-upsertr3   rJ   rK   rL   rN   rH   rI   rD   rO   rP   r   rR   )r=   rh   r!   r$   r   rT   rU   r   rV   r   rW   rX   r6   r1   )r,   r"   r2   rD   rE   rZ   r[   r$   r\   r&   r?   r/   r/   r0   _upload_or_update\  sL    


    z(SyncBucketActionsMixin._upload_or_update)r2   rD   rE   r(   c                 C  s   |  d|||S )r   r3   r   r,   r2   rD   rE   r/   r/   r0   upload  s    zSyncBucketActionsMixin.uploadc                 C  s   |  d|||S )NrQ   r   r   r/   r/   r0   rh     s    zSyncBucketActionsMixin.updatec                 C  s   | j  d| S )NrJ   )r    )r,   r2   r/   r/   r0   r6     s    z&SyncBucketActionsMixin._get_final_path)NNN)N)NN)N)N)N)__name__
__module____qualname____doc____annotations__r1   rC   r^   rj   rm   ru   r|   r}   r   r~   rc   r   r   rh   r6   r/   r/   r/   r0   r      s:   
    > "   G  r   Freprc                   @  s$   e Zd ZU dZeddZded< dS )r   zRepresents a storage bucket.Fr   r   r!   N)r   r   r   r   r   r!   r   r/   r/   r/   r0   r     s   
c                   @  s,   e Zd ZU dZded< eddZded< dS )	SyncBucketProxyzPA bucket proxy, this contains the minimum required fields to query the File API.r   r    Fr   r   r!   N)r   r   r   r   r   r   r!   r/   r/   r/   r0   r     s   
r   )*
__future__r   urllib.parser7   Zdataclassesr   r   ior   r   r%   r   pathlibr   typingr	   r
   r   r   r   Zhttpxr   r   	constantsr   r   typesr   r   r   r   r   r   r   r   utilsr   r   __all__r   r   r   r/   r/   r/   r0   <module>   s&   (
   *