U
    Lwa#                  	   @   s   d dl m Z d dlZd dlZd dlmZmZmZ z,d dlZ	d dl
Z
edd d dlmZ W n eefk
rt   Y nX d dlmZmZmZmZ d dlmZ d	d
 ZG dd dZG dd dejZdS )    )gettextN)GioGLibGObjectSnapd1)r   )has_gnome_online_accountsis_current_distro_ltsis_current_distro_supportedretry)LivepatchSnapc              
   C   sD   |   D ]6\}}ztj|| |< W q ttfk
r<   Y qX q| S N)itemsdateutilparserparse
ValueError	TypeError)Z	json_dictkeyvalue r   E/usr/lib/python3/dist-packages/softwareproperties/LivepatchService.pydatetime_parser/   s    r   c                   @   s   e Zd ZdZdZdZdZdS )LivepatchAvailabilityr            N)__name__
__module____qualname__FALSETRUENO_CONNECTIVITYCHECKINGr   r   r   r   r   7   s   r   c                   @   s   e Zd ZdZdZdZdZedZedZ	e
ddejejejejfedddejfedddejfd	Zd
d Zdd Zdd Zdd Zdd Zdd Zeedd Zdd Zeedd Zdd Zdd ZdS ) LivepatchServicezRhttp+unix://%2Fvar%2Fsnap%2Fcanonical-livepatch%2Fcurrent%2Flivepatchd.sock/statuszWhttp+unix://%2Fvar%2Fsnap%2Fcanonical-livepatch%2Fcurrent%2Flivepatchd-priv.sock/enablezXhttp+unix://%2Fvar%2Fsnap%2Fcanonical-livepatch%2Fcurrent%2Flivepatchd-priv.sock/disablez2/var/snap/canonical-livepatch/common/machine-tokenzFailed to enable Livepatch: {}zFailed to disable Livepatch: {}NF)availabilityavailability-messageenabledc                 C   s   t j |  d| _t | _t | _tj	| _
d | _tjj| jd}| | _tj | _| jd| j |tjj| _| jd| j d S )Nr   )pathznotify::connectivityZchanged)r   __init___timeout_idr   _snaprequests_unixsocketZSession_sessionr   r    _availability_availability_messager   ZFileZnew_for_pathLIVEPATCH_RUNNING_FILEquery_exists_enabledZNetworkMonitorZget_default_nmZconnect_network_changed_cbZmonitor_fileZFileMonitorFlagsZNONEZ_lp_monitor_livepatch_enabled_changed_cb)selfZlp_filer   r   r   r)   W   s    

zLivepatchService.__init__c                 C   s8   |j dkr| jS |j dkr | jS |j dkr0| jS td S )Nr%   r&   r'   )namer.   r/   r2   AssertionError)r6   Zpspecr   r   r   do_get_propertym   s    


z LivepatchService.do_get_propertyc                    sJ    fdd}t j _d _ d  d  jdkrFtd| _dS )a  Trigger a Livepatch availability check to be executed after a short
        timeout. Multiple triggers will result in a single request.

        A notify::availability will be emitted when the check starts, and
        another one when the check ends.
        c                     s    fddt dftt dftt dftt dfg}  jjjtjj	krVt
j _d  _n4| D ] \}}| sZt
j _| _ qqZt
j _d  _ d  d d	 _d
S )Nc                      s    j  tjjkS r   )r+   
get_statusr   
SnapStatusZUNKNOWNr   r6   r   r   <lambda>       z[LivepatchService.trigger_availability_check.<locals>._update_availability.<locals>.<lambda>z*Canonical Livepatch snap is not available.z6Gnome Online Accounts is required to enable Livepatch.z,Livepatch is not available for this release.z+The current release is no longer supported.r%   r&   r   F)_r   r	   r
   r3   ZpropsZconnectivityr   ZNetworkConnectivityZFULLr   r"   r.   r/   r    r!   notifyr*   )Zrulesfuncmessager<   r   r   _update_availability   s6    



