a
    ø£BeH'  ã                   @   s:  d Z ddlZddlZddlZddlm  mZ ddlm	Z	m
Z
mZ ddlmZmZ ddlmZmZmZ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ZdZdZ e!dœdd„Z"e
dd�G dd„ dƒƒZ#G dd„ dej$ƒ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 Z+dS )!z%Announcements handler for JupyterLab.é    N)ÚasdictÚ	dataclassÚfield)ÚdatetimeÚtimezone)Ú	AwaitableÚOptionalÚTupleÚUnion)Ú
APIHandler)Ú
translator)Úparse)Ú
httpclientÚweb)Ú__version__z%Y-%m-%dT%H:%M:%S%zz%https://pypi.org/pypi/jupyterlab/jsonz7https://github.com/jupyterlab/jupyterlab/releases/tag/v©Zdt_strc                 C   s   t  | ¡ ¡ d S )Niè  )r   ÚfromisoformatÚ	timestampr   © r   úd/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyterlab/handlers/announcements.pyÚformat_datetime   s    r   T)Úfrozenc                   @   sb   e Zd ZU dZeed< eed< eed< dZeed< ee	d�Z
eeef ed< eed�Zeed	< d
S )ÚNotificationuK  Notification

    Attributes:
        createdAt: Creation date
        message: Notification message
        modifiedAt: Modification date
        type: Notification type â€” ["default", "error", "info", "success", "warning"]
        link: Notification link button as a tuple (label, URL)
        options: Notification options
    Ú	createdAtÚmessageÚ
modifiedAtÚdefaultÚtype)Údefault_factoryÚlinkÚoptionsN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚfloatÚ__annotations__Ústrr   r   Útupler   r	   Údictr    r   r   r   r   r      s   
r   c                
   @   sR   e Zd ZdZeddœdd„Zejee	dee
ee
eef f f  dœdd„ƒZdS )	ÚCheckForUpdateABCzÑAbstract class to check for update.

    Args:
        version: Current JupyterLab version

    Attributes:
        version - str: Current JupyterLab version
        logger - logging.Logger: Server logger
    N)ÚversionÚreturnc                 C   s
   || _ d S ©N)r+   )Úselfr+   r   r   r   Ú__init__>   s    zCheckForUpdateABC.__init__©r,   c                 Ã   s   d}t |ƒ‚dS )a  Get the notification message if a new version is available.

        Returns:
            None if there is not update.
            or the notification message
            or the notification message and a tuple(label, URL link) for the user to get more information
        z-CheckForUpdateABC.__call__ is not implementedN)ÚNotImplementedError)r.   Úmsgr   r   r   Ú__call__A   s    	zCheckForUpdateABC.__call__)r!   r"   r#   r$   r'   r/   ÚabcÚabstractmethodr   r
   r	   r3   r   r   r   r   r*   3   s   
r*   c                   @   s2   e Zd ZdZeeeeeef f  dœdd„ZdS )ÚCheckForUpdatezÐDefault class to check for update.

    Args:
        version: Current JupyterLab version

    Attributes:
        version - str: Current JupyterLab version
        logger - logging.Logger: Server logger
    r0   c              
   Ã   sÂ   t  ¡ }z6|jtddid�I dH }t |j¡ d¡}|d }W n6 tyt } z| j	j
d|d� W Y d}~dS d}~0 0 t| jƒt|ƒk rºt d	¡}| d
|› d�¡| d¡t› |› �ffS dS dS )á  Get the notification message if a new version is available.

        Returns:
            None if there is no update.
            or the notification message
            or the notification message and a tuple(label, URL link) for the user to get more information
        úContent-Typezapplication/json©ÚheadersNÚinfor+   zFailed to get latest version©Úexc_infoÚ
jupyterlabzA newer version (z) of JupyterLab is available.zOpen changelog)r   ÚAsyncHTTPClientÚfetchÚJUPYTERLAB_LAST_RELEASE_URLÚjsonÚloadsÚbodyÚgetÚ	ExceptionÚloggerÚdebugr   r+   r   ÚloadÚ__ÚJUPYTERLAB_RELEASE_URL)r.   Úhttp_clientÚresponseÚdataZlast_versionÚeÚtransr   r   r   r3   Y   s"    þ
þzCheckForUpdate.__call__N)r!   r"   r#   r$   r   r	   r'   r3   r   r   r   r   r6   N   s   
r6   c                   @   s"   e Zd ZdZed dœdd„ZdS )ÚNeverCheckForUpdatea7  Check update version that does nothing.

    This is provided for administrators that want to
    turn off requesting external resources.

    Args:
        version: Current JupyterLab version

    Attributes:
        version - str: Current JupyterLab version
        logger - logging.Logger: Server logger
    Nr0   c                 Ã   s   dS )r7   Nr   )r.   r   r   r   r3   …   s    zNeverCheckForUpdate.__call__)r!   r"   r#   r$   r   r3   r   r   r   r   rQ   w   s   rQ   c                       s<   e Zd ZdZdee ddœ‡ fdd„Zejdd„ ƒZ	‡  Z
S )	ÚCheckForUpdateHandlerziCheck for Updates API handler.

    Args:
        update_check: The class checking for a new version
    N)Úupdate_checkerr,   c                    s.   t ƒ  ¡  |d u rttƒn|| _| j| j_d S r-   )ÚsuperÚ
