o
    "hJ                  	   @   s   d Z ddlZddlmZ ddlmZmZmZmZ ddl	m
Z
mZ ddlmZmZmZ er2ddlmZ G dd	 d	e
eeef eeef eeef f ZdS )
z/This module contains the DictPersistence class.    N)deepcopy)TYPE_CHECKINGAnyOptionalcast)BasePersistencePersistenceInput)CDCDataConversationDictConversationKey)JSONDictc                       s0  e Zd ZdZdZ							dUdee deded	ed
ededef fddZ	e
deeeeeef f  fddZe
defddZe
deeeeeef f  fddZe
defddZe
deeeef  fddZe
defddZe
dee fddZe
defddZe
deeeef  fd d!Ze
defd"d#Zdeeeeef f fd$d%Zdeeeeef f fd&d'Zdeeef fd(d)Zdee fd*d+Zd,edefd-d.Zd,ed/e d0ee ddfd1d2Z!d3ed4eeef ddfd5d6Z"d7ed4eeef ddfd8d9Z#d4eeef ddfd:d;Z$d4eddfd<d=Z%d7eddfd>d?Z&d3eddfd@dAZ'd3edBeeef ddfdCdDZ(d7edEeeef ddfdFdGZ)dHeeef ddfdIdJZ*dVdKdLZ+e,dMeeef defdNdOZ-e,dPedeeef fdQdRZ.e,d4edeeeeef f fdSdTZ/  Z0S )WDictPersistenceay
  Using Python's :obj:`dict` and :mod:`json` for making your bot persistent.

    Attention:
        The interface provided by this class is intended to be accessed exclusively by
        :class:`~telegram.ext.Application`. Calling any of the methods below manually might
        interfere with the integration of persistence into :class:`~telegram.ext.Application`.

    Note:
        * Data managed by :class:`DictPersistence` is in-memory only and will be lost when the bot
          shuts down. This is, because :class:`DictPersistence` is mainly intended as starting
          point for custom persistence classes that need to JSON-serialize the stored data before
          writing them to file/database.

        * This implementation of :class:`BasePersistence` does not handle data that cannot be
          serialized by :func:`json.dumps`.

    .. seealso:: :wiki:`Making Your Bot Persistent <Making-your-bot-persistent>`

    .. versionchanged:: 20.0
        The parameters and attributes ``store_*_data`` were replaced by :attr:`store_data`.

    Args:
        store_data (:class:`~telegram.ext.PersistenceInput`, optional): Specifies which kinds of
            data will be saved by this persistence instance. By default, all available kinds of
            data will be saved.
        user_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
            user_data on creating this persistence. Default is ``""``.
        chat_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
            chat_data on creating this persistence. Default is ``""``.
        bot_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
            bot_data on creating this persistence. Default is ``""``.
        conversations_json (:obj:`str`, optional): JSON string that will be used to reconstruct
            conversation on creating this persistence. Default is ``""``.
        callback_data_json (:obj:`str`, optional): JSON string that will be used to reconstruct
            callback_data on creating this persistence. Default is ``""``.

            .. versionadded:: 13.6
        update_interval (:obj:`int` | :obj:`float`, optional): The
            :class:`~telegram.ext.Application` will update
            the persistence in regular intervals. This parameter specifies the time (in seconds) to
            wait between two consecutive runs of updating the persistence. Defaults to 60 seconds.

            .. versionadded:: 20.0
    Attributes:
        store_data (:class:`~telegram.ext.PersistenceInput`): Specifies which kinds of data will
            be saved by this persistence instance.
    )
	_bot_data_bot_data_json_callback_data_callback_data_json
_chat_data_chat_data_json_conversations_conversations_json
_user_data_user_data_jsonN <   
store_datauser_data_jsonchat_data_jsonbot_data_jsonconversations_jsoncallback_data_jsonupdate_intervalc           
   
      sJ  t  j||d d | _d | _d | _d | _d | _d | _d | _d | _	d | _
