o
    iY                     @   sJ  d Z ddlm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 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mZmZ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(m)Z)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 da1dd Z2G dd deeZ3dS )z?A contents manager that uses the local file system for storage.    )datetimeN)
send2trash)TrashPermissionError)web   FileCheckpoints)FileManagerMixin)ContentsManager   )exists)import_item)AnyUnicodeBool
TraitErrorobservedefaultvalidate)getcwdstring_types)_tz)	is_hiddenis_file_hiddento_api_pathAuthenticatedFileHandler)_)samefilec                 K   s   ddl m} tdt | d dkrdS tdu r||da|j}tj	|\}}t
|\}}	||	dd	 }
|d
t|
|j t|
ddd}|| W d   dS 1 sYw   Y  dS )zkconvert notebooks to Python script after save with nbconvert

    replaces `jupyter notebook --script`
    r   )ScriptExporterzE`_post_save_script` is deprecated and will be removed in Notebook 5.0typenotebookN)parentoutput_extensionz.txtzSaving script /%swzutf-8)encoding)nbconvert.exporters.scriptr   warningswarnDeprecationWarning_script_exporterlogospathsplitextfrom_filenamegetinfor   root_diropenwrite)modelos_pathcontents_managerkwargsr   r+   baseextscript	resourcesscript_fnamef r?   a/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/notebook/services/contents/filemanager.py_post_save_script*   s   
"rA   c                   @   sL  e Zd ZeddZeddd ZeddddZe	d	d
d Z
edddddZeddd Zdd Zeddd Zeddd ZeddddZeddd Zeddd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) ZdAd*d+ZdBd,d-ZdAd.d/ZdCd0d1ZdDd3d4ZdDd5d6Zd7d8 Z d9d: Z!d;d< Z"dEd=d>Z#e$d?d@ Z%dS )FFileContentsManagerT)configr2   c                 C   s$   z| j jW S  ty   t  Y S w N)r"   notebook_dirAttributeErrorr   selfr?   r?   r@   _default_root_dirF   s
   

z%FileContentsManager._default_root_dirFz?DEPRECATED, use post_save_hook. Will be removed in Notebook 5.0)rC   helpsave_scriptc                 C   s"   |d sd S | j d t| _d S )Nnewa  
        `--script` is deprecated and will be removed in notebook 5.0.

        You can trigger nbconvert via pre- or post-save hooks:

            ContentsManager.pre_save_hook
            FileContentsManager.post_save_hook

        A post-save hook has been registered that calls:

            jupyter nbconvert --to script [notebook]

        which behaves similarly to `--script`.
        )r+   warningrA   post_save_hook)rH   changer?   r?   r@   _update_save_scriptN   s   
z'FileContentsManager._update_save_scriptNa   Python callable or importstring thereof

        to be called on the path of a file just saved.

        This can be used to process the file on disk,
        such as converting the notebook to a script or HTML via nbconvert.

        It will be called as (all arguments passed by keyword)::

            hook(os_path=os_path, model=model, contents_manager=instance)

        - path: the filesystem path to the file just written
        - model: the model representing the file
        - contents_manager: this ContentsManager instance
        )rC   
allow_nonerJ   rN   c                 C   s.   |d }t |trt|}t|std|S )Nvaluezpost_save_hook must be callable)
isinstancer   r   callabler   rH   proposalrR   r?   r?   r@   _validate_post_save_hooku   s   
z,FileContentsManager._validate_post_save_hookc              
   C   sn   | j r5z| jd| | j ||| d W dS  ty4 } z| jjd|dd tdd| |d}~ww dS )	z1Run the post-save hook if defined, and log errorszRunning post-save hook on %s)r6   r5   r7   zPost-save hook failed o-n %sTexc_info  z/Unexpected error while running post hook save: N)rN   r+   debug	Exceptionerrorr   	HTTPError)rH   r5   r6   er?   r?   r@   run_post_save_hook~   s   z&FileContentsManager.run_post_save_hookc                 C   s>   |d }t j|st j|}t j|st|d|S )z'Do a bit of validation of the root_dir.rR    is not a directory)r,   r-   isabsabspathisdirr   rU   r?   r?   r@   _validate_root_dir   s   z&FileContentsManager._validate_root_dircheckpoints_classc                 C      t S rD   r   rG   r?   r?   r@   _checkpoints_class_default      z.FileContentsManager._checkpoints_class_defaultzIf True (default), deleting files will send them to the
        platform's trash/recycle bin, where they can be recovered. If False,
        deleting files really deletes them.files_handler_classc                 C   rg   rD   r   rG   r?   r?   r@   _files_handler_class_default   ri   z0FileContentsManager._files_handler_class_defaultfiles_handler_paramsc                 C   s
   d| j iS )Nr-   )r2   rG   r?   r?   r@   _files_handler_params_default   s   
