o
    XzjäÖ  ã                   @   sÈ  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl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mZmZ dd	lmZ zddlZddlZddlZW n eyy   dZY nw e d
d¡ e dd¡ e dd¡ e dd¡ e dd¡ e dd¡ e dd¡ e dd¡ e dd¡ e dd¡ e dd¡ e d d!¡ e d"d#¡ e d$d%¡ e d&d'¡ e d(d)¡ e d*d+¡ e  d,¡Z!e  d-¡Z"e  d.ej#¡Z$ed/d0ƒZ%e &e'¡Z(d�d2d3„Z)d4d5„ Z*d6d7„ Z+d8d9„ Z,džd;d<„Z-d=d>„ Z.d?d@„ Z/dAdB„ Z0dCdD„ Z1dEdF„ Z2dGdH„ Z3dIdJ„ Z4dKddKdKdKdKddLœdMdN„Z5dOdP„ Z6dQdR„ Z7e-fdSdT„Z8dUdV„ Z9dWdX„ Z:dddKdKdKdKddYœdZd[„Z;d\d]„ Z<d^d_„ Z=d`da„ Z>dbdc„ Z?ddde„ Z@dfdg„ ZAdhdi„ ZBdjdk„ ZCdldm„ ZDdndo„ ZEdpdq„ ZFdrds„ ZGdtdu„ ZHdŸdvdw„ZIdxdy„ ZJdzd{„ ZKd|d}„ ZLd~d„ ZMd€d�„ ZNd‚dƒ„ ZOd„d…„ ZPd†d‡„ ZQdˆd‰„ ZRdŠd‹„ ZSdŒd�„ ZTdŽd�„ ZUd�d1d‘d’œd“d”„ZVG d•d–„ d–ƒZWd—d˜„ ZXd™dš„ ZYd›dœ„ ZZdS ) z˜
Utilities for working with the Telegram API itself (such as handy methods
to convert between an entity like a User, Chat, etc. into its Input version)
é    N)Ú
namedtuple)Úguess_extension)ÚGeneratorTypeé   )ÚmarkdownÚhtml)Úadd_surrogateÚdel_surrogateÚ
strip_text)Útypesz	image/pngz.pngz
image/jpegz.jpegz
image/webpz.webpz	image/gifz.gifz	image/bmpz.bmpzimage/x-tgaz.tgaz
image/tiffz.tiffzimage/vnd.adobe.photoshopz.psdz	video/mp4z.mp4zvideo/quicktimez.movz	video/aviz.aviz
audio/mpegz.mp3z	audio/m4az.m4az	audio/aacz.aacz	audio/oggz.oggz
audio/flacz.flaczapplication/x-tgstickerz.tgszJ@|(?:https?://)?(?:www\.)?(?:telegram\.(?:me|dog)|t\.me)/(@|\+|joinchat/)?ztg://(join)\?invite=z ^[a-z](?:(?!__)\w){1,30}[a-z\d]$ÚFileInfozdc_id location sizeéd   c                 c   s8   � t | ƒ}|d8 }|D ]}t |gt ||¡¡V  qdS )z‹
    Turns the given iterable into chunks of the specified size,
    which is 100 by default since that's what Telegram uses the most.
    r   N)ÚiterÚ	itertoolsÚchainÚislice)ÚiterableÚsizeÚitÚhead© r   úI/var/www/kodo/tsheker/venv/lib/python3.10/site-packages/telethon/utils.pyÚchunksI   s   €ÿr   c                 C   sh   t | tjƒr"| jr| jrd | j| j¡S | jr| jS | jr | jS dS t | tjtjtjtj	fƒr2| j
S dS )z}
    Gets the display name for the given :tl:`User`,
    :tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise.
    z{} {}Ú )Ú
isinstancer   ÚUserÚ	last_nameÚ
first_nameÚformatÚChatÚChatForbiddenÚChannelÚChannelForbiddenÚtitle©Úentityr   r   r   Úget_display_nameT   s   ÿr&   c                 C   s‚   zt | ƒ W dS  ty   t| tjtjfƒrY dS Y nw t| tjƒr&| j} t| tjtj	tj
fƒr?| jdkr8dS t| jƒp>dS dS )z8Gets the corresponding extension for any Telegram media.z.jpgúapplication/octet-streamr   )Úget_input_photoÚ	TypeErrorr   r   ÚUserProfilePhotoÚ	ChatPhotoÚMessageMediaDocumentÚdocumentÚDocumentÚWebDocumentÚWebDocumentNoProxyÚ	mime_typer   )Úmediar   r   r   Úget_extensionj   s"   ÿþÿ
r3   c                 C   s   t d t| ƒj|¡ƒ‚)Nz!Cannot cast {} to any kind of {}.)r)   r   ÚtypeÚ__name__)r%   Útargetr   r   r   Ú_raise_cast_fail„   s   
ÿr7   Tc                 C   s  z
| j dkr	| W S W n& ty0   |rt| dƒr| j Y S t| dƒr)t| jƒ Y S t| dƒ Y nw t| tj	ƒrV| j
r@|r@t ¡ S | jdurH| jrJ|sRt | j| j¡S tdƒ‚t| tjtjtjfƒrgt | j¡S t| tjƒrƒ| jduru| jrw|st | j| j¡S tdƒ‚t| tjƒr‘t | j| j¡S t| tjƒrŸt | j| j¡S t| tjƒr­t | j| j¡S t| tjƒr·t ¡ S t| tjƒrÇt | j| j | j¡S t| tj!ƒr×t "| j| j | j¡S t| tj#ƒrát $¡ S t| tj%ƒrìt| j&ƒS t| tj'ƒrøt | j¡S t| tj(ƒ�rt | j)¡S t| dƒ dS )a�  
    Gets the input peer for the given "entity" (user, chat or channel).

    A ``TypeError`` is raised if the given entity isn't a supported type
    or if ``check_hash is True`` but the entity's ``access_hash is None``
    *or* the entity contains ``min`` information. In this case, the hash
    cannot be used for general purposes, and thus is not returned to avoid
    any issues which can derive from invalid access hashes.

    Note that ``check_hash`` **is ignored** if an input peer is already
    passed since in that case we assume the user knows what they're doing.
    This is key to getting entities by explicitly passing ``hash = 0``.
    ì   ¶9 Úinput_entityr%   Ú	InputPeerNz4User without access_hash or min info cannot be inputz7Channel without access_hash or min info cannot be input)*ÚSUBCLASS_OF_IDÚAttributeErrorÚhasattrr9   Úget_input_peerr%   r7   r   r   r   Úis_selfÚInputPeerSelfÚaccess_hashÚminÚInputPeerUserÚidr)   r   Ú	ChatEmptyr    ÚInputPeerChatr!   ÚInputPeerChannelr"   Ú	InputUserÚuser_idÚInputChannelÚ