d | _|rGz| || _|| _W n ttfyF } ztd|d }~ww |rhz| || _|| _W n ttfyg } ztd|d }~ww |rzt|| _|| _	W n ttfy } ztd|d }~ww t| jtstd|rzt|}	W n ttfy } ztd|d }~ww z|	d u rd | _ntddd	 |	d
 D |	d f| _|| _
W n ttfy } ztd|d }~ww | jd urtdd | jd
 D rt| jd tstd|r#z| || _|| _W d S  ttfy" } ztd|d }~ww d S )N)r   r    z4Unable to deserialize user_data_json. Not valid JSONz4Unable to deserialize chat_data_json. Not valid JSONz3Unable to deserialize bot_data_json. Not valid JSONz%bot_data_json must be serialized dictz8Unable to deserialize callback_data_json. Not valid JSONr	   c                 S   s    g | ]\}}}|t ||fqS  )float).0onetwothreer!   r!   P/var/www/html/venv/lib/python3.10/site-packages/telegram/ext/_dictpersistence.py
<listcomp>   s     z,DictPersistence.__init__.<locals>.<listcomp>r      z0callback_data_json is not in the required formatc                 s   s,    | ]}t |d  tot |d tV  qdS )   r   N)
isinstancedictstr)r#   entryr!   r!   r'   	<genexpr>   s
    
z+DictPersistence.__init__.<locals>.<genexpr>z8Unable to deserialize conversations_json. Not valid JSON)super__init__r   r   r   r   r   r   r   r   r   r    _decode_user_chat_data_from_json
ValueErrorAttributeError	TypeErrorjsonloadsr+   r,   r   
IndexErrorall_decode_conversations_from_json)
selfr   r   r   r   r   r   r    excdata	__class__r!   r'   r1   ]   s   









zDictPersistence.__init__returnc                 C      | j S )z%:obj:`dict`: The user_data as a dict.)r   r;   r!   r!   r'   	user_data      zDictPersistence.user_datac                 C      | j r| j S t| jS )z6:obj:`str`: The user_data serialized as a JSON-string.)r   r6   dumpsrC   rB   r!   r!   r'   r         zDictPersistence.user_data_jsonc                 C   rA   )z%:obj:`dict`: The chat_data as a dict.)r   rB   r!   r!   r'   	chat_data   rD   zDictPersistence.chat_datac                 C   rE   )z6:obj:`str`: The chat_data serialized as a JSON-string.)r   r6   rF   rH   rB   r!   r!   r'   r      rG   zDictPersistence.chat_data_jsonc                 C   rA   )z$:obj:`dict`: The bot_data as a dict.)r   rB   r!   r!   r'   bot_data   rD   zDictPersistence.bot_datac                 C   rE   )z5:obj:`str`: The bot_data serialized as a JSON-string.)r   r6   rF   rI   rB   r!   r!   r'   r      rG   zDictPersistence.bot_data_jsonc                 C   rA   )ztuple[list[tuple[:obj:`str`, :obj:`float`, dict[:obj:`str`, :class:`object`]]],         dict[:obj:`str`, :obj:`str`]]: The metadata on the stored callback data.

        .. versionadded:: 13.6
        )r   rB   r!   r!   r'   callback_data   s   zDictPersistence.callback_datac                 C   rE   )zo:obj:`str`: The metadata on the stored callback data as a JSON-string.

        .. versionadded:: 13.6
        )r   r6   rF   rJ   rB   r!   r!   r'   r      s   z"DictPersistence.callback_data_jsonc                 C   rA   )z):obj:`dict`: The conversations as a dict.)r   rB   r!   r!   r'   conversations   rD   zDictPersistence.conversationsc                 C   s*   | j r| j S | jr| | jS t| jS )z::obj:`str`: The conversations serialized as a JSON-string.)r   rK   _encode_conversations_to_jsonr6   rF   rB   r!   r!   r'   r      s
   z"DictPersistence.conversations_jsonc                       | j du r	i | _t| j S )zReturns the user_data created from the ``user_data_json`` or an empty :obj:`dict`.

        Returns:
            :obj:`dict`: The restored user data.
        N)rC   r   r   rB   r!   r!   r'   get_user_data      

