a
    |f>                     @   s   d Z ddlmZ ddlmZmZmZmZmZm	Z	 ddl
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 dd	lmZ dd
lmZmZ ddlmZmZmZmZ G dd dZ dS )zn
gspread.client
~~~~~~~~~~~~~~

This module contains Client class responsible for managing spreadsheet files

    )
HTTPStatus)AnyDictListOptionalTupleUnion)Credentials)ResponseSession   )APIErrorSpreadsheetNotFound)
HTTPClientHTTPClientType
ParamsType)Spreadsheet)DRIVE_FILES_API_V3_COMMENTS_URLDRIVE_FILES_API_V3_URL)ExportFormatMimeTypeextract_id_from_urlfinditemc                
   @   s  e Zd ZdZdefeee eddddZ	d4ee
eeeef f  ddddZeed	d
dZd5ee ee eeeef  dddZd6ee ee eeeeef  ef dddZd7eee edddZeedddZeedddZd8ee ee dddZd9eee edddZejfeeeddd Zd:eee e ee e ed#d$d%Z!edd&d'd(Z"ee
eef ed)d*d+Z#eeeee
ee f f  d&d,d-Z$d;eee ee ee e ee e ed.d/d0Z%eedd1d2d3Z&dS )<Clienta7  An instance of this class Manages Spreadsheet files

    It is used to:
        - open/create/list/delete spreadsheets
        - create/delete/list spreadsheet permission
        - etc

    It is the gspread entry point.
    It will handle creating necessary :class:`~gspread.models.Spreadsheet` instances.
    N)authsessionhttp_clientreturnc                 C   s   |||| _ d S )N)r   )selfr   r   r    r   HD:\Projects\storyit_web\backend\venv\Lib\site-packages\gspread/client.py__init__"   s    zClient.__init__)timeoutr   c                 C   s   | j | dS )zHow long to wait for the server to send
        data before giving up, as a float, or a ``(connect timeout,
        read timeout)`` tuple.

        Use value ``None`` to restore default timeout

        Value for ``timeout`` is in seconds (s).
        N)r   set_timeout)r   r"   r   r   r    r#   *   s    zClient.set_timeout)idr   c                 C   s   | j |S )zGet the metadata from the Drive API for a specific file
        This method is mainly here to retrieve the create/update time
        of a file (these metadata are only accessible from the Drive API).
        )r   get_file_drive_metadata)r   r$   r   r   r    r%   7   s    zClient.get_file_drive_metadata)title	folder_idr   c                 C   s   | j ||d\}}|S )a:  List all the spreadsheet files

        Will list all spreadsheet files owned by/shared with this user account.

        :param str title: Filter only spreadsheet files with this title
        :param str folder_id: Only look for spreadsheet files in this folder
            The parameter ``folder_id`` can be obtained from the URL when looking at
            a folder in a web browser as follow:
            ``https://drive.google.com/drive/u/0/folders/<folder_id>``

        :returns: a list of dicts containing the keys id, name, createdTime and modifiedTime.
        )r&   r'   )_list_spreadsheet_files)r   r&   r'   files_r   r   r    list_spreadsheet_files>   s    zClient.list_spreadsheet_filesc           
      C   s   g }d}t }dtj d}|r.|d| d7 }|rB|d| d7 }|ddddd	}|r^||d
< | jjd||d}| }	||	d  |	dd }|d u rRqqR||fS )N z
mimeType=""z and name = "z and parents in "i  Tz:kind,nextPageToken,files(id,name,createdTime,modifiedTime))qpageSizesupportsAllDrivesZincludeItemsFromAllDrivesfields	pageTokengetparamsr)   nextPageToken)r   r   google_sheetsr   requestjsonextendr3   )
r   r&   r'   r)   
page_tokenurlqueryr5   responseZresponse_jsonr   r   r    r(   P   s.    	zClient._list_spreadsheet_filesc              
      sn   |   |\}}zt fdd|}W n. tyT } zt||W Y d}~n
d}~0 0 |d |d< t| j|S )a.  Opens a spreadsheet.

        :param str title: A title of a spreadsheet.
        :param str folder_id: (optional) If specified can be used to filter
            spreadsheets by parent folder ID.
        :returns: a :class:`~gspread.models.Spreadsheet` instance.

        If there's more than one spreadsheet with same title the first one
        will be opened.

        :raises gspread.SpreadsheetNotFound: if no spreadsheet with
                                             specified `title` is found.

        >>> gc.open('My fancy spreadsheet')
        c                    s   | d  kS )Nnamer   )xr&   r   r    <lambda>       zClient.open.<locals>.<lambda>Nr?   r&   )r(   r   StopIterationr   r   r   )r   r&   r'   spreadsheet_filesr>   