channel_idÚInputUserSelfÚInputUserFromMessageÚInputPeerUserFromMessageÚpeerÚmsg_idÚInputChannelFromMessageÚInputPeerChannelFromMessageÚ	UserEmptyÚInputPeerEmptyÚUserFullÚuserÚChatFullÚPeerChatÚchat_id)r%   Ú
allow_selfÚ
check_hashr   r   r   r>   ‰   sX   !
ÿ

ù	

r>   c                 C   s¢   z
| j dkr	| W S W n ty   t| dƒ Y nw t| tjtjfƒr,t | j| j	p*d¡S t| tj
ƒr:t | j| j	¡S t| tjƒrJt | j| j| j¡S t| dƒ dS )a'  
    Similar to :meth:`get_input_peer`, but for :tl:`InputChannel`'s alone.

    .. important::

        This method does not validate for invalid general-purpose access
        hashes, unlike `get_input_peer`. Consider using instead:
        ``get_input_channel(get_input_peer(channel))``.
    iýò@rJ   r   N)r;   r<   r7   r   r   r!   r"   rJ   rD   rA   rG   rK   rR   rQ   rO   rP   r$   r   r   r   Úget_input_channelé   s   

ÿÿr\   c                 C   sî   z
| j dkr	| W S W n ty   t| dƒ Y nw t| tjƒr0| jr&t ¡ S t | j	| j
p.d¡S t| tjƒr:t ¡ S t| tjtjfƒrGt ¡ S t| tjƒrRt| jƒS t| tjƒr`t | j| j
¡S t| tjƒrpt | j| j| j¡S t| dƒ dS )a$  
    Similar to :meth:`get_input_peer`, but for :tl:`InputUser`'s alone.

    .. important::

        This method does not validate for invalid general-purpose access
        hashes, unlike `get_input_peer`. Consider using instead:
        ``get_input_channel(get_input_peer(channel))``.
    l   F?ÓL rH   r   N)r;   r<   r7   r   r   r   r?   rL   rH   rD   rA   r@   rS   rT   ÚInputUserEmptyrU   Úget_input_userrV   rC   rI   rN   rM   rO   rP   r$   r   r   r   r^     s,   

ÿÿ
r^   c                 C   sz   z| j dkr	| W S | j dkrt | ¡W S W n ty#   t| dƒ Y nw zt t| ƒ¡W S  ty5   Y nw t| dƒ dS )z2Similar to :meth:`get_input_peer`, but for dialogsl   •9D r8   ÚInputDialogPeerN)r;   r   r_   r<   r7   r>   r)   )Údialogr   r   r   Úget_input_dialog-  s   

ÿÿÿra   c                 C   s¢   z
| j dkr	| W S W n ty   t| dƒ Y nw t| tjƒr*tj| j| j| j	d�S t| tj
ƒr4t ¡ S t| tjƒr?t| jƒS t| tjƒrJt| jƒS t| dƒ dS )z4Similar to :meth:`get_input_peer`, but for documentsì   h[f ÚInputDocument©rD   rA   Úfile_referenceN)r;   r<   r7   r   r   r.   rc   rD   rA   re   ÚDocumentEmptyÚInputDocumentEmptyr,   Úget_input_documentr-   ÚMessager2   )r-   r   r   r   rh   ?  s&   
ÿÿþ

rh   c                 C   s$  z
| j dkr	| W S W n ty   t| dƒ Y nw t| tjƒr"| j} t| tjjtj	fƒr/| j
} t| tjƒr@tj| j| j| jd�S t| tjƒrJt ¡ S t| tjjƒrT| j} t| tjƒr_t| jƒS t| tjƒrjt| jƒS t| tjtjtjfƒrzt| j
ƒS t| tjtjtjtjfƒr‹t ¡ S t| dƒ dS )z1Similar to :meth:`get_input_peer`, but for photosì   àcÆ Ú
InputPhotord   N) r;   r<   r7   r   r   ri   r2   ÚphotosÚPhotoÚMessageMediaPhotoÚphotork   rD   rA   re   Ú
PhotoEmptyÚInputPhotoEmptyÚmessagesrW   Ú	full_chatÚChannelFullr(   Ú
chat_photorU   Úprofile_photor!   r   r   rS   rE   r    r"   ©ro   r   r   r   r(   X  s<   
ÿÿÿ


ÿr(   c                 C   sˆ   z| j dkr	| W S | j dkrt | ¡W S W n ty#   t| dƒ Y nw t| ƒ} t| tjƒr3t | ¡S t| tj	ƒr=t 
¡ S t| dƒ dS )z6Similar to :meth:`get_input_peer`, but for chat photosl   t-Ö) l   _ÊN ÚInputChatPhotoN)r;   r   ÚInputChatUploadedPhotor<   r7   r(   r   rk   rx   rq   ÚInputChatPhotoEmptyrw   r   r   r   Úget_input_chat_photo~  s   

ÿÿ
r{   c                 C   sž   z
| j dkr	| W S W n ty   t| dƒ Y nw t| tjƒr(tj| j| jd�S t| tj	ƒr2t 
¡ S t| tjƒr=t| jƒS t| tjƒrHt| jƒS t| dƒ dS )z5Similar to :meth:`get_input_peer`, but for geo pointsi%Ò0ÚInputGeoPoint)ÚlatÚlongN)r;   r<   r7   r   r   ÚGeoPointr|   r}   r~   ÚGeoPointEmptyÚInputGeoPointEmptyÚMessageMediaGeoÚget_input_geoÚgeori   r2   )r„   r   r   r   rƒ   ‘  s    
ÿÿ

rƒ   F)Úis_photoÚ
attributesÚforce_documentÚ
voice_noteÚ
video_noteÚsupports_streamingÚttlc                C   s  z$| j dkr	| W S | j dkrtj| |d�W S | j dkr#tj| |d�W S W n ty2   t| dƒ Y nw t| tjƒrHtjt| j	ƒ| j
|pE| jd�S t| tjtjjtjfƒr]tjt| ƒ|d�S t| tjƒrrtjt| jƒ| j
|po| jd�S t| tjtjfƒr„tjt| ƒ|d�S t| tjtjfƒr¬|r–tj| |d�S t| |||||d	�\}}	tj| |	|||d
�S t| tjƒrÁtjtj| jj| jjd�d�S t| tjƒrÓtj | j!| j"| j#dd�S t| tj$ƒrâtj%t&| j'ƒd�S t| tj(ƒr÷tj)t&| j'ƒ| j*| j+| j,d�S t| tj-ƒ�rtj.t&| j'ƒ| j/| j0| j1| j2dd�S t| tj3ƒ�rt 4| j5¡S t| tj6tj7tj8tj9tj:tj;fƒ�r3t <¡ S t| tj=ƒ�rBt>| j?||d�S t| tj@ƒ�rq| jAjB�ra| jCjC�sWtDdƒ‚dd„ | jCjCD ƒ}
nd}
tjE| jA|
| jCjF| jCjGd�S t| tjHƒ�r}t E| ¡S t| dƒ dS )a  
    Similar to :meth:`get_input_peer`, but for media.

    If the media is :tl:`InputFile` and ``is_photo`` is known to be `True`,
    it will be treated as an :tl:`InputMediaUploadedPhoto`. Else, the rest
    of parameters will indicate how to treat it.
    l   ôFðu rj   )Úttl_secondsrb   Ú
InputMedia)rD   ÚspoilerrŒ   )rD   rŒ   )ÚfilerŒ   )r†   r‡   rˆ   r‰   rŠ   )r�   r1   r†   Ú
force_filerŒ   ©rD   rA   )rD   r   )Úphone_numberr   r   Úvcard)Ú	geo_point)r”   ÚperiodÚheadingÚproximity_notification_radius)r”   r#   ÚaddressÚproviderÚvenue_idÚ
venue_type)r…   r‹   z6Cannot cast unanswered quiz to any kind of InputMedia.c                 S   s   g | ]}|j r|j‘qS r   )ÚcorrectÚoption)Ú.0Úrr   r   r   Ú
<listcomp>  s    z#get_input_media.<locals>.<listcomp>N)ÚpollÚcorrect_answersÚsolutionÚsolution_entities)Ir;   r   ÚInputMediaPhotoÚInputMediaDocumentr<   r7   r   rn   r(   ro   rŽ   rŒ   rm   rl   rp   r,   rh   r-   r.   rf   Ú	InputFileÚInputFileBigÚInputMediaUploadedPhotoÚget_attributesÚInputMediaUploadedDocumentÚMessageMediaGameÚInputMediaGameÚInputGameIDÚgamerD   rA   ÚMessageMediaContactÚInputMediaContactr’   r   r   r‚   ÚInputMediaGeoPointrƒ   r„   ÚMessageMediaGeoLiveÚInputMediaGeoLiver•   r–   r—   ÚMessageMediaVenueÚInputMediaVenuer#   r˜   r™   rš   ÚMessageMediaDiceÚInputMediaDiceÚemoticonÚMessageMediaEmptyÚMessageMediaUnsupportedÚChatPhotoEmptyÚUserProfilePhotoEmptyr+   r*   ÚInputMediaEmptyri   Úget_input_mediar2   ÚMessageMediaPollr¡   ÚquizÚresultsr)   ÚInputMediaPollr£   r¤   ÚPoll)r2   r…   r†   r‡   rˆ   r‰   rŠ   r‹   ÚattrsÚmimer¢   r   r   r   r¿   ¨  sÎ   


ÿÿýþýþ
úþ
þüüú	ý

ü
r¿   c                 C   sd   z!t | tƒrt | ¡W S | jdkr| W S | jdkr t | j¡W S W n	 ty*   Y nw t| dƒ dS )z:Similar to :meth:`get_input_peer`, but for input messages.iÅ¼¶Téã	 yr�   N)r   Úintr   ÚInputMessageIDr;   rD   r<   r7   ©Úmessager   r   r   Úget_input_message0  s   


ÿÿrÌ   c                 C   sT   z| j dkr	| W S | j dkrtj| j| jd�W S W dS  ty)   t| dƒ Y dS w )z7Similar to :meth:`get_input_peer`, but for input calls.i±aXi ó´ r‘   ÚInputGroupCallN)r;   r   rÍ   rD   rA   r<   r7   )Úcallr   r   r   Úget_input_group_call?  s   

ÿÿrÏ   c                 C   sz   | sdS |  | ¡}z|  t| ƒd ¡ ¡ }W ||fS  ty<   z||ƒ}W n ty1   d}Y nw Y ||fS Y ||fS w )zE
    Returns ``(entity, input_entity)`` for the given entity ID.
    )NNr   N)ÚgetÚ
resolve_idÚ_as_input_peerr<   r)   )Ú	entity_idÚentitiesÚcacher>   r%   r9   r   r   r   Ú_get_entity_pairJ  s"   
ùÿÿþùrÖ   c                 C   sh   | du rdS t | tƒr| S t | tjƒr| jS z| jdkr | jW S W n	 ty*   Y nw td t	| ƒ¡ƒ‚)z7Similar to :meth:`get_input_peer`, but for message IDs.NrÇ   zInvalid message type: {})
r   rÈ   r   rÉ   rD   r;   r<   r)   r   r4   rÊ   r   r   r   Úget_message_id_  s   

þÿr×   c              
   C   s¢  t sd S d }d}d}z±z{t| tƒrt| dƒ}nt| tƒr"t | ¡}n| }d}t| dd ƒr1|  ¡ }nd}|sPW W |rA|rA| 	¡  d S |rL|rN| 
|¡ d S d S d S | ¡ }t| ddƒ}t jj t jj|d| g |d�¡}t j |¡W W |r{|r{| 	¡  S |r…|r†| 
|¡ S S S  ty¡ } zt d	| |j|¡ W Y d }~nd }~ww W |r­|r­| 	¡  d S |r¸|rº| 
|¡ d S d S d S |rÅ|rÅ| 	¡  w |rÏ|rÐ| 
|¡ w w w )
NTÚrbFÚseekableÚnamer   zfile:)ÚsourceÚtagsÚfilenamezFailed to analyze %s: %s %s)Úhachoirr   ÚstrÚopenÚbytesÚioÚBytesIOÚgetattrrÙ   ÚcloseÚseekÚtellÚparserÚguessÚguessParserÚstreamÚInputIOStreamÚmetadataÚextractMetadataÚ	ExceptionÚ_logÚwarningÚ	__class__)r�   rë   Úclose_streamrÙ   ÚposrÝ   rè   Úer   r   r   Ú_get_metadatat  sf   


ÿîü
ÿú€ÿÿþ
ÿrö   )r†   r1   r‡   rˆ   r‰   rŠ   Úthumbc                C   s   t | tƒr| nt| ddƒ}|du rt |¡d }tjt tj 	|¡¡i}	t
| ƒrit| ƒ}
|
ri|
 d¡r9|
 d¡}n|
 d¡rD|
 d¡}nd}tj||
 d¡rS|
 d¡nd|t|
 d¡ra|
 d¡jndƒd	�|	tj< |sÝt| ƒrÝt| ƒ}
|
r¡tj||
 d
¡r‚|
 d
¡nd|
 d¡r�|
 d¡ndt|
 d¡rš|
 d¡jndƒ|d�}n7|rÎt|ƒ}d}d}|r·| d
¡r·| d
¡}|rÃ| d¡rÃ| d¡}tjd||||d�}n
tjddd||d�}||	tj< |rõtj|	v rëd|	tj _n
tjddd�|	tj< |�r|D ]}||	t|ƒ< qú|�sd}t|	 ¡ ƒ|fS )zp
    Get a list of attributes for the given file and
    the mime type as a tuple ([attribute], mime_type).
    rÚ   ÚunnamedNr   ÚauthorÚartistr#   Úduration)Úvoicer#   Ú	performerrû   Úwidthr   Úheight)Úround_messageÚwÚhrû   rŠ   )r   rŠ   T)rü   r'   )r   rß   rä   Ú	mimetypesÚ
guess_typer   ÚDocumentAttributeFilenameÚosÚpathÚbasenameÚis_audiorö   ÚhasrÐ   ÚDocumentAttributeAudiorÈ   ÚsecondsÚis_videoÚDocumentAttributeVideorü   r4   ÚlistÚvalues)r�   r†   r1   r‡   rˆ   r‰   rŠ   r÷   rÚ   Ú	attr_dictÚmrý   ÚdocÚt_mrþ   rÿ   Úar   r   r   rª   §  s†   ÿ

ÿÿüÿ	ÿÿú

þþ

ÿrª   c                    sª   ˆ sdS t ‡ fdd„dD ƒƒrt dd„ ˆ jˆ jfD ƒƒrˆ S tˆ ƒr.G dd„ dƒ}ˆ |_|S tˆ tƒrNzttttdœˆ  ¡  W S  t	yM   t
d	 ˆ ¡ƒ‚w td
 ˆ ¡ƒ‚)zn
    Converts the given parse mode into an object with
    ``parse`` and ``unparse`` callable properties.
    Nc                 3   s   � | ]}t ˆ |ƒV  qd S ©N)r=   ©rž   Úx©Úmoder   r   Ú	<genexpr>  s   € z&sanitize_parse_mode.<locals>.<genexpr>)ÚparseÚunparsec                 s   s   � | ]}t |ƒV  qd S r  )Úcallabler  r   r   r   r    s   € c                   @   s   e Zd Zedd„ ƒZdS )z'sanitize_parse_mode.<locals>.CustomModec                 S   s   t ‚r  )ÚNotImplementedError)ÚtextrÔ   r   r   r   r    s   z/sanitize_parse_mode.<locals>.CustomMode.unparseN)r5   Ú
__module__Ú__qualname__Ústaticmethodr  r   r   r   r   Ú
CustomMode
  s    r$  )Úmdr   Úhtmr   zUnknown parse mode {}zInvalid parse mode type {})Úallr  r  r  r   rß   r   r   ÚlowerÚKeyErrorÚ
ValueErrorr   r)   )r  r$  r   r  r   Úsanitize_parse_modeþ  s.   ÿ
üûÿr+  c                 C   s   t | ƒ}|j|jfS )z©
    Similar to :meth:`get_input_peer`, but for input messages.

    Note that this returns a tuple ``(dc_id, location)``, the
    ``dc_id`` being present if known.
    )Ú_get_file_infoÚdc_idÚlocation)r.  Úinfor   r   r   Úget_input_location  s   r0  c                 C   sð   z| j dkrtd | d ƒW S W n ty   t| dƒ Y nw t| tjƒr&| j} t| tjƒr0| j	} n	t| tj
ƒr9| j} t| tjƒrQt| jtj| j| j| jdd�| jƒS t| tjƒrqt| jtj| j| j| j| jd jd�t| jd ƒƒS t| dƒ d S )NibÔ#ÚInputFileLocationr   )rD   rA   re   Ú
thumb_sizeéÿÿÿÿ)r;   Ú	_FileInfor<   r7   r   r   ri   r2   r,   r-   rn   ro   r.   r-  ÚInputDocumentFileLocationrD   rA   re   r   rm   ÚInputPhotoFileLocationÚsizesr4   Ú_photo_size_byte_count)r.  r   r   r   r,  *  s@   
ÿÿ
üû

üûr,  c                 C   sJ   t | tƒrtj | ¡d S t | tjƒr| jS t| ddƒr!t	| j
ƒS t| ƒS )zŠ
    Gets the extension for the given file, which can be either a
    str or an ``open()``'ed file (which has a ``.name`` attribute).
    r3  rÚ   N)r   rß   r  r  ÚsplitextÚpathlibÚPathÚsuffixrä   Ú_get_extensionrÚ   r3   ©r�   r   r   r   r=  K  s   

r=  c                 C   s,   t  dt| ƒt j¡}|rdS tt| ƒtjƒS )zT
    Returns `True` if the file extension looks like an image file to Telegram.
    z\.(png|jpe?g)T)ÚreÚmatchr=  Ú
IGNORECASEr   Úresolve_bot_file_idr   rm   )r�   r@  r   r   r   Úis_image\  s   rC  c                 C   s   t  dt| ƒt j¡S )zQ
    Returns `True` if the file extension looks like a gif file to Telegram.
    z\.gif)r?  r@  r=  rA  r>  r   r   r   Úis_gifg  s   rD  c                 C   óV   t | ƒ}|st| ƒ}|r| d¡r| d¡ d¡S dS d| } t | ¡d p'd d¡S )z2Returns `True` if the file has an audio mime type.r1   zaudio/Fr  r   r   ©r=  rö   r
  rÐ   Ú
startswithr  r  ©r�   Úextrí   r   r   r   r	  n  ó   r	  c                 C   rE  )z1Returns `True` if the file has a video mime type.r1   zvideo/Fr  r   r   rF  rH  r   r   r   r  |  rJ  r  c                 C   s   t | ttttttfƒS )a   
    Returns `True` if the given object looks like a list.

    Checking ``if hasattr(obj, '__iter__')`` and ignoring ``str/bytes`` is not
    enough. Things like ``open()`` are also iterable (and probably many
    other things), so just support the commonly known list-like objects.
    )r   r  ÚtupleÚsetÚdictÚranger   )Úobjr   r   r   Úis_list_likeŠ  s   rP  c                 C   s4   t | tƒr	t| ƒS t ddt| ƒ¡} |  ¡ r| S dS )z:Parses the given phone, or returns `None` if it's invalid.z[+()\s-]r   N)r   rÈ   rß   r?  ÚsubÚisdigit)Úphoner   r   r   Úparse_phone•  s   
ÿrT  c                 C   sn   |   ¡ } t | ¡pt | ¡}|r*| | ¡ d… } t| d¡ƒ}|r%| dfS |  d¡} t | ¡r5|  	¡ dfS dS )a<  
    Parses the given username or channel access hash, given
    a string, username or URL. Returns a tuple consisting of
    both the stripped, lowercase username and whether it is
    a joinchat/ hash (in which case is not lowercase'd).

    Returns ``(None, False)`` if the ``username`` or link is not valid.
    Nr   Tú/F)NF)
ÚstripÚUSERNAME_REr@  Ú
TG_JOIN_REÚendÚboolÚgroupÚrstripÚVALID_USERNAME_REr(  )Úusernamer  Ú	is_inviter   r   r   Úparse_usernameŸ  s   	

r`  c                 C   sB   t | ƒ} g }|D ]}|j}|j|j }| t| ||… ƒ¡ q|S )aK  
    Gets the inner text that's surrounded by the given entities.
    For instance: text = 'hey!', entity = MessageEntityBold(2, 2) -> 'y!'.

    :param text:     the original text.
    :param entities: the entity or entities that must be matched.
    :return: a single result or a list of the text surrounded by the entities.
    )r   ÚoffsetÚlengthÚappendr	   )r   rÔ   Úresultrõ   ÚstartrY  r   r   r   Úget_inner_text¸  s   	rf  c              	   C   sP  z•t | tƒrt| ƒ\}}||ƒW S | jdkr| W S t | tjjtjtjtj	tj