z1FileContentsManager._files_handler_params_defaultc                 C   s"   | d}| j|d}t|| jS )aW  Does the API style path correspond to a hidden directory or file?

        Parameters
        ----------
        path : string
            The path to check. This is an API path (`/` separated,
            relative to root_dir).

        Returns
        -------
        hidden : bool
            Whether the path exists and is hidden.
        /r-   )strip_get_os_pathr   r2   rH   r-   r6   r?   r?   r@   r      s   
zFileContentsManager.is_hiddenc                 C   s    | d}| |}tj|S )aF  Returns True if the file exists, else returns False.

        API-style wrapper for os.path.isfile

        Parameters
        ----------
        path : string
            The relative path to the file (with '/' as separator)

        Returns
        -------
        exists : bool
            Whether the file exists.
        rn   )rp   rq   r,   r-   isfilerr   r?   r?   r@   file_exists   s   

zFileContentsManager.file_existsc                 C   s"   | d}| j|d}tj|S )ay  Does the API-style path refer to an extant directory?

        API-style wrapper for os.path.isdir

        Parameters
        ----------
        path : string
            The path to check. This is an API path (`/` separated,
            relative to root_dir).

        Returns
        -------
        exists : bool
            Whether the path is indeed a directory.
        rn   ro   )rp   rq   r,   r-   rd   rr   r?   r?   r@   
dir_exists   s   
zFileContentsManager.dir_existsc                 C   s   | d}| j|d}t|S )aC  Returns True if the path exists, else returns False.

        API-style wrapper for os.path.exists

        Parameters
        ----------
        path : string
            The API path to the file (with '/' as separator)

        Returns
        -------
        exists : bool
            Whether the target exists.
        rn   ro   )rp   rq   r   rr   r?   r?   r@   r      s   
zFileContentsManager.existsc           	      C   s  |  |}t|}d| }t|| jr$| js$| jd| t	d|z|j
}W n ttfy<   | jd d}Y nw zt|j}W n ttfyd   | jd|j| tdddd	d	tjd
}Y nw zt|j}W n ttfy   | jd|j| tdddd	d	tjd
}Y nw i }|ddd |d< ||d< ||d< ||d< d|d< d|d< d|d< ||d< zt|tj|d< W |S  ty   | jd| d|d< Y |S w )z)Build the common base of a contents model$file or directory does not exist: %r<Refusing to serve hidden file or directory %r, via 404 Error  zUnable to get size.NzInvalid mtime %s for %si  r   r   )tzinfozInvalid ctime %s for %srn   namer-   last_modifiedcreatedcontentformatmimetypesizewritablez'Failed to check write permissions on %sF)rq   r,   lstatr   r2   allow_hiddenr+   r1   r   r^   st_size
ValueErrorOSErrorrM   tzutcfromtimestampst_mtimer   UTCst_ctimersplitaccessW_OKr]   )	rH   r-   r6   r1   four_o_fourr   r|   r}   r5   r?   r?   r@   _base_model   sR   