propertiesexr   rA   r    opent   s    
 zClient.open)keyr   c              
   C   sp   zt | jd|i}W nV tyj } z>|jjtjkr>t|j||jjtjkrRt	||W Y d}~n
d}~0 0 |S )a+  Opens a spreadsheet specified by `key` (a.k.a Spreadsheet ID).

        :param str key: A key of a spreadsheet as it appears in a URL in a browser.
        :returns: a :class:`~gspread.models.Spreadsheet` instance.

        >>> gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')
        r$   N)
r   r   r   r>   status_coder   	NOT_FOUNDr   	FORBIDDENPermissionError)r   rI   spreadsheetrG   r   r   r    open_by_key   s    zClient.open_by_key)r<   r   c                 C   s   |  t|S )a  Opens a spreadsheet specified by `url`.

        :param str url: URL of a spreadsheet as it appears in a browser.

        :returns: a :class:`~gspread.models.Spreadsheet` instance.

        :raises gspread.SpreadsheetNotFound: if no spreadsheet with
                                             specified `url` is found.

        >>> gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl')
        )rO   r   )r   r<   r   r   r    open_by_url   s    zClient.open_by_url)r&   r   c                    s2     }r fdd|D } fdd|D S )zOpens all available spreadsheets.

        :param str title: (optional) If specified can be used to filter
            spreadsheets by title.

        :returns: a list of :class:`~gspread.models.Spreadsheet` instances.
        c                    s   g | ]} |d  kr|qS )r?   r   ).0ZspreadrA   r   r    
<listcomp>   s   z"Client.openall.<locals>.<listcomp>c              	      s*   g | ]"}t  jtf d |d i|qS )r&   r?   )r   r   dict)rQ   r@   )r   r   r    rR      s   )r+   )r   r&   rE   r   )r   r&   r    openall   s    


zClient.openallc                 C   sP   |t jd}ddi}|dur&|g|d< | jjdt||d}| d }| |S )	a  Creates a new spreadsheet.

        :param str title: A title of a new spreadsheet.

        :param str folder_id: Id of the folder where we want to save
            the spreadsheet.

        :returns: a :class:`~gspread.models.Spreadsheet` instance.

        r?   ZmimeTyper0   TNparentspostr9   r5   r$   )r   r7   r   r8   r   r9   rO   )r   r&   r'   payloadr5   rspreadsheet_idr   r   r    create   s    
zClient.create)file_idformatr   c                 C   s   | j j||dS )a  Export the spreadsheet in the given format.

        :param str file_id: The key of the spreadsheet to export

        :param str format: The format of the resulting file.
            Possible values are:

                * ``ExportFormat.PDF``
                * ``ExportFormat.EXCEL``
                * ``ExportFormat.CSV``
                * ``ExportFormat.OPEN_OFFICE_SHEET``
                * ``ExportFormat.TSV``
                * ``ExportFormat.ZIPPED_HTML``

            See `ExportFormat`_ in the Drive API.

        :type format: :class:`~gspread.utils.ExportFormat`

        :returns bytes: The content of the exported file.

        .. _ExportFormat: https://developers.google.com/drive/api/guides/ref-export-formats
        )r]   r^   )r   export)r   r]   r^   r   r   r    r_      s    zClient.exportFT)r]   r&   copy_permissionsr'   copy_commentsr   c                 C   s  d t|}|tjd}|dur*|g|d< ddi}| jjd|||d}	|	 d	 }