zILivepatchService.trigger_availability_check.<locals>._update_availabilityNr%   r&   r   r   )r   r#   r.   r/   r@   r*   r   Ztimeout_add_seconds)r6   rC   r   r<   r   trigger_availability_checkx   s    !


z+LivepatchService.trigger_availability_checkc                 C   s^   | j |krdS |s|  S | j tjjkr6| |S | j \}}|rR| |S d|fS dS )a  Enable or disable Canonical Livepatch in the current system. This
        function will return once the operation succeeded or failed.

        Args:
            enabled(bool): wheater to enable or disable the service.
            token(str): the authentication token to be used to enable Canonical
                Livepatch service.

        Returns:
            (False, '') if successful, (True, error_message) otherwise.
        )F TN)	r2   _disable_servicer+   r:   r   r;   ZACTIVE_enable_serviceZenable_or_install)r6   r'   tokenZsuccessmsgr   r   r   set_enabled   s    

zLivepatchService.set_enabledc              
   C   sl   z*ddd}| j j| j|d}|jtdW S  tk
rf } ztdt	| W Y dS d}~X Y nX dS )zSynchronously retrieve the status of Canonical Livepatch.

        Returns:
            str: The status. A valid string for success, None otherwise.
        r   json)	verbosityformatparams)Zobject_hookz"Failed to get Livepatch status: {}N)
r-   getSTATUS_ENDPOINTrK   r   	ExceptionloggingdebugrM   str)r6   rO   rer   r   r   r:      s    
zLivepatchService.get_statusc              
   C   sL   z|  |W S  tk
rF } zd| jt|f W Y S d}~X Y nX dS )a`  Enable Canonical Livepatch in the current system. This function will
        return once the operation succeeded or failed.

        Args:
            token(str): the authentication token to be used to enable Canonical
                Livepatch service.

        Returns:
            (False, '') if successful, (True, error_message) otherwise.
        TN)_enable_service_with_retryrR   ENABLE_ERROR_MSGrM   rU   )r6   rH   rW   r   r   r   rG      s    z LivepatchService._enable_servicec                 C   s:   d|i}| j j| j|d}|j |jr*dn| j|jfS )Nz
auth-tokenrN   rE   )r-   putENABLE_ENDPOINTokrY   rM   text)r6   rH   rO   rV   r   r   r   rX      s    z+LivepatchService._enable_service_with_retryc              
   C   sJ   z
|   W S  tk
rD } zd| jt|f W Y S d}~X Y nX dS )zDisable Canonical Livepatch in the current system. This function will
        return once the operation succeeded or failed.

        Returns:
            (False, '') if successful, (True, error_message) otherwise.
        TN)_disable_service_with_retryrR   DISABLE_ERROR_MSGrM   rU   )r6   rW   r   r   r   rF      s    
z!LivepatchService._disable_servicec                 C   s.   | j | j}|j |jrdn| j|jfS )NrE   )r-   rZ   DISABLE_ENDPOINTr\   r_   rM   r]   )r6   rV   r   r   r   r^      s    z,LivepatchService._disable_service_with_retryc                 C   s   |    d S r   )rD   )r6   ZmonitorZnetwork_availabler   r   r   r4      s    z$LivepatchService._network_changed_cbc                 C   s&   |  }| j|kr"|| _| d d S )Nr'   )r1   r2   r@   )r6   ZfmfileZ
other_fileZ
event_typer'   r   r   r   r5      s    
z.LivepatchService._livepatch_enabled_changed_cb) r   r   r   rQ   r[   r`   r0   r?   rY   r_   intr   r    r#   r   ZPARAM_READABLErU   boolZ__gproperties__r)   r9   rD   rJ   r:   rG   r   rR   rX   rF   r^   r4   r5   r   r   r   r   r$   >   sP             0

r$   )r   r?   rS   ZgiZgi.repositoryr   r   r   Zdateutil.parserr   r,   Zrequire_versionr   ImportErrorr   Zsoftwareproperties.gtk.utilsr   r	   r
   r   Z softwareproperties.LivepatchSnapr   r   r   r$   r   r   r   r   <module>   s   