zDictPersistence.get_user_datac                    rM   )zReturns the chat_data created from the ``chat_data_json`` or an empty :obj:`dict`.

        Returns:
            :obj:`dict`: The restored chat data.
        N)rH   r   r   rB   r!   r!   r'   get_chat_data   rO   zDictPersistence.get_chat_datac                    rM   )zReturns the bot_data created from the ``bot_data_json`` or an empty :obj:`dict`.

        Returns:
            :obj:`dict`: The restored bot data.
        N)rI   r   r   rB   r!   r!   r'   get_bot_data  rO   zDictPersistence.get_bot_datac                    s    | j du rd| _dS t| j S )ad  Returns the callback_data created from the ``callback_data_json`` or :obj:`None`.

        .. versionadded:: 13.6

        Returns:
            tuple[list[tuple[:obj:`str`, :obj:`float`, dict[:obj:`str`, :class:`object`]]],                 dict[:obj:`str`, :obj:`str`]]: The restored metadata or :obj:`None`,                 if no data was stored.
        N)rJ   r   r   rB   r!   r!   r'   get_callback_data  s
   


z!DictPersistence.get_callback_datanamec                    s$   | j du r	i | _| j |i  S )zReturns the conversations created from the ``conversations_json`` or an empty
        :obj:`dict`.

        Returns:
            :obj:`dict`: The restored conversations data.
        N)rK   r   getcopy)r;   rS   r!   r!   r'   get_conversations  s   
z!DictPersistence.get_conversationskey	new_statec                    sB   | j si | _ | j |i ||krdS || j | |< d| _dS )a  Will update the conversations for the given handler.

        Args:
            name (:obj:`str`): The handler's name.
            key (:obj:`tuple`): The key the state is changed for.
            new_state (:obj:`tuple` | :class:`object`): The new state for the given key.
        N)r   
setdefaultrT   r   )r;   rS   rW   rX   r!   r!   r'   update_conversation)  s   

z#DictPersistence.update_conversationuser_idr=   c                    :   | j du r	i | _ | j ||krdS || j |< d| _dS )zWill update the user_data (if changed).

        Args:
            user_id (:obj:`int`): The user the data might have been changed for.
            data (:obj:`dict`): The :attr:`telegram.ext.Application.user_data` ``[user_id]``.
        N)r   rT   r   )r;   r[   r=   r!   r!   r'   update_user_data:     


z DictPersistence.update_user_datachat_idc                    r\   )zWill update the chat_data (if changed).

        Args:
            chat_id (:obj:`int`): The chat the data might have been changed for.
            data (:obj:`dict`): The :attr:`telegram.ext.Application.chat_data` ``[chat_id]``.
        N)r   rT   r   )r;   r_   r=   r!   r!   r'   update_chat_dataH  r^   z DictPersistence.update_chat_datac                        | j |krdS || _ d| _dS )zWill update the bot_data (if changed).

        Args:
            data (:obj:`dict`): The :attr:`telegram.ext.Application.bot_data`.
        N)r   r   r;   r=   r!   r!   r'   update_bot_dataV  s
   

zDictPersistence.update_bot_datac                    ra   )aK  Will update the callback_data (if changed).

        .. versionadded:: 13.6

        Args:
            data (tuple[list[tuple[:obj:`str`, :obj:`float`, dict[:obj:`str`, :class:`object`]]],                 dict[:obj:`str`, :obj:`str`]]): The relevant data to restore
                :class:`telegram.ext.CallbackDataCache`.
        N)r   r   rb   r!   r!   r'   update_callback_dataa  s
   


