o
    ^iJ'                     @   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	 ddl
mZmZmZ ddlmZmZ ddl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)	Awaitable)asdict	dataclassfield)datetimetimezone)Optional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   \/home/ubuntu/hpml_nyu/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   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__B   s   	zCheckForUpdateABC.__call__)r    r!   r"   r#   r&   r.   abcabstractmethodr   r	   r'   r1   r   r   r   r   r)   4   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.u   Read more…)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   r1   Z   s(   
zCheckForUpdate.__call__N)r    r!   r"   r#   r   r'   r&   r1   r   r   r   r   r4   O   s    &
r4   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 )r5   Nr   )r-   r   r   r   r1      s   zNeverCheckForUpdate.__call__)r    r!   r"   r#   r   r1   r   r   r   r   rP   x   s    rP   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
initializerP   r   rS   logrE   )r-   rS   	__class__r   r   rU      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     @@r9   rL   updateidtagsr   r   r   r   r   r      notification)rS   
isinstancer&   r   nowr   utcr   hashlibsha1encode	hexdigestr   
set_statusfinishr@   dumpsr   )r-   r`   outr   r   rb   hash_r   r   r   rC      s&   
	zCheckForUpdateHandler.getr,   )r    r!   r"   r#   r   r4   rU   r   authenticatedrC   __classcell__r   r   rW   r   rR      s    
rR   c                       rQ   )
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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/Atomr6   zapplication/atom+xmlr7   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)rr   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)rC   )elemr   r   r   <lambda>   s    z6NewsHandler.get.<locals>.build_entry.<locals>.<lambda>r   href
r9   zOpen full postrL   newsr[   r^   r,   )r&   r   findalllenlistfilterrC   joinr   r   rH   )rx   rz   entry_titleentry_identry_updatedentry_publishedentry_summarylinksr   	link_node
entry_linkr   modified_at
created_atr`   rO   ry   )rx   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   rG   itemsETregister_namespacer>   
fromstringrB   mapr   extendrD   rV   rF   rh   ri   r@   rj   r   r   )
r-   r   rJ   keyspecrK   treer   entriesrN   r   r   r   rC      s4   	

3

"zNewsHandler.getr,   )r    r!   r"   r#   r   r&   rU   r   rm   rC   rn   r   r   rW   r   ro      s    ro   z/lab/api/newsz/lab/api/update),r#   r2   rd   r@   xml.etree.ElementTreeetreeElementTreer   collections.abcr   dataclassesr   r   r   r   r   typingr   r	   jupyter_server.base.handlersr
   #jupyterlab_server.translation_utilsr   packaging.versionr   tornador   r   jupyterlab._versionr   ISO8601_FORMATr?   rI   r&   r   r   ABCr)   r4   rP   rR   ro   news_handler_pathcheck_update_handler_pathr   r   r   r   <module>   s6    ).i