
    Mh;                        d Z ddlZddlmZ ddlmZ 	 ddlmZ n# e$ r	 ddlm	Z Y nw xY wddl
mZ ddlmZ dd	lmZmZ dd
lmZmZmZ ddlmZmZ dZdedeeef         dee         fdZd&dZ G d de          Z G d de          Z  G d de          Z! G d de          Z" G d de          Z# G d de          Z$dZ%d ez  e!fd!e d"e% e"fd#ez  e$fd$ez  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)
HTTPStatus)Any)json_default)date_default)ensure_async)web)allow_unauthenticated
authorized)
APIHandlerJupyterHandler
path_regex)
url_escapeurl_path_joincontentsexpect_definedmodelkeysc                     | r*fd|D             }|rt          j        dd|           dS fd|D             }|rt          j        dd|           dS )zO
    Validate that the keys are defined (i.e. not None) or not (i.e. None)
    c                 $    g | ]}|         
|S N .0keyr   s     i/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/jupyter_server/services/contents/handlers.py
<listcomp>z"_validate_keys.<locals>.<listcomp>!   s"    <<<#s);#);););      zKeys unexpectedly None: c                 2    i | ]}|         
||         S r   r   r   s     r   
<dictcomp>z"_validate_keys.<locals>.<dictcomp>(   s(    LLLcU3Z5K#uSz5K5K5Kr   zKeys unexpectedly not None: N)r   	HTTPError)r   r   r   errorss    `  r   _validate_keysr#      s    
  <<<<<<< 	-3633  	 	 MLLLTLLL 	-7v77  	 	r   Fc                    h d}|r|                     ddg           |t          |                                           z
  }|rt          j        dd|           ddg}t          || |           |rt          || ddg           dS 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'.

    If expect_hash is True, then we expect non-null entries for 'hash' and 'hash_algorithm'.
    >	   namepathtypeformatcontentcreatedmimetypewritablelast_modifiedhashhash_algorithmr   zMissing Model Keys: r)   r(   N)updatesetr   r   r!   r#   )r   expect_contentexpect_hashrequired_keysmissingcontent_keyss         r   validate_modelr7   0   s    
 
 
M  9f&67888c%**,,///G 
m,7,,
 
 	

 x(L>5,777 G{EF4D+EFFFFFG Gr   c                       e Zd ZdZeZdS )ContentsAPIHandlerzA contents API handler.N)__name__
__module____qualname____doc__AUTH_RESOURCEauth_resourcer   r   r   r9   r9   S   s        !!!MMMr   r9   c                   <   e Zd ZdZd ZddZd Zej        e	dd                        Z
ej        e	dd                        Zdd
Zd ZddZd Zej        e	dd                        Zej        e	dd                        Zej        e	dd                        Zd	S )ContentsHandlerzA contents handler.c                 J    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".
        apir   )r   base_urlr   selfr&   s     r   location_urlzContentsHandler.location_url\   s"     T]E:z$?O?OPPPr   Tc                 ,   |r1|                      |d                   }|                     d|           |                     d|d                    |                     dd           |                     t          j        |t
                               dS )	zBFinish a JSON request with a model, setting relevant headers, etc.r&   LocationzLast-Modifiedr-   zContent-Typezapplication/jsondefaultN)rG   
set_headerfinishjsondumpsr   )rF   r   locations      r   _finish_modelzContentsHandler._finish_modelf   s     	2((v77HOOJ111)?@@@(:;;;DJul;;;<<<<<r   c                    K   |                      |           |                     |           |                                  d{V  dS )z@Finish a JSON request with an error code and descriptive messageN)
set_statuswriterM   )rF   codemessages      r   _finish_errorzContentsHandler._finish_erroro   sP      