z$DictPersistence.update_callback_datac                    (   | j du rdS | j |d d| _dS )zWill delete the specified key from the :attr:`chat_data`.

        .. versionadded:: 20.0

        Args:
            chat_id (:obj:`int`): The chat id to delete from the persistence.
        N)r   popr   )r;   r_   r!   r!   r'   drop_chat_datap  
   

zDictPersistence.drop_chat_datac                    re   )zWill delete the specified key from the :attr:`user_data`.

        .. versionadded:: 20.0

        Args:
            user_id (:obj:`int`): The user id to delete from the persistence.
        N)r   rf   r   )r;   r[   r!   r!   r'   drop_user_data}  rh   zDictPersistence.drop_user_datarC   c                       dS )zDoes nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_user_data`
        Nr!   )r;   r[   rC   r!   r!   r'   refresh_user_data      z!DictPersistence.refresh_user_datarH   c                    rj   )zDoes nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_chat_data`
        Nr!   )r;   r_   rH   r!   r!   r'   refresh_chat_data  rl   z!DictPersistence.refresh_chat_datarI   c                    rj   )zDoes nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_bot_data`
        Nr!   )r;   rI   r!   r!   r'   refresh_bot_data  rl   z DictPersistence.refresh_bot_datac                    rj   )zvDoes nothing.

        .. versionadded:: 20.0
        .. seealso:: :meth:`telegram.ext.BasePersistence.flush`
        Nr!   rB   r!   r!   r'   flush  rl   zDictPersistence.flushrK   c                 C   sL   i }|   D ]\}}i ||< |  D ]\}}||| t|< qqt|S )af  Helper method to encode a conversations dict (that uses tuples as keys) to a
        JSON-serializable way. Use :meth:`self._decode_conversations_from_json` to decode.

        Args:
            conversations (:obj:`dict`): The conversations dict to transform to JSON.

        Returns:
            :obj:`str`: The JSON-serialized conversations dict
        )itemsr6   rF   )rK   tmphandlerstatesrW   stater!   r!   r'   rL     s   
z-DictPersistence._encode_conversations_to_jsonjson_stringc                 C   sT   t | }i }| D ]\}}i ||< | D ]\}}||| tt |< qq|S )aQ  Helper method to decode a conversations dict (that uses tuples as keys) from a
        JSON-string created with :meth:`self._encode_conversations_to_json`.

        Args:
            json_string (:obj:`str`): The conversations dict as JSON string.

        Returns:
            :obj:`dict`: The conversations dict after decoding
        )r6   r7   rp   tuple)ru   rq   rK   rr   rs   rW   rt   r!   r!   r'   r:     s   
z/DictPersistence._decode_conversations_from_jsonc           	   
   C   sv   i }t | }| D ]-\}}t|}i ||< | D ]\}}zt|}W n ty0   |}Y nw ||| |< qq|S )a  Helper method to decode chat or user data (that uses ints as keys) from a
        JSON-string.

        Args:
            data (:obj:`str`): The user/chat_data dict as JSON string.

        Returns:
            :obj:`dict`: The user/chat_data defaultdict after decoding
        )r6   r7   rp   intr3   )	r=   rq   decoded_datauserrC   int_user_idrW   value_idr!   r!   r'   r2     s   
z0DictPersistence._decode_user_chat_data_from_json)Nr   r   r   r   r   r   )r@   N)1__name__
__module____qualname____doc__	__slots__r   r   r-   r"   r1   propertyr,   rw   r   rC   r   rH   r   rI   r   r	   rJ   r   r
   rK   r   objectrN   rP   rQ   rR   rV   r   rZ   r]   r`   rc   rd   rg   ri   rk   rm   rn   ro   staticmethodrL   r:   r2   __classcell__r!   r!   r>   r'   r      s    0O$$	




,r   )r   r6   rU   r   typingr   r   r   r   telegram.extr   r   telegram.ext._utils.typesr	   r
   r   telegram._utils.typesr   r,   r   r!   r!   r!   r'   <module>   s   6