fƒr-| jW S t | tjƒr:t | j¡W S t | tjƒrGt | j¡W S t | tjƒrTt | j¡W S | jdv r`t | j¡W S t| ddd�} t | tjtjfƒrwt | j¡W S t | tjƒr„t | j¡W S t | tjtjfƒr”t | j¡W S W n ttfy    Y nw t| dƒ d S )Ni‡VÔ)i†o|}l   |�3 F)rZ   r[   ÚPeer)r   rÈ   rÑ   r;   r   ÚcontactsÚResolvedPeerÚInputNotifyPeerÚTopPeerÚDialogÚ
DialogPeerrO   rt   ÚPeerChannelrD   rS   ÚPeerUserrE   rX   rI   r>   rC   rN   rF   rY   rG   rR   rK   r<   r)   r7   )rO   ÚpidÚclsr   r   r   Úget_peerË  s>   



þ
ÿÿrr  c                 C   sô   t | tƒr|r	| S t| ƒd S t | tjƒrt| dƒ zt| ƒ} W n ty.   t| dƒ Y nw t | tjƒr8| j	S t | tj
ƒr[d| j  k rIdksRn t| jƒd | _|rX| j S | jS d| j  k rfdkson t| jƒd | _|st| jS d| j  S )a±  
    Convert the given peer into its marked ID by default.

    This "mark" comes from the "bot api" format, and with it the peer type
    can be identified back. User ID is left unmodified, chat ID is negated,
    and channel ID is "prefixed" with -100:

    * ``user_id``
    * ``-chat_id``
    * ``-100channel_id``

    The original ID and the peer type class can be returned with
    a call to :meth:`resolve_id(marked_id)`.
    r   z.int (you might want to use client.get_peer_id)rÈ   l   ÿc(	 ì    J)£)r   rÈ   rÑ   r   r@   r7   rr  r)   ro  rI   rX   rY   rK   )rO   Úadd_markr   r   r   Úget_peer_idí  s(   

ÿru  c                 C   s<   | dkr	| t jfS |  } | dkr| d8 } | t jfS | t jfS )zCGiven a marked ID, returns the original ID and its :tl:`Peer` type.r   rs  )r   ro  rn  rX   )Ú	marked_idr   r   r   rÑ     s   


rÑ   c                 C   sN   | s| S d}d}| D ]}|dkr||| 7 }d}q
||7 }t |gƒ}q
|| S )z,
    Decodes run-length-encoded `data`.
    ó    ó    ©rá   )ÚdataÚnewÚlastÚcurr   r   r   Ú_rle_decode*  s   r~  c                 C   sf   d}d}| D ]}|s|d7 }q|r|dt |gƒ 7 }d}|t |gƒ7 }q|dkr1|dt |gƒ 7 }|S )Nrw  r   r   rx  ry  )Ústringr{  Úcountr}  r   r   r   Ú_rle_encode>  s   
r�  c              
   C   s:   zt  | dt| ƒd   ¡W S  tjttfy   Y dS w )a(  
    Decodes a url-safe base64-encoded string into its bytes
    by first adding the stripped necessary padding characters.

    This is the way Telegram shares binary data as strings,
    such as Bot API-style file IDs or invite links.

    Returns `None` if the input string was not valid.
    ú=é   N)Úbase64Úurlsafe_b64decodeÚlenÚbinasciiÚErrorr*  r)   ©r  r   r   r   Ú_decode_telegram_base64O  s
   
ÿrŠ  c              
   C   s6   zt  | ¡ d¡ d¡W S  tjttfy   Y dS w )z0
    Inverse for `_decode_telegram_base64`.
    ó   =ÚasciiN)r„  Úurlsafe_b64encoder\  Údecoder‡  rˆ  r*  r)   r‰  r   r   r   Ú_encode_telegram_base64_  s
   ÿr�  c                 C   sn  t t| ƒƒ}|s
dS |dd… |d }}|dvrdS |dkr%t|ƒdks/|dkr¯t|ƒdkr¯|dkr>t d|¡\}}}}nt d	|¡\}}}}}d
|  krTdksWdS  dS g }|dksa|dkrn| tjd|dkd�¡ n3|dksv|dkr…| tjddd|dkd�¡ n|dkr–| tj	dt 
¡ d�¡ n|dkr¡| t ¡ ¡ tj||dddd||dd�	S |dkr¹t|ƒdksÅ|dk�r3t|ƒdv �r5|dkr×t d|¡\}}}}}	}
}n.t|ƒdkrìt d|¡\}}}}}	}
}}nt|ƒdk�rt d|¡\	}}}}}}	}}}ndS d
|  k�rdk�sdS  dS |�s|�rdnd }tj||ddtj|dddd!�g|dd"�S dS dS )#a¸  
    Given a Bot API-style `file_id <telethon.tl.custom.file.File.id>`,
    returns the media it represents. If the `file_id <telethon.tl.custom.file.File.id>`
    is not valid, `None` is returned instead.

    Note that the `file_id <telethon.tl.custom.file.File.id>` does not have information
    such as image dimensions or file size, so these will be zero if present.

    For thumbnails, the photo ID and hash will always be zero.
    Nr3  )é   rƒ  r�  é   rƒ  é   z<iiqqú<iiqqbr   é   é   é	   r   )rû   rü   é   )rû   r  r  r   é   r   )ÚaltÚ
stickerseté
   rw  )	rD   rA   Údater1   r   Úthumbsr-  r†   re   é,   )é1   éM   z<iiqqqqirŸ  z
<iiqqqqi5sr   z<ii28sqqq12sibÚsr  )r4   r  r  r   )rD   rA   re   rœ  r7  r-  Úhas_stickers)r~  rŠ  r†  ÚstructÚunpackrc  r   r  r  ÚDocumentAttributeStickerÚInputStickerSetEmptyÚDocumentAttributeAnimatedr.   rm   Ú	PhotoSize)Úfile_idrz  ÚversionÚ	file_typer-  Úmedia_idrA   Ú_r†   Ú	volume_idÚsecretÚlocal_idÚ
photo_sizer   r   r   rB  i  sš   (ù
þ
ü
þ÷,

ÿ

ÿ
 ÿüôìrB  c                 C   s&  t | tjƒr
| j} n	t | tjƒr| j} t | tjƒrad}| jD ]1}t |tjƒr.|j	r+dnd}n!t |tj
ƒr<|jr9dnd}nt |tjƒrEd}n
t |tjƒrNd}nq ttt d|| j| j| jd	¡ƒƒS t | tjƒr‘td
d„ t| jƒD ƒdƒ}|sxdS |j}ttt dd	| j| j| j|jd|jd	¡	ƒƒS dS )a  
    Inverse operation for `resolve_bot_file_id`.

    The only parameters this method will accept are :tl:`Document` and
    :tl:`Photo`, and it will return a variable-length ``file_id`` string.

    If an invalid parameter is given, it will ``return None``.
    r”  r•  r–  r—  rƒ  r˜  r›  r“  r�  c                 s   s&   � | ]}t |tjtjfƒr|V  qd S r  )r   r   r¨  ÚPhotoCachedSizer  r   r   r   r  õ  s   € ÿz#pack_bot_file_id.<locals>.<genexpr>Nz	<iiqqqqibr   )r   r   r,   r-   rn   ro   r.   r†   r  rü   r  r   r¥  r§  r�  r�  r£  Úpackr-  rD   rA   rm   ÚnextÚreversedr7  r.  r®  r°  )r�   r«  Ú	attributer   r   r   r   Úpack_bot_file_idÔ  s@   	
ÿÿþr·  c              	   C   s    t | ƒ\}}|s
| }t d|¡rt|ƒdv rt |¡}nt|ƒ}z"t|ƒdkr2dgt d|¡¢R W S t|ƒdkr?t d|¡W S 	 W dS  tj	t
fyO   Y dS w )	a  
    Resolves the given invite link. Returns a tuple of
    ``(link creator user id, global chat id, random int)``.

    Note that for broadcast channels or with the newest link format, the link
    creator user ID will be zero to protect their identity. Normal chats and
    megagroup channels will have such ID.

    Note that the chat ID may not be accurate for chats with a link that were
    upgraded to megagroup, since the link can remain the same, but the chat
    ID will be correct once a new link is generated.
    z[a-fA-F\d]+)r‘  é    é   r   z>LQé   z>LLQ)NNN)r`  r?  r@  r†  rá   ÚfromhexrŠ  r£  r¤  Úerrorr)   )ÚlinkÚ	link_hashÚis_linkÚpayloadr   r   r   Úresolve_invite_link  s"   þþrÁ  c              	   C   s`   z"t  dt| ƒ¡\}}}}|dk rt | ¡nt |¡}||||fW S  t jtfy/   Y dS w )a}  
    Resolves an inline message ID. Returns a tuple of
    ``(message id, peer, dc id, access hash)``

    The ``peer`` may either be a :tl:`PeerUser` referencing
    the user who sent the message via the bot in a private
    conversation or small group chat, or a :tl:`PeerChannel`
    if the message was sent in a channel.

    The ``access_hash`` does not have any use yet.
    z<iiiqr   )NNNN)r£  r¤  rŠ  r   rn  ro  r¼  r)   )Úinline_msg_idr-  Ú