7kkmmr    c           	      t  K   |pd}| j         }|                     dd          }|dvrd}|                     dd          }|dvrt          j        d	d
|z            |                     dd          }|dvrt          j        d	d|z            t	          |pd          }|                     dd          }|dvrt          j        d	d|d          t	          |          }|j        sRt          |                    |                     d{V r*|                     t          j
        d|d           d{V  	 |}		 t          | j                             |||||                     d{V }
nC# t          $ r6 d}	t          | j                             ||||                     d{V }
Y nw xY wt          |
||	           |                     |
d           dS # t          j        $ rE}|j        t          j
        k    r*|                     t          j
        d|d           d{V   d}~ww xY w)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.
        rX   r'   NrJ   >   Nfilenotebook	directoryrZ   r(   >   Ntextbase64  zFormat %r is invalidr)   1>   0r`   zContent %r is invalidr.   ra   zHash argument z# is invalid. It must be '0' or '1'.zfile or directory z does not exist)r&   r'   r(   r)   require_hashF)r&   r'   r(   r)   )r2   r3   )rP   )contents_managerget_query_argumentr   r!   intallow_hiddenr   	is_hiddenrW   r   	NOT_FOUNDget	TypeErrorr7   rQ   status_code)rF   r&   cmr'   r(   content_strr)   hash_strrb   r3   r   excs               r   ri   zContentsHandler.getu   s;      zr"&&vt&<<>>>D((4(@@111-%;f%DEEE--i-EEj((-%<{%JKKKk'R((**63*??:%%-UhUUU   8}} 	bll46H6H)I)I#I#I#I#I#I#I 	$$$&R4&R&R&R         	&K*)--!!% '%1 .              $*)--!!% '	 .         	 5kRRRRuu55555} 	 	 	*"666(((*Vt*V*V*V         	s=   ?G# 2E5 4G# 5=F52G# 4F55,G# #H72A H22H7c                   K   | j         }|                                 }|t          j        dd          |                    d          }|ro|j        sht          |                    |                     d{V s(t          |                    |                     d{V rt          j        dd|          t          |                    ||                     d{V }t          |           | 
                    |           dS )z?PATCH renames a file or directory without re-uploading content.Nr_   zJSON body missingr&   z Cannot rename file or directory )rc   get_json_bodyr   r!   ri   rf   r   rg   r0   r7   rQ   )rF   r&   rl   r   old_paths        r   patchzContentsHandler.patch   s5      """$$=-%899999V$$	RO	R #2<<#5#566666666		R AMR\\ZbMcMc@d@d:d:d:d:d:d:d		R -%P%P%PQQQ"299UD#9#9::::::::u5!!!!!r   Nc                   K   | j                             d||pd           t          | j                            ||                     d{V }|                     d           t          |           |                     |           dS )z6Copy a file, optionally specifying a target directory.zCopying %r to %rrX   N   )loginfor   rc   copyrS   r7   rQ   )rF   	copy_fromcopy_tor   s       r   _copyzContentsHandler._copy   s      Mr	
 	
 	

 #4#8#=#=i#Q#QRRRRRRRRu5!!!!!r   c                   K   | j                             d|           t          | j                            ||                     d{V }|                     d           t          |           |                     |           dS )z#Handle upload of a new file to pathzUploading file to %sNru   )rv   rw   r   rc   newrS   r7   rQ   )rF   r   r&   s      r   _uploadzContentsHandler._upload   s      ,d333"4#8#<#<UD#I#IJJJJJJJJu5!!!!!r   c                   K   | j                             d|pd|           t          | j                            |||                     d{V }|                     d           t          |           |                     |           dS )z#Create a new, empty untitled entityzCreating new %s in %srZ   )r&   r'   extNru   )rv   rw   r   rc   new_untitledrS   r7   rQ   )rF   r&   r'   r   r   s        r   _new_untitledzContentsHandler._new_untitled   s      -t~vtDDD"!..Dt.MM
 
 
 
 
 
 
 
 	u5!!!!!r   c                    K   |                     dd          }|r|dk    r| j                            d|           t          | j                            ||                     d{V }t          |           |                     |           dS )zSave an existing file.chunkNzSaving file at %s)ri   rv   rw   r   rc   saver7   rQ   )rF   r   r&   r   s       r   _savezContentsHandler._save   s      		'4(( 	5HMM-t444"4#8#=#=eT#J#JKKKKKKKKu5!!!!!r   c                   K   | j         }t          |                    |                     d{V }|rt          j        dd          |                                 }|r|                    d          }|r|j        sht          |                    |                     d{V s(t          |                    |                     d{V rt          j        dd|          | 	                    ||           d{V  dS |                    dd          }|                    dd          }|d	vrd
}| 
                    |||           d{V  dS | 
                    |           d{V  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
        Nr_   z&Cannot POST to files, use PUT instead.ry   zCannot copy file or directory r   rX   r'   >   NrX   rZ   r[   r\   rZ   )r'   r   )rc   r   file_existsr   r!   rq   ri   rf   rg   r{   r   )rF   r&   rl   r   r   ry   r   r'   s           r   postzContentsHandler.post   s      "()=)=>>>>>>>> 	O-%MNNN""$$ 	+		+..I C 6&r||D'9'9::::::::6)",,y*A*ABBBBBBBB6 --Vd-V-VWWW**Y55555555555iir**yy,,JJJ!D((Dc(BBBBBBBBBBB$$T***********r   c                   K   |                                  }| j        }|rI|                    d          rt          j        dd          |j        s|                    d          r;t          |                    |                    d                               d{V s(t          |                    |                     d{V rt          j        dd|          t          | j                            |                     d{V }|                    dd          d	vrd
|d<   |r| 	                    ||           d{V  dS | 
                    ||           d{V  dS |                     |           d{V  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.
        ry   r_   zCannot copy with PUT, only POSTr&   Nz Cannot create file or directory r'   rX   >   NrX   rZ   r[   r\   rZ   )rq   rc   ri   r   r!   rf   r   rg   r   r   r~   r   )rF   r&   r   rl   existss        r   putzContentsHandler.put"  s      ""$$" 	+yy%% LmC)JKKK? V6""V-9",,uyyQWGXGX:Y:Y-Z-Z'Z'Z'Z'Z'Z'ZV%bll4&8&899999999V mC)TD)T)TUUU'(=(I(I$(O(OPPPPPPPPFyy$$,WWW &f 0jj-----------ll5$///////////$$T***********r   c                 ~  K   | j         }|j        s@t          |                    |                     d{V rt	          j        dd|          | j                            d|           t          |                    |                     d{V  | 	                    d           | 
                                 dS )zdelete a file in the given pathNr_   z Cannot delete file or directory z	delete %s   )rc   rf   r   rg   r   r!   rv   warningdeleterS   rM   rF   r&   rl   s      r   r   zContentsHandler.deleteF  s       " 	Rbll46H6H)I)I#I#I#I#I#I#I 	R-%P%P%PQQQd+++299T??+++++++++r   )TrX   r   )rX   rX   )r:   r;   r<   r=   rG   rQ   rW   r   authenticatedr
   ri   rs   r{   r~   r   r   r   r   r   r   r   r   rA   rA   Y   s       Q Q Q= = = =   	B B B Z BH 	" " " Z "*
" 
" 
" 
"" " "" " " "" " " 	%+ %+ %+ Z %+N 	 +  +  + Z  +D 	
 
 
 Z 
 
 
r   rA   c                   v    e Zd ZdZej        edd                        Zej        edd                        ZdS )CheckpointsHandlerzA checkpoints API handler.rX   c                    K   | j         }t          |                    |                     d{V }t          j        |t
                    }|                     |           dS )z get lists checkpoints for a fileNrJ   )rc   r   list_checkpointsrN   rO   r   rM   )rF   r&   rl   checkpointsdatas        r   ri   zCheckpointsHandler.getX  si       "()<)<T)B)BCCCCCCCCz+|<<<Dr   c           
        K   | j         }t          |                    |                     d{V }t          j        |t
                    }t          | j        dt          |          dt          |d                             }| 	                    d|           | 
                    d           |                     |           dS )zpost creates a new checkpointNrJ   api/contentsr   idrI   ru   )rc   r   create_checkpointrN   rO   r   r   rD   r   rL   rS   rM   )rF   r&   rl   
checkpointr   rP   s         r   r   zCheckpointsHandler.posta  s       "'(<(<T(B(BCCCCCCCC
z*l;;; Mtz$'((
 
 	
H---Dr   Nr   )	r:   r;   r<   r=   r   r   r
   ri   r   r   r   r   r   r   U  st        $$   Z  	   Z   r   r   c                   r    e Zd ZdZej        ed                         Zej        ed                         ZdS )ModifyCheckpointsHandlerz#A checkpoints modification handler.c                    K   | j         }t          |                    ||                     d{V  |                     d           |                                  dS )z&post restores a file from a checkpointNr   )rc   r   restore_checkpointrS   rM   rF   r&   checkpoint_idrl   s       r   r   zModifyCheckpointsHandler.postw  sc       "200EEFFFFFFFFFr   c                    K   | j         }t          |                    ||                     d{V  |                     d           |                                  dS )z+delete clears a checkpoint for a given fileNr   )rc   r   delete_checkpointrS   rM   r   s       r   r   zModifyCheckpointsHandler.delete  sc       "2//tDDEEEEEEEEEr   N)	r:   r;   r<   r=   r   r   r
   r   r   r   r   r   r   r   t  sj        --  Z  	  Z   r   r   c                   <    e Zd ZdZdZed             ZexZxZxZ	Z
dS )NotebooksRedirectHandlerz(Redirect /api/notebooks to /api/contents)GETPUTPATCHPOSTDELETEc           	          | j                             d           |                     t          | j        dt          |                               dS )zHandle a notebooks redirect.z//api/notebooks is deprecated, use /api/contentsr   N)rv   r   redirectr   rD   r   rE   s     r   ri   zNotebooksRedirectHandler.get  sI     	JKKKmDM>:dCSCSTTUUUUUr   N)r:   r;   r<   r=   SUPPORTED_METHODSr	   ri   r   rs   r   r   r   r   r   r   r     sQ        22 V V V
 #&%C%%%$r   r   c                   X    e Zd ZdZej         ee          dd                        ZdS )TrustNotebooksHandlerz"Handles trust/signing of notebooks)resourcerX   c                    K   | j         }t          |                    |                     d{V  |                     d           |                                  dS )zTrust a notebook by path.Nru   )rc   r   trust_notebookrS   rM   r   s      r   r   zTrustNotebooksHandler.post  sa       "2,,T22333333333r   Nr   )	r:   r;   r<   r=   r   r   r
   r>   r   r   r   r   r   r     sT        ,,Z'''   ('   r   r   z(?P<checkpoint_id>[\w-]+)z/api/contents%s/checkpointsz/api/contentsz/checkpoints/z/api/contents%s/trustz/api/contents%sz/api/notebooks/?(.*))FF)'r=   rN   httpr   typingr   jupyter_client.jsonutilr   ImportErrorr   jupyter_core.utilsr   tornador   jupyter_server.auth.decoratorr	   r
   jupyter_server.base.handlersr   r   r   jupyter_server.utilsr   r   r>   booldictstrlistr#   r7   r9   rA   r   r   r   r   _checkpoint_id_regexdefault_handlersr   r   r   <module>r      s                E4444444 E E EDDDDDDDDE , + + + + +       K K K K K K K K O O O O O O O O O O : : : : : : : :4 S#X d3i    * G  G  G  GF" " " " " " " "y y y y y( y y yx    +   >    1   ,& & & & &~ & & &(
 
 
 
 
N 
 
 
$ 4  $j02DEHHH2FHH  
*,AB*$o667	   s    ))