o
    ZzjOJ  ã                	   @   s–   d Z ddl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mZ er0d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Úcast)ÚBasePersistenceÚPersistenceInput)ÚCDCDataÚConversationDictÚConversationKey)ÚJSONDictc                       s0  e Zd ZdZdZ							dUdedB deded	ed
ededef‡ fdd„Ze	de
ee
eef f dB fdd„ƒZe	defdd„ƒZe	de
ee
eef f dB fdd„ƒZe	defdd„ƒZe	de
eef dB fdd„ƒZe	defdd„ƒZe	dedB fdd„ƒZe	defdd„ƒZe	de
eef dB 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dB fd*d+„Zd,edefd-d.„Zd,ed/ed0edB 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.‡  Z/S )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 |r“zt |¡| _|| _	W n ttfyˆ } ztdƒ|‚d }~ww t| jtƒs“tdƒ‚|rÿzt |¡}	W n ttfy¯ } ztdƒ|‚d }~ww z|	d u r¹d | _ntddd	„ |	d
 D ƒ|	d fƒ| _|| _
W n ttfyá } ztdƒ|‚d }~ww | jd urÿtdd„ | jd
 D ƒƒrût| jd tƒsÿt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    úX/var/www/kodo/tsheker/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&   r0   ^   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   r5   ÚdumpsrB   rA   r    r    r&   r   ²   ó   zDictPersistence.user_data_jsonc                 C   r@   )z%:obj:`dict`: The chat_data as a dict.)r   rA   r    r    r&   Ú	chat_data¹   rC   zDictPersistence.chat_datac                 C   rD   )z6:obj:`str`: The chat_data serialized as a JSON-string.)r   r5   rE   rG   rA   r    r    r&   r   ¾   rF   zDictPersistence.chat_data_jsonc                 C   r@   )z$:obj:`dict`: The bot_data as a dict.)r   rA   r    r    r&   Úbot_dataÅ   rC   zDictPersistence.bot_datac                 C   rD   )z5:obj:`str`: The bot_data serialized as a JSON-string.)r   r5   rE   rH   rA   r    r    r&   r   Ê   rF   zDictPersistence.bot_data_jsonc                 C   r@   )zÉtuple[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   rA   r    r    r&   Úcallback_dataÑ   s   zDictPersistence.callback_datac                 C   rD   )zo:obj:`str`: The metadata on the stored callback data as a JSON-string.

        .. versionadded:: 13.6
        )r   r5   rE   rI   rA   r    r    r&   r   Ú   s   z"DictPersistence.callback_data_jsonc                 C   r@   )z):obj:`dict`: The conversations as a dict.)r   rA   r    r    r&   Úconversationsä   rC   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   rJ   Ú_encode_conversations_to_jsonr5   rE   rA   r    r    r&   r   é   s
   z"DictPersistence.conversations_jsonc                 Ã   ó   �| j du r	i | _t| j ƒS )zžReturns the user_data created from the ``user_data_json`` or an empty :obj:`dict`.

        Returns:
            :obj:`dict`: The restored user data.
        N)rB   r   r   rA   r    r    r&   Úget_user_dataò   ó   €

zDictPersistence.get_user_datac                 Ã   rL   )zžReturns the chat_data created from the ``chat_data_json`` or an empty :obj:`dict`.

        Returns:
            :obj:`dict`: The restored chat data.
        N)rG   r   r   rA   r    r    r&   Úget_chat_dataü   rN   zDictPersistence.get_chat_datac                 Ã   rL   )z›Returns the bot_data created from the ``bot_data_json`` or an empty :obj:`dict`.

        Returns:
            :obj:`dict`: The restored bot data.
        N)rH   r   r   rA   r    r    r&   Úget_bot_data  rN   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)rI   r   r   rA   r    r    r&   Úget_callback_data  s
   €

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

        Returns:
            :obj:`dict`: The restored conversations data.
        N)rJ   r   ÚgetÚcopy)r:   rR   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   Ú
setdefaultrS   r   )r:   rR   rV   rW   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 )zîWill 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   rS   r   )r:   rZ   r<   r    r    r&   Úupdate_user_data;  ó   €


z DictPersistence.update_user_dataÚchat_idc                 Ã   r[   )zîWill 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   rS   r   )r:   r^   r<   r    r    r&   Úupdate_chat_dataI  r]   z DictPersistence.update_chat_datac                 Ã   ó    �| j |krdS || _ d| _dS )z�Will 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_dataW  s
   €

zDictPersistence.update_bot_datac                 Ã   r`   )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   ra   r    r    r&   Úupdate_callback_datab  s
   €


z$DictPersistence.update_callback_datac                 Ã   ó(   �| j du rdS | j  |d¡ d| _dS )z¿Will 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_dataq  ó
   €

zDictPersistence.drop_chat_datac                 Ã   rd   )z¿Will 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   re   r   )r:   rZ   r    r    r&   Údrop_user_data~  rg   zDictPersistence.drop_user_datarB   c                 Ã   ó   �dS )z‚Does nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_user_data`
        Nr    )r:   rZ   rB   r    r    r&   Úrefresh_user_data‹  ó    z!DictPersistence.refresh_user_datarG   c                 Ã   ri   )z‚Does nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_chat_data`
        Nr    )r:   r^   rG   r    r    r&   Úrefresh_chat_data’  rk   z!DictPersistence.refresh_chat_datarH   c                 Ã   ri   )z�Does nothing.

        .. versionadded:: 13.6
        .. seealso:: :meth:`telegram.ext.BasePersistence.refresh_bot_data`
        Nr    )r:   rH   r    r    r&   Úrefresh_bot_data™  rk   z DictPersistence.refresh_bot_datac                 Ã   ri   )zvDoes nothing.

        .. versionadded:: 20.0
        .. seealso:: :meth:`telegram.ext.BasePersistence.flush`
        Nr    rA   r    r    r&   Úflush   rk   zDictPersistence.flushrJ   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
        )Úitemsr5   rE   )rJ   ÚtmpÚhandlerÚstatesrV   Ústater    r    r&   rK   §  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
        )r5   r6   ro   Útuple)rt   rp   rJ   rq   rr   rV   rs   r    r    r&   r9   ¹  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
        )r5   r6   ro   Úintr2   )	r<   rp   Údecoded_dataÚuserrB   Úint_user_idrV   ÚvalueÚ_idr    r    r&   r1   Ì  s   
ÿûz0DictPersistence._decode_user_chat_data_from_json)Nr   r   r   r   r   r   )r?   N)0Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r   r,   r!   r0   Úpropertyr+   rv   r   rB   r   rG   r   rH   r   r   rI   r   r	   rJ   r   ÚobjectrM   rO   rP   rQ   rU   r
   rY   r\   r_   rb   rc   rf   rh   rj   rl   rm   rn   ÚstaticmethodrK   r9   r1   Ú__classcell__r    r    r=   r&   r       s–    0øþýüûúùøO$$	


ÿÿÿ
þ
,r   )r   r5   rT   r   Útypingr   r   r   Útelegram.extr   r   Útelegram.ext._utils.typesr   r	   r
   Útelegram._utils.typesr   r+   r   r    r    r    r&   Ú<module>   s   6