o
    iA                     @   s  d Z ddlZddlZddlm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mZ dd	lmZ d
dlmZmZmZmZ dZdd Zdd Zdd Z				d$ddZdd Zd%ddZdd Z					d&ddZ 	d'd d!Z!G d"d# d#eZ"dS )(z Frontend config storage helpers.    N)glob)Draft4Validator)ValidationError)_tz)
APIHandler)ConfigManagerrecursive_update)web   )DEFAULT_LOCALEL10N_SCHEMA_NAME
SYS_LOCALEis_valid_localez.jupyterlab-settingsc                 C   sr  d}d}d}d}|dur7| d\}}	}
|D ] }tj||d||
d }tj|r6tj||d} |} nq|du r@t| |}tj|sNtd|| t|d	d
+}zt	
|}W n tyw } z|}td||t|f dd}~ww W d   n1 sw   Y  t|||}zt| W n ty } z|}td||t|f dd}~ww t| |}||fS )z=Returns a dict containing a parsed and validated JSON schema.zSchema not found: %szFailed parsing schema (%s): %sz!Failed validating schema (%s): %sN:schemas.json  utf-8encoding  )	partitionospathjoinexists_pathr	   	HTTPErroropenjsonload	Exceptionstr	_override	Validatorcheck_schema_get_version)schemas_dirschema_name	overrideslabextensions_pathnotfound_errorparse_errorvalidation_errorr   ext_name_plugin_nameext_pathtargetfidschemaenameversion r8   [/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/jupyterlab_server/settings_utils.py_get_schema   sJ   

r:   c                 C   sH  t | |dt}d}i }d}d}d}d}	d}
tj|rmt|}t|j	 }	t|j
	 }
t|dd/}z| p=|}t|}W n ty] } ztd||t|f dd}~ww W d   n1 shw   Y  t|rt|}z|| W n ty } z||t|f }d}i }W Y d}~nd}~ww t||||	|
d	S )
z
    Returns a dictionary containing the raw user settings, the parsed user
    settings, a validation warning for a schema, and file times.
    Fz{}Nz#Failed validating settings (%s): %sz Failed loading settings (%s): %sr   r   r   )rawsettingswarninglast_modifiedcreated)r   SETTINGS_EXTENSIONr   r   r   stattzutcfromtimestampst_mtime	isoformatst_ctimer   readjson5loadsr!   r	   r   r"   lenr$   validater   dict)settings_dirr(   r4   r   r;   r<   r=   validation_warningr,   r>   r?   rA   r3   r5   	validatorr8   r8   r9   _get_user_settingsG   sF   

rP   c                 C   s   t | |}tjtj|d d}z#t|dd}t|}|d W  d   W S 1 s.w   Y  W dS  ty?   Y dS w )zEReturns the package version for a given schema or 'N/A' if not found.r   zpackage.json.origr   r   r7   NzN/A)	r   r   r   r   splitr   r   r    r!   )r'   r(   r   package_pathr3   packager8   r8   r9   r&   o   s   

(r&   r   Fc                    s`  i  i }g }t j| sd|  g}g |fS | d | }	dd t|	ddD }
|
  |
D ]_}t j|| }t j|\}}d||dt|  g	d	d
 }}|r[t
|d |< q,t| ||d\}}|durl||}t|||}|d r~||d t
d|||d| |< q,|durg }
|D ]}|d | }	|
dd t|	ddD  q|
  |
D ]e}|	t jd
}|d\}}t j|\}}d||dt|  g	d	d
 }}||v rq|rt
|d||< qt| |||d\}}t|||}|d r
||d t
d|||d|||< q |  fddt  ddD }||fS )ac  
    Returns a tuple containing:
     - the list of plugins, schemas, and their settings,
       respecting any defaults that may have been overridden if `ids_only=False`,
       otherwise a list of dict containing only the ids of plugins.
     - the list of warnings that were generated when
       validating the user overrides against the schemas.
    z'Settings directory does not exist at %sz/**/*c                 S      g | ]}|qS r8   r8   .0r   r8   r8   r9   
<listcomp>       z"_list_settings.<locals>.<listcomp>T)	recursiver   N\/)idr=   r\   r4   r7   z/**/schemas/**/*c                 S   rT   r8   r8   rU   r8   r8   r9   rW      rX   zschemas/r*   c                    s   g | ]} | qS r8   r8   )rV   keyr<   r8   r9   rW      s    )reverser8   )r   r   r   r   sortrelpathrQ   r   rJ   replacerL   r:   rP   appendpopextendsepupdatesortedkeys)r'   rM   r)   	extensionr*   
translatorids_onlyfederated_settingswarningsschema_patternschema_pathsschema_pathrel_pathrel_schema_dirschema_base_idr(   r4   r7   user_settingsext_dirschema_path_base_dirsettings_listr8   r`   r9   _list_settings}   s~   




r}   c                 C   s   | |v r@||  }|D ]5}||d v r4|d | d }t |tr't|||  n|| }||d | d< q
t|| d|d |< q
|S )z3Override default values in the schema if necessary.
propertiesdefault)r   )
isinstancerL   r   )r(   r4   r)   defaultsr_   new_defaultsr8   r8   r9   r#      s   
r#   c              
   C   s   d}d}z| d\}}tj| |}tj||| }	W n ty-   td|| dw |rXtj|sXzt| W |	S  tyW }
 ztd||t	|