message_idrp  rA   rO   r   r   r   Úresolve_inline_message_id)  s   
ÿÿrÄ  c                 C   s   | dkrdS | dkrdS dS )zn
    Gets the appropriated part size when uploading or downloading files,
    given an initial file size.
    i  @é€   i  à.é   i   r   )Ú	file_sizer   r   r   Úget_appropriated_part_size>  s
   rÈ  c           	      C   s¤   t | ƒd }|d d }t|d ƒ}tt | ƒƒD ]1}t|d dƒ\}}| | d@ |> }t d|||d … ¡d }||O }t d|¡|||d …< qt|d	|… ƒS )
af  
    Encodes the input `bytes` into a 5-bit byte-string
    to be used as a voice note's waveform. See `decode_waveform`
    for the reverse operation.

    Example
        .. code-block:: python

            chat = ...
            file = 'my.ogg'

            # Send 'my.ogg' with a ascending-triangle waveform
            await client.send_file(chat, file, attributes=[types.DocumentAttributeAudio(
                duration=7,
                voice=True,
                waveform=utils.encode_waveform(bytes(range(2 ** 5))  # 2**5 because 5-bit
            )]

            # Send 'my.ogg' with a square waveform
            await client.send_file(chat, file, attributes=[types.DocumentAttributeAudio(
                duration=7,
                voice=True,
                waveform=utils.encode_waveform(bytes((31, 31, 15, 15, 15, 15, 31, 31)) * 4)
            )]
    r”  é   r˜  r   é   ú<Hr�  r   N)r†  Ú	bytearrayrN  Údivmodr£  r¤  r³  rá   )	ÚwaveformÚ
bits_countÚbytes_countrd  ÚiÚ
byte_indexÚ	bit_shiftÚvalueÚor_whatr   r   r   Úencode_waveformJ  s   rÖ  c                 C   sÜ   t | ƒd }|d }|dkrdS t|ƒ}t|d ƒD ]!}t|d dƒ\}}t d| ||d … ¡d }||? d@ ||< qt|d dƒ\}}|t | ƒd krR| | }nt d| ||d … ¡d }||? d@ ||d < t|ƒS )	z1
    Inverse operation of `encode_waveform`.
    r˜  r”  r   rw  r   rË  r�  rÊ  )r†  rÌ  rN  rÍ  r£  r¤  rá   )rÎ  Ú	bit_countÚvalue_countrd  rÑ  rÒ  rÓ  rÔ  r   r   r   Údecode_waveforms  s   