initializerQ   r   rS   ÚlogrG   )r.   rS   ©Ú	__class__r   r   rU   —   s    
ÿz CheckForUpdateHandler.initializec              
   Ã   sª   d}|   ¡ I dH }|rxt|tƒr(|dfn|\}}tjtjd� ¡ d }t 	| 
¡ ¡ ¡ }t|||d|d|dgdœid	�}|  d
¡ |  t d|du r˜dnt|ƒi¡¡ dS )z€Check for updates.
        Response:
            {
                "notification": Optional[Notification]
            }
        Nr   )Útzg     @�@r;   rN   Úupdate©ÚidÚtags©r   r   r   r   r   r    éÈ   Únotification)rS   Ú
isinstancer'   r   Únowr   Úutcr   ÚhashlibÚsha1ÚencodeÚ	hexdigestr   Ú
set_statusÚfinishrB   Údumpsr   )r.   r`   Úoutr   r   rb   Úhash_r   r   r   rE   ¡   s$    ú	
ÿzCheckForUpdateHandler.get)N)r!   r"   r#   r$   r   r6   rU   r   ÚauthenticatedrE   Ú__classcell__r   r   rW   r   rR   �   s    þý
rR   c                       s<   e Zd ZdZdee ddœ‡ fdd„Zejdd„ ƒZ	‡  Z
S )	ÚNewsHandlerzSNews API handler.

    Args:
        news_url: The Atom feed to fetch for news
    N)Únews_urlr,   c                    s   t ƒ  ¡  || _d S r-   )rT   rU   rp   )r.   rp   rW   r   r   rU   Å   s    
zNewsHandler.initializec           
   
   ƒ   s  g }t  ¡ }| jdurØt d¡‰ ddi‰ˆ ¡ D ]\}}t ||¡ q0zT|j| jddid�I dH }t 	|j
¡}‡ ‡fdd	„}t|| d
ˆ¡ƒ}| |¡ W n< tyÖ }	 z$| jjd| j› �|	d� W Y d}	~	n
d}	~	0 0 |  d¡ |  t dttt|ƒƒi¡¡ dS )zpGet the news.

        Response:
            {
                "news": List[Notification]
            }
        Nr>   Zatomzhttp://www.w3.org/2005/Atomr8   zapplication/atom+xmlr9   c              
      s  dt tt  t dœ‡ ‡fdd„}|dƒ}|dƒ}|dƒ}|d|ƒ}|dd	d
�}ˆ  dˆ¡}t|ƒdkrŒttdd„ |ƒƒ}|r‚|d n|d }	nt|ƒdkr |d nd }	|	d ur¶|	 d¡nd }
|rÌd ||g¡n|}t|ƒ}t|ƒ}t	|||d|
d u röd nˆ 
d¡|
fd|dgdœid�}|S )N)Úattrr   r,   c                    sB   ˆ   d| › �ˆ¡}|d ur |jS |d ur,|S d| › �}t|ƒ‚d S )Nzatom:z7atom feed entry does not contain a required attribute: )ÚfindÚtextÚKeyError)rq   r   Z	node_itemZerror_m)ÚnodeÚxml_namespacesr   r   Úget_xml_texté   s    ÿz:NewsHandler.get.<locals>.build_entry.<locals>.get_xml_textÚtitler\   ÚupdatedZ	publishedÚsummaryÚ )r   z	atom:linké   c                 S   s   |   d¡dkS )NÚrelÚ	alternate)rE   )Úelemr   r   r   Ú<lambda>ü   ó    z6NewsHandler.get.<locals>.build_entry.<locals>.<lambda>r   ÚhrefÚ
r;   zOpen full postrN   Únewsr[   r^   )N)r'   r   ÚfindallÚlenÚlistÚfilterrE   Újoinr   r   rJ   )ru   rw   Zentry_titleZentry_idZentry_updatedZentry_publishedZentry_summaryÚlinksr~   Z	link_nodeZ
entry_linkr   Zmodified_atZ
created_atr`   ©rP   rv   )ru   r   Úbuild_entryè   sB    
ÿÿþþÿõz$NewsHandler.get.<locals>.build_entryz
atom:entryz,Failed to get announcements from Atom feed: r<   r_   r„   )r   r?   rp   r   rI   ÚitemsÚETZregister_namespacer@   Z
fromstringrD   Úmapr…   ÚextendrF   rV   rH   rh   ri   rB   rj   r‡   r   )
r.   r„   rL   ÚkeyÚspecrM   ÚtreerŒ   ÚentriesrO   r   r‹   r   rE   Ì   s.    	

þ3
þ
zNewsHandler.get)N)r!   r"   r#   r$   r   r'   rU   r   rm   rE   rn   r   r   rW   r   ro   ¾   s    þýro   z/lab/api/newsz/lab/api/update),r$   r4   rd   rB   Zxml.etree.ElementTreeÚetreeZElementTreerŽ   Údataclassesr   r   r   r   r   Útypingr   r   r	   r
   Zjupyter_server.base.handlersr   Z#jupyterlab_server.translation_utilsr   Zpackaging.versionr   Útornador   r   Zjupyterlab._versionr   ZISO8601_FORMATrA   rK   r'   r   r   ÚABCr*   r6   rQ   rR   ro   Znews_handler_pathZcheck_update_handler_pathr   r   r   r   Ú<module>   s2   ).i