o
    iH'                     @   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 de!f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dt_strc                 C   s   t |  d S )Ni  )r   fromisoformat	timestamp)r    r   \/var/www/edux/Edux_v2/venv/lib/python3.10/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                   @   sT   e Zd ZdZdeddfddZejdee	dee
ee
eef f f  fddZdS )	CheckForUpdateABCzAbstract class to check for update.

    Args:
        version: Current JupyterLab version

    Attributes:
        version - str: Current JupyterLab version
        logger - logging.Logger: Server logger
    versionreturnNc                 C   s
   || _ d S N)r+   )selfr+   r   r   r   __init__>   s   
zCheckForUpdateABC.__init__c                    s   d}t |)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 implemented)NotImplementedError)r.   msgr   r   r   __call__A   s   	zCheckForUpdateABC.__call__)r!   r"   r#   r$   r'   r/   abcabstractmethodr   r
   r	   r2   r   r   r   r   r*   3   s
    
2r*   c                   @   s2   e Zd ZdZdeeeeeef f  fddZdS )CheckForUpdatezDefault class to check for update.

    Args:
        version: Current JupyterLab version

    Attributes:
        version - str: Current JupyterLab version
        logger - logging.Logger: Server logger
    r,   c              
      s   t  }z|jtddidI dH }t|jd}|d }W n ty; } z| j	j
d|d W Y d}~dS d}~ww t| jt|k r^td	}|d
| d|dt | ff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datalast_versionetransr   r   r   r2   Y   s(   
zCheckForUpdate.__call__N)r!   r"   r#   r$   r   r	   r'   r2   r   r   r   r   r5   N   s    &
r5   c                   @   s"   e Zd ZdZded f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
    r,   Nc                    s   dS )r6   Nr   )r.   r   r   r   r2      s   zNeverCheckForUpdate.__call__)r!   r"   r#   r$   r   r2   r   r   r   r   rQ   w   s    rQ   c                       @   e Zd ZdZ	d	dee ddf 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   rT   logrF   )r.   rT   	__class__r   r   rV      s   
z CheckForUpdateHandler.initializec              
      s   d}|   I dH }|r=t|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 rMdnt|i dS )zCheck for updates.
        Response:
            {
                "notification": Optional[Notification]
            }
        Nr   )tzg     @@r:   rM   updateidtagsr   r   r   r   r   r       notification)rT   
isinstancer'   r   nowr   utcr   hashlibsha1encode	hexdigestr   
set_statusfinishrA   dumpsr   )r.   ra   outr   r   rc   hash_r   r   r   rD      s&   
	zCheckForUpdateHandler.getr-   )r!   r"   r#   r$   r   r5   rV   r   authenticatedrD   __classcell__r   r   rX   r   rS      s    
rS   c                       rR   )
NewsHandlerzSNews API handler.

    Args:
        news_url: The Atom feed to fetch for news
    Nnews_urlr,   c                    s   t    || _d S r-   )rU   rV   rq   )r.   rq   rX   r   r   rV      s   

zNewsHandler.initializec           
   
      s  g }t  }| jdurmtd ddi D ]
\}}t|| qz*|j| jddidI dH }t	|j
} fdd	}t||d
}|| W n tyl }	 z| jjd| j |	d W Y d}	~	nd}	~	ww | d | tdttt|i dS )zpGet the news.

        Response:
            {
                "news": List[Notification]
            }
        Nr=   atomzhttp://www.w3.org/2005/Atomr7   zapplication/atom+xmlr8   c              
      s  ddt dtt  dt f fdd}|d}|d}|d}|d	|}|d
dd} d}t|dkrHttdd |}|rC|d n|d }	nt|dkrR|d nd }	|	d ur]|	dnd }
|rhd||gn|}t|}t|}t	|||d|
d u r}d n
d|
fd|dgdid}|S )Nattrr   r,   c                    s>     d|  }|d ur|jS |d ur|S d|  }t|)Nzatom:z7atom feed entry does not contain a required attribute: )findtextKeyError)rs   r   	node_itemerror_m)nodexml_namespacesr   r   get_xml_text   s   z:NewsHandler.get.<locals>.build_entry.<locals>.get_xml_texttitler]   updated	publishedsummary )r   z	atom:link   c                 S   s   |  ddkS )Nrel	alternate)rD   )elemr   r   r   <lambda>   s    z6NewsHandler.get.<locals>.build_entry.<locals>.<lambda>r   href
r:   zOpen full postrM   newsr\   r_   r-   )r'   r   findalllenlistfilterrD   joinr   r   rI   )ry   r{   entry_titleentry_identry_updatedentry_publishedentry_summarylinksr   	link_node
entry_linkr   modified_at
created_atra   rP   rz   )ry   r   build_entry   sB   "
z$NewsHandler.get.<locals>.build_entryz
atom:entryz,Failed to get announcements from Atom feed: r;   r`   r   )r   r>   rq   r   rH   itemsETregister_namespacer?   
fromstringrC   mapr   extendrE   rW   rG   ri   rj   rA   rk   r   r   )
r.   r   rK   keyspecrL   treer   entriesrO   r   r   r   rD      s4   	

3

"zNewsHandler.getr-   )r!   r"   r#   r$   r   r'   rV   r   rn   rD   ro   r   r   rX   r   rp      s    rp   z/lab/api/newsz/lab/api/update),r$   r3   re   rA   xml.etree.ElementTreeetreeElementTreer   dataclassesr   r   r   r   r   typingr   r   r	   r
   jupyter_server.base.handlersr   #jupyterlab_server.translation_utilsr   packaging.versionr   tornador   r   jupyterlab._versionr   ISO8601_FORMATr@   rJ   r'   r   r   ABCr*   r5   rQ   rS   rp   news_handler_pathcheck_update_handler_pathr   r   r   r   <module>   s4    ).i