rÙ  i   )z\nz\sÚ.)ÚlimitÚmax_entitiesÚsplit_atc                c   sˆ  � dd„ }t | ƒ} tttj|ƒƒ}	 t|ƒ|kr(||d  }t||j|j ƒ}n|}t| ƒ|kr1nŠ|D ]…}t	t
|ƒƒD ]z}	|j| |	d�}
|
rµ| d|
 ¡ … | |
 ¡ d… }}g g }}|D ]H}|j|
 ¡ k r˜|j|j |
 ¡ kr’| |||
 ¡ |j d�¡ | ||d|j|j |
 ¡  d	�¡ q^| |¡ q^| |||j|
 ¡  d
�¡ q^t|ƒ|fV  ||} } nq;q3 nnqt| ƒ|fV  dS )a  
    Split a message text and entities into multiple messages, each with their
    own set of entities. This allows sending a very large message as multiple
    messages while respecting the formatting.

    Arguments
        text (`str`):
            The message text.

        entities (List[:tl:`MessageEntity`])
            The formatting entities.

        limit (`int`):
            The maximum message length of each individual message.

        max_entities (`int`):
            The maximum amount of entities that will be present in each
            individual message.

        split_at (Tuplel[`str`]):
            The list of regular expressions that will determine where to split
            the text. By default, a newline is searched. If no newline is
            present, a space is searched. If no space is found, the split will
            be made at any character.

            The last expression should always match a character, or else the
            text will stop being splitted and the resulting text may be larger
            than the limit.

    Yields
        Pairs of ``(str, entities)`` with the split message.

    Example
        .. code-block:: python

            from telethon import utils
            from telethon.extensions import markdown

            very_long_markdown_text = "..."
            text, entities = markdown.parse(very_long_markdown_text)

            for text, entities in utils.split_text(text, entities):
                await client.send_message(chat, text, formatting_entities=entities)
    c                 [   s(   |   ¡ }|d= | |¡ | jdi |¤ŽS )Nr­  r   )Úto_dictÚupdaterò   )ÚentÚupdatesÚkwargsr   r   r   rß  »  s   