f dd}
~
ww |	S )a1  
    Returns the local file system path for a schema name in the given root
    directory. This function can be used to filed user overrides in addition to
    schema files. If the `make_dirs` flag is set to `True` it will create the
    parent directory for the calculated path if it does not exist.
    zSettings not found (%s)z Failed writing settings (%s): %sr   r   Nr   )
rQ   r   r   r   r!   r	   r   r   makedirsr"   )root_dirr(   	make_dirsrl   r+   write_errorpackage_dirplugin
parent_dirr   r5   r8   r8   r9   r      s$   r   c                 C   sV  i d}}t j| d}tg tt j|dtt j|d}|t j| dt j| dg7 }|D ]X}t j|s=q4t|ddA}z$|d	rPt	|}nt
	|}| D ]\}}	t||i |	 qYW n ty| }
 z|
}W Y d
}
~
nd
}
~
ww W d
   n1 sw   Y  q4tdd}|d D ]\}}	t||i |	 q||fS )zGet overrides settings from `app_settings_dir`.

    The ordering of paths is:
    - {app_settings_dir}/overrides.d/*.{json,json5} (many, namespaced by package)
    - {app_settings_dir}/overrides.{json,json5} (singleton, owned by the user)
     zoverrides.dz*.jsonz*.json5zoverrides.jsonzoverrides.json5r   r   z.json5N	labconfig)config_dir_namedefault_setting_overrides)r   r   r   rj   r   r   r   endswithrH   r    r   itemsr   
setdefaultr!   r   get)app_settings_dirr)   erroroverrides_dall_override_pathsoverrides_pathr3   path_overrides	plugin_idconfigr5   cmr8   r8   r9   _get_overrides  sF   



r   r   c                 C   s   i }g }	|du rt | \}}
|r9t||||\}}|dur!||}t|||}|dg}	|||d|}||	fS t||||||d\}}	d|i}||	fS )aK  
    Get settings.

    Parameters
    ----------
    app_settings_dir:
        Path to applications settings.
    schemas_dir: str
        Path to schemas.
    settings_dir:
        Path to settings.
    schema_name str, optional
        Schema name. Default is "".
    overrides: dict, optional
        Settings overrides. If not provided, the overrides will be loaded
        from the `app_settings_dir`. Default is None.
    labextensions_path: list, optional
        List of paths to federated labextensions containing their own schema files.
    translator: Callable[[Dict], Dict] or None, optional
        Translate a schema. It requires the schema dictionary and returns its translation

    Returns
    -------
    tuple
        The first item is a dictionary with a list of setting if no `schema_name`
        was provided (only the ids if `ids_only=True`), otherwise it is a dictionary
        with id, raw, scheme, settings and version keys.
        The second item is a list of warnings. Warnings will either be a list of
        i) strings with the warning messages or ii) `None`.
    Nr=   r]   )r*   rm   rn   r<   )r   r:   rP   rf   r}   )r   r'   rM   r(   r)   r*   rm   rn   resultrp   _errorr4   r7   rx   r|   r8   r8   r9   get_settingsC  s.   (
	r   c                 C   s|   t |}t| |||d\}}t|}	|	| t||dt}
t|
ddd}|| W d   dS 1 s7w   Y  dS )a  
    Save ``raw_settings`` settings for ``schema_name``.

    Parameters
    ----------
    schemas_dir: str
        Path to schemas.
    settings_dir: str
        Path to settings.
    schema_name str
        Schema name.
    raw_settings: str
        Raw serialized settings dictionary
    overrides: dict
        Settings overrides.
    labextensions_path: list, optional
        List of paths to federated labextensions containing their own schema files.
    r^   Twr   r   N)	rH   rI   r:   r$   rK   r   r@   r   write)r'   rM   r(   raw_settingsr)   r*   payloadr4   r/   rO   r   r3   r8   r8   r9   save_settings  s   


"r   c                       s(   e Zd ZdZ fddZdd Z  ZS )SchemaHandlerz6Base handler for handler requiring access to settings.c                    s\   t  jdi | t|\| _}|| _|| _|| _|| _|r,d}| j	|t
|  dS dS )zInitialize the handler.zFailed loading overrides: %sNr8   )super
initializer   r)   r   r'   rM   r*   logr=   r"   )selfr   r'   rM   r*   kwargsr   overrides_warning	__class__r8   r9   r     s   zSchemaHandler.initializec              
   C   s   zt | j| j| jt| j| jd\}}W n! tjy4 } zd}| j	
|t|  i }W Y d}~nd}~ww |di dp?t}|dkrFt}t|sLt}|S )aQ  
        Get the current locale as specified in the translation-extension settings.

        Returns
        -------
        str
            The current locale string.

        Notes
        -----
        If the locale setting is not available or not valid, it will default to jupyterlab_server.translation_utils.DEFAULT_LOCALE.
        )r(   r)   r*   z4Missing or misshapen translation settings schema:
%sNr<   localer   )r   r   r'   rM   r   r)   r*   r	   r   r   r=   r"   r   r   r   r   )r   r<   r/   r5   schema_warningcurrent_localer8   r8   r9   get_current_locale  s*   z SchemaHandler.get_current_locale)__name__
__module____qualname____doc__r   r   __classcell__r8   r8   r   r9   r     s    r   )r   NNF)Fr   )r   NNNF)N)#r   r   r   r   rH   
jsonschemar   r$   r   jupyter_serverr   rB   jupyter_server.base.handlersr   &jupyter_server.services.config.managerr   r   tornador	   translation_utilsr   r   r   r   r@   r:   rP   r&   r}   r#   r   r   r   r   r   r8   r8   r8   r9   <module>   sB    0(
e
6
K
)