| |
}|du r| |}| }|D ]p}|	d
rqzd}t
|d dkrt
|d }nt
|d dv rt
|d }|j|t
|d t
|d dd qz|du rt| }d}g }dddd}|durX||d< | jjd||d }||d  |	dd}qt|j }dd	i}|D ]}| jjd|||d qn|S )a  Copies a spreadsheet.

        :param str file_id: A key of a spreadsheet to copy.
        :param str title: (optional) A title for the new spreadsheet.

        :param bool copy_permissions: (optional) If True, copy permissions from
            the original spreadsheet to the new spreadsheet.

        :param str folder_id: Id of the folder where we want to save
            the spreadsheet.

        :param bool copy_comments: (optional) If True, copy the comments from
            the original spreadsheet to the new spreadsheet.

        :returns: a :class:`~gspread.models.Spreadsheet` instance.

        .. versionadded:: 3.1.0

        .. note::

           If you're using custom credentials without the Drive scope, you need to add
           ``https://www.googleapis.com/auth/drive`` to your OAuth scope in order to use
           this method.

           Example::

              scope = [
                  'https://www.googleapis.com/auth/spreadsheets',
                  'https://www.googleapis.com/auth/drive'
              ]

           Otherwise, you will get an ``Insufficient Permission`` error
           when you try to copy a spreadsheet.

        z
{}/{}/copyrU   NrV   r0   TrW   rX   r$   Zdeletedr,   typedomain)usergroupZemailAddressroleF)Zemail_address	perm_typerf   notifyz.comments/content,comments/anchor,nextPageTokend   )r1   ZincludeDeletedr/   r2   r3   r4   commentsr6   r1   )r^   r   r   r7   r   r8   r9   rO   list_permissionsr3   strsharer   r:   r$   )r   r]   r&   r`   r'   ra   r<   rY   r5   rZ   r[   Znew_spreadsheetoriginalZpermissionspZemail_or_domain
source_urlr;   rj   resZdestination_urlcommentr   r   r    copy   s^    +









zClient.copy)r]   r   c                 C   s*   d t|}ddi}| jjd||d dS )z^Deletes a spreadsheet.

        :param str file_id: a spreadsheet ID (a.k.a file ID).
        z{}/{}r0   Tdeleter4   N)r^   r   r   r8   )r   r]   r<   r5   r   r   r    del_spreadsheetm  s    zClient.del_spreadsheet)r]   datar   c                 C   s   | j ||S )a  Imports data into the first page of the spreadsheet.

        :param str file_id:
        :param str data: A CSV string of data.

        Example:

        .. code::

            # Read CSV file contents
            content = open('file_to_import.csv', 'r').read()

            gc.import_csv(spreadsheet.id, content)

        .. note::

           This method removes all other worksheets and then entirely
           replaces the contents of the first worksheet.

        )r   
import_csv)r   r]   rv   r   r   r    rw   w  s    zClient.import_csvc                 C   s   | j |S )zpRetrieve a list of permissions for a file.

        :param str file_id: a spreadsheet ID (aka file ID).
        )r   rk   )r   r]   r   r   r    rk     s    zClient.list_permissions)r]   valuerg   rf   rh   email_message	with_linkr   c              	   C   s   | j |||||||S )ap  Creates a new permission for a file.

        :param str file_id: a spreadsheet ID (aka file ID).
        :param value: user or group e-mail address, domain name
            or None for 'anyone' type.
        :type value: str, None
        :param str perm_type: (optional) The account type.
            Allowed values are: ``user``, ``group``, ``domain``, ``anyone``
        :param str role: (optional) The primary role for this user.
            Allowed values are: ``owner``, ``writer``, ``reader``
        :param bool notify: (optional) Whether to send an email to the target
            user/domain.
        :param str email_message: (optional) An email message to be sent
            if ``notify=True``.
        :param bool with_link: (optional) Whether the link is required for this
            permission to be active.

        :returns dict: the newly created permission

        Examples::

            # Give write permissions to otto@example.com

            gc.insert_permission(
                '0BmgG6nO_6dprnRRUWl1UFE',
                'otto@example.org',
                perm_type='user',
                role='writer'
            )

            # Make the spreadsheet publicly readable

            gc.insert_permission(
                '0BmgG6nO_6dprnRRUWl1UFE',
                None,
                perm_type='anyone',
                role='reader'
            )

        )r   insert_permission)r   r]   rx   rg   rf   rh   ry   rz   r   r   r    r{     s    2zClient.insert_permission)r]   permission_idr   c                 C   s   | j || dS )zDeletes a permission from a file.

        :param str file_id: a spreadsheet ID (aka file ID.)
        :param str permission_id: an ID for the permission.
        N)r   remove_permission)r   r]   r|   r   r   r    r}     s    zClient.remove_permission)N)NN)NN)N)N)N)NFNT)NNNTNF)'__name__
__module____qualname____doc__r   r	   r   r   r   r!   r   floatr   r#   rl   r   r%   r   r   r+   r
   r(   r   rH   rO   rP   rT   r\   r   ZPDFbytesr_   boolrs   ru   rw   rk   r{   r}   r   r   r   r    r      s~   	   $    p
$
      6r   N)!r   httpr   typingr   r   r   r   r   r   Zgoogle.auth.credentialsr	   requestsr
   r   
exceptionsr   r   r   r   r   r   rN   r   urlsr   r   utilsr   r   r   r   r   r   r   r   r    <module>   s    