zsplit_text.<locals>.updateTr   )rô   N)rb  r   )ra  rb  )ra  )r   rK  Úmapr?  Úcompiler†  rB   ra  rb  rµ  rN  r@  rY  rc  r	   )r   rÔ   rÛ  rÜ  rÝ  rß  Úlast_entÚ	cur_limitÚsplitrÑ  r  Úcur_textÚnew_textÚcur_entÚnew_entrà  r   r   r   Ú
split_textŒ  sB   €/"
&
ñÞ$rì  c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚAsyncClassWrapperc                 C   s
   || _ d S r  )Úwrapped)Úselfrî  r   r   r   Ú__init__ì  s   
zAsyncClassWrapper.__init__c                    s(   t | j|ƒ‰ ‡ fdd„}tˆ ƒr|S ˆ S )Nc                  Ÿ   s(   �ˆ | i |¤Ž}t  |¡r|I d H S |S r  )ÚinspectÚisawaitable)Úargsrâ  Úval©r  r   r   Úwrapperñ  s   €z.AsyncClassWrapper.__getattr__.<locals>.wrapper)rä   rî  r  )rï  Úitemrö  r   rõ  r   Ú__getattr__ï  s
   zAsyncClassWrapper.__getattr__N)r5   r!  r"  rð  rø  r   r   r   r   rí  ë  s    rí  c                 C   sX   t | ƒdk s| d dkr| S tdƒ}d}| d |d< | d |d< t|ƒ| dd	…  | S )
