a
    m b+                     @   s&  d Z ddlZzddlmZ W n ey:   ddlmZ Y n0 ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ dd	lmZ dd
lmZ ddlmZ dd ZG dd de	ZG dd de	ZG dd de	ZG dd de
ZG dd de
ZdZde efdeef efde efde efdefgZdS )zTornado handlers for the contents web service.

Preliminary documentation at https://github.com/ipython/ipython/wiki/IPEP-27%3A-Contents-Service
    N)json_default)date_default)web)
APIHandler)JupyterHandler)
path_regex)ensure_async)
url_escape)url_path_joinc                    s   h d}|t    }|r0tddj|dddg}|rh fdd|D }|rtdd	j|d
n* fdd|D }|rtddj|d
dS )z
    Validate a model returned by a ContentsManager method.

    If expect_content is True, then we expect non-null entries for 'content'
    and 'format'.
    >	   ZmimetypewritableformattypeZcreatednamelast_modifiedcontentpathi  zMissing Model Keys: {missing})missingr   r   c                    s   g | ]} | d u r|qS N .0keymodelr   Hlib/python3.9/site-packages/jupyter_server/services/contents/handlers.py
<listcomp>2       z"validate_model.<locals>.<listcomp>zKeys unexpectedly None: {keys})keysc                    s"   i | ]} | d ur| | qS r   r   r   r   r   r   
<dictcomp>9   r   z"validate_model.<locals>.<dictcomp>z"Keys unexpectedly not None: {keys}N)setr   r   	HTTPErrorr   )r   expect_contentrequired_keysr   Zmaybe_none_keyserrorsr   r   r   validate_model   s*    


r$   c                   @   s   e Zd Zdd ZdddZejdddZejdd	d
ZdddZ	dd Z
dddZdd ZejdddZejd ddZejd!ddZdS )"ContentsHandlerc                 C   s   t | jddt|S )zReturn the full URL location of a file.

        Parameters
        ----------
        path : unicode
            The API path of the file, such as "foo/bar.txt".
        Zapicontents)r
   base_urlr	   selfr   r   r   r   location_urlB   s    zContentsHandler.location_urlTc                 C   sR   |r|  |d }| d| | d|d  | dd | tj|td dS )	zBFinish a JSON request with a model, setting relevant headers, etc.r   LocationzLast-Modifiedr   zContent-Typezapplication/jsondefaultN)r*   
set_headerfinishjsondumpsr   )r)   r   locationr   r   r   _finish_modelL   s    zContentsHandler._finish_model c                    s   |pd}| j ddd}|dvr.tdd| | j ddd}|d	vrTtdd
| | j ddd}|dvrztdd| t|}t| jj||||dI dH }t||d | j|dd dS )zReturn a model for a file or directory.

        A directory model contains a list of models (without content)
        of the files and directories it contains.
        r4   r   Nr,   >   NZnotebookfileZ	directory  zType %r is invalidr   >   Ntextbase64zFormat %r is invalidr   1>   0r9   zContent %r is invalid)r   r   r   r   r!   F)r2   )	Zget_query_argumentr   r    intr   contents_managergetr$   r3   )r)   r   r   r   r   r   r   r   r   r>   U   s*    
zContentsHandler.getc                    sR   | j }|  }|du r"tddt|||I dH }t|dd | | dS )z?PATCH renames a file or directory without re-uploading content.Nr6   zJSON body missingFr;   )r=   get_json_bodyr   r    r   updater$   r3   )r)   r   cmr   r   r   r   patcht   s    zContentsHandler.patchNc                    sV   | j dj||pdd t| j||I dH }| d t|dd | | dS )z6Copy a file, optionally specifying a target directory.z Copying {copy_from} to {copy_to}r4   )	copy_fromcopy_toN   Fr;   )	loginfor   r   r=   copy
set_statusr$   r3   )r)   rC   rD   r   r   r   r   _copy   s    
zContentsHandler._copyc                    sJ   | j d| t| j||I dH }| d t|dd | | dS )z#Handle upload of a new file to pathzUploading file to %sNrE   Fr;   )rF   rG   r   r=   newrI   r$   r3   )r)   r   r   r   r   r   _upload   s
    
zContentsHandler._uploadc                    sT   | j d|pd| t| jj|||dI dH }| d t|dd | | dS )z#Create a new, empty untitled entityzCreating new %s in %sr5   )r   r   extNrE   Fr;   )rF   rG   r   r=   Znew_untitledrI   r$   r3   )r)   r   r   rM   r   r   r   r   _new_untitled   s    

zContentsHandler._new_untitledc                    sX   | dd}|r|dkr&| jd| t| j||I dH }t|dd | | dS )zSave an existing file.chunkNzSaving file at %sFr;   )r>   rF   rG   r   r=   Zsaver$   r3   )r)   r   r   rO   r   r   r   _save   s    zContentsHandler._savec           	         s   | j }t||I dH }|r*tddt||I dH }|sRtdd| |  }|dur|d}|dd}|d	d}|r| ||I dH  q| j	|||d
I dH  n| 	|I dH  dS )aZ  Create a new file in the specified path.

        POST creates new files. The server always decides on the name.

        POST /api/contents/path
          New untitled, empty file or directory.
        POST /api/contents/path
          with body {"copy_from" : "/path/to/OtherNotebook.ipynb"}
          New copy of OtherNotebook in path
        Nr6   z&Cannot POST to files, use PUT instead.i  zNo such directory: %srC   rM   r4   r   )r   rM   )