zFileContentsManager._base_modelc                 C   s  |  |}d|}tj|std|t|| jr,| js,| j	
d| td|| |}d|d< d|d< |rg  |d< }|  |}t|D ]}z	tj||}W n tyq }	 z| j	d	||	 W Y d}	~	qLd}	~	ww zt|}
W n( ty }	 z|	jtjkr| j	d
| n| j	d||	 W Y d}	~	qLd}	~	ww t|
jst|
jst|
js| j	d| qLz| |r| jst||
ds|| j| d| dd W qL ty }	 z|	jtjkr| j	jd|dd W Y d}	~	qLd}	~	ww d|d< |S )zpBuild a model for a directory

        if content is requested, will include a listing of the directory
        zdirectory does not exist: rx   z4Refusing to serve hidden directory %r, via 404 Error	directoryr    Nr   r~   z"failed to decode filename '%s': %sz%s doesn't existzError stat-ing %s: %sz%s not a regular file)stat_resrn   F)r-   r~   z+Unknown error checking if file %r is hiddenTrX   jsonr   )rq   r,   r-   rd   r   r^   r   r2   r   r+   r1   r   listdirjoinUnicodeDecodeErrorrM   r   r   errnoENOENTstatS_ISLNKst_modeS_ISREGS_ISDIRr[   should_listr   appendr0   ELOOP)rH   r-   r~   r6   r   r5   contentsos_dirr{   r_   str?   r?   r@   
_dir_model$  sv   






zFileContentsManager._dir_modelc                 C   sv   |  |}d|d< | |}t|d |d< |r9| ||\}}|d du r2ddd| }||d< |j||d	 |S )
a@  Build a model for a file

        if content is requested, include the file contents.

        format:
          If 'text', the contents will be decoded as UTF-8.
          If 'base64', the raw bytes contents will be encoded as base64.
          If not specified, try to decode as UTF-8, and fall back to base64
        filer    r   r   Nz
text/plainzapplication/octet-stream)textbase64r~   r   )r   rq   	mimetypes
guess_type
_read_fileupdate)rH   r-   r~   r   r5   r6   default_mimer?   r?   r@   _file_modelf  s$   


zFileContentsManager._file_modelc                 C   sX   |  |}d|d< | |}|r*| j|dd}| || ||d< d|d< | | |S )zBuild a notebook model

        if content is requested, the notebook content will be populated
        as a JSON structure (not double-serialized)
        r!   r       )
as_versionr~   r   r   )r   rq   _read_notebookmark_trusted_cellsvalidate_notebook_model)rH   r-   r~   r5   r6   nbr?   r?   r@   _notebook_model  s   


z#FileContentsManager._notebook_modelc                 C   s   | d}| |}d| }| |std|t|| jr/| js/| j	d| td|t
j|rO|dvrFtjd| d| dd	| j||d
}|S |dks\|du re|dre| j||d
}|S |dkrttjd| ddd	| j|||d}|S )a   Takes a path for an entity and returns its model

        Parameters
        ----------
        path : str
            the API path that describes the relative path for the target
        content : bool
            Whether to include the contents in the reply
        type : str, optional
            The requested type - 'file', 'notebook', or 'directory'.
            Will raise HTTPError 400 if the content doesn't match.
        format : str, optional
            The requested format for file contents. 'text' or 'base64'.
            Ignored if this returns a notebook or directory model.

        Returns
        -------
        model : dict
            the contents model. If content=True, returns the contents
            of the file or directory as well.
        rn   rv   rx   rw   )Nr     z is a directory, not a zbad type)reasonr~   r!   Nz.ipynbr   ra   r   )rp   rq   r   r   r^   r   r2   r   r+   r1   r,   r-   rd   r   endswithr   r   )rH   r-   r~   r    r   r6   r   r5   r?   r?   r@   r0     s2   


	
zFileContentsManager.get c                 C   s   t || jr| jstdd|tj|s4|   t	| W d   dS 1 s-w   Y  dS tj
|sCtdd| | jd| dS )zcreate a directoryr   zCannot create directory NzNot a directory: zDirectory %r already exists)r   r2   r   r   r^   r,   r-   r   perm_to_403mkdirrd   r+   r[   )rH   r6   r5   r-   r?   r?   r@   _save_directory  s   
"z#FileContentsManager._save_directoryc              
   C   s  | d}d|vrtddd|vr|d dkrtdd| |}t|| jr6| js6tdd|| jd	| | j	||d
 zS|d dkrjt