zÕ
    Adds the JPG header and footer to a stripped image.

    Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225
    r•  r   r   so  ÿØÿà JFIF      ÿÛ C (#(#!#-+(0<dA<77<{X]Id‘€™–�€ŒŠ ´æÃ ªÚ­ŠŒÈÿËÚîõÿÿÿ›ÁÿÿÿúÿæýÿøÿÛ C+--<5<vAAvø¥Œ¥øøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøøÿÀ     " ÿÄ           	
ÿÄ µ   } !1AQa"q2�‘¡#B±ÁRÑð$3br‚	
%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyzƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚáâãäåæçèéêñòóôõö÷øùúÿÄ        	
ÿÄ µ  w !1AQaq"2�B‘¡±Á	#3RðbrÑ
$4á%ñ&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz‚ƒ„…†‡ˆ‰Š’“”•–—˜™š¢£¤¥¦§¨©ª²³´µ¶·¸¹ºÂÃÄÅÆÇÈÉÊÒÓÔÕÖ×ØÙÚâãäåæçèéêòóôõö÷øùúÿÚ   ? s   ÿÙé¤   r�  é¦   N)r†  rÌ  rá   )ÚstrippedÚheaderÚfooterr   r   r   Ústripped_photo_to_jpgû  s   rþ  c                 C   s’   t | tjƒr	| jS t | tjƒr)t| jƒdk s| jd dkr"t| jƒS t| jƒd S t | tjƒr4t| jƒS t | tjƒr<dS t | tj	ƒrGt
| jƒS d S )Nr•  r   r   in  )r   r   r¨  r   ÚPhotoStrippedSizer†  rá   r²  ÚPhotoSizeEmptyÚPhotoSizeProgressiveÚmaxr7  )r   r   r   r   r8    s   


r8  c                 Ã   s(   �| }t  |¡rt d¡ |I d H }|S )Nz7Using async sessions support is an experimental feature)rñ  rò  ÚwarningsÚwarn)Úcorord  r   r   r   Úmaybe_async  s   €


r  )r   )TT)T)[Ú__doc__r„  r‡  rñ  râ   r   ÚloggingÚmathr  r  r:  r?  r£  r  Úcollectionsr   r   r   r   Ú
extensionsr   r   Úhelpersr   r	   r
   ÚtlrÞ   Úhachoir.metadataÚhachoir.parserÚImportErrorÚadd_typerä  rW  rX  rA  r]  r4  Ú	getLoggerr5   rð   r   r&   r3   r7   r>   r\   r^   ra   rh   r(   r{   rƒ   r¿   rÌ   rÏ   rÖ   r×   rö   rª   r+  r0  r,  r=  rC  rD  r	  r  rP  rT  r`  rf  rr  ru  rÑ   r~  r�  rŠ  r�  rB  r·  rÁ  rÄ  rÈ  rÖ  rÙ  rì  rí  rþ  r8  r  r   r   r   r   Ú<module>   sä    ÿÿÿþ



`(&ü 	
ÿ3þW!!

"0
k0%)_