r=   r   file_existsr   r    
dir_existsr?   r>   rJ   rN   )	r)   r   rA   rR   rS   r   rC   rM   r   r   r   r   post   s     
zContentsHandler.postc                    sx   |   }|rd|dr"tddt| j|I dH }|rP| ||I dH  qt| ||I dH  n| 	|I dH  dS )a  Saves the file in the location specified by name and path.

        PUT is very similar to POST, but the requester specifies the name,
        whereas with POST, the server picks the name.

        PUT /api/contents/path/Name.ipynb
          Save notebook at ``path/Name.ipynb``. Notebook structure is specified
          in `content` key of JSON request body. If content is not specified,
          create a new empty notebook.
        rC   r6   zCannot copy with PUT, only POSTN)
r?   r>   r   r    r   r=   rR   rQ   rL   rN   )r)   r   r   existsr   r   r   put   s    
zContentsHandler.putc                    s>   | j }| jd| t||I dH  | d |   dS )zdelete a file in the given pathz	delete %sN   )r=   rF   warningr   deleterI   r/   r)   r   rA   r   r   r   rY      s
    
zContentsHandler.delete)T)r4   )r4   )N)r4   r4   )r4   )r4   )r4   )__name__
__module____qualname__r*   r3   r   authenticatedr>   rB   rJ   rL   rN   rQ   rT   rV   rY   r   r   r   r   r%   A   s    

	



	#r%   c                   @   s,   e Zd ZejdddZejdddZdS )	CheckpointsHandlerr4   c                    s6   | j }t||I dH }tj|td}| | dS )z get lists checkpoints for a fileNr,   )r=   r   Zlist_checkpointsr0   r1   r   r/   )r)   r   rA   checkpointsdatar   r   r   r>      s    zCheckpointsHandler.getc                    sj   | j }t||I dH }tj|td}t| jdt|dt|d }| 	d| | 
d | | dS )zpost creates a new checkpointNr,   api/contentsr`   idr+   rE   )r=   r   Zcreate_checkpointr0   r1   r   r
   r'   r	   r.   rI   r/   )r)   r   rA   Z
checkpointra   r2   r   r   r   rT      s    

zCheckpointsHandler.postN)r4   )r4   )r[   r\   r]   r   r^   r>   rT   r   r   r   r   r_      s   r_   c                   @   s(   e Zd Zejdd Zejdd ZdS )ModifyCheckpointsHandlerc                    s2   | j }t|||I dH  | d |   dS )z&post restores a file from a checkpointNrW   )r=   r   Zrestore_checkpointrI   r/   r)   r   Zcheckpoint_idrA   r   r   r   rT   	  s    
zModifyCheckpointsHandler.postc                    s2   | j }t|||I dH  | d |   dS )z+delete clears a checkpoint for a given fileNrW   )r=   r   Zdelete_checkpointrI   r/   re   r   r   r   rY     s    
zModifyCheckpointsHandler.deleteN)r[   r\   r]   r   r^   rT   rY   r   r   r   r   rd     s   
rd   c                   @   s,   e Zd ZdZdZdd Ze Z Z ZZ	dS )NotebooksRedirectHandlerz(Redirect /api/notebooks to /api/contents)ZGETZPUTZPATCHZPOSTZDELETEc                 C   s(   | j d | t| jdt| d S )Nz//api/notebooks is deprecated, use /api/contentsrb   )rF   rX   Zredirectr
   r'   r	   r(   r   r   r   r>     s    zNotebooksRedirectHandler.getN)
r[   r\   r]   __doc__ZSUPPORTED_METHODSr>   rV   rB   rT   rY   r   r   r   r   rf     s   rf   c                   @   s    e Zd ZdZejdddZdS )TrustNotebooksHandlerz$ Handles trust/signing of notebooks r4   c                    s0   | j }t||I d H  | d |   d S )NrE   )r=   r   Ztrust_notebookrI   r/   rZ   r   r   r   rT   )  s    
zTrustNotebooksHandler.postN)r4   )r[   r\   r]   rg   r   r^   rT   r   r   r   r   rh   &  s   rh   z(?P<checkpoint_id>[\w-]+)z/api/contents%s/checkpointsz/api/contents%s/checkpoints/%sz/api/contents%s/trustz/api/contents%sz/api/notebooks/?(.*))rg   r0   Zjupyter_client.jsonutilr   ImportErrorr   Ztornador   Zjupyter_server.base.handlersr   r   r   Zjupyter_server.utilsr   r	   r
   r$   r%   r_   rd   rf   rh   Z_checkpoint_id_regexZdefault_handlersr   r   r   r   <module>   s8   * -