|d }| || | || | j|si| | n,|d dkr}| ||d |d n|d dkr| ||| ntdd|d  W n+ tjy     ty } z| jjd||dd tdd| d| |d}~ww d}|d dkr| | |dd}| j|dd}|r||d< | j||d |S )z9Save the file model and return the model with no content.rn   r    r   zNo file type providedr~   r   zNo file content providedz Cannot create file or directory z	Saving %s)r5   r-   r!   r   r   zUnhandled contents type: zError while saving file: %s %sTrX   rZ   z$Unexpected error while saving file:  NmessageFr   )r5   r6   )rp   r   r^   rq   r   r2   r   r+   r[   run_pre_save_hooknbformat	from_dictcheck_and_sign_save_notebookcheckpointslist_checkpointscreate_checkpoint
_save_filer0   r   r\   r]   r   r`   )rH   r5   r-   r6   r   r_   validation_messager?   r?   r@   save  sP   



zFileContentsManager.savec              
      s  | d} |}tj}t| jr jstdd|d| } 	|s.td| fdd} j
rstjdkrJ||rJtdd	| d
z jd| t| W dS  tyr } z jd|| W Y d}~nd}~ww tj|r||rtdd	| d
 jd|    t| W d   dS 1 sw   Y  dS  jd|    || W d   dS 1 sw   Y  dS )zDelete file at path.rn   r   z Cannot delete file or directory rv   rx   c                    s6   t j| rt jdd }tt | |h rdS dS )Ncheckpoint_dirTF)r,   r-   rd   getattrr   setr   )r6   cp_dirrG   r?   r@   is_non_empty_dir  s
   z9FileContentsManager.delete_file.<locals>.is_non_empty_dirwin32z
Directory z
 not emptyzSending %s to trashNzSkipping trash for %s, %szRemoving directory %szUnlinking file %s)rp   rq   r,   unlinkr   r2   r   r   r^   r   delete_to_trashsysplatformr+   r[   r   r   rM   r-   rd   r   shutilrmtree)rH   r-   r6   rmr   r   r_   r?   rG   r@   delete_file  s>   




"

"zFileContentsManager.delete_filec              
   C   s  | d}| d}||krdS | | | |}| |}t|| js+t|| jr7| js7tdd|tj	
|rKt||sKtdd| z|   t|| W d   W dS 1 scw   Y  W dS  tjys     ty } ztdd| d	| |d}~ww )
zRename a file.rn   Nr   z Cannot rename file or directory i  zFile already exists: rZ   zUnknown error renaming file: r   )rp   _validate_pathrq   r   r2   r   r   r^   r,   r-   r   r   r   r   mover\   )rH   old_pathnew_pathnew_os_pathold_os_pathr_   r?   r?   r@   rename_file;  s*   





&zFileContentsManager.rename_filec                 C   s   t d| j S )Nz*Serving notebooks from local directory: %s)r   r2   rG   r?   r?   r@   info_stringY  s   zFileContentsManager.info_stringc                 C   s2   |  |r|S d|v r|ddd }|S d}|S )zIReturn the initial API path of  a kernel associated with a given notebookrn   r   r   r   )ru   r   )rH   r-   r5   
parent_dirr?   r?   r@   get_kernel_path\  s   
z#FileContentsManager.get_kernel_pathc                 C   sB   t jdkrd}nd}|D ]}|| v rtdd|  d| qdS )zOChecks if the path contains invalid characters relative to the current platformr   z?:><*"|r   r   zPath 'z' contains characters that are invalid for the filesystem. Path names on this filesystem cannot contain any of the following characters: N)r   r   r   r^   )r-   invalid_charscharr?   r?   r@   r   f  s   
z"FileContentsManager._validate_path)T)TN)TNN)r   rD   )&__name__
__module____qualname__r   r2   r   rI   r   rK   r   rP   r   rN   r   rW   r`   re   rh   r   rk   rm   r   rt   ru   r   r   r   r   r   r0   r   r   r   r   r   r   staticmethodr   r?   r?   r?   r@   rB   B   sR    










4
B
!

1
40

rB   )4__doc__r   r   r,   r   r   r   r'   r   r   r   send2trash.exceptionsr   tornador   filecheckpointsr   fileior	   managerr
   utilsr   ipython_genutils.importstringr   	traitletsr   r   r   r   r   r   r   ipython_genutils.py3compatr   r   r!   r   r   notebook.utilsr   r   r   notebook.base.handlersr   notebook.transutilsr   os.pathr   r*   rA   rB   r?   r?   r?   r@   <module>   s8    $